blob: d265f7e520784fc1380c6342e2ff9e79c01b9044 [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
Daniel Dunbarf8690832010-01-24 21:20:21 +0000269 def __repr__(self):
270 return "<SourceRange start %r, end %r>" % (self.start, self.end)
Daniel Dunbar30c0f262010-01-24 02:02:07 +0000271
Daniel Dunbar532fc632010-01-30 23:59:02 +0000272class Diagnostic(object):
273 """
274 A Diagnostic is a single instance of a Clang diagnostic. It includes the
275 diagnostic severity, the message, the location the diagnostic occurred, as
276 well as additional source ranges and associated fix-it hints.
277 """
278
279 Ignored = 0
280 Note = 1
281 Warning = 2
282 Error = 3
283 Fatal = 4
284
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000285 def __init__(self, ptr):
286 self.ptr = ptr
287
288 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000289 conf.lib.clang_disposeDiagnostic(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000290
291 @property
292 def severity(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000293 return conf.lib.clang_getDiagnosticSeverity(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000294
295 @property
296 def location(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000297 return conf.lib.clang_getDiagnosticLocation(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000298
299 @property
300 def spelling(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000301 return conf.lib.clang_getDiagnosticSpelling(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000302
303 @property
304 def ranges(self):
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +0000305 class RangeIterator:
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000306 def __init__(self, diag):
307 self.diag = diag
308
309 def __len__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000310 return int(conf.lib.clang_getDiagnosticNumRanges(self.diag))
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000311
312 def __getitem__(self, key):
Tobias Grosserba5d10b2011-10-31 02:06:50 +0000313 if (key >= len(self)):
314 raise IndexError
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000315 return conf.lib.clang_getDiagnosticRange(self.diag, key)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000316
Tobias Grosserff090ca2011-02-05 17:53:48 +0000317 return RangeIterator(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000318
319 @property
320 def fixits(self):
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +0000321 class FixItIterator:
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000322 def __init__(self, diag):
323 self.diag = diag
324
325 def __len__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000326 return int(conf.lib.clang_getDiagnosticNumFixIts(self.diag))
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000327
328 def __getitem__(self, key):
329 range = SourceRange()
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000330 value = conf.lib.clang_getDiagnosticFixIt(self.diag, key,
Gregory Szorc9537e202012-07-12 04:56:46 +0000331 byref(range))
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +0000332 if len(value) == 0:
333 raise IndexError
Benjamin Kramer3b0cf092010-03-06 14:53:07 +0000334
335 return FixIt(range, value)
336
Tobias Grosserff090ca2011-02-05 17:53:48 +0000337 return FixItIterator(self)
Daniel Dunbar532fc632010-01-30 23:59:02 +0000338
Tobias Grosserea403822012-02-05 11:41:58 +0000339 @property
340 def category_number(self):
341 """The category number for this diagnostic."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000342 return conf.lib.clang_getDiagnosticCategory(self)
Tobias Grosserea403822012-02-05 11:41:58 +0000343
344 @property
345 def category_name(self):
346 """The string name of the category for this diagnostic."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000347 return conf.lib.clang_getDiagnosticCategoryName(self.category_number)
Tobias Grosserea403822012-02-05 11:41:58 +0000348
349 @property
350 def option(self):
351 """The command-line option that enables this diagnostic."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000352 return conf.lib.clang_getDiagnosticOption(self, None)
Tobias Grosserea403822012-02-05 11:41:58 +0000353
354 @property
355 def disable_option(self):
356 """The command-line option that disables this diagnostic."""
357 disable = _CXString()
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000358 conf.lib.clang_getDiagnosticOption(self, byref(disable))
Tobias Grosserea403822012-02-05 11:41:58 +0000359
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000360 return conf.lib.clang_getCString(disable)
Tobias Grosserea403822012-02-05 11:41:58 +0000361
Daniel Dunbar532fc632010-01-30 23:59:02 +0000362 def __repr__(self):
363 return "<Diagnostic severity %r, location %r, spelling %r>" % (
364 self.severity, self.location, self.spelling)
365
Tobias Grosserff090ca2011-02-05 17:53:48 +0000366 def from_param(self):
367 return self.ptr
368
Daniel Dunbar532fc632010-01-30 23:59:02 +0000369class FixIt(object):
370 """
371 A FixIt represents a transformation to be applied to the source to
372 "fix-it". The fix-it shouldbe applied by replacing the given source range
373 with the given value.
374 """
375
376 def __init__(self, range, value):
377 self.range = range
378 self.value = value
379
380 def __repr__(self):
381 return "<FixIt range %r, value %r>" % (self.range, self.value)
382
Gregory Szorcbe51e432012-07-12 07:21:12 +0000383class TokenGroup(object):
384 """Helper class to facilitate token management.
385
386 Tokens are allocated from libclang in chunks. They must be disposed of as a
387 collective group.
388
389 One purpose of this class is for instances to represent groups of allocated
390 tokens. Each token in a group contains a reference back to an instance of
391 this class. When all tokens from a group are garbage collected, it allows
392 this class to be garbage collected. When this class is garbage collected,
393 it calls the libclang destructor which invalidates all tokens in the group.
394
395 You should not instantiate this class outside of this module.
396 """
397 def __init__(self, tu, memory, count):
398 self._tu = tu
399 self._memory = memory
400 self._count = count
401
402 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000403 conf.lib.clang_disposeTokens(self._tu, self._memory, self._count)
Gregory Szorcbe51e432012-07-12 07:21:12 +0000404
405 @staticmethod
406 def get_tokens(tu, extent):
407 """Helper method to return all tokens in an extent.
408
409 This functionality is needed multiple places in this module. We define
410 it here because it seems like a logical place.
411 """
412 tokens_memory = POINTER(Token)()
413 tokens_count = c_uint()
414
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000415 conf.lib.clang_tokenize(tu, extent, byref(tokens_memory),
Gregory Szorcbe51e432012-07-12 07:21:12 +0000416 byref(tokens_count))
417
418 count = int(tokens_count.value)
419
420 # If we get no tokens, no memory was allocated. Be sure not to return
421 # anything and potentially call a destructor on nothing.
422 if count < 1:
423 return
424
425 tokens_array = cast(tokens_memory, POINTER(Token * count)).contents
426
427 token_group = TokenGroup(tu, tokens_memory, tokens_count)
428
429 for i in xrange(0, count):
430 token = Token()
431 token.int_data = tokens_array[i].int_data
432 token.ptr_data = tokens_array[i].ptr_data
433 token._tu = tu
434 token._group = token_group
435
436 yield token
437
438class TokenKind(object):
439 """Describes a specific type of a Token."""
440
441 _value_map = {} # int -> TokenKind
442
443 def __init__(self, value, name):
444 """Create a new TokenKind instance from a numeric value and a name."""
445 self.value = value
446 self.name = name
447
448 def __repr__(self):
449 return 'TokenKind.%s' % (self.name,)
450
451 @staticmethod
452 def from_value(value):
453 """Obtain a registered TokenKind instance from its value."""
454 result = TokenKind._value_map.get(value, None)
455
456 if result is None:
457 raise ValueError('Unknown TokenKind: %d' % value)
458
459 return result
460
461 @staticmethod
462 def register(value, name):
463 """Register a new TokenKind enumeration.
464
465 This should only be called at module load time by code within this
466 package.
467 """
468 if value in TokenKind._value_map:
469 raise ValueError('TokenKind already registered: %d' % value)
470
471 kind = TokenKind(value, name)
472 TokenKind._value_map[value] = kind
473 setattr(TokenKind, name, kind)
474
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000475### Cursor Kinds ###
476
477class CursorKind(object):
478 """
479 A CursorKind describes the kind of entity that a cursor points to.
480 """
481
482 # The unique kind objects, indexed by id.
483 _kinds = []
484 _name_map = None
485
486 def __init__(self, value):
487 if value >= len(CursorKind._kinds):
488 CursorKind._kinds += [None] * (value - len(CursorKind._kinds) + 1)
489 if CursorKind._kinds[value] is not None:
490 raise ValueError,'CursorKind already loaded'
491 self.value = value
492 CursorKind._kinds[value] = self
493 CursorKind._name_map = None
494
495 def from_param(self):
496 return self.value
497
498 @property
499 def name(self):
500 """Get the enumeration name of this cursor kind."""
501 if self._name_map is None:
502 self._name_map = {}
503 for key,value in CursorKind.__dict__.items():
504 if isinstance(value,CursorKind):
505 self._name_map[value] = key
506 return self._name_map[self]
507
508 @staticmethod
509 def from_id(id):
510 if id >= len(CursorKind._kinds) or CursorKind._kinds[id] is None:
511 raise ValueError,'Unknown cursor kind'
512 return CursorKind._kinds[id]
513
Daniel Dunbara6a64992010-01-24 21:20:39 +0000514 @staticmethod
515 def get_all_kinds():
Daniel Dunbar4efd6322010-01-25 00:43:08 +0000516 """Return all CursorKind enumeration instances."""
Daniel Dunbara6a64992010-01-24 21:20:39 +0000517 return filter(None, CursorKind._kinds)
518
519 def is_declaration(self):
520 """Test if this is a declaration kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000521 return conf.lib.clang_isDeclaration(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000522
523 def is_reference(self):
524 """Test if this is a reference kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000525 return conf.lib.clang_isReference(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000526
527 def is_expression(self):
528 """Test if this is an expression kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000529 return conf.lib.clang_isExpression(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000530
531 def is_statement(self):
532 """Test if this is a statement kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000533 return conf.lib.clang_isStatement(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000534
Douglas Gregor8be80e12011-07-06 03:00:34 +0000535 def is_attribute(self):
536 """Test if this is an attribute kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000537 return conf.lib.clang_isAttribute(self)
Douglas Gregor8be80e12011-07-06 03:00:34 +0000538
Daniel Dunbara6a64992010-01-24 21:20:39 +0000539 def is_invalid(self):
540 """Test if this is an invalid kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000541 return conf.lib.clang_isInvalid(self)
Daniel Dunbara6a64992010-01-24 21:20:39 +0000542
Tobias Grossereb136342012-02-05 11:42:09 +0000543 def is_translation_unit(self):
544 """Test if this is a translation unit kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000545 return conf.lib.clang_isTranslationUnit(self)
Tobias Grossereb136342012-02-05 11:42:09 +0000546
547 def is_preprocessing(self):
548 """Test if this is a preprocessing kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000549 return conf.lib.clang_isPreprocessing(self)
Tobias Grossereb136342012-02-05 11:42:09 +0000550
551 def is_unexposed(self):
552 """Test if this is an unexposed kind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +0000553 return conf.lib.clang_isUnexposed(self)
Tobias Grossereb136342012-02-05 11:42:09 +0000554
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000555 def __repr__(self):
556 return 'CursorKind.%s' % (self.name,)
557
558# FIXME: Is there a nicer way to expose this enumeration? We could potentially
559# represent the nested structure, or even build a class hierarchy. The main
560# things we want for sure are (a) simple external access to kinds, (b) a place
561# to hang a description and name, (c) easy to keep in sync with Index.h.
562
Daniel Dunbara6a64992010-01-24 21:20:39 +0000563###
564# Declaration Kinds
565
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000566# A declaration whose specific kind is not exposed via this interface.
567#
568# Unexposed declarations have the same operations as any other kind of
569# declaration; one can extract their location information, spelling, find their
570# definitions, etc. However, the specific kind of the declaration is not
571# reported.
572CursorKind.UNEXPOSED_DECL = CursorKind(1)
573
574# A C or C++ struct.
575CursorKind.STRUCT_DECL = CursorKind(2)
576
577# A C or C++ union.
578CursorKind.UNION_DECL = CursorKind(3)
579
580# A C++ class.
581CursorKind.CLASS_DECL = CursorKind(4)
582
583# An enumeration.
584CursorKind.ENUM_DECL = CursorKind(5)
585
586# A field (in C) or non-static data member (in C++) in a struct, union, or C++
587# class.
588CursorKind.FIELD_DECL = CursorKind(6)
589
590# An enumerator constant.
591CursorKind.ENUM_CONSTANT_DECL = CursorKind(7)
592
593# A function.
594CursorKind.FUNCTION_DECL = CursorKind(8)
595
596# A variable.
597CursorKind.VAR_DECL = CursorKind(9)
598
599# A function or method parameter.
600CursorKind.PARM_DECL = CursorKind(10)
601
602# An Objective-C @interface.
603CursorKind.OBJC_INTERFACE_DECL = CursorKind(11)
604
605# An Objective-C @interface for a category.
606CursorKind.OBJC_CATEGORY_DECL = CursorKind(12)
607
608# An Objective-C @protocol declaration.
609CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13)
610
611# An Objective-C @property declaration.
612CursorKind.OBJC_PROPERTY_DECL = CursorKind(14)
613
614# An Objective-C instance variable.
615CursorKind.OBJC_IVAR_DECL = CursorKind(15)
616
617# An Objective-C instance method.
618CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16)
619
620# An Objective-C class method.
621CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17)
622
623# An Objective-C @implementation.
624CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18)
625
626# An Objective-C @implementation for a category.
627CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19)
628
Daniel Dunbara6a64992010-01-24 21:20:39 +0000629# A typedef.
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000630CursorKind.TYPEDEF_DECL = CursorKind(20)
631
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000632# A C++ class method.
633CursorKind.CXX_METHOD = CursorKind(21)
634
635# A C++ namespace.
636CursorKind.NAMESPACE = CursorKind(22)
637
638# A linkage specification, e.g. 'extern "C"'.
639CursorKind.LINKAGE_SPEC = CursorKind(23)
640
641# A C++ constructor.
642CursorKind.CONSTRUCTOR = CursorKind(24)
643
644# A C++ destructor.
645CursorKind.DESTRUCTOR = CursorKind(25)
646
647# A C++ conversion function.
648CursorKind.CONVERSION_FUNCTION = CursorKind(26)
649
650# A C++ template type parameter
651CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27)
652
653# A C++ non-type template paramater.
654CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28)
655
656# A C++ template template parameter.
657CursorKind.TEMPLATE_TEMPLATE_PARAMTER = CursorKind(29)
658
659# A C++ function template.
660CursorKind.FUNCTION_TEMPLATE = CursorKind(30)
661
662# A C++ class template.
663CursorKind.CLASS_TEMPLATE = CursorKind(31)
664
665# A C++ class template partial specialization.
666CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32)
667
668# A C++ namespace alias declaration.
669CursorKind.NAMESPACE_ALIAS = CursorKind(33)
670
671# A C++ using directive
672CursorKind.USING_DIRECTIVE = CursorKind(34)
673
674# A C++ using declaration
675CursorKind.USING_DECLARATION = CursorKind(35)
676
Douglas Gregor42b29842011-10-05 19:00:14 +0000677# A Type alias decl.
678CursorKind.TYPE_ALIAS_DECL = CursorKind(36)
679
680# A Objective-C synthesize decl
681CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37)
682
683# A Objective-C dynamic decl
684CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38)
685
686# A C++ access specifier decl.
687CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39)
688
689
Daniel Dunbara6a64992010-01-24 21:20:39 +0000690###
691# Reference Kinds
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000692
693CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40)
694CursorKind.OBJC_PROTOCOL_REF = CursorKind(41)
695CursorKind.OBJC_CLASS_REF = CursorKind(42)
696
697# A reference to a type declaration.
698#
699# A type reference occurs anywhere where a type is named but not
700# declared. For example, given:
701# typedef unsigned size_type;
702# size_type size;
703#
704# The typedef is a declaration of size_type (CXCursor_TypedefDecl),
705# while the type of the variable "size" is referenced. The cursor
706# referenced by the type of size is the typedef for size_type.
707CursorKind.TYPE_REF = CursorKind(43)
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000708CursorKind.CXX_BASE_SPECIFIER = CursorKind(44)
709
710# A reference to a class template, function template, template
711# template parameter, or class template partial specialization.
712CursorKind.TEMPLATE_REF = CursorKind(45)
713
714# A reference to a namespace or namepsace alias.
715CursorKind.NAMESPACE_REF = CursorKind(46)
716
717# A reference to a member of a struct, union, or class that occurs in
718# some non-expression context, e.g., a designated initializer.
719CursorKind.MEMBER_REF = CursorKind(47)
720
721# A reference to a labeled statement.
722CursorKind.LABEL_REF = CursorKind(48)
723
724# A reference toa a set of overloaded functions or function templates
725# that has not yet been resolved to a specific function or function template.
726CursorKind.OVERLOADED_DECL_REF = CursorKind(49)
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000727
Daniel Dunbara6a64992010-01-24 21:20:39 +0000728###
729# Invalid/Error Kinds
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000730
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000731CursorKind.INVALID_FILE = CursorKind(70)
732CursorKind.NO_DECL_FOUND = CursorKind(71)
733CursorKind.NOT_IMPLEMENTED = CursorKind(72)
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000734CursorKind.INVALID_CODE = CursorKind(73)
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000735
Daniel Dunbara6a64992010-01-24 21:20:39 +0000736###
737# Expression Kinds
738
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000739# An expression whose specific kind is not exposed via this interface.
740#
741# Unexposed expressions have the same operations as any other kind of
742# expression; one can extract their location information, spelling, children,
743# etc. However, the specific kind of the expression is not reported.
744CursorKind.UNEXPOSED_EXPR = CursorKind(100)
745
746# An expression that refers to some value declaration, such as a function,
747# varible, or enumerator.
748CursorKind.DECL_REF_EXPR = CursorKind(101)
749
750# An expression that refers to a member of a struct, union, class, Objective-C
751# class, etc.
752CursorKind.MEMBER_REF_EXPR = CursorKind(102)
753
754# An expression that calls a function.
755CursorKind.CALL_EXPR = CursorKind(103)
756
757# An expression that sends a message to an Objective-C object or class.
758CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104)
759
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000760# An expression that represents a block literal.
761CursorKind.BLOCK_EXPR = CursorKind(105)
762
Douglas Gregor42b29842011-10-05 19:00:14 +0000763# An integer literal.
764CursorKind.INTEGER_LITERAL = CursorKind(106)
765
766# A floating point number literal.
767CursorKind.FLOATING_LITERAL = CursorKind(107)
768
769# An imaginary number literal.
770CursorKind.IMAGINARY_LITERAL = CursorKind(108)
771
772# A string literal.
773CursorKind.STRING_LITERAL = CursorKind(109)
774
775# A character literal.
776CursorKind.CHARACTER_LITERAL = CursorKind(110)
777
778# A parenthesized expression, e.g. "(1)".
779#
780# This AST node is only formed if full location information is requested.
781CursorKind.PAREN_EXPR = CursorKind(111)
782
783# This represents the unary-expression's (except sizeof and
784# alignof).
785CursorKind.UNARY_OPERATOR = CursorKind(112)
786
787# [C99 6.5.2.1] Array Subscripting.
788CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113)
789
790# A builtin binary operation expression such as "x + y" or
791# "x <= y".
792CursorKind.BINARY_OPERATOR = CursorKind(114)
793
794# Compound assignment such as "+=".
795CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115)
796
797# The ?: ternary operator.
Douglas Gregor39a03d12012-06-08 00:16:27 +0000798CursorKind.CONDITIONAL_OPERATOR = CursorKind(116)
Douglas Gregor42b29842011-10-05 19:00:14 +0000799
800# An explicit cast in C (C99 6.5.4) or a C-style cast in C++
801# (C++ [expr.cast]), which uses the syntax (Type)expr.
802#
803# For example: (int)f.
804CursorKind.CSTYLE_CAST_EXPR = CursorKind(117)
805
806# [C99 6.5.2.5]
807CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118)
808
809# Describes an C or C++ initializer list.
810CursorKind.INIT_LIST_EXPR = CursorKind(119)
811
812# The GNU address of label extension, representing &&label.
813CursorKind.ADDR_LABEL_EXPR = CursorKind(120)
814
815# This is the GNU Statement Expression extension: ({int X=4; X;})
816CursorKind.StmtExpr = CursorKind(121)
817
Benjamin Kramerffbe9b92011-12-23 17:00:35 +0000818# Represents a C11 generic selection.
Douglas Gregor42b29842011-10-05 19:00:14 +0000819CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122)
820
821# Implements the GNU __null extension, which is a name for a null
822# pointer constant that has integral type (e.g., int or long) and is the same
823# size and alignment as a pointer.
824#
825# The __null extension is typically only used by system headers, which define
826# NULL as __null in C++ rather than using 0 (which is an integer that may not
827# match the size of a pointer).
828CursorKind.GNU_NULL_EXPR = CursorKind(123)
829
830# C++'s static_cast<> expression.
831CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124)
832
833# C++'s dynamic_cast<> expression.
834CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125)
835
836# C++'s reinterpret_cast<> expression.
837CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126)
838
839# C++'s const_cast<> expression.
840CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127)
841
842# Represents an explicit C++ type conversion that uses "functional"
843# notion (C++ [expr.type.conv]).
844#
845# Example:
846# \code
847# x = int(0.5);
848# \endcode
849CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128)
850
851# A C++ typeid expression (C++ [expr.typeid]).
852CursorKind.CXX_TYPEID_EXPR = CursorKind(129)
853
854# [C++ 2.13.5] C++ Boolean Literal.
855CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130)
856
857# [C++0x 2.14.7] C++ Pointer Literal.
858CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131)
859
860# Represents the "this" expression in C++
861CursorKind.CXX_THIS_EXPR = CursorKind(132)
862
863# [C++ 15] C++ Throw Expression.
864#
865# This handles 'throw' and 'throw' assignment-expression. When
866# assignment-expression isn't present, Op will be null.
867CursorKind.CXX_THROW_EXPR = CursorKind(133)
868
869# A new expression for memory allocation and constructor calls, e.g:
870# "new CXXNewExpr(foo)".
871CursorKind.CXX_NEW_EXPR = CursorKind(134)
872
873# A delete expression for memory deallocation and destructor calls,
874# e.g. "delete[] pArray".
875CursorKind.CXX_DELETE_EXPR = CursorKind(135)
876
877# Represents a unary expression.
878CursorKind.CXX_UNARY_EXPR = CursorKind(136)
879
880# ObjCStringLiteral, used for Objective-C string literals i.e. "foo".
881CursorKind.OBJC_STRING_LITERAL = CursorKind(137)
882
883# ObjCEncodeExpr, used for in Objective-C.
884CursorKind.OBJC_ENCODE_EXPR = CursorKind(138)
885
886# ObjCSelectorExpr used for in Objective-C.
887CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139)
888
889# Objective-C's protocol expression.
890CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140)
891
892# An Objective-C "bridged" cast expression, which casts between
893# Objective-C pointers and C pointers, transferring ownership in the process.
894#
895# \code
896# NSString *str = (__bridge_transfer NSString *)CFCreateString();
897# \endcode
898CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141)
899
900# Represents a C++0x pack expansion that produces a sequence of
901# expressions.
902#
903# A pack expansion expression contains a pattern (which itself is an
904# expression) followed by an ellipsis. For example:
905CursorKind.PACK_EXPANSION_EXPR = CursorKind(142)
906
907# Represents an expression that computes the length of a parameter
908# pack.
909CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143)
910
Daniel Dunbar12bf15c2010-01-24 21:20:29 +0000911# A statement whose specific kind is not exposed via this interface.
912#
913# Unexposed statements have the same operations as any other kind of statement;
914# one can extract their location information, spelling, children, etc. However,
915# the specific kind of the statement is not reported.
916CursorKind.UNEXPOSED_STMT = CursorKind(200)
917
Tobias Grosser4ed73ce2011-02-05 17:53:47 +0000918# A labelled statement in a function.
919CursorKind.LABEL_STMT = CursorKind(201)
920
Douglas Gregor42b29842011-10-05 19:00:14 +0000921# A compound statement
922CursorKind.COMPOUND_STMT = CursorKind(202)
923
924# A case statement.
925CursorKind.CASE_STMT = CursorKind(203)
926
927# A default statement.
928CursorKind.DEFAULT_STMT = CursorKind(204)
929
930# An if statement.
931CursorKind.IF_STMT = CursorKind(205)
932
933# A switch statement.
934CursorKind.SWITCH_STMT = CursorKind(206)
935
936# A while statement.
937CursorKind.WHILE_STMT = CursorKind(207)
938
939# A do statement.
940CursorKind.DO_STMT = CursorKind(208)
941
942# A for statement.
943CursorKind.FOR_STMT = CursorKind(209)
944
945# A goto statement.
946CursorKind.GOTO_STMT = CursorKind(210)
947
948# An indirect goto statement.
949CursorKind.INDIRECT_GOTO_STMT = CursorKind(211)
950
951# A continue statement.
952CursorKind.CONTINUE_STMT = CursorKind(212)
953
954# A break statement.
955CursorKind.BREAK_STMT = CursorKind(213)
956
957# A return statement.
958CursorKind.RETURN_STMT = CursorKind(214)
959
960# A GNU-style inline assembler statement.
961CursorKind.ASM_STMT = CursorKind(215)
962
963# Objective-C's overall @try-@catch-@finally statement.
964CursorKind.OBJC_AT_TRY_STMT = CursorKind(216)
965
966# Objective-C's @catch statement.
967CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217)
968
969# Objective-C's @finally statement.
970CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218)
971
972# Objective-C's @throw statement.
973CursorKind.OBJC_AT_THROW_STMT = CursorKind(219)
974
975# Objective-C's @synchronized statement.
976CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220)
977
978# Objective-C's autorealease pool statement.
979CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221)
980
981# Objective-C's for collection statement.
982CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222)
983
984# C++'s catch statement.
985CursorKind.CXX_CATCH_STMT = CursorKind(223)
986
987# C++'s try statement.
988CursorKind.CXX_TRY_STMT = CursorKind(224)
989
990# C++'s for (* : *) statement.
991CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225)
992
993# Windows Structured Exception Handling's try statement.
994CursorKind.SEH_TRY_STMT = CursorKind(226)
995
996# Windows Structured Exception Handling's except statement.
997CursorKind.SEH_EXCEPT_STMT = CursorKind(227)
998
999# Windows Structured Exception Handling's finally statement.
1000CursorKind.SEH_FINALLY_STMT = CursorKind(228)
1001
1002# The null statement.
1003CursorKind.NULL_STMT = CursorKind(230)
1004
1005# Adaptor class for mixing declarations with statements and expressions.
1006CursorKind.DECL_STMT = CursorKind(231)
Tobias Grosser4ed73ce2011-02-05 17:53:47 +00001007
Daniel Dunbara6a64992010-01-24 21:20:39 +00001008###
1009# Other Kinds
1010
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001011# Cursor that represents the translation unit itself.
1012#
1013# The translation unit cursor exists primarily to act as the root cursor for
1014# traversing the contents of a translation unit.
1015CursorKind.TRANSLATION_UNIT = CursorKind(300)
1016
Tobias Grosser4ed73ce2011-02-05 17:53:47 +00001017###
1018# Attributes
1019
1020# An attribute whoe specific kind is note exposed via this interface
1021CursorKind.UNEXPOSED_ATTR = CursorKind(400)
1022
1023CursorKind.IB_ACTION_ATTR = CursorKind(401)
1024CursorKind.IB_OUTLET_ATTR = CursorKind(402)
1025CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403)
1026
Rafael Espindolabf3cc732011-12-30 15:27:22 +00001027CursorKind.CXX_FINAL_ATTR = CursorKind(404)
1028CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405)
1029CursorKind.ANNOTATE_ATTR = CursorKind(406)
1030CursorKind.ASM_LABEL_ATTR = CursorKind(407)
1031
Tobias Grosser4ed73ce2011-02-05 17:53:47 +00001032###
1033# Preprocessing
1034CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500)
1035CursorKind.MACRO_DEFINITION = CursorKind(501)
1036CursorKind.MACRO_INSTANTIATION = CursorKind(502)
1037CursorKind.INCLUSION_DIRECTIVE = CursorKind(503)
1038
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001039### Cursors ###
1040
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001041class Cursor(Structure):
1042 """
1043 The Cursor class represents a reference to an element within the AST. It
1044 acts as a kind of iterator.
1045 """
Douglas Gregor2abfec32011-10-19 05:47:46 +00001046 _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001047
Tobias Grosser58ba8c92011-10-31 00:31:32 +00001048 @staticmethod
1049 def from_location(tu, location):
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001050 # We store a reference to the TU in the instance so the TU won't get
1051 # collected before the cursor.
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001052 cursor = conf.lib.clang_getCursor(tu, location)
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001053 cursor._tu = tu
1054
1055 return cursor
Tobias Grosser58ba8c92011-10-31 00:31:32 +00001056
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001057 def __eq__(self, other):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001058 return conf.lib.clang_equalCursors(self, other)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001059
1060 def __ne__(self, other):
Gregory Szorc9d008fd2012-03-05 00:42:15 +00001061 return not self.__eq__(other)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001062
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001063 def is_definition(self):
1064 """
1065 Returns true if the declaration pointed at by the cursor is also a
1066 definition of that entity.
1067 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001068 return conf.lib.clang_isCursorDefinition(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001069
Gregory Szorce65b34d2012-06-09 16:21:34 +00001070 def is_static_method(self):
1071 """Returns True if the cursor refers to a C++ member function or member
1072 function template that is declared 'static'.
1073 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001074 return conf.lib.clang_CXXMethod_isStatic(self)
Gregory Szorce65b34d2012-06-09 16:21:34 +00001075
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001076 def get_definition(self):
1077 """
1078 If the cursor is a reference to a declaration or a declaration of
1079 some entity, return a cursor that points to the definition of that
1080 entity.
1081 """
1082 # TODO: Should probably check that this is either a reference or
1083 # declaration prior to issuing the lookup.
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001084 return conf.lib.clang_getCursorDefinition(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001085
Daniel Dunbar3d855f82010-01-24 21:20:13 +00001086 def get_usr(self):
1087 """Return the Unified Symbol Resultion (USR) for the entity referenced
1088 by the given cursor (or None).
1089
1090 A Unified Symbol Resolution (USR) is a string that identifies a
1091 particular entity (function, class, variable, etc.) within a
1092 program. USRs can be compared across translation units to determine,
1093 e.g., when references in one translation refer to an entity defined in
1094 another translation unit."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001095 return conf.lib.clang_getCursorUSR(self)
Daniel Dunbar3d855f82010-01-24 21:20:13 +00001096
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001097 @property
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001098 def kind(self):
1099 """Return the kind of this cursor."""
1100 return CursorKind.from_id(self._kind_id)
1101
1102 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001103 def spelling(self):
1104 """Return the spelling of the entity pointed at by the cursor."""
Daniel Dunbara6a64992010-01-24 21:20:39 +00001105 if not self.kind.is_declaration():
Daniel Dunbar3d855f82010-01-24 21:20:13 +00001106 # FIXME: clang_getCursorSpelling should be fixed to not assert on
1107 # this, for consistency with clang_getCursorUSR.
1108 return None
Douglas Gregor42b29842011-10-05 19:00:14 +00001109 if not hasattr(self, '_spelling'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001110 self._spelling = conf.lib.clang_getCursorSpelling(self)
Gregory Szorc9537e202012-07-12 04:56:46 +00001111
Douglas Gregor42b29842011-10-05 19:00:14 +00001112 return self._spelling
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001113
1114 @property
Douglas Gregorb60a2be2011-08-30 00:15:34 +00001115 def displayname(self):
1116 """
1117 Return the display name for the entity referenced by this cursor.
1118
1119 The display name contains extra information that helps identify the cursor,
1120 such as the parameters of a function or template or the arguments of a
1121 class template specialization.
1122 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001123 if not hasattr(self, '_displayname'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001124 self._displayname = conf.lib.clang_getCursorDisplayName(self)
Gregory Szorc9537e202012-07-12 04:56:46 +00001125
Douglas Gregor42b29842011-10-05 19:00:14 +00001126 return self._displayname
Douglas Gregorb60a2be2011-08-30 00:15:34 +00001127
1128 @property
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001129 def location(self):
1130 """
1131 Return the source location (the starting character) of the entity
1132 pointed at by the cursor.
1133 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001134 if not hasattr(self, '_loc'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001135 self._loc = conf.lib.clang_getCursorLocation(self)
Gregory Szorc9537e202012-07-12 04:56:46 +00001136
Douglas Gregor42b29842011-10-05 19:00:14 +00001137 return self._loc
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001138
1139 @property
1140 def extent(self):
1141 """
1142 Return the source range (the range of text) occupied by the entity
1143 pointed at by the cursor.
1144 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001145 if not hasattr(self, '_extent'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001146 self._extent = conf.lib.clang_getCursorExtent(self)
Gregory Szorc9537e202012-07-12 04:56:46 +00001147
Douglas Gregor42b29842011-10-05 19:00:14 +00001148 return self._extent
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001149
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001150 @property
1151 def type(self):
1152 """
Tobias Grosser2d106802012-02-05 12:15:56 +00001153 Retrieve the Type (if any) of the entity pointed at by the cursor.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001154 """
Douglas Gregor42b29842011-10-05 19:00:14 +00001155 if not hasattr(self, '_type'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001156 self._type = conf.lib.clang_getCursorType(self)
Gregory Szorc9537e202012-07-12 04:56:46 +00001157
Douglas Gregor42b29842011-10-05 19:00:14 +00001158 return self._type
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001159
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00001160 @property
Gregory Szorc2c408352012-05-14 03:56:33 +00001161 def canonical(self):
1162 """Return the canonical Cursor corresponding to this Cursor.
1163
1164 The canonical cursor is the cursor which is representative for the
1165 underlying entity. For example, if you have multiple forward
1166 declarations for the same class, the canonical cursor for the forward
1167 declarations will be identical.
1168 """
1169 if not hasattr(self, '_canonical'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001170 self._canonical = conf.lib.clang_getCanonicalCursor(self)
Gregory Szorc2c408352012-05-14 03:56:33 +00001171
1172 return self._canonical
1173
1174 @property
Gregory Szorc1e370ab2012-05-14 03:53:29 +00001175 def result_type(self):
1176 """Retrieve the Type of the result for this Cursor."""
1177 if not hasattr(self, '_result_type'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001178 self._result_type = conf.lib.clang_getResultType(self.type)
Gregory Szorc1e370ab2012-05-14 03:53:29 +00001179
1180 return self._result_type
1181
1182 @property
Tobias Grosser28d939f2012-02-05 11:42:20 +00001183 def underlying_typedef_type(self):
1184 """Return the underlying type of a typedef declaration.
1185
Tobias Grosser2d106802012-02-05 12:15:56 +00001186 Returns a Type for the typedef this cursor is a declaration for. If
Tobias Grosser28d939f2012-02-05 11:42:20 +00001187 the current cursor is not a typedef, this raises.
1188 """
1189 if not hasattr(self, '_underlying_type'):
1190 assert self.kind.is_declaration()
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001191 self._underlying_type = \
1192 conf.lib.clang_getTypedefDeclUnderlyingType(self)
Tobias Grosser28d939f2012-02-05 11:42:20 +00001193
1194 return self._underlying_type
1195
1196 @property
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00001197 def enum_type(self):
1198 """Return the integer type of an enum declaration.
1199
Tobias Grosser2d106802012-02-05 12:15:56 +00001200 Returns a Type corresponding to an integer. If the cursor is not for an
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00001201 enum, this raises.
1202 """
1203 if not hasattr(self, '_enum_type'):
1204 assert self.kind == CursorKind.ENUM_DECL
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001205 self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self)
Tobias Grossereb9ff2e2012-02-05 11:42:25 +00001206
1207 return self._enum_type
1208
1209 @property
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00001210 def enum_value(self):
1211 """Return the value of an enum constant."""
1212 if not hasattr(self, '_enum_value'):
1213 assert self.kind == CursorKind.ENUM_CONSTANT_DECL
1214 # Figure out the underlying type of the enum to know if it
1215 # is a signed or unsigned quantity.
1216 underlying_type = self.type
1217 if underlying_type.kind == TypeKind.ENUM:
1218 underlying_type = underlying_type.get_declaration().enum_type
1219 if underlying_type.kind in (TypeKind.CHAR_U,
1220 TypeKind.UCHAR,
1221 TypeKind.CHAR16,
1222 TypeKind.CHAR32,
1223 TypeKind.USHORT,
1224 TypeKind.UINT,
1225 TypeKind.ULONG,
1226 TypeKind.ULONGLONG,
1227 TypeKind.UINT128):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001228 self._enum_value = \
1229 conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00001230 else:
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001231 self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self)
Anders Waldenborgbbc2e092012-05-02 20:57:33 +00001232 return self._enum_value
1233
1234 @property
Gregory Szorc5cc67872012-03-10 22:23:27 +00001235 def objc_type_encoding(self):
1236 """Return the Objective-C type encoding as a str."""
1237 if not hasattr(self, '_objc_type_encoding'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001238 self._objc_type_encoding = \
1239 conf.lib.clang_getDeclObjCTypeEncoding(self)
Gregory Szorc5cc67872012-03-10 22:23:27 +00001240
1241 return self._objc_type_encoding
1242
1243 @property
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00001244 def hash(self):
1245 """Returns a hash of the cursor as an int."""
1246 if not hasattr(self, '_hash'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001247 self._hash = conf.lib.clang_hashCursor(self)
Tobias Grosser64e7bdc2012-02-05 11:42:03 +00001248
1249 return self._hash
1250
Manuel Klimek667fd802012-05-07 05:56:03 +00001251 @property
1252 def semantic_parent(self):
1253 """Return the semantic parent for this cursor."""
1254 if not hasattr(self, '_semantic_parent'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001255 self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self)
Gregory Szorcfd04a6a2012-05-08 06:01:34 +00001256
Manuel Klimek667fd802012-05-07 05:56:03 +00001257 return self._semantic_parent
1258
1259 @property
1260 def lexical_parent(self):
1261 """Return the lexical parent for this cursor."""
1262 if not hasattr(self, '_lexical_parent'):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001263 self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self)
Gregory Szorcfd04a6a2012-05-08 06:01:34 +00001264
Manuel Klimek667fd802012-05-07 05:56:03 +00001265 return self._lexical_parent
Gregory Szorcfd04a6a2012-05-08 06:01:34 +00001266
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001267 @property
1268 def translation_unit(self):
1269 """Returns the TranslationUnit to which this Cursor belongs."""
1270 # If this triggers an AttributeError, the instance was not properly
1271 # created.
1272 return self._tu
1273
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001274 def get_children(self):
Daniel Dunbar12bf15c2010-01-24 21:20:29 +00001275 """Return an iterator for accessing the children of this cursor."""
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001276
1277 # FIXME: Expose iteration from CIndex, PR6125.
1278 def visitor(child, parent, children):
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001279 # FIXME: Document this assertion in API.
1280 # FIXME: There should just be an isNull method.
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001281 assert child != conf.lib.clang_getNullCursor()
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001282
1283 # Create reference to TU so it isn't GC'd before Cursor.
1284 child._tu = self._tu
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001285 children.append(child)
1286 return 1 # continue
1287 children = []
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001288 conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
Gregory Szorc9537e202012-07-12 04:56:46 +00001289 children)
Daniel Dunbarde3b8e52010-01-24 04:10:22 +00001290 return iter(children)
1291
Gregory Szorcbe51e432012-07-12 07:21:12 +00001292 def get_tokens(self):
1293 """Obtain Token instances formulating that compose this Cursor.
1294
1295 This is a generator for Token instances. It returns all tokens which
1296 occupy the extent this cursor occupies.
1297 """
1298 return TokenGroup.get_tokens(self._tu, self.extent)
1299
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001300 @staticmethod
1301 def from_result(res, fn, args):
1302 assert isinstance(res, Cursor)
1303 # FIXME: There should just be an isNull method.
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001304 if res == conf.lib.clang_getNullCursor():
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001305 return None
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001306
1307 # Store a reference to the TU in the Python object so it won't get GC'd
1308 # before the Cursor.
1309 tu = None
1310 for arg in args:
1311 if isinstance(arg, TranslationUnit):
1312 tu = arg
1313 break
1314
1315 if hasattr(arg, 'translation_unit'):
1316 tu = arg.translation_unit
1317 break
1318
1319 assert tu is not None
1320
1321 res._tu = tu
Daniel Dunbarfb8ae172010-01-24 21:20:05 +00001322 return res
1323
Gregory Szorc9537e202012-07-12 04:56:46 +00001324 @staticmethod
1325 def from_cursor_result(res, fn, args):
1326 assert isinstance(res, Cursor)
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001327 if res == conf.lib.clang_getNullCursor():
Gregory Szorc9537e202012-07-12 04:56:46 +00001328 return None
1329
1330 res._tu = args[0]._tu
1331 return res
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001332
1333### Type Kinds ###
1334
1335class TypeKind(object):
1336 """
1337 Describes the kind of type.
1338 """
1339
1340 # The unique kind objects, indexed by id.
1341 _kinds = []
1342 _name_map = None
1343
1344 def __init__(self, value):
1345 if value >= len(TypeKind._kinds):
1346 TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1)
1347 if TypeKind._kinds[value] is not None:
1348 raise ValueError,'TypeKind already loaded'
1349 self.value = value
1350 TypeKind._kinds[value] = self
1351 TypeKind._name_map = None
1352
1353 def from_param(self):
1354 return self.value
1355
1356 @property
1357 def name(self):
1358 """Get the enumeration name of this cursor kind."""
1359 if self._name_map is None:
1360 self._name_map = {}
1361 for key,value in TypeKind.__dict__.items():
1362 if isinstance(value,TypeKind):
1363 self._name_map[value] = key
1364 return self._name_map[self]
1365
Gregory Szorc6e67eed2012-04-15 18:51:10 +00001366 @property
1367 def spelling(self):
1368 """Retrieve the spelling of this TypeKind."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001369 return conf.lib.clang_getTypeKindSpelling(self.value)
Gregory Szorc6e67eed2012-04-15 18:51:10 +00001370
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001371 @staticmethod
1372 def from_id(id):
1373 if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None:
Douglas Gregor9d342ab2011-10-19 05:49:29 +00001374 raise ValueError,'Unknown type kind %d' % id
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001375 return TypeKind._kinds[id]
1376
1377 def __repr__(self):
1378 return 'TypeKind.%s' % (self.name,)
1379
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001380TypeKind.INVALID = TypeKind(0)
1381TypeKind.UNEXPOSED = TypeKind(1)
1382TypeKind.VOID = TypeKind(2)
1383TypeKind.BOOL = TypeKind(3)
1384TypeKind.CHAR_U = TypeKind(4)
1385TypeKind.UCHAR = TypeKind(5)
1386TypeKind.CHAR16 = TypeKind(6)
1387TypeKind.CHAR32 = TypeKind(7)
1388TypeKind.USHORT = TypeKind(8)
1389TypeKind.UINT = TypeKind(9)
1390TypeKind.ULONG = TypeKind(10)
1391TypeKind.ULONGLONG = TypeKind(11)
1392TypeKind.UINT128 = TypeKind(12)
1393TypeKind.CHAR_S = TypeKind(13)
1394TypeKind.SCHAR = TypeKind(14)
1395TypeKind.WCHAR = TypeKind(15)
1396TypeKind.SHORT = TypeKind(16)
1397TypeKind.INT = TypeKind(17)
1398TypeKind.LONG = TypeKind(18)
1399TypeKind.LONGLONG = TypeKind(19)
1400TypeKind.INT128 = TypeKind(20)
1401TypeKind.FLOAT = TypeKind(21)
1402TypeKind.DOUBLE = TypeKind(22)
1403TypeKind.LONGDOUBLE = TypeKind(23)
1404TypeKind.NULLPTR = TypeKind(24)
1405TypeKind.OVERLOAD = TypeKind(25)
1406TypeKind.DEPENDENT = TypeKind(26)
1407TypeKind.OBJCID = TypeKind(27)
1408TypeKind.OBJCCLASS = TypeKind(28)
1409TypeKind.OBJCSEL = TypeKind(29)
1410TypeKind.COMPLEX = TypeKind(100)
1411TypeKind.POINTER = TypeKind(101)
1412TypeKind.BLOCKPOINTER = TypeKind(102)
1413TypeKind.LVALUEREFERENCE = TypeKind(103)
1414TypeKind.RVALUEREFERENCE = TypeKind(104)
1415TypeKind.RECORD = TypeKind(105)
1416TypeKind.ENUM = TypeKind(106)
1417TypeKind.TYPEDEF = TypeKind(107)
1418TypeKind.OBJCINTERFACE = TypeKind(108)
1419TypeKind.OBJCOBJECTPOINTER = TypeKind(109)
1420TypeKind.FUNCTIONNOPROTO = TypeKind(110)
1421TypeKind.FUNCTIONPROTO = TypeKind(111)
Douglas Gregor38d2d552011-10-19 05:50:34 +00001422TypeKind.CONSTANTARRAY = TypeKind(112)
Tobias Grosser250d2172012-02-05 11:42:14 +00001423TypeKind.VECTOR = TypeKind(113)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001424
1425class Type(Structure):
1426 """
1427 The type of an element in the abstract syntax tree.
1428 """
1429 _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)]
1430
1431 @property
1432 def kind(self):
1433 """Return the kind of this type."""
1434 return TypeKind.from_id(self._kind_id)
1435
Gregory Szorc826fce52012-02-20 17:45:30 +00001436 def argument_types(self):
1437 """Retrieve a container for the non-variadic arguments for this type.
1438
1439 The returned object is iterable and indexable. Each item in the
1440 container is a Type instance.
1441 """
1442 class ArgumentsIterator(collections.Sequence):
1443 def __init__(self, parent):
1444 self.parent = parent
1445 self.length = None
1446
1447 def __len__(self):
1448 if self.length is None:
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001449 self.length = conf.lib.clang_getNumArgTypes(self.parent)
Gregory Szorc826fce52012-02-20 17:45:30 +00001450
1451 return self.length
1452
1453 def __getitem__(self, key):
1454 # FIXME Support slice objects.
1455 if not isinstance(key, int):
1456 raise TypeError("Must supply a non-negative int.")
1457
1458 if key < 0:
1459 raise IndexError("Only non-negative indexes are accepted.")
1460
1461 if key >= len(self):
1462 raise IndexError("Index greater than container length: "
1463 "%d > %d" % ( key, len(self) ))
1464
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001465 result = conf.lib.clang_getArgType(self.parent, key)
Gregory Szorc826fce52012-02-20 17:45:30 +00001466 if result.kind == TypeKind.INVALID:
1467 raise IndexError("Argument could not be retrieved.")
1468
1469 return result
1470
1471 assert self.kind == TypeKind.FUNCTIONPROTO
1472 return ArgumentsIterator(self)
1473
Gregory Szorc86057602012-02-17 07:44:46 +00001474 @property
1475 def element_type(self):
1476 """Retrieve the Type of elements within this Type.
1477
1478 If accessed on a type that is not an array, complex, or vector type, an
1479 exception will be raised.
1480 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001481 result = conf.lib.clang_getElementType(self)
Gregory Szorc86057602012-02-17 07:44:46 +00001482 if result.kind == TypeKind.INVALID:
1483 raise Exception('Element type not available on this type.')
1484
1485 return result
1486
Gregory Szorcbf8ca002012-02-17 07:47:38 +00001487 @property
1488 def element_count(self):
1489 """Retrieve the number of elements in this type.
1490
1491 Returns an int.
1492
1493 If the Type is not an array or vector, this raises.
1494 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001495 result = conf.lib.clang_getNumElements(self)
Gregory Szorcbf8ca002012-02-17 07:47:38 +00001496 if result < 0:
1497 raise Exception('Type does not have elements.')
1498
1499 return result
1500
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001501 @property
1502 def translation_unit(self):
1503 """The TranslationUnit to which this Type is associated."""
1504 # If this triggers an AttributeError, the instance was not properly
1505 # instantiated.
1506 return self._tu
1507
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001508 @staticmethod
1509 def from_result(res, fn, args):
1510 assert isinstance(res, Type)
Gregory Szorca63ef1f2012-05-15 19:51:02 +00001511
1512 tu = None
1513 for arg in args:
1514 if hasattr(arg, 'translation_unit'):
1515 tu = arg.translation_unit
1516 break
1517
1518 assert tu is not None
1519 res._tu = tu
1520
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001521 return res
1522
1523 def get_canonical(self):
1524 """
1525 Return the canonical type for a Type.
1526
1527 Clang's type system explicitly models typedefs and all the
1528 ways a specific type can be represented. The canonical type
1529 is the underlying type with all the "sugar" removed. For
1530 example, if 'T' is a typedef for 'int', the canonical type for
1531 'T' would be 'int'.
1532 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001533 return conf.lib.clang_getCanonicalType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001534
1535 def is_const_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001536 """Determine whether a Type has the "const" qualifier set.
1537
1538 This does not look through typedefs that may have added "const"
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001539 at a different level.
1540 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001541 return conf.lib.clang_isConstQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001542
1543 def is_volatile_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001544 """Determine whether a Type has the "volatile" qualifier set.
1545
1546 This does not look through typedefs that may have added "volatile"
1547 at a different level.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001548 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001549 return conf.lib.clang_isVolatileQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001550
1551 def is_restrict_qualified(self):
Gregory Szorc82613452012-02-20 17:58:40 +00001552 """Determine whether a Type has the "restrict" qualifier set.
1553
1554 This does not look through typedefs that may have added "restrict" at
1555 a different level.
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001556 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001557 return conf.lib.clang_isRestrictQualifiedType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001558
Gregory Szorc31cc38c2012-02-19 18:28:33 +00001559 def is_function_variadic(self):
1560 """Determine whether this function Type is a variadic function type."""
1561 assert self.kind == TypeKind.FUNCTIONPROTO
1562
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001563 return conf.lib.clang_isFunctionTypeVariadic(self)
Gregory Szorc31cc38c2012-02-19 18:28:33 +00001564
Gregory Szorc96ad6332012-02-05 19:42:06 +00001565 def is_pod(self):
1566 """Determine whether this Type represents plain old data (POD)."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001567 return conf.lib.clang_isPODType(self)
Gregory Szorc96ad6332012-02-05 19:42:06 +00001568
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001569 def get_pointee(self):
1570 """
1571 For pointer types, returns the type of the pointee.
1572 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001573 return conf.lib.clang_getPointeeType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001574
1575 def get_declaration(self):
1576 """
1577 Return the cursor for the declaration of the given type.
1578 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001579 return conf.lib.clang_getTypeDeclaration(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001580
1581 def get_result(self):
1582 """
1583 Retrieve the result type associated with a function type.
1584 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001585 return conf.lib.clang_getResultType(self)
Argyrios Kyrtzidisd7933e62011-08-17 00:43:03 +00001586
Douglas Gregor13102ff2011-10-19 05:51:43 +00001587 def get_array_element_type(self):
1588 """
1589 Retrieve the type of the elements of the array type.
1590 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001591 return conf.lib.clang_getArrayElementType(self)
Douglas Gregor13102ff2011-10-19 05:51:43 +00001592
1593 def get_array_size(self):
1594 """
1595 Retrieve the size of the constant array.
1596 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001597 return conf.lib.clang_getArraySize(self)
Douglas Gregor13102ff2011-10-19 05:51:43 +00001598
Gregory Szorc7eb691a2012-02-20 17:44:49 +00001599 def __eq__(self, other):
1600 if type(other) != type(self):
1601 return False
1602
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001603 return conf.lib.clang_equalTypes(self, other)
Gregory Szorc7eb691a2012-02-20 17:44:49 +00001604
1605 def __ne__(self, other):
1606 return not self.__eq__(other)
1607
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001608## CIndex Objects ##
1609
1610# CIndex objects (derived from ClangObject) are essentially lightweight
1611# wrappers attached to some underlying object, which is exposed via CIndex as
1612# a void*.
1613
1614class ClangObject(object):
1615 """
1616 A helper for Clang objects. This class helps act as an intermediary for
1617 the ctypes library and the Clang CIndex library.
1618 """
1619 def __init__(self, obj):
1620 assert isinstance(obj, c_object_p) and obj
1621 self.obj = self._as_parameter_ = obj
1622
1623 def from_param(self):
1624 return self._as_parameter_
1625
Daniel Dunbar5b534f62010-01-25 00:44:11 +00001626
1627class _CXUnsavedFile(Structure):
1628 """Helper for passing unsaved file arguments."""
1629 _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
1630
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001631class CompletionChunk:
1632 class Kind:
1633 def __init__(self, name):
1634 self.name = name
1635
1636 def __str__(self):
1637 return self.name
1638
1639 def __repr__(self):
1640 return "<ChunkKind: %s>" % self
1641
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001642 def __init__(self, completionString, key):
1643 self.cs = completionString
1644 self.key = key
1645
1646 def __repr__(self):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001647 return "{'" + self.spelling + "', " + str(self.kind) + "}"
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001648
Tobias Grosserd9ee06b2012-08-19 22:26:15 +00001649 @CachedProperty
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001650 def spelling(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001651 return conf.lib.clang_getCompletionChunkText(self.cs, self.key).spelling
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001652
Tobias Grosserd9ee06b2012-08-19 22:26:15 +00001653 @CachedProperty
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001654 def kind(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001655 res = conf.lib.clang_getCompletionChunkKind(self.cs, self.key)
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001656 return completionChunkKindMap[res]
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001657
Tobias Grosserd9ee06b2012-08-19 22:26:15 +00001658 @CachedProperty
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001659 def string(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001660 res = conf.lib.clang_getCompletionChunkCompletionString(self.cs,
1661 self.key)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001662
1663 if (res):
1664 return CompletionString(res)
1665 else:
1666 None
1667
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001668 def isKindOptional(self):
1669 return self.kind == completionChunkKindMap[0]
1670
1671 def isKindTypedText(self):
1672 return self.kind == completionChunkKindMap[1]
1673
1674 def isKindPlaceHolder(self):
1675 return self.kind == completionChunkKindMap[3]
1676
1677 def isKindInformative(self):
1678 return self.kind == completionChunkKindMap[4]
1679
1680 def isKindResultType(self):
1681 return self.kind == completionChunkKindMap[15]
1682
1683completionChunkKindMap = {
1684 0: CompletionChunk.Kind("Optional"),
1685 1: CompletionChunk.Kind("TypedText"),
1686 2: CompletionChunk.Kind("Text"),
1687 3: CompletionChunk.Kind("Placeholder"),
1688 4: CompletionChunk.Kind("Informative"),
1689 5: CompletionChunk.Kind("CurrentParameter"),
1690 6: CompletionChunk.Kind("LeftParen"),
1691 7: CompletionChunk.Kind("RightParen"),
1692 8: CompletionChunk.Kind("LeftBracket"),
1693 9: CompletionChunk.Kind("RightBracket"),
1694 10: CompletionChunk.Kind("LeftBrace"),
1695 11: CompletionChunk.Kind("RightBrace"),
1696 12: CompletionChunk.Kind("LeftAngle"),
1697 13: CompletionChunk.Kind("RightAngle"),
1698 14: CompletionChunk.Kind("Comma"),
1699 15: CompletionChunk.Kind("ResultType"),
1700 16: CompletionChunk.Kind("Colon"),
1701 17: CompletionChunk.Kind("SemiColon"),
1702 18: CompletionChunk.Kind("Equal"),
1703 19: CompletionChunk.Kind("HorizontalSpace"),
1704 20: CompletionChunk.Kind("VerticalSpace")}
1705
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001706class CompletionString(ClangObject):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001707 class Availability:
1708 def __init__(self, name):
1709 self.name = name
1710
1711 def __str__(self):
1712 return self.name
1713
1714 def __repr__(self):
1715 return "<Availability: %s>" % self
1716
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001717 def __len__(self):
Tobias Grosser147785b2012-08-20 10:38:16 +00001718 self.num_chunks
1719
1720 @CachedProperty
1721 def num_chunks(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001722 return conf.lib.clang_getNumCompletionChunks(self.obj)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001723
1724 def __getitem__(self, key):
Tobias Grosser147785b2012-08-20 10:38:16 +00001725 if self.num_chunks <= key:
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001726 raise IndexError
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001727 return CompletionChunk(self.obj, key)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001728
1729 @property
1730 def priority(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001731 return conf.lib.clang_getCompletionPriority(self.obj)
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001732
1733 @property
1734 def availability(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001735 res = conf.lib.clang_getCompletionAvailability(self.obj)
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001736 return availabilityKinds[res]
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001737
1738 def __repr__(self):
Tobias Grossera87dbcc2011-02-05 17:54:10 +00001739 return " | ".join([str(a) for a in self]) \
1740 + " || Priority: " + str(self.priority) \
1741 + " || Availability: " + str(self.availability)
1742
1743availabilityKinds = {
1744 0: CompletionChunk.Kind("Available"),
1745 1: CompletionChunk.Kind("Deprecated"),
1746 2: CompletionChunk.Kind("NotAvailable")}
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001747
Tobias Grosser0a166802011-02-05 17:54:04 +00001748class CodeCompletionResult(Structure):
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001749 _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
1750
1751 def __repr__(self):
1752 return str(CompletionString(self.completionString))
1753
1754 @property
1755 def kind(self):
1756 return CursorKind.from_id(self.cursorKind)
1757
1758 @property
1759 def string(self):
1760 return CompletionString(self.completionString)
Tobias Grosser0a166802011-02-05 17:54:04 +00001761
1762class CCRStructure(Structure):
1763 _fields_ = [('results', POINTER(CodeCompletionResult)),
1764 ('numResults', c_int)]
1765
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001766 def __len__(self):
1767 return self.numResults
1768
1769 def __getitem__(self, key):
1770 if len(self) <= key:
1771 raise IndexError
1772
1773 return self.results[key]
1774
Tobias Grosser0a166802011-02-05 17:54:04 +00001775class CodeCompletionResults(ClangObject):
1776 def __init__(self, ptr):
1777 assert isinstance(ptr, POINTER(CCRStructure)) and ptr
1778 self.ptr = self._as_parameter_ = ptr
1779
1780 def from_param(self):
1781 return self._as_parameter_
1782
1783 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001784 conf.lib.clang_disposeCodeCompleteResults(self)
Tobias Grosser0a166802011-02-05 17:54:04 +00001785
1786 @property
1787 def results(self):
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00001788 return self.ptr.contents
Tobias Grosser0a166802011-02-05 17:54:04 +00001789
1790 @property
1791 def diagnostics(self):
1792 class DiagnosticsItr:
1793 def __init__(self, ccr):
1794 self.ccr= ccr
1795
1796 def __len__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001797 return int(\
1798 conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr))
Tobias Grosser0a166802011-02-05 17:54:04 +00001799
1800 def __getitem__(self, key):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001801 return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key)
Tobias Grosser0a166802011-02-05 17:54:04 +00001802
1803 return DiagnosticsItr(self)
1804
1805
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001806class Index(ClangObject):
1807 """
1808 The Index type provides the primary interface to the Clang CIndex library,
1809 primarily by providing an interface for reading and parsing translation
1810 units.
1811 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001812
1813 @staticmethod
Daniel Dunbar2791dfc2010-01-30 23:58:39 +00001814 def create(excludeDecls=False):
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001815 """
1816 Create a new Index.
1817 Parameters:
1818 excludeDecls -- Exclude local declarations from translation units.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001819 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001820 return Index(conf.lib.clang_createIndex(excludeDecls, 0))
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001821
1822 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001823 conf.lib.clang_disposeIndex(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001824
1825 def read(self, path):
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001826 """Load a TranslationUnit from the given AST file."""
1827 return TranslationUnit.from_ast(path, self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001828
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001829 def parse(self, path, args=None, unsaved_files=None, options = 0):
1830 """Load the translation unit from the given source code file by running
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001831 clang and generating the AST before loading. Additional command line
1832 parameters can be passed to clang via the args parameter.
Daniel Dunbar5b534f62010-01-25 00:44:11 +00001833
1834 In-memory contents for files can be provided by passing a list of pairs
1835 to as unsaved_files, the first item should be the filenames to be mapped
1836 and the second should be the contents to be substituted for the
1837 file. The contents may be passed as strings or file objects.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001838
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001839 If an error was encountered during parsing, a TranslationUnitLoadError
1840 will be raised.
1841 """
1842 return TranslationUnit.from_source(path, args, unsaved_files, options,
1843 self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001844
1845class TranslationUnit(ClangObject):
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001846 """Represents a source code translation unit.
1847
1848 This is one of the main types in the API. Any time you wish to interact
1849 with Clang's representation of a source file, you typically start with a
1850 translation unit.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001851 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001852
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001853 # Default parsing mode.
1854 PARSE_NONE = 0
1855
1856 # Instruct the parser to create a detailed processing record containing
1857 # metadata not normally retained.
1858 PARSE_DETAILED_PROCESSING_RECORD = 1
1859
1860 # Indicates that the translation unit is incomplete. This is typically used
1861 # when parsing headers.
1862 PARSE_INCOMPLETE = 2
1863
1864 # Instruct the parser to create a pre-compiled preamble for the translation
1865 # unit. This caches the preamble (included files at top of source file).
1866 # This is useful if the translation unit will be reparsed and you don't
1867 # want to incur the overhead of reparsing the preamble.
1868 PARSE_PRECOMPILED_PREAMBLE = 4
1869
1870 # Cache code completion information on parse. This adds time to parsing but
1871 # speeds up code completion.
1872 PARSE_CACHE_COMPLETION_RESULTS = 8
1873
1874 # Flags with values 16 and 32 are deprecated and intentionally omitted.
1875
1876 # Do not parse function bodies. This is useful if you only care about
1877 # searching for declarations/definitions.
1878 PARSE_SKIP_FUNCTION_BODIES = 64
1879
1880 @classmethod
1881 def from_source(cls, filename, args=None, unsaved_files=None, options=0,
1882 index=None):
1883 """Create a TranslationUnit by parsing source.
1884
1885 This is capable of processing source code both from files on the
1886 filesystem as well as in-memory contents.
1887
1888 Command-line arguments that would be passed to clang are specified as
1889 a list via args. These can be used to specify include paths, warnings,
1890 etc. e.g. ["-Wall", "-I/path/to/include"].
1891
1892 In-memory file content can be provided via unsaved_files. This is an
1893 iterable of 2-tuples. The first element is the str filename. The
1894 second element defines the content. Content can be provided as str
1895 source code or as file objects (anything with a read() method). If
1896 a file object is being used, content will be read until EOF and the
1897 read cursor will not be reset to its original position.
1898
1899 options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
1900 control parsing behavior.
1901
Gregory Szorc2283b462012-05-12 20:49:13 +00001902 index is an Index instance to utilize. If not provided, a new Index
1903 will be created for this TranslationUnit.
1904
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001905 To parse source from the filesystem, the filename of the file to parse
1906 is specified by the filename argument. Or, filename could be None and
1907 the args list would contain the filename(s) to parse.
1908
1909 To parse source from an in-memory buffer, set filename to the virtual
1910 filename you wish to associate with this source (e.g. "test.c"). The
1911 contents of that file are then provided in unsaved_files.
1912
1913 If an error occurs, a TranslationUnitLoadError is raised.
1914
1915 Please note that a TranslationUnit with parser errors may be returned.
1916 It is the caller's responsibility to check tu.diagnostics for errors.
1917
1918 Also note that Clang infers the source language from the extension of
1919 the input filename. If you pass in source code containing a C++ class
1920 declaration with the filename "test.c" parsing will fail.
1921 """
1922 if args is None:
1923 args = []
1924
1925 if unsaved_files is None:
1926 unsaved_files = []
1927
1928 if index is None:
1929 index = Index.create()
1930
1931 args_array = None
1932 if len(args) > 0:
1933 args_array = (c_char_p * len(args))(* args)
1934
1935 unsaved_array = None
1936 if len(unsaved_files) > 0:
1937 unsaved_array = (_CXUnsavedFile * len(unsaved_files))()
1938 for i, (name, contents) in enumerate(unsaved_files):
1939 if hasattr(contents, "read"):
1940 contents = contents.read()
1941
1942 unsaved_array[i].name = name
1943 unsaved_array[i].contents = contents
1944 unsaved_array[i].length = len(contents)
1945
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001946 ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array,
Gregory Szorc9537e202012-07-12 04:56:46 +00001947 len(args), unsaved_array,
1948 len(unsaved_files), options)
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001949
1950 if ptr is None:
1951 raise TranslationUnitLoadError("Error parsing translation unit.")
1952
1953 return cls(ptr, index=index)
1954
1955 @classmethod
1956 def from_ast_file(cls, filename, index=None):
1957 """Create a TranslationUnit instance from a saved AST file.
1958
1959 A previously-saved AST file (provided with -emit-ast or
1960 TranslationUnit.save()) is loaded from the filename specified.
1961
1962 If the file cannot be loaded, a TranslationUnitLoadError will be
1963 raised.
1964
1965 index is optional and is the Index instance to use. If not provided,
1966 a default Index will be created.
1967 """
1968 if index is None:
1969 index = Index.create()
1970
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001971 ptr = conf.lib.clang_createTranslationUnit(index, filename)
Gregory Szorcfbf620b2012-05-08 05:56:38 +00001972 if ptr is None:
1973 raise TranslationUnitLoadError(filename)
1974
1975 return cls(ptr=ptr, index=index)
1976
1977 def __init__(self, ptr, index):
1978 """Create a TranslationUnit instance.
1979
1980 TranslationUnits should be created using one of the from_* @classmethod
1981 functions above. __init__ is only called internally.
1982 """
1983 assert isinstance(index, Index)
1984
Daniel Dunbar532fc632010-01-30 23:59:02 +00001985 ClangObject.__init__(self, ptr)
Daniel Dunbar532fc632010-01-30 23:59:02 +00001986
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001987 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001988 conf.lib.clang_disposeTranslationUnit(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001989
Daniel Dunbar1b945a72010-01-24 04:09:43 +00001990 @property
1991 def cursor(self):
1992 """Retrieve the cursor that represents the given translation unit."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001993 return conf.lib.clang_getTranslationUnitCursor(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001994
1995 @property
1996 def spelling(self):
Daniel Dunbar1b945a72010-01-24 04:09:43 +00001997 """Get the original translation unit source file name."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00001998 return conf.lib.clang_getTranslationUnitSpelling(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00001999
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002000 def get_includes(self):
2001 """
2002 Return an iterable sequence of FileInclusion objects that describe the
2003 sequence of inclusions in a translation unit. The first object in
2004 this sequence is always the input file. Note that this method will not
2005 recursively iterate over header files included through precompiled
2006 headers.
2007 """
2008 def visitor(fobj, lptr, depth, includes):
Douglas Gregor8be80e12011-07-06 03:00:34 +00002009 if depth > 0:
2010 loc = lptr.contents
2011 includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002012
2013 # Automatically adapt CIndex/ctype pointers to python objects
2014 includes = []
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002015 conf.lib.clang_getInclusions(self,
Gregory Szorc9537e202012-07-12 04:56:46 +00002016 callbacks['translation_unit_includes'](visitor), includes)
2017
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002018 return iter(includes)
2019
Gregory Szorc0f1964a2012-07-12 05:05:56 +00002020 def get_file(self, filename):
2021 """Obtain a File from this translation unit."""
2022
2023 return File.from_name(self, filename)
2024
2025 def get_location(self, filename, position):
2026 """Obtain a SourceLocation for a file in this translation unit.
2027
2028 The position can be specified by passing:
2029
2030 - Integer file offset. Initial file offset is 0.
2031 - 2-tuple of (line number, column number). Initial file position is
2032 (0, 0)
2033 """
2034 f = self.get_file(filename)
2035
2036 if isinstance(position, int):
2037 return SourceLocation.from_offset(self, f, position)
2038
2039 return SourceLocation.from_position(self, f, position[0], position[1])
2040
2041 def get_extent(self, filename, locations):
2042 """Obtain a SourceRange from this translation unit.
2043
2044 The bounds of the SourceRange must ultimately be defined by a start and
2045 end SourceLocation. For the locations argument, you can pass:
2046
2047 - 2 SourceLocation instances in a 2-tuple or list.
2048 - 2 int file offsets via a 2-tuple or list.
2049 - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
2050
2051 e.g.
2052
2053 get_extent('foo.c', (5, 10))
2054 get_extent('foo.c', ((1, 1), (1, 15)))
2055 """
2056 f = self.get_file(filename)
2057
2058 if len(locations) < 2:
2059 raise Exception('Must pass object with at least 2 elements')
2060
2061 start_location, end_location = locations
2062
2063 if hasattr(start_location, '__len__'):
2064 start_location = SourceLocation.from_position(self, f,
2065 start_location[0], start_location[1])
2066 elif isinstance(start_location, int):
2067 start_location = SourceLocation.from_offset(self, f,
2068 start_location)
2069
2070 if hasattr(end_location, '__len__'):
2071 end_location = SourceLocation.from_position(self, f,
2072 end_location[0], end_location[1])
2073 elif isinstance(end_location, int):
2074 end_location = SourceLocation.from_offset(self, f, end_location)
2075
2076 assert isinstance(start_location, SourceLocation)
2077 assert isinstance(end_location, SourceLocation)
2078
2079 return SourceRange.from_locations(start_location, end_location)
2080
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002081 @property
2082 def diagnostics(self):
2083 """
2084 Return an iterable (and indexable) object containing the diagnostics.
2085 """
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00002086 class DiagIterator:
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002087 def __init__(self, tu):
2088 self.tu = tu
2089
2090 def __len__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002091 return int(conf.lib.clang_getNumDiagnostics(self.tu))
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002092
2093 def __getitem__(self, key):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002094 diag = conf.lib.clang_getDiagnostic(self.tu, key)
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00002095 if not diag:
2096 raise IndexError
2097 return Diagnostic(diag)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002098
Benjamin Kramer1d02ccd2010-03-06 15:38:03 +00002099 return DiagIterator(self)
Benjamin Kramer3b0cf092010-03-06 14:53:07 +00002100
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002101 def reparse(self, unsaved_files=None, options=0):
Tobias Grosser265e6b22011-02-05 17:54:00 +00002102 """
2103 Reparse an already parsed translation unit.
2104
2105 In-memory contents for files can be provided by passing a list of pairs
2106 as unsaved_files, the first items should be the filenames to be mapped
2107 and the second should be the contents to be substituted for the
2108 file. The contents may be passed as strings or file objects.
2109 """
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002110 if unsaved_files is None:
2111 unsaved_files = []
2112
Tobias Grosser265e6b22011-02-05 17:54:00 +00002113 unsaved_files_array = 0
2114 if len(unsaved_files):
2115 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
2116 for i,(name,value) in enumerate(unsaved_files):
2117 if not isinstance(value, str):
2118 # FIXME: It would be great to support an efficient version
2119 # of this, one day.
2120 value = value.read()
2121 print value
2122 if not isinstance(value, str):
2123 raise TypeError,'Unexpected unsaved file contents.'
2124 unsaved_files_array[i].name = name
2125 unsaved_files_array[i].contents = value
2126 unsaved_files_array[i].length = len(value)
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002127 ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
Gregory Szorc9537e202012-07-12 04:56:46 +00002128 unsaved_files_array, options)
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002129
2130 def save(self, filename):
2131 """Saves the TranslationUnit to a file.
2132
2133 This is equivalent to passing -emit-ast to the clang frontend. The
2134 saved file can be loaded back into a TranslationUnit. Or, if it
2135 corresponds to a header, it can be used as a pre-compiled header file.
2136
2137 If an error occurs while saving, a TranslationUnitSaveError is raised.
2138 If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
2139 the constructed TranslationUnit was not valid at time of save. In this
2140 case, the reason(s) why should be available via
2141 TranslationUnit.diagnostics().
2142
2143 filename -- The path to save the translation unit to.
2144 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002145 options = conf.lib.clang_defaultSaveOptions(self)
2146 result = int(conf.lib.clang_saveTranslationUnit(self, filename,
2147 options))
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002148 if result != 0:
2149 raise TranslationUnitSaveError(result,
2150 'Error saving TranslationUnit.')
2151
Gregory Szorc2283b462012-05-12 20:49:13 +00002152 def codeComplete(self, path, line, column, unsaved_files=None, options=0):
Tobias Grosser0a166802011-02-05 17:54:04 +00002153 """
2154 Code complete in this translation unit.
2155
2156 In-memory contents for files can be provided by passing a list of pairs
2157 as unsaved_files, the first items should be the filenames to be mapped
2158 and the second should be the contents to be substituted for the
2159 file. The contents may be passed as strings or file objects.
2160 """
Gregory Szorcfbf620b2012-05-08 05:56:38 +00002161 if unsaved_files is None:
2162 unsaved_files = []
2163
Tobias Grosser0a166802011-02-05 17:54:04 +00002164 unsaved_files_array = 0
2165 if len(unsaved_files):
2166 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
2167 for i,(name,value) in enumerate(unsaved_files):
2168 if not isinstance(value, str):
2169 # FIXME: It would be great to support an efficient version
2170 # of this, one day.
2171 value = value.read()
2172 print value
2173 if not isinstance(value, str):
2174 raise TypeError,'Unexpected unsaved file contents.'
2175 unsaved_files_array[i].name = name
2176 unsaved_files_array[i].contents = value
2177 unsaved_files_array[i].length = len(value)
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002178 ptr = conf.lib.clang_codeCompleteAt(self, path, line, column,
Gregory Szorc9537e202012-07-12 04:56:46 +00002179 unsaved_files_array, len(unsaved_files), options)
Tobias Grosserba5d10b2011-10-31 02:06:50 +00002180 if ptr:
2181 return CodeCompletionResults(ptr)
2182 return None
Tobias Grosser265e6b22011-02-05 17:54:00 +00002183
Gregory Szorcbe51e432012-07-12 07:21:12 +00002184 def get_tokens(self, locations=None, extent=None):
2185 """Obtain tokens in this translation unit.
2186
2187 This is a generator for Token instances. The caller specifies a range
2188 of source code to obtain tokens for. The range can be specified as a
2189 2-tuple of SourceLocation or as a SourceRange. If both are defined,
2190 behavior is undefined.
2191 """
2192 if locations is not None:
2193 extent = SourceRange(start=locations[0], end=locations[1])
2194
2195 return TokenGroup.get_tokens(self, extent)
2196
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002197class File(ClangObject):
2198 """
Daniel Dunbar7b48b352010-01-24 04:09:34 +00002199 The File class represents a particular source file that is part of a
2200 translation unit.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002201 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002202
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002203 @staticmethod
2204 def from_name(translation_unit, file_name):
2205 """Retrieve a file handle within the given translation unit."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002206 return File(conf.lib.clang_getFile(translation_unit, file_name))
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002207
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002208 @property
2209 def name(self):
Daniel Dunbar4efd6322010-01-25 00:43:08 +00002210 """Return the complete file and path name of the file."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002211 return conf.lib.clang_getCString(conf.lib.clang_getFileName(self))
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002212
2213 @property
2214 def time(self):
Daniel Dunbar4efd6322010-01-25 00:43:08 +00002215 """Return the last modification time of the file."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002216 return conf.lib.clang_getFileTime(self)
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002217
Tobias Grossera9ea5df2011-10-31 00:07:19 +00002218 def __str__(self):
2219 return self.name
2220
2221 def __repr__(self):
2222 return "<File: %s>" % (self.name)
2223
Gregory Szorc9537e202012-07-12 04:56:46 +00002224 @staticmethod
2225 def from_cursor_result(res, fn, args):
2226 assert isinstance(res, File)
2227
2228 # Copy a reference to the TranslationUnit to prevent premature GC.
2229 res._tu = args[0]._tu
2230 return res
2231
Daniel Dunbaref7f7982010-02-13 18:33:18 +00002232class FileInclusion(object):
2233 """
2234 The FileInclusion class represents the inclusion of one source file by
2235 another via a '#include' directive or as the input file for the translation
2236 unit. This class provides information about the included file, the including
2237 file, the location of the '#include' directive and the depth of the included
2238 file in the stack. Note that the input file has depth 0.
2239 """
2240
2241 def __init__(self, src, tgt, loc, depth):
2242 self.source = src
2243 self.include = tgt
2244 self.location = loc
2245 self.depth = depth
2246
2247 @property
2248 def is_input_file(self):
2249 """True if the included file is the input file."""
2250 return self.depth == 0
2251
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002252class CompilationDatabaseError(Exception):
2253 """Represents an error that occurred when working with a CompilationDatabase
2254
2255 Each error is associated to an enumerated value, accessible under
2256 e.cdb_error. Consumers can compare the value with one of the ERROR_
2257 constants in this class.
2258 """
2259
2260 # An unknown error occured
2261 ERROR_UNKNOWN = 0
2262
2263 # The database could not be loaded
2264 ERROR_CANNOTLOADDATABASE = 1
2265
2266 def __init__(self, enumeration, message):
2267 assert isinstance(enumeration, int)
2268
2269 if enumeration > 1:
2270 raise Exception("Encountered undefined CompilationDatabase error "
2271 "constant: %d. Please file a bug to have this "
2272 "value supported." % enumeration)
2273
2274 self.cdb_error = enumeration
2275 Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
2276
2277class CompileCommand(object):
2278 """Represents the compile command used to build a file"""
2279 def __init__(self, cmd, ccmds):
2280 self.cmd = cmd
2281 # Keep a reference to the originating CompileCommands
2282 # to prevent garbage collection
2283 self.ccmds = ccmds
2284
2285 @property
2286 def directory(self):
2287 """Get the working directory for this CompileCommand"""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002288 return conf.lib.clang_CompileCommand_getDirectory(self.cmd)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002289
2290 @property
2291 def arguments(self):
2292 """
2293 Get an iterable object providing each argument in the
2294 command line for the compiler invocation as a _CXString.
2295
Arnaud A. de Grandmaison577c5302012-07-06 08:22:05 +00002296 Invariant : the first argument is the compiler executable
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002297 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002298 length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002299 for i in xrange(length):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002300 yield conf.lib.clang_CompileCommand_getArg(self.cmd, i)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002301
2302class CompileCommands(object):
2303 """
2304 CompileCommands is an iterable object containing all CompileCommand
2305 that can be used for building a specific file.
2306 """
2307 def __init__(self, ccmds):
2308 self.ccmds = ccmds
2309
2310 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002311 conf.lib.clang_CompileCommands_dispose(self.ccmds)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002312
2313 def __len__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002314 return int(conf.lib.clang_CompileCommands_getSize(self.ccmds))
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002315
2316 def __getitem__(self, i):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002317 cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i)
Arnaud A. de Grandmaisonb1614042012-07-09 11:57:30 +00002318 if not cc:
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002319 raise IndexError
2320 return CompileCommand(cc, self)
2321
2322 @staticmethod
2323 def from_result(res, fn, args):
2324 if not res:
2325 return None
2326 return CompileCommands(res)
2327
2328class CompilationDatabase(ClangObject):
2329 """
2330 The CompilationDatabase is a wrapper class around
2331 clang::tooling::CompilationDatabase
2332
2333 It enables querying how a specific source file can be built.
2334 """
2335
2336 def __del__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002337 conf.lib.clang_CompilationDatabase_dispose(self)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002338
2339 @staticmethod
2340 def from_result(res, fn, args):
2341 if not res:
2342 raise CompilationDatabaseError(0,
2343 "CompilationDatabase loading failed")
2344 return CompilationDatabase(res)
2345
2346 @staticmethod
2347 def fromDirectory(buildDir):
2348 """Builds a CompilationDatabase from the database found in buildDir"""
2349 errorCode = c_uint()
2350 try:
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002351 cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
Gregory Szorc9537e202012-07-12 04:56:46 +00002352 byref(errorCode))
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002353 except CompilationDatabaseError as e:
Gregory Szorc9537e202012-07-12 04:56:46 +00002354 raise CompilationDatabaseError(int(errorCode.value),
2355 "CompilationDatabase loading failed")
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002356 return cdb
2357
2358 def getCompileCommands(self, filename):
2359 """
2360 Get an iterable object providing all the CompileCommands available to
Arnaud A. de Grandmaison44394782012-06-30 20:43:37 +00002361 build filename. Returns None if filename is not found in the database.
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002362 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002363 return conf.lib.clang_CompilationDatabase_getCompileCommands(self,
2364 filename)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002365
Gregory Szorcbe51e432012-07-12 07:21:12 +00002366class Token(Structure):
2367 """Represents a single token from the preprocessor.
2368
2369 Tokens are effectively segments of source code. Source code is first parsed
2370 into tokens before being converted into the AST and Cursors.
2371
2372 Tokens are obtained from parsed TranslationUnit instances. You currently
2373 can't create tokens manually.
2374 """
2375 _fields_ = [
2376 ('int_data', c_uint * 4),
2377 ('ptr_data', c_void_p)
2378 ]
2379
2380 @property
2381 def spelling(self):
2382 """The spelling of this token.
2383
2384 This is the textual representation of the token in source.
2385 """
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002386 return conf.lib.clang_getTokenSpelling(self._tu, self)
Gregory Szorcbe51e432012-07-12 07:21:12 +00002387
2388 @property
2389 def kind(self):
2390 """Obtain the TokenKind of the current token."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002391 return TokenKind.from_value(conf.lib.clang_getTokenKind(self))
Gregory Szorcbe51e432012-07-12 07:21:12 +00002392
2393 @property
2394 def location(self):
2395 """The SourceLocation this Token occurs at."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002396 return conf.lib.clang_getTokenLocation(self._tu, self)
Gregory Szorcbe51e432012-07-12 07:21:12 +00002397
2398 @property
2399 def extent(self):
2400 """The SourceRange this Token occupies."""
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002401 return conf.lib.clang_getTokenExtent(self._tu, self)
Gregory Szorcbe51e432012-07-12 07:21:12 +00002402
2403 @property
2404 def cursor(self):
2405 """The Cursor this Token corresponds to."""
2406 cursor = Cursor()
2407
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002408 conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
Gregory Szorcbe51e432012-07-12 07:21:12 +00002409
2410 return cursor
2411
Gregory Szorc9537e202012-07-12 04:56:46 +00002412# Now comes the plumbing to hook up the C library.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002413
Gregory Szorc9537e202012-07-12 04:56:46 +00002414# Register callback types in common container.
2415callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p,
2416 POINTER(SourceLocation), c_uint, py_object)
2417callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
Daniel Dunbara33dca42010-01-24 21:19:57 +00002418
Tobias Grosser010556e2012-09-01 08:55:17 +00002419# Functions strictly alphabetical order.
2420functionList = [
2421 ("clang_annotateTokens",
2422 [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]),
2423
2424 ("clang_CompilationDatabase_dispose",
2425 [c_object_p]),
2426
2427 ("clang_CompilationDatabase_fromDirectory",
2428 [c_char_p, POINTER(c_uint)],
2429 c_object_p,
2430 CompilationDatabase.from_result),
2431
2432 ("clang_CompilationDatabase_getCompileCommands",
2433 [c_object_p, c_char_p],
2434 c_object_p,
2435 CompileCommands.from_result),
2436
2437 ("clang_CompileCommands_dispose",
2438 [c_object_p]),
2439
2440 ("clang_CompileCommands_getCommand",
2441 [c_object_p, c_uint],
2442 c_object_p),
2443
2444 ("clang_CompileCommands_getSize",
2445 [c_object_p],
2446 c_uint),
2447
2448 ("clang_CompileCommand_getArg",
2449 [c_object_p, c_uint],
2450 _CXString,
2451 _CXString.from_result),
2452
2453 ("clang_CompileCommand_getDirectory",
2454 [c_object_p],
2455 _CXString,
2456 _CXString.from_result),
2457
2458 ("clang_CompileCommand_getNumArgs",
2459 [c_object_p],
2460 c_uint),
2461
2462 ("clang_codeCompleteAt",
2463 [TranslationUnit, c_char_p, c_int, c_int, c_void_p, c_int, c_int],
2464 POINTER(CCRStructure)),
2465
2466 ("clang_codeCompleteGetDiagnostic",
2467 [CodeCompletionResults, c_int],
2468 Diagnostic),
2469
2470 ("clang_codeCompleteGetNumDiagnostics",
2471 [CodeCompletionResults],
2472 c_int),
2473
2474 ("clang_createIndex",
2475 [c_int, c_int],
2476 c_object_p),
2477
2478 ("clang_createTranslationUnit",
2479 [Index, c_char_p],
2480 c_object_p),
2481
2482 ("clang_CXXMethod_isStatic",
2483 [Cursor],
2484 bool),
2485
2486 ("clang_CXXMethod_isVirtual",
2487 [Cursor],
2488 bool),
2489
2490 ("clang_defaultSaveOptions",
2491 [TranslationUnit],
2492 c_uint),
2493
2494 ("clang_disposeCodeCompleteResults",
2495 [CodeCompletionResults]),
2496
2497# ("clang_disposeCXTUResourceUsage",
2498# [CXTUResourceUsage]),
2499
2500 ("clang_disposeDiagnostic",
2501 [Diagnostic]),
2502
2503 ("clang_disposeIndex",
2504 [Index]),
2505
2506 ("clang_disposeString",
2507 [_CXString]),
2508
2509 ("clang_disposeTokens",
2510 [TranslationUnit, POINTER(Token), c_uint]),
2511
2512 ("clang_disposeTranslationUnit",
2513 [TranslationUnit]),
2514
2515 ("clang_equalCursors",
2516 [Cursor, Cursor],
2517 bool),
2518
2519 ("clang_equalLocations",
2520 [SourceLocation, SourceLocation],
2521 bool),
2522
2523 ("clang_equalRanges",
2524 [SourceRange, SourceRange],
2525 bool),
2526
2527 ("clang_equalTypes",
2528 [Type, Type],
2529 bool),
2530
2531 ("clang_getArgType",
2532 [Type, c_uint],
2533 Type,
2534 Type.from_result),
2535
2536 ("clang_getArrayElementType",
2537 [Type],
2538 Type,
2539 Type.from_result),
2540
2541 ("clang_getArraySize",
2542 [Type],
2543 c_longlong),
2544
2545 ("clang_getCanonicalCursor",
2546 [Cursor],
2547 Cursor,
2548 Cursor.from_cursor_result),
2549
2550 ("clang_getCanonicalType",
2551 [Type],
2552 Type,
2553 Type.from_result),
2554
2555 ("clang_getCompletionAvailability",
2556 [c_void_p],
2557 c_int),
2558
2559 ("clang_getCompletionChunkCompletionString",
2560 [c_void_p, c_int],
2561 c_object_p),
2562
2563 ("clang_getCompletionChunkKind",
2564 [c_void_p, c_int],
2565 c_int),
2566
2567 ("clang_getCompletionChunkText",
2568 [c_void_p, c_int],
2569 _CXString),
2570
2571 ("clang_getCompletionPriority",
2572 [c_void_p],
2573 c_int),
2574
2575 ("clang_getCString",
2576 [_CXString],
2577 c_char_p),
2578
2579 ("clang_getCursor",
2580 [TranslationUnit, SourceLocation],
2581 Cursor),
2582
2583 ("clang_getCursorDefinition",
2584 [Cursor],
2585 Cursor,
2586 Cursor.from_result),
2587
2588 ("clang_getCursorDisplayName",
2589 [Cursor],
2590 _CXString,
2591 _CXString.from_result),
2592
2593 ("clang_getCursorExtent",
2594 [Cursor],
2595 SourceRange),
2596
2597 ("clang_getCursorLexicalParent",
2598 [Cursor],
2599 Cursor,
2600 Cursor.from_cursor_result),
2601
2602 ("clang_getCursorLocation",
2603 [Cursor],
2604 SourceLocation),
2605
2606 ("clang_getCursorReferenced",
2607 [Cursor],
2608 Cursor,
2609 Cursor.from_result),
2610
2611 ("clang_getCursorReferenceNameRange",
2612 [Cursor, c_uint, c_uint],
2613 SourceRange),
2614
2615 ("clang_getCursorSemanticParent",
2616 [Cursor],
2617 Cursor,
2618 Cursor.from_cursor_result),
2619
2620 ("clang_getCursorSpelling",
2621 [Cursor],
2622 _CXString,
2623 _CXString.from_result),
2624
2625 ("clang_getCursorType",
2626 [Cursor],
2627 Type,
2628 Type.from_result),
2629
2630 ("clang_getCursorUSR",
2631 [Cursor],
2632 _CXString,
2633 _CXString.from_result),
2634
2635# ("clang_getCXTUResourceUsage",
2636# [TranslationUnit],
2637# CXTUResourceUsage),
2638
2639 ("clang_getCXXAccessSpecifier",
2640 [Cursor],
2641 c_uint),
2642
2643 ("clang_getDeclObjCTypeEncoding",
2644 [Cursor],
2645 _CXString,
2646 _CXString.from_result),
2647
2648 ("clang_getDiagnostic",
2649 [c_object_p, c_uint],
2650 c_object_p),
2651
2652 ("clang_getDiagnosticCategory",
2653 [Diagnostic],
2654 c_uint),
2655
2656 ("clang_getDiagnosticCategoryName",
2657 [c_uint],
2658 _CXString,
2659 _CXString.from_result),
2660
2661 ("clang_getDiagnosticFixIt",
2662 [Diagnostic, c_uint, POINTER(SourceRange)],
2663 _CXString,
2664 _CXString.from_result),
2665
2666 ("clang_getDiagnosticLocation",
2667 [Diagnostic],
2668 SourceLocation),
2669
2670 ("clang_getDiagnosticNumFixIts",
2671 [Diagnostic],
2672 c_uint),
2673
2674 ("clang_getDiagnosticNumRanges",
2675 [Diagnostic],
2676 c_uint),
2677
2678 ("clang_getDiagnosticOption",
2679 [Diagnostic, POINTER(_CXString)],
2680 _CXString,
2681 _CXString.from_result),
2682
2683 ("clang_getDiagnosticRange",
2684 [Diagnostic, c_uint],
2685 SourceRange),
2686
2687 ("clang_getDiagnosticSeverity",
2688 [Diagnostic],
2689 c_int),
2690
2691 ("clang_getDiagnosticSpelling",
2692 [Diagnostic],
2693 _CXString,
2694 _CXString.from_result),
2695
2696 ("clang_getElementType",
2697 [Type],
2698 Type,
2699 Type.from_result),
2700
2701 ("clang_getEnumConstantDeclUnsignedValue",
2702 [Cursor],
2703 c_ulonglong),
2704
2705 ("clang_getEnumConstantDeclValue",
2706 [Cursor],
2707 c_longlong),
2708
2709 ("clang_getEnumDeclIntegerType",
2710 [Cursor],
2711 Type,
2712 Type.from_result),
2713
2714 ("clang_getFile",
2715 [TranslationUnit, c_char_p],
2716 c_object_p),
2717
2718 ("clang_getFileName",
2719 [File],
2720 _CXString), # TODO go through _CXString.from_result?
2721
2722 ("clang_getFileTime",
2723 [File],
2724 c_uint),
2725
2726 ("clang_getIBOutletCollectionType",
2727 [Cursor],
2728 Type,
2729 Type.from_result),
2730
2731 ("clang_getIncludedFile",
2732 [Cursor],
2733 File,
2734 File.from_cursor_result),
2735
2736 ("clang_getInclusions",
2737 [TranslationUnit, callbacks['translation_unit_includes'], py_object]),
2738
2739 ("clang_getInstantiationLocation",
2740 [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint),
2741 POINTER(c_uint)]),
2742
2743 ("clang_getLocation",
2744 [TranslationUnit, File, c_uint, c_uint],
2745 SourceLocation),
2746
2747 ("clang_getLocationForOffset",
2748 [TranslationUnit, File, c_uint],
2749 SourceLocation),
2750
2751 ("clang_getNullCursor",
2752 None,
2753 Cursor),
2754
2755 ("clang_getNumArgTypes",
2756 [Type],
2757 c_uint),
2758
2759 ("clang_getNumCompletionChunks",
2760 [c_void_p],
2761 c_int),
2762
2763 ("clang_getNumDiagnostics",
2764 [c_object_p],
2765 c_uint),
2766
2767 ("clang_getNumElements",
2768 [Type],
2769 c_longlong),
2770
2771 ("clang_getNumOverloadedDecls",
2772 [Cursor],
2773 c_uint),
2774
2775 ("clang_getOverloadedDecl",
2776 [Cursor, c_uint],
2777 Cursor,
2778 Cursor.from_cursor_result),
2779
2780 ("clang_getPointeeType",
2781 [Type],
2782 Type,
2783 Type.from_result),
2784
2785 ("clang_getRange",
2786 [SourceLocation, SourceLocation],
2787 SourceRange),
2788
2789 ("clang_getRangeEnd",
2790 [SourceRange],
2791 SourceLocation),
2792
2793 ("clang_getRangeStart",
2794 [SourceRange],
2795 SourceLocation),
2796
2797 ("clang_getResultType",
2798 [Type],
2799 Type,
2800 Type.from_result),
2801
2802 ("clang_getSpecializedCursorTemplate",
2803 [Cursor],
2804 Cursor,
2805 Cursor.from_cursor_result),
2806
2807 ("clang_getTemplateCursorKind",
2808 [Cursor],
2809 c_uint),
2810
2811 ("clang_getTokenExtent",
2812 [TranslationUnit, Token],
2813 SourceRange),
2814
2815 ("clang_getTokenKind",
2816 [Token],
2817 c_uint),
2818
2819 ("clang_getTokenLocation",
2820 [TranslationUnit, Token],
2821 SourceLocation),
2822
2823 ("clang_getTokenSpelling",
2824 [TranslationUnit, Token],
2825 _CXString,
2826 _CXString.from_result),
2827
2828 ("clang_getTranslationUnitCursor",
2829 [TranslationUnit],
2830 Cursor,
2831 Cursor.from_result),
2832
2833 ("clang_getTranslationUnitSpelling",
2834 [TranslationUnit],
2835 _CXString,
2836 _CXString.from_result),
2837
2838 ("clang_getTUResourceUsageName",
2839 [c_uint],
2840 c_char_p),
2841
2842 ("clang_getTypeDeclaration",
2843 [Type],
2844 Cursor,
2845 Cursor.from_result),
2846
2847 ("clang_getTypedefDeclUnderlyingType",
2848 [Cursor],
2849 Type,
2850 Type.from_result),
2851
2852 ("clang_getTypeKindSpelling",
2853 [c_uint],
2854 _CXString,
2855 _CXString.from_result),
2856
2857 ("clang_hashCursor",
2858 [Cursor],
2859 c_uint),
2860
2861 ("clang_isAttribute",
2862 [CursorKind],
2863 bool),
2864
2865 ("clang_isConstQualifiedType",
2866 [Type],
2867 bool),
2868
2869 ("clang_isCursorDefinition",
2870 [Cursor],
2871 bool),
2872
2873 ("clang_isDeclaration",
2874 [CursorKind],
2875 bool),
2876
2877 ("clang_isExpression",
2878 [CursorKind],
2879 bool),
2880
2881 ("clang_isFileMultipleIncludeGuarded",
2882 [TranslationUnit, File],
2883 bool),
2884
2885 ("clang_isFunctionTypeVariadic",
2886 [Type],
2887 bool),
2888
2889 ("clang_isInvalid",
2890 [CursorKind],
2891 bool),
2892
2893 ("clang_isPODType",
2894 [Type],
2895 bool),
2896
2897 ("clang_isPreprocessing",
2898 [CursorKind],
2899 bool),
2900
2901 ("clang_isReference",
2902 [CursorKind],
2903 bool),
2904
2905 ("clang_isRestrictQualifiedType",
2906 [Type],
2907 bool),
2908
2909 ("clang_isStatement",
2910 [CursorKind],
2911 bool),
2912
2913 ("clang_isTranslationUnit",
2914 [CursorKind],
2915 bool),
2916
2917 ("clang_isUnexposed",
2918 [CursorKind],
2919 bool),
2920
2921 ("clang_isVirtualBase",
2922 [Cursor],
2923 bool),
2924
2925 ("clang_isVolatileQualifiedType",
2926 [Type],
2927 bool),
2928
2929 ("clang_parseTranslationUnit",
2930 [Index, c_char_p, c_void_p, c_int, c_void_p, c_int, c_int],
2931 c_object_p),
2932
2933 ("clang_reparseTranslationUnit",
2934 [TranslationUnit, c_int, c_void_p, c_int],
2935 c_int),
2936
2937 ("clang_saveTranslationUnit",
2938 [TranslationUnit, c_char_p, c_uint],
2939 c_int),
2940
2941 ("clang_tokenize",
2942 [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]),
2943
2944 ("clang_visitChildren",
2945 [Cursor, callbacks['cursor_visit'], py_object],
2946 c_uint),
2947]
2948
2949class LibclangError(Exception):
2950 def __init__(self, message):
2951 self.m = message
2952
2953 def __str__(self):
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002954 return self.m
Tobias Grosser010556e2012-09-01 08:55:17 +00002955
Tobias Grosser857134e2012-09-05 20:23:53 +00002956def register_function(lib, item, ignore_errors):
Tobias Grosser010556e2012-09-01 08:55:17 +00002957 # A function may not exist, if these bindings are used with an older or
2958 # incompatible version of libclang.so.
2959 try:
2960 func = getattr(lib, item[0])
2961 except AttributeError as e:
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002962 msg = str(e) + ". Please ensure that your python bindings are "\
2963 "compatible with your libclang.so version."
Tobias Grosser857134e2012-09-05 20:23:53 +00002964 if ignore_errors:
2965 return
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002966 raise LibclangError(msg)
Tobias Grosser010556e2012-09-01 08:55:17 +00002967
2968 if len(item) >= 2:
2969 func.argtypes = item[1]
2970
2971 if len(item) >= 3:
2972 func.restype = item[2]
2973
2974 if len(item) == 4:
2975 func.errcheck = item[3]
2976
Tobias Grosser857134e2012-09-05 20:23:53 +00002977def register_functions(lib, ignore_errors):
Gregory Szorc9537e202012-07-12 04:56:46 +00002978 """Register function prototypes with a libclang library instance.
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002979
Gregory Szorc9537e202012-07-12 04:56:46 +00002980 This must be called as part of library instantiation so Python knows how
2981 to call out to the shared library.
2982 """
Daniel Dunbar30c0f262010-01-24 02:02:07 +00002983
Tobias Grosser010556e2012-09-01 08:55:17 +00002984 def register(item):
Tobias Grosser857134e2012-09-05 20:23:53 +00002985 return register_function(lib, item, ignore_errors)
Tobias Grosser58ba8c92011-10-31 00:31:32 +00002986
Tobias Grosser010556e2012-09-01 08:55:17 +00002987 map(register, functionList)
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00002988
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002989class Config:
2990 library_path = None
2991 library_file = None
Tobias Grosser857134e2012-09-05 20:23:53 +00002992 compatibility_check = True
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00002993 loaded = False
2994
2995 @staticmethod
2996 def set_library_path(path):
2997 """Set the path in which to search for libclang"""
2998 if Config.loaded:
2999 raise Exception("library path must be set before before using " \
3000 "any other functionalities in libclang.")
3001
3002 Config.library_path = path
3003
3004 @staticmethod
3005 def set_library_file(file):
3006 """Set the exact location of libclang from"""
3007 if Config.loaded:
3008 raise Exception("library file must be set before before using " \
3009 "any other functionalities in libclang.")
3010
3011 Config.library_file = path
3012
Tobias Grosser857134e2012-09-05 20:23:53 +00003013 @staticmethod
3014 def set_compatibility_check(check_status):
3015 """ Perform compatibility check when loading libclang
3016
3017 The python bindings are only tested and evaluated with the version of
3018 libclang they are provided with. To ensure correct behavior a (limited)
3019 compatibility check is performed when loading the bindings. This check
3020 will throw an exception, as soon as it fails.
3021
3022 In case these bindings are used with an older version of libclang, parts
3023 that have been stable between releases may still work. Users of the
3024 python bindings can disable the compatibility check. This will cause
3025 the python bindings to load, even though they are written for a newer
3026 version of libclang. Failures now arise if unsupported or incompatible
3027 features are accessed. The user is required to test himself if the
3028 features he is using are available and compatible between different
3029 libclang versions.
3030 """
3031 if Config.loaded:
3032 raise Exception("compatibility_check must be set before before " \
3033 "using any other functionalities in libclang.")
3034
3035 Config.compatibility_check = check_status
3036
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003037 @CachedProperty
3038 def lib(self):
3039 lib = self.get_cindex_library()
Tobias Grosser857134e2012-09-05 20:23:53 +00003040 register_functions(lib, not Config.compatibility_check)
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003041 Config.loaded = True
3042 return lib
3043
3044 def get_filename(self):
3045 if Config.library_file:
3046 return Config.library_file
3047
3048 import platform
3049 name = platform.system()
3050
3051 if name == 'Darwin':
3052 file = 'libclang.dylib'
3053 elif name == 'Windows':
3054 file = 'libclang.dll'
3055 else:
3056 file = 'libclang.so'
3057
3058 if Config.library_path:
3059 file = Config.library_path + '/' + file
3060
3061 return file
3062
3063 def get_cindex_library(self):
3064 try:
3065 library = cdll.LoadLibrary(self.get_filename())
3066 except OSError as e:
3067 msg = str(e) + ". To provide a path to libclang use " \
3068 "Config.set_library_path() or " \
3069 "Config.set_library_file()."
3070 raise LibclangError(msg)
3071
3072 return library
3073
Tobias Grosser6d2a40c2011-02-05 17:54:07 +00003074
Gregory Szorcbe51e432012-07-12 07:21:12 +00003075def register_enumerations():
3076 for name, value in clang.enumerations.TokenKinds:
3077 TokenKind.register(value, name)
3078
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003079conf = Config()
Gregory Szorcbe51e432012-07-12 07:21:12 +00003080register_enumerations()
3081
Gregory Szorcfbf620b2012-05-08 05:56:38 +00003082__all__ = [
Tobias Grosserfcbc0fb2012-09-03 18:32:30 +00003083 'Config',
Gregory Szorcfbf620b2012-05-08 05:56:38 +00003084 'CodeCompletionResults',
Arnaud A. de Grandmaison910ff3f2012-06-30 11:28:04 +00003085 'CompilationDatabase',
3086 'CompileCommands',
3087 'CompileCommand',
Gregory Szorcfbf620b2012-05-08 05:56:38 +00003088 'CursorKind',
3089 'Cursor',
3090 'Diagnostic',
3091 'File',
3092 'FixIt',
3093 'Index',
3094 'SourceLocation',
3095 'SourceRange',
Gregory Szorcbe51e432012-07-12 07:21:12 +00003096 'TokenKind',
3097 'Token',
Gregory Szorcfbf620b2012-05-08 05:56:38 +00003098 'TranslationUnitLoadError',
3099 'TranslationUnit',
3100 'TypeKind',
3101 'Type',
3102]