blob: b673f4b5777df938d9cb312019e3d6a9bed1ee87 [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 +000070# ctypes doesn't implicitly convert c_void_p to the appropriate wrapper
71# object. This is a problem, because it means that from_parameter will see an
72# integer and pass the wrong value on platforms where int != void*. Work around
73# this by marshalling object arguments as void**.
74c_object_p = POINTER(c_void_p)
75
Gregory Szorc9537e202012-07-12 04:56:46 +000076callbacks = {}
Daniel Dunbar30c0f262010-01-24 02:02:07 +000077
Gregory Szorcfbf620b2012-05-08 05:56:38 +000078### Exception Classes ###
79
80class TranslationUnitLoadError(Exception):
81 """Represents an error that occurred when loading a TranslationUnit.
82
83 This is raised in the case where a TranslationUnit could not be
84 instantiated due to failure in the libclang library.
85
86 FIXME: Make libclang expose additional error information in this scenario.
87 """
88 pass
89
90class TranslationUnitSaveError(Exception):
91 """Represents an error that occurred when saving a TranslationUnit.
92
93 Each error has associated with it an enumerated value, accessible under
94 e.save_error. Consumers can compare the value with one of the ERROR_
95 constants in this class.
96 """
97
98 # Indicates that an unknown error occurred. This typically indicates that
99 # I/O failed during save.
100 ERROR_UNKNOWN = 1
101
102 # Indicates that errors during translation prevented saving. The errors
103 # should be available via the TranslationUnit's diagnostics.
104 ERROR_TRANSLATION_ERRORS = 2
105
106 # Indicates that the translation unit was somehow invalid.
107 ERROR_INVALID_TU = 3
108
109 def __init__(self, enumeration, message):
110 assert isinstance(enumeration, int)
111
112 if enumeration < 1 or enumeration > 3:
113 raise Exception("Encountered undefined TranslationUnit save error "
114 "constant: %d. Please file a bug to have this "
115 "value supported." % enumeration)
116
117 self.save_error = enumeration
Gregory Szorc2283b462012-05-12 20:49:13 +0000118 Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
Gregory Szorcfbf620b2012-05-08 05:56:38 +0000119
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000120### Structures and Utility Classes ###
121
Gregory Szorcb15b15c2012-08-19 21:17:46 +0000122class CachedProperty(object):
123 """Decorator that lazy-loads the value of a property.
124
125 The first time the property is accessed, the original property function is
126 executed. The value it returns is set as the new value of that instance's
127 property, replacing the original method.
128 """
129
130 def __init__(self, wrapped):
131 self.wrapped = wrapped
132 try:
133 self.__doc__ = wrapped.__doc__
134 except:
135 pass
136
137 def __get__(self, instance, instance_type=None):
138 if instance is None:
139 return self
140
141 value = self.wrapped(instance)
142 setattr(instance, self.wrapped.__name__, value)
143
144 return value
145
146
Daniel Dunbara33dca42010-01-24 21:19:57 +0000147class _CXString(Structure):
148 """Helper for transforming CXString results."""
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000149
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000150 _fields_ = [("spelling", c_char_p), ("free", c_int)]
151
152 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000153 conf.lib.clang_disposeString(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000154
Daniel Dunbara33dca42010-01-24 21:19:57 +0000155 @staticmethod
156 def from_result(res, fn, args):
157 assert isinstance(res, _CXString)
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000158 return conf.lib.clang_getCString(res)
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000159
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000160class SourceLocation(Structure):
161 """
Daniel Dunbar149f38a2010-01-24 04:09:58 +0000162 A SourceLocation represents a particular location within a source file.
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000163 """
Daniel Dunbare32af422010-01-30 23:58:50 +0000164 _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)]
Daniel Dunbarf8690832010-01-24 21:20:21 +0000165 _data = None
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000166
Daniel Dunbarf8690832010-01-24 21:20:21 +0000167 def _get_instantiation(self):
168 if self._data is None:
Daniel Dunbar3239a672010-01-29 17:02:32 +0000169 f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint()
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000170 conf.lib.clang_getInstantiationLocation(self, byref(f), byref(l),
Gregory Szorc9537e202012-07-12 04:56:46 +0000171 byref(c), byref(o))
Tobias Grosser81982882011-10-31 00:49:07 +0000172 if f:
173 f = File(f)
174 else:
175 f = None
Argyrios Kyrtzidis6b046232011-08-17 17:20:24 +0000176 self._data = (f, int(l.value), int(c.value), int(o.value))
Daniel Dunbarf8690832010-01-24 21:20:21 +0000177 return self._data
178
Tobias Grosser58ba8c92011-10-31 00:31:32 +0000179 @staticmethod
180 def from_position(tu, file, line, column):
181 """
182 Retrieve the source location associated with a given file/line/column in
183 a particular translation unit.
184 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000185 return conf.lib.clang_getLocation(tu, file, line, column)
Tobias Grosser58ba8c92011-10-31 00:31:32 +0000186
Gregory Szorc74bb7102012-06-11 11:11:48 +0000187 @staticmethod
188 def from_offset(tu, file, offset):
189 """Retrieve a SourceLocation from a given character offset.
190
191 tu -- TranslationUnit file belongs to
192 file -- File instance to obtain offset from
193 offset -- Integer character offset within file
194 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000195 return conf.lib.clang_getLocationForOffset(tu, file, offset)
Gregory Szorc74bb7102012-06-11 11:11:48 +0000196
Daniel Dunbarf8690832010-01-24 21:20:21 +0000197 @property
198 def file(self):
199 """Get the file represented by this source location."""
200 return self._get_instantiation()[0]
201
202 @property
203 def line(self):
204 """Get the line represented by this source location."""
205 return self._get_instantiation()[1]
206
207 @property
208 def column(self):
209 """Get the column represented by this source location."""
210 return self._get_instantiation()[2]
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000211
Daniel Dunbar3239a672010-01-29 17:02:32 +0000212 @property
213 def offset(self):
214 """Get the file offset represented by this source location."""
215 return self._get_instantiation()[3]
216
Tobias Grosser74858332012-02-05 11:40:59 +0000217 def __eq__(self, other):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000218 return conf.lib.clang_equalLocations(self, other)
Tobias Grosser74858332012-02-05 11:40:59 +0000219
220 def __ne__(self, other):
221 return not self.__eq__(other)
222
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000223 def __repr__(self):
Tobias Grosser81982882011-10-31 00:49:07 +0000224 if self.file:
225 filename = self.file.name
226 else:
227 filename = None
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000228 return "<SourceLocation file %r, line %r, column %r>" % (
Tobias Grosser81982882011-10-31 00:49:07 +0000229 filename, self.line, self.column)
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000230
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000231class SourceRange(Structure):
232 """
233 A SourceRange describes a range of source locations within the source
234 code.
235 """
236 _fields_ = [
Daniel Dunbare32af422010-01-30 23:58:50 +0000237 ("ptr_data", c_void_p * 2),
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000238 ("begin_int_data", c_uint),
239 ("end_int_data", c_uint)]
240
Daniel Dunbar532fc632010-01-30 23:59:02 +0000241 # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes
242 # object.
243 @staticmethod
244 def from_locations(start, end):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000245 return conf.lib.clang_getRange(start, end)
Daniel Dunbar532fc632010-01-30 23:59:02 +0000246
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000247 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000248 def start(self):
249 """
250 Return a SourceLocation representing the first character within a
251 source range.
252 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000253 return conf.lib.clang_getRangeStart(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000254
Daniel Dunbar7b48b352010-01-24 04:09:34 +0000255 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000256 def end(self):
257 """
258 Return a SourceLocation representing the last character within a
259 source range.
260 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000261 return conf.lib.clang_getRangeEnd(self)
Daniel Dunbarf8690832010-01-24 21:20:21 +0000262
Tobias Grosser74858332012-02-05 11:40:59 +0000263 def __eq__(self, other):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000264 return conf.lib.clang_equalRanges(self, other)
Tobias Grosser74858332012-02-05 11:40:59 +0000265
266 def __ne__(self, other):
267 return not self.__eq__(other)
268
Argyrios Kyrtzidis8c099d92013-10-31 00:03:33 +0000269 def __contains__(self, other):
270 """Useful to detect the Token/Lexer bug"""
271 if not isinstance(other, SourceLocation):
272 return False
273 if other.file is None and self.start.file is None:
274 pass
275 elif ( self.start.file.name != other.file.name or
276 other.file.name != self.end.file.name):
277 # same file name
278 return False
279 # same file, in between lines
280 if self.start.line < other.line < self.end.line:
281 return True
282 elif self.start.line == other.line:
283 # same file first line
284 if self.start.column <= other.column:
285 return True
286 elif other.line == self.end.line:
287 # same file last line
288 if other.column <= self.end.column:
289 return True
290 return False
291
Daniel Dunbarf8690832010-01-24 21:20:21 +0000292 def __repr__(self):
293 return "<SourceRange start %r, end %r>" % (self.start, self.end)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000294
Daniel Dunbar532fc632010-01-30 23:59:02 +0000295class Diagnostic(object):
296 """
297 A Diagnostic is a single instance of a Clang diagnostic. It includes the
298 diagnostic severity, the message, the location the diagnostic occurred, as
299 well as additional source ranges and associated fix-it hints.
300 """
301
302 Ignored = 0
303 Note = 1
304 Warning = 2
305 Error = 3
306 Fatal = 4
307
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000308 def __init__(self, ptr):
309 self.ptr = ptr
310
311 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000312 conf.lib.clang_disposeDiagnostic(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000313
314 @property
315 def severity(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000316 return conf.lib.clang_getDiagnosticSeverity(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000317
318 @property
319 def location(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000320 return conf.lib.clang_getDiagnosticLocation(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000321
322 @property
323 def spelling(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000324 return conf.lib.clang_getDiagnosticSpelling(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000325
326 @property
327 def ranges(self):
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +0000328 class RangeIterator:
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000329 def __init__(self, diag):
330 self.diag = diag
331
332 def __len__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000333 return int(conf.lib.clang_getDiagnosticNumRanges(self.diag))
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000334
335 def __getitem__(self, key):
Tobias Grosserba5d10b2011-10-31 02:06:50 +0000336 if (key >= len(self)):
337 raise IndexError
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000338 return conf.lib.clang_getDiagnosticRange(self.diag, key)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000339
Tobias Grosserff090ca2011-02-05 17:53:48 +0000340 return RangeIterator(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000341
342 @property
343 def fixits(self):
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +0000344 class FixItIterator:
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000345 def __init__(self, diag):
346 self.diag = diag
347
348 def __len__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000349 return int(conf.lib.clang_getDiagnosticNumFixIts(self.diag))
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000350
351 def __getitem__(self, key):
352 range = SourceRange()
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000353 value = conf.lib.clang_getDiagnosticFixIt(self.diag, key,
Gregory Szorc9537e202012-07-12 04:56:46 +0000354 byref(range))
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +0000355 if len(value) == 0:
356 raise IndexError
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000357
358 return FixIt(range, value)
359
Tobias Grosserff090ca2011-02-05 17:53:48 +0000360 return FixItIterator(self)
Daniel Dunbar532fc632010-01-30 23:59:02 +0000361
Tobias Grosserea403822012-02-05 11:41:58 +0000362 @property
363 def category_number(self):
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700364 """The category number for this diagnostic or 0 if unavailable."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000365 return conf.lib.clang_getDiagnosticCategory(self)
Tobias Grosserea403822012-02-05 11:41:58 +0000366
367 @property
368 def category_name(self):
369 """The string name of the category for this diagnostic."""
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700370 return conf.lib.clang_getDiagnosticCategoryText(self)
Tobias Grosserea403822012-02-05 11:41:58 +0000371
372 @property
373 def option(self):
374 """The command-line option that enables this diagnostic."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000375 return conf.lib.clang_getDiagnosticOption(self, None)
Tobias Grosserea403822012-02-05 11:41:58 +0000376
377 @property
378 def disable_option(self):
379 """The command-line option that disables this diagnostic."""
380 disable = _CXString()
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000381 conf.lib.clang_getDiagnosticOption(self, byref(disable))
Tobias Grosserea403822012-02-05 11:41:58 +0000382
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000383 return conf.lib.clang_getCString(disable)
Tobias Grosserea403822012-02-05 11:41:58 +0000384
Daniel Dunbar532fc632010-01-30 23:59:02 +0000385 def __repr__(self):
386 return "<Diagnostic severity %r, location %r, spelling %r>" % (
387 self.severity, self.location, self.spelling)
388
Tobias Grosserff090ca2011-02-05 17:53:48 +0000389 def from_param(self):
390 return self.ptr
391
Daniel Dunbar532fc632010-01-30 23:59:02 +0000392class FixIt(object):
393 """
394 A FixIt represents a transformation to be applied to the source to
395 "fix-it". The fix-it shouldbe applied by replacing the given source range
396 with the given value.
397 """
398
399 def __init__(self, range, value):
400 self.range = range
401 self.value = value
402
403 def __repr__(self):
404 return "<FixIt range %r, value %r>" % (self.range, self.value)
405
Gregory Szorcbe51e432012-07-12 07:21:12 +0000406class TokenGroup(object):
407 """Helper class to facilitate token management.
408
409 Tokens are allocated from libclang in chunks. They must be disposed of as a
410 collective group.
411
412 One purpose of this class is for instances to represent groups of allocated
413 tokens. Each token in a group contains a reference back to an instance of
414 this class. When all tokens from a group are garbage collected, it allows
415 this class to be garbage collected. When this class is garbage collected,
416 it calls the libclang destructor which invalidates all tokens in the group.
417
418 You should not instantiate this class outside of this module.
419 """
420 def __init__(self, tu, memory, count):
421 self._tu = tu
422 self._memory = memory
423 self._count = count
424
425 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000426 conf.lib.clang_disposeTokens(self._tu, self._memory, self._count)
Gregory Szorcbe51e432012-07-12 07:21:12 +0000427
428 @staticmethod
429 def get_tokens(tu, extent):
430 """Helper method to return all tokens in an extent.
431
432 This functionality is needed multiple places in this module. We define
433 it here because it seems like a logical place.
434 """
435 tokens_memory = POINTER(Token)()
436 tokens_count = c_uint()
437
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000438 conf.lib.clang_tokenize(tu, extent, byref(tokens_memory),
Gregory Szorcbe51e432012-07-12 07:21:12 +0000439 byref(tokens_count))
440
441 count = int(tokens_count.value)
442
443 # If we get no tokens, no memory was allocated. Be sure not to return
444 # anything and potentially call a destructor on nothing.
445 if count < 1:
446 return
447
448 tokens_array = cast(tokens_memory, POINTER(Token * count)).contents
449
450 token_group = TokenGroup(tu, tokens_memory, tokens_count)
451
452 for i in xrange(0, count):
453 token = Token()
454 token.int_data = tokens_array[i].int_data
455 token.ptr_data = tokens_array[i].ptr_data
456 token._tu = tu
457 token._group = token_group
458
459 yield token
460
461class TokenKind(object):
462 """Describes a specific type of a Token."""
463
464 _value_map = {} # int -> TokenKind
465
466 def __init__(self, value, name):
467 """Create a new TokenKind instance from a numeric value and a name."""
468 self.value = value
469 self.name = name
470
471 def __repr__(self):
472 return 'TokenKind.%s' % (self.name,)
473
474 @staticmethod
475 def from_value(value):
476 """Obtain a registered TokenKind instance from its value."""
477 result = TokenKind._value_map.get(value, None)
478
479 if result is None:
480 raise ValueError('Unknown TokenKind: %d' % value)
481
482 return result
483
484 @staticmethod
485 def register(value, name):
486 """Register a new TokenKind enumeration.
487
488 This should only be called at module load time by code within this
489 package.
490 """
491 if value in TokenKind._value_map:
492 raise ValueError('TokenKind already registered: %d' % value)
493
494 kind = TokenKind(value, name)
495 TokenKind._value_map[value] = kind
496 setattr(TokenKind, name, kind)
497
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000498### Cursor Kinds ###
499
500class CursorKind(object):
501 """
502 A CursorKind describes the kind of entity that a cursor points to.
503 """
504
505 # The unique kind objects, indexed by id.
506 _kinds = []
507 _name_map = None
508
509 def __init__(self, value):
510 if value >= len(CursorKind._kinds):
511 CursorKind._kinds += [None] * (value - len(CursorKind._kinds) + 1)
512 if CursorKind._kinds[value] is not None:
513 raise ValueError,'CursorKind already loaded'
514 self.value = value
515 CursorKind._kinds[value] = self
516 CursorKind._name_map = None
517
518 def from_param(self):
519 return self.value
520
521 @property
522 def name(self):
523 """Get the enumeration name of this cursor kind."""
524 if self._name_map is None:
525 self._name_map = {}
526 for key,value in CursorKind.__dict__.items():
527 if isinstance(value,CursorKind):
528 self._name_map[value] = key
529 return self._name_map[self]
530
531 @staticmethod
532 def from_id(id):
533 if id >= len(CursorKind._kinds) or CursorKind._kinds[id] is None:
Argyrios Kyrtzidisda6a6f02013-06-11 18:05:42 +0000534 raise ValueError,'Unknown cursor kind %d' % id
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000535 return CursorKind._kinds[id]
536
Daniel Dunbara6a64992010-01-24 21:20:39 +0000537 @staticmethod
538 def get_all_kinds():
Daniel Dunbar4efd6322010-01-25 00:43:08 +0000539 """Return all CursorKind enumeration instances."""
Daniel Dunbara6a64992010-01-24 21:20:39 +0000540 return filter(None, CursorKind._kinds)
541
542 def is_declaration(self):
543 """Test if this is a declaration kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000544 return conf.lib.clang_isDeclaration(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000545
546 def is_reference(self):
547 """Test if this is a reference kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000548 return conf.lib.clang_isReference(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000549
550 def is_expression(self):
551 """Test if this is an expression kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000552 return conf.lib.clang_isExpression(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000553
554 def is_statement(self):
555 """Test if this is a statement kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000556 return conf.lib.clang_isStatement(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000557
Douglas Gregor8be80e12011-07-06 03:00:34 +0000558 def is_attribute(self):
559 """Test if this is an attribute kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000560 return conf.lib.clang_isAttribute(self)
Douglas Gregor8be80e12011-07-06 03:00:34 +0000561
Daniel Dunbara6a64992010-01-24 21:20:39 +0000562 def is_invalid(self):
563 """Test if this is an invalid kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000564 return conf.lib.clang_isInvalid(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000565
Tobias Grossereb136342012-02-05 11:42:09 +0000566 def is_translation_unit(self):
567 """Test if this is a translation unit kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000568 return conf.lib.clang_isTranslationUnit(self)
Tobias Grossereb136342012-02-05 11:42:09 +0000569
570 def is_preprocessing(self):
571 """Test if this is a preprocessing kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000572 return conf.lib.clang_isPreprocessing(self)
Tobias Grossereb136342012-02-05 11:42:09 +0000573
574 def is_unexposed(self):
575 """Test if this is an unexposed kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000576 return conf.lib.clang_isUnexposed(self)
Tobias Grossereb136342012-02-05 11:42:09 +0000577
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000578 def __repr__(self):
579 return 'CursorKind.%s' % (self.name,)
580
581# FIXME: Is there a nicer way to expose this enumeration? We could potentially
582# represent the nested structure, or even build a class hierarchy. The main
583# things we want for sure are (a) simple external access to kinds, (b) a place
584# to hang a description and name, (c) easy to keep in sync with Index.h.
585
Daniel Dunbara6a64992010-01-24 21:20:39 +0000586###
587# Declaration Kinds
588
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000589# A declaration whose specific kind is not exposed via this interface.
590#
591# Unexposed declarations have the same operations as any other kind of
592# declaration; one can extract their location information, spelling, find their
593# definitions, etc. However, the specific kind of the declaration is not
594# reported.
595CursorKind.UNEXPOSED_DECL = CursorKind(1)
596
597# A C or C++ struct.
598CursorKind.STRUCT_DECL = CursorKind(2)
599
600# A C or C++ union.
601CursorKind.UNION_DECL = CursorKind(3)
602
603# A C++ class.
604CursorKind.CLASS_DECL = CursorKind(4)
605
606# An enumeration.
607CursorKind.ENUM_DECL = CursorKind(5)
608
609# A field (in C) or non-static data member (in C++) in a struct, union, or C++
610# class.
611CursorKind.FIELD_DECL = CursorKind(6)
612
613# An enumerator constant.
614CursorKind.ENUM_CONSTANT_DECL = CursorKind(7)
615
616# A function.
617CursorKind.FUNCTION_DECL = CursorKind(8)
618
619# A variable.
620CursorKind.VAR_DECL = CursorKind(9)
621
622# A function or method parameter.
623CursorKind.PARM_DECL = CursorKind(10)
624
625# An Objective-C @interface.
626CursorKind.OBJC_INTERFACE_DECL = CursorKind(11)
627
628# An Objective-C @interface for a category.
629CursorKind.OBJC_CATEGORY_DECL = CursorKind(12)
630
631# An Objective-C @protocol declaration.
632CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13)
633
634# An Objective-C @property declaration.
635CursorKind.OBJC_PROPERTY_DECL = CursorKind(14)
636
637# An Objective-C instance variable.
638CursorKind.OBJC_IVAR_DECL = CursorKind(15)
639
640# An Objective-C instance method.
641CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16)
642
643# An Objective-C class method.
644CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17)
645
646# An Objective-C @implementation.
647CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18)
648
649# An Objective-C @implementation for a category.
650CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19)
651
Daniel Dunbara6a64992010-01-24 21:20:39 +0000652# A typedef.
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000653CursorKind.TYPEDEF_DECL = CursorKind(20)
654
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000655# A C++ class method.
656CursorKind.CXX_METHOD = CursorKind(21)
657
658# A C++ namespace.
659CursorKind.NAMESPACE = CursorKind(22)
660
661# A linkage specification, e.g. 'extern "C"'.
662CursorKind.LINKAGE_SPEC = CursorKind(23)
663
664# A C++ constructor.
665CursorKind.CONSTRUCTOR = CursorKind(24)
666
667# A C++ destructor.
668CursorKind.DESTRUCTOR = CursorKind(25)
669
670# A C++ conversion function.
671CursorKind.CONVERSION_FUNCTION = CursorKind(26)
672
673# A C++ template type parameter
674CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27)
675
676# A C++ non-type template paramater.
677CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28)
678
679# A C++ template template parameter.
Benjamin Kramer69886662012-10-07 11:51:45 +0000680CursorKind.TEMPLATE_TEMPLATE_PARAMETER = CursorKind(29)
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000681
682# A C++ function template.
683CursorKind.FUNCTION_TEMPLATE = CursorKind(30)
684
685# A C++ class template.
686CursorKind.CLASS_TEMPLATE = CursorKind(31)
687
688# A C++ class template partial specialization.
689CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32)
690
691# A C++ namespace alias declaration.
692CursorKind.NAMESPACE_ALIAS = CursorKind(33)
693
694# A C++ using directive
695CursorKind.USING_DIRECTIVE = CursorKind(34)
696
697# A C++ using declaration
698CursorKind.USING_DECLARATION = CursorKind(35)
699
Douglas Gregor42b29842011-10-05 19:00:14 +0000700# A Type alias decl.
701CursorKind.TYPE_ALIAS_DECL = CursorKind(36)
702
703# A Objective-C synthesize decl
704CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37)
705
706# A Objective-C dynamic decl
707CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38)
708
709# A C++ access specifier decl.
710CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39)
711
712
Daniel Dunbara6a64992010-01-24 21:20:39 +0000713###
714# Reference Kinds
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000715
716CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40)
717CursorKind.OBJC_PROTOCOL_REF = CursorKind(41)
718CursorKind.OBJC_CLASS_REF = CursorKind(42)
719
720# A reference to a type declaration.
721#
722# A type reference occurs anywhere where a type is named but not
723# declared. For example, given:
724# typedef unsigned size_type;
725# size_type size;
726#
727# The typedef is a declaration of size_type (CXCursor_TypedefDecl),
728# while the type of the variable "size" is referenced. The cursor
729# referenced by the type of size is the typedef for size_type.
730CursorKind.TYPE_REF = CursorKind(43)
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000731CursorKind.CXX_BASE_SPECIFIER = CursorKind(44)
732
733# A reference to a class template, function template, template
734# template parameter, or class template partial specialization.
735CursorKind.TEMPLATE_REF = CursorKind(45)
736
737# A reference to a namespace or namepsace alias.
738CursorKind.NAMESPACE_REF = CursorKind(46)
739
740# A reference to a member of a struct, union, or class that occurs in
741# some non-expression context, e.g., a designated initializer.
742CursorKind.MEMBER_REF = CursorKind(47)
743
744# A reference to a labeled statement.
745CursorKind.LABEL_REF = CursorKind(48)
746
Argyrios Kyrtzidisda6a6f02013-06-11 18:05:42 +0000747# A reference to a set of overloaded functions or function templates
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000748# that has not yet been resolved to a specific function or function template.
749CursorKind.OVERLOADED_DECL_REF = CursorKind(49)
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000750
Argyrios Kyrtzidisda6a6f02013-06-11 18:05:42 +0000751# A reference to a variable that occurs in some non-expression
752# context, e.g., a C++ lambda capture list.
753CursorKind.VARIABLE_REF = CursorKind(50)
754
Daniel Dunbara6a64992010-01-24 21:20:39 +0000755###
756# Invalid/Error Kinds
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000757
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000758CursorKind.INVALID_FILE = CursorKind(70)
759CursorKind.NO_DECL_FOUND = CursorKind(71)
760CursorKind.NOT_IMPLEMENTED = CursorKind(72)
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000761CursorKind.INVALID_CODE = CursorKind(73)
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000762
Daniel Dunbara6a64992010-01-24 21:20:39 +0000763###
764# Expression Kinds
765
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000766# An expression whose specific kind is not exposed via this interface.
767#
768# Unexposed expressions have the same operations as any other kind of
769# expression; one can extract their location information, spelling, children,
770# etc. However, the specific kind of the expression is not reported.
771CursorKind.UNEXPOSED_EXPR = CursorKind(100)
772
773# An expression that refers to some value declaration, such as a function,
774# varible, or enumerator.
775CursorKind.DECL_REF_EXPR = CursorKind(101)
776
777# An expression that refers to a member of a struct, union, class, Objective-C
778# class, etc.
779CursorKind.MEMBER_REF_EXPR = CursorKind(102)
780
781# An expression that calls a function.
782CursorKind.CALL_EXPR = CursorKind(103)
783
784# An expression that sends a message to an Objective-C object or class.
785CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104)
786
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000787# An expression that represents a block literal.
788CursorKind.BLOCK_EXPR = CursorKind(105)
789
Douglas Gregor42b29842011-10-05 19:00:14 +0000790# An integer literal.
791CursorKind.INTEGER_LITERAL = CursorKind(106)
792
793# A floating point number literal.
794CursorKind.FLOATING_LITERAL = CursorKind(107)
795
796# An imaginary number literal.
797CursorKind.IMAGINARY_LITERAL = CursorKind(108)
798
799# A string literal.
800CursorKind.STRING_LITERAL = CursorKind(109)
801
802# A character literal.
803CursorKind.CHARACTER_LITERAL = CursorKind(110)
804
805# A parenthesized expression, e.g. "(1)".
806#
807# This AST node is only formed if full location information is requested.
808CursorKind.PAREN_EXPR = CursorKind(111)
809
810# This represents the unary-expression's (except sizeof and
811# alignof).
812CursorKind.UNARY_OPERATOR = CursorKind(112)
813
814# [C99 6.5.2.1] Array Subscripting.
815CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113)
816
817# A builtin binary operation expression such as "x + y" or
818# "x <= y".
819CursorKind.BINARY_OPERATOR = CursorKind(114)
820
821# Compound assignment such as "+=".
822CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115)
823
824# The ?: ternary operator.
Douglas Gregor39a03d12012-06-08 00:16:27 +0000825CursorKind.CONDITIONAL_OPERATOR = CursorKind(116)
Douglas Gregor42b29842011-10-05 19:00:14 +0000826
827# An explicit cast in C (C99 6.5.4) or a C-style cast in C++
828# (C++ [expr.cast]), which uses the syntax (Type)expr.
829#
830# For example: (int)f.
831CursorKind.CSTYLE_CAST_EXPR = CursorKind(117)
832
833# [C99 6.5.2.5]
834CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118)
835
836# Describes an C or C++ initializer list.
837CursorKind.INIT_LIST_EXPR = CursorKind(119)
838
839# The GNU address of label extension, representing &&label.
840CursorKind.ADDR_LABEL_EXPR = CursorKind(120)
841
842# This is the GNU Statement Expression extension: ({int X=4; X;})
843CursorKind.StmtExpr = CursorKind(121)
844
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000845# Represents a C11 generic selection.
Douglas Gregor42b29842011-10-05 19:00:14 +0000846CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122)
847
848# Implements the GNU __null extension, which is a name for a null
849# pointer constant that has integral type (e.g., int or long) and is the same
850# size and alignment as a pointer.
851#
852# The __null extension is typically only used by system headers, which define
853# NULL as __null in C++ rather than using 0 (which is an integer that may not
854# match the size of a pointer).
855CursorKind.GNU_NULL_EXPR = CursorKind(123)
856
857# C++'s static_cast<> expression.
858CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124)
859
860# C++'s dynamic_cast<> expression.
861CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125)
862
863# C++'s reinterpret_cast<> expression.
864CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126)
865
866# C++'s const_cast<> expression.
867CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127)
868
869# Represents an explicit C++ type conversion that uses "functional"
870# notion (C++ [expr.type.conv]).
871#
872# Example:
873# \code
874# x = int(0.5);
875# \endcode
876CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128)
877
878# A C++ typeid expression (C++ [expr.typeid]).
879CursorKind.CXX_TYPEID_EXPR = CursorKind(129)
880
881# [C++ 2.13.5] C++ Boolean Literal.
882CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130)
883
884# [C++0x 2.14.7] C++ Pointer Literal.
885CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131)
886
887# Represents the "this" expression in C++
888CursorKind.CXX_THIS_EXPR = CursorKind(132)
889
890# [C++ 15] C++ Throw Expression.
891#
892# This handles 'throw' and 'throw' assignment-expression. When
893# assignment-expression isn't present, Op will be null.
894CursorKind.CXX_THROW_EXPR = CursorKind(133)
895
896# A new expression for memory allocation and constructor calls, e.g:
897# "new CXXNewExpr(foo)".
898CursorKind.CXX_NEW_EXPR = CursorKind(134)
899
900# A delete expression for memory deallocation and destructor calls,
901# e.g. "delete[] pArray".
902CursorKind.CXX_DELETE_EXPR = CursorKind(135)
903
904# Represents a unary expression.
905CursorKind.CXX_UNARY_EXPR = CursorKind(136)
906
907# ObjCStringLiteral, used for Objective-C string literals i.e. "foo".
908CursorKind.OBJC_STRING_LITERAL = CursorKind(137)
909
910# ObjCEncodeExpr, used for in Objective-C.
911CursorKind.OBJC_ENCODE_EXPR = CursorKind(138)
912
913# ObjCSelectorExpr used for in Objective-C.
914CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139)
915
916# Objective-C's protocol expression.
917CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140)
918
919# An Objective-C "bridged" cast expression, which casts between
920# Objective-C pointers and C pointers, transferring ownership in the process.
921#
922# \code
923# NSString *str = (__bridge_transfer NSString *)CFCreateString();
924# \endcode
925CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141)
926
927# Represents a C++0x pack expansion that produces a sequence of
928# expressions.
929#
930# A pack expansion expression contains a pattern (which itself is an
931# expression) followed by an ellipsis. For example:
932CursorKind.PACK_EXPANSION_EXPR = CursorKind(142)
933
934# Represents an expression that computes the length of a parameter
935# pack.
936CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143)
937
Argyrios Kyrtzidisda6a6f02013-06-11 18:05:42 +0000938# Represents a C++ lambda expression that produces a local function
939# object.
940#
941# \code
942# void abssort(float *x, unsigned N) {
943# std::sort(x, x + N,
944# [](float a, float b) {
945# return std::abs(a) < std::abs(b);
946# });
947# }
948# \endcode
949CursorKind.LAMBDA_EXPR = CursorKind(144)
950
951# Objective-c Boolean Literal.
952CursorKind.OBJ_BOOL_LITERAL_EXPR = CursorKind(145)
953
954# Represents the "self" expression in a ObjC method.
955CursorKind.OBJ_SELF_EXPR = CursorKind(146)
956
957
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000958# A statement whose specific kind is not exposed via this interface.
959#
960# Unexposed statements have the same operations as any other kind of statement;
961# one can extract their location information, spelling, children, etc. However,
962# the specific kind of the statement is not reported.
963CursorKind.UNEXPOSED_STMT = CursorKind(200)
964
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000965# A labelled statement in a function.
966CursorKind.LABEL_STMT = CursorKind(201)
967
Douglas Gregor42b29842011-10-05 19:00:14 +0000968# A compound statement
969CursorKind.COMPOUND_STMT = CursorKind(202)
970
971# A case statement.
972CursorKind.CASE_STMT = CursorKind(203)
973
974# A default statement.
975CursorKind.DEFAULT_STMT = CursorKind(204)
976
977# An if statement.
978CursorKind.IF_STMT = CursorKind(205)
979
980# A switch statement.
981CursorKind.SWITCH_STMT = CursorKind(206)
982
983# A while statement.
984CursorKind.WHILE_STMT = CursorKind(207)
985
986# A do statement.
987CursorKind.DO_STMT = CursorKind(208)
988
989# A for statement.
990CursorKind.FOR_STMT = CursorKind(209)
991
992# A goto statement.
993CursorKind.GOTO_STMT = CursorKind(210)
994
995# An indirect goto statement.
996CursorKind.INDIRECT_GOTO_STMT = CursorKind(211)
997
998# A continue statement.
999CursorKind.CONTINUE_STMT = CursorKind(212)
1000
1001# A break statement.
1002CursorKind.BREAK_STMT = CursorKind(213)
1003
1004# A return statement.
1005CursorKind.RETURN_STMT = CursorKind(214)
1006
1007# A GNU-style inline assembler statement.
1008CursorKind.ASM_STMT = CursorKind(215)
1009
1010# Objective-C's overall @try-@catch-@finally statement.
1011CursorKind.OBJC_AT_TRY_STMT = CursorKind(216)
1012
1013# Objective-C's @catch statement.
1014CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217)
1015
1016# Objective-C's @finally statement.
1017CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218)
1018
1019# Objective-C's @throw statement.
1020CursorKind.OBJC_AT_THROW_STMT = CursorKind(219)
1021
1022# Objective-C's @synchronized statement.
1023CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220)
1024
1025# Objective-C's autorealease pool statement.
1026CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221)
1027
1028# Objective-C's for collection statement.
1029CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222)
1030
1031# C++'s catch statement.
1032CursorKind.CXX_CATCH_STMT = CursorKind(223)
1033
1034# C++'s try statement.
1035CursorKind.CXX_TRY_STMT = CursorKind(224)
1036
1037# C++'s for (* : *) statement.
1038CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225)
1039
1040# Windows Structured Exception Handling's try statement.
1041CursorKind.SEH_TRY_STMT = CursorKind(226)
1042
1043# Windows Structured Exception Handling's except statement.
1044CursorKind.SEH_EXCEPT_STMT = CursorKind(227)
1045
1046# Windows Structured Exception Handling's finally statement.
1047CursorKind.SEH_FINALLY_STMT = CursorKind(228)
1048
Argyrios Kyrtzidisda6a6f02013-06-11 18:05:42 +00001049# A MS inline assembly statement extension.
1050CursorKind.MS_ASM_STMT = CursorKind(229)
1051
Douglas Gregor42b29842011-10-05 19:00:14 +00001052# The null statement.
1053CursorKind.NULL_STMT = CursorKind(230)
1054
1055# Adaptor class for mixing declarations with statements and expressions.
1056CursorKind.DECL_STMT = CursorKind(231)
Tobias Grosser4ed73ce2011-02-05 17:53:47 +00001057
Daniel Dunbara6a64992010-01-24 21:20:39 +00001058###
1059# Other Kinds
1060
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001061# Cursor that represents the translation unit itself.
1062#
1063# The translation unit cursor exists primarily to act as the root cursor for
1064# traversing the contents of a translation unit.
1065CursorKind.TRANSLATION_UNIT = CursorKind(300)
1066
Tobias Grosser4ed73ce2011-02-05 17:53:47 +00001067###
1068# Attributes
1069
1070# An attribute whoe specific kind is note exposed via this interface
1071CursorKind.UNEXPOSED_ATTR = CursorKind(400)
1072
1073CursorKind.IB_ACTION_ATTR = CursorKind(401)
1074CursorKind.IB_OUTLET_ATTR = CursorKind(402)
1075CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403)
1076
Rafael Espindolabf3cc732011-12-30 15:27:22 +00001077CursorKind.CXX_FINAL_ATTR = CursorKind(404)
1078CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405)
1079CursorKind.ANNOTATE_ATTR = CursorKind(406)
1080CursorKind.ASM_LABEL_ATTR = CursorKind(407)
Argyrios Kyrtzidis51337112013-09-25 00:14:38 +00001081CursorKind.PACKED_ATTR = CursorKind(408)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001082CursorKind.PURE_ATTR = CursorKind(409)
1083CursorKind.CONST_ATTR = CursorKind(410)
1084CursorKind.NODUPLICATE_ATTR = CursorKind(411)
Rafael Espindolabf3cc732011-12-30 15:27:22 +00001085
Tobias Grosser4ed73ce2011-02-05 17:53:47 +00001086###
1087# Preprocessing
1088CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500)
1089CursorKind.MACRO_DEFINITION = CursorKind(501)
1090CursorKind.MACRO_INSTANTIATION = CursorKind(502)
1091CursorKind.INCLUSION_DIRECTIVE = CursorKind(503)
1092
Argyrios Kyrtzidisda6a6f02013-06-11 18:05:42 +00001093###
1094# Extra declaration
1095
1096# A module import declaration.
1097CursorKind.MODULE_IMPORT_DECL = CursorKind(600)
1098
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001099### Cursors ###
1100
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001101class Cursor(Structure):
1102 """
1103 The Cursor class represents a reference to an element within the AST. It
1104 acts as a kind of iterator.
1105 """
Douglas Gregor2abfec32011-10-19 05:47:46 +00001106 _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001107
Tobias Grosser58ba8c92011-10-31 00:31:32 +00001108 @staticmethod
1109 def from_location(tu, location):
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001110 # We store a reference to the TU in the instance so the TU won't get
1111 # collected before the cursor.
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001112 cursor = conf.lib.clang_getCursor(tu, location)
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001113 cursor._tu = tu
1114
1115 return cursor
Tobias Grosser58ba8c92011-10-31 00:31:32 +00001116
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001117 def __eq__(self, other):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001118 return conf.lib.clang_equalCursors(self, other)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001119
1120 def __ne__(self, other):
Gregory Szorc9d008fd2012-03-05 00:42:15 +00001121 return not self.__eq__(other)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001122
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001123 def is_definition(self):
1124 """
1125 Returns true if the declaration pointed at by the cursor is also a
1126 definition of that entity.
1127 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001128 return conf.lib.clang_isCursorDefinition(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001129
Gregory Szorce65b34d2012-06-09 16:21:34 +00001130 def is_static_method(self):
1131 """Returns True if the cursor refers to a C++ member function or member
1132 function template that is declared 'static'.
1133 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001134 return conf.lib.clang_CXXMethod_isStatic(self)
Gregory Szorce65b34d2012-06-09 16:21:34 +00001135
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001136 def get_definition(self):
1137 """
1138 If the cursor is a reference to a declaration or a declaration of
1139 some entity, return a cursor that points to the definition of that
1140 entity.
1141 """
1142 # TODO: Should probably check that this is either a reference or
1143 # declaration prior to issuing the lookup.
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001144 return conf.lib.clang_getCursorDefinition(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001145
Daniel Dunbar3d855f82010-01-24 21:20:13 +00001146 def get_usr(self):
1147 """Return the Unified Symbol Resultion (USR) for the entity referenced
1148 by the given cursor (or None).
1149
1150 A Unified Symbol Resolution (USR) is a string that identifies a
1151 particular entity (function, class, variable, etc.) within a
1152 program. USRs can be compared across translation units to determine,
1153 e.g., when references in one translation refer to an entity defined in
1154 another translation unit."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001155 return conf.lib.clang_getCursorUSR(self)
Daniel Dunbar3d855f82010-01-24 21:20:13 +00001156
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001157 @property
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001158 def kind(self):
1159 """Return the kind of this cursor."""
1160 return CursorKind.from_id(self._kind_id)
1161
1162 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001163 def spelling(self):
1164 """Return the spelling of the entity pointed at by the cursor."""
Daniel Dunbara6a64992010-01-24 21:20:39 +00001165 if not self.kind.is_declaration():
Daniel Dunbar3d855f82010-01-24 21:20:13 +00001166 # FIXME: clang_getCursorSpelling should be fixed to not assert on
1167 # this, for consistency with clang_getCursorUSR.
1168 return None
Douglas Gregor42b29842011-10-05 19:00:14 +00001169 if not hasattr(self, '_spelling'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001170 self._spelling = conf.lib.clang_getCursorSpelling(self)
Gregory Szorc9537e202012-07-12 04:56:46 +00001171
Douglas Gregor42b29842011-10-05 19:00:14 +00001172 return self._spelling
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001173
1174 @property
Douglas Gregorb60a2be2011-08-30 00:15:34 +00001175 def displayname(self):
1176 """
1177 Return the display name for the entity referenced by this cursor.
1178
1179 The display name contains extra information that helps identify the cursor,
1180 such as the parameters of a function or template or the arguments of a
1181 class template specialization.
1182 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001183 if not hasattr(self, '_displayname'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001184 self._displayname = conf.lib.clang_getCursorDisplayName(self)
Gregory Szorc9537e202012-07-12 04:56:46 +00001185
Douglas Gregor42b29842011-10-05 19:00:14 +00001186 return self._displayname
Douglas Gregorb60a2be2011-08-30 00:15:34 +00001187
1188 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001189 def location(self):
1190 """
1191 Return the source location (the starting character) of the entity
1192 pointed at by the cursor.
1193 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001194 if not hasattr(self, '_loc'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001195 self._loc = conf.lib.clang_getCursorLocation(self)
Gregory Szorc9537e202012-07-12 04:56:46 +00001196
Douglas Gregor42b29842011-10-05 19:00:14 +00001197 return self._loc
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001198
1199 @property
1200 def extent(self):
1201 """
1202 Return the source range (the range of text) occupied by the entity
1203 pointed at by the cursor.
1204 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001205 if not hasattr(self, '_extent'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001206 self._extent = conf.lib.clang_getCursorExtent(self)
Gregory Szorc9537e202012-07-12 04:56:46 +00001207
Douglas Gregor42b29842011-10-05 19:00:14 +00001208 return self._extent
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001209
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001210 @property
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001211 def access_specifier(self):
1212 """
1213 Retrieves the access specifier (if any) of the entity pointed at by the
1214 cursor.
1215 """
1216 if not hasattr(self, '_access_specifier'):
1217 self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self)
1218
1219 return AccessSpecifier.from_id(self._access_specifier)
1220
1221 @property
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001222 def type(self):
1223 """
Tobias Grosser2d106802012-02-05 12:15:56 +00001224 Retrieve the Type (if any) of the entity pointed at by the cursor.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001225 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001226 if not hasattr(self, '_type'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001227 self._type = conf.lib.clang_getCursorType(self)
Gregory Szorc9537e202012-07-12 04:56:46 +00001228
Douglas Gregor42b29842011-10-05 19:00:14 +00001229 return self._type
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001230
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00001231 @property
Gregory Szorc2c408352012-05-14 03:56:33 +00001232 def canonical(self):
1233 """Return the canonical Cursor corresponding to this Cursor.
1234
1235 The canonical cursor is the cursor which is representative for the
1236 underlying entity. For example, if you have multiple forward
1237 declarations for the same class, the canonical cursor for the forward
1238 declarations will be identical.
1239 """
1240 if not hasattr(self, '_canonical'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001241 self._canonical = conf.lib.clang_getCanonicalCursor(self)
Gregory Szorc2c408352012-05-14 03:56:33 +00001242
1243 return self._canonical
1244
1245 @property
Gregory Szorc1e370ab2012-05-14 03:53:29 +00001246 def result_type(self):
1247 """Retrieve the Type of the result for this Cursor."""
1248 if not hasattr(self, '_result_type'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001249 self._result_type = conf.lib.clang_getResultType(self.type)
Gregory Szorc1e370ab2012-05-14 03:53:29 +00001250
1251 return self._result_type
1252
1253 @property
Tobias Grosser28d939f2012-02-05 11:42:20 +00001254 def underlying_typedef_type(self):
1255 """Return the underlying type of a typedef declaration.
1256
Tobias Grosser2d106802012-02-05 12:15:56 +00001257 Returns a Type for the typedef this cursor is a declaration for. If
Tobias Grosser28d939f2012-02-05 11:42:20 +00001258 the current cursor is not a typedef, this raises.
1259 """
1260 if not hasattr(self, '_underlying_type'):
1261 assert self.kind.is_declaration()
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001262 self._underlying_type = \
1263 conf.lib.clang_getTypedefDeclUnderlyingType(self)
Tobias Grosser28d939f2012-02-05 11:42:20 +00001264
1265 return self._underlying_type
1266
1267 @property
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00001268 def enum_type(self):
1269 """Return the integer type of an enum declaration.
1270
Tobias Grosser2d106802012-02-05 12:15:56 +00001271 Returns a Type corresponding to an integer. If the cursor is not for an
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00001272 enum, this raises.
1273 """
1274 if not hasattr(self, '_enum_type'):
1275 assert self.kind == CursorKind.ENUM_DECL
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001276 self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self)
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00001277
1278 return self._enum_type
1279
1280 @property
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00001281 def enum_value(self):
1282 """Return the value of an enum constant."""
1283 if not hasattr(self, '_enum_value'):
1284 assert self.kind == CursorKind.ENUM_CONSTANT_DECL
1285 # Figure out the underlying type of the enum to know if it
1286 # is a signed or unsigned quantity.
1287 underlying_type = self.type
1288 if underlying_type.kind == TypeKind.ENUM:
1289 underlying_type = underlying_type.get_declaration().enum_type
1290 if underlying_type.kind in (TypeKind.CHAR_U,
1291 TypeKind.UCHAR,
1292 TypeKind.CHAR16,
1293 TypeKind.CHAR32,
1294 TypeKind.USHORT,
1295 TypeKind.UINT,
1296 TypeKind.ULONG,
1297 TypeKind.ULONGLONG,
1298 TypeKind.UINT128):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001299 self._enum_value = \
1300 conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00001301 else:
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001302 self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self)
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00001303 return self._enum_value
1304
1305 @property
Gregory Szorc5cc67872012-03-10 22:23:27 +00001306 def objc_type_encoding(self):
1307 """Return the Objective-C type encoding as a str."""
1308 if not hasattr(self, '_objc_type_encoding'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001309 self._objc_type_encoding = \
1310 conf.lib.clang_getDeclObjCTypeEncoding(self)
Gregory Szorc5cc67872012-03-10 22:23:27 +00001311
1312 return self._objc_type_encoding
1313
1314 @property
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00001315 def hash(self):
1316 """Returns a hash of the cursor as an int."""
1317 if not hasattr(self, '_hash'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001318 self._hash = conf.lib.clang_hashCursor(self)
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00001319
1320 return self._hash
1321
Manuel Klimek667fd802012-05-07 05:56:03 +00001322 @property
1323 def semantic_parent(self):
1324 """Return the semantic parent for this cursor."""
1325 if not hasattr(self, '_semantic_parent'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001326 self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self)
Gregory Szorcfd04a6a2012-05-08 06:01:34 +00001327
Manuel Klimek667fd802012-05-07 05:56:03 +00001328 return self._semantic_parent
1329
1330 @property
1331 def lexical_parent(self):
1332 """Return the lexical parent for this cursor."""
1333 if not hasattr(self, '_lexical_parent'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001334 self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self)
Gregory Szorcfd04a6a2012-05-08 06:01:34 +00001335
Manuel Klimek667fd802012-05-07 05:56:03 +00001336 return self._lexical_parent
Gregory Szorcfd04a6a2012-05-08 06:01:34 +00001337
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001338 @property
1339 def translation_unit(self):
1340 """Returns the TranslationUnit to which this Cursor belongs."""
1341 # If this triggers an AttributeError, the instance was not properly
1342 # created.
1343 return self._tu
1344
Argyrios Kyrtzidisd8293792013-01-02 22:31:57 +00001345 @property
1346 def referenced(self):
1347 """
1348 For a cursor that is a reference, returns a cursor
1349 representing the entity that it references.
1350 """
1351 if not hasattr(self, '_referenced'):
1352 self._referenced = conf.lib.clang_getCursorReferenced(self)
1353
1354 return self._referenced
1355
Argyrios Kyrtzidisc23cb2d2013-10-03 16:19:27 +00001356 @property
1357 def brief_comment(self):
1358 """Returns the brief comment text associated with that Cursor"""
1359 return conf.lib.clang_Cursor_getBriefCommentText(self)
1360
1361 @property
1362 def raw_comment(self):
1363 """Returns the raw comment text associated with that Cursor"""
1364 return conf.lib.clang_Cursor_getRawCommentText(self)
1365
Gregory Szorcb03b57d2012-11-01 05:46:30 +00001366 def get_arguments(self):
1367 """Return an iterator for accessing the arguments of this cursor."""
1368 num_args = conf.lib.clang_Cursor_getNumArguments(self)
1369 for i in range(0, num_args):
1370 yield conf.lib.clang_Cursor_getArgument(self, i)
1371
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001372 def get_children(self):
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001373 """Return an iterator for accessing the children of this cursor."""
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001374
1375 # FIXME: Expose iteration from CIndex, PR6125.
1376 def visitor(child, parent, children):
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001377 # FIXME: Document this assertion in API.
1378 # FIXME: There should just be an isNull method.
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001379 assert child != conf.lib.clang_getNullCursor()
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001380
1381 # Create reference to TU so it isn't GC'd before Cursor.
1382 child._tu = self._tu
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001383 children.append(child)
1384 return 1 # continue
1385 children = []
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001386 conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
Gregory Szorc9537e202012-07-12 04:56:46 +00001387 children)
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001388 return iter(children)
1389
Gregory Szorcbe51e432012-07-12 07:21:12 +00001390 def get_tokens(self):
1391 """Obtain Token instances formulating that compose this Cursor.
1392
1393 This is a generator for Token instances. It returns all tokens which
1394 occupy the extent this cursor occupies.
1395 """
1396 return TokenGroup.get_tokens(self._tu, self.extent)
1397
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00001398 def is_bitfield(self):
1399 """
1400 Check if the field is a bitfield.
1401 """
1402 return conf.lib.clang_Cursor_isBitField(self)
1403
1404 def get_bitfield_width(self):
1405 """
1406 Retrieve the width of a bitfield.
1407 """
1408 return conf.lib.clang_getFieldDeclBitWidth(self)
1409
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001410 @staticmethod
1411 def from_result(res, fn, args):
1412 assert isinstance(res, Cursor)
1413 # FIXME: There should just be an isNull method.
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001414 if res == conf.lib.clang_getNullCursor():
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001415 return None
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001416
1417 # Store a reference to the TU in the Python object so it won't get GC'd
1418 # before the Cursor.
1419 tu = None
1420 for arg in args:
1421 if isinstance(arg, TranslationUnit):
1422 tu = arg
1423 break
1424
1425 if hasattr(arg, 'translation_unit'):
1426 tu = arg.translation_unit
1427 break
1428
1429 assert tu is not None
1430
1431 res._tu = tu
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001432 return res
1433
Gregory Szorc9537e202012-07-12 04:56:46 +00001434 @staticmethod
1435 def from_cursor_result(res, fn, args):
1436 assert isinstance(res, Cursor)
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001437 if res == conf.lib.clang_getNullCursor():
Gregory Szorc9537e202012-07-12 04:56:46 +00001438 return None
1439
1440 res._tu = args[0]._tu
1441 return res
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001442
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001443### C++ access specifiers ###
1444
1445class AccessSpecifier(object):
1446 """
1447 Describes the access of a C++ class member
1448 """
1449
1450 # The unique kind objects, index by id.
1451 _kinds = []
1452 _name_map = None
1453
1454 def __init__(self, value):
1455 if value >= len(AccessSpecifier._kinds):
1456 AccessSpecifier._kinds += [None] * (value - len(AccessSpecifier._kinds) + 1)
1457 if AccessSpecifier._kinds[value] is not None:
1458 raise ValueError,'AccessSpecifier already loaded'
1459 self.value = value
1460 AccessSpecifier._kinds[value] = self
1461 AccessSpecifier._name_map = None
1462
1463 def from_param(self):
1464 return self.value
1465
1466 @property
1467 def name(self):
1468 """Get the enumeration name of this access specifier."""
1469 if self._name_map is None:
1470 self._name_map = {}
1471 for key,value in AccessSpecifier.__dict__.items():
1472 if isinstance(value,AccessSpecifier):
1473 self._name_map[value] = key
1474 return self._name_map[self]
1475
1476 @staticmethod
1477 def from_id(id):
1478 if id >= len(AccessSpecifier._kinds) or not AccessSpecifier._kinds[id]:
1479 raise ValueError,'Unknown access specifier %d' % id
1480 return AccessSpecifier._kinds[id]
1481
1482 def __repr__(self):
1483 return 'AccessSpecifier.%s' % (self.name,)
1484
1485AccessSpecifier.INVALID = AccessSpecifier(0)
1486AccessSpecifier.PUBLIC = AccessSpecifier(1)
1487AccessSpecifier.PROTECTED = AccessSpecifier(2)
1488AccessSpecifier.PRIVATE = AccessSpecifier(3)
1489AccessSpecifier.NONE = AccessSpecifier(4)
1490
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001491### Type Kinds ###
1492
1493class TypeKind(object):
1494 """
1495 Describes the kind of type.
1496 """
1497
1498 # The unique kind objects, indexed by id.
1499 _kinds = []
1500 _name_map = None
1501
1502 def __init__(self, value):
1503 if value >= len(TypeKind._kinds):
1504 TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1)
1505 if TypeKind._kinds[value] is not None:
1506 raise ValueError,'TypeKind already loaded'
1507 self.value = value
1508 TypeKind._kinds[value] = self
1509 TypeKind._name_map = None
1510
1511 def from_param(self):
1512 return self.value
1513
1514 @property
1515 def name(self):
1516 """Get the enumeration name of this cursor kind."""
1517 if self._name_map is None:
1518 self._name_map = {}
1519 for key,value in TypeKind.__dict__.items():
1520 if isinstance(value,TypeKind):
1521 self._name_map[value] = key
1522 return self._name_map[self]
1523
Gregory Szorc6e67eed2012-04-15 18:51:10 +00001524 @property
1525 def spelling(self):
1526 """Retrieve the spelling of this TypeKind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001527 return conf.lib.clang_getTypeKindSpelling(self.value)
Gregory Szorc6e67eed2012-04-15 18:51:10 +00001528
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001529 @staticmethod
1530 def from_id(id):
1531 if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None:
Douglas Gregor9d342ab2011-10-19 05:49:29 +00001532 raise ValueError,'Unknown type kind %d' % id
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001533 return TypeKind._kinds[id]
1534
1535 def __repr__(self):
1536 return 'TypeKind.%s' % (self.name,)
1537
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001538TypeKind.INVALID = TypeKind(0)
1539TypeKind.UNEXPOSED = TypeKind(1)
1540TypeKind.VOID = TypeKind(2)
1541TypeKind.BOOL = TypeKind(3)
1542TypeKind.CHAR_U = TypeKind(4)
1543TypeKind.UCHAR = TypeKind(5)
1544TypeKind.CHAR16 = TypeKind(6)
1545TypeKind.CHAR32 = TypeKind(7)
1546TypeKind.USHORT = TypeKind(8)
1547TypeKind.UINT = TypeKind(9)
1548TypeKind.ULONG = TypeKind(10)
1549TypeKind.ULONGLONG = TypeKind(11)
1550TypeKind.UINT128 = TypeKind(12)
1551TypeKind.CHAR_S = TypeKind(13)
1552TypeKind.SCHAR = TypeKind(14)
1553TypeKind.WCHAR = TypeKind(15)
1554TypeKind.SHORT = TypeKind(16)
1555TypeKind.INT = TypeKind(17)
1556TypeKind.LONG = TypeKind(18)
1557TypeKind.LONGLONG = TypeKind(19)
1558TypeKind.INT128 = TypeKind(20)
1559TypeKind.FLOAT = TypeKind(21)
1560TypeKind.DOUBLE = TypeKind(22)
1561TypeKind.LONGDOUBLE = TypeKind(23)
1562TypeKind.NULLPTR = TypeKind(24)
1563TypeKind.OVERLOAD = TypeKind(25)
1564TypeKind.DEPENDENT = TypeKind(26)
1565TypeKind.OBJCID = TypeKind(27)
1566TypeKind.OBJCCLASS = TypeKind(28)
1567TypeKind.OBJCSEL = TypeKind(29)
1568TypeKind.COMPLEX = TypeKind(100)
1569TypeKind.POINTER = TypeKind(101)
1570TypeKind.BLOCKPOINTER = TypeKind(102)
1571TypeKind.LVALUEREFERENCE = TypeKind(103)
1572TypeKind.RVALUEREFERENCE = TypeKind(104)
1573TypeKind.RECORD = TypeKind(105)
1574TypeKind.ENUM = TypeKind(106)
1575TypeKind.TYPEDEF = TypeKind(107)
1576TypeKind.OBJCINTERFACE = TypeKind(108)
1577TypeKind.OBJCOBJECTPOINTER = TypeKind(109)
1578TypeKind.FUNCTIONNOPROTO = TypeKind(110)
1579TypeKind.FUNCTIONPROTO = TypeKind(111)
Douglas Gregor38d2d552011-10-19 05:50:34 +00001580TypeKind.CONSTANTARRAY = TypeKind(112)
Tobias Grosser250d2172012-02-05 11:42:14 +00001581TypeKind.VECTOR = TypeKind(113)
Argyrios Kyrtzidis4c4f6fe2013-07-23 17:36:21 +00001582TypeKind.INCOMPLETEARRAY = TypeKind(114)
1583TypeKind.VARIABLEARRAY = TypeKind(115)
1584TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116)
Argyrios Kyrtzidis367e8fe2013-10-03 16:19:23 +00001585TypeKind.MEMBERPOINTER = TypeKind(117)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001586
Argyrios Kyrtzidis659837e2013-10-11 19:58:38 +00001587class RefQualifierKind(object):
1588 """Describes a specific ref-qualifier of a type."""
1589
1590 # The unique kind objects, indexed by id.
1591 _kinds = []
1592 _name_map = None
1593
1594 def __init__(self, value):
1595 if value >= len(RefQualifierKind._kinds):
1596 num_kinds = value - len(RefQualifierKind._kinds) + 1
1597 RefQualifierKind._kinds += [None] * num_kinds
1598 if RefQualifierKind._kinds[value] is not None:
1599 raise ValueError, 'RefQualifierKind already loaded'
1600 self.value = value
1601 RefQualifierKind._kinds[value] = self
1602 RefQualifierKind._name_map = None
1603
1604 def from_param(self):
1605 return self.value
1606
1607 @property
1608 def name(self):
1609 """Get the enumeration name of this kind."""
1610 if self._name_map is None:
1611 self._name_map = {}
1612 for key, value in RefQualifierKind.__dict__.items():
1613 if isinstance(value, RefQualifierKind):
1614 self._name_map[value] = key
1615 return self._name_map[self]
1616
1617 @staticmethod
1618 def from_id(id):
1619 if (id >= len(RefQualifierKind._kinds) or
1620 RefQualifierKind._kinds[id] is None):
1621 raise ValueError, 'Unknown type kind %d' % id
1622 return RefQualifierKind._kinds[id]
1623
1624 def __repr__(self):
1625 return 'RefQualifierKind.%s' % (self.name,)
1626
1627RefQualifierKind.NONE = RefQualifierKind(0)
1628RefQualifierKind.LVALUE = RefQualifierKind(1)
1629RefQualifierKind.RVALUE = RefQualifierKind(2)
1630
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001631class Type(Structure):
1632 """
1633 The type of an element in the abstract syntax tree.
1634 """
1635 _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)]
1636
1637 @property
1638 def kind(self):
1639 """Return the kind of this type."""
1640 return TypeKind.from_id(self._kind_id)
1641
Gregory Szorc826fce52012-02-20 17:45:30 +00001642 def argument_types(self):
1643 """Retrieve a container for the non-variadic arguments for this type.
1644
1645 The returned object is iterable and indexable. Each item in the
1646 container is a Type instance.
1647 """
1648 class ArgumentsIterator(collections.Sequence):
1649 def __init__(self, parent):
1650 self.parent = parent
1651 self.length = None
1652
1653 def __len__(self):
1654 if self.length is None:
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001655 self.length = conf.lib.clang_getNumArgTypes(self.parent)
Gregory Szorc826fce52012-02-20 17:45:30 +00001656
1657 return self.length
1658
1659 def __getitem__(self, key):
1660 # FIXME Support slice objects.
1661 if not isinstance(key, int):
1662 raise TypeError("Must supply a non-negative int.")
1663
1664 if key < 0:
1665 raise IndexError("Only non-negative indexes are accepted.")
1666
1667 if key >= len(self):
1668 raise IndexError("Index greater than container length: "
1669 "%d > %d" % ( key, len(self) ))
1670
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001671 result = conf.lib.clang_getArgType(self.parent, key)
Gregory Szorc826fce52012-02-20 17:45:30 +00001672 if result.kind == TypeKind.INVALID:
1673 raise IndexError("Argument could not be retrieved.")
1674
1675 return result
1676
1677 assert self.kind == TypeKind.FUNCTIONPROTO
1678 return ArgumentsIterator(self)
1679
Gregory Szorc86057602012-02-17 07:44:46 +00001680 @property
1681 def element_type(self):
1682 """Retrieve the Type of elements within this Type.
1683
1684 If accessed on a type that is not an array, complex, or vector type, an
1685 exception will be raised.
1686 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001687 result = conf.lib.clang_getElementType(self)
Gregory Szorc86057602012-02-17 07:44:46 +00001688 if result.kind == TypeKind.INVALID:
1689 raise Exception('Element type not available on this type.')
1690
1691 return result
1692
Gregory Szorcbf8ca002012-02-17 07:47:38 +00001693 @property
1694 def element_count(self):
1695 """Retrieve the number of elements in this type.
1696
1697 Returns an int.
1698
1699 If the Type is not an array or vector, this raises.
1700 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001701 result = conf.lib.clang_getNumElements(self)
Gregory Szorcbf8ca002012-02-17 07:47:38 +00001702 if result < 0:
1703 raise Exception('Type does not have elements.')
1704
1705 return result
1706
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001707 @property
1708 def translation_unit(self):
1709 """The TranslationUnit to which this Type is associated."""
1710 # If this triggers an AttributeError, the instance was not properly
1711 # instantiated.
1712 return self._tu
1713
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001714 @staticmethod
1715 def from_result(res, fn, args):
1716 assert isinstance(res, Type)
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001717
1718 tu = None
1719 for arg in args:
1720 if hasattr(arg, 'translation_unit'):
1721 tu = arg.translation_unit
1722 break
1723
1724 assert tu is not None
1725 res._tu = tu
1726
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001727 return res
1728
1729 def get_canonical(self):
1730 """
1731 Return the canonical type for a Type.
1732
1733 Clang's type system explicitly models typedefs and all the
1734 ways a specific type can be represented. The canonical type
1735 is the underlying type with all the "sugar" removed. For
1736 example, if 'T' is a typedef for 'int', the canonical type for
1737 'T' would be 'int'.
1738 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001739 return conf.lib.clang_getCanonicalType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001740
1741 def is_const_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001742 """Determine whether a Type has the "const" qualifier set.
1743
1744 This does not look through typedefs that may have added "const"
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001745 at a different level.
1746 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001747 return conf.lib.clang_isConstQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001748
1749 def is_volatile_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001750 """Determine whether a Type has the "volatile" qualifier set.
1751
1752 This does not look through typedefs that may have added "volatile"
1753 at a different level.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001754 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001755 return conf.lib.clang_isVolatileQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001756
1757 def is_restrict_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001758 """Determine whether a Type has the "restrict" qualifier set.
1759
1760 This does not look through typedefs that may have added "restrict" at
1761 a different level.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001762 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001763 return conf.lib.clang_isRestrictQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001764
Gregory Szorc31cc38c2012-02-19 18:28:33 +00001765 def is_function_variadic(self):
1766 """Determine whether this function Type is a variadic function type."""
1767 assert self.kind == TypeKind.FUNCTIONPROTO
1768
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001769 return conf.lib.clang_isFunctionTypeVariadic(self)
Gregory Szorc31cc38c2012-02-19 18:28:33 +00001770
Gregory Szorc96ad6332012-02-05 19:42:06 +00001771 def is_pod(self):
1772 """Determine whether this Type represents plain old data (POD)."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001773 return conf.lib.clang_isPODType(self)
Gregory Szorc96ad6332012-02-05 19:42:06 +00001774
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001775 def get_pointee(self):
1776 """
1777 For pointer types, returns the type of the pointee.
1778 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001779 return conf.lib.clang_getPointeeType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001780
1781 def get_declaration(self):
1782 """
1783 Return the cursor for the declaration of the given type.
1784 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001785 return conf.lib.clang_getTypeDeclaration(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001786
1787 def get_result(self):
1788 """
1789 Retrieve the result type associated with a function type.
1790 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001791 return conf.lib.clang_getResultType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001792
Douglas Gregor13102ff2011-10-19 05:51:43 +00001793 def get_array_element_type(self):
1794 """
1795 Retrieve the type of the elements of the array type.
1796 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001797 return conf.lib.clang_getArrayElementType(self)
Douglas Gregor13102ff2011-10-19 05:51:43 +00001798
1799 def get_array_size(self):
1800 """
1801 Retrieve the size of the constant array.
1802 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001803 return conf.lib.clang_getArraySize(self)
Douglas Gregor13102ff2011-10-19 05:51:43 +00001804
Argyrios Kyrtzidis367e8fe2013-10-03 16:19:23 +00001805 def get_class_type(self):
1806 """
1807 Retrieve the class type of the member pointer type.
1808 """
1809 return conf.lib.clang_Type_getClassType(self)
1810
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00001811 def get_align(self):
1812 """
1813 Retrieve the alignment of the record.
1814 """
1815 return conf.lib.clang_Type_getAlignOf(self)
1816
1817 def get_size(self):
1818 """
1819 Retrieve the size of the record.
1820 """
1821 return conf.lib.clang_Type_getSizeOf(self)
1822
1823 def get_offset(self, fieldname):
1824 """
1825 Retrieve the offset of a field in the record.
1826 """
1827 return conf.lib.clang_Type_getOffsetOf(self, c_char_p(fieldname))
1828
Argyrios Kyrtzidis659837e2013-10-11 19:58:38 +00001829 def get_ref_qualifier(self):
1830 """
1831 Retrieve the ref-qualifier of the type.
1832 """
1833 return RefQualifierKind.from_id(
1834 conf.lib.clang_Type_getCXXRefQualifier(self))
1835
Argyrios Kyrtzidisc23cb2d2013-10-03 16:19:27 +00001836 @property
1837 def spelling(self):
1838 """Retrieve the spelling of this Type."""
1839 return conf.lib.clang_getTypeSpelling(self)
1840
Gregory Szorc7eb691a2012-02-20 17:44:49 +00001841 def __eq__(self, other):
1842 if type(other) != type(self):
1843 return False
1844
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001845 return conf.lib.clang_equalTypes(self, other)
Gregory Szorc7eb691a2012-02-20 17:44:49 +00001846
1847 def __ne__(self, other):
1848 return not self.__eq__(other)
1849
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001850## CIndex Objects ##
1851
1852# CIndex objects (derived from ClangObject) are essentially lightweight
1853# wrappers attached to some underlying object, which is exposed via CIndex as
1854# a void*.
1855
1856class ClangObject(object):
1857 """
1858 A helper for Clang objects. This class helps act as an intermediary for
1859 the ctypes library and the Clang CIndex library.
1860 """
1861 def __init__(self, obj):
1862 assert isinstance(obj, c_object_p) and obj
1863 self.obj = self._as_parameter_ = obj
1864
1865 def from_param(self):
1866 return self._as_parameter_
1867
Daniel Dunbar5b534f62010-01-25 00:44:11 +00001868
1869class _CXUnsavedFile(Structure):
1870 """Helper for passing unsaved file arguments."""
1871 _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
1872
Tobias Grosser69a85522013-01-19 11:03:44 +00001873# Functions calls through the python interface are rather slow. Fortunately,
1874# for most symboles, we do not need to perform a function call. Their spelling
1875# never changes and is consequently provided by this spelling cache.
1876SpellingCache = {
1877 # 0: CompletionChunk.Kind("Optional"),
1878 # 1: CompletionChunk.Kind("TypedText"),
1879 # 2: CompletionChunk.Kind("Text"),
1880 # 3: CompletionChunk.Kind("Placeholder"),
1881 # 4: CompletionChunk.Kind("Informative"),
1882 # 5 : CompletionChunk.Kind("CurrentParameter"),
1883 6: '(', # CompletionChunk.Kind("LeftParen"),
1884 7: ')', # CompletionChunk.Kind("RightParen"),
Stephen Hines651f13c2014-04-23 16:59:28 -07001885 8: '[', # CompletionChunk.Kind("LeftBracket"),
Tobias Grosser69a85522013-01-19 11:03:44 +00001886 9: ']', # CompletionChunk.Kind("RightBracket"),
1887 10: '{', # CompletionChunk.Kind("LeftBrace"),
1888 11: '}', # CompletionChunk.Kind("RightBrace"),
1889 12: '<', # CompletionChunk.Kind("LeftAngle"),
1890 13: '>', # CompletionChunk.Kind("RightAngle"),
1891 14: ', ', # CompletionChunk.Kind("Comma"),
1892 # 15: CompletionChunk.Kind("ResultType"),
1893 16: ':', # CompletionChunk.Kind("Colon"),
1894 17: ';', # CompletionChunk.Kind("SemiColon"),
1895 18: '=', # CompletionChunk.Kind("Equal"),
1896 19: ' ', # CompletionChunk.Kind("HorizontalSpace"),
1897 # 20: CompletionChunk.Kind("VerticalSpace")
1898}
1899
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001900class CompletionChunk:
1901 class Kind:
1902 def __init__(self, name):
1903 self.name = name
1904
1905 def __str__(self):
1906 return self.name
1907
1908 def __repr__(self):
1909 return "<ChunkKind: %s>" % self
1910
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001911 def __init__(self, completionString, key):
1912 self.cs = completionString
1913 self.key = key
Tobias Grossereca36d12013-01-19 11:03:42 +00001914 self.__kindNumberCache = -1
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001915
1916 def __repr__(self):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001917 return "{'" + self.spelling + "', " + str(self.kind) + "}"
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001918
Tobias Grosserd9ee06b2012-08-19 22:26:15 +00001919 @CachedProperty
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001920 def spelling(self):
Tobias Grosserbba99ad2013-01-20 00:42:16 +00001921 if self.__kindNumber in SpellingCache:
1922 return SpellingCache[self.__kindNumber]
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001923 return conf.lib.clang_getCompletionChunkText(self.cs, self.key).spelling
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001924
Tobias Grossereca36d12013-01-19 11:03:42 +00001925 # We do not use @CachedProperty here, as the manual implementation is
1926 # apparently still significantly faster. Please profile carefully if you
1927 # would like to add CachedProperty back.
1928 @property
Tobias Grossere43d3862013-01-19 11:03:40 +00001929 def __kindNumber(self):
Tobias Grossereca36d12013-01-19 11:03:42 +00001930 if self.__kindNumberCache == -1:
1931 self.__kindNumberCache = \
Tobias Grosserbba99ad2013-01-20 00:42:16 +00001932 conf.lib.clang_getCompletionChunkKind(self.cs, self.key)
Tobias Grossereca36d12013-01-19 11:03:42 +00001933 return self.__kindNumberCache
Tobias Grossere43d3862013-01-19 11:03:40 +00001934
1935 @CachedProperty
1936 def kind(self):
1937 return completionChunkKindMap[self.__kindNumber]
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001938
Tobias Grosserd9ee06b2012-08-19 22:26:15 +00001939 @CachedProperty
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001940 def string(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001941 res = conf.lib.clang_getCompletionChunkCompletionString(self.cs,
1942 self.key)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001943
1944 if (res):
1945 return CompletionString(res)
1946 else:
1947 None
1948
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001949 def isKindOptional(self):
Tobias Grossere43d3862013-01-19 11:03:40 +00001950 return self.__kindNumber == 0
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001951
1952 def isKindTypedText(self):
Tobias Grossere43d3862013-01-19 11:03:40 +00001953 return self.__kindNumber == 1
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001954
1955 def isKindPlaceHolder(self):
Tobias Grossere43d3862013-01-19 11:03:40 +00001956 return self.__kindNumber == 3
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001957
1958 def isKindInformative(self):
Tobias Grossere43d3862013-01-19 11:03:40 +00001959 return self.__kindNumber == 4
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001960
1961 def isKindResultType(self):
Tobias Grossere43d3862013-01-19 11:03:40 +00001962 return self.__kindNumber == 15
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001963
1964completionChunkKindMap = {
1965 0: CompletionChunk.Kind("Optional"),
1966 1: CompletionChunk.Kind("TypedText"),
1967 2: CompletionChunk.Kind("Text"),
1968 3: CompletionChunk.Kind("Placeholder"),
1969 4: CompletionChunk.Kind("Informative"),
1970 5: CompletionChunk.Kind("CurrentParameter"),
1971 6: CompletionChunk.Kind("LeftParen"),
1972 7: CompletionChunk.Kind("RightParen"),
1973 8: CompletionChunk.Kind("LeftBracket"),
1974 9: CompletionChunk.Kind("RightBracket"),
1975 10: CompletionChunk.Kind("LeftBrace"),
1976 11: CompletionChunk.Kind("RightBrace"),
1977 12: CompletionChunk.Kind("LeftAngle"),
1978 13: CompletionChunk.Kind("RightAngle"),
1979 14: CompletionChunk.Kind("Comma"),
1980 15: CompletionChunk.Kind("ResultType"),
1981 16: CompletionChunk.Kind("Colon"),
1982 17: CompletionChunk.Kind("SemiColon"),
1983 18: CompletionChunk.Kind("Equal"),
1984 19: CompletionChunk.Kind("HorizontalSpace"),
1985 20: CompletionChunk.Kind("VerticalSpace")}
1986
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001987class CompletionString(ClangObject):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001988 class Availability:
1989 def __init__(self, name):
1990 self.name = name
1991
1992 def __str__(self):
1993 return self.name
1994
1995 def __repr__(self):
1996 return "<Availability: %s>" % self
1997
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001998 def __len__(self):
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001999 return self.num_chunks
Tobias Grosser147785b2012-08-20 10:38:16 +00002000
2001 @CachedProperty
2002 def num_chunks(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002003 return conf.lib.clang_getNumCompletionChunks(self.obj)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002004
2005 def __getitem__(self, key):
Tobias Grosser147785b2012-08-20 10:38:16 +00002006 if self.num_chunks <= key:
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002007 raise IndexError
Tobias Grossera87dbcc2011-02-05 17:54:10 +00002008 return CompletionChunk(self.obj, key)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002009
2010 @property
2011 def priority(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002012 return conf.lib.clang_getCompletionPriority(self.obj)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002013
2014 @property
2015 def availability(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002016 res = conf.lib.clang_getCompletionAvailability(self.obj)
Tobias Grossera87dbcc2011-02-05 17:54:10 +00002017 return availabilityKinds[res]
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002018
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002019 @property
2020 def briefComment(self):
Dmitri Gribenkoc12d6a02012-09-22 17:52:29 +00002021 if conf.function_exists("clang_getCompletionBriefComment"):
2022 return conf.lib.clang_getCompletionBriefComment(self.obj)
2023 return _CXString()
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002024
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002025 def __repr__(self):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00002026 return " | ".join([str(a) for a in self]) \
2027 + " || Priority: " + str(self.priority) \
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002028 + " || Availability: " + str(self.availability) \
2029 + " || Brief comment: " + str(self.briefComment.spelling)
Tobias Grossera87dbcc2011-02-05 17:54:10 +00002030
2031availabilityKinds = {
2032 0: CompletionChunk.Kind("Available"),
2033 1: CompletionChunk.Kind("Deprecated"),
Benjamin Kramer724d0dc2012-10-07 11:46:37 +00002034 2: CompletionChunk.Kind("NotAvailable"),
2035 3: CompletionChunk.Kind("NotAccessible")}
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002036
Tobias Grosser0a166802011-02-05 17:54:04 +00002037class CodeCompletionResult(Structure):
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002038 _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
2039
2040 def __repr__(self):
2041 return str(CompletionString(self.completionString))
2042
2043 @property
2044 def kind(self):
2045 return CursorKind.from_id(self.cursorKind)
2046
2047 @property
2048 def string(self):
2049 return CompletionString(self.completionString)
Tobias Grosser0a166802011-02-05 17:54:04 +00002050
2051class CCRStructure(Structure):
2052 _fields_ = [('results', POINTER(CodeCompletionResult)),
2053 ('numResults', c_int)]
2054
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002055 def __len__(self):
2056 return self.numResults
2057
2058 def __getitem__(self, key):
2059 if len(self) <= key:
2060 raise IndexError
2061
2062 return self.results[key]
2063
Tobias Grosser0a166802011-02-05 17:54:04 +00002064class CodeCompletionResults(ClangObject):
2065 def __init__(self, ptr):
2066 assert isinstance(ptr, POINTER(CCRStructure)) and ptr
2067 self.ptr = self._as_parameter_ = ptr
2068
2069 def from_param(self):
2070 return self._as_parameter_
2071
2072 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002073 conf.lib.clang_disposeCodeCompleteResults(self)
Tobias Grosser0a166802011-02-05 17:54:04 +00002074
2075 @property
2076 def results(self):
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002077 return self.ptr.contents
Tobias Grosser0a166802011-02-05 17:54:04 +00002078
2079 @property
2080 def diagnostics(self):
2081 class DiagnosticsItr:
2082 def __init__(self, ccr):
2083 self.ccr= ccr
2084
2085 def __len__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002086 return int(\
2087 conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr))
Tobias Grosser0a166802011-02-05 17:54:04 +00002088
2089 def __getitem__(self, key):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002090 return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key)
Tobias Grosser0a166802011-02-05 17:54:04 +00002091
2092 return DiagnosticsItr(self)
2093
2094
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002095class Index(ClangObject):
2096 """
2097 The Index type provides the primary interface to the Clang CIndex library,
2098 primarily by providing an interface for reading and parsing translation
2099 units.
2100 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002101
2102 @staticmethod
Daniel Dunbar2791dfc2010-01-30 23:58:39 +00002103 def create(excludeDecls=False):
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002104 """
2105 Create a new Index.
2106 Parameters:
2107 excludeDecls -- Exclude local declarations from translation units.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002108 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002109 return Index(conf.lib.clang_createIndex(excludeDecls, 0))
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002110
2111 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002112 conf.lib.clang_disposeIndex(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002113
2114 def read(self, path):
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002115 """Load a TranslationUnit from the given AST file."""
Argyrios Kyrtzidisda6a6f02013-06-11 18:05:42 +00002116 return TranslationUnit.from_ast_file(path, self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002117
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002118 def parse(self, path, args=None, unsaved_files=None, options = 0):
2119 """Load the translation unit from the given source code file by running
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002120 clang and generating the AST before loading. Additional command line
2121 parameters can be passed to clang via the args parameter.
Daniel Dunbar5b534f62010-01-25 00:44:11 +00002122
2123 In-memory contents for files can be provided by passing a list of pairs
2124 to as unsaved_files, the first item should be the filenames to be mapped
2125 and the second should be the contents to be substituted for the
2126 file. The contents may be passed as strings or file objects.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002127
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002128 If an error was encountered during parsing, a TranslationUnitLoadError
2129 will be raised.
2130 """
2131 return TranslationUnit.from_source(path, args, unsaved_files, options,
2132 self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002133
2134class TranslationUnit(ClangObject):
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002135 """Represents a source code translation unit.
2136
2137 This is one of the main types in the API. Any time you wish to interact
2138 with Clang's representation of a source file, you typically start with a
2139 translation unit.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002140 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002141
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002142 # Default parsing mode.
2143 PARSE_NONE = 0
2144
2145 # Instruct the parser to create a detailed processing record containing
2146 # metadata not normally retained.
2147 PARSE_DETAILED_PROCESSING_RECORD = 1
2148
2149 # Indicates that the translation unit is incomplete. This is typically used
2150 # when parsing headers.
2151 PARSE_INCOMPLETE = 2
2152
2153 # Instruct the parser to create a pre-compiled preamble for the translation
2154 # unit. This caches the preamble (included files at top of source file).
2155 # This is useful if the translation unit will be reparsed and you don't
2156 # want to incur the overhead of reparsing the preamble.
2157 PARSE_PRECOMPILED_PREAMBLE = 4
2158
2159 # Cache code completion information on parse. This adds time to parsing but
2160 # speeds up code completion.
2161 PARSE_CACHE_COMPLETION_RESULTS = 8
2162
2163 # Flags with values 16 and 32 are deprecated and intentionally omitted.
2164
2165 # Do not parse function bodies. This is useful if you only care about
2166 # searching for declarations/definitions.
2167 PARSE_SKIP_FUNCTION_BODIES = 64
2168
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002169 # Used to indicate that brief documentation comments should be included
2170 # into the set of code completions returned from this translation unit.
2171 PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128
2172
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002173 @classmethod
2174 def from_source(cls, filename, args=None, unsaved_files=None, options=0,
2175 index=None):
2176 """Create a TranslationUnit by parsing source.
2177
2178 This is capable of processing source code both from files on the
2179 filesystem as well as in-memory contents.
2180
2181 Command-line arguments that would be passed to clang are specified as
2182 a list via args. These can be used to specify include paths, warnings,
2183 etc. e.g. ["-Wall", "-I/path/to/include"].
2184
2185 In-memory file content can be provided via unsaved_files. This is an
2186 iterable of 2-tuples. The first element is the str filename. The
2187 second element defines the content. Content can be provided as str
2188 source code or as file objects (anything with a read() method). If
2189 a file object is being used, content will be read until EOF and the
2190 read cursor will not be reset to its original position.
2191
2192 options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
2193 control parsing behavior.
2194
Gregory Szorc2283b462012-05-12 20:49:13 +00002195 index is an Index instance to utilize. If not provided, a new Index
2196 will be created for this TranslationUnit.
2197
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002198 To parse source from the filesystem, the filename of the file to parse
2199 is specified by the filename argument. Or, filename could be None and
2200 the args list would contain the filename(s) to parse.
2201
2202 To parse source from an in-memory buffer, set filename to the virtual
2203 filename you wish to associate with this source (e.g. "test.c"). The
2204 contents of that file are then provided in unsaved_files.
2205
2206 If an error occurs, a TranslationUnitLoadError is raised.
2207
2208 Please note that a TranslationUnit with parser errors may be returned.
2209 It is the caller's responsibility to check tu.diagnostics for errors.
2210
2211 Also note that Clang infers the source language from the extension of
2212 the input filename. If you pass in source code containing a C++ class
2213 declaration with the filename "test.c" parsing will fail.
2214 """
2215 if args is None:
2216 args = []
2217
2218 if unsaved_files is None:
2219 unsaved_files = []
2220
2221 if index is None:
2222 index = Index.create()
2223
2224 args_array = None
2225 if len(args) > 0:
2226 args_array = (c_char_p * len(args))(* args)
2227
2228 unsaved_array = None
2229 if len(unsaved_files) > 0:
2230 unsaved_array = (_CXUnsavedFile * len(unsaved_files))()
2231 for i, (name, contents) in enumerate(unsaved_files):
2232 if hasattr(contents, "read"):
2233 contents = contents.read()
2234
2235 unsaved_array[i].name = name
2236 unsaved_array[i].contents = contents
2237 unsaved_array[i].length = len(contents)
2238
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002239 ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array,
Gregory Szorc9537e202012-07-12 04:56:46 +00002240 len(args), unsaved_array,
2241 len(unsaved_files), options)
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002242
Tobias Grosser11d6cd32013-03-19 15:30:48 +00002243 if not ptr:
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002244 raise TranslationUnitLoadError("Error parsing translation unit.")
2245
2246 return cls(ptr, index=index)
2247
2248 @classmethod
2249 def from_ast_file(cls, filename, index=None):
2250 """Create a TranslationUnit instance from a saved AST file.
2251
2252 A previously-saved AST file (provided with -emit-ast or
2253 TranslationUnit.save()) is loaded from the filename specified.
2254
2255 If the file cannot be loaded, a TranslationUnitLoadError will be
2256 raised.
2257
2258 index is optional and is the Index instance to use. If not provided,
2259 a default Index will be created.
2260 """
2261 if index is None:
2262 index = Index.create()
2263
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002264 ptr = conf.lib.clang_createTranslationUnit(index, filename)
Tobias Grosser11d6cd32013-03-19 15:30:48 +00002265 if not ptr:
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002266 raise TranslationUnitLoadError(filename)
2267
2268 return cls(ptr=ptr, index=index)
2269
2270 def __init__(self, ptr, index):
2271 """Create a TranslationUnit instance.
2272
2273 TranslationUnits should be created using one of the from_* @classmethod
2274 functions above. __init__ is only called internally.
2275 """
2276 assert isinstance(index, Index)
2277
Daniel Dunbar532fc632010-01-30 23:59:02 +00002278 ClangObject.__init__(self, ptr)
Daniel Dunbar532fc632010-01-30 23:59:02 +00002279
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002280 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002281 conf.lib.clang_disposeTranslationUnit(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002282
Daniel Dunbar1b945a72010-01-24 04:09:43 +00002283 @property
2284 def cursor(self):
2285 """Retrieve the cursor that represents the given translation unit."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002286 return conf.lib.clang_getTranslationUnitCursor(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002287
2288 @property
2289 def spelling(self):
Daniel Dunbar1b945a72010-01-24 04:09:43 +00002290 """Get the original translation unit source file name."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002291 return conf.lib.clang_getTranslationUnitSpelling(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002292
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002293 def get_includes(self):
2294 """
2295 Return an iterable sequence of FileInclusion objects that describe the
2296 sequence of inclusions in a translation unit. The first object in
2297 this sequence is always the input file. Note that this method will not
2298 recursively iterate over header files included through precompiled
2299 headers.
2300 """
2301 def visitor(fobj, lptr, depth, includes):
Douglas Gregor8be80e12011-07-06 03:00:34 +00002302 if depth > 0:
2303 loc = lptr.contents
2304 includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002305
2306 # Automatically adapt CIndex/ctype pointers to python objects
2307 includes = []
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002308 conf.lib.clang_getInclusions(self,
Gregory Szorc9537e202012-07-12 04:56:46 +00002309 callbacks['translation_unit_includes'](visitor), includes)
2310
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002311 return iter(includes)
2312
Gregory Szorc0f1964a2012-07-12 05:05:56 +00002313 def get_file(self, filename):
2314 """Obtain a File from this translation unit."""
2315
2316 return File.from_name(self, filename)
2317
2318 def get_location(self, filename, position):
2319 """Obtain a SourceLocation for a file in this translation unit.
2320
2321 The position can be specified by passing:
2322
2323 - Integer file offset. Initial file offset is 0.
2324 - 2-tuple of (line number, column number). Initial file position is
2325 (0, 0)
2326 """
2327 f = self.get_file(filename)
2328
2329 if isinstance(position, int):
2330 return SourceLocation.from_offset(self, f, position)
2331
2332 return SourceLocation.from_position(self, f, position[0], position[1])
2333
2334 def get_extent(self, filename, locations):
2335 """Obtain a SourceRange from this translation unit.
2336
2337 The bounds of the SourceRange must ultimately be defined by a start and
2338 end SourceLocation. For the locations argument, you can pass:
2339
2340 - 2 SourceLocation instances in a 2-tuple or list.
2341 - 2 int file offsets via a 2-tuple or list.
2342 - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
2343
2344 e.g.
2345
2346 get_extent('foo.c', (5, 10))
2347 get_extent('foo.c', ((1, 1), (1, 15)))
2348 """
2349 f = self.get_file(filename)
2350
2351 if len(locations) < 2:
2352 raise Exception('Must pass object with at least 2 elements')
2353
2354 start_location, end_location = locations
2355
2356 if hasattr(start_location, '__len__'):
2357 start_location = SourceLocation.from_position(self, f,
2358 start_location[0], start_location[1])
2359 elif isinstance(start_location, int):
2360 start_location = SourceLocation.from_offset(self, f,
2361 start_location)
2362
2363 if hasattr(end_location, '__len__'):
2364 end_location = SourceLocation.from_position(self, f,
2365 end_location[0], end_location[1])
2366 elif isinstance(end_location, int):
2367 end_location = SourceLocation.from_offset(self, f, end_location)
2368
2369 assert isinstance(start_location, SourceLocation)
2370 assert isinstance(end_location, SourceLocation)
2371
2372 return SourceRange.from_locations(start_location, end_location)
2373
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002374 @property
2375 def diagnostics(self):
2376 """
2377 Return an iterable (and indexable) object containing the diagnostics.
2378 """
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00002379 class DiagIterator:
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002380 def __init__(self, tu):
2381 self.tu = tu
2382
2383 def __len__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002384 return int(conf.lib.clang_getNumDiagnostics(self.tu))
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002385
2386 def __getitem__(self, key):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002387 diag = conf.lib.clang_getDiagnostic(self.tu, key)
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00002388 if not diag:
2389 raise IndexError
2390 return Diagnostic(diag)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002391
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00002392 return DiagIterator(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002393
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002394 def reparse(self, unsaved_files=None, options=0):
Tobias Grosser265e6b22011-02-05 17:54:00 +00002395 """
2396 Reparse an already parsed translation unit.
2397
2398 In-memory contents for files can be provided by passing a list of pairs
2399 as unsaved_files, the first items should be the filenames to be mapped
2400 and the second should be the contents to be substituted for the
2401 file. The contents may be passed as strings or file objects.
2402 """
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002403 if unsaved_files is None:
2404 unsaved_files = []
2405
Tobias Grosser265e6b22011-02-05 17:54:00 +00002406 unsaved_files_array = 0
2407 if len(unsaved_files):
2408 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
2409 for i,(name,value) in enumerate(unsaved_files):
2410 if not isinstance(value, str):
2411 # FIXME: It would be great to support an efficient version
2412 # of this, one day.
2413 value = value.read()
2414 print value
2415 if not isinstance(value, str):
2416 raise TypeError,'Unexpected unsaved file contents.'
2417 unsaved_files_array[i].name = name
2418 unsaved_files_array[i].contents = value
2419 unsaved_files_array[i].length = len(value)
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002420 ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
Gregory Szorc9537e202012-07-12 04:56:46 +00002421 unsaved_files_array, options)
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002422
2423 def save(self, filename):
2424 """Saves the TranslationUnit to a file.
2425
2426 This is equivalent to passing -emit-ast to the clang frontend. The
2427 saved file can be loaded back into a TranslationUnit. Or, if it
2428 corresponds to a header, it can be used as a pre-compiled header file.
2429
2430 If an error occurs while saving, a TranslationUnitSaveError is raised.
2431 If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
2432 the constructed TranslationUnit was not valid at time of save. In this
2433 case, the reason(s) why should be available via
2434 TranslationUnit.diagnostics().
2435
2436 filename -- The path to save the translation unit to.
2437 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002438 options = conf.lib.clang_defaultSaveOptions(self)
2439 result = int(conf.lib.clang_saveTranslationUnit(self, filename,
2440 options))
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002441 if result != 0:
2442 raise TranslationUnitSaveError(result,
2443 'Error saving TranslationUnit.')
2444
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002445 def codeComplete(self, path, line, column, unsaved_files=None,
2446 include_macros=False, include_code_patterns=False,
2447 include_brief_comments=False):
Tobias Grosser0a166802011-02-05 17:54:04 +00002448 """
2449 Code complete in this translation unit.
2450
2451 In-memory contents for files can be provided by passing a list of pairs
2452 as unsaved_files, the first items should be the filenames to be mapped
2453 and the second should be the contents to be substituted for the
2454 file. The contents may be passed as strings or file objects.
2455 """
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002456 options = 0
2457
2458 if include_macros:
2459 options += 1
2460
2461 if include_code_patterns:
2462 options += 2
2463
2464 if include_brief_comments:
2465 options += 4
2466
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002467 if unsaved_files is None:
2468 unsaved_files = []
2469
Tobias Grosser0a166802011-02-05 17:54:04 +00002470 unsaved_files_array = 0
2471 if len(unsaved_files):
2472 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
2473 for i,(name,value) in enumerate(unsaved_files):
2474 if not isinstance(value, str):
2475 # FIXME: It would be great to support an efficient version
2476 # of this, one day.
2477 value = value.read()
2478 print value
2479 if not isinstance(value, str):
2480 raise TypeError,'Unexpected unsaved file contents.'
2481 unsaved_files_array[i].name = name
2482 unsaved_files_array[i].contents = value
2483 unsaved_files_array[i].length = len(value)
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002484 ptr = conf.lib.clang_codeCompleteAt(self, path, line, column,
Gregory Szorc9537e202012-07-12 04:56:46 +00002485 unsaved_files_array, len(unsaved_files), options)
Tobias Grosserba5d10b2011-10-31 02:06:50 +00002486 if ptr:
2487 return CodeCompletionResults(ptr)
2488 return None
Tobias Grosser265e6b22011-02-05 17:54:00 +00002489
Gregory Szorcbe51e432012-07-12 07:21:12 +00002490 def get_tokens(self, locations=None, extent=None):
2491 """Obtain tokens in this translation unit.
2492
2493 This is a generator for Token instances. The caller specifies a range
2494 of source code to obtain tokens for. The range can be specified as a
2495 2-tuple of SourceLocation or as a SourceRange. If both are defined,
2496 behavior is undefined.
2497 """
2498 if locations is not None:
2499 extent = SourceRange(start=locations[0], end=locations[1])
2500
2501 return TokenGroup.get_tokens(self, extent)
2502
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002503class File(ClangObject):
2504 """
Daniel Dunbar7b48b352010-01-24 04:09:34 +00002505 The File class represents a particular source file that is part of a
2506 translation unit.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002507 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002508
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002509 @staticmethod
2510 def from_name(translation_unit, file_name):
2511 """Retrieve a file handle within the given translation unit."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002512 return File(conf.lib.clang_getFile(translation_unit, file_name))
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002513
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002514 @property
2515 def name(self):
Daniel Dunbar4efd6322010-01-25 00:43:08 +00002516 """Return the complete file and path name of the file."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002517 return conf.lib.clang_getCString(conf.lib.clang_getFileName(self))
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002518
2519 @property
2520 def time(self):
Daniel Dunbar4efd6322010-01-25 00:43:08 +00002521 """Return the last modification time of the file."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002522 return conf.lib.clang_getFileTime(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002523
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002524 def __str__(self):
2525 return self.name
2526
2527 def __repr__(self):
2528 return "<File: %s>" % (self.name)
2529
Gregory Szorc9537e202012-07-12 04:56:46 +00002530 @staticmethod
2531 def from_cursor_result(res, fn, args):
2532 assert isinstance(res, File)
2533
2534 # Copy a reference to the TranslationUnit to prevent premature GC.
2535 res._tu = args[0]._tu
2536 return res
2537
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002538class FileInclusion(object):
2539 """
2540 The FileInclusion class represents the inclusion of one source file by
2541 another via a '#include' directive or as the input file for the translation
2542 unit. This class provides information about the included file, the including
2543 file, the location of the '#include' directive and the depth of the included
2544 file in the stack. Note that the input file has depth 0.
2545 """
2546
2547 def __init__(self, src, tgt, loc, depth):
2548 self.source = src
2549 self.include = tgt
2550 self.location = loc
2551 self.depth = depth
2552
2553 @property
2554 def is_input_file(self):
2555 """True if the included file is the input file."""
2556 return self.depth == 0
2557
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002558class CompilationDatabaseError(Exception):
2559 """Represents an error that occurred when working with a CompilationDatabase
2560
2561 Each error is associated to an enumerated value, accessible under
2562 e.cdb_error. Consumers can compare the value with one of the ERROR_
2563 constants in this class.
2564 """
2565
Stephen Hines651f13c2014-04-23 16:59:28 -07002566 # An unknown error occurred
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002567 ERROR_UNKNOWN = 0
2568
2569 # The database could not be loaded
2570 ERROR_CANNOTLOADDATABASE = 1
2571
2572 def __init__(self, enumeration, message):
2573 assert isinstance(enumeration, int)
2574
2575 if enumeration > 1:
2576 raise Exception("Encountered undefined CompilationDatabase error "
2577 "constant: %d. Please file a bug to have this "
2578 "value supported." % enumeration)
2579
2580 self.cdb_error = enumeration
2581 Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
2582
2583class CompileCommand(object):
2584 """Represents the compile command used to build a file"""
2585 def __init__(self, cmd, ccmds):
2586 self.cmd = cmd
2587 # Keep a reference to the originating CompileCommands
2588 # to prevent garbage collection
2589 self.ccmds = ccmds
2590
2591 @property
2592 def directory(self):
2593 """Get the working directory for this CompileCommand"""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002594 return conf.lib.clang_CompileCommand_getDirectory(self.cmd)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002595
2596 @property
2597 def arguments(self):
2598 """
2599 Get an iterable object providing each argument in the
2600 command line for the compiler invocation as a _CXString.
2601
Arnaud A. de Grandmaison577c5302012-07-06 08:22:05 +00002602 Invariant : the first argument is the compiler executable
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002603 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002604 length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002605 for i in xrange(length):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002606 yield conf.lib.clang_CompileCommand_getArg(self.cmd, i)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002607
2608class CompileCommands(object):
2609 """
2610 CompileCommands is an iterable object containing all CompileCommand
2611 that can be used for building a specific file.
2612 """
2613 def __init__(self, ccmds):
2614 self.ccmds = ccmds
2615
2616 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002617 conf.lib.clang_CompileCommands_dispose(self.ccmds)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002618
2619 def __len__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002620 return int(conf.lib.clang_CompileCommands_getSize(self.ccmds))
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002621
2622 def __getitem__(self, i):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002623 cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i)
Arnaud A. de Grandmaisonb1614042012-07-09 11:57:30 +00002624 if not cc:
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002625 raise IndexError
2626 return CompileCommand(cc, self)
2627
2628 @staticmethod
2629 def from_result(res, fn, args):
2630 if not res:
2631 return None
2632 return CompileCommands(res)
2633
2634class CompilationDatabase(ClangObject):
2635 """
2636 The CompilationDatabase is a wrapper class around
2637 clang::tooling::CompilationDatabase
2638
2639 It enables querying how a specific source file can be built.
2640 """
2641
2642 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002643 conf.lib.clang_CompilationDatabase_dispose(self)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002644
2645 @staticmethod
2646 def from_result(res, fn, args):
2647 if not res:
2648 raise CompilationDatabaseError(0,
2649 "CompilationDatabase loading failed")
2650 return CompilationDatabase(res)
2651
2652 @staticmethod
2653 def fromDirectory(buildDir):
2654 """Builds a CompilationDatabase from the database found in buildDir"""
2655 errorCode = c_uint()
2656 try:
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002657 cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
Gregory Szorc9537e202012-07-12 04:56:46 +00002658 byref(errorCode))
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002659 except CompilationDatabaseError as e:
Gregory Szorc9537e202012-07-12 04:56:46 +00002660 raise CompilationDatabaseError(int(errorCode.value),
2661 "CompilationDatabase loading failed")
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002662 return cdb
2663
2664 def getCompileCommands(self, filename):
2665 """
2666 Get an iterable object providing all the CompileCommands available to
Arnaud A. de Grandmaison44394782012-06-30 20:43:37 +00002667 build filename. Returns None if filename is not found in the database.
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002668 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002669 return conf.lib.clang_CompilationDatabase_getCompileCommands(self,
2670 filename)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002671
Stephen Hines651f13c2014-04-23 16:59:28 -07002672 def getAllCompileCommands(self):
2673 """
2674 Get an iterable object providing all the CompileCommands available from
2675 the database.
2676 """
2677 return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self)
2678
2679
Gregory Szorcbe51e432012-07-12 07:21:12 +00002680class Token(Structure):
2681 """Represents a single token from the preprocessor.
2682
2683 Tokens are effectively segments of source code. Source code is first parsed
2684 into tokens before being converted into the AST and Cursors.
2685
2686 Tokens are obtained from parsed TranslationUnit instances. You currently
2687 can't create tokens manually.
2688 """
2689 _fields_ = [
2690 ('int_data', c_uint * 4),
2691 ('ptr_data', c_void_p)
2692 ]
2693
2694 @property
2695 def spelling(self):
2696 """The spelling of this token.
2697
2698 This is the textual representation of the token in source.
2699 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002700 return conf.lib.clang_getTokenSpelling(self._tu, self)
Gregory Szorcbe51e432012-07-12 07:21:12 +00002701
2702 @property
2703 def kind(self):
2704 """Obtain the TokenKind of the current token."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002705 return TokenKind.from_value(conf.lib.clang_getTokenKind(self))
Gregory Szorcbe51e432012-07-12 07:21:12 +00002706
2707 @property
2708 def location(self):
2709 """The SourceLocation this Token occurs at."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002710 return conf.lib.clang_getTokenLocation(self._tu, self)
Gregory Szorcbe51e432012-07-12 07:21:12 +00002711
2712 @property
2713 def extent(self):
2714 """The SourceRange this Token occupies."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002715 return conf.lib.clang_getTokenExtent(self._tu, self)
Gregory Szorcbe51e432012-07-12 07:21:12 +00002716
2717 @property
2718 def cursor(self):
2719 """The Cursor this Token corresponds to."""
2720 cursor = Cursor()
2721
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002722 conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
Gregory Szorcbe51e432012-07-12 07:21:12 +00002723
2724 return cursor
2725
Gregory Szorc9537e202012-07-12 04:56:46 +00002726# Now comes the plumbing to hook up the C library.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002727
Gregory Szorc9537e202012-07-12 04:56:46 +00002728# Register callback types in common container.
2729callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p,
2730 POINTER(SourceLocation), c_uint, py_object)
2731callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
Daniel Dunbara33dca42010-01-24 21:19:57 +00002732
Tobias Grosser010556e2012-09-01 08:55:17 +00002733# Functions strictly alphabetical order.
2734functionList = [
2735 ("clang_annotateTokens",
2736 [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]),
2737
2738 ("clang_CompilationDatabase_dispose",
2739 [c_object_p]),
2740
2741 ("clang_CompilationDatabase_fromDirectory",
2742 [c_char_p, POINTER(c_uint)],
2743 c_object_p,
2744 CompilationDatabase.from_result),
2745
Stephen Hines651f13c2014-04-23 16:59:28 -07002746 ("clang_CompilationDatabase_getAllCompileCommands",
2747 [c_object_p],
2748 c_object_p,
2749 CompileCommands.from_result),
2750
Tobias Grosser010556e2012-09-01 08:55:17 +00002751 ("clang_CompilationDatabase_getCompileCommands",
2752 [c_object_p, c_char_p],
2753 c_object_p,
2754 CompileCommands.from_result),
2755
2756 ("clang_CompileCommands_dispose",
2757 [c_object_p]),
2758
2759 ("clang_CompileCommands_getCommand",
2760 [c_object_p, c_uint],
2761 c_object_p),
2762
2763 ("clang_CompileCommands_getSize",
2764 [c_object_p],
2765 c_uint),
2766
2767 ("clang_CompileCommand_getArg",
2768 [c_object_p, c_uint],
2769 _CXString,
2770 _CXString.from_result),
2771
2772 ("clang_CompileCommand_getDirectory",
2773 [c_object_p],
2774 _CXString,
2775 _CXString.from_result),
2776
2777 ("clang_CompileCommand_getNumArgs",
2778 [c_object_p],
2779 c_uint),
2780
2781 ("clang_codeCompleteAt",
2782 [TranslationUnit, c_char_p, c_int, c_int, c_void_p, c_int, c_int],
2783 POINTER(CCRStructure)),
2784
2785 ("clang_codeCompleteGetDiagnostic",
2786 [CodeCompletionResults, c_int],
2787 Diagnostic),
2788
2789 ("clang_codeCompleteGetNumDiagnostics",
2790 [CodeCompletionResults],
2791 c_int),
2792
2793 ("clang_createIndex",
2794 [c_int, c_int],
2795 c_object_p),
2796
2797 ("clang_createTranslationUnit",
2798 [Index, c_char_p],
2799 c_object_p),
2800
Dmitri Gribenkoc965f762013-05-17 18:38:35 +00002801 ("clang_CXXMethod_isPureVirtual",
2802 [Cursor],
2803 bool),
2804
Tobias Grosser010556e2012-09-01 08:55:17 +00002805 ("clang_CXXMethod_isStatic",
2806 [Cursor],
2807 bool),
2808
2809 ("clang_CXXMethod_isVirtual",
2810 [Cursor],
2811 bool),
2812
2813 ("clang_defaultSaveOptions",
2814 [TranslationUnit],
2815 c_uint),
2816
2817 ("clang_disposeCodeCompleteResults",
2818 [CodeCompletionResults]),
2819
2820# ("clang_disposeCXTUResourceUsage",
2821# [CXTUResourceUsage]),
2822
2823 ("clang_disposeDiagnostic",
2824 [Diagnostic]),
2825
2826 ("clang_disposeIndex",
2827 [Index]),
2828
2829 ("clang_disposeString",
2830 [_CXString]),
2831
2832 ("clang_disposeTokens",
2833 [TranslationUnit, POINTER(Token), c_uint]),
2834
2835 ("clang_disposeTranslationUnit",
2836 [TranslationUnit]),
2837
2838 ("clang_equalCursors",
2839 [Cursor, Cursor],
2840 bool),
2841
2842 ("clang_equalLocations",
2843 [SourceLocation, SourceLocation],
2844 bool),
2845
2846 ("clang_equalRanges",
2847 [SourceRange, SourceRange],
2848 bool),
2849
2850 ("clang_equalTypes",
2851 [Type, Type],
2852 bool),
2853
2854 ("clang_getArgType",
2855 [Type, c_uint],
2856 Type,
2857 Type.from_result),
2858
2859 ("clang_getArrayElementType",
2860 [Type],
2861 Type,
2862 Type.from_result),
2863
2864 ("clang_getArraySize",
2865 [Type],
2866 c_longlong),
2867
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00002868 ("clang_getFieldDeclBitWidth",
2869 [Cursor],
2870 c_int),
2871
Tobias Grosser010556e2012-09-01 08:55:17 +00002872 ("clang_getCanonicalCursor",
2873 [Cursor],
2874 Cursor,
2875 Cursor.from_cursor_result),
2876
2877 ("clang_getCanonicalType",
2878 [Type],
2879 Type,
2880 Type.from_result),
2881
2882 ("clang_getCompletionAvailability",
2883 [c_void_p],
2884 c_int),
2885
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002886 ("clang_getCompletionBriefComment",
2887 [c_void_p],
2888 _CXString),
2889
Tobias Grosser010556e2012-09-01 08:55:17 +00002890 ("clang_getCompletionChunkCompletionString",
2891 [c_void_p, c_int],
2892 c_object_p),
2893
2894 ("clang_getCompletionChunkKind",
2895 [c_void_p, c_int],
2896 c_int),
2897
2898 ("clang_getCompletionChunkText",
2899 [c_void_p, c_int],
2900 _CXString),
2901
2902 ("clang_getCompletionPriority",
2903 [c_void_p],
2904 c_int),
2905
2906 ("clang_getCString",
2907 [_CXString],
2908 c_char_p),
2909
2910 ("clang_getCursor",
2911 [TranslationUnit, SourceLocation],
2912 Cursor),
2913
2914 ("clang_getCursorDefinition",
2915 [Cursor],
2916 Cursor,
2917 Cursor.from_result),
2918
2919 ("clang_getCursorDisplayName",
2920 [Cursor],
2921 _CXString,
2922 _CXString.from_result),
2923
2924 ("clang_getCursorExtent",
2925 [Cursor],
2926 SourceRange),
2927
2928 ("clang_getCursorLexicalParent",
2929 [Cursor],
2930 Cursor,
2931 Cursor.from_cursor_result),
2932
2933 ("clang_getCursorLocation",
2934 [Cursor],
2935 SourceLocation),
2936
2937 ("clang_getCursorReferenced",
2938 [Cursor],
2939 Cursor,
2940 Cursor.from_result),
2941
2942 ("clang_getCursorReferenceNameRange",
2943 [Cursor, c_uint, c_uint],
2944 SourceRange),
2945
2946 ("clang_getCursorSemanticParent",
2947 [Cursor],
2948 Cursor,
2949 Cursor.from_cursor_result),
2950
2951 ("clang_getCursorSpelling",
2952 [Cursor],
2953 _CXString,
2954 _CXString.from_result),
2955
2956 ("clang_getCursorType",
2957 [Cursor],
2958 Type,
2959 Type.from_result),
2960
2961 ("clang_getCursorUSR",
2962 [Cursor],
2963 _CXString,
2964 _CXString.from_result),
2965
2966# ("clang_getCXTUResourceUsage",
2967# [TranslationUnit],
2968# CXTUResourceUsage),
2969
2970 ("clang_getCXXAccessSpecifier",
2971 [Cursor],
2972 c_uint),
2973
2974 ("clang_getDeclObjCTypeEncoding",
2975 [Cursor],
2976 _CXString,
2977 _CXString.from_result),
2978
2979 ("clang_getDiagnostic",
2980 [c_object_p, c_uint],
2981 c_object_p),
2982
2983 ("clang_getDiagnosticCategory",
2984 [Diagnostic],
2985 c_uint),
2986
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002987 ("clang_getDiagnosticCategoryText",
2988 [Diagnostic],
Tobias Grosser010556e2012-09-01 08:55:17 +00002989 _CXString,
2990 _CXString.from_result),
2991
2992 ("clang_getDiagnosticFixIt",
2993 [Diagnostic, c_uint, POINTER(SourceRange)],
2994 _CXString,
2995 _CXString.from_result),
2996
2997 ("clang_getDiagnosticLocation",
2998 [Diagnostic],
2999 SourceLocation),
3000
3001 ("clang_getDiagnosticNumFixIts",
3002 [Diagnostic],
3003 c_uint),
3004
3005 ("clang_getDiagnosticNumRanges",
3006 [Diagnostic],
3007 c_uint),
3008
3009 ("clang_getDiagnosticOption",
3010 [Diagnostic, POINTER(_CXString)],
3011 _CXString,
3012 _CXString.from_result),
3013
3014 ("clang_getDiagnosticRange",
3015 [Diagnostic, c_uint],
3016 SourceRange),
3017
3018 ("clang_getDiagnosticSeverity",
3019 [Diagnostic],
3020 c_int),
3021
3022 ("clang_getDiagnosticSpelling",
3023 [Diagnostic],
3024 _CXString,
3025 _CXString.from_result),
3026
3027 ("clang_getElementType",
3028 [Type],
3029 Type,
3030 Type.from_result),
3031
3032 ("clang_getEnumConstantDeclUnsignedValue",
3033 [Cursor],
3034 c_ulonglong),
3035
3036 ("clang_getEnumConstantDeclValue",
3037 [Cursor],
3038 c_longlong),
3039
3040 ("clang_getEnumDeclIntegerType",
3041 [Cursor],
3042 Type,
3043 Type.from_result),
3044
3045 ("clang_getFile",
3046 [TranslationUnit, c_char_p],
3047 c_object_p),
3048
3049 ("clang_getFileName",
3050 [File],
3051 _CXString), # TODO go through _CXString.from_result?
3052
3053 ("clang_getFileTime",
3054 [File],
3055 c_uint),
3056
3057 ("clang_getIBOutletCollectionType",
3058 [Cursor],
3059 Type,
3060 Type.from_result),
3061
3062 ("clang_getIncludedFile",
3063 [Cursor],
3064 File,
3065 File.from_cursor_result),
3066
3067 ("clang_getInclusions",
3068 [TranslationUnit, callbacks['translation_unit_includes'], py_object]),
3069
3070 ("clang_getInstantiationLocation",
3071 [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint),
3072 POINTER(c_uint)]),
3073
3074 ("clang_getLocation",
3075 [TranslationUnit, File, c_uint, c_uint],
3076 SourceLocation),
3077
3078 ("clang_getLocationForOffset",
3079 [TranslationUnit, File, c_uint],
3080 SourceLocation),
3081
3082 ("clang_getNullCursor",
3083 None,
3084 Cursor),
3085
3086 ("clang_getNumArgTypes",
3087 [Type],
3088 c_uint),
3089
3090 ("clang_getNumCompletionChunks",
3091 [c_void_p],
3092 c_int),
3093
3094 ("clang_getNumDiagnostics",
3095 [c_object_p],
3096 c_uint),
3097
3098 ("clang_getNumElements",
3099 [Type],
3100 c_longlong),
3101
3102 ("clang_getNumOverloadedDecls",
3103 [Cursor],
3104 c_uint),
3105
3106 ("clang_getOverloadedDecl",
3107 [Cursor, c_uint],
3108 Cursor,
3109 Cursor.from_cursor_result),
3110
3111 ("clang_getPointeeType",
3112 [Type],
3113 Type,
3114 Type.from_result),
3115
3116 ("clang_getRange",
3117 [SourceLocation, SourceLocation],
3118 SourceRange),
3119
3120 ("clang_getRangeEnd",
3121 [SourceRange],
3122 SourceLocation),
3123
3124 ("clang_getRangeStart",
3125 [SourceRange],
3126 SourceLocation),
3127
3128 ("clang_getResultType",
3129 [Type],
3130 Type,
3131 Type.from_result),
3132
3133 ("clang_getSpecializedCursorTemplate",
3134 [Cursor],
3135 Cursor,
3136 Cursor.from_cursor_result),
3137
3138 ("clang_getTemplateCursorKind",
3139 [Cursor],
3140 c_uint),
3141
3142 ("clang_getTokenExtent",
3143 [TranslationUnit, Token],
3144 SourceRange),
3145
3146 ("clang_getTokenKind",
3147 [Token],
3148 c_uint),
3149
3150 ("clang_getTokenLocation",
3151 [TranslationUnit, Token],
3152 SourceLocation),
3153
3154 ("clang_getTokenSpelling",
3155 [TranslationUnit, Token],
3156 _CXString,
3157 _CXString.from_result),
3158
3159 ("clang_getTranslationUnitCursor",
3160 [TranslationUnit],
3161 Cursor,
3162 Cursor.from_result),
3163
3164 ("clang_getTranslationUnitSpelling",
3165 [TranslationUnit],
3166 _CXString,
3167 _CXString.from_result),
3168
3169 ("clang_getTUResourceUsageName",
3170 [c_uint],
3171 c_char_p),
3172
3173 ("clang_getTypeDeclaration",
3174 [Type],
3175 Cursor,
3176 Cursor.from_result),
3177
3178 ("clang_getTypedefDeclUnderlyingType",
3179 [Cursor],
3180 Type,
3181 Type.from_result),
3182
3183 ("clang_getTypeKindSpelling",
3184 [c_uint],
3185 _CXString,
3186 _CXString.from_result),
3187
Argyrios Kyrtzidisc23cb2d2013-10-03 16:19:27 +00003188 ("clang_getTypeSpelling",
3189 [Type],
3190 _CXString,
3191 _CXString.from_result),
3192
Tobias Grosser010556e2012-09-01 08:55:17 +00003193 ("clang_hashCursor",
3194 [Cursor],
3195 c_uint),
3196
3197 ("clang_isAttribute",
3198 [CursorKind],
3199 bool),
3200
3201 ("clang_isConstQualifiedType",
3202 [Type],
3203 bool),
3204
3205 ("clang_isCursorDefinition",
3206 [Cursor],
3207 bool),
3208
3209 ("clang_isDeclaration",
3210 [CursorKind],
3211 bool),
3212
3213 ("clang_isExpression",
3214 [CursorKind],
3215 bool),
3216
3217 ("clang_isFileMultipleIncludeGuarded",
3218 [TranslationUnit, File],
3219 bool),
3220
3221 ("clang_isFunctionTypeVariadic",
3222 [Type],
3223 bool),
3224
3225 ("clang_isInvalid",
3226 [CursorKind],
3227 bool),
3228
3229 ("clang_isPODType",
3230 [Type],
3231 bool),
3232
3233 ("clang_isPreprocessing",
3234 [CursorKind],
3235 bool),
3236
3237 ("clang_isReference",
3238 [CursorKind],
3239 bool),
3240
3241 ("clang_isRestrictQualifiedType",
3242 [Type],
3243 bool),
3244
3245 ("clang_isStatement",
3246 [CursorKind],
3247 bool),
3248
3249 ("clang_isTranslationUnit",
3250 [CursorKind],
3251 bool),
3252
3253 ("clang_isUnexposed",
3254 [CursorKind],
3255 bool),
3256
3257 ("clang_isVirtualBase",
3258 [Cursor],
3259 bool),
3260
3261 ("clang_isVolatileQualifiedType",
3262 [Type],
3263 bool),
3264
3265 ("clang_parseTranslationUnit",
3266 [Index, c_char_p, c_void_p, c_int, c_void_p, c_int, c_int],
3267 c_object_p),
3268
3269 ("clang_reparseTranslationUnit",
3270 [TranslationUnit, c_int, c_void_p, c_int],
3271 c_int),
3272
3273 ("clang_saveTranslationUnit",
3274 [TranslationUnit, c_char_p, c_uint],
3275 c_int),
3276
3277 ("clang_tokenize",
3278 [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]),
3279
3280 ("clang_visitChildren",
3281 [Cursor, callbacks['cursor_visit'], py_object],
3282 c_uint),
Gregory Szorcb03b57d2012-11-01 05:46:30 +00003283
3284 ("clang_Cursor_getNumArguments",
3285 [Cursor],
3286 c_int),
3287
3288 ("clang_Cursor_getArgument",
3289 [Cursor, c_uint],
3290 Cursor,
3291 Cursor.from_result),
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00003292
3293 ("clang_Cursor_isBitField",
3294 [Cursor],
Dmitri Gribenko52bb2a02013-04-21 18:35:51 +00003295 bool),
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00003296
Argyrios Kyrtzidisc23cb2d2013-10-03 16:19:27 +00003297 ("clang_Cursor_getBriefCommentText",
3298 [Cursor],
3299 _CXString,
3300 _CXString.from_result),
3301
3302 ("clang_Cursor_getRawCommentText",
3303 [Cursor],
3304 _CXString,
3305 _CXString.from_result),
3306
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00003307 ("clang_Type_getAlignOf",
3308 [Type],
3309 c_longlong),
3310
Argyrios Kyrtzidis659837e2013-10-11 19:58:38 +00003311 ("clang_Type_getClassType",
3312 [Type],
3313 Type,
3314 Type.from_result),
3315
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00003316 ("clang_Type_getOffsetOf",
3317 [Type, c_char_p],
3318 c_longlong),
3319
3320 ("clang_Type_getSizeOf",
3321 [Type],
Argyrios Kyrtzidisdd9e2cb2013-09-25 00:14:43 +00003322 c_longlong),
Argyrios Kyrtzidis659837e2013-10-11 19:58:38 +00003323
3324 ("clang_Type_getCXXRefQualifier",
3325 [Type],
3326 c_uint),
Tobias Grosser010556e2012-09-01 08:55:17 +00003327]
3328
3329class LibclangError(Exception):
3330 def __init__(self, message):
3331 self.m = message
3332
3333 def __str__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003334 return self.m
Tobias Grosser010556e2012-09-01 08:55:17 +00003335
Tobias Grosser857134e2012-09-05 20:23:53 +00003336def register_function(lib, item, ignore_errors):
Tobias Grosser010556e2012-09-01 08:55:17 +00003337 # A function may not exist, if these bindings are used with an older or
3338 # incompatible version of libclang.so.
3339 try:
3340 func = getattr(lib, item[0])
3341 except AttributeError as e:
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003342 msg = str(e) + ". Please ensure that your python bindings are "\
3343 "compatible with your libclang.so version."
Tobias Grosser857134e2012-09-05 20:23:53 +00003344 if ignore_errors:
3345 return
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003346 raise LibclangError(msg)
Tobias Grosser010556e2012-09-01 08:55:17 +00003347
3348 if len(item) >= 2:
3349 func.argtypes = item[1]
3350
3351 if len(item) >= 3:
3352 func.restype = item[2]
3353
3354 if len(item) == 4:
3355 func.errcheck = item[3]
3356
Tobias Grosser857134e2012-09-05 20:23:53 +00003357def register_functions(lib, ignore_errors):
Gregory Szorc9537e202012-07-12 04:56:46 +00003358 """Register function prototypes with a libclang library instance.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00003359
Gregory Szorc9537e202012-07-12 04:56:46 +00003360 This must be called as part of library instantiation so Python knows how
3361 to call out to the shared library.
3362 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00003363
Tobias Grosser010556e2012-09-01 08:55:17 +00003364 def register(item):
Tobias Grosser857134e2012-09-05 20:23:53 +00003365 return register_function(lib, item, ignore_errors)
Tobias Grosser58ba8c92011-10-31 00:31:32 +00003366
Tobias Grosser010556e2012-09-01 08:55:17 +00003367 map(register, functionList)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00003368
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003369class Config:
3370 library_path = None
3371 library_file = None
Tobias Grosser857134e2012-09-05 20:23:53 +00003372 compatibility_check = True
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003373 loaded = False
3374
3375 @staticmethod
3376 def set_library_path(path):
3377 """Set the path in which to search for libclang"""
3378 if Config.loaded:
3379 raise Exception("library path must be set before before using " \
3380 "any other functionalities in libclang.")
3381
3382 Config.library_path = path
3383
3384 @staticmethod
Matt Beaumont-Gay379ffe42012-12-11 17:37:46 +00003385 def set_library_file(filename):
3386 """Set the exact location of libclang"""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003387 if Config.loaded:
3388 raise Exception("library file must be set before before using " \
3389 "any other functionalities in libclang.")
3390
Matt Beaumont-Gay379ffe42012-12-11 17:37:46 +00003391 Config.library_file = filename
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003392
Tobias Grosser857134e2012-09-05 20:23:53 +00003393 @staticmethod
3394 def set_compatibility_check(check_status):
3395 """ Perform compatibility check when loading libclang
3396
3397 The python bindings are only tested and evaluated with the version of
3398 libclang they are provided with. To ensure correct behavior a (limited)
3399 compatibility check is performed when loading the bindings. This check
3400 will throw an exception, as soon as it fails.
3401
3402 In case these bindings are used with an older version of libclang, parts
3403 that have been stable between releases may still work. Users of the
3404 python bindings can disable the compatibility check. This will cause
3405 the python bindings to load, even though they are written for a newer
3406 version of libclang. Failures now arise if unsupported or incompatible
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003407 features are accessed. The user is required to test themselves if the
3408 features they are using are available and compatible between different
Tobias Grosser857134e2012-09-05 20:23:53 +00003409 libclang versions.
3410 """
3411 if Config.loaded:
3412 raise Exception("compatibility_check must be set before before " \
3413 "using any other functionalities in libclang.")
3414
3415 Config.compatibility_check = check_status
3416
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003417 @CachedProperty
3418 def lib(self):
3419 lib = self.get_cindex_library()
Tobias Grosser857134e2012-09-05 20:23:53 +00003420 register_functions(lib, not Config.compatibility_check)
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003421 Config.loaded = True
3422 return lib
3423
3424 def get_filename(self):
3425 if Config.library_file:
3426 return Config.library_file
3427
3428 import platform
3429 name = platform.system()
3430
3431 if name == 'Darwin':
3432 file = 'libclang.dylib'
3433 elif name == 'Windows':
3434 file = 'libclang.dll'
3435 else:
3436 file = 'libclang.so'
3437
3438 if Config.library_path:
3439 file = Config.library_path + '/' + file
3440
3441 return file
3442
3443 def get_cindex_library(self):
3444 try:
3445 library = cdll.LoadLibrary(self.get_filename())
3446 except OSError as e:
3447 msg = str(e) + ". To provide a path to libclang use " \
3448 "Config.set_library_path() or " \
3449 "Config.set_library_file()."
3450 raise LibclangError(msg)
3451
3452 return library
3453
Dmitri Gribenkoc12d6a02012-09-22 17:52:29 +00003454 def function_exists(self, name):
3455 try:
3456 getattr(self.lib, name)
3457 except AttributeError:
3458 return False
3459
3460 return True
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00003461
Gregory Szorcbe51e432012-07-12 07:21:12 +00003462def register_enumerations():
3463 for name, value in clang.enumerations.TokenKinds:
3464 TokenKind.register(value, name)
3465
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003466conf = Config()
Gregory Szorcbe51e432012-07-12 07:21:12 +00003467register_enumerations()
3468
Gregory Szorcfbf620b2012-05-08 05:56:38 +00003469__all__ = [
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003470 'Config',
Gregory Szorcfbf620b2012-05-08 05:56:38 +00003471 'CodeCompletionResults',
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00003472 'CompilationDatabase',
3473 'CompileCommands',
3474 'CompileCommand',
Gregory Szorcfbf620b2012-05-08 05:56:38 +00003475 'CursorKind',
3476 'Cursor',
3477 'Diagnostic',
3478 'File',
3479 'FixIt',
3480 'Index',
3481 'SourceLocation',
3482 'SourceRange',
Gregory Szorcbe51e432012-07-12 07:21:12 +00003483 'TokenKind',
3484 'Token',
Gregory Szorcfbf620b2012-05-08 05:56:38 +00003485 'TranslationUnitLoadError',
3486 'TranslationUnit',
3487 'TypeKind',
3488 'Type',
3489]