blob: 517b3c1bac6ed1bda14634da28029d3da1b2dacc [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
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700275 elif ( self.start.file.name != other.file.name or
Argyrios Kyrtzidis8c099d92013-10-31 00:03:33 +0000276 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
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700751# A reference to a variable that occurs in some non-expression
Argyrios Kyrtzidisda6a6f02013-06-11 18:05:42 +0000752# 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.
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700940#
Argyrios Kyrtzidisda6a6f02013-06-11 18:05:42 +0000941# \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)
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700950
Argyrios Kyrtzidisda6a6f02013-06-11 18:05:42 +0000951# 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)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001085CursorKind.CUDACONSTANT_ATTR = CursorKind(412)
1086CursorKind.CUDADEVICE_ATTR = CursorKind(413)
1087CursorKind.CUDAGLOBAL_ATTR = CursorKind(414)
1088CursorKind.CUDAHOST_ATTR = CursorKind(415)
Rafael Espindolabf3cc732011-12-30 15:27:22 +00001089
Tobias Grosser4ed73ce2011-02-05 17:53:47 +00001090###
1091# Preprocessing
1092CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500)
1093CursorKind.MACRO_DEFINITION = CursorKind(501)
1094CursorKind.MACRO_INSTANTIATION = CursorKind(502)
1095CursorKind.INCLUSION_DIRECTIVE = CursorKind(503)
1096
Argyrios Kyrtzidisda6a6f02013-06-11 18:05:42 +00001097###
1098# Extra declaration
1099
1100# A module import declaration.
1101CursorKind.MODULE_IMPORT_DECL = CursorKind(600)
1102
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001103### Cursors ###
1104
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001105class Cursor(Structure):
1106 """
1107 The Cursor class represents a reference to an element within the AST. It
1108 acts as a kind of iterator.
1109 """
Douglas Gregor2abfec32011-10-19 05:47:46 +00001110 _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001111
Tobias Grosser58ba8c92011-10-31 00:31:32 +00001112 @staticmethod
1113 def from_location(tu, location):
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001114 # We store a reference to the TU in the instance so the TU won't get
1115 # collected before the cursor.
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001116 cursor = conf.lib.clang_getCursor(tu, location)
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001117 cursor._tu = tu
1118
1119 return cursor
Tobias Grosser58ba8c92011-10-31 00:31:32 +00001120
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001121 def __eq__(self, other):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001122 return conf.lib.clang_equalCursors(self, other)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001123
1124 def __ne__(self, other):
Gregory Szorc9d008fd2012-03-05 00:42:15 +00001125 return not self.__eq__(other)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001126
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001127 def is_definition(self):
1128 """
1129 Returns true if the declaration pointed at by the cursor is also a
1130 definition of that entity.
1131 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001132 return conf.lib.clang_isCursorDefinition(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001133
Gregory Szorce65b34d2012-06-09 16:21:34 +00001134 def is_static_method(self):
1135 """Returns True if the cursor refers to a C++ member function or member
1136 function template that is declared 'static'.
1137 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001138 return conf.lib.clang_CXXMethod_isStatic(self)
Gregory Szorce65b34d2012-06-09 16:21:34 +00001139
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001140 def get_definition(self):
1141 """
1142 If the cursor is a reference to a declaration or a declaration of
1143 some entity, return a cursor that points to the definition of that
1144 entity.
1145 """
1146 # TODO: Should probably check that this is either a reference or
1147 # declaration prior to issuing the lookup.
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001148 return conf.lib.clang_getCursorDefinition(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001149
Daniel Dunbar3d855f82010-01-24 21:20:13 +00001150 def get_usr(self):
1151 """Return the Unified Symbol Resultion (USR) for the entity referenced
1152 by the given cursor (or None).
1153
1154 A Unified Symbol Resolution (USR) is a string that identifies a
1155 particular entity (function, class, variable, etc.) within a
1156 program. USRs can be compared across translation units to determine,
1157 e.g., when references in one translation refer to an entity defined in
1158 another translation unit."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001159 return conf.lib.clang_getCursorUSR(self)
Daniel Dunbar3d855f82010-01-24 21:20:13 +00001160
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001161 @property
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001162 def kind(self):
1163 """Return the kind of this cursor."""
1164 return CursorKind.from_id(self._kind_id)
1165
1166 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001167 def spelling(self):
1168 """Return the spelling of the entity pointed at by the cursor."""
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 """
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001348 For a cursor that is a reference, returns a cursor
Argyrios Kyrtzidisd8293792013-01-02 22:31:57 +00001349 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)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001360
Argyrios Kyrtzidisc23cb2d2013-10-03 16:19:27 +00001361 @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
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001390 def walk_preorder(self):
1391 """Depth-first preorder walk over the cursor and its descendants.
1392
1393 Yields cursors.
1394 """
1395 yield self
1396 for child in self.get_children():
1397 for descendant in child.walk_preorder():
1398 yield descendant
1399
Gregory Szorcbe51e432012-07-12 07:21:12 +00001400 def get_tokens(self):
1401 """Obtain Token instances formulating that compose this Cursor.
1402
1403 This is a generator for Token instances. It returns all tokens which
1404 occupy the extent this cursor occupies.
1405 """
1406 return TokenGroup.get_tokens(self._tu, self.extent)
1407
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00001408 def is_bitfield(self):
1409 """
1410 Check if the field is a bitfield.
1411 """
1412 return conf.lib.clang_Cursor_isBitField(self)
1413
1414 def get_bitfield_width(self):
1415 """
1416 Retrieve the width of a bitfield.
1417 """
1418 return conf.lib.clang_getFieldDeclBitWidth(self)
1419
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001420 @staticmethod
1421 def from_result(res, fn, args):
1422 assert isinstance(res, Cursor)
1423 # FIXME: There should just be an isNull method.
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001424 if res == conf.lib.clang_getNullCursor():
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001425 return None
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001426
1427 # Store a reference to the TU in the Python object so it won't get GC'd
1428 # before the Cursor.
1429 tu = None
1430 for arg in args:
1431 if isinstance(arg, TranslationUnit):
1432 tu = arg
1433 break
1434
1435 if hasattr(arg, 'translation_unit'):
1436 tu = arg.translation_unit
1437 break
1438
1439 assert tu is not None
1440
1441 res._tu = tu
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001442 return res
1443
Gregory Szorc9537e202012-07-12 04:56:46 +00001444 @staticmethod
1445 def from_cursor_result(res, fn, args):
1446 assert isinstance(res, Cursor)
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001447 if res == conf.lib.clang_getNullCursor():
Gregory Szorc9537e202012-07-12 04:56:46 +00001448 return None
1449
1450 res._tu = args[0]._tu
1451 return res
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001452
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001453### C++ access specifiers ###
1454
1455class AccessSpecifier(object):
1456 """
1457 Describes the access of a C++ class member
1458 """
1459
1460 # The unique kind objects, index by id.
1461 _kinds = []
1462 _name_map = None
1463
1464 def __init__(self, value):
1465 if value >= len(AccessSpecifier._kinds):
1466 AccessSpecifier._kinds += [None] * (value - len(AccessSpecifier._kinds) + 1)
1467 if AccessSpecifier._kinds[value] is not None:
1468 raise ValueError,'AccessSpecifier already loaded'
1469 self.value = value
1470 AccessSpecifier._kinds[value] = self
1471 AccessSpecifier._name_map = None
1472
1473 def from_param(self):
1474 return self.value
1475
1476 @property
1477 def name(self):
1478 """Get the enumeration name of this access specifier."""
1479 if self._name_map is None:
1480 self._name_map = {}
1481 for key,value in AccessSpecifier.__dict__.items():
1482 if isinstance(value,AccessSpecifier):
1483 self._name_map[value] = key
1484 return self._name_map[self]
1485
1486 @staticmethod
1487 def from_id(id):
1488 if id >= len(AccessSpecifier._kinds) or not AccessSpecifier._kinds[id]:
1489 raise ValueError,'Unknown access specifier %d' % id
1490 return AccessSpecifier._kinds[id]
1491
1492 def __repr__(self):
1493 return 'AccessSpecifier.%s' % (self.name,)
1494
1495AccessSpecifier.INVALID = AccessSpecifier(0)
1496AccessSpecifier.PUBLIC = AccessSpecifier(1)
1497AccessSpecifier.PROTECTED = AccessSpecifier(2)
1498AccessSpecifier.PRIVATE = AccessSpecifier(3)
1499AccessSpecifier.NONE = AccessSpecifier(4)
1500
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001501### Type Kinds ###
1502
1503class TypeKind(object):
1504 """
1505 Describes the kind of type.
1506 """
1507
1508 # The unique kind objects, indexed by id.
1509 _kinds = []
1510 _name_map = None
1511
1512 def __init__(self, value):
1513 if value >= len(TypeKind._kinds):
1514 TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1)
1515 if TypeKind._kinds[value] is not None:
1516 raise ValueError,'TypeKind already loaded'
1517 self.value = value
1518 TypeKind._kinds[value] = self
1519 TypeKind._name_map = None
1520
1521 def from_param(self):
1522 return self.value
1523
1524 @property
1525 def name(self):
1526 """Get the enumeration name of this cursor kind."""
1527 if self._name_map is None:
1528 self._name_map = {}
1529 for key,value in TypeKind.__dict__.items():
1530 if isinstance(value,TypeKind):
1531 self._name_map[value] = key
1532 return self._name_map[self]
1533
Gregory Szorc6e67eed2012-04-15 18:51:10 +00001534 @property
1535 def spelling(self):
1536 """Retrieve the spelling of this TypeKind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001537 return conf.lib.clang_getTypeKindSpelling(self.value)
Gregory Szorc6e67eed2012-04-15 18:51:10 +00001538
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001539 @staticmethod
1540 def from_id(id):
1541 if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None:
Douglas Gregor9d342ab2011-10-19 05:49:29 +00001542 raise ValueError,'Unknown type kind %d' % id
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001543 return TypeKind._kinds[id]
1544
1545 def __repr__(self):
1546 return 'TypeKind.%s' % (self.name,)
1547
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001548TypeKind.INVALID = TypeKind(0)
1549TypeKind.UNEXPOSED = TypeKind(1)
1550TypeKind.VOID = TypeKind(2)
1551TypeKind.BOOL = TypeKind(3)
1552TypeKind.CHAR_U = TypeKind(4)
1553TypeKind.UCHAR = TypeKind(5)
1554TypeKind.CHAR16 = TypeKind(6)
1555TypeKind.CHAR32 = TypeKind(7)
1556TypeKind.USHORT = TypeKind(8)
1557TypeKind.UINT = TypeKind(9)
1558TypeKind.ULONG = TypeKind(10)
1559TypeKind.ULONGLONG = TypeKind(11)
1560TypeKind.UINT128 = TypeKind(12)
1561TypeKind.CHAR_S = TypeKind(13)
1562TypeKind.SCHAR = TypeKind(14)
1563TypeKind.WCHAR = TypeKind(15)
1564TypeKind.SHORT = TypeKind(16)
1565TypeKind.INT = TypeKind(17)
1566TypeKind.LONG = TypeKind(18)
1567TypeKind.LONGLONG = TypeKind(19)
1568TypeKind.INT128 = TypeKind(20)
1569TypeKind.FLOAT = TypeKind(21)
1570TypeKind.DOUBLE = TypeKind(22)
1571TypeKind.LONGDOUBLE = TypeKind(23)
1572TypeKind.NULLPTR = TypeKind(24)
1573TypeKind.OVERLOAD = TypeKind(25)
1574TypeKind.DEPENDENT = TypeKind(26)
1575TypeKind.OBJCID = TypeKind(27)
1576TypeKind.OBJCCLASS = TypeKind(28)
1577TypeKind.OBJCSEL = TypeKind(29)
1578TypeKind.COMPLEX = TypeKind(100)
1579TypeKind.POINTER = TypeKind(101)
1580TypeKind.BLOCKPOINTER = TypeKind(102)
1581TypeKind.LVALUEREFERENCE = TypeKind(103)
1582TypeKind.RVALUEREFERENCE = TypeKind(104)
1583TypeKind.RECORD = TypeKind(105)
1584TypeKind.ENUM = TypeKind(106)
1585TypeKind.TYPEDEF = TypeKind(107)
1586TypeKind.OBJCINTERFACE = TypeKind(108)
1587TypeKind.OBJCOBJECTPOINTER = TypeKind(109)
1588TypeKind.FUNCTIONNOPROTO = TypeKind(110)
1589TypeKind.FUNCTIONPROTO = TypeKind(111)
Douglas Gregor38d2d552011-10-19 05:50:34 +00001590TypeKind.CONSTANTARRAY = TypeKind(112)
Tobias Grosser250d2172012-02-05 11:42:14 +00001591TypeKind.VECTOR = TypeKind(113)
Argyrios Kyrtzidis4c4f6fe2013-07-23 17:36:21 +00001592TypeKind.INCOMPLETEARRAY = TypeKind(114)
1593TypeKind.VARIABLEARRAY = TypeKind(115)
1594TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116)
Argyrios Kyrtzidis367e8fe2013-10-03 16:19:23 +00001595TypeKind.MEMBERPOINTER = TypeKind(117)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001596
Argyrios Kyrtzidis659837e2013-10-11 19:58:38 +00001597class RefQualifierKind(object):
1598 """Describes a specific ref-qualifier of a type."""
1599
1600 # The unique kind objects, indexed by id.
1601 _kinds = []
1602 _name_map = None
1603
1604 def __init__(self, value):
1605 if value >= len(RefQualifierKind._kinds):
1606 num_kinds = value - len(RefQualifierKind._kinds) + 1
1607 RefQualifierKind._kinds += [None] * num_kinds
1608 if RefQualifierKind._kinds[value] is not None:
1609 raise ValueError, 'RefQualifierKind already loaded'
1610 self.value = value
1611 RefQualifierKind._kinds[value] = self
1612 RefQualifierKind._name_map = None
1613
1614 def from_param(self):
1615 return self.value
1616
1617 @property
1618 def name(self):
1619 """Get the enumeration name of this kind."""
1620 if self._name_map is None:
1621 self._name_map = {}
1622 for key, value in RefQualifierKind.__dict__.items():
1623 if isinstance(value, RefQualifierKind):
1624 self._name_map[value] = key
1625 return self._name_map[self]
1626
1627 @staticmethod
1628 def from_id(id):
1629 if (id >= len(RefQualifierKind._kinds) or
1630 RefQualifierKind._kinds[id] is None):
1631 raise ValueError, 'Unknown type kind %d' % id
1632 return RefQualifierKind._kinds[id]
1633
1634 def __repr__(self):
1635 return 'RefQualifierKind.%s' % (self.name,)
1636
1637RefQualifierKind.NONE = RefQualifierKind(0)
1638RefQualifierKind.LVALUE = RefQualifierKind(1)
1639RefQualifierKind.RVALUE = RefQualifierKind(2)
1640
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001641class Type(Structure):
1642 """
1643 The type of an element in the abstract syntax tree.
1644 """
1645 _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)]
1646
1647 @property
1648 def kind(self):
1649 """Return the kind of this type."""
1650 return TypeKind.from_id(self._kind_id)
1651
Gregory Szorc826fce52012-02-20 17:45:30 +00001652 def argument_types(self):
1653 """Retrieve a container for the non-variadic arguments for this type.
1654
1655 The returned object is iterable and indexable. Each item in the
1656 container is a Type instance.
1657 """
1658 class ArgumentsIterator(collections.Sequence):
1659 def __init__(self, parent):
1660 self.parent = parent
1661 self.length = None
1662
1663 def __len__(self):
1664 if self.length is None:
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001665 self.length = conf.lib.clang_getNumArgTypes(self.parent)
Gregory Szorc826fce52012-02-20 17:45:30 +00001666
1667 return self.length
1668
1669 def __getitem__(self, key):
1670 # FIXME Support slice objects.
1671 if not isinstance(key, int):
1672 raise TypeError("Must supply a non-negative int.")
1673
1674 if key < 0:
1675 raise IndexError("Only non-negative indexes are accepted.")
1676
1677 if key >= len(self):
1678 raise IndexError("Index greater than container length: "
1679 "%d > %d" % ( key, len(self) ))
1680
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001681 result = conf.lib.clang_getArgType(self.parent, key)
Gregory Szorc826fce52012-02-20 17:45:30 +00001682 if result.kind == TypeKind.INVALID:
1683 raise IndexError("Argument could not be retrieved.")
1684
1685 return result
1686
1687 assert self.kind == TypeKind.FUNCTIONPROTO
1688 return ArgumentsIterator(self)
1689
Gregory Szorc86057602012-02-17 07:44:46 +00001690 @property
1691 def element_type(self):
1692 """Retrieve the Type of elements within this Type.
1693
1694 If accessed on a type that is not an array, complex, or vector type, an
1695 exception will be raised.
1696 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001697 result = conf.lib.clang_getElementType(self)
Gregory Szorc86057602012-02-17 07:44:46 +00001698 if result.kind == TypeKind.INVALID:
1699 raise Exception('Element type not available on this type.')
1700
1701 return result
1702
Gregory Szorcbf8ca002012-02-17 07:47:38 +00001703 @property
1704 def element_count(self):
1705 """Retrieve the number of elements in this type.
1706
1707 Returns an int.
1708
1709 If the Type is not an array or vector, this raises.
1710 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001711 result = conf.lib.clang_getNumElements(self)
Gregory Szorcbf8ca002012-02-17 07:47:38 +00001712 if result < 0:
1713 raise Exception('Type does not have elements.')
1714
1715 return result
1716
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001717 @property
1718 def translation_unit(self):
1719 """The TranslationUnit to which this Type is associated."""
1720 # If this triggers an AttributeError, the instance was not properly
1721 # instantiated.
1722 return self._tu
1723
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001724 @staticmethod
1725 def from_result(res, fn, args):
1726 assert isinstance(res, Type)
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001727
1728 tu = None
1729 for arg in args:
1730 if hasattr(arg, 'translation_unit'):
1731 tu = arg.translation_unit
1732 break
1733
1734 assert tu is not None
1735 res._tu = tu
1736
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001737 return res
1738
1739 def get_canonical(self):
1740 """
1741 Return the canonical type for a Type.
1742
1743 Clang's type system explicitly models typedefs and all the
1744 ways a specific type can be represented. The canonical type
1745 is the underlying type with all the "sugar" removed. For
1746 example, if 'T' is a typedef for 'int', the canonical type for
1747 'T' would be 'int'.
1748 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001749 return conf.lib.clang_getCanonicalType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001750
1751 def is_const_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001752 """Determine whether a Type has the "const" qualifier set.
1753
1754 This does not look through typedefs that may have added "const"
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001755 at a different level.
1756 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001757 return conf.lib.clang_isConstQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001758
1759 def is_volatile_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001760 """Determine whether a Type has the "volatile" qualifier set.
1761
1762 This does not look through typedefs that may have added "volatile"
1763 at a different level.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001764 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001765 return conf.lib.clang_isVolatileQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001766
1767 def is_restrict_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001768 """Determine whether a Type has the "restrict" qualifier set.
1769
1770 This does not look through typedefs that may have added "restrict" at
1771 a different level.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001772 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001773 return conf.lib.clang_isRestrictQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001774
Gregory Szorc31cc38c2012-02-19 18:28:33 +00001775 def is_function_variadic(self):
1776 """Determine whether this function Type is a variadic function type."""
1777 assert self.kind == TypeKind.FUNCTIONPROTO
1778
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001779 return conf.lib.clang_isFunctionTypeVariadic(self)
Gregory Szorc31cc38c2012-02-19 18:28:33 +00001780
Gregory Szorc96ad6332012-02-05 19:42:06 +00001781 def is_pod(self):
1782 """Determine whether this Type represents plain old data (POD)."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001783 return conf.lib.clang_isPODType(self)
Gregory Szorc96ad6332012-02-05 19:42:06 +00001784
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001785 def get_pointee(self):
1786 """
1787 For pointer types, returns the type of the pointee.
1788 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001789 return conf.lib.clang_getPointeeType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001790
1791 def get_declaration(self):
1792 """
1793 Return the cursor for the declaration of the given type.
1794 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001795 return conf.lib.clang_getTypeDeclaration(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001796
1797 def get_result(self):
1798 """
1799 Retrieve the result type associated with a function type.
1800 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001801 return conf.lib.clang_getResultType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001802
Douglas Gregor13102ff2011-10-19 05:51:43 +00001803 def get_array_element_type(self):
1804 """
1805 Retrieve the type of the elements of the array type.
1806 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001807 return conf.lib.clang_getArrayElementType(self)
Douglas Gregor13102ff2011-10-19 05:51:43 +00001808
1809 def get_array_size(self):
1810 """
1811 Retrieve the size of the constant array.
1812 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001813 return conf.lib.clang_getArraySize(self)
Douglas Gregor13102ff2011-10-19 05:51:43 +00001814
Argyrios Kyrtzidis367e8fe2013-10-03 16:19:23 +00001815 def get_class_type(self):
1816 """
1817 Retrieve the class type of the member pointer type.
1818 """
1819 return conf.lib.clang_Type_getClassType(self)
1820
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00001821 def get_align(self):
1822 """
1823 Retrieve the alignment of the record.
1824 """
1825 return conf.lib.clang_Type_getAlignOf(self)
1826
1827 def get_size(self):
1828 """
1829 Retrieve the size of the record.
1830 """
1831 return conf.lib.clang_Type_getSizeOf(self)
1832
1833 def get_offset(self, fieldname):
1834 """
1835 Retrieve the offset of a field in the record.
1836 """
1837 return conf.lib.clang_Type_getOffsetOf(self, c_char_p(fieldname))
1838
Argyrios Kyrtzidis659837e2013-10-11 19:58:38 +00001839 def get_ref_qualifier(self):
1840 """
1841 Retrieve the ref-qualifier of the type.
1842 """
1843 return RefQualifierKind.from_id(
1844 conf.lib.clang_Type_getCXXRefQualifier(self))
1845
Argyrios Kyrtzidisc23cb2d2013-10-03 16:19:27 +00001846 @property
1847 def spelling(self):
1848 """Retrieve the spelling of this Type."""
1849 return conf.lib.clang_getTypeSpelling(self)
1850
Gregory Szorc7eb691a2012-02-20 17:44:49 +00001851 def __eq__(self, other):
1852 if type(other) != type(self):
1853 return False
1854
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001855 return conf.lib.clang_equalTypes(self, other)
Gregory Szorc7eb691a2012-02-20 17:44:49 +00001856
1857 def __ne__(self, other):
1858 return not self.__eq__(other)
1859
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001860## CIndex Objects ##
1861
1862# CIndex objects (derived from ClangObject) are essentially lightweight
1863# wrappers attached to some underlying object, which is exposed via CIndex as
1864# a void*.
1865
1866class ClangObject(object):
1867 """
1868 A helper for Clang objects. This class helps act as an intermediary for
1869 the ctypes library and the Clang CIndex library.
1870 """
1871 def __init__(self, obj):
1872 assert isinstance(obj, c_object_p) and obj
1873 self.obj = self._as_parameter_ = obj
1874
1875 def from_param(self):
1876 return self._as_parameter_
1877
Daniel Dunbar5b534f62010-01-25 00:44:11 +00001878
1879class _CXUnsavedFile(Structure):
1880 """Helper for passing unsaved file arguments."""
1881 _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
1882
Tobias Grosser69a85522013-01-19 11:03:44 +00001883# Functions calls through the python interface are rather slow. Fortunately,
1884# for most symboles, we do not need to perform a function call. Their spelling
1885# never changes and is consequently provided by this spelling cache.
1886SpellingCache = {
1887 # 0: CompletionChunk.Kind("Optional"),
1888 # 1: CompletionChunk.Kind("TypedText"),
1889 # 2: CompletionChunk.Kind("Text"),
1890 # 3: CompletionChunk.Kind("Placeholder"),
1891 # 4: CompletionChunk.Kind("Informative"),
1892 # 5 : CompletionChunk.Kind("CurrentParameter"),
1893 6: '(', # CompletionChunk.Kind("LeftParen"),
1894 7: ')', # CompletionChunk.Kind("RightParen"),
Stephen Hines651f13c2014-04-23 16:59:28 -07001895 8: '[', # CompletionChunk.Kind("LeftBracket"),
Tobias Grosser69a85522013-01-19 11:03:44 +00001896 9: ']', # CompletionChunk.Kind("RightBracket"),
1897 10: '{', # CompletionChunk.Kind("LeftBrace"),
1898 11: '}', # CompletionChunk.Kind("RightBrace"),
1899 12: '<', # CompletionChunk.Kind("LeftAngle"),
1900 13: '>', # CompletionChunk.Kind("RightAngle"),
1901 14: ', ', # CompletionChunk.Kind("Comma"),
1902 # 15: CompletionChunk.Kind("ResultType"),
1903 16: ':', # CompletionChunk.Kind("Colon"),
1904 17: ';', # CompletionChunk.Kind("SemiColon"),
1905 18: '=', # CompletionChunk.Kind("Equal"),
1906 19: ' ', # CompletionChunk.Kind("HorizontalSpace"),
1907 # 20: CompletionChunk.Kind("VerticalSpace")
1908}
1909
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001910class CompletionChunk:
1911 class Kind:
1912 def __init__(self, name):
1913 self.name = name
1914
1915 def __str__(self):
1916 return self.name
1917
1918 def __repr__(self):
1919 return "<ChunkKind: %s>" % self
1920
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001921 def __init__(self, completionString, key):
1922 self.cs = completionString
1923 self.key = key
Tobias Grossereca36d12013-01-19 11:03:42 +00001924 self.__kindNumberCache = -1
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001925
1926 def __repr__(self):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001927 return "{'" + self.spelling + "', " + str(self.kind) + "}"
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001928
Tobias Grosserd9ee06b2012-08-19 22:26:15 +00001929 @CachedProperty
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001930 def spelling(self):
Tobias Grosserbba99ad2013-01-20 00:42:16 +00001931 if self.__kindNumber in SpellingCache:
1932 return SpellingCache[self.__kindNumber]
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001933 return conf.lib.clang_getCompletionChunkText(self.cs, self.key).spelling
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001934
Tobias Grossereca36d12013-01-19 11:03:42 +00001935 # We do not use @CachedProperty here, as the manual implementation is
1936 # apparently still significantly faster. Please profile carefully if you
1937 # would like to add CachedProperty back.
1938 @property
Tobias Grossere43d3862013-01-19 11:03:40 +00001939 def __kindNumber(self):
Tobias Grossereca36d12013-01-19 11:03:42 +00001940 if self.__kindNumberCache == -1:
1941 self.__kindNumberCache = \
Tobias Grosserbba99ad2013-01-20 00:42:16 +00001942 conf.lib.clang_getCompletionChunkKind(self.cs, self.key)
Tobias Grossereca36d12013-01-19 11:03:42 +00001943 return self.__kindNumberCache
Tobias Grossere43d3862013-01-19 11:03:40 +00001944
1945 @CachedProperty
1946 def kind(self):
1947 return completionChunkKindMap[self.__kindNumber]
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001948
Tobias Grosserd9ee06b2012-08-19 22:26:15 +00001949 @CachedProperty
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001950 def string(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001951 res = conf.lib.clang_getCompletionChunkCompletionString(self.cs,
1952 self.key)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001953
1954 if (res):
1955 return CompletionString(res)
1956 else:
1957 None
1958
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001959 def isKindOptional(self):
Tobias Grossere43d3862013-01-19 11:03:40 +00001960 return self.__kindNumber == 0
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001961
1962 def isKindTypedText(self):
Tobias Grossere43d3862013-01-19 11:03:40 +00001963 return self.__kindNumber == 1
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001964
1965 def isKindPlaceHolder(self):
Tobias Grossere43d3862013-01-19 11:03:40 +00001966 return self.__kindNumber == 3
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001967
1968 def isKindInformative(self):
Tobias Grossere43d3862013-01-19 11:03:40 +00001969 return self.__kindNumber == 4
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001970
1971 def isKindResultType(self):
Tobias Grossere43d3862013-01-19 11:03:40 +00001972 return self.__kindNumber == 15
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001973
1974completionChunkKindMap = {
1975 0: CompletionChunk.Kind("Optional"),
1976 1: CompletionChunk.Kind("TypedText"),
1977 2: CompletionChunk.Kind("Text"),
1978 3: CompletionChunk.Kind("Placeholder"),
1979 4: CompletionChunk.Kind("Informative"),
1980 5: CompletionChunk.Kind("CurrentParameter"),
1981 6: CompletionChunk.Kind("LeftParen"),
1982 7: CompletionChunk.Kind("RightParen"),
1983 8: CompletionChunk.Kind("LeftBracket"),
1984 9: CompletionChunk.Kind("RightBracket"),
1985 10: CompletionChunk.Kind("LeftBrace"),
1986 11: CompletionChunk.Kind("RightBrace"),
1987 12: CompletionChunk.Kind("LeftAngle"),
1988 13: CompletionChunk.Kind("RightAngle"),
1989 14: CompletionChunk.Kind("Comma"),
1990 15: CompletionChunk.Kind("ResultType"),
1991 16: CompletionChunk.Kind("Colon"),
1992 17: CompletionChunk.Kind("SemiColon"),
1993 18: CompletionChunk.Kind("Equal"),
1994 19: CompletionChunk.Kind("HorizontalSpace"),
1995 20: CompletionChunk.Kind("VerticalSpace")}
1996
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001997class CompletionString(ClangObject):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001998 class Availability:
1999 def __init__(self, name):
2000 self.name = name
2001
2002 def __str__(self):
2003 return self.name
2004
2005 def __repr__(self):
2006 return "<Availability: %s>" % self
2007
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002008 def __len__(self):
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002009 return self.num_chunks
Tobias Grosser147785b2012-08-20 10:38:16 +00002010
2011 @CachedProperty
2012 def num_chunks(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002013 return conf.lib.clang_getNumCompletionChunks(self.obj)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002014
2015 def __getitem__(self, key):
Tobias Grosser147785b2012-08-20 10:38:16 +00002016 if self.num_chunks <= key:
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002017 raise IndexError
Tobias Grossera87dbcc2011-02-05 17:54:10 +00002018 return CompletionChunk(self.obj, key)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002019
2020 @property
2021 def priority(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002022 return conf.lib.clang_getCompletionPriority(self.obj)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002023
2024 @property
2025 def availability(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002026 res = conf.lib.clang_getCompletionAvailability(self.obj)
Tobias Grossera87dbcc2011-02-05 17:54:10 +00002027 return availabilityKinds[res]
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002028
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002029 @property
2030 def briefComment(self):
Dmitri Gribenkoc12d6a02012-09-22 17:52:29 +00002031 if conf.function_exists("clang_getCompletionBriefComment"):
2032 return conf.lib.clang_getCompletionBriefComment(self.obj)
2033 return _CXString()
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002034
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002035 def __repr__(self):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00002036 return " | ".join([str(a) for a in self]) \
2037 + " || Priority: " + str(self.priority) \
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002038 + " || Availability: " + str(self.availability) \
2039 + " || Brief comment: " + str(self.briefComment.spelling)
Tobias Grossera87dbcc2011-02-05 17:54:10 +00002040
2041availabilityKinds = {
2042 0: CompletionChunk.Kind("Available"),
2043 1: CompletionChunk.Kind("Deprecated"),
Benjamin Kramer724d0dc2012-10-07 11:46:37 +00002044 2: CompletionChunk.Kind("NotAvailable"),
2045 3: CompletionChunk.Kind("NotAccessible")}
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002046
Tobias Grosser0a166802011-02-05 17:54:04 +00002047class CodeCompletionResult(Structure):
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002048 _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
2049
2050 def __repr__(self):
2051 return str(CompletionString(self.completionString))
2052
2053 @property
2054 def kind(self):
2055 return CursorKind.from_id(self.cursorKind)
2056
2057 @property
2058 def string(self):
2059 return CompletionString(self.completionString)
Tobias Grosser0a166802011-02-05 17:54:04 +00002060
2061class CCRStructure(Structure):
2062 _fields_ = [('results', POINTER(CodeCompletionResult)),
2063 ('numResults', c_int)]
2064
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002065 def __len__(self):
2066 return self.numResults
2067
2068 def __getitem__(self, key):
2069 if len(self) <= key:
2070 raise IndexError
2071
2072 return self.results[key]
2073
Tobias Grosser0a166802011-02-05 17:54:04 +00002074class CodeCompletionResults(ClangObject):
2075 def __init__(self, ptr):
2076 assert isinstance(ptr, POINTER(CCRStructure)) and ptr
2077 self.ptr = self._as_parameter_ = ptr
2078
2079 def from_param(self):
2080 return self._as_parameter_
2081
2082 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002083 conf.lib.clang_disposeCodeCompleteResults(self)
Tobias Grosser0a166802011-02-05 17:54:04 +00002084
2085 @property
2086 def results(self):
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00002087 return self.ptr.contents
Tobias Grosser0a166802011-02-05 17:54:04 +00002088
2089 @property
2090 def diagnostics(self):
2091 class DiagnosticsItr:
2092 def __init__(self, ccr):
2093 self.ccr= ccr
2094
2095 def __len__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002096 return int(\
2097 conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr))
Tobias Grosser0a166802011-02-05 17:54:04 +00002098
2099 def __getitem__(self, key):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002100 return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key)
Tobias Grosser0a166802011-02-05 17:54:04 +00002101
2102 return DiagnosticsItr(self)
2103
2104
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002105class Index(ClangObject):
2106 """
2107 The Index type provides the primary interface to the Clang CIndex library,
2108 primarily by providing an interface for reading and parsing translation
2109 units.
2110 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002111
2112 @staticmethod
Daniel Dunbar2791dfc2010-01-30 23:58:39 +00002113 def create(excludeDecls=False):
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002114 """
2115 Create a new Index.
2116 Parameters:
2117 excludeDecls -- Exclude local declarations from translation units.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002118 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002119 return Index(conf.lib.clang_createIndex(excludeDecls, 0))
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002120
2121 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002122 conf.lib.clang_disposeIndex(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002123
2124 def read(self, path):
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002125 """Load a TranslationUnit from the given AST file."""
Argyrios Kyrtzidisda6a6f02013-06-11 18:05:42 +00002126 return TranslationUnit.from_ast_file(path, self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002127
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002128 def parse(self, path, args=None, unsaved_files=None, options = 0):
2129 """Load the translation unit from the given source code file by running
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002130 clang and generating the AST before loading. Additional command line
2131 parameters can be passed to clang via the args parameter.
Daniel Dunbar5b534f62010-01-25 00:44:11 +00002132
2133 In-memory contents for files can be provided by passing a list of pairs
2134 to as unsaved_files, the first item should be the filenames to be mapped
2135 and the second should be the contents to be substituted for the
2136 file. The contents may be passed as strings or file objects.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002137
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002138 If an error was encountered during parsing, a TranslationUnitLoadError
2139 will be raised.
2140 """
2141 return TranslationUnit.from_source(path, args, unsaved_files, options,
2142 self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002143
2144class TranslationUnit(ClangObject):
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002145 """Represents a source code translation unit.
2146
2147 This is one of the main types in the API. Any time you wish to interact
2148 with Clang's representation of a source file, you typically start with a
2149 translation unit.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002150 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002151
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002152 # Default parsing mode.
2153 PARSE_NONE = 0
2154
2155 # Instruct the parser to create a detailed processing record containing
2156 # metadata not normally retained.
2157 PARSE_DETAILED_PROCESSING_RECORD = 1
2158
2159 # Indicates that the translation unit is incomplete. This is typically used
2160 # when parsing headers.
2161 PARSE_INCOMPLETE = 2
2162
2163 # Instruct the parser to create a pre-compiled preamble for the translation
2164 # unit. This caches the preamble (included files at top of source file).
2165 # This is useful if the translation unit will be reparsed and you don't
2166 # want to incur the overhead of reparsing the preamble.
2167 PARSE_PRECOMPILED_PREAMBLE = 4
2168
2169 # Cache code completion information on parse. This adds time to parsing but
2170 # speeds up code completion.
2171 PARSE_CACHE_COMPLETION_RESULTS = 8
2172
2173 # Flags with values 16 and 32 are deprecated and intentionally omitted.
2174
2175 # Do not parse function bodies. This is useful if you only care about
2176 # searching for declarations/definitions.
2177 PARSE_SKIP_FUNCTION_BODIES = 64
2178
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002179 # Used to indicate that brief documentation comments should be included
2180 # into the set of code completions returned from this translation unit.
2181 PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128
2182
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002183 @classmethod
2184 def from_source(cls, filename, args=None, unsaved_files=None, options=0,
2185 index=None):
2186 """Create a TranslationUnit by parsing source.
2187
2188 This is capable of processing source code both from files on the
2189 filesystem as well as in-memory contents.
2190
2191 Command-line arguments that would be passed to clang are specified as
2192 a list via args. These can be used to specify include paths, warnings,
2193 etc. e.g. ["-Wall", "-I/path/to/include"].
2194
2195 In-memory file content can be provided via unsaved_files. This is an
2196 iterable of 2-tuples. The first element is the str filename. The
2197 second element defines the content. Content can be provided as str
2198 source code or as file objects (anything with a read() method). If
2199 a file object is being used, content will be read until EOF and the
2200 read cursor will not be reset to its original position.
2201
2202 options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
2203 control parsing behavior.
2204
Gregory Szorc2283b462012-05-12 20:49:13 +00002205 index is an Index instance to utilize. If not provided, a new Index
2206 will be created for this TranslationUnit.
2207
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002208 To parse source from the filesystem, the filename of the file to parse
2209 is specified by the filename argument. Or, filename could be None and
2210 the args list would contain the filename(s) to parse.
2211
2212 To parse source from an in-memory buffer, set filename to the virtual
2213 filename you wish to associate with this source (e.g. "test.c"). The
2214 contents of that file are then provided in unsaved_files.
2215
2216 If an error occurs, a TranslationUnitLoadError is raised.
2217
2218 Please note that a TranslationUnit with parser errors may be returned.
2219 It is the caller's responsibility to check tu.diagnostics for errors.
2220
2221 Also note that Clang infers the source language from the extension of
2222 the input filename. If you pass in source code containing a C++ class
2223 declaration with the filename "test.c" parsing will fail.
2224 """
2225 if args is None:
2226 args = []
2227
2228 if unsaved_files is None:
2229 unsaved_files = []
2230
2231 if index is None:
2232 index = Index.create()
2233
2234 args_array = None
2235 if len(args) > 0:
2236 args_array = (c_char_p * len(args))(* args)
2237
2238 unsaved_array = None
2239 if len(unsaved_files) > 0:
2240 unsaved_array = (_CXUnsavedFile * len(unsaved_files))()
2241 for i, (name, contents) in enumerate(unsaved_files):
2242 if hasattr(contents, "read"):
2243 contents = contents.read()
2244
2245 unsaved_array[i].name = name
2246 unsaved_array[i].contents = contents
2247 unsaved_array[i].length = len(contents)
2248
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002249 ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array,
Gregory Szorc9537e202012-07-12 04:56:46 +00002250 len(args), unsaved_array,
2251 len(unsaved_files), options)
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002252
Tobias Grosser11d6cd32013-03-19 15:30:48 +00002253 if not ptr:
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002254 raise TranslationUnitLoadError("Error parsing translation unit.")
2255
2256 return cls(ptr, index=index)
2257
2258 @classmethod
2259 def from_ast_file(cls, filename, index=None):
2260 """Create a TranslationUnit instance from a saved AST file.
2261
2262 A previously-saved AST file (provided with -emit-ast or
2263 TranslationUnit.save()) is loaded from the filename specified.
2264
2265 If the file cannot be loaded, a TranslationUnitLoadError will be
2266 raised.
2267
2268 index is optional and is the Index instance to use. If not provided,
2269 a default Index will be created.
2270 """
2271 if index is None:
2272 index = Index.create()
2273
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002274 ptr = conf.lib.clang_createTranslationUnit(index, filename)
Tobias Grosser11d6cd32013-03-19 15:30:48 +00002275 if not ptr:
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002276 raise TranslationUnitLoadError(filename)
2277
2278 return cls(ptr=ptr, index=index)
2279
2280 def __init__(self, ptr, index):
2281 """Create a TranslationUnit instance.
2282
2283 TranslationUnits should be created using one of the from_* @classmethod
2284 functions above. __init__ is only called internally.
2285 """
2286 assert isinstance(index, Index)
2287
Daniel Dunbar532fc632010-01-30 23:59:02 +00002288 ClangObject.__init__(self, ptr)
Daniel Dunbar532fc632010-01-30 23:59:02 +00002289
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002290 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002291 conf.lib.clang_disposeTranslationUnit(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002292
Daniel Dunbar1b945a72010-01-24 04:09:43 +00002293 @property
2294 def cursor(self):
2295 """Retrieve the cursor that represents the given translation unit."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002296 return conf.lib.clang_getTranslationUnitCursor(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002297
2298 @property
2299 def spelling(self):
Daniel Dunbar1b945a72010-01-24 04:09:43 +00002300 """Get the original translation unit source file name."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002301 return conf.lib.clang_getTranslationUnitSpelling(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002302
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002303 def get_includes(self):
2304 """
2305 Return an iterable sequence of FileInclusion objects that describe the
2306 sequence of inclusions in a translation unit. The first object in
2307 this sequence is always the input file. Note that this method will not
2308 recursively iterate over header files included through precompiled
2309 headers.
2310 """
2311 def visitor(fobj, lptr, depth, includes):
Douglas Gregor8be80e12011-07-06 03:00:34 +00002312 if depth > 0:
2313 loc = lptr.contents
2314 includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002315
2316 # Automatically adapt CIndex/ctype pointers to python objects
2317 includes = []
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002318 conf.lib.clang_getInclusions(self,
Gregory Szorc9537e202012-07-12 04:56:46 +00002319 callbacks['translation_unit_includes'](visitor), includes)
2320
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002321 return iter(includes)
2322
Gregory Szorc0f1964a2012-07-12 05:05:56 +00002323 def get_file(self, filename):
2324 """Obtain a File from this translation unit."""
2325
2326 return File.from_name(self, filename)
2327
2328 def get_location(self, filename, position):
2329 """Obtain a SourceLocation for a file in this translation unit.
2330
2331 The position can be specified by passing:
2332
2333 - Integer file offset. Initial file offset is 0.
2334 - 2-tuple of (line number, column number). Initial file position is
2335 (0, 0)
2336 """
2337 f = self.get_file(filename)
2338
2339 if isinstance(position, int):
2340 return SourceLocation.from_offset(self, f, position)
2341
2342 return SourceLocation.from_position(self, f, position[0], position[1])
2343
2344 def get_extent(self, filename, locations):
2345 """Obtain a SourceRange from this translation unit.
2346
2347 The bounds of the SourceRange must ultimately be defined by a start and
2348 end SourceLocation. For the locations argument, you can pass:
2349
2350 - 2 SourceLocation instances in a 2-tuple or list.
2351 - 2 int file offsets via a 2-tuple or list.
2352 - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
2353
2354 e.g.
2355
2356 get_extent('foo.c', (5, 10))
2357 get_extent('foo.c', ((1, 1), (1, 15)))
2358 """
2359 f = self.get_file(filename)
2360
2361 if len(locations) < 2:
2362 raise Exception('Must pass object with at least 2 elements')
2363
2364 start_location, end_location = locations
2365
2366 if hasattr(start_location, '__len__'):
2367 start_location = SourceLocation.from_position(self, f,
2368 start_location[0], start_location[1])
2369 elif isinstance(start_location, int):
2370 start_location = SourceLocation.from_offset(self, f,
2371 start_location)
2372
2373 if hasattr(end_location, '__len__'):
2374 end_location = SourceLocation.from_position(self, f,
2375 end_location[0], end_location[1])
2376 elif isinstance(end_location, int):
2377 end_location = SourceLocation.from_offset(self, f, end_location)
2378
2379 assert isinstance(start_location, SourceLocation)
2380 assert isinstance(end_location, SourceLocation)
2381
2382 return SourceRange.from_locations(start_location, end_location)
2383
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002384 @property
2385 def diagnostics(self):
2386 """
2387 Return an iterable (and indexable) object containing the diagnostics.
2388 """
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00002389 class DiagIterator:
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002390 def __init__(self, tu):
2391 self.tu = tu
2392
2393 def __len__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002394 return int(conf.lib.clang_getNumDiagnostics(self.tu))
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002395
2396 def __getitem__(self, key):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002397 diag = conf.lib.clang_getDiagnostic(self.tu, key)
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00002398 if not diag:
2399 raise IndexError
2400 return Diagnostic(diag)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002401
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00002402 return DiagIterator(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002403
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002404 def reparse(self, unsaved_files=None, options=0):
Tobias Grosser265e6b22011-02-05 17:54:00 +00002405 """
2406 Reparse an already parsed translation unit.
2407
2408 In-memory contents for files can be provided by passing a list of pairs
2409 as unsaved_files, the first items should be the filenames to be mapped
2410 and the second should be the contents to be substituted for the
2411 file. The contents may be passed as strings or file objects.
2412 """
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002413 if unsaved_files is None:
2414 unsaved_files = []
2415
Tobias Grosser265e6b22011-02-05 17:54:00 +00002416 unsaved_files_array = 0
2417 if len(unsaved_files):
2418 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
2419 for i,(name,value) in enumerate(unsaved_files):
2420 if not isinstance(value, str):
2421 # FIXME: It would be great to support an efficient version
2422 # of this, one day.
2423 value = value.read()
2424 print value
2425 if not isinstance(value, str):
2426 raise TypeError,'Unexpected unsaved file contents.'
2427 unsaved_files_array[i].name = name
2428 unsaved_files_array[i].contents = value
2429 unsaved_files_array[i].length = len(value)
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002430 ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
Gregory Szorc9537e202012-07-12 04:56:46 +00002431 unsaved_files_array, options)
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002432
2433 def save(self, filename):
2434 """Saves the TranslationUnit to a file.
2435
2436 This is equivalent to passing -emit-ast to the clang frontend. The
2437 saved file can be loaded back into a TranslationUnit. Or, if it
2438 corresponds to a header, it can be used as a pre-compiled header file.
2439
2440 If an error occurs while saving, a TranslationUnitSaveError is raised.
2441 If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
2442 the constructed TranslationUnit was not valid at time of save. In this
2443 case, the reason(s) why should be available via
2444 TranslationUnit.diagnostics().
2445
2446 filename -- The path to save the translation unit to.
2447 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002448 options = conf.lib.clang_defaultSaveOptions(self)
2449 result = int(conf.lib.clang_saveTranslationUnit(self, filename,
2450 options))
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002451 if result != 0:
2452 raise TranslationUnitSaveError(result,
2453 'Error saving TranslationUnit.')
2454
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002455 def codeComplete(self, path, line, column, unsaved_files=None,
2456 include_macros=False, include_code_patterns=False,
2457 include_brief_comments=False):
Tobias Grosser0a166802011-02-05 17:54:04 +00002458 """
2459 Code complete in this translation unit.
2460
2461 In-memory contents for files can be provided by passing a list of pairs
2462 as unsaved_files, the first items should be the filenames to be mapped
2463 and the second should be the contents to be substituted for the
2464 file. The contents may be passed as strings or file objects.
2465 """
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002466 options = 0
2467
2468 if include_macros:
2469 options += 1
2470
2471 if include_code_patterns:
2472 options += 2
2473
2474 if include_brief_comments:
2475 options += 4
2476
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002477 if unsaved_files is None:
2478 unsaved_files = []
2479
Tobias Grosser0a166802011-02-05 17:54:04 +00002480 unsaved_files_array = 0
2481 if len(unsaved_files):
2482 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
2483 for i,(name,value) in enumerate(unsaved_files):
2484 if not isinstance(value, str):
2485 # FIXME: It would be great to support an efficient version
2486 # of this, one day.
2487 value = value.read()
2488 print value
2489 if not isinstance(value, str):
2490 raise TypeError,'Unexpected unsaved file contents.'
2491 unsaved_files_array[i].name = name
2492 unsaved_files_array[i].contents = value
2493 unsaved_files_array[i].length = len(value)
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002494 ptr = conf.lib.clang_codeCompleteAt(self, path, line, column,
Gregory Szorc9537e202012-07-12 04:56:46 +00002495 unsaved_files_array, len(unsaved_files), options)
Tobias Grosserba5d10b2011-10-31 02:06:50 +00002496 if ptr:
2497 return CodeCompletionResults(ptr)
2498 return None
Tobias Grosser265e6b22011-02-05 17:54:00 +00002499
Gregory Szorcbe51e432012-07-12 07:21:12 +00002500 def get_tokens(self, locations=None, extent=None):
2501 """Obtain tokens in this translation unit.
2502
2503 This is a generator for Token instances. The caller specifies a range
2504 of source code to obtain tokens for. The range can be specified as a
2505 2-tuple of SourceLocation or as a SourceRange. If both are defined,
2506 behavior is undefined.
2507 """
2508 if locations is not None:
2509 extent = SourceRange(start=locations[0], end=locations[1])
2510
2511 return TokenGroup.get_tokens(self, extent)
2512
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002513class File(ClangObject):
2514 """
Daniel Dunbar7b48b352010-01-24 04:09:34 +00002515 The File class represents a particular source file that is part of a
2516 translation unit.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002517 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002518
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002519 @staticmethod
2520 def from_name(translation_unit, file_name):
2521 """Retrieve a file handle within the given translation unit."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002522 return File(conf.lib.clang_getFile(translation_unit, file_name))
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002523
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002524 @property
2525 def name(self):
Daniel Dunbar4efd6322010-01-25 00:43:08 +00002526 """Return the complete file and path name of the file."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002527 return conf.lib.clang_getCString(conf.lib.clang_getFileName(self))
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002528
2529 @property
2530 def time(self):
Daniel Dunbar4efd6322010-01-25 00:43:08 +00002531 """Return the last modification time of the file."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002532 return conf.lib.clang_getFileTime(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002533
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002534 def __str__(self):
2535 return self.name
2536
2537 def __repr__(self):
2538 return "<File: %s>" % (self.name)
2539
Gregory Szorc9537e202012-07-12 04:56:46 +00002540 @staticmethod
2541 def from_cursor_result(res, fn, args):
2542 assert isinstance(res, File)
2543
2544 # Copy a reference to the TranslationUnit to prevent premature GC.
2545 res._tu = args[0]._tu
2546 return res
2547
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002548class FileInclusion(object):
2549 """
2550 The FileInclusion class represents the inclusion of one source file by
2551 another via a '#include' directive or as the input file for the translation
2552 unit. This class provides information about the included file, the including
2553 file, the location of the '#include' directive and the depth of the included
2554 file in the stack. Note that the input file has depth 0.
2555 """
2556
2557 def __init__(self, src, tgt, loc, depth):
2558 self.source = src
2559 self.include = tgt
2560 self.location = loc
2561 self.depth = depth
2562
2563 @property
2564 def is_input_file(self):
2565 """True if the included file is the input file."""
2566 return self.depth == 0
2567
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002568class CompilationDatabaseError(Exception):
2569 """Represents an error that occurred when working with a CompilationDatabase
2570
2571 Each error is associated to an enumerated value, accessible under
2572 e.cdb_error. Consumers can compare the value with one of the ERROR_
2573 constants in this class.
2574 """
2575
Stephen Hines651f13c2014-04-23 16:59:28 -07002576 # An unknown error occurred
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002577 ERROR_UNKNOWN = 0
2578
2579 # The database could not be loaded
2580 ERROR_CANNOTLOADDATABASE = 1
2581
2582 def __init__(self, enumeration, message):
2583 assert isinstance(enumeration, int)
2584
2585 if enumeration > 1:
2586 raise Exception("Encountered undefined CompilationDatabase error "
2587 "constant: %d. Please file a bug to have this "
2588 "value supported." % enumeration)
2589
2590 self.cdb_error = enumeration
2591 Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
2592
2593class CompileCommand(object):
2594 """Represents the compile command used to build a file"""
2595 def __init__(self, cmd, ccmds):
2596 self.cmd = cmd
2597 # Keep a reference to the originating CompileCommands
2598 # to prevent garbage collection
2599 self.ccmds = ccmds
2600
2601 @property
2602 def directory(self):
2603 """Get the working directory for this CompileCommand"""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002604 return conf.lib.clang_CompileCommand_getDirectory(self.cmd)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002605
2606 @property
2607 def arguments(self):
2608 """
2609 Get an iterable object providing each argument in the
2610 command line for the compiler invocation as a _CXString.
2611
Arnaud A. de Grandmaison577c5302012-07-06 08:22:05 +00002612 Invariant : the first argument is the compiler executable
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002613 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002614 length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002615 for i in xrange(length):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002616 yield conf.lib.clang_CompileCommand_getArg(self.cmd, i)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002617
2618class CompileCommands(object):
2619 """
2620 CompileCommands is an iterable object containing all CompileCommand
2621 that can be used for building a specific file.
2622 """
2623 def __init__(self, ccmds):
2624 self.ccmds = ccmds
2625
2626 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002627 conf.lib.clang_CompileCommands_dispose(self.ccmds)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002628
2629 def __len__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002630 return int(conf.lib.clang_CompileCommands_getSize(self.ccmds))
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002631
2632 def __getitem__(self, i):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002633 cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i)
Arnaud A. de Grandmaisonb1614042012-07-09 11:57:30 +00002634 if not cc:
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002635 raise IndexError
2636 return CompileCommand(cc, self)
2637
2638 @staticmethod
2639 def from_result(res, fn, args):
2640 if not res:
2641 return None
2642 return CompileCommands(res)
2643
2644class CompilationDatabase(ClangObject):
2645 """
2646 The CompilationDatabase is a wrapper class around
2647 clang::tooling::CompilationDatabase
2648
2649 It enables querying how a specific source file can be built.
2650 """
2651
2652 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002653 conf.lib.clang_CompilationDatabase_dispose(self)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002654
2655 @staticmethod
2656 def from_result(res, fn, args):
2657 if not res:
2658 raise CompilationDatabaseError(0,
2659 "CompilationDatabase loading failed")
2660 return CompilationDatabase(res)
2661
2662 @staticmethod
2663 def fromDirectory(buildDir):
2664 """Builds a CompilationDatabase from the database found in buildDir"""
2665 errorCode = c_uint()
2666 try:
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002667 cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
Gregory Szorc9537e202012-07-12 04:56:46 +00002668 byref(errorCode))
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002669 except CompilationDatabaseError as e:
Gregory Szorc9537e202012-07-12 04:56:46 +00002670 raise CompilationDatabaseError(int(errorCode.value),
2671 "CompilationDatabase loading failed")
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002672 return cdb
2673
2674 def getCompileCommands(self, filename):
2675 """
2676 Get an iterable object providing all the CompileCommands available to
Arnaud A. de Grandmaison44394782012-06-30 20:43:37 +00002677 build filename. Returns None if filename is not found in the database.
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002678 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002679 return conf.lib.clang_CompilationDatabase_getCompileCommands(self,
2680 filename)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002681
Stephen Hines651f13c2014-04-23 16:59:28 -07002682 def getAllCompileCommands(self):
2683 """
2684 Get an iterable object providing all the CompileCommands available from
2685 the database.
2686 """
2687 return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self)
2688
2689
Gregory Szorcbe51e432012-07-12 07:21:12 +00002690class Token(Structure):
2691 """Represents a single token from the preprocessor.
2692
2693 Tokens are effectively segments of source code. Source code is first parsed
2694 into tokens before being converted into the AST and Cursors.
2695
2696 Tokens are obtained from parsed TranslationUnit instances. You currently
2697 can't create tokens manually.
2698 """
2699 _fields_ = [
2700 ('int_data', c_uint * 4),
2701 ('ptr_data', c_void_p)
2702 ]
2703
2704 @property
2705 def spelling(self):
2706 """The spelling of this token.
2707
2708 This is the textual representation of the token in source.
2709 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002710 return conf.lib.clang_getTokenSpelling(self._tu, self)
Gregory Szorcbe51e432012-07-12 07:21:12 +00002711
2712 @property
2713 def kind(self):
2714 """Obtain the TokenKind of the current token."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002715 return TokenKind.from_value(conf.lib.clang_getTokenKind(self))
Gregory Szorcbe51e432012-07-12 07:21:12 +00002716
2717 @property
2718 def location(self):
2719 """The SourceLocation this Token occurs at."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002720 return conf.lib.clang_getTokenLocation(self._tu, self)
Gregory Szorcbe51e432012-07-12 07:21:12 +00002721
2722 @property
2723 def extent(self):
2724 """The SourceRange this Token occupies."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002725 return conf.lib.clang_getTokenExtent(self._tu, self)
Gregory Szorcbe51e432012-07-12 07:21:12 +00002726
2727 @property
2728 def cursor(self):
2729 """The Cursor this Token corresponds to."""
2730 cursor = Cursor()
2731
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002732 conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
Gregory Szorcbe51e432012-07-12 07:21:12 +00002733
2734 return cursor
2735
Gregory Szorc9537e202012-07-12 04:56:46 +00002736# Now comes the plumbing to hook up the C library.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002737
Gregory Szorc9537e202012-07-12 04:56:46 +00002738# Register callback types in common container.
2739callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p,
2740 POINTER(SourceLocation), c_uint, py_object)
2741callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
Daniel Dunbara33dca42010-01-24 21:19:57 +00002742
Tobias Grosser010556e2012-09-01 08:55:17 +00002743# Functions strictly alphabetical order.
2744functionList = [
2745 ("clang_annotateTokens",
2746 [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]),
2747
2748 ("clang_CompilationDatabase_dispose",
2749 [c_object_p]),
2750
2751 ("clang_CompilationDatabase_fromDirectory",
2752 [c_char_p, POINTER(c_uint)],
2753 c_object_p,
2754 CompilationDatabase.from_result),
2755
Stephen Hines651f13c2014-04-23 16:59:28 -07002756 ("clang_CompilationDatabase_getAllCompileCommands",
2757 [c_object_p],
2758 c_object_p,
2759 CompileCommands.from_result),
2760
Tobias Grosser010556e2012-09-01 08:55:17 +00002761 ("clang_CompilationDatabase_getCompileCommands",
2762 [c_object_p, c_char_p],
2763 c_object_p,
2764 CompileCommands.from_result),
2765
2766 ("clang_CompileCommands_dispose",
2767 [c_object_p]),
2768
2769 ("clang_CompileCommands_getCommand",
2770 [c_object_p, c_uint],
2771 c_object_p),
2772
2773 ("clang_CompileCommands_getSize",
2774 [c_object_p],
2775 c_uint),
2776
2777 ("clang_CompileCommand_getArg",
2778 [c_object_p, c_uint],
2779 _CXString,
2780 _CXString.from_result),
2781
2782 ("clang_CompileCommand_getDirectory",
2783 [c_object_p],
2784 _CXString,
2785 _CXString.from_result),
2786
2787 ("clang_CompileCommand_getNumArgs",
2788 [c_object_p],
2789 c_uint),
2790
2791 ("clang_codeCompleteAt",
2792 [TranslationUnit, c_char_p, c_int, c_int, c_void_p, c_int, c_int],
2793 POINTER(CCRStructure)),
2794
2795 ("clang_codeCompleteGetDiagnostic",
2796 [CodeCompletionResults, c_int],
2797 Diagnostic),
2798
2799 ("clang_codeCompleteGetNumDiagnostics",
2800 [CodeCompletionResults],
2801 c_int),
2802
2803 ("clang_createIndex",
2804 [c_int, c_int],
2805 c_object_p),
2806
2807 ("clang_createTranslationUnit",
2808 [Index, c_char_p],
2809 c_object_p),
2810
Dmitri Gribenkoc965f762013-05-17 18:38:35 +00002811 ("clang_CXXMethod_isPureVirtual",
2812 [Cursor],
2813 bool),
2814
Tobias Grosser010556e2012-09-01 08:55:17 +00002815 ("clang_CXXMethod_isStatic",
2816 [Cursor],
2817 bool),
2818
2819 ("clang_CXXMethod_isVirtual",
2820 [Cursor],
2821 bool),
2822
2823 ("clang_defaultSaveOptions",
2824 [TranslationUnit],
2825 c_uint),
2826
2827 ("clang_disposeCodeCompleteResults",
2828 [CodeCompletionResults]),
2829
2830# ("clang_disposeCXTUResourceUsage",
2831# [CXTUResourceUsage]),
2832
2833 ("clang_disposeDiagnostic",
2834 [Diagnostic]),
2835
2836 ("clang_disposeIndex",
2837 [Index]),
2838
2839 ("clang_disposeString",
2840 [_CXString]),
2841
2842 ("clang_disposeTokens",
2843 [TranslationUnit, POINTER(Token), c_uint]),
2844
2845 ("clang_disposeTranslationUnit",
2846 [TranslationUnit]),
2847
2848 ("clang_equalCursors",
2849 [Cursor, Cursor],
2850 bool),
2851
2852 ("clang_equalLocations",
2853 [SourceLocation, SourceLocation],
2854 bool),
2855
2856 ("clang_equalRanges",
2857 [SourceRange, SourceRange],
2858 bool),
2859
2860 ("clang_equalTypes",
2861 [Type, Type],
2862 bool),
2863
2864 ("clang_getArgType",
2865 [Type, c_uint],
2866 Type,
2867 Type.from_result),
2868
2869 ("clang_getArrayElementType",
2870 [Type],
2871 Type,
2872 Type.from_result),
2873
2874 ("clang_getArraySize",
2875 [Type],
2876 c_longlong),
2877
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00002878 ("clang_getFieldDeclBitWidth",
2879 [Cursor],
2880 c_int),
2881
Tobias Grosser010556e2012-09-01 08:55:17 +00002882 ("clang_getCanonicalCursor",
2883 [Cursor],
2884 Cursor,
2885 Cursor.from_cursor_result),
2886
2887 ("clang_getCanonicalType",
2888 [Type],
2889 Type,
2890 Type.from_result),
2891
2892 ("clang_getCompletionAvailability",
2893 [c_void_p],
2894 c_int),
2895
Dmitri Gribenkoc69e0672012-09-15 11:56:32 +00002896 ("clang_getCompletionBriefComment",
2897 [c_void_p],
2898 _CXString),
2899
Tobias Grosser010556e2012-09-01 08:55:17 +00002900 ("clang_getCompletionChunkCompletionString",
2901 [c_void_p, c_int],
2902 c_object_p),
2903
2904 ("clang_getCompletionChunkKind",
2905 [c_void_p, c_int],
2906 c_int),
2907
2908 ("clang_getCompletionChunkText",
2909 [c_void_p, c_int],
2910 _CXString),
2911
2912 ("clang_getCompletionPriority",
2913 [c_void_p],
2914 c_int),
2915
2916 ("clang_getCString",
2917 [_CXString],
2918 c_char_p),
2919
2920 ("clang_getCursor",
2921 [TranslationUnit, SourceLocation],
2922 Cursor),
2923
2924 ("clang_getCursorDefinition",
2925 [Cursor],
2926 Cursor,
2927 Cursor.from_result),
2928
2929 ("clang_getCursorDisplayName",
2930 [Cursor],
2931 _CXString,
2932 _CXString.from_result),
2933
2934 ("clang_getCursorExtent",
2935 [Cursor],
2936 SourceRange),
2937
2938 ("clang_getCursorLexicalParent",
2939 [Cursor],
2940 Cursor,
2941 Cursor.from_cursor_result),
2942
2943 ("clang_getCursorLocation",
2944 [Cursor],
2945 SourceLocation),
2946
2947 ("clang_getCursorReferenced",
2948 [Cursor],
2949 Cursor,
2950 Cursor.from_result),
2951
2952 ("clang_getCursorReferenceNameRange",
2953 [Cursor, c_uint, c_uint],
2954 SourceRange),
2955
2956 ("clang_getCursorSemanticParent",
2957 [Cursor],
2958 Cursor,
2959 Cursor.from_cursor_result),
2960
2961 ("clang_getCursorSpelling",
2962 [Cursor],
2963 _CXString,
2964 _CXString.from_result),
2965
2966 ("clang_getCursorType",
2967 [Cursor],
2968 Type,
2969 Type.from_result),
2970
2971 ("clang_getCursorUSR",
2972 [Cursor],
2973 _CXString,
2974 _CXString.from_result),
2975
2976# ("clang_getCXTUResourceUsage",
2977# [TranslationUnit],
2978# CXTUResourceUsage),
2979
2980 ("clang_getCXXAccessSpecifier",
2981 [Cursor],
2982 c_uint),
2983
2984 ("clang_getDeclObjCTypeEncoding",
2985 [Cursor],
2986 _CXString,
2987 _CXString.from_result),
2988
2989 ("clang_getDiagnostic",
2990 [c_object_p, c_uint],
2991 c_object_p),
2992
2993 ("clang_getDiagnosticCategory",
2994 [Diagnostic],
2995 c_uint),
2996
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002997 ("clang_getDiagnosticCategoryText",
2998 [Diagnostic],
Tobias Grosser010556e2012-09-01 08:55:17 +00002999 _CXString,
3000 _CXString.from_result),
3001
3002 ("clang_getDiagnosticFixIt",
3003 [Diagnostic, c_uint, POINTER(SourceRange)],
3004 _CXString,
3005 _CXString.from_result),
3006
3007 ("clang_getDiagnosticLocation",
3008 [Diagnostic],
3009 SourceLocation),
3010
3011 ("clang_getDiagnosticNumFixIts",
3012 [Diagnostic],
3013 c_uint),
3014
3015 ("clang_getDiagnosticNumRanges",
3016 [Diagnostic],
3017 c_uint),
3018
3019 ("clang_getDiagnosticOption",
3020 [Diagnostic, POINTER(_CXString)],
3021 _CXString,
3022 _CXString.from_result),
3023
3024 ("clang_getDiagnosticRange",
3025 [Diagnostic, c_uint],
3026 SourceRange),
3027
3028 ("clang_getDiagnosticSeverity",
3029 [Diagnostic],
3030 c_int),
3031
3032 ("clang_getDiagnosticSpelling",
3033 [Diagnostic],
3034 _CXString,
3035 _CXString.from_result),
3036
3037 ("clang_getElementType",
3038 [Type],
3039 Type,
3040 Type.from_result),
3041
3042 ("clang_getEnumConstantDeclUnsignedValue",
3043 [Cursor],
3044 c_ulonglong),
3045
3046 ("clang_getEnumConstantDeclValue",
3047 [Cursor],
3048 c_longlong),
3049
3050 ("clang_getEnumDeclIntegerType",
3051 [Cursor],
3052 Type,
3053 Type.from_result),
3054
3055 ("clang_getFile",
3056 [TranslationUnit, c_char_p],
3057 c_object_p),
3058
3059 ("clang_getFileName",
3060 [File],
3061 _CXString), # TODO go through _CXString.from_result?
3062
3063 ("clang_getFileTime",
3064 [File],
3065 c_uint),
3066
3067 ("clang_getIBOutletCollectionType",
3068 [Cursor],
3069 Type,
3070 Type.from_result),
3071
3072 ("clang_getIncludedFile",
3073 [Cursor],
3074 File,
3075 File.from_cursor_result),
3076
3077 ("clang_getInclusions",
3078 [TranslationUnit, callbacks['translation_unit_includes'], py_object]),
3079
3080 ("clang_getInstantiationLocation",
3081 [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint),
3082 POINTER(c_uint)]),
3083
3084 ("clang_getLocation",
3085 [TranslationUnit, File, c_uint, c_uint],
3086 SourceLocation),
3087
3088 ("clang_getLocationForOffset",
3089 [TranslationUnit, File, c_uint],
3090 SourceLocation),
3091
3092 ("clang_getNullCursor",
3093 None,
3094 Cursor),
3095
3096 ("clang_getNumArgTypes",
3097 [Type],
3098 c_uint),
3099
3100 ("clang_getNumCompletionChunks",
3101 [c_void_p],
3102 c_int),
3103
3104 ("clang_getNumDiagnostics",
3105 [c_object_p],
3106 c_uint),
3107
3108 ("clang_getNumElements",
3109 [Type],
3110 c_longlong),
3111
3112 ("clang_getNumOverloadedDecls",
3113 [Cursor],
3114 c_uint),
3115
3116 ("clang_getOverloadedDecl",
3117 [Cursor, c_uint],
3118 Cursor,
3119 Cursor.from_cursor_result),
3120
3121 ("clang_getPointeeType",
3122 [Type],
3123 Type,
3124 Type.from_result),
3125
3126 ("clang_getRange",
3127 [SourceLocation, SourceLocation],
3128 SourceRange),
3129
3130 ("clang_getRangeEnd",
3131 [SourceRange],
3132 SourceLocation),
3133
3134 ("clang_getRangeStart",
3135 [SourceRange],
3136 SourceLocation),
3137
3138 ("clang_getResultType",
3139 [Type],
3140 Type,
3141 Type.from_result),
3142
3143 ("clang_getSpecializedCursorTemplate",
3144 [Cursor],
3145 Cursor,
3146 Cursor.from_cursor_result),
3147
3148 ("clang_getTemplateCursorKind",
3149 [Cursor],
3150 c_uint),
3151
3152 ("clang_getTokenExtent",
3153 [TranslationUnit, Token],
3154 SourceRange),
3155
3156 ("clang_getTokenKind",
3157 [Token],
3158 c_uint),
3159
3160 ("clang_getTokenLocation",
3161 [TranslationUnit, Token],
3162 SourceLocation),
3163
3164 ("clang_getTokenSpelling",
3165 [TranslationUnit, Token],
3166 _CXString,
3167 _CXString.from_result),
3168
3169 ("clang_getTranslationUnitCursor",
3170 [TranslationUnit],
3171 Cursor,
3172 Cursor.from_result),
3173
3174 ("clang_getTranslationUnitSpelling",
3175 [TranslationUnit],
3176 _CXString,
3177 _CXString.from_result),
3178
3179 ("clang_getTUResourceUsageName",
3180 [c_uint],
3181 c_char_p),
3182
3183 ("clang_getTypeDeclaration",
3184 [Type],
3185 Cursor,
3186 Cursor.from_result),
3187
3188 ("clang_getTypedefDeclUnderlyingType",
3189 [Cursor],
3190 Type,
3191 Type.from_result),
3192
3193 ("clang_getTypeKindSpelling",
3194 [c_uint],
3195 _CXString,
3196 _CXString.from_result),
3197
Argyrios Kyrtzidisc23cb2d2013-10-03 16:19:27 +00003198 ("clang_getTypeSpelling",
3199 [Type],
3200 _CXString,
3201 _CXString.from_result),
3202
Tobias Grosser010556e2012-09-01 08:55:17 +00003203 ("clang_hashCursor",
3204 [Cursor],
3205 c_uint),
3206
3207 ("clang_isAttribute",
3208 [CursorKind],
3209 bool),
3210
3211 ("clang_isConstQualifiedType",
3212 [Type],
3213 bool),
3214
3215 ("clang_isCursorDefinition",
3216 [Cursor],
3217 bool),
3218
3219 ("clang_isDeclaration",
3220 [CursorKind],
3221 bool),
3222
3223 ("clang_isExpression",
3224 [CursorKind],
3225 bool),
3226
3227 ("clang_isFileMultipleIncludeGuarded",
3228 [TranslationUnit, File],
3229 bool),
3230
3231 ("clang_isFunctionTypeVariadic",
3232 [Type],
3233 bool),
3234
3235 ("clang_isInvalid",
3236 [CursorKind],
3237 bool),
3238
3239 ("clang_isPODType",
3240 [Type],
3241 bool),
3242
3243 ("clang_isPreprocessing",
3244 [CursorKind],
3245 bool),
3246
3247 ("clang_isReference",
3248 [CursorKind],
3249 bool),
3250
3251 ("clang_isRestrictQualifiedType",
3252 [Type],
3253 bool),
3254
3255 ("clang_isStatement",
3256 [CursorKind],
3257 bool),
3258
3259 ("clang_isTranslationUnit",
3260 [CursorKind],
3261 bool),
3262
3263 ("clang_isUnexposed",
3264 [CursorKind],
3265 bool),
3266
3267 ("clang_isVirtualBase",
3268 [Cursor],
3269 bool),
3270
3271 ("clang_isVolatileQualifiedType",
3272 [Type],
3273 bool),
3274
3275 ("clang_parseTranslationUnit",
3276 [Index, c_char_p, c_void_p, c_int, c_void_p, c_int, c_int],
3277 c_object_p),
3278
3279 ("clang_reparseTranslationUnit",
3280 [TranslationUnit, c_int, c_void_p, c_int],
3281 c_int),
3282
3283 ("clang_saveTranslationUnit",
3284 [TranslationUnit, c_char_p, c_uint],
3285 c_int),
3286
3287 ("clang_tokenize",
3288 [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]),
3289
3290 ("clang_visitChildren",
3291 [Cursor, callbacks['cursor_visit'], py_object],
3292 c_uint),
Gregory Szorcb03b57d2012-11-01 05:46:30 +00003293
3294 ("clang_Cursor_getNumArguments",
3295 [Cursor],
3296 c_int),
3297
3298 ("clang_Cursor_getArgument",
3299 [Cursor, c_uint],
3300 Cursor,
3301 Cursor.from_result),
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00003302
3303 ("clang_Cursor_isBitField",
3304 [Cursor],
Dmitri Gribenko52bb2a02013-04-21 18:35:51 +00003305 bool),
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00003306
Argyrios Kyrtzidisc23cb2d2013-10-03 16:19:27 +00003307 ("clang_Cursor_getBriefCommentText",
3308 [Cursor],
3309 _CXString,
3310 _CXString.from_result),
3311
3312 ("clang_Cursor_getRawCommentText",
3313 [Cursor],
3314 _CXString,
3315 _CXString.from_result),
3316
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00003317 ("clang_Type_getAlignOf",
3318 [Type],
3319 c_longlong),
3320
Argyrios Kyrtzidis659837e2013-10-11 19:58:38 +00003321 ("clang_Type_getClassType",
3322 [Type],
3323 Type,
3324 Type.from_result),
3325
Argyrios Kyrtzidis411d33a2013-04-11 01:20:11 +00003326 ("clang_Type_getOffsetOf",
3327 [Type, c_char_p],
3328 c_longlong),
3329
3330 ("clang_Type_getSizeOf",
3331 [Type],
Argyrios Kyrtzidisdd9e2cb2013-09-25 00:14:43 +00003332 c_longlong),
Argyrios Kyrtzidis659837e2013-10-11 19:58:38 +00003333
3334 ("clang_Type_getCXXRefQualifier",
3335 [Type],
3336 c_uint),
Tobias Grosser010556e2012-09-01 08:55:17 +00003337]
3338
3339class LibclangError(Exception):
3340 def __init__(self, message):
3341 self.m = message
3342
3343 def __str__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003344 return self.m
Tobias Grosser010556e2012-09-01 08:55:17 +00003345
Tobias Grosser857134e2012-09-05 20:23:53 +00003346def register_function(lib, item, ignore_errors):
Tobias Grosser010556e2012-09-01 08:55:17 +00003347 # A function may not exist, if these bindings are used with an older or
3348 # incompatible version of libclang.so.
3349 try:
3350 func = getattr(lib, item[0])
3351 except AttributeError as e:
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003352 msg = str(e) + ". Please ensure that your python bindings are "\
3353 "compatible with your libclang.so version."
Tobias Grosser857134e2012-09-05 20:23:53 +00003354 if ignore_errors:
3355 return
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003356 raise LibclangError(msg)
Tobias Grosser010556e2012-09-01 08:55:17 +00003357
3358 if len(item) >= 2:
3359 func.argtypes = item[1]
3360
3361 if len(item) >= 3:
3362 func.restype = item[2]
3363
3364 if len(item) == 4:
3365 func.errcheck = item[3]
3366
Tobias Grosser857134e2012-09-05 20:23:53 +00003367def register_functions(lib, ignore_errors):
Gregory Szorc9537e202012-07-12 04:56:46 +00003368 """Register function prototypes with a libclang library instance.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00003369
Gregory Szorc9537e202012-07-12 04:56:46 +00003370 This must be called as part of library instantiation so Python knows how
3371 to call out to the shared library.
3372 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00003373
Tobias Grosser010556e2012-09-01 08:55:17 +00003374 def register(item):
Tobias Grosser857134e2012-09-05 20:23:53 +00003375 return register_function(lib, item, ignore_errors)
Tobias Grosser58ba8c92011-10-31 00:31:32 +00003376
Tobias Grosser010556e2012-09-01 08:55:17 +00003377 map(register, functionList)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00003378
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003379class Config:
3380 library_path = None
3381 library_file = None
Tobias Grosser857134e2012-09-05 20:23:53 +00003382 compatibility_check = True
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003383 loaded = False
3384
3385 @staticmethod
3386 def set_library_path(path):
3387 """Set the path in which to search for libclang"""
3388 if Config.loaded:
3389 raise Exception("library path must be set before before using " \
3390 "any other functionalities in libclang.")
3391
3392 Config.library_path = path
3393
3394 @staticmethod
Matt Beaumont-Gay379ffe42012-12-11 17:37:46 +00003395 def set_library_file(filename):
3396 """Set the exact location of libclang"""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003397 if Config.loaded:
3398 raise Exception("library file must be set before before using " \
3399 "any other functionalities in libclang.")
3400
Matt Beaumont-Gay379ffe42012-12-11 17:37:46 +00003401 Config.library_file = filename
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003402
Tobias Grosser857134e2012-09-05 20:23:53 +00003403 @staticmethod
3404 def set_compatibility_check(check_status):
3405 """ Perform compatibility check when loading libclang
3406
3407 The python bindings are only tested and evaluated with the version of
3408 libclang they are provided with. To ensure correct behavior a (limited)
3409 compatibility check is performed when loading the bindings. This check
3410 will throw an exception, as soon as it fails.
3411
3412 In case these bindings are used with an older version of libclang, parts
3413 that have been stable between releases may still work. Users of the
3414 python bindings can disable the compatibility check. This will cause
3415 the python bindings to load, even though they are written for a newer
3416 version of libclang. Failures now arise if unsupported or incompatible
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003417 features are accessed. The user is required to test themselves if the
3418 features they are using are available and compatible between different
Tobias Grosser857134e2012-09-05 20:23:53 +00003419 libclang versions.
3420 """
3421 if Config.loaded:
3422 raise Exception("compatibility_check must be set before before " \
3423 "using any other functionalities in libclang.")
3424
3425 Config.compatibility_check = check_status
3426
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003427 @CachedProperty
3428 def lib(self):
3429 lib = self.get_cindex_library()
Tobias Grosser857134e2012-09-05 20:23:53 +00003430 register_functions(lib, not Config.compatibility_check)
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003431 Config.loaded = True
3432 return lib
3433
3434 def get_filename(self):
3435 if Config.library_file:
3436 return Config.library_file
3437
3438 import platform
3439 name = platform.system()
3440
3441 if name == 'Darwin':
3442 file = 'libclang.dylib'
3443 elif name == 'Windows':
3444 file = 'libclang.dll'
3445 else:
3446 file = 'libclang.so'
3447
3448 if Config.library_path:
3449 file = Config.library_path + '/' + file
3450
3451 return file
3452
3453 def get_cindex_library(self):
3454 try:
3455 library = cdll.LoadLibrary(self.get_filename())
3456 except OSError as e:
3457 msg = str(e) + ". To provide a path to libclang use " \
3458 "Config.set_library_path() or " \
3459 "Config.set_library_file()."
3460 raise LibclangError(msg)
3461
3462 return library
3463
Dmitri Gribenkoc12d6a02012-09-22 17:52:29 +00003464 def function_exists(self, name):
3465 try:
3466 getattr(self.lib, name)
3467 except AttributeError:
3468 return False
3469
3470 return True
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00003471
Gregory Szorcbe51e432012-07-12 07:21:12 +00003472def register_enumerations():
3473 for name, value in clang.enumerations.TokenKinds:
3474 TokenKind.register(value, name)
3475
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003476conf = Config()
Gregory Szorcbe51e432012-07-12 07:21:12 +00003477register_enumerations()
3478
Gregory Szorcfbf620b2012-05-08 05:56:38 +00003479__all__ = [
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003480 'Config',
Gregory Szorcfbf620b2012-05-08 05:56:38 +00003481 'CodeCompletionResults',
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00003482 'CompilationDatabase',
3483 'CompileCommands',
3484 'CompileCommand',
Gregory Szorcfbf620b2012-05-08 05:56:38 +00003485 'CursorKind',
3486 'Cursor',
3487 'Diagnostic',
3488 'File',
3489 'FixIt',
3490 'Index',
3491 'SourceLocation',
3492 'SourceRange',
Gregory Szorcbe51e432012-07-12 07:21:12 +00003493 'TokenKind',
3494 'Token',
Gregory Szorcfbf620b2012-05-08 05:56:38 +00003495 'TranslationUnitLoadError',
3496 'TranslationUnit',
3497 'TypeKind',
3498 'Type',
3499]