blob: 628ade15932c011febcc61c9964a55c2bb433ad4 [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
Gregory Szorcbe51e432012-07-12 07:21:12 +000068import clang.enumerations
69
Daniel Dunbar30c0f262010-01-24 02:02:07 +000070def get_cindex_library():
71 # FIXME: It's probably not the case that the library is actually found in
72 # this location. We need a better system of identifying and loading the
73 # CIndex library. It could be on path or elsewhere, or versioned, etc.
74 import platform
75 name = platform.system()
76 if name == 'Darwin':
Daniel Dunbarf51f20f2010-04-30 21:51:10 +000077 return cdll.LoadLibrary('libclang.dylib')
Daniel Dunbar30c0f262010-01-24 02:02:07 +000078 elif name == 'Windows':
Daniel Dunbarf51f20f2010-04-30 21:51:10 +000079 return cdll.LoadLibrary('libclang.dll')
Daniel Dunbar30c0f262010-01-24 02:02:07 +000080 else:
Daniel Dunbarf51f20f2010-04-30 21:51:10 +000081 return cdll.LoadLibrary('libclang.so')
Daniel Dunbar12bf15c2010-01-24 21:20:29 +000082
Daniel Dunbar30c0f262010-01-24 02:02:07 +000083# ctypes doesn't implicitly convert c_void_p to the appropriate wrapper
84# object. This is a problem, because it means that from_parameter will see an
85# integer and pass the wrong value on platforms where int != void*. Work around
86# this by marshalling object arguments as void**.
87c_object_p = POINTER(c_void_p)
88
89lib = get_cindex_library()
Gregory Szorc9537e202012-07-12 04:56:46 +000090callbacks = {}
Daniel Dunbar30c0f262010-01-24 02:02:07 +000091
Gregory Szorcfbf620b2012-05-08 05:56:38 +000092### Exception Classes ###
93
94class TranslationUnitLoadError(Exception):
95 """Represents an error that occurred when loading a TranslationUnit.
96
97 This is raised in the case where a TranslationUnit could not be
98 instantiated due to failure in the libclang library.
99
100 FIXME: Make libclang expose additional error information in this scenario.
101 """
102 pass
103
104class TranslationUnitSaveError(Exception):
105 """Represents an error that occurred when saving a TranslationUnit.
106
107 Each error has associated with it an enumerated value, accessible under
108 e.save_error. Consumers can compare the value with one of the ERROR_
109 constants in this class.
110 """
111
112 # Indicates that an unknown error occurred. This typically indicates that
113 # I/O failed during save.
114 ERROR_UNKNOWN = 1
115
116 # Indicates that errors during translation prevented saving. The errors
117 # should be available via the TranslationUnit's diagnostics.
118 ERROR_TRANSLATION_ERRORS = 2
119
120 # Indicates that the translation unit was somehow invalid.
121 ERROR_INVALID_TU = 3
122
123 def __init__(self, enumeration, message):
124 assert isinstance(enumeration, int)
125
126 if enumeration < 1 or enumeration > 3:
127 raise Exception("Encountered undefined TranslationUnit save error "
128 "constant: %d. Please file a bug to have this "
129 "value supported." % enumeration)
130
131 self.save_error = enumeration
Gregory Szorc2283b462012-05-12 20:49:13 +0000132 Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
Gregory Szorcfbf620b2012-05-08 05:56:38 +0000133
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000134### Structures and Utility Classes ###
135
Gregory Szorcb15b15c2012-08-19 21:17:46 +0000136class CachedProperty(object):
137 """Decorator that lazy-loads the value of a property.
138
139 The first time the property is accessed, the original property function is
140 executed. The value it returns is set as the new value of that instance's
141 property, replacing the original method.
142 """
143
144 def __init__(self, wrapped):
145 self.wrapped = wrapped
146 try:
147 self.__doc__ = wrapped.__doc__
148 except:
149 pass
150
151 def __get__(self, instance, instance_type=None):
152 if instance is None:
153 return self
154
155 value = self.wrapped(instance)
156 setattr(instance, self.wrapped.__name__, value)
157
158 return value
159
160
Daniel Dunbara33dca42010-01-24 21:19:57 +0000161class _CXString(Structure):
162 """Helper for transforming CXString results."""
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000163
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000164 _fields_ = [("spelling", c_char_p), ("free", c_int)]
165
166 def __del__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000167 lib.clang_disposeString(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000168
Daniel Dunbara33dca42010-01-24 21:19:57 +0000169 @staticmethod
170 def from_result(res, fn, args):
171 assert isinstance(res, _CXString)
Gregory Szorc9537e202012-07-12 04:56:46 +0000172 return lib.clang_getCString(res)
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000173
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000174class SourceLocation(Structure):
175 """
Daniel Dunbar149f38a2010-01-24 04:09:58 +0000176 A SourceLocation represents a particular location within a source file.
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000177 """
Daniel Dunbare32af422010-01-30 23:58:50 +0000178 _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)]
Daniel Dunbarf8690832010-01-24 21:20:21 +0000179 _data = None
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000180
Daniel Dunbarf8690832010-01-24 21:20:21 +0000181 def _get_instantiation(self):
182 if self._data is None:
Daniel Dunbar3239a672010-01-29 17:02:32 +0000183 f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint()
Gregory Szorc9537e202012-07-12 04:56:46 +0000184 lib.clang_getInstantiationLocation(self, byref(f), byref(l),
185 byref(c), byref(o))
Tobias Grosser81982882011-10-31 00:49:07 +0000186 if f:
187 f = File(f)
188 else:
189 f = None
Argyrios Kyrtzidis6b046232011-08-17 17:20:24 +0000190 self._data = (f, int(l.value), int(c.value), int(o.value))
Daniel Dunbarf8690832010-01-24 21:20:21 +0000191 return self._data
192
Tobias Grosser58ba8c92011-10-31 00:31:32 +0000193 @staticmethod
194 def from_position(tu, file, line, column):
195 """
196 Retrieve the source location associated with a given file/line/column in
197 a particular translation unit.
198 """
Gregory Szorc9537e202012-07-12 04:56:46 +0000199 return lib.clang_getLocation(tu, file, line, column)
Tobias Grosser58ba8c92011-10-31 00:31:32 +0000200
Gregory Szorc74bb7102012-06-11 11:11:48 +0000201 @staticmethod
202 def from_offset(tu, file, offset):
203 """Retrieve a SourceLocation from a given character offset.
204
205 tu -- TranslationUnit file belongs to
206 file -- File instance to obtain offset from
207 offset -- Integer character offset within file
208 """
Gregory Szorc9537e202012-07-12 04:56:46 +0000209 return lib.clang_getLocationForOffset(tu, file, offset)
Gregory Szorc74bb7102012-06-11 11:11:48 +0000210
Daniel Dunbarf8690832010-01-24 21:20:21 +0000211 @property
212 def file(self):
213 """Get the file represented by this source location."""
214 return self._get_instantiation()[0]
215
216 @property
217 def line(self):
218 """Get the line represented by this source location."""
219 return self._get_instantiation()[1]
220
221 @property
222 def column(self):
223 """Get the column represented by this source location."""
224 return self._get_instantiation()[2]
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000225
Daniel Dunbar3239a672010-01-29 17:02:32 +0000226 @property
227 def offset(self):
228 """Get the file offset represented by this source location."""
229 return self._get_instantiation()[3]
230
Tobias Grosser74858332012-02-05 11:40:59 +0000231 def __eq__(self, other):
Gregory Szorc9537e202012-07-12 04:56:46 +0000232 return lib.clang_equalLocations(self, other)
Tobias Grosser74858332012-02-05 11:40:59 +0000233
234 def __ne__(self, other):
235 return not self.__eq__(other)
236
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000237 def __repr__(self):
Tobias Grosser81982882011-10-31 00:49:07 +0000238 if self.file:
239 filename = self.file.name
240 else:
241 filename = None
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000242 return "<SourceLocation file %r, line %r, column %r>" % (
Tobias Grosser81982882011-10-31 00:49:07 +0000243 filename, self.line, self.column)
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000244
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000245class SourceRange(Structure):
246 """
247 A SourceRange describes a range of source locations within the source
248 code.
249 """
250 _fields_ = [
Daniel Dunbare32af422010-01-30 23:58:50 +0000251 ("ptr_data", c_void_p * 2),
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000252 ("begin_int_data", c_uint),
253 ("end_int_data", c_uint)]
254
Daniel Dunbar532fc632010-01-30 23:59:02 +0000255 # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes
256 # object.
257 @staticmethod
258 def from_locations(start, end):
Gregory Szorc9537e202012-07-12 04:56:46 +0000259 return lib.clang_getRange(start, end)
Daniel Dunbar532fc632010-01-30 23:59:02 +0000260
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000261 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000262 def start(self):
263 """
264 Return a SourceLocation representing the first character within a
265 source range.
266 """
Gregory Szorc9537e202012-07-12 04:56:46 +0000267 return lib.clang_getRangeStart(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000268
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000269 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000270 def end(self):
271 """
272 Return a SourceLocation representing the last character within a
273 source range.
274 """
Gregory Szorc9537e202012-07-12 04:56:46 +0000275 return lib.clang_getRangeEnd(self)
Daniel Dunbarf8690832010-01-24 21:20:21 +0000276
Tobias Grosser74858332012-02-05 11:40:59 +0000277 def __eq__(self, other):
Gregory Szorc9537e202012-07-12 04:56:46 +0000278 return lib.clang_equalRanges(self, other)
Tobias Grosser74858332012-02-05 11:40:59 +0000279
280 def __ne__(self, other):
281 return not self.__eq__(other)
282
Daniel Dunbarf8690832010-01-24 21:20:21 +0000283 def __repr__(self):
284 return "<SourceRange start %r, end %r>" % (self.start, self.end)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000285
Daniel Dunbar532fc632010-01-30 23:59:02 +0000286class Diagnostic(object):
287 """
288 A Diagnostic is a single instance of a Clang diagnostic. It includes the
289 diagnostic severity, the message, the location the diagnostic occurred, as
290 well as additional source ranges and associated fix-it hints.
291 """
292
293 Ignored = 0
294 Note = 1
295 Warning = 2
296 Error = 3
297 Fatal = 4
298
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000299 def __init__(self, ptr):
300 self.ptr = ptr
301
302 def __del__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000303 lib.clang_disposeDiagnostic(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000304
305 @property
306 def severity(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000307 return lib.clang_getDiagnosticSeverity(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000308
309 @property
310 def location(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000311 return lib.clang_getDiagnosticLocation(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000312
313 @property
314 def spelling(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000315 return lib.clang_getDiagnosticSpelling(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000316
317 @property
318 def ranges(self):
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +0000319 class RangeIterator:
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000320 def __init__(self, diag):
321 self.diag = diag
322
323 def __len__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000324 return int(lib.clang_getDiagnosticNumRanges(self.diag))
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000325
326 def __getitem__(self, key):
Tobias Grosserba5d10b2011-10-31 02:06:50 +0000327 if (key >= len(self)):
328 raise IndexError
Gregory Szorc9537e202012-07-12 04:56:46 +0000329 return lib.clang_getDiagnosticRange(self.diag, key)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000330
Tobias Grosserff090ca2011-02-05 17:53:48 +0000331 return RangeIterator(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000332
333 @property
334 def fixits(self):
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +0000335 class FixItIterator:
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000336 def __init__(self, diag):
337 self.diag = diag
338
339 def __len__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +0000340 return int(lib.clang_getDiagnosticNumFixIts(self.diag))
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000341
342 def __getitem__(self, key):
343 range = SourceRange()
Gregory Szorc9537e202012-07-12 04:56:46 +0000344 value = lib.clang_getDiagnosticFixIt(self.diag, key,
345 byref(range))
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +0000346 if len(value) == 0:
347 raise IndexError
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000348
349 return FixIt(range, value)
350
Tobias Grosserff090ca2011-02-05 17:53:48 +0000351 return FixItIterator(self)
Daniel Dunbar532fc632010-01-30 23:59:02 +0000352
Tobias Grosserea403822012-02-05 11:41:58 +0000353 @property
354 def category_number(self):
355 """The category number for this diagnostic."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000356 return lib.clang_getDiagnosticCategory(self)
Tobias Grosserea403822012-02-05 11:41:58 +0000357
358 @property
359 def category_name(self):
360 """The string name of the category for this diagnostic."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000361 return lib.clang_getDiagnosticCategoryName(self.category_number)
Tobias Grosserea403822012-02-05 11:41:58 +0000362
363 @property
364 def option(self):
365 """The command-line option that enables this diagnostic."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000366 return lib.clang_getDiagnosticOption(self, None)
Tobias Grosserea403822012-02-05 11:41:58 +0000367
368 @property
369 def disable_option(self):
370 """The command-line option that disables this diagnostic."""
371 disable = _CXString()
Gregory Szorc9537e202012-07-12 04:56:46 +0000372 lib.clang_getDiagnosticOption(self, byref(disable))
Tobias Grosserea403822012-02-05 11:41:58 +0000373
Gregory Szorc9537e202012-07-12 04:56:46 +0000374 return lib.clang_getCString(disable)
Tobias Grosserea403822012-02-05 11:41:58 +0000375
Daniel Dunbar532fc632010-01-30 23:59:02 +0000376 def __repr__(self):
377 return "<Diagnostic severity %r, location %r, spelling %r>" % (
378 self.severity, self.location, self.spelling)
379
Tobias Grosserff090ca2011-02-05 17:53:48 +0000380 def from_param(self):
381 return self.ptr
382
Daniel Dunbar532fc632010-01-30 23:59:02 +0000383class FixIt(object):
384 """
385 A FixIt represents a transformation to be applied to the source to
386 "fix-it". The fix-it shouldbe applied by replacing the given source range
387 with the given value.
388 """
389
390 def __init__(self, range, value):
391 self.range = range
392 self.value = value
393
394 def __repr__(self):
395 return "<FixIt range %r, value %r>" % (self.range, self.value)
396
Gregory Szorcbe51e432012-07-12 07:21:12 +0000397class TokenGroup(object):
398 """Helper class to facilitate token management.
399
400 Tokens are allocated from libclang in chunks. They must be disposed of as a
401 collective group.
402
403 One purpose of this class is for instances to represent groups of allocated
404 tokens. Each token in a group contains a reference back to an instance of
405 this class. When all tokens from a group are garbage collected, it allows
406 this class to be garbage collected. When this class is garbage collected,
407 it calls the libclang destructor which invalidates all tokens in the group.
408
409 You should not instantiate this class outside of this module.
410 """
411 def __init__(self, tu, memory, count):
412 self._tu = tu
413 self._memory = memory
414 self._count = count
415
416 def __del__(self):
417 lib.clang_disposeTokens(self._tu, self._memory, self._count)
418
419 @staticmethod
420 def get_tokens(tu, extent):
421 """Helper method to return all tokens in an extent.
422
423 This functionality is needed multiple places in this module. We define
424 it here because it seems like a logical place.
425 """
426 tokens_memory = POINTER(Token)()
427 tokens_count = c_uint()
428
429 lib.clang_tokenize(tu, extent, byref(tokens_memory),
430 byref(tokens_count))
431
432 count = int(tokens_count.value)
433
434 # If we get no tokens, no memory was allocated. Be sure not to return
435 # anything and potentially call a destructor on nothing.
436 if count < 1:
437 return
438
439 tokens_array = cast(tokens_memory, POINTER(Token * count)).contents
440
441 token_group = TokenGroup(tu, tokens_memory, tokens_count)
442
443 for i in xrange(0, count):
444 token = Token()
445 token.int_data = tokens_array[i].int_data
446 token.ptr_data = tokens_array[i].ptr_data
447 token._tu = tu
448 token._group = token_group
449
450 yield token
451
452class TokenKind(object):
453 """Describes a specific type of a Token."""
454
455 _value_map = {} # int -> TokenKind
456
457 def __init__(self, value, name):
458 """Create a new TokenKind instance from a numeric value and a name."""
459 self.value = value
460 self.name = name
461
462 def __repr__(self):
463 return 'TokenKind.%s' % (self.name,)
464
465 @staticmethod
466 def from_value(value):
467 """Obtain a registered TokenKind instance from its value."""
468 result = TokenKind._value_map.get(value, None)
469
470 if result is None:
471 raise ValueError('Unknown TokenKind: %d' % value)
472
473 return result
474
475 @staticmethod
476 def register(value, name):
477 """Register a new TokenKind enumeration.
478
479 This should only be called at module load time by code within this
480 package.
481 """
482 if value in TokenKind._value_map:
483 raise ValueError('TokenKind already registered: %d' % value)
484
485 kind = TokenKind(value, name)
486 TokenKind._value_map[value] = kind
487 setattr(TokenKind, name, kind)
488
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000489### Cursor Kinds ###
490
491class CursorKind(object):
492 """
493 A CursorKind describes the kind of entity that a cursor points to.
494 """
495
496 # The unique kind objects, indexed by id.
497 _kinds = []
498 _name_map = None
499
500 def __init__(self, value):
501 if value >= len(CursorKind._kinds):
502 CursorKind._kinds += [None] * (value - len(CursorKind._kinds) + 1)
503 if CursorKind._kinds[value] is not None:
504 raise ValueError,'CursorKind already loaded'
505 self.value = value
506 CursorKind._kinds[value] = self
507 CursorKind._name_map = None
508
509 def from_param(self):
510 return self.value
511
512 @property
513 def name(self):
514 """Get the enumeration name of this cursor kind."""
515 if self._name_map is None:
516 self._name_map = {}
517 for key,value in CursorKind.__dict__.items():
518 if isinstance(value,CursorKind):
519 self._name_map[value] = key
520 return self._name_map[self]
521
522 @staticmethod
523 def from_id(id):
524 if id >= len(CursorKind._kinds) or CursorKind._kinds[id] is None:
525 raise ValueError,'Unknown cursor kind'
526 return CursorKind._kinds[id]
527
Daniel Dunbara6a64992010-01-24 21:20:39 +0000528 @staticmethod
529 def get_all_kinds():
Daniel Dunbar4efd6322010-01-25 00:43:08 +0000530 """Return all CursorKind enumeration instances."""
Daniel Dunbara6a64992010-01-24 21:20:39 +0000531 return filter(None, CursorKind._kinds)
532
533 def is_declaration(self):
534 """Test if this is a declaration kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000535 return lib.clang_isDeclaration(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000536
537 def is_reference(self):
538 """Test if this is a reference kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000539 return lib.clang_isReference(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000540
541 def is_expression(self):
542 """Test if this is an expression kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000543 return lib.clang_isExpression(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000544
545 def is_statement(self):
546 """Test if this is a statement kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000547 return lib.clang_isStatement(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000548
Douglas Gregor8be80e12011-07-06 03:00:34 +0000549 def is_attribute(self):
550 """Test if this is an attribute kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000551 return lib.clang_isAttribute(self)
Douglas Gregor8be80e12011-07-06 03:00:34 +0000552
Daniel Dunbara6a64992010-01-24 21:20:39 +0000553 def is_invalid(self):
554 """Test if this is an invalid kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000555 return lib.clang_isInvalid(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000556
Tobias Grossereb136342012-02-05 11:42:09 +0000557 def is_translation_unit(self):
558 """Test if this is a translation unit kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000559 return lib.clang_isTranslationUnit(self)
Tobias Grossereb136342012-02-05 11:42:09 +0000560
561 def is_preprocessing(self):
562 """Test if this is a preprocessing kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000563 return lib.clang_isPreprocessing(self)
Tobias Grossereb136342012-02-05 11:42:09 +0000564
565 def is_unexposed(self):
566 """Test if this is an unexposed kind."""
Gregory Szorc9537e202012-07-12 04:56:46 +0000567 return lib.clang_isUnexposed(self)
Tobias Grossereb136342012-02-05 11:42:09 +0000568
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000569 def __repr__(self):
570 return 'CursorKind.%s' % (self.name,)
571
572# FIXME: Is there a nicer way to expose this enumeration? We could potentially
573# represent the nested structure, or even build a class hierarchy. The main
574# things we want for sure are (a) simple external access to kinds, (b) a place
575# to hang a description and name, (c) easy to keep in sync with Index.h.
576
Daniel Dunbara6a64992010-01-24 21:20:39 +0000577###
578# Declaration Kinds
579
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000580# A declaration whose specific kind is not exposed via this interface.
581#
582# Unexposed declarations have the same operations as any other kind of
583# declaration; one can extract their location information, spelling, find their
584# definitions, etc. However, the specific kind of the declaration is not
585# reported.
586CursorKind.UNEXPOSED_DECL = CursorKind(1)
587
588# A C or C++ struct.
589CursorKind.STRUCT_DECL = CursorKind(2)
590
591# A C or C++ union.
592CursorKind.UNION_DECL = CursorKind(3)
593
594# A C++ class.
595CursorKind.CLASS_DECL = CursorKind(4)
596
597# An enumeration.
598CursorKind.ENUM_DECL = CursorKind(5)
599
600# A field (in C) or non-static data member (in C++) in a struct, union, or C++
601# class.
602CursorKind.FIELD_DECL = CursorKind(6)
603
604# An enumerator constant.
605CursorKind.ENUM_CONSTANT_DECL = CursorKind(7)
606
607# A function.
608CursorKind.FUNCTION_DECL = CursorKind(8)
609
610# A variable.
611CursorKind.VAR_DECL = CursorKind(9)
612
613# A function or method parameter.
614CursorKind.PARM_DECL = CursorKind(10)
615
616# An Objective-C @interface.
617CursorKind.OBJC_INTERFACE_DECL = CursorKind(11)
618
619# An Objective-C @interface for a category.
620CursorKind.OBJC_CATEGORY_DECL = CursorKind(12)
621
622# An Objective-C @protocol declaration.
623CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13)
624
625# An Objective-C @property declaration.
626CursorKind.OBJC_PROPERTY_DECL = CursorKind(14)
627
628# An Objective-C instance variable.
629CursorKind.OBJC_IVAR_DECL = CursorKind(15)
630
631# An Objective-C instance method.
632CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16)
633
634# An Objective-C class method.
635CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17)
636
637# An Objective-C @implementation.
638CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18)
639
640# An Objective-C @implementation for a category.
641CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19)
642
Daniel Dunbara6a64992010-01-24 21:20:39 +0000643# A typedef.
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000644CursorKind.TYPEDEF_DECL = CursorKind(20)
645
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000646# A C++ class method.
647CursorKind.CXX_METHOD = CursorKind(21)
648
649# A C++ namespace.
650CursorKind.NAMESPACE = CursorKind(22)
651
652# A linkage specification, e.g. 'extern "C"'.
653CursorKind.LINKAGE_SPEC = CursorKind(23)
654
655# A C++ constructor.
656CursorKind.CONSTRUCTOR = CursorKind(24)
657
658# A C++ destructor.
659CursorKind.DESTRUCTOR = CursorKind(25)
660
661# A C++ conversion function.
662CursorKind.CONVERSION_FUNCTION = CursorKind(26)
663
664# A C++ template type parameter
665CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27)
666
667# A C++ non-type template paramater.
668CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28)
669
670# A C++ template template parameter.
671CursorKind.TEMPLATE_TEMPLATE_PARAMTER = CursorKind(29)
672
673# A C++ function template.
674CursorKind.FUNCTION_TEMPLATE = CursorKind(30)
675
676# A C++ class template.
677CursorKind.CLASS_TEMPLATE = CursorKind(31)
678
679# A C++ class template partial specialization.
680CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32)
681
682# A C++ namespace alias declaration.
683CursorKind.NAMESPACE_ALIAS = CursorKind(33)
684
685# A C++ using directive
686CursorKind.USING_DIRECTIVE = CursorKind(34)
687
688# A C++ using declaration
689CursorKind.USING_DECLARATION = CursorKind(35)
690
Douglas Gregor42b29842011-10-05 19:00:14 +0000691# A Type alias decl.
692CursorKind.TYPE_ALIAS_DECL = CursorKind(36)
693
694# A Objective-C synthesize decl
695CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37)
696
697# A Objective-C dynamic decl
698CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38)
699
700# A C++ access specifier decl.
701CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39)
702
703
Daniel Dunbara6a64992010-01-24 21:20:39 +0000704###
705# Reference Kinds
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000706
707CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40)
708CursorKind.OBJC_PROTOCOL_REF = CursorKind(41)
709CursorKind.OBJC_CLASS_REF = CursorKind(42)
710
711# A reference to a type declaration.
712#
713# A type reference occurs anywhere where a type is named but not
714# declared. For example, given:
715# typedef unsigned size_type;
716# size_type size;
717#
718# The typedef is a declaration of size_type (CXCursor_TypedefDecl),
719# while the type of the variable "size" is referenced. The cursor
720# referenced by the type of size is the typedef for size_type.
721CursorKind.TYPE_REF = CursorKind(43)
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000722CursorKind.CXX_BASE_SPECIFIER = CursorKind(44)
723
724# A reference to a class template, function template, template
725# template parameter, or class template partial specialization.
726CursorKind.TEMPLATE_REF = CursorKind(45)
727
728# A reference to a namespace or namepsace alias.
729CursorKind.NAMESPACE_REF = CursorKind(46)
730
731# A reference to a member of a struct, union, or class that occurs in
732# some non-expression context, e.g., a designated initializer.
733CursorKind.MEMBER_REF = CursorKind(47)
734
735# A reference to a labeled statement.
736CursorKind.LABEL_REF = CursorKind(48)
737
738# A reference toa a set of overloaded functions or function templates
739# that has not yet been resolved to a specific function or function template.
740CursorKind.OVERLOADED_DECL_REF = CursorKind(49)
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000741
Daniel Dunbara6a64992010-01-24 21:20:39 +0000742###
743# Invalid/Error Kinds
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000744
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000745CursorKind.INVALID_FILE = CursorKind(70)
746CursorKind.NO_DECL_FOUND = CursorKind(71)
747CursorKind.NOT_IMPLEMENTED = CursorKind(72)
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000748CursorKind.INVALID_CODE = CursorKind(73)
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000749
Daniel Dunbara6a64992010-01-24 21:20:39 +0000750###
751# Expression Kinds
752
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000753# An expression whose specific kind is not exposed via this interface.
754#
755# Unexposed expressions have the same operations as any other kind of
756# expression; one can extract their location information, spelling, children,
757# etc. However, the specific kind of the expression is not reported.
758CursorKind.UNEXPOSED_EXPR = CursorKind(100)
759
760# An expression that refers to some value declaration, such as a function,
761# varible, or enumerator.
762CursorKind.DECL_REF_EXPR = CursorKind(101)
763
764# An expression that refers to a member of a struct, union, class, Objective-C
765# class, etc.
766CursorKind.MEMBER_REF_EXPR = CursorKind(102)
767
768# An expression that calls a function.
769CursorKind.CALL_EXPR = CursorKind(103)
770
771# An expression that sends a message to an Objective-C object or class.
772CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104)
773
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000774# An expression that represents a block literal.
775CursorKind.BLOCK_EXPR = CursorKind(105)
776
Douglas Gregor42b29842011-10-05 19:00:14 +0000777# An integer literal.
778CursorKind.INTEGER_LITERAL = CursorKind(106)
779
780# A floating point number literal.
781CursorKind.FLOATING_LITERAL = CursorKind(107)
782
783# An imaginary number literal.
784CursorKind.IMAGINARY_LITERAL = CursorKind(108)
785
786# A string literal.
787CursorKind.STRING_LITERAL = CursorKind(109)
788
789# A character literal.
790CursorKind.CHARACTER_LITERAL = CursorKind(110)
791
792# A parenthesized expression, e.g. "(1)".
793#
794# This AST node is only formed if full location information is requested.
795CursorKind.PAREN_EXPR = CursorKind(111)
796
797# This represents the unary-expression's (except sizeof and
798# alignof).
799CursorKind.UNARY_OPERATOR = CursorKind(112)
800
801# [C99 6.5.2.1] Array Subscripting.
802CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113)
803
804# A builtin binary operation expression such as "x + y" or
805# "x <= y".
806CursorKind.BINARY_OPERATOR = CursorKind(114)
807
808# Compound assignment such as "+=".
809CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115)
810
811# The ?: ternary operator.
Douglas Gregor39a03d12012-06-08 00:16:27 +0000812CursorKind.CONDITIONAL_OPERATOR = CursorKind(116)
Douglas Gregor42b29842011-10-05 19:00:14 +0000813
814# An explicit cast in C (C99 6.5.4) or a C-style cast in C++
815# (C++ [expr.cast]), which uses the syntax (Type)expr.
816#
817# For example: (int)f.
818CursorKind.CSTYLE_CAST_EXPR = CursorKind(117)
819
820# [C99 6.5.2.5]
821CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118)
822
823# Describes an C or C++ initializer list.
824CursorKind.INIT_LIST_EXPR = CursorKind(119)
825
826# The GNU address of label extension, representing &&label.
827CursorKind.ADDR_LABEL_EXPR = CursorKind(120)
828
829# This is the GNU Statement Expression extension: ({int X=4; X;})
830CursorKind.StmtExpr = CursorKind(121)
831
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000832# Represents a C11 generic selection.
Douglas Gregor42b29842011-10-05 19:00:14 +0000833CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122)
834
835# Implements the GNU __null extension, which is a name for a null
836# pointer constant that has integral type (e.g., int or long) and is the same
837# size and alignment as a pointer.
838#
839# The __null extension is typically only used by system headers, which define
840# NULL as __null in C++ rather than using 0 (which is an integer that may not
841# match the size of a pointer).
842CursorKind.GNU_NULL_EXPR = CursorKind(123)
843
844# C++'s static_cast<> expression.
845CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124)
846
847# C++'s dynamic_cast<> expression.
848CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125)
849
850# C++'s reinterpret_cast<> expression.
851CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126)
852
853# C++'s const_cast<> expression.
854CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127)
855
856# Represents an explicit C++ type conversion that uses "functional"
857# notion (C++ [expr.type.conv]).
858#
859# Example:
860# \code
861# x = int(0.5);
862# \endcode
863CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128)
864
865# A C++ typeid expression (C++ [expr.typeid]).
866CursorKind.CXX_TYPEID_EXPR = CursorKind(129)
867
868# [C++ 2.13.5] C++ Boolean Literal.
869CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130)
870
871# [C++0x 2.14.7] C++ Pointer Literal.
872CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131)
873
874# Represents the "this" expression in C++
875CursorKind.CXX_THIS_EXPR = CursorKind(132)
876
877# [C++ 15] C++ Throw Expression.
878#
879# This handles 'throw' and 'throw' assignment-expression. When
880# assignment-expression isn't present, Op will be null.
881CursorKind.CXX_THROW_EXPR = CursorKind(133)
882
883# A new expression for memory allocation and constructor calls, e.g:
884# "new CXXNewExpr(foo)".
885CursorKind.CXX_NEW_EXPR = CursorKind(134)
886
887# A delete expression for memory deallocation and destructor calls,
888# e.g. "delete[] pArray".
889CursorKind.CXX_DELETE_EXPR = CursorKind(135)
890
891# Represents a unary expression.
892CursorKind.CXX_UNARY_EXPR = CursorKind(136)
893
894# ObjCStringLiteral, used for Objective-C string literals i.e. "foo".
895CursorKind.OBJC_STRING_LITERAL = CursorKind(137)
896
897# ObjCEncodeExpr, used for in Objective-C.
898CursorKind.OBJC_ENCODE_EXPR = CursorKind(138)
899
900# ObjCSelectorExpr used for in Objective-C.
901CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139)
902
903# Objective-C's protocol expression.
904CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140)
905
906# An Objective-C "bridged" cast expression, which casts between
907# Objective-C pointers and C pointers, transferring ownership in the process.
908#
909# \code
910# NSString *str = (__bridge_transfer NSString *)CFCreateString();
911# \endcode
912CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141)
913
914# Represents a C++0x pack expansion that produces a sequence of
915# expressions.
916#
917# A pack expansion expression contains a pattern (which itself is an
918# expression) followed by an ellipsis. For example:
919CursorKind.PACK_EXPANSION_EXPR = CursorKind(142)
920
921# Represents an expression that computes the length of a parameter
922# pack.
923CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143)
924
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000925# A statement whose specific kind is not exposed via this interface.
926#
927# Unexposed statements have the same operations as any other kind of statement;
928# one can extract their location information, spelling, children, etc. However,
929# the specific kind of the statement is not reported.
930CursorKind.UNEXPOSED_STMT = CursorKind(200)
931
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000932# A labelled statement in a function.
933CursorKind.LABEL_STMT = CursorKind(201)
934
Douglas Gregor42b29842011-10-05 19:00:14 +0000935# A compound statement
936CursorKind.COMPOUND_STMT = CursorKind(202)
937
938# A case statement.
939CursorKind.CASE_STMT = CursorKind(203)
940
941# A default statement.
942CursorKind.DEFAULT_STMT = CursorKind(204)
943
944# An if statement.
945CursorKind.IF_STMT = CursorKind(205)
946
947# A switch statement.
948CursorKind.SWITCH_STMT = CursorKind(206)
949
950# A while statement.
951CursorKind.WHILE_STMT = CursorKind(207)
952
953# A do statement.
954CursorKind.DO_STMT = CursorKind(208)
955
956# A for statement.
957CursorKind.FOR_STMT = CursorKind(209)
958
959# A goto statement.
960CursorKind.GOTO_STMT = CursorKind(210)
961
962# An indirect goto statement.
963CursorKind.INDIRECT_GOTO_STMT = CursorKind(211)
964
965# A continue statement.
966CursorKind.CONTINUE_STMT = CursorKind(212)
967
968# A break statement.
969CursorKind.BREAK_STMT = CursorKind(213)
970
971# A return statement.
972CursorKind.RETURN_STMT = CursorKind(214)
973
974# A GNU-style inline assembler statement.
975CursorKind.ASM_STMT = CursorKind(215)
976
977# Objective-C's overall @try-@catch-@finally statement.
978CursorKind.OBJC_AT_TRY_STMT = CursorKind(216)
979
980# Objective-C's @catch statement.
981CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217)
982
983# Objective-C's @finally statement.
984CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218)
985
986# Objective-C's @throw statement.
987CursorKind.OBJC_AT_THROW_STMT = CursorKind(219)
988
989# Objective-C's @synchronized statement.
990CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220)
991
992# Objective-C's autorealease pool statement.
993CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221)
994
995# Objective-C's for collection statement.
996CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222)
997
998# C++'s catch statement.
999CursorKind.CXX_CATCH_STMT = CursorKind(223)
1000
1001# C++'s try statement.
1002CursorKind.CXX_TRY_STMT = CursorKind(224)
1003
1004# C++'s for (* : *) statement.
1005CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225)
1006
1007# Windows Structured Exception Handling's try statement.
1008CursorKind.SEH_TRY_STMT = CursorKind(226)
1009
1010# Windows Structured Exception Handling's except statement.
1011CursorKind.SEH_EXCEPT_STMT = CursorKind(227)
1012
1013# Windows Structured Exception Handling's finally statement.
1014CursorKind.SEH_FINALLY_STMT = CursorKind(228)
1015
1016# The null statement.
1017CursorKind.NULL_STMT = CursorKind(230)
1018
1019# Adaptor class for mixing declarations with statements and expressions.
1020CursorKind.DECL_STMT = CursorKind(231)
Tobias Grosser4ed73ce2011-02-05 17:53:47 +00001021
Daniel Dunbara6a64992010-01-24 21:20:39 +00001022###
1023# Other Kinds
1024
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001025# Cursor that represents the translation unit itself.
1026#
1027# The translation unit cursor exists primarily to act as the root cursor for
1028# traversing the contents of a translation unit.
1029CursorKind.TRANSLATION_UNIT = CursorKind(300)
1030
Tobias Grosser4ed73ce2011-02-05 17:53:47 +00001031###
1032# Attributes
1033
1034# An attribute whoe specific kind is note exposed via this interface
1035CursorKind.UNEXPOSED_ATTR = CursorKind(400)
1036
1037CursorKind.IB_ACTION_ATTR = CursorKind(401)
1038CursorKind.IB_OUTLET_ATTR = CursorKind(402)
1039CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403)
1040
Rafael Espindolabf3cc732011-12-30 15:27:22 +00001041CursorKind.CXX_FINAL_ATTR = CursorKind(404)
1042CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405)
1043CursorKind.ANNOTATE_ATTR = CursorKind(406)
1044CursorKind.ASM_LABEL_ATTR = CursorKind(407)
1045
Tobias Grosser4ed73ce2011-02-05 17:53:47 +00001046###
1047# Preprocessing
1048CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500)
1049CursorKind.MACRO_DEFINITION = CursorKind(501)
1050CursorKind.MACRO_INSTANTIATION = CursorKind(502)
1051CursorKind.INCLUSION_DIRECTIVE = CursorKind(503)
1052
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001053### Cursors ###
1054
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001055class Cursor(Structure):
1056 """
1057 The Cursor class represents a reference to an element within the AST. It
1058 acts as a kind of iterator.
1059 """
Douglas Gregor2abfec32011-10-19 05:47:46 +00001060 _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001061
Tobias Grosser58ba8c92011-10-31 00:31:32 +00001062 @staticmethod
1063 def from_location(tu, location):
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001064 # We store a reference to the TU in the instance so the TU won't get
1065 # collected before the cursor.
Gregory Szorc9537e202012-07-12 04:56:46 +00001066 cursor = lib.clang_getCursor(tu, location)
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001067 cursor._tu = tu
1068
1069 return cursor
Tobias Grosser58ba8c92011-10-31 00:31:32 +00001070
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001071 def __eq__(self, other):
Gregory Szorc9537e202012-07-12 04:56:46 +00001072 return lib.clang_equalCursors(self, other)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001073
1074 def __ne__(self, other):
Gregory Szorc9d008fd2012-03-05 00:42:15 +00001075 return not self.__eq__(other)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001076
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001077 def is_definition(self):
1078 """
1079 Returns true if the declaration pointed at by the cursor is also a
1080 definition of that entity.
1081 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001082 return lib.clang_isCursorDefinition(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001083
Gregory Szorce65b34d2012-06-09 16:21:34 +00001084 def is_static_method(self):
1085 """Returns True if the cursor refers to a C++ member function or member
1086 function template that is declared 'static'.
1087 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001088 return lib.clang_CXXMethod_isStatic(self)
Gregory Szorce65b34d2012-06-09 16:21:34 +00001089
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001090 def get_definition(self):
1091 """
1092 If the cursor is a reference to a declaration or a declaration of
1093 some entity, return a cursor that points to the definition of that
1094 entity.
1095 """
1096 # TODO: Should probably check that this is either a reference or
1097 # declaration prior to issuing the lookup.
Gregory Szorc9537e202012-07-12 04:56:46 +00001098 return lib.clang_getCursorDefinition(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001099
Daniel Dunbar3d855f82010-01-24 21:20:13 +00001100 def get_usr(self):
1101 """Return the Unified Symbol Resultion (USR) for the entity referenced
1102 by the given cursor (or None).
1103
1104 A Unified Symbol Resolution (USR) is a string that identifies a
1105 particular entity (function, class, variable, etc.) within a
1106 program. USRs can be compared across translation units to determine,
1107 e.g., when references in one translation refer to an entity defined in
1108 another translation unit."""
Gregory Szorc9537e202012-07-12 04:56:46 +00001109 return lib.clang_getCursorUSR(self)
Daniel Dunbar3d855f82010-01-24 21:20:13 +00001110
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001111 @property
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001112 def kind(self):
1113 """Return the kind of this cursor."""
1114 return CursorKind.from_id(self._kind_id)
1115
1116 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001117 def spelling(self):
1118 """Return the spelling of the entity pointed at by the cursor."""
Daniel Dunbara6a64992010-01-24 21:20:39 +00001119 if not self.kind.is_declaration():
Daniel Dunbar3d855f82010-01-24 21:20:13 +00001120 # FIXME: clang_getCursorSpelling should be fixed to not assert on
1121 # this, for consistency with clang_getCursorUSR.
1122 return None
Douglas Gregor42b29842011-10-05 19:00:14 +00001123 if not hasattr(self, '_spelling'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001124 self._spelling = lib.clang_getCursorSpelling(self)
1125
Douglas Gregor42b29842011-10-05 19:00:14 +00001126 return self._spelling
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001127
1128 @property
Douglas Gregorb60a2be2011-08-30 00:15:34 +00001129 def displayname(self):
1130 """
1131 Return the display name for the entity referenced by this cursor.
1132
1133 The display name contains extra information that helps identify the cursor,
1134 such as the parameters of a function or template or the arguments of a
1135 class template specialization.
1136 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001137 if not hasattr(self, '_displayname'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001138 self._displayname = lib.clang_getCursorDisplayName(self)
1139
Douglas Gregor42b29842011-10-05 19:00:14 +00001140 return self._displayname
Douglas Gregorb60a2be2011-08-30 00:15:34 +00001141
1142 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001143 def location(self):
1144 """
1145 Return the source location (the starting character) of the entity
1146 pointed at by the cursor.
1147 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001148 if not hasattr(self, '_loc'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001149 self._loc = lib.clang_getCursorLocation(self)
1150
Douglas Gregor42b29842011-10-05 19:00:14 +00001151 return self._loc
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001152
1153 @property
1154 def extent(self):
1155 """
1156 Return the source range (the range of text) occupied by the entity
1157 pointed at by the cursor.
1158 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001159 if not hasattr(self, '_extent'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001160 self._extent = lib.clang_getCursorExtent(self)
1161
Douglas Gregor42b29842011-10-05 19:00:14 +00001162 return self._extent
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001163
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001164 @property
1165 def type(self):
1166 """
Tobias Grosser2d106802012-02-05 12:15:56 +00001167 Retrieve the Type (if any) of the entity pointed at by the cursor.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001168 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001169 if not hasattr(self, '_type'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001170 self._type = lib.clang_getCursorType(self)
1171
Douglas Gregor42b29842011-10-05 19:00:14 +00001172 return self._type
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001173
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00001174 @property
Gregory Szorc2c408352012-05-14 03:56:33 +00001175 def canonical(self):
1176 """Return the canonical Cursor corresponding to this Cursor.
1177
1178 The canonical cursor is the cursor which is representative for the
1179 underlying entity. For example, if you have multiple forward
1180 declarations for the same class, the canonical cursor for the forward
1181 declarations will be identical.
1182 """
1183 if not hasattr(self, '_canonical'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001184 self._canonical = lib.clang_getCanonicalCursor(self)
Gregory Szorc2c408352012-05-14 03:56:33 +00001185
1186 return self._canonical
1187
1188 @property
Gregory Szorc1e370ab2012-05-14 03:53:29 +00001189 def result_type(self):
1190 """Retrieve the Type of the result for this Cursor."""
1191 if not hasattr(self, '_result_type'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001192 self._result_type = lib.clang_getResultType(self.type)
Gregory Szorc1e370ab2012-05-14 03:53:29 +00001193
1194 return self._result_type
1195
1196 @property
Tobias Grosser28d939f2012-02-05 11:42:20 +00001197 def underlying_typedef_type(self):
1198 """Return the underlying type of a typedef declaration.
1199
Tobias Grosser2d106802012-02-05 12:15:56 +00001200 Returns a Type for the typedef this cursor is a declaration for. If
Tobias Grosser28d939f2012-02-05 11:42:20 +00001201 the current cursor is not a typedef, this raises.
1202 """
1203 if not hasattr(self, '_underlying_type'):
1204 assert self.kind.is_declaration()
Gregory Szorc9537e202012-07-12 04:56:46 +00001205 self._underlying_type = lib.clang_getTypedefDeclUnderlyingType(self)
Tobias Grosser28d939f2012-02-05 11:42:20 +00001206
1207 return self._underlying_type
1208
1209 @property
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00001210 def enum_type(self):
1211 """Return the integer type of an enum declaration.
1212
Tobias Grosser2d106802012-02-05 12:15:56 +00001213 Returns a Type corresponding to an integer. If the cursor is not for an
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00001214 enum, this raises.
1215 """
1216 if not hasattr(self, '_enum_type'):
1217 assert self.kind == CursorKind.ENUM_DECL
Gregory Szorc9537e202012-07-12 04:56:46 +00001218 self._enum_type = lib.clang_getEnumDeclIntegerType(self)
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00001219
1220 return self._enum_type
1221
1222 @property
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00001223 def enum_value(self):
1224 """Return the value of an enum constant."""
1225 if not hasattr(self, '_enum_value'):
1226 assert self.kind == CursorKind.ENUM_CONSTANT_DECL
1227 # Figure out the underlying type of the enum to know if it
1228 # is a signed or unsigned quantity.
1229 underlying_type = self.type
1230 if underlying_type.kind == TypeKind.ENUM:
1231 underlying_type = underlying_type.get_declaration().enum_type
1232 if underlying_type.kind in (TypeKind.CHAR_U,
1233 TypeKind.UCHAR,
1234 TypeKind.CHAR16,
1235 TypeKind.CHAR32,
1236 TypeKind.USHORT,
1237 TypeKind.UINT,
1238 TypeKind.ULONG,
1239 TypeKind.ULONGLONG,
1240 TypeKind.UINT128):
Gregory Szorc9537e202012-07-12 04:56:46 +00001241 self._enum_value = lib.clang_getEnumConstantDeclUnsignedValue(self)
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00001242 else:
Gregory Szorc9537e202012-07-12 04:56:46 +00001243 self._enum_value = lib.clang_getEnumConstantDeclValue(self)
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00001244 return self._enum_value
1245
1246 @property
Gregory Szorc5cc67872012-03-10 22:23:27 +00001247 def objc_type_encoding(self):
1248 """Return the Objective-C type encoding as a str."""
1249 if not hasattr(self, '_objc_type_encoding'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001250 self._objc_type_encoding = lib.clang_getDeclObjCTypeEncoding(self)
Gregory Szorc5cc67872012-03-10 22:23:27 +00001251
1252 return self._objc_type_encoding
1253
1254 @property
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00001255 def hash(self):
1256 """Returns a hash of the cursor as an int."""
1257 if not hasattr(self, '_hash'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001258 self._hash = lib.clang_hashCursor(self)
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00001259
1260 return self._hash
1261
Manuel Klimek667fd802012-05-07 05:56:03 +00001262 @property
1263 def semantic_parent(self):
1264 """Return the semantic parent for this cursor."""
1265 if not hasattr(self, '_semantic_parent'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001266 self._semantic_parent = lib.clang_getCursorSemanticParent(self)
Gregory Szorcfd04a6a2012-05-08 06:01:34 +00001267
Manuel Klimek667fd802012-05-07 05:56:03 +00001268 return self._semantic_parent
1269
1270 @property
1271 def lexical_parent(self):
1272 """Return the lexical parent for this cursor."""
1273 if not hasattr(self, '_lexical_parent'):
Gregory Szorc9537e202012-07-12 04:56:46 +00001274 self._lexical_parent = lib.clang_getCursorLexicalParent(self)
Gregory Szorcfd04a6a2012-05-08 06:01:34 +00001275
Manuel Klimek667fd802012-05-07 05:56:03 +00001276 return self._lexical_parent
Gregory Szorcfd04a6a2012-05-08 06:01:34 +00001277
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001278 @property
1279 def translation_unit(self):
1280 """Returns the TranslationUnit to which this Cursor belongs."""
1281 # If this triggers an AttributeError, the instance was not properly
1282 # created.
1283 return self._tu
1284
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001285 def get_children(self):
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001286 """Return an iterator for accessing the children of this cursor."""
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001287
1288 # FIXME: Expose iteration from CIndex, PR6125.
1289 def visitor(child, parent, children):
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001290 # FIXME: Document this assertion in API.
1291 # FIXME: There should just be an isNull method.
Gregory Szorc9537e202012-07-12 04:56:46 +00001292 assert child != lib.clang_getNullCursor()
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001293
1294 # Create reference to TU so it isn't GC'd before Cursor.
1295 child._tu = self._tu
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001296 children.append(child)
1297 return 1 # continue
1298 children = []
Gregory Szorc9537e202012-07-12 04:56:46 +00001299 lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
1300 children)
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001301 return iter(children)
1302
Gregory Szorcbe51e432012-07-12 07:21:12 +00001303 def get_tokens(self):
1304 """Obtain Token instances formulating that compose this Cursor.
1305
1306 This is a generator for Token instances. It returns all tokens which
1307 occupy the extent this cursor occupies.
1308 """
1309 return TokenGroup.get_tokens(self._tu, self.extent)
1310
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001311 @staticmethod
1312 def from_result(res, fn, args):
1313 assert isinstance(res, Cursor)
1314 # FIXME: There should just be an isNull method.
Gregory Szorc9537e202012-07-12 04:56:46 +00001315 if res == lib.clang_getNullCursor():
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001316 return None
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001317
1318 # Store a reference to the TU in the Python object so it won't get GC'd
1319 # before the Cursor.
1320 tu = None
1321 for arg in args:
1322 if isinstance(arg, TranslationUnit):
1323 tu = arg
1324 break
1325
1326 if hasattr(arg, 'translation_unit'):
1327 tu = arg.translation_unit
1328 break
1329
1330 assert tu is not None
1331
1332 res._tu = tu
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001333 return res
1334
Gregory Szorc9537e202012-07-12 04:56:46 +00001335 @staticmethod
1336 def from_cursor_result(res, fn, args):
1337 assert isinstance(res, Cursor)
1338 if res == lib.clang_getNullCursor():
1339 return None
1340
1341 res._tu = args[0]._tu
1342 return res
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001343
1344### Type Kinds ###
1345
1346class TypeKind(object):
1347 """
1348 Describes the kind of type.
1349 """
1350
1351 # The unique kind objects, indexed by id.
1352 _kinds = []
1353 _name_map = None
1354
1355 def __init__(self, value):
1356 if value >= len(TypeKind._kinds):
1357 TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1)
1358 if TypeKind._kinds[value] is not None:
1359 raise ValueError,'TypeKind already loaded'
1360 self.value = value
1361 TypeKind._kinds[value] = self
1362 TypeKind._name_map = None
1363
1364 def from_param(self):
1365 return self.value
1366
1367 @property
1368 def name(self):
1369 """Get the enumeration name of this cursor kind."""
1370 if self._name_map is None:
1371 self._name_map = {}
1372 for key,value in TypeKind.__dict__.items():
1373 if isinstance(value,TypeKind):
1374 self._name_map[value] = key
1375 return self._name_map[self]
1376
Gregory Szorc6e67eed2012-04-15 18:51:10 +00001377 @property
1378 def spelling(self):
1379 """Retrieve the spelling of this TypeKind."""
Gregory Szorc9537e202012-07-12 04:56:46 +00001380 return lib.clang_getTypeKindSpelling(self.value)
Gregory Szorc6e67eed2012-04-15 18:51:10 +00001381
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001382 @staticmethod
1383 def from_id(id):
1384 if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None:
Douglas Gregor9d342ab2011-10-19 05:49:29 +00001385 raise ValueError,'Unknown type kind %d' % id
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001386 return TypeKind._kinds[id]
1387
1388 def __repr__(self):
1389 return 'TypeKind.%s' % (self.name,)
1390
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001391TypeKind.INVALID = TypeKind(0)
1392TypeKind.UNEXPOSED = TypeKind(1)
1393TypeKind.VOID = TypeKind(2)
1394TypeKind.BOOL = TypeKind(3)
1395TypeKind.CHAR_U = TypeKind(4)
1396TypeKind.UCHAR = TypeKind(5)
1397TypeKind.CHAR16 = TypeKind(6)
1398TypeKind.CHAR32 = TypeKind(7)
1399TypeKind.USHORT = TypeKind(8)
1400TypeKind.UINT = TypeKind(9)
1401TypeKind.ULONG = TypeKind(10)
1402TypeKind.ULONGLONG = TypeKind(11)
1403TypeKind.UINT128 = TypeKind(12)
1404TypeKind.CHAR_S = TypeKind(13)
1405TypeKind.SCHAR = TypeKind(14)
1406TypeKind.WCHAR = TypeKind(15)
1407TypeKind.SHORT = TypeKind(16)
1408TypeKind.INT = TypeKind(17)
1409TypeKind.LONG = TypeKind(18)
1410TypeKind.LONGLONG = TypeKind(19)
1411TypeKind.INT128 = TypeKind(20)
1412TypeKind.FLOAT = TypeKind(21)
1413TypeKind.DOUBLE = TypeKind(22)
1414TypeKind.LONGDOUBLE = TypeKind(23)
1415TypeKind.NULLPTR = TypeKind(24)
1416TypeKind.OVERLOAD = TypeKind(25)
1417TypeKind.DEPENDENT = TypeKind(26)
1418TypeKind.OBJCID = TypeKind(27)
1419TypeKind.OBJCCLASS = TypeKind(28)
1420TypeKind.OBJCSEL = TypeKind(29)
1421TypeKind.COMPLEX = TypeKind(100)
1422TypeKind.POINTER = TypeKind(101)
1423TypeKind.BLOCKPOINTER = TypeKind(102)
1424TypeKind.LVALUEREFERENCE = TypeKind(103)
1425TypeKind.RVALUEREFERENCE = TypeKind(104)
1426TypeKind.RECORD = TypeKind(105)
1427TypeKind.ENUM = TypeKind(106)
1428TypeKind.TYPEDEF = TypeKind(107)
1429TypeKind.OBJCINTERFACE = TypeKind(108)
1430TypeKind.OBJCOBJECTPOINTER = TypeKind(109)
1431TypeKind.FUNCTIONNOPROTO = TypeKind(110)
1432TypeKind.FUNCTIONPROTO = TypeKind(111)
Douglas Gregor38d2d552011-10-19 05:50:34 +00001433TypeKind.CONSTANTARRAY = TypeKind(112)
Tobias Grosser250d2172012-02-05 11:42:14 +00001434TypeKind.VECTOR = TypeKind(113)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001435
1436class Type(Structure):
1437 """
1438 The type of an element in the abstract syntax tree.
1439 """
1440 _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)]
1441
1442 @property
1443 def kind(self):
1444 """Return the kind of this type."""
1445 return TypeKind.from_id(self._kind_id)
1446
Gregory Szorc826fce52012-02-20 17:45:30 +00001447 def argument_types(self):
1448 """Retrieve a container for the non-variadic arguments for this type.
1449
1450 The returned object is iterable and indexable. Each item in the
1451 container is a Type instance.
1452 """
1453 class ArgumentsIterator(collections.Sequence):
1454 def __init__(self, parent):
1455 self.parent = parent
1456 self.length = None
1457
1458 def __len__(self):
1459 if self.length is None:
Gregory Szorc9537e202012-07-12 04:56:46 +00001460 self.length = lib.clang_getNumArgTypes(self.parent)
Gregory Szorc826fce52012-02-20 17:45:30 +00001461
1462 return self.length
1463
1464 def __getitem__(self, key):
1465 # FIXME Support slice objects.
1466 if not isinstance(key, int):
1467 raise TypeError("Must supply a non-negative int.")
1468
1469 if key < 0:
1470 raise IndexError("Only non-negative indexes are accepted.")
1471
1472 if key >= len(self):
1473 raise IndexError("Index greater than container length: "
1474 "%d > %d" % ( key, len(self) ))
1475
Gregory Szorc9537e202012-07-12 04:56:46 +00001476 result = lib.clang_getArgType(self.parent, key)
Gregory Szorc826fce52012-02-20 17:45:30 +00001477 if result.kind == TypeKind.INVALID:
1478 raise IndexError("Argument could not be retrieved.")
1479
1480 return result
1481
1482 assert self.kind == TypeKind.FUNCTIONPROTO
1483 return ArgumentsIterator(self)
1484
Gregory Szorc86057602012-02-17 07:44:46 +00001485 @property
1486 def element_type(self):
1487 """Retrieve the Type of elements within this Type.
1488
1489 If accessed on a type that is not an array, complex, or vector type, an
1490 exception will be raised.
1491 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001492 result = lib.clang_getElementType(self)
Gregory Szorc86057602012-02-17 07:44:46 +00001493 if result.kind == TypeKind.INVALID:
1494 raise Exception('Element type not available on this type.')
1495
1496 return result
1497
Gregory Szorcbf8ca002012-02-17 07:47:38 +00001498 @property
1499 def element_count(self):
1500 """Retrieve the number of elements in this type.
1501
1502 Returns an int.
1503
1504 If the Type is not an array or vector, this raises.
1505 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001506 result = lib.clang_getNumElements(self)
Gregory Szorcbf8ca002012-02-17 07:47:38 +00001507 if result < 0:
1508 raise Exception('Type does not have elements.')
1509
1510 return result
1511
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001512 @property
1513 def translation_unit(self):
1514 """The TranslationUnit to which this Type is associated."""
1515 # If this triggers an AttributeError, the instance was not properly
1516 # instantiated.
1517 return self._tu
1518
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001519 @staticmethod
1520 def from_result(res, fn, args):
1521 assert isinstance(res, Type)
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001522
1523 tu = None
1524 for arg in args:
1525 if hasattr(arg, 'translation_unit'):
1526 tu = arg.translation_unit
1527 break
1528
1529 assert tu is not None
1530 res._tu = tu
1531
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001532 return res
1533
1534 def get_canonical(self):
1535 """
1536 Return the canonical type for a Type.
1537
1538 Clang's type system explicitly models typedefs and all the
1539 ways a specific type can be represented. The canonical type
1540 is the underlying type with all the "sugar" removed. For
1541 example, if 'T' is a typedef for 'int', the canonical type for
1542 'T' would be 'int'.
1543 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001544 return lib.clang_getCanonicalType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001545
1546 def is_const_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001547 """Determine whether a Type has the "const" qualifier set.
1548
1549 This does not look through typedefs that may have added "const"
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001550 at a different level.
1551 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001552 return lib.clang_isConstQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001553
1554 def is_volatile_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001555 """Determine whether a Type has the "volatile" qualifier set.
1556
1557 This does not look through typedefs that may have added "volatile"
1558 at a different level.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001559 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001560 return lib.clang_isVolatileQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001561
1562 def is_restrict_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001563 """Determine whether a Type has the "restrict" qualifier set.
1564
1565 This does not look through typedefs that may have added "restrict" at
1566 a different level.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001567 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001568 return lib.clang_isRestrictQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001569
Gregory Szorc31cc38c2012-02-19 18:28:33 +00001570 def is_function_variadic(self):
1571 """Determine whether this function Type is a variadic function type."""
1572 assert self.kind == TypeKind.FUNCTIONPROTO
1573
Gregory Szorc9537e202012-07-12 04:56:46 +00001574 return lib.clang_isFunctionTypeVariadic(self)
Gregory Szorc31cc38c2012-02-19 18:28:33 +00001575
Gregory Szorc96ad6332012-02-05 19:42:06 +00001576 def is_pod(self):
1577 """Determine whether this Type represents plain old data (POD)."""
Gregory Szorc9537e202012-07-12 04:56:46 +00001578 return lib.clang_isPODType(self)
Gregory Szorc96ad6332012-02-05 19:42:06 +00001579
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001580 def get_pointee(self):
1581 """
1582 For pointer types, returns the type of the pointee.
1583 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001584 return lib.clang_getPointeeType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001585
1586 def get_declaration(self):
1587 """
1588 Return the cursor for the declaration of the given type.
1589 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001590 return lib.clang_getTypeDeclaration(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001591
1592 def get_result(self):
1593 """
1594 Retrieve the result type associated with a function type.
1595 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001596 return lib.clang_getResultType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001597
Douglas Gregor13102ff2011-10-19 05:51:43 +00001598 def get_array_element_type(self):
1599 """
1600 Retrieve the type of the elements of the array type.
1601 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001602 return lib.clang_getArrayElementType(self)
Douglas Gregor13102ff2011-10-19 05:51:43 +00001603
1604 def get_array_size(self):
1605 """
1606 Retrieve the size of the constant array.
1607 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001608 return lib.clang_getArraySize(self)
Douglas Gregor13102ff2011-10-19 05:51:43 +00001609
Gregory Szorc7eb691a2012-02-20 17:44:49 +00001610 def __eq__(self, other):
1611 if type(other) != type(self):
1612 return False
1613
Gregory Szorc9537e202012-07-12 04:56:46 +00001614 return lib.clang_equalTypes(self, other)
Gregory Szorc7eb691a2012-02-20 17:44:49 +00001615
1616 def __ne__(self, other):
1617 return not self.__eq__(other)
1618
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001619## CIndex Objects ##
1620
1621# CIndex objects (derived from ClangObject) are essentially lightweight
1622# wrappers attached to some underlying object, which is exposed via CIndex as
1623# a void*.
1624
1625class ClangObject(object):
1626 """
1627 A helper for Clang objects. This class helps act as an intermediary for
1628 the ctypes library and the Clang CIndex library.
1629 """
1630 def __init__(self, obj):
1631 assert isinstance(obj, c_object_p) and obj
1632 self.obj = self._as_parameter_ = obj
1633
1634 def from_param(self):
1635 return self._as_parameter_
1636
Daniel Dunbar5b534f62010-01-25 00:44:11 +00001637
1638class _CXUnsavedFile(Structure):
1639 """Helper for passing unsaved file arguments."""
1640 _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
1641
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001642class CompletionChunk:
1643 class Kind:
1644 def __init__(self, name):
1645 self.name = name
1646
1647 def __str__(self):
1648 return self.name
1649
1650 def __repr__(self):
1651 return "<ChunkKind: %s>" % self
1652
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001653 def __init__(self, completionString, key):
1654 self.cs = completionString
1655 self.key = key
1656
1657 def __repr__(self):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001658 return "{'" + self.spelling + "', " + str(self.kind) + "}"
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001659
Tobias Grosserd9ee06b2012-08-19 22:26:15 +00001660 @CachedProperty
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001661 def spelling(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001662 return lib.clang_getCompletionChunkText(self.cs, self.key).spelling
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001663
Tobias Grosserd9ee06b2012-08-19 22:26:15 +00001664 @CachedProperty
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001665 def kind(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001666 res = lib.clang_getCompletionChunkKind(self.cs, self.key)
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001667 return completionChunkKindMap[res]
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001668
Tobias Grosserd9ee06b2012-08-19 22:26:15 +00001669 @CachedProperty
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001670 def string(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001671 res = lib.clang_getCompletionChunkCompletionString(self.cs, self.key)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001672
1673 if (res):
1674 return CompletionString(res)
1675 else:
1676 None
1677
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001678 def isKindOptional(self):
1679 return self.kind == completionChunkKindMap[0]
1680
1681 def isKindTypedText(self):
1682 return self.kind == completionChunkKindMap[1]
1683
1684 def isKindPlaceHolder(self):
1685 return self.kind == completionChunkKindMap[3]
1686
1687 def isKindInformative(self):
1688 return self.kind == completionChunkKindMap[4]
1689
1690 def isKindResultType(self):
1691 return self.kind == completionChunkKindMap[15]
1692
1693completionChunkKindMap = {
1694 0: CompletionChunk.Kind("Optional"),
1695 1: CompletionChunk.Kind("TypedText"),
1696 2: CompletionChunk.Kind("Text"),
1697 3: CompletionChunk.Kind("Placeholder"),
1698 4: CompletionChunk.Kind("Informative"),
1699 5: CompletionChunk.Kind("CurrentParameter"),
1700 6: CompletionChunk.Kind("LeftParen"),
1701 7: CompletionChunk.Kind("RightParen"),
1702 8: CompletionChunk.Kind("LeftBracket"),
1703 9: CompletionChunk.Kind("RightBracket"),
1704 10: CompletionChunk.Kind("LeftBrace"),
1705 11: CompletionChunk.Kind("RightBrace"),
1706 12: CompletionChunk.Kind("LeftAngle"),
1707 13: CompletionChunk.Kind("RightAngle"),
1708 14: CompletionChunk.Kind("Comma"),
1709 15: CompletionChunk.Kind("ResultType"),
1710 16: CompletionChunk.Kind("Colon"),
1711 17: CompletionChunk.Kind("SemiColon"),
1712 18: CompletionChunk.Kind("Equal"),
1713 19: CompletionChunk.Kind("HorizontalSpace"),
1714 20: CompletionChunk.Kind("VerticalSpace")}
1715
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001716class CompletionString(ClangObject):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001717 class Availability:
1718 def __init__(self, name):
1719 self.name = name
1720
1721 def __str__(self):
1722 return self.name
1723
1724 def __repr__(self):
1725 return "<Availability: %s>" % self
1726
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001727 def __len__(self):
Tobias Grosser147785b2012-08-20 10:38:16 +00001728 self.num_chunks
1729
1730 @CachedProperty
1731 def num_chunks(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001732 return lib.clang_getNumCompletionChunks(self.obj)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001733
1734 def __getitem__(self, key):
Tobias Grosser147785b2012-08-20 10:38:16 +00001735 if self.num_chunks <= key:
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001736 raise IndexError
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001737 return CompletionChunk(self.obj, key)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001738
1739 @property
1740 def priority(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001741 return lib.clang_getCompletionPriority(self.obj)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001742
1743 @property
1744 def availability(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001745 res = lib.clang_getCompletionAvailability(self.obj)
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001746 return availabilityKinds[res]
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001747
1748 def __repr__(self):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001749 return " | ".join([str(a) for a in self]) \
1750 + " || Priority: " + str(self.priority) \
1751 + " || Availability: " + str(self.availability)
1752
1753availabilityKinds = {
1754 0: CompletionChunk.Kind("Available"),
1755 1: CompletionChunk.Kind("Deprecated"),
1756 2: CompletionChunk.Kind("NotAvailable")}
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001757
Tobias Grosser0a166802011-02-05 17:54:04 +00001758class CodeCompletionResult(Structure):
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001759 _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
1760
1761 def __repr__(self):
1762 return str(CompletionString(self.completionString))
1763
1764 @property
1765 def kind(self):
1766 return CursorKind.from_id(self.cursorKind)
1767
1768 @property
1769 def string(self):
1770 return CompletionString(self.completionString)
Tobias Grosser0a166802011-02-05 17:54:04 +00001771
1772class CCRStructure(Structure):
1773 _fields_ = [('results', POINTER(CodeCompletionResult)),
1774 ('numResults', c_int)]
1775
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001776 def __len__(self):
1777 return self.numResults
1778
1779 def __getitem__(self, key):
1780 if len(self) <= key:
1781 raise IndexError
1782
1783 return self.results[key]
1784
Tobias Grosser0a166802011-02-05 17:54:04 +00001785class CodeCompletionResults(ClangObject):
1786 def __init__(self, ptr):
1787 assert isinstance(ptr, POINTER(CCRStructure)) and ptr
1788 self.ptr = self._as_parameter_ = ptr
1789
1790 def from_param(self):
1791 return self._as_parameter_
1792
1793 def __del__(self):
Tobias Grosser58308d82012-08-18 23:52:41 +00001794 lib.clang_disposeCodeCompleteResults(self)
Tobias Grosser0a166802011-02-05 17:54:04 +00001795
1796 @property
1797 def results(self):
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001798 return self.ptr.contents
Tobias Grosser0a166802011-02-05 17:54:04 +00001799
1800 @property
1801 def diagnostics(self):
1802 class DiagnosticsItr:
1803 def __init__(self, ccr):
1804 self.ccr= ccr
1805
1806 def __len__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001807 return int(lib.clang_codeCompleteGetNumDiagnostics(self.ccr))
Tobias Grosser0a166802011-02-05 17:54:04 +00001808
1809 def __getitem__(self, key):
Gregory Szorc9537e202012-07-12 04:56:46 +00001810 return lib.clang_codeCompleteGetDiagnostic(self.ccr, key)
Tobias Grosser0a166802011-02-05 17:54:04 +00001811
1812 return DiagnosticsItr(self)
1813
1814
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001815class Index(ClangObject):
1816 """
1817 The Index type provides the primary interface to the Clang CIndex library,
1818 primarily by providing an interface for reading and parsing translation
1819 units.
1820 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001821
1822 @staticmethod
Daniel Dunbar2791dfc2010-01-30 23:58:39 +00001823 def create(excludeDecls=False):
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001824 """
1825 Create a new Index.
1826 Parameters:
1827 excludeDecls -- Exclude local declarations from translation units.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001828 """
Gregory Szorc9537e202012-07-12 04:56:46 +00001829 return Index(lib.clang_createIndex(excludeDecls, 0))
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001830
1831 def __del__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001832 lib.clang_disposeIndex(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001833
1834 def read(self, path):
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001835 """Load a TranslationUnit from the given AST file."""
1836 return TranslationUnit.from_ast(path, self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001837
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001838 def parse(self, path, args=None, unsaved_files=None, options = 0):
1839 """Load the translation unit from the given source code file by running
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001840 clang and generating the AST before loading. Additional command line
1841 parameters can be passed to clang via the args parameter.
Daniel Dunbar5b534f62010-01-25 00:44:11 +00001842
1843 In-memory contents for files can be provided by passing a list of pairs
1844 to as unsaved_files, the first item should be the filenames to be mapped
1845 and the second should be the contents to be substituted for the
1846 file. The contents may be passed as strings or file objects.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001847
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001848 If an error was encountered during parsing, a TranslationUnitLoadError
1849 will be raised.
1850 """
1851 return TranslationUnit.from_source(path, args, unsaved_files, options,
1852 self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001853
1854class TranslationUnit(ClangObject):
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001855 """Represents a source code translation unit.
1856
1857 This is one of the main types in the API. Any time you wish to interact
1858 with Clang's representation of a source file, you typically start with a
1859 translation unit.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001860 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001861
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001862 # Default parsing mode.
1863 PARSE_NONE = 0
1864
1865 # Instruct the parser to create a detailed processing record containing
1866 # metadata not normally retained.
1867 PARSE_DETAILED_PROCESSING_RECORD = 1
1868
1869 # Indicates that the translation unit is incomplete. This is typically used
1870 # when parsing headers.
1871 PARSE_INCOMPLETE = 2
1872
1873 # Instruct the parser to create a pre-compiled preamble for the translation
1874 # unit. This caches the preamble (included files at top of source file).
1875 # This is useful if the translation unit will be reparsed and you don't
1876 # want to incur the overhead of reparsing the preamble.
1877 PARSE_PRECOMPILED_PREAMBLE = 4
1878
1879 # Cache code completion information on parse. This adds time to parsing but
1880 # speeds up code completion.
1881 PARSE_CACHE_COMPLETION_RESULTS = 8
1882
1883 # Flags with values 16 and 32 are deprecated and intentionally omitted.
1884
1885 # Do not parse function bodies. This is useful if you only care about
1886 # searching for declarations/definitions.
1887 PARSE_SKIP_FUNCTION_BODIES = 64
1888
1889 @classmethod
1890 def from_source(cls, filename, args=None, unsaved_files=None, options=0,
1891 index=None):
1892 """Create a TranslationUnit by parsing source.
1893
1894 This is capable of processing source code both from files on the
1895 filesystem as well as in-memory contents.
1896
1897 Command-line arguments that would be passed to clang are specified as
1898 a list via args. These can be used to specify include paths, warnings,
1899 etc. e.g. ["-Wall", "-I/path/to/include"].
1900
1901 In-memory file content can be provided via unsaved_files. This is an
1902 iterable of 2-tuples. The first element is the str filename. The
1903 second element defines the content. Content can be provided as str
1904 source code or as file objects (anything with a read() method). If
1905 a file object is being used, content will be read until EOF and the
1906 read cursor will not be reset to its original position.
1907
1908 options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
1909 control parsing behavior.
1910
Gregory Szorc2283b462012-05-12 20:49:13 +00001911 index is an Index instance to utilize. If not provided, a new Index
1912 will be created for this TranslationUnit.
1913
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001914 To parse source from the filesystem, the filename of the file to parse
1915 is specified by the filename argument. Or, filename could be None and
1916 the args list would contain the filename(s) to parse.
1917
1918 To parse source from an in-memory buffer, set filename to the virtual
1919 filename you wish to associate with this source (e.g. "test.c"). The
1920 contents of that file are then provided in unsaved_files.
1921
1922 If an error occurs, a TranslationUnitLoadError is raised.
1923
1924 Please note that a TranslationUnit with parser errors may be returned.
1925 It is the caller's responsibility to check tu.diagnostics for errors.
1926
1927 Also note that Clang infers the source language from the extension of
1928 the input filename. If you pass in source code containing a C++ class
1929 declaration with the filename "test.c" parsing will fail.
1930 """
1931 if args is None:
1932 args = []
1933
1934 if unsaved_files is None:
1935 unsaved_files = []
1936
1937 if index is None:
1938 index = Index.create()
1939
1940 args_array = None
1941 if len(args) > 0:
1942 args_array = (c_char_p * len(args))(* args)
1943
1944 unsaved_array = None
1945 if len(unsaved_files) > 0:
1946 unsaved_array = (_CXUnsavedFile * len(unsaved_files))()
1947 for i, (name, contents) in enumerate(unsaved_files):
1948 if hasattr(contents, "read"):
1949 contents = contents.read()
1950
1951 unsaved_array[i].name = name
1952 unsaved_array[i].contents = contents
1953 unsaved_array[i].length = len(contents)
1954
Gregory Szorc9537e202012-07-12 04:56:46 +00001955 ptr = lib.clang_parseTranslationUnit(index, filename, args_array,
1956 len(args), unsaved_array,
1957 len(unsaved_files), options)
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001958
1959 if ptr is None:
1960 raise TranslationUnitLoadError("Error parsing translation unit.")
1961
1962 return cls(ptr, index=index)
1963
1964 @classmethod
1965 def from_ast_file(cls, filename, index=None):
1966 """Create a TranslationUnit instance from a saved AST file.
1967
1968 A previously-saved AST file (provided with -emit-ast or
1969 TranslationUnit.save()) is loaded from the filename specified.
1970
1971 If the file cannot be loaded, a TranslationUnitLoadError will be
1972 raised.
1973
1974 index is optional and is the Index instance to use. If not provided,
1975 a default Index will be created.
1976 """
1977 if index is None:
1978 index = Index.create()
1979
Gregory Szorc9537e202012-07-12 04:56:46 +00001980 ptr = lib.clang_createTranslationUnit(index, filename)
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001981 if ptr is None:
1982 raise TranslationUnitLoadError(filename)
1983
1984 return cls(ptr=ptr, index=index)
1985
1986 def __init__(self, ptr, index):
1987 """Create a TranslationUnit instance.
1988
1989 TranslationUnits should be created using one of the from_* @classmethod
1990 functions above. __init__ is only called internally.
1991 """
1992 assert isinstance(index, Index)
1993
Daniel Dunbar532fc632010-01-30 23:59:02 +00001994 ClangObject.__init__(self, ptr)
Daniel Dunbar532fc632010-01-30 23:59:02 +00001995
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001996 def __del__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00001997 lib.clang_disposeTranslationUnit(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001998
Daniel Dunbar1b945a72010-01-24 04:09:43 +00001999 @property
2000 def cursor(self):
2001 """Retrieve the cursor that represents the given translation unit."""
Gregory Szorc9537e202012-07-12 04:56:46 +00002002 return lib.clang_getTranslationUnitCursor(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002003
2004 @property
2005 def spelling(self):
Daniel Dunbar1b945a72010-01-24 04:09:43 +00002006 """Get the original translation unit source file name."""
Gregory Szorc9537e202012-07-12 04:56:46 +00002007 return lib.clang_getTranslationUnitSpelling(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002008
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002009 def get_includes(self):
2010 """
2011 Return an iterable sequence of FileInclusion objects that describe the
2012 sequence of inclusions in a translation unit. The first object in
2013 this sequence is always the input file. Note that this method will not
2014 recursively iterate over header files included through precompiled
2015 headers.
2016 """
2017 def visitor(fobj, lptr, depth, includes):
Douglas Gregor8be80e12011-07-06 03:00:34 +00002018 if depth > 0:
2019 loc = lptr.contents
2020 includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002021
2022 # Automatically adapt CIndex/ctype pointers to python objects
2023 includes = []
Gregory Szorc9537e202012-07-12 04:56:46 +00002024 lib.clang_getInclusions(self,
2025 callbacks['translation_unit_includes'](visitor), includes)
2026
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002027 return iter(includes)
2028
Gregory Szorc0f1964a2012-07-12 05:05:56 +00002029 def get_file(self, filename):
2030 """Obtain a File from this translation unit."""
2031
2032 return File.from_name(self, filename)
2033
2034 def get_location(self, filename, position):
2035 """Obtain a SourceLocation for a file in this translation unit.
2036
2037 The position can be specified by passing:
2038
2039 - Integer file offset. Initial file offset is 0.
2040 - 2-tuple of (line number, column number). Initial file position is
2041 (0, 0)
2042 """
2043 f = self.get_file(filename)
2044
2045 if isinstance(position, int):
2046 return SourceLocation.from_offset(self, f, position)
2047
2048 return SourceLocation.from_position(self, f, position[0], position[1])
2049
2050 def get_extent(self, filename, locations):
2051 """Obtain a SourceRange from this translation unit.
2052
2053 The bounds of the SourceRange must ultimately be defined by a start and
2054 end SourceLocation. For the locations argument, you can pass:
2055
2056 - 2 SourceLocation instances in a 2-tuple or list.
2057 - 2 int file offsets via a 2-tuple or list.
2058 - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
2059
2060 e.g.
2061
2062 get_extent('foo.c', (5, 10))
2063 get_extent('foo.c', ((1, 1), (1, 15)))
2064 """
2065 f = self.get_file(filename)
2066
2067 if len(locations) < 2:
2068 raise Exception('Must pass object with at least 2 elements')
2069
2070 start_location, end_location = locations
2071
2072 if hasattr(start_location, '__len__'):
2073 start_location = SourceLocation.from_position(self, f,
2074 start_location[0], start_location[1])
2075 elif isinstance(start_location, int):
2076 start_location = SourceLocation.from_offset(self, f,
2077 start_location)
2078
2079 if hasattr(end_location, '__len__'):
2080 end_location = SourceLocation.from_position(self, f,
2081 end_location[0], end_location[1])
2082 elif isinstance(end_location, int):
2083 end_location = SourceLocation.from_offset(self, f, end_location)
2084
2085 assert isinstance(start_location, SourceLocation)
2086 assert isinstance(end_location, SourceLocation)
2087
2088 return SourceRange.from_locations(start_location, end_location)
2089
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002090 @property
2091 def diagnostics(self):
2092 """
2093 Return an iterable (and indexable) object containing the diagnostics.
2094 """
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00002095 class DiagIterator:
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002096 def __init__(self, tu):
2097 self.tu = tu
2098
2099 def __len__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00002100 return int(lib.clang_getNumDiagnostics(self.tu))
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002101
2102 def __getitem__(self, key):
Gregory Szorc9537e202012-07-12 04:56:46 +00002103 diag = lib.clang_getDiagnostic(self.tu, key)
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00002104 if not diag:
2105 raise IndexError
2106 return Diagnostic(diag)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002107
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00002108 return DiagIterator(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002109
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002110 def reparse(self, unsaved_files=None, options=0):
Tobias Grosser265e6b22011-02-05 17:54:00 +00002111 """
2112 Reparse an already parsed translation unit.
2113
2114 In-memory contents for files can be provided by passing a list of pairs
2115 as unsaved_files, the first items should be the filenames to be mapped
2116 and the second should be the contents to be substituted for the
2117 file. The contents may be passed as strings or file objects.
2118 """
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002119 if unsaved_files is None:
2120 unsaved_files = []
2121
Tobias Grosser265e6b22011-02-05 17:54:00 +00002122 unsaved_files_array = 0
2123 if len(unsaved_files):
2124 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
2125 for i,(name,value) in enumerate(unsaved_files):
2126 if not isinstance(value, str):
2127 # FIXME: It would be great to support an efficient version
2128 # of this, one day.
2129 value = value.read()
2130 print value
2131 if not isinstance(value, str):
2132 raise TypeError,'Unexpected unsaved file contents.'
2133 unsaved_files_array[i].name = name
2134 unsaved_files_array[i].contents = value
2135 unsaved_files_array[i].length = len(value)
Gregory Szorc9537e202012-07-12 04:56:46 +00002136 ptr = lib.clang_reparseTranslationUnit(self, len(unsaved_files),
2137 unsaved_files_array, options)
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002138
2139 def save(self, filename):
2140 """Saves the TranslationUnit to a file.
2141
2142 This is equivalent to passing -emit-ast to the clang frontend. The
2143 saved file can be loaded back into a TranslationUnit. Or, if it
2144 corresponds to a header, it can be used as a pre-compiled header file.
2145
2146 If an error occurs while saving, a TranslationUnitSaveError is raised.
2147 If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
2148 the constructed TranslationUnit was not valid at time of save. In this
2149 case, the reason(s) why should be available via
2150 TranslationUnit.diagnostics().
2151
2152 filename -- The path to save the translation unit to.
2153 """
Gregory Szorc9537e202012-07-12 04:56:46 +00002154 options = lib.clang_defaultSaveOptions(self)
2155 result = int(lib.clang_saveTranslationUnit(self, filename, options))
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002156 if result != 0:
2157 raise TranslationUnitSaveError(result,
2158 'Error saving TranslationUnit.')
2159
Gregory Szorc2283b462012-05-12 20:49:13 +00002160 def codeComplete(self, path, line, column, unsaved_files=None, options=0):
Tobias Grosser0a166802011-02-05 17:54:04 +00002161 """
2162 Code complete in this translation unit.
2163
2164 In-memory contents for files can be provided by passing a list of pairs
2165 as unsaved_files, the first items should be the filenames to be mapped
2166 and the second should be the contents to be substituted for the
2167 file. The contents may be passed as strings or file objects.
2168 """
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002169 if unsaved_files is None:
2170 unsaved_files = []
2171
Tobias Grosser0a166802011-02-05 17:54:04 +00002172 unsaved_files_array = 0
2173 if len(unsaved_files):
2174 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
2175 for i,(name,value) in enumerate(unsaved_files):
2176 if not isinstance(value, str):
2177 # FIXME: It would be great to support an efficient version
2178 # of this, one day.
2179 value = value.read()
2180 print value
2181 if not isinstance(value, str):
2182 raise TypeError,'Unexpected unsaved file contents.'
2183 unsaved_files_array[i].name = name
2184 unsaved_files_array[i].contents = value
2185 unsaved_files_array[i].length = len(value)
Gregory Szorc9537e202012-07-12 04:56:46 +00002186 ptr = lib.clang_codeCompleteAt(self, path, line, column,
2187 unsaved_files_array, len(unsaved_files), options)
Tobias Grosserba5d10b2011-10-31 02:06:50 +00002188 if ptr:
2189 return CodeCompletionResults(ptr)
2190 return None
Tobias Grosser265e6b22011-02-05 17:54:00 +00002191
Gregory Szorcbe51e432012-07-12 07:21:12 +00002192 def get_tokens(self, locations=None, extent=None):
2193 """Obtain tokens in this translation unit.
2194
2195 This is a generator for Token instances. The caller specifies a range
2196 of source code to obtain tokens for. The range can be specified as a
2197 2-tuple of SourceLocation or as a SourceRange. If both are defined,
2198 behavior is undefined.
2199 """
2200 if locations is not None:
2201 extent = SourceRange(start=locations[0], end=locations[1])
2202
2203 return TokenGroup.get_tokens(self, extent)
2204
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002205class File(ClangObject):
2206 """
Daniel Dunbar7b48b352010-01-24 04:09:34 +00002207 The File class represents a particular source file that is part of a
2208 translation unit.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002209 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002210
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002211 @staticmethod
2212 def from_name(translation_unit, file_name):
2213 """Retrieve a file handle within the given translation unit."""
Gregory Szorc9537e202012-07-12 04:56:46 +00002214 return File(lib.clang_getFile(translation_unit, file_name))
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002215
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002216 @property
2217 def name(self):
Daniel Dunbar4efd6322010-01-25 00:43:08 +00002218 """Return the complete file and path name of the file."""
Gregory Szorc9537e202012-07-12 04:56:46 +00002219 return lib.clang_getCString(lib.clang_getFileName(self))
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002220
2221 @property
2222 def time(self):
Daniel Dunbar4efd6322010-01-25 00:43:08 +00002223 """Return the last modification time of the file."""
Gregory Szorc9537e202012-07-12 04:56:46 +00002224 return lib.clang_getFileTime(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002225
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002226 def __str__(self):
2227 return self.name
2228
2229 def __repr__(self):
2230 return "<File: %s>" % (self.name)
2231
Gregory Szorc9537e202012-07-12 04:56:46 +00002232 @staticmethod
2233 def from_cursor_result(res, fn, args):
2234 assert isinstance(res, File)
2235
2236 # Copy a reference to the TranslationUnit to prevent premature GC.
2237 res._tu = args[0]._tu
2238 return res
2239
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002240class FileInclusion(object):
2241 """
2242 The FileInclusion class represents the inclusion of one source file by
2243 another via a '#include' directive or as the input file for the translation
2244 unit. This class provides information about the included file, the including
2245 file, the location of the '#include' directive and the depth of the included
2246 file in the stack. Note that the input file has depth 0.
2247 """
2248
2249 def __init__(self, src, tgt, loc, depth):
2250 self.source = src
2251 self.include = tgt
2252 self.location = loc
2253 self.depth = depth
2254
2255 @property
2256 def is_input_file(self):
2257 """True if the included file is the input file."""
2258 return self.depth == 0
2259
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002260class CompilationDatabaseError(Exception):
2261 """Represents an error that occurred when working with a CompilationDatabase
2262
2263 Each error is associated to an enumerated value, accessible under
2264 e.cdb_error. Consumers can compare the value with one of the ERROR_
2265 constants in this class.
2266 """
2267
2268 # An unknown error occured
2269 ERROR_UNKNOWN = 0
2270
2271 # The database could not be loaded
2272 ERROR_CANNOTLOADDATABASE = 1
2273
2274 def __init__(self, enumeration, message):
2275 assert isinstance(enumeration, int)
2276
2277 if enumeration > 1:
2278 raise Exception("Encountered undefined CompilationDatabase error "
2279 "constant: %d. Please file a bug to have this "
2280 "value supported." % enumeration)
2281
2282 self.cdb_error = enumeration
2283 Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
2284
2285class CompileCommand(object):
2286 """Represents the compile command used to build a file"""
2287 def __init__(self, cmd, ccmds):
2288 self.cmd = cmd
2289 # Keep a reference to the originating CompileCommands
2290 # to prevent garbage collection
2291 self.ccmds = ccmds
2292
2293 @property
2294 def directory(self):
2295 """Get the working directory for this CompileCommand"""
Gregory Szorc9537e202012-07-12 04:56:46 +00002296 return lib.clang_CompileCommand_getDirectory(self.cmd)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002297
2298 @property
2299 def arguments(self):
2300 """
2301 Get an iterable object providing each argument in the
2302 command line for the compiler invocation as a _CXString.
2303
Arnaud A. de Grandmaison577c5302012-07-06 08:22:05 +00002304 Invariant : the first argument is the compiler executable
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002305 """
Gregory Szorc9537e202012-07-12 04:56:46 +00002306 length = lib.clang_CompileCommand_getNumArgs(self.cmd)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002307 for i in xrange(length):
Gregory Szorc9537e202012-07-12 04:56:46 +00002308 yield lib.clang_CompileCommand_getArg(self.cmd, i)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002309
2310class CompileCommands(object):
2311 """
2312 CompileCommands is an iterable object containing all CompileCommand
2313 that can be used for building a specific file.
2314 """
2315 def __init__(self, ccmds):
2316 self.ccmds = ccmds
2317
2318 def __del__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00002319 lib.clang_CompileCommands_dispose(self.ccmds)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002320
2321 def __len__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00002322 return int(lib.clang_CompileCommands_getSize(self.ccmds))
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002323
2324 def __getitem__(self, i):
Gregory Szorc9537e202012-07-12 04:56:46 +00002325 cc = lib.clang_CompileCommands_getCommand(self.ccmds, i)
Arnaud A. de Grandmaisonb1614042012-07-09 11:57:30 +00002326 if not cc:
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002327 raise IndexError
2328 return CompileCommand(cc, self)
2329
2330 @staticmethod
2331 def from_result(res, fn, args):
2332 if not res:
2333 return None
2334 return CompileCommands(res)
2335
2336class CompilationDatabase(ClangObject):
2337 """
2338 The CompilationDatabase is a wrapper class around
2339 clang::tooling::CompilationDatabase
2340
2341 It enables querying how a specific source file can be built.
2342 """
2343
2344 def __del__(self):
Gregory Szorc9537e202012-07-12 04:56:46 +00002345 lib.clang_CompilationDatabase_dispose(self)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002346
2347 @staticmethod
2348 def from_result(res, fn, args):
2349 if not res:
2350 raise CompilationDatabaseError(0,
2351 "CompilationDatabase loading failed")
2352 return CompilationDatabase(res)
2353
2354 @staticmethod
2355 def fromDirectory(buildDir):
2356 """Builds a CompilationDatabase from the database found in buildDir"""
2357 errorCode = c_uint()
2358 try:
Gregory Szorc9537e202012-07-12 04:56:46 +00002359 cdb = lib.clang_CompilationDatabase_fromDirectory(buildDir,
2360 byref(errorCode))
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002361 except CompilationDatabaseError as e:
Gregory Szorc9537e202012-07-12 04:56:46 +00002362 raise CompilationDatabaseError(int(errorCode.value),
2363 "CompilationDatabase loading failed")
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002364 return cdb
2365
2366 def getCompileCommands(self, filename):
2367 """
2368 Get an iterable object providing all the CompileCommands available to
Arnaud A. de Grandmaison44394782012-06-30 20:43:37 +00002369 build filename. Returns None if filename is not found in the database.
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002370 """
Gregory Szorc9537e202012-07-12 04:56:46 +00002371 return lib.clang_CompilationDatabase_getCompileCommands(self, filename)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002372
Gregory Szorcbe51e432012-07-12 07:21:12 +00002373class Token(Structure):
2374 """Represents a single token from the preprocessor.
2375
2376 Tokens are effectively segments of source code. Source code is first parsed
2377 into tokens before being converted into the AST and Cursors.
2378
2379 Tokens are obtained from parsed TranslationUnit instances. You currently
2380 can't create tokens manually.
2381 """
2382 _fields_ = [
2383 ('int_data', c_uint * 4),
2384 ('ptr_data', c_void_p)
2385 ]
2386
2387 @property
2388 def spelling(self):
2389 """The spelling of this token.
2390
2391 This is the textual representation of the token in source.
2392 """
2393 return lib.clang_getTokenSpelling(self._tu, self)
2394
2395 @property
2396 def kind(self):
2397 """Obtain the TokenKind of the current token."""
2398 return TokenKind.from_value(lib.clang_getTokenKind(self))
2399
2400 @property
2401 def location(self):
2402 """The SourceLocation this Token occurs at."""
2403 return lib.clang_getTokenLocation(self._tu, self)
2404
2405 @property
2406 def extent(self):
2407 """The SourceRange this Token occupies."""
2408 return lib.clang_getTokenExtent(self._tu, self)
2409
2410 @property
2411 def cursor(self):
2412 """The Cursor this Token corresponds to."""
2413 cursor = Cursor()
2414
2415 lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
2416
2417 return cursor
2418
Gregory Szorc9537e202012-07-12 04:56:46 +00002419# Now comes the plumbing to hook up the C library.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002420
Gregory Szorc9537e202012-07-12 04:56:46 +00002421# Register callback types in common container.
2422callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p,
2423 POINTER(SourceLocation), c_uint, py_object)
2424callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
Daniel Dunbara33dca42010-01-24 21:19:57 +00002425
Gregory Szorc9537e202012-07-12 04:56:46 +00002426def register_functions(lib):
2427 """Register function prototypes with a libclang library instance.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002428
Gregory Szorc9537e202012-07-12 04:56:46 +00002429 This must be called as part of library instantiation so Python knows how
2430 to call out to the shared library.
2431 """
2432 # Functions are registered in strictly alphabetical order.
Gregory Szorcbe51e432012-07-12 07:21:12 +00002433 lib.clang_annotateTokens.argtype = [TranslationUnit, POINTER(Token),
2434 c_uint, POINTER(Cursor)]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002435
Gregory Szorc9537e202012-07-12 04:56:46 +00002436 lib.clang_CompilationDatabase_dispose.argtypes = [c_object_p]
Tobias Grosser58ba8c92011-10-31 00:31:32 +00002437
Gregory Szorc9537e202012-07-12 04:56:46 +00002438 lib.clang_CompilationDatabase_fromDirectory.argtypes = [c_char_p,
2439 POINTER(c_uint)]
2440 lib.clang_CompilationDatabase_fromDirectory.restype = c_object_p
2441 lib.clang_CompilationDatabase_fromDirectory.errcheck = CompilationDatabase.from_result
Tobias Grosser74858332012-02-05 11:40:59 +00002442
Gregory Szorc9537e202012-07-12 04:56:46 +00002443 lib.clang_CompilationDatabase_getCompileCommands.argtypes = [c_object_p, c_char_p]
2444 lib.clang_CompilationDatabase_getCompileCommands.restype = c_object_p
2445 lib.clang_CompilationDatabase_getCompileCommands.errcheck = CompileCommands.from_result
Gregory Szorc74bb7102012-06-11 11:11:48 +00002446
Gregory Szorc9537e202012-07-12 04:56:46 +00002447 lib.clang_CompileCommands_dispose.argtypes = [c_object_p]
Daniel Dunbar532fc632010-01-30 23:59:02 +00002448
Gregory Szorc9537e202012-07-12 04:56:46 +00002449 lib.clang_CompileCommands_getCommand.argtypes = [c_object_p, c_uint]
2450 lib.clang_CompileCommands_getCommand.restype = c_object_p
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002451
Gregory Szorc9537e202012-07-12 04:56:46 +00002452 lib.clang_CompileCommands_getSize.argtypes = [c_object_p]
2453 lib.clang_CompileCommands_getSize.restype = c_uint
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002454
Gregory Szorc9537e202012-07-12 04:56:46 +00002455 lib.clang_CompileCommand_getArg.argtypes = [c_object_p, c_uint]
2456 lib.clang_CompileCommand_getArg.restype = _CXString
2457 lib.clang_CompileCommand_getArg.errcheck = _CXString.from_result
Tobias Grosser74858332012-02-05 11:40:59 +00002458
Gregory Szorc9537e202012-07-12 04:56:46 +00002459 lib.clang_CompileCommand_getDirectory.argtypes = [c_object_p]
2460 lib.clang_CompileCommand_getDirectory.restype = _CXString
2461 lib.clang_CompileCommand_getDirectory.errcheck = _CXString.from_result
Daniel Dunbara6a64992010-01-24 21:20:39 +00002462
Gregory Szorc9537e202012-07-12 04:56:46 +00002463 lib.clang_CompileCommand_getNumArgs.argtypes = [c_object_p]
2464 lib.clang_CompileCommand_getNumArgs.restype = c_uint
Daniel Dunbara6a64992010-01-24 21:20:39 +00002465
Gregory Szorc9537e202012-07-12 04:56:46 +00002466 lib.clang_codeCompleteAt.argtypes = [TranslationUnit, c_char_p, c_int,
2467 c_int, c_void_p, c_int, c_int]
2468 lib.clang_codeCompleteAt.restype = POINTER(CCRStructure)
Daniel Dunbara6a64992010-01-24 21:20:39 +00002469
Gregory Szorc9537e202012-07-12 04:56:46 +00002470 lib.clang_codeCompleteGetDiagnostic.argtypes = [CodeCompletionResults,
2471 c_int]
2472 lib.clang_codeCompleteGetDiagnostic.restype = Diagnostic
Daniel Dunbara6a64992010-01-24 21:20:39 +00002473
Gregory Szorc9537e202012-07-12 04:56:46 +00002474 lib.clang_codeCompleteGetNumDiagnostics.argtypes = [CodeCompletionResults]
2475 lib.clang_codeCompleteGetNumDiagnostics.restype = c_int
Douglas Gregor8be80e12011-07-06 03:00:34 +00002476
Gregory Szorc9537e202012-07-12 04:56:46 +00002477 lib.clang_createIndex.argtypes = [c_int, c_int]
2478 lib.clang_createIndex.restype = c_object_p
Daniel Dunbara6a64992010-01-24 21:20:39 +00002479
Gregory Szorc9537e202012-07-12 04:56:46 +00002480 lib.clang_createTranslationUnit.argtypes = [Index, c_char_p]
2481 lib.clang_createTranslationUnit.restype = c_object_p
Tobias Grossereb136342012-02-05 11:42:09 +00002482
Gregory Szorc9537e202012-07-12 04:56:46 +00002483 lib.clang_CXXMethod_isStatic.argtypes = [Cursor]
2484 lib.clang_CXXMethod_isStatic.restype = bool
Tobias Grossereb136342012-02-05 11:42:09 +00002485
Gregory Szorc9537e202012-07-12 04:56:46 +00002486 lib.clang_CXXMethod_isVirtual.argtypes = [Cursor]
2487 lib.clang_CXXMethod_isVirtual.restype = bool
Tobias Grossereb136342012-02-05 11:42:09 +00002488
Gregory Szorc9537e202012-07-12 04:56:46 +00002489 lib.clang_defaultSaveOptions.argtypes = [TranslationUnit]
2490 lib.clang_defaultSaveOptions.restype = c_uint
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002491
Gregory Szorc9537e202012-07-12 04:56:46 +00002492 lib.clang_disposeCodeCompleteResults.argtypes = [CodeCompletionResults]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002493
Gregory Szorc9537e202012-07-12 04:56:46 +00002494 #lib.clang_disposeCXTUResourceUsage.argtypes = [CXTUResourceUsage]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002495
Gregory Szorc9537e202012-07-12 04:56:46 +00002496 lib.clang_disposeDiagnostic.argtypes = [Diagnostic]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002497
Gregory Szorc9537e202012-07-12 04:56:46 +00002498 lib.clang_disposeIndex.argtypes = [Index]
Gregory Szorce65b34d2012-06-09 16:21:34 +00002499
Gregory Szorc9537e202012-07-12 04:56:46 +00002500 lib.clang_disposeString.argtypes = [_CXString]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002501
Gregory Szorcbe51e432012-07-12 07:21:12 +00002502 lib.clang_disposeTokens.argtype = [TranslationUnit, POINTER(Token), c_uint]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002503
Gregory Szorc9537e202012-07-12 04:56:46 +00002504 lib.clang_disposeTranslationUnit.argtypes = [TranslationUnit]
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00002505
Gregory Szorc9537e202012-07-12 04:56:46 +00002506 lib.clang_equalCursors.argtypes = [Cursor, Cursor]
2507 lib.clang_equalCursors.restype = bool
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002508
Gregory Szorc9537e202012-07-12 04:56:46 +00002509 lib.clang_equalLocations.argtypes = [SourceLocation, SourceLocation]
2510 lib.clang_equalLocations.restype = bool
Douglas Gregor8be80e12011-07-06 03:00:34 +00002511
Gregory Szorc9537e202012-07-12 04:56:46 +00002512 lib.clang_equalRanges.argtypes = [SourceRange, SourceRange]
2513 lib.clang_equalRanges.restype = bool
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002514
Gregory Szorc9537e202012-07-12 04:56:46 +00002515 lib.clang_equalTypes.argtypes = [Type, Type]
2516 lib.clang_equalTypes.restype = bool
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002517
Gregory Szorc9537e202012-07-12 04:56:46 +00002518 lib.clang_getArgType.argtypes = [Type, c_uint]
2519 lib.clang_getArgType.restype = Type
2520 lib.clang_getArgType.errcheck = Type.from_result
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002521
Gregory Szorc9537e202012-07-12 04:56:46 +00002522 lib.clang_getArrayElementType.argtypes = [Type]
2523 lib.clang_getArrayElementType.restype = Type
2524 lib.clang_getArrayElementType.errcheck = Type.from_result
Gregory Szorc2c408352012-05-14 03:56:33 +00002525
Gregory Szorc9537e202012-07-12 04:56:46 +00002526 lib.clang_getArraySize.argtypes = [Type]
2527 lib.clang_getArraySize.restype = c_longlong
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002528
Gregory Szorc9537e202012-07-12 04:56:46 +00002529 lib.clang_getCanonicalCursor.argtypes = [Cursor]
2530 lib.clang_getCanonicalCursor.restype = Cursor
2531 lib.clang_getCanonicalCursor.errcheck = Cursor.from_cursor_result
2532
2533 lib.clang_getCanonicalType.argtypes = [Type]
2534 lib.clang_getCanonicalType.restype = Type
2535 lib.clang_getCanonicalType.errcheck = Type.from_result
2536
2537 lib.clang_getCompletionAvailability.argtypes = [c_void_p]
2538 lib.clang_getCompletionAvailability.restype = c_int
2539
2540 lib.clang_getCompletionChunkCompletionString.argtypes = [c_void_p, c_int]
2541 lib.clang_getCompletionChunkCompletionString.restype = c_object_p
2542
2543 lib.clang_getCompletionChunkKind.argtypes = [c_void_p, c_int]
2544 lib.clang_getCompletionChunkKind.restype = c_int
2545
2546 lib.clang_getCompletionChunkText.argtypes = [c_void_p, c_int]
2547 lib.clang_getCompletionChunkText.restype = _CXString
2548
2549 lib.clang_getCompletionPriority.argtypes = [c_void_p]
2550 lib.clang_getCompletionPriority.restype = c_int
2551
2552 lib.clang_getCString.argtypes = [_CXString]
2553 lib.clang_getCString.restype = c_char_p
2554
2555 lib.clang_getCursor.argtypes = [TranslationUnit, SourceLocation]
2556 lib.clang_getCursor.restype = Cursor
2557
2558 lib.clang_getCursorDefinition.argtypes = [Cursor]
2559 lib.clang_getCursorDefinition.restype = Cursor
2560 lib.clang_getCursorDefinition.errcheck = Cursor.from_result
2561
2562 lib.clang_getCursorDisplayName.argtypes = [Cursor]
2563 lib.clang_getCursorDisplayName.restype = _CXString
2564 lib.clang_getCursorDisplayName.errcheck = _CXString.from_result
2565
2566 lib.clang_getCursorExtent.argtypes = [Cursor]
2567 lib.clang_getCursorExtent.restype = SourceRange
2568
2569 lib.clang_getCursorLexicalParent.argtypes = [Cursor]
2570 lib.clang_getCursorLexicalParent.restype = Cursor
2571 lib.clang_getCursorLexicalParent.errcheck = Cursor.from_cursor_result
2572
2573 lib.clang_getCursorLocation.argtypes = [Cursor]
2574 lib.clang_getCursorLocation.restype = SourceLocation
2575
2576 lib.clang_getCursorReferenced.argtypes = [Cursor]
2577 lib.clang_getCursorReferenced.restype = Cursor
2578 lib.clang_getCursorReferenced.errcheck = Cursor.from_result
2579
2580 lib.clang_getCursorReferenceNameRange.argtypes = [Cursor, c_uint, c_uint]
2581 lib.clang_getCursorReferenceNameRange.restype = SourceRange
2582
2583 lib.clang_getCursorSemanticParent.argtypes = [Cursor]
2584 lib.clang_getCursorSemanticParent.restype = Cursor
2585 lib.clang_getCursorSemanticParent.errcheck = Cursor.from_cursor_result
2586
2587 lib.clang_getCursorSpelling.argtypes = [Cursor]
2588 lib.clang_getCursorSpelling.restype = _CXString
2589 lib.clang_getCursorSpelling.errcheck = _CXString.from_result
2590
2591 lib.clang_getCursorType.argtypes = [Cursor]
2592 lib.clang_getCursorType.restype = Type
2593 lib.clang_getCursorType.errcheck = Type.from_result
2594
2595 lib.clang_getCursorUSR.argtypes = [Cursor]
2596 lib.clang_getCursorUSR.restype = _CXString
2597 lib.clang_getCursorUSR.errcheck = _CXString.from_result
2598
2599 #lib.clang_getCXTUResourceUsage.argtypes = [TranslationUnit]
2600 #lib.clang_getCXTUResourceUsage.restype = CXTUResourceUsage
2601
2602 lib.clang_getCXXAccessSpecifier.argtypes = [Cursor]
2603 lib.clang_getCXXAccessSpecifier.restype = c_uint
2604
2605 lib.clang_getDeclObjCTypeEncoding.argtypes = [Cursor]
2606 lib.clang_getDeclObjCTypeEncoding.restype = _CXString
2607 lib.clang_getDeclObjCTypeEncoding.errcheck = _CXString.from_result
2608
2609 lib.clang_getDiagnostic.argtypes = [c_object_p, c_uint]
2610 lib.clang_getDiagnostic.restype = c_object_p
2611
2612 lib.clang_getDiagnosticCategory.argtypes = [Diagnostic]
2613 lib.clang_getDiagnosticCategory.restype = c_uint
2614
2615 lib.clang_getDiagnosticCategoryName.argtypes = [c_uint]
2616 lib.clang_getDiagnosticCategoryName.restype = _CXString
2617 lib.clang_getDiagnosticCategoryName.errcheck = _CXString.from_result
2618
2619 lib.clang_getDiagnosticFixIt.argtypes = [Diagnostic, c_uint,
2620 POINTER(SourceRange)]
2621 lib.clang_getDiagnosticFixIt.restype = _CXString
2622 lib.clang_getDiagnosticFixIt.errcheck = _CXString.from_result
2623
2624 lib.clang_getDiagnosticLocation.argtypes = [Diagnostic]
2625 lib.clang_getDiagnosticLocation.restype = SourceLocation
2626
2627 lib.clang_getDiagnosticNumFixIts.argtypes = [Diagnostic]
2628 lib.clang_getDiagnosticNumFixIts.restype = c_uint
2629
2630 lib.clang_getDiagnosticNumRanges.argtypes = [Diagnostic]
2631 lib.clang_getDiagnosticNumRanges.restype = c_uint
2632
2633 lib.clang_getDiagnosticOption.argtypes = [Diagnostic, POINTER(_CXString)]
2634 lib.clang_getDiagnosticOption.restype = _CXString
2635 lib.clang_getDiagnosticOption.errcheck = _CXString.from_result
2636
2637 lib.clang_getDiagnosticRange.argtypes = [Diagnostic, c_uint]
2638 lib.clang_getDiagnosticRange.restype = SourceRange
2639
2640 lib.clang_getDiagnosticSeverity.argtypes = [Diagnostic]
2641 lib.clang_getDiagnosticSeverity.restype = c_int
2642
2643 lib.clang_getDiagnosticSpelling.argtypes = [Diagnostic]
2644 lib.clang_getDiagnosticSpelling.restype = _CXString
2645 lib.clang_getDiagnosticSpelling.errcheck = _CXString.from_result
2646
2647 lib.clang_getElementType.argtypes = [Type]
2648 lib.clang_getElementType.restype = Type
2649 lib.clang_getElementType.errcheck = Type.from_result
2650
2651 lib.clang_getEnumConstantDeclUnsignedValue.argtypes = [Cursor]
2652 lib.clang_getEnumConstantDeclUnsignedValue.restype = c_ulonglong
2653
2654 lib.clang_getEnumConstantDeclValue.argtypes = [Cursor]
2655 lib.clang_getEnumConstantDeclValue.restype = c_longlong
2656
2657 lib.clang_getEnumDeclIntegerType.argtypes = [Cursor]
2658 lib.clang_getEnumDeclIntegerType.restype = Type
2659 lib.clang_getEnumDeclIntegerType.errcheck = Type.from_result
Tobias Grosser28d939f2012-02-05 11:42:20 +00002660
Gregory Szorc9537e202012-07-12 04:56:46 +00002661 lib.clang_getFile.argtypes = [TranslationUnit, c_char_p]
2662 lib.clang_getFile.restype = c_object_p
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00002663
Gregory Szorc9537e202012-07-12 04:56:46 +00002664 lib.clang_getFileName.argtypes = [File]
2665 lib.clang_getFileName.restype = _CXString
2666 # TODO go through _CXString.from_result?
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00002667
Gregory Szorc9537e202012-07-12 04:56:46 +00002668 lib.clang_getFileTime.argtypes = [File]
2669 lib.clang_getFileTime.restype = c_uint
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00002670
Gregory Szorc9537e202012-07-12 04:56:46 +00002671 lib.clang_getIBOutletCollectionType.argtypes = [Cursor]
2672 lib.clang_getIBOutletCollectionType.restype = Type
2673 lib.clang_getIBOutletCollectionType.errcheck = Type.from_result
Gregory Szorc5cc67872012-03-10 22:23:27 +00002674
Gregory Szorc9537e202012-07-12 04:56:46 +00002675 lib.clang_getIncludedFile.argtypes = [Cursor]
2676 lib.clang_getIncludedFile.restype = File
2677 lib.clang_getIncludedFile.errcheck = File.from_cursor_result
Manuel Klimek667fd802012-05-07 05:56:03 +00002678
Gregory Szorc9537e202012-07-12 04:56:46 +00002679 lib.clang_getInclusions.argtypes = [TranslationUnit,
2680 callbacks['translation_unit_includes'], py_object]
Manuel Klimek667fd802012-05-07 05:56:03 +00002681
Gregory Szorc9537e202012-07-12 04:56:46 +00002682 lib.clang_getInstantiationLocation.argtypes = [SourceLocation,
2683 POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint), POINTER(c_uint)]
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00002684
Gregory Szorc9537e202012-07-12 04:56:46 +00002685 lib.clang_getLocation.argtypes = [TranslationUnit, File, c_uint, c_uint]
2686 lib.clang_getLocation.restype = SourceLocation
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002687
Gregory Szorc9537e202012-07-12 04:56:46 +00002688 lib.clang_getLocationForOffset.argtypes = [TranslationUnit, File, c_uint]
2689 lib.clang_getLocationForOffset.restype = SourceLocation
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002690
Gregory Szorc9537e202012-07-12 04:56:46 +00002691 lib.clang_getNullCursor.restype = Cursor
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002692
Gregory Szorc9537e202012-07-12 04:56:46 +00002693 lib.clang_getNumArgTypes.argtypes = [Type]
2694 lib.clang_getNumArgTypes.restype = c_uint
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002695
Gregory Szorc9537e202012-07-12 04:56:46 +00002696 lib.clang_getNumCompletionChunks.argtypes = [c_void_p]
2697 lib.clang_getNumCompletionChunks.restype = c_int
Gregory Szorc96ad6332012-02-05 19:42:06 +00002698
Gregory Szorc9537e202012-07-12 04:56:46 +00002699 lib.clang_getNumDiagnostics.argtypes = [c_object_p]
2700 lib.clang_getNumDiagnostics.restype = c_uint
Gregory Szorc31cc38c2012-02-19 18:28:33 +00002701
Gregory Szorc9537e202012-07-12 04:56:46 +00002702 lib.clang_getNumElements.argtypes = [Type]
2703 lib.clang_getNumElements.restype = c_longlong
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002704
Gregory Szorc9537e202012-07-12 04:56:46 +00002705 lib.clang_getNumOverloadedDecls.argtypes = [Cursor]
2706 lib.clang_getNumOverloadedDecls.restyp = c_uint
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002707
Gregory Szorc9537e202012-07-12 04:56:46 +00002708 lib.clang_getOverloadedDecl.argtypes = [Cursor, c_uint]
2709 lib.clang_getOverloadedDecl.restype = Cursor
2710 lib.clang_getOverloadedDecl.errcheck = Cursor.from_cursor_result
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002711
Gregory Szorc9537e202012-07-12 04:56:46 +00002712 lib.clang_getPointeeType.argtypes = [Type]
2713 lib.clang_getPointeeType.restype = Type
2714 lib.clang_getPointeeType.errcheck = Type.from_result
Gregory Szorc826fce52012-02-20 17:45:30 +00002715
Gregory Szorc9537e202012-07-12 04:56:46 +00002716 lib.clang_getRange.argtypes = [SourceLocation, SourceLocation]
2717 lib.clang_getRange.restype = SourceRange
Gregory Szorc826fce52012-02-20 17:45:30 +00002718
Gregory Szorc9537e202012-07-12 04:56:46 +00002719 lib.clang_getRangeEnd.argtypes = [SourceRange]
2720 lib.clang_getRangeEnd.restype = SourceLocation
Gregory Szorc86057602012-02-17 07:44:46 +00002721
Gregory Szorc9537e202012-07-12 04:56:46 +00002722 lib.clang_getRangeStart.argtypes = [SourceRange]
2723 lib.clang_getRangeStart.restype = SourceLocation
Gregory Szorcbf8ca002012-02-17 07:47:38 +00002724
Gregory Szorc9537e202012-07-12 04:56:46 +00002725 lib.clang_getResultType.argtypes = [Type]
2726 lib.clang_getResultType.restype = Type
2727 lib.clang_getResultType.errcheck = Type.from_result
Douglas Gregor13102ff2011-10-19 05:51:43 +00002728
Gregory Szorc9537e202012-07-12 04:56:46 +00002729 lib.clang_getSpecializedCursorTemplate.argtypes = [Cursor]
2730 lib.clang_getSpecializedCursorTemplate.restype = Cursor
2731 lib.clang_getSpecializedCursorTemplate.errcheck = Cursor.from_cursor_result
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00002732
Gregory Szorc9537e202012-07-12 04:56:46 +00002733 lib.clang_getTemplateCursorKind.argtypes = [Cursor]
2734 lib.clang_getTemplateCursorKind.restype = c_uint
Gregory Szorc7eb691a2012-02-20 17:44:49 +00002735
Gregory Szorcbe51e432012-07-12 07:21:12 +00002736 lib.clang_getTokenExtent.argtypes = [TranslationUnit, Token]
2737 lib.clang_getTokenExtent.restype = SourceRange
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002738
Gregory Szorcbe51e432012-07-12 07:21:12 +00002739 lib.clang_getTokenKind.argtypes = [Token]
2740 lib.clang_getTokenKind.restype = c_uint
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002741
Gregory Szorcbe51e432012-07-12 07:21:12 +00002742 lib.clang_getTokenLocation.argtype = [TranslationUnit, Token]
2743 lib.clang_getTokenLocation.restype = SourceLocation
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002744
Gregory Szorcbe51e432012-07-12 07:21:12 +00002745 lib.clang_getTokenSpelling.argtype = [TranslationUnit, Token]
2746 lib.clang_getTokenSpelling.restype = _CXString
2747 lib.clang_getTokenSpelling.errcheck = _CXString.from_result
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002748
Gregory Szorc9537e202012-07-12 04:56:46 +00002749 lib.clang_getTranslationUnitCursor.argtypes = [TranslationUnit]
2750 lib.clang_getTranslationUnitCursor.restype = Cursor
2751 lib.clang_getTranslationUnitCursor.errcheck = Cursor.from_result
Tobias Grosser265e6b22011-02-05 17:54:00 +00002752
Gregory Szorc9537e202012-07-12 04:56:46 +00002753 lib.clang_getTranslationUnitSpelling.argtypes = [TranslationUnit]
2754 lib.clang_getTranslationUnitSpelling.restype = _CXString
2755 lib.clang_getTranslationUnitSpelling.errcheck = _CXString.from_result
Tobias Grosser0a166802011-02-05 17:54:04 +00002756
Gregory Szorc9537e202012-07-12 04:56:46 +00002757 lib.clang_getTUResourceUsageName.argtypes = [c_uint]
2758 lib.clang_getTUResourceUsageName.restype = c_char_p
Daniel Dunbar1b945a72010-01-24 04:09:43 +00002759
Gregory Szorc9537e202012-07-12 04:56:46 +00002760 lib.clang_getTypeDeclaration.argtypes = [Type]
2761 lib.clang_getTypeDeclaration.restype = Cursor
2762 lib.clang_getTypeDeclaration.errcheck = Cursor.from_result
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002763
Gregory Szorc9537e202012-07-12 04:56:46 +00002764 lib.clang_getTypedefDeclUnderlyingType.argtypes = [Cursor]
2765 lib.clang_getTypedefDeclUnderlyingType.restype = Type
2766 lib.clang_getTypedefDeclUnderlyingType.errcheck = Type.from_result
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002767
Gregory Szorc9537e202012-07-12 04:56:46 +00002768 lib.clang_getTypeKindSpelling.argtypes = [c_uint]
2769 lib.clang_getTypeKindSpelling.restype = _CXString
2770 lib.clang_getTypeKindSpelling.errcheck = _CXString.from_result
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002771
Gregory Szorc9537e202012-07-12 04:56:46 +00002772 lib.clang_hashCursor.argtypes = [Cursor]
2773 lib.clang_hashCursor.restype = c_uint
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002774
Gregory Szorc9537e202012-07-12 04:56:46 +00002775 lib.clang_isAttribute.argtypes = [CursorKind]
2776 lib.clang_isAttribute.restype = bool
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002777
Gregory Szorc9537e202012-07-12 04:56:46 +00002778 lib.clang_isConstQualifiedType.argtypes = [Type]
2779 lib.clang_isConstQualifiedType.restype = bool
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002780
Gregory Szorc9537e202012-07-12 04:56:46 +00002781 lib.clang_isCursorDefinition.argtypes = [Cursor]
2782 lib.clang_isCursorDefinition.restype = bool
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002783
Gregory Szorc9537e202012-07-12 04:56:46 +00002784 lib.clang_isDeclaration.argtypes = [CursorKind]
2785 lib.clang_isDeclaration.restype = bool
Daniel Dunbar4efd6322010-01-25 00:43:08 +00002786
Gregory Szorc9537e202012-07-12 04:56:46 +00002787 lib.clang_isExpression.argtypes = [CursorKind]
2788 lib.clang_isExpression.restype = bool
Tobias Grosser0a166802011-02-05 17:54:04 +00002789
Gregory Szorc9537e202012-07-12 04:56:46 +00002790 lib.clang_isFileMultipleIncludeGuarded.argtypes = [TranslationUnit, File]
2791 lib.clang_isFileMultipleIncludeGuarded.restype = bool
Tobias Grosser0a166802011-02-05 17:54:04 +00002792
Gregory Szorc9537e202012-07-12 04:56:46 +00002793 lib.clang_isFunctionTypeVariadic.argtypes = [Type]
2794 lib.clang_isFunctionTypeVariadic.restype = bool
Tobias Grosser0a166802011-02-05 17:54:04 +00002795
Gregory Szorc9537e202012-07-12 04:56:46 +00002796 lib.clang_isInvalid.argtypes = [CursorKind]
2797 lib.clang_isInvalid.restype = bool
Tobias Grosser0a166802011-02-05 17:54:04 +00002798
Gregory Szorc9537e202012-07-12 04:56:46 +00002799 lib.clang_isPODType.argtypes = [Type]
2800 lib.clang_isPODType.restype = bool
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002801
Gregory Szorc9537e202012-07-12 04:56:46 +00002802 lib.clang_isPreprocessing.argtypes = [CursorKind]
2803 lib.clang_isPreprocessing.restype = bool
Tobias Grossera87dbcc2011-02-05 17:54:10 +00002804
Gregory Szorc9537e202012-07-12 04:56:46 +00002805 lib.clang_isReference.argtypes = [CursorKind]
2806 lib.clang_isReference.restype = bool
Tobias Grossera87dbcc2011-02-05 17:54:10 +00002807
Gregory Szorc9537e202012-07-12 04:56:46 +00002808 lib.clang_isRestrictQualifiedType.argtypes = [Type]
2809 lib.clang_isRestrictQualifiedType.restype = bool
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002810
Gregory Szorc9537e202012-07-12 04:56:46 +00002811 lib.clang_isStatement.argtypes = [CursorKind]
2812 lib.clang_isStatement.restype = bool
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002813
Gregory Szorc9537e202012-07-12 04:56:46 +00002814 lib.clang_isTranslationUnit.argtypes = [CursorKind]
2815 lib.clang_isTranslationUnit.restype = bool
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002816
Gregory Szorc9537e202012-07-12 04:56:46 +00002817 lib.clang_isUnexposed.argtypes = [CursorKind]
2818 lib.clang_isUnexposed.restype = bool
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002819
Gregory Szorc9537e202012-07-12 04:56:46 +00002820 lib.clang_isVirtualBase.argtypes = [Cursor]
2821 lib.clang_isVirtualBase.restype = bool
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002822
Gregory Szorc9537e202012-07-12 04:56:46 +00002823 lib.clang_isVolatileQualifiedType.argtypes = [Type]
2824 lib.clang_isVolatileQualifiedType.restype = bool
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002825
Gregory Szorc9537e202012-07-12 04:56:46 +00002826 lib.clang_parseTranslationUnit.argypes = [Index, c_char_p, c_void_p, c_int,
2827 c_void_p, c_int, c_int]
2828 lib.clang_parseTranslationUnit.restype = c_object_p
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002829
Gregory Szorc9537e202012-07-12 04:56:46 +00002830 lib.clang_reparseTranslationUnit.argtypes = [TranslationUnit, c_int,
2831 c_void_p, c_int]
2832 lib.clang_reparseTranslationUnit.restype = c_int
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002833
Gregory Szorc9537e202012-07-12 04:56:46 +00002834 lib.clang_saveTranslationUnit.argtypes = [TranslationUnit, c_char_p,
2835 c_uint]
2836 lib.clang_saveTranslationUnit.restype = c_int
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002837
Gregory Szorcbe51e432012-07-12 07:21:12 +00002838 lib.clang_tokenize.argtypes = [TranslationUnit, SourceRange,
2839 POINTER(POINTER(Token)), POINTER(c_uint)]
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002840
Gregory Szorc9537e202012-07-12 04:56:46 +00002841 lib.clang_visitChildren.argtypes = [Cursor, callbacks['cursor_visit'],
2842 py_object]
2843 lib.clang_visitChildren.restype = c_uint
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002844
Gregory Szorc9537e202012-07-12 04:56:46 +00002845register_functions(lib)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002846
Gregory Szorcbe51e432012-07-12 07:21:12 +00002847def register_enumerations():
2848 for name, value in clang.enumerations.TokenKinds:
2849 TokenKind.register(value, name)
2850
2851register_enumerations()
2852
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002853__all__ = [
2854 'CodeCompletionResults',
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002855 'CompilationDatabase',
2856 'CompileCommands',
2857 'CompileCommand',
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002858 'CursorKind',
2859 'Cursor',
2860 'Diagnostic',
2861 'File',
2862 'FixIt',
2863 'Index',
2864 'SourceLocation',
2865 'SourceRange',
Gregory Szorcbe51e432012-07-12 07:21:12 +00002866 'TokenKind',
2867 'Token',
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002868 'TranslationUnitLoadError',
2869 'TranslationUnit',
2870 'TypeKind',
2871 'Type',
2872]