| 1 | #===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===# |
| 2 | # |
| 3 | # Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | # See https://llvm.org/LICENSE.txt for license information. |
| 5 | # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 | # |
| 7 | #===------------------------------------------------------------------------===# |
| 8 | |
| 9 | r""" |
| 10 | Clang Indexing Library Bindings |
| 11 | =============================== |
| 12 | |
| 13 | This module provides an interface to the Clang indexing library. It is a |
| 14 | low-level interface to the indexing library which attempts to match the Clang |
| 15 | API directly while also being "pythonic". Notable differences from the C API |
| 16 | are: |
| 17 | |
| 18 | * string results are returned as Python strings, not CXString objects. |
| 19 | |
| 20 | * null cursors are translated to None. |
| 21 | |
| 22 | * access to child cursors is done via iteration, not visitation. |
| 23 | |
| 24 | The major indexing objects are: |
| 25 | |
| 26 | Index |
| 27 | |
| 28 | The top-level object which manages some global library state. |
| 29 | |
| 30 | TranslationUnit |
| 31 | |
| 32 | High-level object encapsulating the AST for a single translation unit. These |
| 33 | can be loaded from .ast files or parsed on the fly. |
| 34 | |
| 35 | Cursor |
| 36 | |
| 37 | Generic object for representing a node in the AST. |
| 38 | |
| 39 | SourceRange, SourceLocation, and File |
| 40 | |
| 41 | Objects representing information about the input source. |
| 42 | |
| 43 | Most object information is exposed using properties, when the underlying API |
| 44 | call is efficient. |
| 45 | """ |
| 46 | from __future__ import absolute_import, division, print_function |
| 47 | |
| 48 | # TODO |
| 49 | # ==== |
| 50 | # |
| 51 | # 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 | # |
| 55 | # 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. |
| 64 | |
| 65 | from ctypes import * |
| 66 | |
| 67 | import clang.enumerations |
| 68 | |
| 69 | import os |
| 70 | import sys |
| 71 | if sys.version_info[0] == 3: |
| 72 | # Python 3 strings are unicode, translate them to/from utf8 for C-interop. |
| 73 | class c_interop_string(c_char_p): |
| 74 | |
| 75 | def __init__(self, p=None): |
| 76 | if p is None: |
| 77 | p = "" |
| 78 | if isinstance(p, str): |
| 79 | p = p.encode("utf8") |
| 80 | super(c_char_p, self).__init__(p) |
| 81 | |
| 82 | def __str__(self): |
| 83 | return self.value |
| 84 | |
| 85 | @property |
| 86 | def value(self): |
| 87 | if super(c_char_p, self).value is None: |
| 88 | return None |
| 89 | return super(c_char_p, self).value.decode("utf8") |
| 90 | |
| 91 | @classmethod |
| 92 | def from_param(cls, param): |
| 93 | if isinstance(param, str): |
| 94 | return cls(param) |
| 95 | if isinstance(param, bytes): |
| 96 | return cls(param) |
| 97 | if param is None: |
| 98 | # Support passing null to C functions expecting char arrays |
| 99 | return None |
| 100 | raise TypeError("Cannot convert '{}' to '{}'".format(type(param).__name__, cls.__name__)) |
| 101 | |
| 102 | @staticmethod |
| 103 | def to_python_string(x, *args): |
| 104 | return x.value |
| 105 | |
| 106 | def b(x): |
| 107 | if isinstance(x, bytes): |
| 108 | return x |
| 109 | return x.encode('utf8') |
| 110 | |
| 111 | elif sys.version_info[0] == 2: |
| 112 | # Python 2 strings are utf8 byte strings, no translation is needed for |
| 113 | # C-interop. |
| 114 | c_interop_string = c_char_p |
| 115 | |
| 116 | def _to_python_string(x, *args): |
| 117 | return x |
| 118 | |
| 119 | c_interop_string.to_python_string = staticmethod(_to_python_string) |
| 120 | |
| 121 | def b(x): |
| 122 | return x |
| 123 | |
| 124 | # Importing ABC-s directly from collections is deprecated since Python 3.7, |
| 125 | # will stop working in Python 3.8. |
| 126 | # See: https://docs.python.org/dev/whatsnew/3.7.html#id3 |
| 127 | if sys.version_info[:2] >= (3, 7): |
| 128 | from collections import abc as collections_abc |
| 129 | else: |
| 130 | import collections as collections_abc |
| 131 | |
| 132 | # We only support PathLike objects on Python version with os.fspath present |
| 133 | # to be consistent with the Python standard library. On older Python versions |
| 134 | # we only support strings and we have dummy fspath to just pass them through. |
| 135 | try: |
| 136 | fspath = os.fspath |
| 137 | except AttributeError: |
| 138 | def fspath(x): |
| 139 | return x |
| 140 | |
| 141 | # ctypes doesn't implicitly convert c_void_p to the appropriate wrapper |
| 142 | # object. This is a problem, because it means that from_parameter will see an |
| 143 | # integer and pass the wrong value on platforms where int != void*. Work around |
| 144 | # this by marshalling object arguments as void**. |
| 145 | c_object_p = POINTER(c_void_p) |
| 146 | |
| 147 | callbacks = {} |
| 148 | |
| 149 | ### Exception Classes ### |
| 150 | |
| 151 | class TranslationUnitLoadError(Exception): |
| 152 | """Represents an error that occurred when loading a TranslationUnit. |
| 153 | |
| 154 | This is raised in the case where a TranslationUnit could not be |
| 155 | instantiated due to failure in the libclang library. |
| 156 | |
| 157 | FIXME: Make libclang expose additional error information in this scenario. |
| 158 | """ |
| 159 | pass |
| 160 | |
| 161 | class TranslationUnitSaveError(Exception): |
| 162 | """Represents an error that occurred when saving a TranslationUnit. |
| 163 | |
| 164 | Each error has associated with it an enumerated value, accessible under |
| 165 | e.save_error. Consumers can compare the value with one of the ERROR_ |
| 166 | constants in this class. |
| 167 | """ |
| 168 | |
| 169 | # Indicates that an unknown error occurred. This typically indicates that |
| 170 | # I/O failed during save. |
| 171 | ERROR_UNKNOWN = 1 |
| 172 | |
| 173 | # Indicates that errors during translation prevented saving. The errors |
| 174 | # should be available via the TranslationUnit's diagnostics. |
| 175 | ERROR_TRANSLATION_ERRORS = 2 |
| 176 | |
| 177 | # Indicates that the translation unit was somehow invalid. |
| 178 | ERROR_INVALID_TU = 3 |
| 179 | |
| 180 | def __init__(self, enumeration, message): |
| 181 | assert isinstance(enumeration, int) |
| 182 | |
| 183 | if enumeration < 1 or enumeration > 3: |
| 184 | raise Exception("Encountered undefined TranslationUnit save error " |
| 185 | "constant: %d. Please file a bug to have this " |
| 186 | "value supported." % enumeration) |
| 187 | |
| 188 | self.save_error = enumeration |
| 189 | Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) |
| 190 | |
| 191 | ### Structures and Utility Classes ### |
| 192 | |
| 193 | class CachedProperty(object): |
| 194 | """Decorator that lazy-loads the value of a property. |
| 195 | |
| 196 | The first time the property is accessed, the original property function is |
| 197 | executed. The value it returns is set as the new value of that instance's |
| 198 | property, replacing the original method. |
| 199 | """ |
| 200 | |
| 201 | def __init__(self, wrapped): |
| 202 | self.wrapped = wrapped |
| 203 | try: |
| 204 | self.__doc__ = wrapped.__doc__ |
| 205 | except: |
| 206 | pass |
| 207 | |
| 208 | def __get__(self, instance, instance_type=None): |
| 209 | if instance is None: |
| 210 | return self |
| 211 | |
| 212 | value = self.wrapped(instance) |
| 213 | setattr(instance, self.wrapped.__name__, value) |
| 214 | |
| 215 | return value |
| 216 | |
| 217 | |
| 218 | class _CXString(Structure): |
| 219 | """Helper for transforming CXString results.""" |
| 220 | |
| 221 | _fields_ = [("spelling", c_char_p), ("free", c_int)] |
| 222 | |
| 223 | def __del__(self): |
| 224 | conf.lib.clang_disposeString(self) |
| 225 | |
| 226 | @staticmethod |
| 227 | def from_result(res, fn=None, args=None): |
| 228 | assert isinstance(res, _CXString) |
| 229 | return conf.lib.clang_getCString(res) |
| 230 | |
| 231 | |
| 232 | class SourceLocation(Structure): |
| 233 | """ |
| 234 | A SourceLocation represents a particular location within a source file. |
| 235 | """ |
| 236 | _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)] |
| 237 | _data = None |
| 238 | |
| 239 | def _get_instantiation(self): |
| 240 | if self._data is None: |
| 241 | f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint() |
| 242 | conf.lib.clang_getInstantiationLocation(self, byref(f), byref(l), |
| 243 | byref(c), byref(o)) |
| 244 | if f: |
| 245 | f = File(f) |
| 246 | else: |
| 247 | f = None |
| 248 | self._data = (f, int(l.value), int(c.value), int(o.value)) |
| 249 | return self._data |
| 250 | |
| 251 | @staticmethod |
| 252 | def from_position(tu, file, line, column): |
| 253 | """ |
| 254 | Retrieve the source location associated with a given file/line/column in |
| 255 | a particular translation unit. |
| 256 | """ |
| 257 | return conf.lib.clang_getLocation(tu, file, line, column) |
| 258 | |
| 259 | @staticmethod |
| 260 | def from_offset(tu, file, offset): |
| 261 | """Retrieve a SourceLocation from a given character offset. |
| 262 | |
| 263 | tu -- TranslationUnit file belongs to |
| 264 | file -- File instance to obtain offset from |
| 265 | offset -- Integer character offset within file |
| 266 | """ |
| 267 | return conf.lib.clang_getLocationForOffset(tu, file, offset) |
| 268 | |
| 269 | @property |
| 270 | def file(self): |
| 271 | """Get the file represented by this source location.""" |
| 272 | return self._get_instantiation()[0] |
| 273 | |
| 274 | @property |
| 275 | def line(self): |
| 276 | """Get the line represented by this source location.""" |
| 277 | return self._get_instantiation()[1] |
| 278 | |
| 279 | @property |
| 280 | def column(self): |
| 281 | """Get the column represented by this source location.""" |
| 282 | return self._get_instantiation()[2] |
| 283 | |
| 284 | @property |
| 285 | def offset(self): |
| 286 | """Get the file offset represented by this source location.""" |
| 287 | return self._get_instantiation()[3] |
| 288 | |
| 289 | def __eq__(self, other): |
| 290 | return conf.lib.clang_equalLocations(self, other) |
| 291 | |
| 292 | def __ne__(self, other): |
| 293 | return not self.__eq__(other) |
| 294 | |
| 295 | def __repr__(self): |
| 296 | if self.file: |
| 297 | filename = self.file.name |
| 298 | else: |
| 299 | filename = None |
| 300 | return "<SourceLocation file %r, line %r, column %r>" % ( |
| 301 | filename, self.line, self.column) |
| 302 | |
| 303 | class SourceRange(Structure): |
| 304 | """ |
| 305 | A SourceRange describes a range of source locations within the source |
| 306 | code. |
| 307 | """ |
| 308 | _fields_ = [ |
| 309 | ("ptr_data", c_void_p * 2), |
| 310 | ("begin_int_data", c_uint), |
| 311 | ("end_int_data", c_uint)] |
| 312 | |
| 313 | # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes |
| 314 | # object. |
| 315 | @staticmethod |
| 316 | def from_locations(start, end): |
| 317 | return conf.lib.clang_getRange(start, end) |
| 318 | |
| 319 | @property |
| 320 | def start(self): |
| 321 | """ |
| 322 | Return a SourceLocation representing the first character within a |
| 323 | source range. |
| 324 | """ |
| 325 | return conf.lib.clang_getRangeStart(self) |
| 326 | |
| 327 | @property |
| 328 | def end(self): |
| 329 | """ |
| 330 | Return a SourceLocation representing the last character within a |
| 331 | source range. |
| 332 | """ |
| 333 | return conf.lib.clang_getRangeEnd(self) |
| 334 | |
| 335 | def __eq__(self, other): |
| 336 | return conf.lib.clang_equalRanges(self, other) |
| 337 | |
| 338 | def __ne__(self, other): |
| 339 | return not self.__eq__(other) |
| 340 | |
| 341 | def __contains__(self, other): |
| 342 | """Useful to detect the Token/Lexer bug""" |
| 343 | if not isinstance(other, SourceLocation): |
| 344 | return False |
| 345 | if other.file is None and self.start.file is None: |
| 346 | pass |
| 347 | elif ( self.start.file.name != other.file.name or |
| 348 | other.file.name != self.end.file.name): |
| 349 | # same file name |
| 350 | return False |
| 351 | # same file, in between lines |
| 352 | if self.start.line < other.line < self.end.line: |
| 353 | return True |
| 354 | elif self.start.line == other.line: |
| 355 | # same file first line |
| 356 | if self.start.column <= other.column: |
| 357 | return True |
| 358 | elif other.line == self.end.line: |
| 359 | # same file last line |
| 360 | if other.column <= self.end.column: |
| 361 | return True |
| 362 | return False |
| 363 | |
| 364 | def __repr__(self): |
| 365 | return "<SourceRange start %r, end %r>" % (self.start, self.end) |
| 366 | |
| 367 | class Diagnostic(object): |
| 368 | """ |
| 369 | A Diagnostic is a single instance of a Clang diagnostic. It includes the |
| 370 | diagnostic severity, the message, the location the diagnostic occurred, as |
| 371 | well as additional source ranges and associated fix-it hints. |
| 372 | """ |
| 373 | |
| 374 | Ignored = 0 |
| 375 | Note = 1 |
| 376 | Warning = 2 |
| 377 | Error = 3 |
| 378 | Fatal = 4 |
| 379 | |
| 380 | DisplaySourceLocation = 0x01 |
| 381 | DisplayColumn = 0x02 |
| 382 | DisplaySourceRanges = 0x04 |
| 383 | DisplayOption = 0x08 |
| 384 | DisplayCategoryId = 0x10 |
| 385 | DisplayCategoryName = 0x20 |
| 386 | _FormatOptionsMask = 0x3f |
| 387 | |
| 388 | def __init__(self, ptr): |
| 389 | self.ptr = ptr |
| 390 | |
| 391 | def __del__(self): |
| 392 | conf.lib.clang_disposeDiagnostic(self) |
| 393 | |
| 394 | @property |
| 395 | def severity(self): |
| 396 | return conf.lib.clang_getDiagnosticSeverity(self) |
| 397 | |
| 398 | @property |
| 399 | def location(self): |
| 400 | return conf.lib.clang_getDiagnosticLocation(self) |
| 401 | |
| 402 | @property |
| 403 | def spelling(self): |
| 404 | return conf.lib.clang_getDiagnosticSpelling(self) |
| 405 | |
| 406 | @property |
| 407 | def ranges(self): |
| 408 | class RangeIterator(object): |
| 409 | def __init__(self, diag): |
| 410 | self.diag = diag |
| 411 | |
| 412 | def __len__(self): |
| 413 | return int(conf.lib.clang_getDiagnosticNumRanges(self.diag)) |
| 414 | |
| 415 | def __getitem__(self, key): |
| 416 | if (key >= len(self)): |
| 417 | raise IndexError |
| 418 | return conf.lib.clang_getDiagnosticRange(self.diag, key) |
| 419 | |
| 420 | return RangeIterator(self) |
| 421 | |
| 422 | @property |
| 423 | def fixits(self): |
| 424 | class FixItIterator(object): |
| 425 | def __init__(self, diag): |
| 426 | self.diag = diag |
| 427 | |
| 428 | def __len__(self): |
| 429 | return int(conf.lib.clang_getDiagnosticNumFixIts(self.diag)) |
| 430 | |
| 431 | def __getitem__(self, key): |
| 432 | range = SourceRange() |
| 433 | value = conf.lib.clang_getDiagnosticFixIt(self.diag, key, |
| 434 | byref(range)) |
| 435 | if len(value) == 0: |
| 436 | raise IndexError |
| 437 | |
| 438 | return FixIt(range, value) |
| 439 | |
| 440 | return FixItIterator(self) |
| 441 | |
| 442 | @property |
| 443 | def children(self): |
| 444 | class ChildDiagnosticsIterator(object): |
| 445 | def __init__(self, diag): |
| 446 | self.diag_set = conf.lib.clang_getChildDiagnostics(diag) |
| 447 | |
| 448 | def __len__(self): |
| 449 | return int(conf.lib.clang_getNumDiagnosticsInSet(self.diag_set)) |
| 450 | |
| 451 | def __getitem__(self, key): |
| 452 | diag = conf.lib.clang_getDiagnosticInSet(self.diag_set, key) |
| 453 | if not diag: |
| 454 | raise IndexError |
| 455 | return Diagnostic(diag) |
| 456 | |
| 457 | return ChildDiagnosticsIterator(self) |
| 458 | |
| 459 | @property |
| 460 | def category_number(self): |
| 461 | """The category number for this diagnostic or 0 if unavailable.""" |
| 462 | return conf.lib.clang_getDiagnosticCategory(self) |
| 463 | |
| 464 | @property |
| 465 | def category_name(self): |
| 466 | """The string name of the category for this diagnostic.""" |
| 467 | return conf.lib.clang_getDiagnosticCategoryText(self) |
| 468 | |
| 469 | @property |
| 470 | def option(self): |
| 471 | """The command-line option that enables this diagnostic.""" |
| 472 | return conf.lib.clang_getDiagnosticOption(self, None) |
| 473 | |
| 474 | @property |
| 475 | def disable_option(self): |
| 476 | """The command-line option that disables this diagnostic.""" |
| 477 | disable = _CXString() |
| 478 | conf.lib.clang_getDiagnosticOption(self, byref(disable)) |
| 479 | return _CXString.from_result(disable) |
| 480 | |
| 481 | def format(self, options=None): |
| 482 | """ |
| 483 | Format this diagnostic for display. The options argument takes |
| 484 | Diagnostic.Display* flags, which can be combined using bitwise OR. If |
| 485 | the options argument is not provided, the default display options will |
| 486 | be used. |
| 487 | """ |
| 488 | if options is None: |
| 489 | options = conf.lib.clang_defaultDiagnosticDisplayOptions() |
| 490 | if options & ~Diagnostic._FormatOptionsMask: |
| 491 | raise ValueError('Invalid format options') |
| 492 | return conf.lib.clang_formatDiagnostic(self, options) |
| 493 | |
| 494 | def __repr__(self): |
| 495 | return "<Diagnostic severity %r, location %r, spelling %r>" % ( |
| 496 | self.severity, self.location, self.spelling) |
| 497 | |
| 498 | def __str__(self): |
| 499 | return self.format() |
| 500 | |
| 501 | def from_param(self): |
| 502 | return self.ptr |
| 503 | |
| 504 | class FixIt(object): |
| 505 | """ |
| 506 | A FixIt represents a transformation to be applied to the source to |
| 507 | "fix-it". The fix-it shouldbe applied by replacing the given source range |
| 508 | with the given value. |
| 509 | """ |
| 510 | |
| 511 | def __init__(self, range, value): |
| 512 | self.range = range |
| 513 | self.value = value |
| 514 | |
| 515 | def __repr__(self): |
| 516 | return "<FixIt range %r, value %r>" % (self.range, self.value) |
| 517 | |
| 518 | class TokenGroup(object): |
| 519 | """Helper class to facilitate token management. |
| 520 | |
| 521 | Tokens are allocated from libclang in chunks. They must be disposed of as a |
| 522 | collective group. |
| 523 | |
| 524 | One purpose of this class is for instances to represent groups of allocated |
| 525 | tokens. Each token in a group contains a reference back to an instance of |
| 526 | this class. When all tokens from a group are garbage collected, it allows |
| 527 | this class to be garbage collected. When this class is garbage collected, |
| 528 | it calls the libclang destructor which invalidates all tokens in the group. |
| 529 | |
| 530 | You should not instantiate this class outside of this module. |
| 531 | """ |
| 532 | def __init__(self, tu, memory, count): |
| 533 | self._tu = tu |
| 534 | self._memory = memory |
| 535 | self._count = count |
| 536 | |
| 537 | def __del__(self): |
| 538 | conf.lib.clang_disposeTokens(self._tu, self._memory, self._count) |
| 539 | |
| 540 | @staticmethod |
| 541 | def get_tokens(tu, extent): |
| 542 | """Helper method to return all tokens in an extent. |
| 543 | |
| 544 | This functionality is needed multiple places in this module. We define |
| 545 | it here because it seems like a logical place. |
| 546 | """ |
| 547 | tokens_memory = POINTER(Token)() |
| 548 | tokens_count = c_uint() |
| 549 | |
| 550 | conf.lib.clang_tokenize(tu, extent, byref(tokens_memory), |
| 551 | byref(tokens_count)) |
| 552 | |
| 553 | count = int(tokens_count.value) |
| 554 | |
| 555 | # If we get no tokens, no memory was allocated. Be sure not to return |
| 556 | # anything and potentially call a destructor on nothing. |
| 557 | if count < 1: |
| 558 | return |
| 559 | |
| 560 | tokens_array = cast(tokens_memory, POINTER(Token * count)).contents |
| 561 | |
| 562 | token_group = TokenGroup(tu, tokens_memory, tokens_count) |
| 563 | |
| 564 | for i in range(0, count): |
| 565 | token = Token() |
| 566 | token.int_data = tokens_array[i].int_data |
| 567 | token.ptr_data = tokens_array[i].ptr_data |
| 568 | token._tu = tu |
| 569 | token._group = token_group |
| 570 | |
| 571 | yield token |
| 572 | |
| 573 | class TokenKind(object): |
| 574 | """Describes a specific type of a Token.""" |
| 575 | |
| 576 | _value_map = {} # int -> TokenKind |
| 577 | |
| 578 | def __init__(self, value, name): |
| 579 | """Create a new TokenKind instance from a numeric value and a name.""" |
| 580 | self.value = value |
| 581 | self.name = name |
| 582 | |
| 583 | def __repr__(self): |
| 584 | return 'TokenKind.%s' % (self.name,) |
| 585 | |
| 586 | @staticmethod |
| 587 | def from_value(value): |
| 588 | """Obtain a registered TokenKind instance from its value.""" |
| 589 | result = TokenKind._value_map.get(value, None) |
| 590 | |
| 591 | if result is None: |
| 592 | raise ValueError('Unknown TokenKind: %d' % value) |
| 593 | |
| 594 | return result |
| 595 | |
| 596 | @staticmethod |
| 597 | def register(value, name): |
| 598 | """Register a new TokenKind enumeration. |
| 599 | |
| 600 | This should only be called at module load time by code within this |
| 601 | package. |
| 602 | """ |
| 603 | if value in TokenKind._value_map: |
| 604 | raise ValueError('TokenKind already registered: %d' % value) |
| 605 | |
| 606 | kind = TokenKind(value, name) |
| 607 | TokenKind._value_map[value] = kind |
| 608 | setattr(TokenKind, name, kind) |
| 609 | |
| 610 | ### Cursor Kinds ### |
| 611 | class BaseEnumeration(object): |
| 612 | """ |
| 613 | Common base class for named enumerations held in sync with Index.h values. |
| 614 | |
| 615 | Subclasses must define their own _kinds and _name_map members, as: |
| 616 | _kinds = [] |
| 617 | _name_map = None |
| 618 | These values hold the per-subclass instances and value-to-name mappings, |
| 619 | respectively. |
| 620 | |
| 621 | """ |
| 622 | |
| 623 | def __init__(self, value): |
| 624 | if value >= len(self.__class__._kinds): |
| 625 | self.__class__._kinds += [None] * (value - len(self.__class__._kinds) + 1) |
| 626 | if self.__class__._kinds[value] is not None: |
| 627 | raise ValueError('{0} value {1} already loaded'.format( |
| 628 | str(self.__class__), value)) |
| 629 | self.value = value |
| 630 | self.__class__._kinds[value] = self |
| 631 | self.__class__._name_map = None |
| 632 | |
| 633 | |
| 634 | def from_param(self): |
| 635 | return self.value |
| 636 | |
| 637 | @property |
| 638 | def name(self): |
| 639 | """Get the enumeration name of this cursor kind.""" |
| 640 | if self._name_map is None: |
| 641 | self._name_map = {} |
| 642 | for key, value in self.__class__.__dict__.items(): |
| 643 | if isinstance(value, self.__class__): |
| 644 | self._name_map[value] = key |
| 645 | return self._name_map[self] |
| 646 | |
| 647 | @classmethod |
| 648 | def from_id(cls, id): |
| 649 | if id >= len(cls._kinds) or cls._kinds[id] is None: |
| 650 | raise ValueError('Unknown template argument kind %d' % id) |
| 651 | return cls._kinds[id] |
| 652 | |
| 653 | def __repr__(self): |
| 654 | return '%s.%s' % (self.__class__, self.name,) |
| 655 | |
| 656 | |
| 657 | class CursorKind(BaseEnumeration): |
| 658 | """ |
| 659 | A CursorKind describes the kind of entity that a cursor points to. |
| 660 | """ |
| 661 | |
| 662 | # The required BaseEnumeration declarations. |
| 663 | _kinds = [] |
| 664 | _name_map = None |
| 665 | |
| 666 | @staticmethod |
| 667 | def get_all_kinds(): |
| 668 | """Return all CursorKind enumeration instances.""" |
| 669 | return [x for x in CursorKind._kinds if not x is None] |
| 670 | |
| 671 | def is_declaration(self): |
| 672 | """Test if this is a declaration kind.""" |
| 673 | return conf.lib.clang_isDeclaration(self) |
| 674 | |
| 675 | def is_reference(self): |
| 676 | """Test if this is a reference kind.""" |
| 677 | return conf.lib.clang_isReference(self) |
| 678 | |
| 679 | def is_expression(self): |
| 680 | """Test if this is an expression kind.""" |
| 681 | return conf.lib.clang_isExpression(self) |
| 682 | |
| 683 | def is_statement(self): |
| 684 | """Test if this is a statement kind.""" |
| 685 | return conf.lib.clang_isStatement(self) |
| 686 | |
| 687 | def is_attribute(self): |
| 688 | """Test if this is an attribute kind.""" |
| 689 | return conf.lib.clang_isAttribute(self) |
| 690 | |
| 691 | def is_invalid(self): |
| 692 | """Test if this is an invalid kind.""" |
| 693 | return conf.lib.clang_isInvalid(self) |
| 694 | |
| 695 | def is_translation_unit(self): |
| 696 | """Test if this is a translation unit kind.""" |
| 697 | return conf.lib.clang_isTranslationUnit(self) |
| 698 | |
| 699 | def is_preprocessing(self): |
| 700 | """Test if this is a preprocessing kind.""" |
| 701 | return conf.lib.clang_isPreprocessing(self) |
| 702 | |
| 703 | def is_unexposed(self): |
| 704 | """Test if this is an unexposed kind.""" |
| 705 | return conf.lib.clang_isUnexposed(self) |
| 706 | |
| 707 | def __repr__(self): |
| 708 | return 'CursorKind.%s' % (self.name,) |
| 709 | |
| 710 | ### |
| 711 | # Declaration Kinds |
| 712 | |
| 713 | # A declaration whose specific kind is not exposed via this interface. |
| 714 | # |
| 715 | # Unexposed declarations have the same operations as any other kind of |
| 716 | # declaration; one can extract their location information, spelling, find their |
| 717 | # definitions, etc. However, the specific kind of the declaration is not |
| 718 | # reported. |
| 719 | CursorKind.UNEXPOSED_DECL = CursorKind(1) |
| 720 | |
| 721 | # A C or C++ struct. |
| 722 | CursorKind.STRUCT_DECL = CursorKind(2) |
| 723 | |
| 724 | # A C or C++ union. |
| 725 | CursorKind.UNION_DECL = CursorKind(3) |
| 726 | |
| 727 | # A C++ class. |
| 728 | CursorKind.CLASS_DECL = CursorKind(4) |
| 729 | |
| 730 | # An enumeration. |
| 731 | CursorKind.ENUM_DECL = CursorKind(5) |
| 732 | |
| 733 | # A field (in C) or non-static data member (in C++) in a struct, union, or C++ |
| 734 | # class. |
| 735 | CursorKind.FIELD_DECL = CursorKind(6) |
| 736 | |
| 737 | # An enumerator constant. |
| 738 | CursorKind.ENUM_CONSTANT_DECL = CursorKind(7) |
| 739 | |
| 740 | # A function. |
| 741 | CursorKind.FUNCTION_DECL = CursorKind(8) |
| 742 | |
| 743 | # A variable. |
| 744 | CursorKind.VAR_DECL = CursorKind(9) |
| 745 | |
| 746 | # A function or method parameter. |
| 747 | CursorKind.PARM_DECL = CursorKind(10) |
| 748 | |
| 749 | # An Objective-C @interface. |
| 750 | CursorKind.OBJC_INTERFACE_DECL = CursorKind(11) |
| 751 | |
| 752 | # An Objective-C @interface for a category. |
| 753 | CursorKind.OBJC_CATEGORY_DECL = CursorKind(12) |
| 754 | |
| 755 | # An Objective-C @protocol declaration. |
| 756 | CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13) |
| 757 | |
| 758 | # An Objective-C @property declaration. |
| 759 | CursorKind.OBJC_PROPERTY_DECL = CursorKind(14) |
| 760 | |
| 761 | # An Objective-C instance variable. |
| 762 | CursorKind.OBJC_IVAR_DECL = CursorKind(15) |
| 763 | |
| 764 | # An Objective-C instance method. |
| 765 | CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16) |
| 766 | |
| 767 | # An Objective-C class method. |
| 768 | CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17) |
| 769 | |
| 770 | # An Objective-C @implementation. |
| 771 | CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18) |
| 772 | |
| 773 | # An Objective-C @implementation for a category. |
| 774 | CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19) |
| 775 | |
| 776 | # A typedef. |
| 777 | CursorKind.TYPEDEF_DECL = CursorKind(20) |
| 778 | |
| 779 | # A C++ class method. |
| 780 | CursorKind.CXX_METHOD = CursorKind(21) |
| 781 | |
| 782 | # A C++ namespace. |
| 783 | CursorKind.NAMESPACE = CursorKind(22) |
| 784 | |
| 785 | # A linkage specification, e.g. 'extern "C"'. |
| 786 | CursorKind.LINKAGE_SPEC = CursorKind(23) |
| 787 | |
| 788 | # A C++ constructor. |
| 789 | CursorKind.CONSTRUCTOR = CursorKind(24) |
| 790 | |
| 791 | # A C++ destructor. |
| 792 | CursorKind.DESTRUCTOR = CursorKind(25) |
| 793 | |
| 794 | # A C++ conversion function. |
| 795 | CursorKind.CONVERSION_FUNCTION = CursorKind(26) |
| 796 | |
| 797 | # A C++ template type parameter |
| 798 | CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27) |
| 799 | |
| 800 | # A C++ non-type template parameter. |
| 801 | CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28) |
| 802 | |
| 803 | # A C++ template template parameter. |
| 804 | CursorKind.TEMPLATE_TEMPLATE_PARAMETER = CursorKind(29) |
| 805 | |
| 806 | # A C++ function template. |
| 807 | CursorKind.FUNCTION_TEMPLATE = CursorKind(30) |
| 808 | |
| 809 | # A C++ class template. |
| 810 | CursorKind.CLASS_TEMPLATE = CursorKind(31) |
| 811 | |
| 812 | # A C++ class template partial specialization. |
| 813 | CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32) |
| 814 | |
| 815 | # A C++ namespace alias declaration. |
| 816 | CursorKind.NAMESPACE_ALIAS = CursorKind(33) |
| 817 | |
| 818 | # A C++ using directive |
| 819 | CursorKind.USING_DIRECTIVE = CursorKind(34) |
| 820 | |
| 821 | # A C++ using declaration |
| 822 | CursorKind.USING_DECLARATION = CursorKind(35) |
| 823 | |
| 824 | # A Type alias decl. |
| 825 | CursorKind.TYPE_ALIAS_DECL = CursorKind(36) |
| 826 | |
| 827 | # A Objective-C synthesize decl |
| 828 | CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37) |
| 829 | |
| 830 | # A Objective-C dynamic decl |
| 831 | CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38) |
| 832 | |
| 833 | # A C++ access specifier decl. |
| 834 | CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39) |
| 835 | |
| 836 | |
| 837 | ### |
| 838 | # Reference Kinds |
| 839 | |
| 840 | CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40) |
| 841 | CursorKind.OBJC_PROTOCOL_REF = CursorKind(41) |
| 842 | CursorKind.OBJC_CLASS_REF = CursorKind(42) |
| 843 | |
| 844 | # A reference to a type declaration. |
| 845 | # |
| 846 | # A type reference occurs anywhere where a type is named but not |
| 847 | # declared. For example, given: |
| 848 | # typedef unsigned size_type; |
| 849 | # size_type size; |
| 850 | # |
| 851 | # The typedef is a declaration of size_type (CXCursor_TypedefDecl), |
| 852 | # while the type of the variable "size" is referenced. The cursor |
| 853 | # referenced by the type of size is the typedef for size_type. |
| 854 | CursorKind.TYPE_REF = CursorKind(43) |
| 855 | CursorKind.CXX_BASE_SPECIFIER = CursorKind(44) |
| 856 | |
| 857 | # A reference to a class template, function template, template |
| 858 | # template parameter, or class template partial specialization. |
| 859 | CursorKind.TEMPLATE_REF = CursorKind(45) |
| 860 | |
| 861 | # A reference to a namespace or namepsace alias. |
| 862 | CursorKind.NAMESPACE_REF = CursorKind(46) |
| 863 | |
| 864 | # A reference to a member of a struct, union, or class that occurs in |
| 865 | # some non-expression context, e.g., a designated initializer. |
| 866 | CursorKind.MEMBER_REF = CursorKind(47) |
| 867 | |
| 868 | # A reference to a labeled statement. |
| 869 | CursorKind.LABEL_REF = CursorKind(48) |
| 870 | |
| 871 | # A reference to a set of overloaded functions or function templates |
| 872 | # that has not yet been resolved to a specific function or function template. |
| 873 | CursorKind.OVERLOADED_DECL_REF = CursorKind(49) |
| 874 | |
| 875 | # A reference to a variable that occurs in some non-expression |
| 876 | # context, e.g., a C++ lambda capture list. |
| 877 | CursorKind.VARIABLE_REF = CursorKind(50) |
| 878 | |
| 879 | ### |
| 880 | # Invalid/Error Kinds |
| 881 | |
| 882 | CursorKind.INVALID_FILE = CursorKind(70) |
| 883 | CursorKind.NO_DECL_FOUND = CursorKind(71) |
| 884 | CursorKind.NOT_IMPLEMENTED = CursorKind(72) |
| 885 | CursorKind.INVALID_CODE = CursorKind(73) |
| 886 | |
| 887 | ### |
| 888 | # Expression Kinds |
| 889 | |
| 890 | # An expression whose specific kind is not exposed via this interface. |
| 891 | # |
| 892 | # Unexposed expressions have the same operations as any other kind of |
| 893 | # expression; one can extract their location information, spelling, children, |
| 894 | # etc. However, the specific kind of the expression is not reported. |
| 895 | CursorKind.UNEXPOSED_EXPR = CursorKind(100) |
| 896 | |
| 897 | # An expression that refers to some value declaration, such as a function, |
| 898 | # variable, or enumerator. |
| 899 | CursorKind.DECL_REF_EXPR = CursorKind(101) |
| 900 | |
| 901 | # An expression that refers to a member of a struct, union, class, Objective-C |
| 902 | # class, etc. |
| 903 | CursorKind.MEMBER_REF_EXPR = CursorKind(102) |
| 904 | |
| 905 | # An expression that calls a function. |
| 906 | CursorKind.CALL_EXPR = CursorKind(103) |
| 907 | |
| 908 | # An expression that sends a message to an Objective-C object or class. |
| 909 | CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104) |
| 910 | |
| 911 | # An expression that represents a block literal. |
| 912 | CursorKind.BLOCK_EXPR = CursorKind(105) |
| 913 | |
| 914 | # An integer literal. |
| 915 | CursorKind.INTEGER_LITERAL = CursorKind(106) |
| 916 | |
| 917 | # A floating point number literal. |
| 918 | CursorKind.FLOATING_LITERAL = CursorKind(107) |
| 919 | |
| 920 | # An imaginary number literal. |
| 921 | CursorKind.IMAGINARY_LITERAL = CursorKind(108) |
| 922 | |
| 923 | # A string literal. |
| 924 | CursorKind.STRING_LITERAL = CursorKind(109) |
| 925 | |
| 926 | # A character literal. |
| 927 | CursorKind.CHARACTER_LITERAL = CursorKind(110) |
| 928 | |
| 929 | # A parenthesized expression, e.g. "(1)". |
| 930 | # |
| 931 | # This AST node is only formed if full location information is requested. |
| 932 | CursorKind.PAREN_EXPR = CursorKind(111) |
| 933 | |
| 934 | # This represents the unary-expression's (except sizeof and |
| 935 | # alignof). |
| 936 | CursorKind.UNARY_OPERATOR = CursorKind(112) |
| 937 | |
| 938 | # [C99 6.5.2.1] Array Subscripting. |
| 939 | CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113) |
| 940 | |
| 941 | # A builtin binary operation expression such as "x + y" or |
| 942 | # "x <= y". |
| 943 | CursorKind.BINARY_OPERATOR = CursorKind(114) |
| 944 | |
| 945 | # Compound assignment such as "+=". |
| 946 | CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115) |
| 947 | |
| 948 | # The ?: ternary operator. |
| 949 | CursorKind.CONDITIONAL_OPERATOR = CursorKind(116) |
| 950 | |
| 951 | # An explicit cast in C (C99 6.5.4) or a C-style cast in C++ |
| 952 | # (C++ [expr.cast]), which uses the syntax (Type)expr. |
| 953 | # |
| 954 | # For example: (int)f. |
| 955 | CursorKind.CSTYLE_CAST_EXPR = CursorKind(117) |
| 956 | |
| 957 | # [C99 6.5.2.5] |
| 958 | CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118) |
| 959 | |
| 960 | # Describes an C or C++ initializer list. |
| 961 | CursorKind.INIT_LIST_EXPR = CursorKind(119) |
| 962 | |
| 963 | # The GNU address of label extension, representing &&label. |
| 964 | CursorKind.ADDR_LABEL_EXPR = CursorKind(120) |
| 965 | |
| 966 | # This is the GNU Statement Expression extension: ({int X=4; X;}) |
| 967 | CursorKind.StmtExpr = CursorKind(121) |
| 968 | |
| 969 | # Represents a C11 generic selection. |
| 970 | CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122) |
| 971 | |
| 972 | # Implements the GNU __null extension, which is a name for a null |
| 973 | # pointer constant that has integral type (e.g., int or long) and is the same |
| 974 | # size and alignment as a pointer. |
| 975 | # |
| 976 | # The __null extension is typically only used by system headers, which define |
| 977 | # NULL as __null in C++ rather than using 0 (which is an integer that may not |
| 978 | # match the size of a pointer). |
| 979 | CursorKind.GNU_NULL_EXPR = CursorKind(123) |
| 980 | |
| 981 | # C++'s static_cast<> expression. |
| 982 | CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124) |
| 983 | |
| 984 | # C++'s dynamic_cast<> expression. |
| 985 | CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125) |
| 986 | |
| 987 | # C++'s reinterpret_cast<> expression. |
| 988 | CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126) |
| 989 | |
| 990 | # C++'s const_cast<> expression. |
| 991 | CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127) |
| 992 | |
| 993 | # Represents an explicit C++ type conversion that uses "functional" |
| 994 | # notion (C++ [expr.type.conv]). |
| 995 | # |
| 996 | # Example: |
| 997 | # \code |
| 998 | # x = int(0.5); |
| 999 | # \endcode |
| 1000 | CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128) |
| 1001 | |
| 1002 | # A C++ typeid expression (C++ [expr.typeid]). |
| 1003 | CursorKind.CXX_TYPEID_EXPR = CursorKind(129) |
| 1004 | |
| 1005 | # [C++ 2.13.5] C++ Boolean Literal. |
| 1006 | CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130) |
| 1007 | |
| 1008 | # [C++0x 2.14.7] C++ Pointer Literal. |
| 1009 | CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131) |
| 1010 | |
| 1011 | # Represents the "this" expression in C++ |
| 1012 | CursorKind.CXX_THIS_EXPR = CursorKind(132) |
| 1013 | |
| 1014 | # [C++ 15] C++ Throw Expression. |
| 1015 | # |
| 1016 | # This handles 'throw' and 'throw' assignment-expression. When |
| 1017 | # assignment-expression isn't present, Op will be null. |
| 1018 | CursorKind.CXX_THROW_EXPR = CursorKind(133) |
| 1019 | |
| 1020 | # A new expression for memory allocation and constructor calls, e.g: |
| 1021 | # "new CXXNewExpr(foo)". |
| 1022 | CursorKind.CXX_NEW_EXPR = CursorKind(134) |
| 1023 | |
| 1024 | # A delete expression for memory deallocation and destructor calls, |
| 1025 | # e.g. "delete[] pArray". |
| 1026 | CursorKind.CXX_DELETE_EXPR = CursorKind(135) |
| 1027 | |
| 1028 | # Represents a unary expression. |
| 1029 | CursorKind.CXX_UNARY_EXPR = CursorKind(136) |
| 1030 | |
| 1031 | # ObjCStringLiteral, used for Objective-C string literals i.e. "foo". |
| 1032 | CursorKind.OBJC_STRING_LITERAL = CursorKind(137) |
| 1033 | |
| 1034 | # ObjCEncodeExpr, used for in Objective-C. |
| 1035 | CursorKind.OBJC_ENCODE_EXPR = CursorKind(138) |
| 1036 | |
| 1037 | # ObjCSelectorExpr used for in Objective-C. |
| 1038 | CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139) |
| 1039 | |
| 1040 | # Objective-C's protocol expression. |
| 1041 | CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140) |
| 1042 | |
| 1043 | # An Objective-C "bridged" cast expression, which casts between |
| 1044 | # Objective-C pointers and C pointers, transferring ownership in the process. |
| 1045 | # |
| 1046 | # \code |
| 1047 | # NSString *str = (__bridge_transfer NSString *)CFCreateString(); |
| 1048 | # \endcode |
| 1049 | CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141) |
| 1050 | |
| 1051 | # Represents a C++0x pack expansion that produces a sequence of |
| 1052 | # expressions. |
| 1053 | # |
| 1054 | # A pack expansion expression contains a pattern (which itself is an |
| 1055 | # expression) followed by an ellipsis. For example: |
| 1056 | CursorKind.PACK_EXPANSION_EXPR = CursorKind(142) |
| 1057 | |
| 1058 | # Represents an expression that computes the length of a parameter |
| 1059 | # pack. |
| 1060 | CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143) |
| 1061 | |
| 1062 | # Represents a C++ lambda expression that produces a local function |
| 1063 | # object. |
| 1064 | # |
| 1065 | # \code |
| 1066 | # void abssort(float *x, unsigned N) { |
| 1067 | # std::sort(x, x + N, |
| 1068 | # [](float a, float b) { |
| 1069 | # return std::abs(a) < std::abs(b); |
| 1070 | # }); |
| 1071 | # } |
| 1072 | # \endcode |
| 1073 | CursorKind.LAMBDA_EXPR = CursorKind(144) |
| 1074 | |
| 1075 | # Objective-c Boolean Literal. |
| 1076 | CursorKind.OBJ_BOOL_LITERAL_EXPR = CursorKind(145) |
| 1077 | |
| 1078 | # Represents the "self" expression in a ObjC method. |
| 1079 | CursorKind.OBJ_SELF_EXPR = CursorKind(146) |
| 1080 | |
| 1081 | # OpenMP 4.0 [2.4, Array Section]. |
| 1082 | CursorKind.OMP_ARRAY_SECTION_EXPR = CursorKind(147) |
| 1083 | |
| 1084 | # Represents an @available(...) check. |
| 1085 | CursorKind.OBJC_AVAILABILITY_CHECK_EXPR = CursorKind(148) |
| 1086 | |
| 1087 | |
| 1088 | # A statement whose specific kind is not exposed via this interface. |
| 1089 | # |
| 1090 | # Unexposed statements have the same operations as any other kind of statement; |
| 1091 | # one can extract their location information, spelling, children, etc. However, |
| 1092 | # the specific kind of the statement is not reported. |
| 1093 | CursorKind.UNEXPOSED_STMT = CursorKind(200) |
| 1094 | |
| 1095 | # A labelled statement in a function. |
| 1096 | CursorKind.LABEL_STMT = CursorKind(201) |
| 1097 | |
| 1098 | # A compound statement |
| 1099 | CursorKind.COMPOUND_STMT = CursorKind(202) |
| 1100 | |
| 1101 | # A case statement. |
| 1102 | CursorKind.CASE_STMT = CursorKind(203) |
| 1103 | |
| 1104 | # A default statement. |
| 1105 | CursorKind.DEFAULT_STMT = CursorKind(204) |
| 1106 | |
| 1107 | # An if statement. |
| 1108 | CursorKind.IF_STMT = CursorKind(205) |
| 1109 | |
| 1110 | # A switch statement. |
| 1111 | CursorKind.SWITCH_STMT = CursorKind(206) |
| 1112 | |
| 1113 | # A while statement. |
| 1114 | CursorKind.WHILE_STMT = CursorKind(207) |
| 1115 | |
| 1116 | # A do statement. |
| 1117 | CursorKind.DO_STMT = CursorKind(208) |
| 1118 | |
| 1119 | # A for statement. |
| 1120 | CursorKind.FOR_STMT = CursorKind(209) |
| 1121 | |
| 1122 | # A goto statement. |
| 1123 | CursorKind.GOTO_STMT = CursorKind(210) |
| 1124 | |
| 1125 | # An indirect goto statement. |
| 1126 | CursorKind.INDIRECT_GOTO_STMT = CursorKind(211) |
| 1127 | |
| 1128 | # A continue statement. |
| 1129 | CursorKind.CONTINUE_STMT = CursorKind(212) |
| 1130 | |
| 1131 | # A break statement. |
| 1132 | CursorKind.BREAK_STMT = CursorKind(213) |
| 1133 | |
| 1134 | # A return statement. |
| 1135 | CursorKind.RETURN_STMT = CursorKind(214) |
| 1136 | |
| 1137 | # A GNU-style inline assembler statement. |
| 1138 | CursorKind.ASM_STMT = CursorKind(215) |
| 1139 | |
| 1140 | # Objective-C's overall @try-@catch-@finally statement. |
| 1141 | CursorKind.OBJC_AT_TRY_STMT = CursorKind(216) |
| 1142 | |
| 1143 | # Objective-C's @catch statement. |
| 1144 | CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217) |
| 1145 | |
| 1146 | # Objective-C's @finally statement. |
| 1147 | CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218) |
| 1148 | |
| 1149 | # Objective-C's @throw statement. |
| 1150 | CursorKind.OBJC_AT_THROW_STMT = CursorKind(219) |
| 1151 | |
| 1152 | # Objective-C's @synchronized statement. |
| 1153 | CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220) |
| 1154 | |
| 1155 | # Objective-C's autorealease pool statement. |
| 1156 | CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221) |
| 1157 | |
| 1158 | # Objective-C's for collection statement. |
| 1159 | CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222) |
| 1160 | |
| 1161 | # C++'s catch statement. |
| 1162 | CursorKind.CXX_CATCH_STMT = CursorKind(223) |
| 1163 | |
| 1164 | # C++'s try statement. |
| 1165 | CursorKind.CXX_TRY_STMT = CursorKind(224) |
| 1166 | |
| 1167 | # C++'s for (* : *) statement. |
| 1168 | CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225) |
| 1169 | |
| 1170 | # Windows Structured Exception Handling's try statement. |
| 1171 | CursorKind.SEH_TRY_STMT = CursorKind(226) |
| 1172 | |
| 1173 | # Windows Structured Exception Handling's except statement. |
| 1174 | CursorKind.SEH_EXCEPT_STMT = CursorKind(227) |
| 1175 | |
| 1176 | # Windows Structured Exception Handling's finally statement. |
| 1177 | CursorKind.SEH_FINALLY_STMT = CursorKind(228) |
| 1178 | |
| 1179 | # A MS inline assembly statement extension. |
| 1180 | CursorKind.MS_ASM_STMT = CursorKind(229) |
| 1181 | |
| 1182 | # The null statement. |
| 1183 | CursorKind.NULL_STMT = CursorKind(230) |
| 1184 | |
| 1185 | # Adaptor class for mixing declarations with statements and expressions. |
| 1186 | CursorKind.DECL_STMT = CursorKind(231) |
| 1187 | |
| 1188 | # OpenMP parallel directive. |
| 1189 | CursorKind.OMP_PARALLEL_DIRECTIVE = CursorKind(232) |
| 1190 | |
| 1191 | # OpenMP SIMD directive. |
| 1192 | CursorKind.OMP_SIMD_DIRECTIVE = CursorKind(233) |
| 1193 | |
| 1194 | # OpenMP for directive. |
| 1195 | CursorKind.OMP_FOR_DIRECTIVE = CursorKind(234) |
| 1196 | |
| 1197 | # OpenMP sections directive. |
| 1198 | CursorKind.OMP_SECTIONS_DIRECTIVE = CursorKind(235) |
| 1199 | |
| 1200 | # OpenMP section directive. |
| 1201 | CursorKind.OMP_SECTION_DIRECTIVE = CursorKind(236) |
| 1202 | |
| 1203 | # OpenMP single directive. |
| 1204 | CursorKind.OMP_SINGLE_DIRECTIVE = CursorKind(237) |
| 1205 | |
| 1206 | # OpenMP parallel for directive. |
| 1207 | CursorKind.OMP_PARALLEL_FOR_DIRECTIVE = CursorKind(238) |
| 1208 | |
| 1209 | # OpenMP parallel sections directive. |
| 1210 | CursorKind.OMP_PARALLEL_SECTIONS_DIRECTIVE = CursorKind(239) |
| 1211 | |
| 1212 | # OpenMP task directive. |
| 1213 | CursorKind.OMP_TASK_DIRECTIVE = CursorKind(240) |
| 1214 | |
| 1215 | # OpenMP master directive. |
| 1216 | CursorKind.OMP_MASTER_DIRECTIVE = CursorKind(241) |
| 1217 | |
| 1218 | # OpenMP critical directive. |
| 1219 | CursorKind.OMP_CRITICAL_DIRECTIVE = CursorKind(242) |
| 1220 | |
| 1221 | # OpenMP taskyield directive. |
| 1222 | CursorKind.OMP_TASKYIELD_DIRECTIVE = CursorKind(243) |
| 1223 | |
| 1224 | # OpenMP barrier directive. |
| 1225 | CursorKind.OMP_BARRIER_DIRECTIVE = CursorKind(244) |
| 1226 | |
| 1227 | # OpenMP taskwait directive. |
| 1228 | CursorKind.OMP_TASKWAIT_DIRECTIVE = CursorKind(245) |
| 1229 | |
| 1230 | # OpenMP flush directive. |
| 1231 | CursorKind.OMP_FLUSH_DIRECTIVE = CursorKind(246) |
| 1232 | |
| 1233 | # Windows Structured Exception Handling's leave statement. |
| 1234 | CursorKind.SEH_LEAVE_STMT = CursorKind(247) |
| 1235 | |
| 1236 | # OpenMP ordered directive. |
| 1237 | CursorKind.OMP_ORDERED_DIRECTIVE = CursorKind(248) |
| 1238 | |
| 1239 | # OpenMP atomic directive. |
| 1240 | CursorKind.OMP_ATOMIC_DIRECTIVE = CursorKind(249) |
| 1241 | |
| 1242 | # OpenMP for SIMD directive. |
| 1243 | CursorKind.OMP_FOR_SIMD_DIRECTIVE = CursorKind(250) |
| 1244 | |
| 1245 | # OpenMP parallel for SIMD directive. |
| 1246 | CursorKind.OMP_PARALLELFORSIMD_DIRECTIVE = CursorKind(251) |
| 1247 | |
| 1248 | # OpenMP target directive. |
| 1249 | CursorKind.OMP_TARGET_DIRECTIVE = CursorKind(252) |
| 1250 | |
| 1251 | # OpenMP teams directive. |
| 1252 | CursorKind.OMP_TEAMS_DIRECTIVE = CursorKind(253) |
| 1253 | |
| 1254 | # OpenMP taskgroup directive. |
| 1255 | CursorKind.OMP_TASKGROUP_DIRECTIVE = CursorKind(254) |
| 1256 | |
| 1257 | # OpenMP cancellation point directive. |
| 1258 | CursorKind.OMP_CANCELLATION_POINT_DIRECTIVE = CursorKind(255) |
| 1259 | |
| 1260 | # OpenMP cancel directive. |
| 1261 | CursorKind.OMP_CANCEL_DIRECTIVE = CursorKind(256) |
| 1262 | |
| 1263 | # OpenMP target data directive. |
| 1264 | CursorKind.OMP_TARGET_DATA_DIRECTIVE = CursorKind(257) |
| 1265 | |
| 1266 | # OpenMP taskloop directive. |
| 1267 | CursorKind.OMP_TASK_LOOP_DIRECTIVE = CursorKind(258) |
| 1268 | |
| 1269 | # OpenMP taskloop simd directive. |
| 1270 | CursorKind.OMP_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(259) |
| 1271 | |
| 1272 | # OpenMP distribute directive. |
| 1273 | CursorKind.OMP_DISTRIBUTE_DIRECTIVE = CursorKind(260) |
| 1274 | |
| 1275 | # OpenMP target enter data directive. |
| 1276 | CursorKind.OMP_TARGET_ENTER_DATA_DIRECTIVE = CursorKind(261) |
| 1277 | |
| 1278 | # OpenMP target exit data directive. |
| 1279 | CursorKind.OMP_TARGET_EXIT_DATA_DIRECTIVE = CursorKind(262) |
| 1280 | |
| 1281 | # OpenMP target parallel directive. |
| 1282 | CursorKind.OMP_TARGET_PARALLEL_DIRECTIVE = CursorKind(263) |
| 1283 | |
| 1284 | # OpenMP target parallel for directive. |
| 1285 | CursorKind.OMP_TARGET_PARALLELFOR_DIRECTIVE = CursorKind(264) |
| 1286 | |
| 1287 | # OpenMP target update directive. |
| 1288 | CursorKind.OMP_TARGET_UPDATE_DIRECTIVE = CursorKind(265) |
| 1289 | |
| 1290 | # OpenMP distribute parallel for directive. |
| 1291 | CursorKind.OMP_DISTRIBUTE_PARALLELFOR_DIRECTIVE = CursorKind(266) |
| 1292 | |
| 1293 | # OpenMP distribute parallel for simd directive. |
| 1294 | CursorKind.OMP_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(267) |
| 1295 | |
| 1296 | # OpenMP distribute simd directive. |
| 1297 | CursorKind.OMP_DISTRIBUTE_SIMD_DIRECTIVE = CursorKind(268) |
| 1298 | |
| 1299 | # OpenMP target parallel for simd directive. |
| 1300 | CursorKind.OMP_TARGET_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(269) |
| 1301 | |
| 1302 | # OpenMP target simd directive. |
| 1303 | CursorKind.OMP_TARGET_SIMD_DIRECTIVE = CursorKind(270) |
| 1304 | |
| 1305 | # OpenMP teams distribute directive. |
| 1306 | CursorKind.OMP_TEAMS_DISTRIBUTE_DIRECTIVE = CursorKind(271) |
| 1307 | |
| 1308 | ### |
| 1309 | # Other Kinds |
| 1310 | |
| 1311 | # Cursor that represents the translation unit itself. |
| 1312 | # |
| 1313 | # The translation unit cursor exists primarily to act as the root cursor for |
| 1314 | # traversing the contents of a translation unit. |
| 1315 | CursorKind.TRANSLATION_UNIT = CursorKind(300) |
| 1316 | |
| 1317 | ### |
| 1318 | # Attributes |
| 1319 | |
| 1320 | # An attribute whoe specific kind is note exposed via this interface |
| 1321 | CursorKind.UNEXPOSED_ATTR = CursorKind(400) |
| 1322 | |
| 1323 | CursorKind.IB_ACTION_ATTR = CursorKind(401) |
| 1324 | CursorKind.IB_OUTLET_ATTR = CursorKind(402) |
| 1325 | CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403) |
| 1326 | |
| 1327 | CursorKind.CXX_FINAL_ATTR = CursorKind(404) |
| 1328 | CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405) |
| 1329 | CursorKind.ANNOTATE_ATTR = CursorKind(406) |
| 1330 | CursorKind.ASM_LABEL_ATTR = CursorKind(407) |
| 1331 | CursorKind.PACKED_ATTR = CursorKind(408) |
| 1332 | CursorKind.PURE_ATTR = CursorKind(409) |
| 1333 | CursorKind.CONST_ATTR = CursorKind(410) |
| 1334 | CursorKind.NODUPLICATE_ATTR = CursorKind(411) |
| 1335 | CursorKind.CUDACONSTANT_ATTR = CursorKind(412) |
| 1336 | CursorKind.CUDADEVICE_ATTR = CursorKind(413) |
| 1337 | CursorKind.CUDAGLOBAL_ATTR = CursorKind(414) |
| 1338 | CursorKind.CUDAHOST_ATTR = CursorKind(415) |
| 1339 | CursorKind.CUDASHARED_ATTR = CursorKind(416) |
| 1340 | |
| 1341 | CursorKind.VISIBILITY_ATTR = CursorKind(417) |
| 1342 | |
| 1343 | CursorKind.DLLEXPORT_ATTR = CursorKind(418) |
| 1344 | CursorKind.DLLIMPORT_ATTR = CursorKind(419) |
| 1345 | CursorKind.CONVERGENT_ATTR = CursorKind(438) |
| 1346 | CursorKind.WARN_UNUSED_ATTR = CursorKind(439) |
| 1347 | CursorKind.WARN_UNUSED_RESULT_ATTR = CursorKind(440) |
| 1348 | CursorKind.ALIGNED_ATTR = CursorKind(441) |
| 1349 | |
| 1350 | ### |
| 1351 | # Preprocessing |
| 1352 | CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500) |
| 1353 | CursorKind.MACRO_DEFINITION = CursorKind(501) |
| 1354 | CursorKind.MACRO_INSTANTIATION = CursorKind(502) |
| 1355 | CursorKind.INCLUSION_DIRECTIVE = CursorKind(503) |
| 1356 | |
| 1357 | ### |
| 1358 | # Extra declaration |
| 1359 | |
| 1360 | # A module import declaration. |
| 1361 | CursorKind.MODULE_IMPORT_DECL = CursorKind(600) |
| 1362 | # A type alias template declaration |
| 1363 | CursorKind.TYPE_ALIAS_TEMPLATE_DECL = CursorKind(601) |
| 1364 | # A static_assert or _Static_assert node |
| 1365 | CursorKind.STATIC_ASSERT = CursorKind(602) |
| 1366 | # A friend declaration |
| 1367 | CursorKind.FRIEND_DECL = CursorKind(603) |
| 1368 | |
| 1369 | # A code completion overload candidate. |
| 1370 | CursorKind.OVERLOAD_CANDIDATE = CursorKind(700) |
| 1371 | |
| 1372 | ### Template Argument Kinds ### |
| 1373 | class TemplateArgumentKind(BaseEnumeration): |
| 1374 | """ |
| 1375 | A TemplateArgumentKind describes the kind of entity that a template argument |
| 1376 | represents. |
| 1377 | """ |
| 1378 | |
| 1379 | # The required BaseEnumeration declarations. |
| 1380 | _kinds = [] |
| 1381 | _name_map = None |
| 1382 | |
| 1383 | TemplateArgumentKind.NULL = TemplateArgumentKind(0) |
| 1384 | TemplateArgumentKind.TYPE = TemplateArgumentKind(1) |
| 1385 | TemplateArgumentKind.DECLARATION = TemplateArgumentKind(2) |
| 1386 | TemplateArgumentKind.NULLPTR = TemplateArgumentKind(3) |
| 1387 | TemplateArgumentKind.INTEGRAL = TemplateArgumentKind(4) |
| 1388 | |
| 1389 | ### Exception Specification Kinds ### |
| 1390 | class ExceptionSpecificationKind(BaseEnumeration): |
| 1391 | """ |
| 1392 | An ExceptionSpecificationKind describes the kind of exception specification |
| 1393 | that a function has. |
| 1394 | """ |
| 1395 | |
| 1396 | # The required BaseEnumeration declarations. |
| 1397 | _kinds = [] |
| 1398 | _name_map = None |
| 1399 | |
| 1400 | def __repr__(self): |
| 1401 | return 'ExceptionSpecificationKind.{}'.format(self.name) |
| 1402 | |
| 1403 | ExceptionSpecificationKind.NONE = ExceptionSpecificationKind(0) |
| 1404 | ExceptionSpecificationKind.DYNAMIC_NONE = ExceptionSpecificationKind(1) |
| 1405 | ExceptionSpecificationKind.DYNAMIC = ExceptionSpecificationKind(2) |
| 1406 | ExceptionSpecificationKind.MS_ANY = ExceptionSpecificationKind(3) |
| 1407 | ExceptionSpecificationKind.BASIC_NOEXCEPT = ExceptionSpecificationKind(4) |
| 1408 | ExceptionSpecificationKind.COMPUTED_NOEXCEPT = ExceptionSpecificationKind(5) |
| 1409 | ExceptionSpecificationKind.UNEVALUATED = ExceptionSpecificationKind(6) |
| 1410 | ExceptionSpecificationKind.UNINSTANTIATED = ExceptionSpecificationKind(7) |
| 1411 | ExceptionSpecificationKind.UNPARSED = ExceptionSpecificationKind(8) |
| 1412 | |
| 1413 | ### Cursors ### |
| 1414 | |
| 1415 | class Cursor(Structure): |
| 1416 | """ |
| 1417 | The Cursor class represents a reference to an element within the AST. It |
| 1418 | acts as a kind of iterator. |
| 1419 | """ |
| 1420 | _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)] |
| 1421 | |
| 1422 | @staticmethod |
| 1423 | def from_location(tu, location): |
| 1424 | # We store a reference to the TU in the instance so the TU won't get |
| 1425 | # collected before the cursor. |
| 1426 | cursor = conf.lib.clang_getCursor(tu, location) |
| 1427 | cursor._tu = tu |
| 1428 | |
| 1429 | return cursor |
| 1430 | |
| 1431 | def __eq__(self, other): |
| 1432 | return conf.lib.clang_equalCursors(self, other) |
| 1433 | |
| 1434 | def __ne__(self, other): |
| 1435 | return not self.__eq__(other) |
| 1436 | |
| 1437 | def is_definition(self): |
| 1438 | """ |
| 1439 | Returns true if the declaration pointed at by the cursor is also a |
| 1440 | definition of that entity. |
| 1441 | """ |
| 1442 | return conf.lib.clang_isCursorDefinition(self) |
| 1443 | |
| 1444 | def is_const_method(self): |
| 1445 | """Returns True if the cursor refers to a C++ member function or member |
| 1446 | function template that is declared 'const'. |
| 1447 | """ |
| 1448 | return conf.lib.clang_CXXMethod_isConst(self) |
| 1449 | |
| 1450 | def is_converting_constructor(self): |
| 1451 | """Returns True if the cursor refers to a C++ converting constructor. |
| 1452 | """ |
| 1453 | return conf.lib.clang_CXXConstructor_isConvertingConstructor(self) |
| 1454 | |
| 1455 | def is_copy_constructor(self): |
| 1456 | """Returns True if the cursor refers to a C++ copy constructor. |
| 1457 | """ |
| 1458 | return conf.lib.clang_CXXConstructor_isCopyConstructor(self) |
| 1459 | |
| 1460 | def is_default_constructor(self): |
| 1461 | """Returns True if the cursor refers to a C++ default constructor. |
| 1462 | """ |
| 1463 | return conf.lib.clang_CXXConstructor_isDefaultConstructor(self) |
| 1464 | |
| 1465 | def is_move_constructor(self): |
| 1466 | """Returns True if the cursor refers to a C++ move constructor. |
| 1467 | """ |
| 1468 | return conf.lib.clang_CXXConstructor_isMoveConstructor(self) |
| 1469 | |
| 1470 | def is_default_method(self): |
| 1471 | """Returns True if the cursor refers to a C++ member function or member |
| 1472 | function template that is declared '= default'. |
| 1473 | """ |
| 1474 | return conf.lib.clang_CXXMethod_isDefaulted(self) |
| 1475 | |
| 1476 | def is_mutable_field(self): |
| 1477 | """Returns True if the cursor refers to a C++ field that is declared |
| 1478 | 'mutable'. |
| 1479 | """ |
| 1480 | return conf.lib.clang_CXXField_isMutable(self) |
| 1481 | |
| 1482 | def is_pure_virtual_method(self): |
| 1483 | """Returns True if the cursor refers to a C++ member function or member |
| 1484 | function template that is declared pure virtual. |
| 1485 | """ |
| 1486 | return conf.lib.clang_CXXMethod_isPureVirtual(self) |
| 1487 | |
| 1488 | def is_static_method(self): |
| 1489 | """Returns True if the cursor refers to a C++ member function or member |
| 1490 | function template that is declared 'static'. |
| 1491 | """ |
| 1492 | return conf.lib.clang_CXXMethod_isStatic(self) |
| 1493 | |
| 1494 | def is_virtual_method(self): |
| 1495 | """Returns True if the cursor refers to a C++ member function or member |
| 1496 | function template that is declared 'virtual'. |
| 1497 | """ |
| 1498 | return conf.lib.clang_CXXMethod_isVirtual(self) |
| 1499 | |
| 1500 | def is_abstract_record(self): |
| 1501 | """Returns True if the cursor refers to a C++ record declaration |
| 1502 | that has pure virtual member functions. |
| 1503 | """ |
| 1504 | return conf.lib.clang_CXXRecord_isAbstract(self) |
| 1505 | |
| 1506 | def is_scoped_enum(self): |
| 1507 | """Returns True if the cursor refers to a scoped enum declaration. |
| 1508 | """ |
| 1509 | return conf.lib.clang_EnumDecl_isScoped(self) |
| 1510 | |
| 1511 | def get_definition(self): |
| 1512 | """ |
| 1513 | If the cursor is a reference to a declaration or a declaration of |
| 1514 | some entity, return a cursor that points to the definition of that |
| 1515 | entity. |
| 1516 | """ |
| 1517 | # TODO: Should probably check that this is either a reference or |
| 1518 | # declaration prior to issuing the lookup. |
| 1519 | return conf.lib.clang_getCursorDefinition(self) |
| 1520 | |
| 1521 | def get_usr(self): |
| 1522 | """Return the Unified Symbol Resolution (USR) for the entity referenced |
| 1523 | by the given cursor (or None). |
| 1524 | |
| 1525 | A Unified Symbol Resolution (USR) is a string that identifies a |
| 1526 | particular entity (function, class, variable, etc.) within a |
| 1527 | program. USRs can be compared across translation units to determine, |
| 1528 | e.g., when references in one translation refer to an entity defined in |
| 1529 | another translation unit.""" |
| 1530 | return conf.lib.clang_getCursorUSR(self) |
| 1531 | |
| 1532 | def get_included_file(self): |
| 1533 | """Returns the File that is included by the current inclusion cursor.""" |
| 1534 | assert self.kind == CursorKind.INCLUSION_DIRECTIVE |
| 1535 | |
| 1536 | return conf.lib.clang_getIncludedFile(self) |
| 1537 | |
| 1538 | @property |
| 1539 | def kind(self): |
| 1540 | """Return the kind of this cursor.""" |
| 1541 | return CursorKind.from_id(self._kind_id) |
| 1542 | |
| 1543 | @property |
| 1544 | def spelling(self): |
| 1545 | """Return the spelling of the entity pointed at by the cursor.""" |
| 1546 | if not hasattr(self, '_spelling'): |
| 1547 | self._spelling = conf.lib.clang_getCursorSpelling(self) |
| 1548 | |
| 1549 | return self._spelling |
| 1550 | |
| 1551 | @property |
| 1552 | def displayname(self): |
| 1553 | """ |
| 1554 | Return the display name for the entity referenced by this cursor. |
| 1555 | |
| 1556 | The display name contains extra information that helps identify the |
| 1557 | cursor, such as the parameters of a function or template or the |
| 1558 | arguments of a class template specialization. |
| 1559 | """ |
| 1560 | if not hasattr(self, '_displayname'): |
| 1561 | self._displayname = conf.lib.clang_getCursorDisplayName(self) |
| 1562 | |
| 1563 | return self._displayname |
| 1564 | |
| 1565 | @property |
| 1566 | def mangled_name(self): |
| 1567 | """Return the mangled name for the entity referenced by this cursor.""" |
| 1568 | if not hasattr(self, '_mangled_name'): |
| 1569 | self._mangled_name = conf.lib.clang_Cursor_getMangling(self) |
| 1570 | |
| 1571 | return self._mangled_name |
| 1572 | |
| 1573 | @property |
| 1574 | def location(self): |
| 1575 | """ |
| 1576 | Return the source location (the starting character) of the entity |
| 1577 | pointed at by the cursor. |
| 1578 | """ |
| 1579 | if not hasattr(self, '_loc'): |
| 1580 | self._loc = conf.lib.clang_getCursorLocation(self) |
| 1581 | |
| 1582 | return self._loc |
| 1583 | |
| 1584 | @property |
| 1585 | def linkage(self): |
| 1586 | """Return the linkage of this cursor.""" |
| 1587 | if not hasattr(self, '_linkage'): |
| 1588 | self._linkage = conf.lib.clang_getCursorLinkage(self) |
| 1589 | |
| 1590 | return LinkageKind.from_id(self._linkage) |
| 1591 | |
| 1592 | @property |
| 1593 | def tls_kind(self): |
| 1594 | """Return the thread-local storage (TLS) kind of this cursor.""" |
| 1595 | if not hasattr(self, '_tls_kind'): |
| 1596 | self._tls_kind = conf.lib.clang_getCursorTLSKind(self) |
| 1597 | |
| 1598 | return TLSKind.from_id(self._tls_kind) |
| 1599 | |
| 1600 | @property |
| 1601 | def extent(self): |
| 1602 | """ |
| 1603 | Return the source range (the range of text) occupied by the entity |
| 1604 | pointed at by the cursor. |
| 1605 | """ |
| 1606 | if not hasattr(self, '_extent'): |
| 1607 | self._extent = conf.lib.clang_getCursorExtent(self) |
| 1608 | |
| 1609 | return self._extent |
| 1610 | |
| 1611 | @property |
| 1612 | def storage_class(self): |
| 1613 | """ |
| 1614 | Retrieves the storage class (if any) of the entity pointed at by the |
| 1615 | cursor. |
| 1616 | """ |
| 1617 | if not hasattr(self, '_storage_class'): |
| 1618 | self._storage_class = conf.lib.clang_Cursor_getStorageClass(self) |
| 1619 | |
| 1620 | return StorageClass.from_id(self._storage_class) |
| 1621 | |
| 1622 | @property |
| 1623 | def availability(self): |
| 1624 | """ |
| 1625 | Retrieves the availability of the entity pointed at by the cursor. |
| 1626 | """ |
| 1627 | if not hasattr(self, '_availability'): |
| 1628 | self._availability = conf.lib.clang_getCursorAvailability(self) |
| 1629 | |
| 1630 | return AvailabilityKind.from_id(self._availability) |
| 1631 | |
| 1632 | @property |
| 1633 | def access_specifier(self): |
| 1634 | """ |
| 1635 | Retrieves the access specifier (if any) of the entity pointed at by the |
| 1636 | cursor. |
| 1637 | """ |
| 1638 | if not hasattr(self, '_access_specifier'): |
| 1639 | self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self) |
| 1640 | |
| 1641 | return AccessSpecifier.from_id(self._access_specifier) |
| 1642 | |
| 1643 | @property |
| 1644 | def type(self): |
| 1645 | """ |
| 1646 | Retrieve the Type (if any) of the entity pointed at by the cursor. |
| 1647 | """ |
| 1648 | if not hasattr(self, '_type'): |
| 1649 | self._type = conf.lib.clang_getCursorType(self) |
| 1650 | |
| 1651 | return self._type |
| 1652 | |
| 1653 | @property |
| 1654 | def canonical(self): |
| 1655 | """Return the canonical Cursor corresponding to this Cursor. |
| 1656 | |
| 1657 | The canonical cursor is the cursor which is representative for the |
| 1658 | underlying entity. For example, if you have multiple forward |
| 1659 | declarations for the same class, the canonical cursor for the forward |
| 1660 | declarations will be identical. |
| 1661 | """ |
| 1662 | if not hasattr(self, '_canonical'): |
| 1663 | self._canonical = conf.lib.clang_getCanonicalCursor(self) |
| 1664 | |
| 1665 | return self._canonical |
| 1666 | |
| 1667 | @property |
| 1668 | def result_type(self): |
| 1669 | """Retrieve the Type of the result for this Cursor.""" |
| 1670 | if not hasattr(self, '_result_type'): |
| 1671 | self._result_type = conf.lib.clang_getCursorResultType(self) |
| 1672 | |
| 1673 | return self._result_type |
| 1674 | |
| 1675 | @property |
| 1676 | def exception_specification_kind(self): |
| 1677 | ''' |
| 1678 | Retrieve the exception specification kind, which is one of the values |
| 1679 | from the ExceptionSpecificationKind enumeration. |
| 1680 | ''' |
| 1681 | if not hasattr(self, '_exception_specification_kind'): |
| 1682 | exc_kind = conf.lib.clang_getCursorExceptionSpecificationType(self) |
| 1683 | self._exception_specification_kind = ExceptionSpecificationKind.from_id(exc_kind) |
| 1684 | |
| 1685 | return self._exception_specification_kind |
| 1686 | |
| 1687 | @property |
| 1688 | def underlying_typedef_type(self): |
| 1689 | """Return the underlying type of a typedef declaration. |
| 1690 | |
| 1691 | Returns a Type for the typedef this cursor is a declaration for. If |
| 1692 | the current cursor is not a typedef, this raises. |
| 1693 | """ |
| 1694 | if not hasattr(self, '_underlying_type'): |
| 1695 | assert self.kind.is_declaration() |
| 1696 | self._underlying_type = \ |
| 1697 | conf.lib.clang_getTypedefDeclUnderlyingType(self) |
| 1698 | |
| 1699 | return self._underlying_type |
| 1700 | |
| 1701 | @property |
| 1702 | def enum_type(self): |
| 1703 | """Return the integer type of an enum declaration. |
| 1704 | |
| 1705 | Returns a Type corresponding to an integer. If the cursor is not for an |
| 1706 | enum, this raises. |
| 1707 | """ |
| 1708 | if not hasattr(self, '_enum_type'): |
| 1709 | assert self.kind == CursorKind.ENUM_DECL |
| 1710 | self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self) |
| 1711 | |
| 1712 | return self._enum_type |
| 1713 | |
| 1714 | @property |
| 1715 | def enum_value(self): |
| 1716 | """Return the value of an enum constant.""" |
| 1717 | if not hasattr(self, '_enum_value'): |
| 1718 | assert self.kind == CursorKind.ENUM_CONSTANT_DECL |
| 1719 | # Figure out the underlying type of the enum to know if it |
| 1720 | # is a signed or unsigned quantity. |
| 1721 | underlying_type = self.type |
| 1722 | if underlying_type.kind == TypeKind.ENUM: |
| 1723 | underlying_type = underlying_type.get_declaration().enum_type |
| 1724 | if underlying_type.kind in (TypeKind.CHAR_U, |
| 1725 | TypeKind.UCHAR, |
| 1726 | TypeKind.CHAR16, |
| 1727 | TypeKind.CHAR32, |
| 1728 | TypeKind.USHORT, |
| 1729 | TypeKind.UINT, |
| 1730 | TypeKind.ULONG, |
| 1731 | TypeKind.ULONGLONG, |
| 1732 | TypeKind.UINT128): |
| 1733 | self._enum_value = \ |
| 1734 | conf.lib.clang_getEnumConstantDeclUnsignedValue(self) |
| 1735 | else: |
| 1736 | self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self) |
| 1737 | return self._enum_value |
| 1738 | |
| 1739 | @property |
| 1740 | def objc_type_encoding(self): |
| 1741 | """Return the Objective-C type encoding as a str.""" |
| 1742 | if not hasattr(self, '_objc_type_encoding'): |
| 1743 | self._objc_type_encoding = \ |
| 1744 | conf.lib.clang_getDeclObjCTypeEncoding(self) |
| 1745 | |
| 1746 | return self._objc_type_encoding |
| 1747 | |
| 1748 | @property |
| 1749 | def hash(self): |
| 1750 | """Returns a hash of the cursor as an int.""" |
| 1751 | if not hasattr(self, '_hash'): |
| 1752 | self._hash = conf.lib.clang_hashCursor(self) |
| 1753 | |
| 1754 | return self._hash |
| 1755 | |
| 1756 | @property |
| 1757 | def semantic_parent(self): |
| 1758 | """Return the semantic parent for this cursor.""" |
| 1759 | if not hasattr(self, '_semantic_parent'): |
| 1760 | self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self) |
| 1761 | |
| 1762 | return self._semantic_parent |
| 1763 | |
| 1764 | @property |
| 1765 | def lexical_parent(self): |
| 1766 | """Return the lexical parent for this cursor.""" |
| 1767 | if not hasattr(self, '_lexical_parent'): |
| 1768 | self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self) |
| 1769 | |
| 1770 | return self._lexical_parent |
| 1771 | |
| 1772 | @property |
| 1773 | def translation_unit(self): |
| 1774 | """Returns the TranslationUnit to which this Cursor belongs.""" |
| 1775 | # If this triggers an AttributeError, the instance was not properly |
| 1776 | # created. |
| 1777 | return self._tu |
| 1778 | |
| 1779 | @property |
| 1780 | def referenced(self): |
| 1781 | """ |
| 1782 | For a cursor that is a reference, returns a cursor |
| 1783 | representing the entity that it references. |
| 1784 | """ |
| 1785 | if not hasattr(self, '_referenced'): |
| 1786 | self._referenced = conf.lib.clang_getCursorReferenced(self) |
| 1787 | |
| 1788 | return self._referenced |
| 1789 | |
| 1790 | @property |
| 1791 | def brief_comment(self): |
| 1792 | """Returns the brief comment text associated with that Cursor""" |
| 1793 | return conf.lib.clang_Cursor_getBriefCommentText(self) |
| 1794 | |
| 1795 | @property |
| 1796 | def raw_comment(self): |
| 1797 | """Returns the raw comment text associated with that Cursor""" |
| 1798 | return conf.lib.clang_Cursor_getRawCommentText(self) |
| 1799 | |
| 1800 | def get_arguments(self): |
| 1801 | """Return an iterator for accessing the arguments of this cursor.""" |
| 1802 | num_args = conf.lib.clang_Cursor_getNumArguments(self) |
| 1803 | for i in range(0, num_args): |
| 1804 | yield conf.lib.clang_Cursor_getArgument(self, i) |
| 1805 | |
| 1806 | def get_num_template_arguments(self): |
| 1807 | """Returns the number of template args associated with this cursor.""" |
| 1808 | return conf.lib.clang_Cursor_getNumTemplateArguments(self) |
| 1809 | |
| 1810 | def get_template_argument_kind(self, num): |
| 1811 | """Returns the TemplateArgumentKind for the indicated template |
| 1812 | argument.""" |
| 1813 | return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num) |
| 1814 | |
| 1815 | def get_template_argument_type(self, num): |
| 1816 | """Returns the CXType for the indicated template argument.""" |
| 1817 | return conf.lib.clang_Cursor_getTemplateArgumentType(self, num) |
| 1818 | |
| 1819 | def get_template_argument_value(self, num): |
| 1820 | """Returns the value of the indicated arg as a signed 64b integer.""" |
| 1821 | return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num) |
| 1822 | |
| 1823 | def get_template_argument_unsigned_value(self, num): |
| 1824 | """Returns the value of the indicated arg as an unsigned 64b integer.""" |
| 1825 | return conf.lib.clang_Cursor_getTemplateArgumentUnsignedValue(self, num) |
| 1826 | |
| 1827 | def get_children(self): |
| 1828 | """Return an iterator for accessing the children of this cursor.""" |
| 1829 | |
| 1830 | # FIXME: Expose iteration from CIndex, PR6125. |
| 1831 | def visitor(child, parent, children): |
| 1832 | # FIXME: Document this assertion in API. |
| 1833 | # FIXME: There should just be an isNull method. |
| 1834 | assert child != conf.lib.clang_getNullCursor() |
| 1835 | |
| 1836 | # Create reference to TU so it isn't GC'd before Cursor. |
| 1837 | child._tu = self._tu |
| 1838 | children.append(child) |
| 1839 | return 1 # continue |
| 1840 | children = [] |
| 1841 | conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor), |
| 1842 | children) |
| 1843 | return iter(children) |
| 1844 | |
| 1845 | def walk_preorder(self): |
| 1846 | """Depth-first preorder walk over the cursor and its descendants. |
| 1847 | |
| 1848 | Yields cursors. |
| 1849 | """ |
| 1850 | yield self |
| 1851 | for child in self.get_children(): |
| 1852 | for descendant in child.walk_preorder(): |
| 1853 | yield descendant |
| 1854 | |
| 1855 | def get_tokens(self): |
| 1856 | """Obtain Token instances formulating that compose this Cursor. |
| 1857 | |
| 1858 | This is a generator for Token instances. It returns all tokens which |
| 1859 | occupy the extent this cursor occupies. |
| 1860 | """ |
| 1861 | return TokenGroup.get_tokens(self._tu, self.extent) |
| 1862 | |
| 1863 | def get_field_offsetof(self): |
| 1864 | """Returns the offsetof the FIELD_DECL pointed by this Cursor.""" |
| 1865 | return conf.lib.clang_Cursor_getOffsetOfField(self) |
| 1866 | |
| 1867 | def is_anonymous(self): |
| 1868 | """ |
| 1869 | Check if the record is anonymous. |
| 1870 | """ |
| 1871 | if self.kind == CursorKind.FIELD_DECL: |
| 1872 | return self.type.get_declaration().is_anonymous() |
| 1873 | return conf.lib.clang_Cursor_isAnonymous(self) |
| 1874 | |
| 1875 | def is_bitfield(self): |
| 1876 | """ |
| 1877 | Check if the field is a bitfield. |
| 1878 | """ |
| 1879 | return conf.lib.clang_Cursor_isBitField(self) |
| 1880 | |
| 1881 | def get_bitfield_width(self): |
| 1882 | """ |
| 1883 | Retrieve the width of a bitfield. |
| 1884 | """ |
| 1885 | return conf.lib.clang_getFieldDeclBitWidth(self) |
| 1886 | |
| 1887 | @staticmethod |
| 1888 | def from_result(res, fn, args): |
| 1889 | assert isinstance(res, Cursor) |
| 1890 | # FIXME: There should just be an isNull method. |
| 1891 | if res == conf.lib.clang_getNullCursor(): |
| 1892 | return None |
| 1893 | |
| 1894 | # Store a reference to the TU in the Python object so it won't get GC'd |
| 1895 | # before the Cursor. |
| 1896 | tu = None |
| 1897 | for arg in args: |
| 1898 | if isinstance(arg, TranslationUnit): |
| 1899 | tu = arg |
| 1900 | break |
| 1901 | |
| 1902 | if hasattr(arg, 'translation_unit'): |
| 1903 | tu = arg.translation_unit |
| 1904 | break |
| 1905 | |
| 1906 | assert tu is not None |
| 1907 | |
| 1908 | res._tu = tu |
| 1909 | return res |
| 1910 | |
| 1911 | @staticmethod |
| 1912 | def from_cursor_result(res, fn, args): |
| 1913 | assert isinstance(res, Cursor) |
| 1914 | if res == conf.lib.clang_getNullCursor(): |
| 1915 | return None |
| 1916 | |
| 1917 | res._tu = args[0]._tu |
| 1918 | return res |
| 1919 | |
| 1920 | class StorageClass(object): |
| 1921 | """ |
| 1922 | Describes the storage class of a declaration |
| 1923 | """ |
| 1924 | |
| 1925 | # The unique kind objects, index by id. |
| 1926 | _kinds = [] |
| 1927 | _name_map = None |
| 1928 | |
| 1929 | def __init__(self, value): |
| 1930 | if value >= len(StorageClass._kinds): |
| 1931 | StorageClass._kinds += [None] * (value - len(StorageClass._kinds) + 1) |
| 1932 | if StorageClass._kinds[value] is not None: |
| 1933 | raise ValueError('StorageClass already loaded') |
| 1934 | self.value = value |
| 1935 | StorageClass._kinds[value] = self |
| 1936 | StorageClass._name_map = None |
| 1937 | |
| 1938 | def from_param(self): |
| 1939 | return self.value |
| 1940 | |
| 1941 | @property |
| 1942 | def name(self): |
| 1943 | """Get the enumeration name of this storage class.""" |
| 1944 | if self._name_map is None: |
| 1945 | self._name_map = {} |
| 1946 | for key,value in StorageClass.__dict__.items(): |
| 1947 | if isinstance(value,StorageClass): |
| 1948 | self._name_map[value] = key |
| 1949 | return self._name_map[self] |
| 1950 | |
| 1951 | @staticmethod |
| 1952 | def from_id(id): |
| 1953 | if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]: |
| 1954 | raise ValueError('Unknown storage class %d' % id) |
| 1955 | return StorageClass._kinds[id] |
| 1956 | |
| 1957 | def __repr__(self): |
| 1958 | return 'StorageClass.%s' % (self.name,) |
| 1959 | |
| 1960 | StorageClass.INVALID = StorageClass(0) |
| 1961 | StorageClass.NONE = StorageClass(1) |
| 1962 | StorageClass.EXTERN = StorageClass(2) |
| 1963 | StorageClass.STATIC = StorageClass(3) |
| 1964 | StorageClass.PRIVATEEXTERN = StorageClass(4) |
| 1965 | StorageClass.OPENCLWORKGROUPLOCAL = StorageClass(5) |
| 1966 | StorageClass.AUTO = StorageClass(6) |
| 1967 | StorageClass.REGISTER = StorageClass(7) |
| 1968 | |
| 1969 | ### Availability Kinds ### |
| 1970 | |
| 1971 | class AvailabilityKind(BaseEnumeration): |
| 1972 | """ |
| 1973 | Describes the availability of an entity. |
| 1974 | """ |
| 1975 | |
| 1976 | # The unique kind objects, indexed by id. |
| 1977 | _kinds = [] |
| 1978 | _name_map = None |
| 1979 | |
| 1980 | def __repr__(self): |
| 1981 | return 'AvailabilityKind.%s' % (self.name,) |
| 1982 | |
| 1983 | AvailabilityKind.AVAILABLE = AvailabilityKind(0) |
| 1984 | AvailabilityKind.DEPRECATED = AvailabilityKind(1) |
| 1985 | AvailabilityKind.NOT_AVAILABLE = AvailabilityKind(2) |
| 1986 | AvailabilityKind.NOT_ACCESSIBLE = AvailabilityKind(3) |
| 1987 | |
| 1988 | ### C++ access specifiers ### |
| 1989 | |
| 1990 | class AccessSpecifier(BaseEnumeration): |
| 1991 | """ |
| 1992 | Describes the access of a C++ class member |
| 1993 | """ |
| 1994 | |
| 1995 | # The unique kind objects, index by id. |
| 1996 | _kinds = [] |
| 1997 | _name_map = None |
| 1998 | |
| 1999 | def from_param(self): |
| 2000 | return self.value |
| 2001 | |
| 2002 | def __repr__(self): |
| 2003 | return 'AccessSpecifier.%s' % (self.name,) |
| 2004 | |
| 2005 | AccessSpecifier.INVALID = AccessSpecifier(0) |
| 2006 | AccessSpecifier.PUBLIC = AccessSpecifier(1) |
| 2007 | AccessSpecifier.PROTECTED = AccessSpecifier(2) |
| 2008 | AccessSpecifier.PRIVATE = AccessSpecifier(3) |
| 2009 | AccessSpecifier.NONE = AccessSpecifier(4) |
| 2010 | |
| 2011 | ### Type Kinds ### |
| 2012 | |
| 2013 | class TypeKind(BaseEnumeration): |
| 2014 | """ |
| 2015 | Describes the kind of type. |
| 2016 | """ |
| 2017 | |
| 2018 | # The unique kind objects, indexed by id. |
| 2019 | _kinds = [] |
| 2020 | _name_map = None |
| 2021 | |
| 2022 | @property |
| 2023 | def spelling(self): |
| 2024 | """Retrieve the spelling of this TypeKind.""" |
| 2025 | return conf.lib.clang_getTypeKindSpelling(self.value) |
| 2026 | |
| 2027 | def __repr__(self): |
| 2028 | return 'TypeKind.%s' % (self.name,) |
| 2029 | |
| 2030 | TypeKind.INVALID = TypeKind(0) |
| 2031 | TypeKind.UNEXPOSED = TypeKind(1) |
| 2032 | TypeKind.VOID = TypeKind(2) |
| 2033 | TypeKind.BOOL = TypeKind(3) |
| 2034 | TypeKind.CHAR_U = TypeKind(4) |
| 2035 | TypeKind.UCHAR = TypeKind(5) |
| 2036 | TypeKind.CHAR16 = TypeKind(6) |
| 2037 | TypeKind.CHAR32 = TypeKind(7) |
| 2038 | TypeKind.USHORT = TypeKind(8) |
| 2039 | TypeKind.UINT = TypeKind(9) |
| 2040 | TypeKind.ULONG = TypeKind(10) |
| 2041 | TypeKind.ULONGLONG = TypeKind(11) |
| 2042 | TypeKind.UINT128 = TypeKind(12) |
| 2043 | TypeKind.CHAR_S = TypeKind(13) |
| 2044 | TypeKind.SCHAR = TypeKind(14) |
| 2045 | TypeKind.WCHAR = TypeKind(15) |
| 2046 | TypeKind.SHORT = TypeKind(16) |
| 2047 | TypeKind.INT = TypeKind(17) |
| 2048 | TypeKind.LONG = TypeKind(18) |
| 2049 | TypeKind.LONGLONG = TypeKind(19) |
| 2050 | TypeKind.INT128 = TypeKind(20) |
| 2051 | TypeKind.FLOAT = TypeKind(21) |
| 2052 | TypeKind.DOUBLE = TypeKind(22) |
| 2053 | TypeKind.LONGDOUBLE = TypeKind(23) |
| 2054 | TypeKind.NULLPTR = TypeKind(24) |
| 2055 | TypeKind.OVERLOAD = TypeKind(25) |
| 2056 | TypeKind.DEPENDENT = TypeKind(26) |
| 2057 | TypeKind.OBJCID = TypeKind(27) |
| 2058 | TypeKind.OBJCCLASS = TypeKind(28) |
| 2059 | TypeKind.OBJCSEL = TypeKind(29) |
| 2060 | TypeKind.FLOAT128 = TypeKind(30) |
| 2061 | TypeKind.HALF = TypeKind(31) |
| 2062 | TypeKind.COMPLEX = TypeKind(100) |
| 2063 | TypeKind.POINTER = TypeKind(101) |
| 2064 | TypeKind.BLOCKPOINTER = TypeKind(102) |
| 2065 | TypeKind.LVALUEREFERENCE = TypeKind(103) |
| 2066 | TypeKind.RVALUEREFERENCE = TypeKind(104) |
| 2067 | TypeKind.RECORD = TypeKind(105) |
| 2068 | TypeKind.ENUM = TypeKind(106) |
| 2069 | TypeKind.TYPEDEF = TypeKind(107) |
| 2070 | TypeKind.OBJCINTERFACE = TypeKind(108) |
| 2071 | TypeKind.OBJCOBJECTPOINTER = TypeKind(109) |
| 2072 | TypeKind.FUNCTIONNOPROTO = TypeKind(110) |
| 2073 | TypeKind.FUNCTIONPROTO = TypeKind(111) |
| 2074 | TypeKind.CONSTANTARRAY = TypeKind(112) |
| 2075 | TypeKind.VECTOR = TypeKind(113) |
| 2076 | TypeKind.INCOMPLETEARRAY = TypeKind(114) |
| 2077 | TypeKind.VARIABLEARRAY = TypeKind(115) |
| 2078 | TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116) |
| 2079 | TypeKind.MEMBERPOINTER = TypeKind(117) |
| 2080 | TypeKind.AUTO = TypeKind(118) |
| 2081 | TypeKind.ELABORATED = TypeKind(119) |
| 2082 | TypeKind.PIPE = TypeKind(120) |
| 2083 | TypeKind.OCLIMAGE1DRO = TypeKind(121) |
| 2084 | TypeKind.OCLIMAGE1DARRAYRO = TypeKind(122) |
| 2085 | TypeKind.OCLIMAGE1DBUFFERRO = TypeKind(123) |
| 2086 | TypeKind.OCLIMAGE2DRO = TypeKind(124) |
| 2087 | TypeKind.OCLIMAGE2DARRAYRO = TypeKind(125) |
| 2088 | TypeKind.OCLIMAGE2DDEPTHRO = TypeKind(126) |
| 2089 | TypeKind.OCLIMAGE2DARRAYDEPTHRO = TypeKind(127) |
| 2090 | TypeKind.OCLIMAGE2DMSAARO = TypeKind(128) |
| 2091 | TypeKind.OCLIMAGE2DARRAYMSAARO = TypeKind(129) |
| 2092 | TypeKind.OCLIMAGE2DMSAADEPTHRO = TypeKind(130) |
| 2093 | TypeKind.OCLIMAGE2DARRAYMSAADEPTHRO = TypeKind(131) |
| 2094 | TypeKind.OCLIMAGE3DRO = TypeKind(132) |
| 2095 | TypeKind.OCLIMAGE1DWO = TypeKind(133) |
| 2096 | TypeKind.OCLIMAGE1DARRAYWO = TypeKind(134) |
| 2097 | TypeKind.OCLIMAGE1DBUFFERWO = TypeKind(135) |
| 2098 | TypeKind.OCLIMAGE2DWO = TypeKind(136) |
| 2099 | TypeKind.OCLIMAGE2DARRAYWO = TypeKind(137) |
| 2100 | TypeKind.OCLIMAGE2DDEPTHWO = TypeKind(138) |
| 2101 | TypeKind.OCLIMAGE2DARRAYDEPTHWO = TypeKind(139) |
| 2102 | TypeKind.OCLIMAGE2DMSAAWO = TypeKind(140) |
| 2103 | TypeKind.OCLIMAGE2DARRAYMSAAWO = TypeKind(141) |
| 2104 | TypeKind.OCLIMAGE2DMSAADEPTHWO = TypeKind(142) |
| 2105 | TypeKind.OCLIMAGE2DARRAYMSAADEPTHWO = TypeKind(143) |
| 2106 | TypeKind.OCLIMAGE3DWO = TypeKind(144) |
| 2107 | TypeKind.OCLIMAGE1DRW = TypeKind(145) |
| 2108 | TypeKind.OCLIMAGE1DARRAYRW = TypeKind(146) |
| 2109 | TypeKind.OCLIMAGE1DBUFFERRW = TypeKind(147) |
| 2110 | TypeKind.OCLIMAGE2DRW = TypeKind(148) |
| 2111 | TypeKind.OCLIMAGE2DARRAYRW = TypeKind(149) |
| 2112 | TypeKind.OCLIMAGE2DDEPTHRW = TypeKind(150) |
| 2113 | TypeKind.OCLIMAGE2DARRAYDEPTHRW = TypeKind(151) |
| 2114 | TypeKind.OCLIMAGE2DMSAARW = TypeKind(152) |
| 2115 | TypeKind.OCLIMAGE2DARRAYMSAARW = TypeKind(153) |
| 2116 | TypeKind.OCLIMAGE2DMSAADEPTHRW = TypeKind(154) |
| 2117 | TypeKind.OCLIMAGE2DARRAYMSAADEPTHRW = TypeKind(155) |
| 2118 | TypeKind.OCLIMAGE3DRW = TypeKind(156) |
| 2119 | TypeKind.OCLSAMPLER = TypeKind(157) |
| 2120 | TypeKind.OCLEVENT = TypeKind(158) |
| 2121 | TypeKind.OCLQUEUE = TypeKind(159) |
| 2122 | TypeKind.OCLRESERVEID = TypeKind(160) |
| 2123 | |
| 2124 | class RefQualifierKind(BaseEnumeration): |
| 2125 | """Describes a specific ref-qualifier of a type.""" |
| 2126 | |
| 2127 | # The unique kind objects, indexed by id. |
| 2128 | _kinds = [] |
| 2129 | _name_map = None |
| 2130 | |
| 2131 | def from_param(self): |
| 2132 | return self.value |
| 2133 | |
| 2134 | def __repr__(self): |
| 2135 | return 'RefQualifierKind.%s' % (self.name,) |
| 2136 | |
| 2137 | RefQualifierKind.NONE = RefQualifierKind(0) |
| 2138 | RefQualifierKind.LVALUE = RefQualifierKind(1) |
| 2139 | RefQualifierKind.RVALUE = RefQualifierKind(2) |
| 2140 | |
| 2141 | class LinkageKind(BaseEnumeration): |
| 2142 | """Describes the kind of linkage of a cursor.""" |
| 2143 | |
| 2144 | # The unique kind objects, indexed by id. |
| 2145 | _kinds = [] |
| 2146 | _name_map = None |
| 2147 | |
| 2148 | def from_param(self): |
| 2149 | return self.value |
| 2150 | |
| 2151 | def __repr__(self): |
| 2152 | return 'LinkageKind.%s' % (self.name,) |
| 2153 | |
| 2154 | LinkageKind.INVALID = LinkageKind(0) |
| 2155 | LinkageKind.NO_LINKAGE = LinkageKind(1) |
| 2156 | LinkageKind.INTERNAL = LinkageKind(2) |
| 2157 | LinkageKind.UNIQUE_EXTERNAL = LinkageKind(3) |
| 2158 | LinkageKind.EXTERNAL = LinkageKind(4) |
| 2159 | |
| 2160 | class TLSKind(BaseEnumeration): |
| 2161 | """Describes the kind of thread-local storage (TLS) of a cursor.""" |
| 2162 | |
| 2163 | # The unique kind objects, indexed by id. |
| 2164 | _kinds = [] |
| 2165 | _name_map = None |
| 2166 | |
| 2167 | def from_param(self): |
| 2168 | return self.value |
| 2169 | |
| 2170 | def __repr__(self): |
| 2171 | return 'TLSKind.%s' % (self.name,) |
| 2172 | |
| 2173 | TLSKind.NONE = TLSKind(0) |
| 2174 | TLSKind.DYNAMIC = TLSKind(1) |
| 2175 | TLSKind.STATIC = TLSKind(2) |
| 2176 | |
| 2177 | class Type(Structure): |
| 2178 | """ |
| 2179 | The type of an element in the abstract syntax tree. |
| 2180 | """ |
| 2181 | _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)] |
| 2182 | |
| 2183 | @property |
| 2184 | def kind(self): |
| 2185 | """Return the kind of this type.""" |
| 2186 | return TypeKind.from_id(self._kind_id) |
| 2187 | |
| 2188 | def argument_types(self): |
| 2189 | """Retrieve a container for the non-variadic arguments for this type. |
| 2190 | |
| 2191 | The returned object is iterable and indexable. Each item in the |
| 2192 | container is a Type instance. |
| 2193 | """ |
| 2194 | class ArgumentsIterator(collections_abc.Sequence): |
| 2195 | def __init__(self, parent): |
| 2196 | self.parent = parent |
| 2197 | self.length = None |
| 2198 | |
| 2199 | def __len__(self): |
| 2200 | if self.length is None: |
| 2201 | self.length = conf.lib.clang_getNumArgTypes(self.parent) |
| 2202 | |
| 2203 | return self.length |
| 2204 | |
| 2205 | def __getitem__(self, key): |
| 2206 | # FIXME Support slice objects. |
| 2207 | if not isinstance(key, int): |
| 2208 | raise TypeError("Must supply a non-negative int.") |
| 2209 | |
| 2210 | if key < 0: |
| 2211 | raise IndexError("Only non-negative indexes are accepted.") |
| 2212 | |
| 2213 | if key >= len(self): |
| 2214 | raise IndexError("Index greater than container length: " |
| 2215 | "%d > %d" % ( key, len(self) )) |
| 2216 | |
| 2217 | result = conf.lib.clang_getArgType(self.parent, key) |
| 2218 | if result.kind == TypeKind.INVALID: |
| 2219 | raise IndexError("Argument could not be retrieved.") |
| 2220 | |
| 2221 | return result |
| 2222 | |
| 2223 | assert self.kind == TypeKind.FUNCTIONPROTO |
| 2224 | return ArgumentsIterator(self) |
| 2225 | |
| 2226 | @property |
| 2227 | def element_type(self): |
| 2228 | """Retrieve the Type of elements within this Type. |
| 2229 | |
| 2230 | If accessed on a type that is not an array, complex, or vector type, an |
| 2231 | exception will be raised. |
| 2232 | """ |
| 2233 | result = conf.lib.clang_getElementType(self) |
| 2234 | if result.kind == TypeKind.INVALID: |
| 2235 | raise Exception('Element type not available on this type.') |
| 2236 | |
| 2237 | return result |
| 2238 | |
| 2239 | @property |
| 2240 | def element_count(self): |
| 2241 | """Retrieve the number of elements in this type. |
| 2242 | |
| 2243 | Returns an int. |
| 2244 | |
| 2245 | If the Type is not an array or vector, this raises. |
| 2246 | """ |
| 2247 | result = conf.lib.clang_getNumElements(self) |
| 2248 | if result < 0: |
| 2249 | raise Exception('Type does not have elements.') |
| 2250 | |
| 2251 | return result |
| 2252 | |
| 2253 | @property |
| 2254 | def translation_unit(self): |
| 2255 | """The TranslationUnit to which this Type is associated.""" |
| 2256 | # If this triggers an AttributeError, the instance was not properly |
| 2257 | # instantiated. |
| 2258 | return self._tu |
| 2259 | |
| 2260 | @staticmethod |
| 2261 | def from_result(res, fn, args): |
| 2262 | assert isinstance(res, Type) |
| 2263 | |
| 2264 | tu = None |
| 2265 | for arg in args: |
| 2266 | if hasattr(arg, 'translation_unit'): |
| 2267 | tu = arg.translation_unit |
| 2268 | break |
| 2269 | |
| 2270 | assert tu is not None |
| 2271 | res._tu = tu |
| 2272 | |
| 2273 | return res |
| 2274 | |
| 2275 | def get_num_template_arguments(self): |
| 2276 | return conf.lib.clang_Type_getNumTemplateArguments(self) |
| 2277 | |
| 2278 | def get_template_argument_type(self, num): |
| 2279 | return conf.lib.clang_Type_getTemplateArgumentAsType(self, num) |
| 2280 | |
| 2281 | def get_canonical(self): |
| 2282 | """ |
| 2283 | Return the canonical type for a Type. |
| 2284 | |
| 2285 | Clang's type system explicitly models typedefs and all the |
| 2286 | ways a specific type can be represented. The canonical type |
| 2287 | is the underlying type with all the "sugar" removed. For |
| 2288 | example, if 'T' is a typedef for 'int', the canonical type for |
| 2289 | 'T' would be 'int'. |
| 2290 | """ |
| 2291 | return conf.lib.clang_getCanonicalType(self) |
| 2292 | |
| 2293 | def is_const_qualified(self): |
| 2294 | """Determine whether a Type has the "const" qualifier set. |
| 2295 | |
| 2296 | This does not look through typedefs that may have added "const" |
| 2297 | at a different level. |
| 2298 | """ |
| 2299 | return conf.lib.clang_isConstQualifiedType(self) |
| 2300 | |
| 2301 | def is_volatile_qualified(self): |
| 2302 | """Determine whether a Type has the "volatile" qualifier set. |
| 2303 | |
| 2304 | This does not look through typedefs that may have added "volatile" |
| 2305 | at a different level. |
| 2306 | """ |
| 2307 | return conf.lib.clang_isVolatileQualifiedType(self) |
| 2308 | |
| 2309 | def is_restrict_qualified(self): |
| 2310 | """Determine whether a Type has the "restrict" qualifier set. |
| 2311 | |
| 2312 | This does not look through typedefs that may have added "restrict" at |
| 2313 | a different level. |
| 2314 | """ |
| 2315 | return conf.lib.clang_isRestrictQualifiedType(self) |
| 2316 | |
| 2317 | def is_function_variadic(self): |
| 2318 | """Determine whether this function Type is a variadic function type.""" |
| 2319 | assert self.kind == TypeKind.FUNCTIONPROTO |
| 2320 | |
| 2321 | return conf.lib.clang_isFunctionTypeVariadic(self) |
| 2322 | |
| 2323 | def get_address_space(self): |
| 2324 | return conf.lib.clang_getAddressSpace(self) |
| 2325 | |
| 2326 | def get_typedef_name(self): |
| 2327 | return conf.lib.clang_getTypedefName(self) |
| 2328 | |
| 2329 | def is_pod(self): |
| 2330 | """Determine whether this Type represents plain old data (POD).""" |
| 2331 | return conf.lib.clang_isPODType(self) |
| 2332 | |
| 2333 | def get_pointee(self): |
| 2334 | """ |
| 2335 | For pointer types, returns the type of the pointee. |
| 2336 | """ |
| 2337 | return conf.lib.clang_getPointeeType(self) |
| 2338 | |
| 2339 | def get_declaration(self): |
| 2340 | """ |
| 2341 | Return the cursor for the declaration of the given type. |
| 2342 | """ |
| 2343 | return conf.lib.clang_getTypeDeclaration(self) |
| 2344 | |
| 2345 | def get_result(self): |
| 2346 | """ |
| 2347 | Retrieve the result type associated with a function type. |
| 2348 | """ |
| 2349 | return conf.lib.clang_getResultType(self) |
| 2350 | |
| 2351 | def get_array_element_type(self): |
| 2352 | """ |
| 2353 | Retrieve the type of the elements of the array type. |
| 2354 | """ |
| 2355 | return conf.lib.clang_getArrayElementType(self) |
| 2356 | |
| 2357 | def get_array_size(self): |
| 2358 | """ |
| 2359 | Retrieve the size of the constant array. |
| 2360 | """ |
| 2361 | return conf.lib.clang_getArraySize(self) |
| 2362 | |
| 2363 | def get_class_type(self): |
| 2364 | """ |
| 2365 | Retrieve the class type of the member pointer type. |
| 2366 | """ |
| 2367 | return conf.lib.clang_Type_getClassType(self) |
| 2368 | |
| 2369 | def get_named_type(self): |
| 2370 | """ |
| 2371 | Retrieve the type named by the qualified-id. |
| 2372 | """ |
| 2373 | return conf.lib.clang_Type_getNamedType(self) |
| 2374 | |
| 2375 | def get_align(self): |
| 2376 | """ |
| 2377 | Retrieve the alignment of the record. |
| 2378 | """ |
| 2379 | return conf.lib.clang_Type_getAlignOf(self) |
| 2380 | |
| 2381 | def get_size(self): |
| 2382 | """ |
| 2383 | Retrieve the size of the record. |
| 2384 | """ |
| 2385 | return conf.lib.clang_Type_getSizeOf(self) |
| 2386 | |
| 2387 | def get_offset(self, fieldname): |
| 2388 | """ |
| 2389 | Retrieve the offset of a field in the record. |
| 2390 | """ |
| 2391 | return conf.lib.clang_Type_getOffsetOf(self, fieldname) |
| 2392 | |
| 2393 | def get_ref_qualifier(self): |
| 2394 | """ |
| 2395 | Retrieve the ref-qualifier of the type. |
| 2396 | """ |
| 2397 | return RefQualifierKind.from_id( |
| 2398 | conf.lib.clang_Type_getCXXRefQualifier(self)) |
| 2399 | |
| 2400 | def get_fields(self): |
| 2401 | """Return an iterator for accessing the fields of this type.""" |
| 2402 | |
| 2403 | def visitor(field, children): |
| 2404 | assert field != conf.lib.clang_getNullCursor() |
| 2405 | |
| 2406 | # Create reference to TU so it isn't GC'd before Cursor. |
| 2407 | field._tu = self._tu |
| 2408 | fields.append(field) |
| 2409 | return 1 # continue |
| 2410 | fields = [] |
| 2411 | conf.lib.clang_Type_visitFields(self, |
| 2412 | callbacks['fields_visit'](visitor), fields) |
| 2413 | return iter(fields) |
| 2414 | |
| 2415 | def get_exception_specification_kind(self): |
| 2416 | """ |
| 2417 | Return the kind of the exception specification; a value from |
| 2418 | the ExceptionSpecificationKind enumeration. |
| 2419 | """ |
| 2420 | return ExceptionSpecificationKind.from_id( |
| 2421 | conf.lib.clang.getExceptionSpecificationType(self)) |
| 2422 | |
| 2423 | @property |
| 2424 | def spelling(self): |
| 2425 | """Retrieve the spelling of this Type.""" |
| 2426 | return conf.lib.clang_getTypeSpelling(self) |
| 2427 | |
| 2428 | def __eq__(self, other): |
| 2429 | if type(other) != type(self): |
| 2430 | return False |
| 2431 | |
| 2432 | return conf.lib.clang_equalTypes(self, other) |
| 2433 | |
| 2434 | def __ne__(self, other): |
| 2435 | return not self.__eq__(other) |
| 2436 | |
| 2437 | ## CIndex Objects ## |
| 2438 | |
| 2439 | # CIndex objects (derived from ClangObject) are essentially lightweight |
| 2440 | # wrappers attached to some underlying object, which is exposed via CIndex as |
| 2441 | # a void*. |
| 2442 | |
| 2443 | class ClangObject(object): |
| 2444 | """ |
| 2445 | A helper for Clang objects. This class helps act as an intermediary for |
| 2446 | the ctypes library and the Clang CIndex library. |
| 2447 | """ |
| 2448 | def __init__(self, obj): |
| 2449 | assert isinstance(obj, c_object_p) and obj |
| 2450 | self.obj = self._as_parameter_ = obj |
| 2451 | |
| 2452 | def from_param(self): |
| 2453 | return self._as_parameter_ |
| 2454 | |
| 2455 | |
| 2456 | class _CXUnsavedFile(Structure): |
| 2457 | """Helper for passing unsaved file arguments.""" |
| 2458 | _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)] |
| 2459 | |
| 2460 | # Functions calls through the python interface are rather slow. Fortunately, |
| 2461 | # for most symboles, we do not need to perform a function call. Their spelling |
| 2462 | # never changes and is consequently provided by this spelling cache. |
| 2463 | SpellingCache = { |
| 2464 | # 0: CompletionChunk.Kind("Optional"), |
| 2465 | # 1: CompletionChunk.Kind("TypedText"), |
| 2466 | # 2: CompletionChunk.Kind("Text"), |
| 2467 | # 3: CompletionChunk.Kind("Placeholder"), |
| 2468 | # 4: CompletionChunk.Kind("Informative"), |
| 2469 | # 5 : CompletionChunk.Kind("CurrentParameter"), |
| 2470 | 6: '(', # CompletionChunk.Kind("LeftParen"), |
| 2471 | 7: ')', # CompletionChunk.Kind("RightParen"), |
| 2472 | 8: '[', # CompletionChunk.Kind("LeftBracket"), |
| 2473 | 9: ']', # CompletionChunk.Kind("RightBracket"), |
| 2474 | 10: '{', # CompletionChunk.Kind("LeftBrace"), |
| 2475 | 11: '}', # CompletionChunk.Kind("RightBrace"), |
| 2476 | 12: '<', # CompletionChunk.Kind("LeftAngle"), |
| 2477 | 13: '>', # CompletionChunk.Kind("RightAngle"), |
| 2478 | 14: ', ', # CompletionChunk.Kind("Comma"), |
| 2479 | # 15: CompletionChunk.Kind("ResultType"), |
| 2480 | 16: ':', # CompletionChunk.Kind("Colon"), |
| 2481 | 17: ';', # CompletionChunk.Kind("SemiColon"), |
| 2482 | 18: '=', # CompletionChunk.Kind("Equal"), |
| 2483 | 19: ' ', # CompletionChunk.Kind("HorizontalSpace"), |
| 2484 | # 20: CompletionChunk.Kind("VerticalSpace") |
| 2485 | } |
| 2486 | |
| 2487 | class CompletionChunk(object): |
| 2488 | class Kind(object): |
| 2489 | def __init__(self, name): |
| 2490 | self.name = name |
| 2491 | |
| 2492 | def __str__(self): |
| 2493 | return self.name |
| 2494 | |
| 2495 | def __repr__(self): |
| 2496 | return "<ChunkKind: %s>" % self |
| 2497 | |
| 2498 | def __init__(self, completionString, key): |
| 2499 | self.cs = completionString |
| 2500 | self.key = key |
| 2501 | self.__kindNumberCache = -1 |
| 2502 | |
| 2503 | def __repr__(self): |
| 2504 | return "{'" + self.spelling + "', " + str(self.kind) + "}" |
| 2505 | |
| 2506 | @CachedProperty |
| 2507 | def spelling(self): |
| 2508 | if self.__kindNumber in SpellingCache: |
| 2509 | return SpellingCache[self.__kindNumber] |
| 2510 | return conf.lib.clang_getCompletionChunkText(self.cs, self.key) |
| 2511 | |
| 2512 | # We do not use @CachedProperty here, as the manual implementation is |
| 2513 | # apparently still significantly faster. Please profile carefully if you |
| 2514 | # would like to add CachedProperty back. |
| 2515 | @property |
| 2516 | def __kindNumber(self): |
| 2517 | if self.__kindNumberCache == -1: |
| 2518 | self.__kindNumberCache = \ |
| 2519 | conf.lib.clang_getCompletionChunkKind(self.cs, self.key) |
| 2520 | return self.__kindNumberCache |
| 2521 | |
| 2522 | @CachedProperty |
| 2523 | def kind(self): |
| 2524 | return completionChunkKindMap[self.__kindNumber] |
| 2525 | |
| 2526 | @CachedProperty |
| 2527 | def string(self): |
| 2528 | res = conf.lib.clang_getCompletionChunkCompletionString(self.cs, |
| 2529 | self.key) |
| 2530 | |
| 2531 | if (res): |
| 2532 | return CompletionString(res) |
| 2533 | else: |
| 2534 | None |
| 2535 | |
| 2536 | def isKindOptional(self): |
| 2537 | return self.__kindNumber == 0 |
| 2538 | |
| 2539 | def isKindTypedText(self): |
| 2540 | return self.__kindNumber == 1 |
| 2541 | |
| 2542 | def isKindPlaceHolder(self): |
| 2543 | return self.__kindNumber == 3 |
| 2544 | |
| 2545 | def isKindInformative(self): |
| 2546 | return self.__kindNumber == 4 |
| 2547 | |
| 2548 | def isKindResultType(self): |
| 2549 | return self.__kindNumber == 15 |
| 2550 | |
| 2551 | completionChunkKindMap = { |
| 2552 | 0: CompletionChunk.Kind("Optional"), |
| 2553 | 1: CompletionChunk.Kind("TypedText"), |
| 2554 | 2: CompletionChunk.Kind("Text"), |
| 2555 | 3: CompletionChunk.Kind("Placeholder"), |
| 2556 | 4: CompletionChunk.Kind("Informative"), |
| 2557 | 5: CompletionChunk.Kind("CurrentParameter"), |
| 2558 | 6: CompletionChunk.Kind("LeftParen"), |
| 2559 | 7: CompletionChunk.Kind("RightParen"), |
| 2560 | 8: CompletionChunk.Kind("LeftBracket"), |
| 2561 | 9: CompletionChunk.Kind("RightBracket"), |
| 2562 | 10: CompletionChunk.Kind("LeftBrace"), |
| 2563 | 11: CompletionChunk.Kind("RightBrace"), |
| 2564 | 12: CompletionChunk.Kind("LeftAngle"), |
| 2565 | 13: CompletionChunk.Kind("RightAngle"), |
| 2566 | 14: CompletionChunk.Kind("Comma"), |
| 2567 | 15: CompletionChunk.Kind("ResultType"), |
| 2568 | 16: CompletionChunk.Kind("Colon"), |
| 2569 | 17: CompletionChunk.Kind("SemiColon"), |
| 2570 | 18: CompletionChunk.Kind("Equal"), |
| 2571 | 19: CompletionChunk.Kind("HorizontalSpace"), |
| 2572 | 20: CompletionChunk.Kind("VerticalSpace")} |
| 2573 | |
| 2574 | class CompletionString(ClangObject): |
| 2575 | class Availability(object): |
| 2576 | def __init__(self, name): |
| 2577 | self.name = name |
| 2578 | |
| 2579 | def __str__(self): |
| 2580 | return self.name |
| 2581 | |
| 2582 | def __repr__(self): |
| 2583 | return "<Availability: %s>" % self |
| 2584 | |
| 2585 | def __len__(self): |
| 2586 | return self.num_chunks |
| 2587 | |
| 2588 | @CachedProperty |
| 2589 | def num_chunks(self): |
| 2590 | return conf.lib.clang_getNumCompletionChunks(self.obj) |
| 2591 | |
| 2592 | def __getitem__(self, key): |
| 2593 | if self.num_chunks <= key: |
| 2594 | raise IndexError |
| 2595 | return CompletionChunk(self.obj, key) |
| 2596 | |
| 2597 | @property |
| 2598 | def priority(self): |
| 2599 | return conf.lib.clang_getCompletionPriority(self.obj) |
| 2600 | |
| 2601 | @property |
| 2602 | def availability(self): |
| 2603 | res = conf.lib.clang_getCompletionAvailability(self.obj) |
| 2604 | return availabilityKinds[res] |
| 2605 | |
| 2606 | @property |
| 2607 | def briefComment(self): |
| 2608 | if conf.function_exists("clang_getCompletionBriefComment"): |
| 2609 | return conf.lib.clang_getCompletionBriefComment(self.obj) |
| 2610 | return _CXString() |
| 2611 | |
| 2612 | def __repr__(self): |
| 2613 | return " | ".join([str(a) for a in self]) \ |
| 2614 | + " || Priority: " + str(self.priority) \ |
| 2615 | + " || Availability: " + str(self.availability) \ |
| 2616 | + " || Brief comment: " + str(self.briefComment) |
| 2617 | |
| 2618 | availabilityKinds = { |
| 2619 | 0: CompletionChunk.Kind("Available"), |
| 2620 | 1: CompletionChunk.Kind("Deprecated"), |
| 2621 | 2: CompletionChunk.Kind("NotAvailable"), |
| 2622 | 3: CompletionChunk.Kind("NotAccessible")} |
| 2623 | |
| 2624 | class CodeCompletionResult(Structure): |
| 2625 | _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)] |
| 2626 | |
| 2627 | def __repr__(self): |
| 2628 | return str(CompletionString(self.completionString)) |
| 2629 | |
| 2630 | @property |
| 2631 | def kind(self): |
| 2632 | return CursorKind.from_id(self.cursorKind) |
| 2633 | |
| 2634 | @property |
| 2635 | def string(self): |
| 2636 | return CompletionString(self.completionString) |
| 2637 | |
| 2638 | class CCRStructure(Structure): |
| 2639 | _fields_ = [('results', POINTER(CodeCompletionResult)), |
| 2640 | ('numResults', c_int)] |
| 2641 | |
| 2642 | def __len__(self): |
| 2643 | return self.numResults |
| 2644 | |
| 2645 | def __getitem__(self, key): |
| 2646 | if len(self) <= key: |
| 2647 | raise IndexError |
| 2648 | |
| 2649 | return self.results[key] |
| 2650 | |
| 2651 | class CodeCompletionResults(ClangObject): |
| 2652 | def __init__(self, ptr): |
| 2653 | assert isinstance(ptr, POINTER(CCRStructure)) and ptr |
| 2654 | self.ptr = self._as_parameter_ = ptr |
| 2655 | |
| 2656 | def from_param(self): |
| 2657 | return self._as_parameter_ |
| 2658 | |
| 2659 | def __del__(self): |
| 2660 | conf.lib.clang_disposeCodeCompleteResults(self) |
| 2661 | |
| 2662 | @property |
| 2663 | def results(self): |
| 2664 | return self.ptr.contents |
| 2665 | |
| 2666 | @property |
| 2667 | def diagnostics(self): |
| 2668 | class DiagnosticsItr(object): |
| 2669 | def __init__(self, ccr): |
| 2670 | self.ccr= ccr |
| 2671 | |
| 2672 | def __len__(self): |
| 2673 | return int(\ |
| 2674 | conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr)) |
| 2675 | |
| 2676 | def __getitem__(self, key): |
| 2677 | return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key) |
| 2678 | |
| 2679 | return DiagnosticsItr(self) |
| 2680 | |
| 2681 | |
| 2682 | class Index(ClangObject): |
| 2683 | """ |
| 2684 | The Index type provides the primary interface to the Clang CIndex library, |
| 2685 | primarily by providing an interface for reading and parsing translation |
| 2686 | units. |
| 2687 | """ |
| 2688 | |
| 2689 | @staticmethod |
| 2690 | def create(excludeDecls=False): |
| 2691 | """ |
| 2692 | Create a new Index. |
| 2693 | Parameters: |
| 2694 | excludeDecls -- Exclude local declarations from translation units. |
| 2695 | """ |
| 2696 | return Index(conf.lib.clang_createIndex(excludeDecls, 0)) |
| 2697 | |
| 2698 | def __del__(self): |
| 2699 | conf.lib.clang_disposeIndex(self) |
| 2700 | |
| 2701 | def read(self, path): |
| 2702 | """Load a TranslationUnit from the given AST file.""" |
| 2703 | return TranslationUnit.from_ast_file(path, self) |
| 2704 | |
| 2705 | def parse(self, path, args=None, unsaved_files=None, options = 0): |
| 2706 | """Load the translation unit from the given source code file by running |
| 2707 | clang and generating the AST before loading. Additional command line |
| 2708 | parameters can be passed to clang via the args parameter. |
| 2709 | |
| 2710 | In-memory contents for files can be provided by passing a list of pairs |
| 2711 | to as unsaved_files, the first item should be the filenames to be mapped |
| 2712 | and the second should be the contents to be substituted for the |
| 2713 | file. The contents may be passed as strings or file objects. |
| 2714 | |
| 2715 | If an error was encountered during parsing, a TranslationUnitLoadError |
| 2716 | will be raised. |
| 2717 | """ |
| 2718 | return TranslationUnit.from_source(path, args, unsaved_files, options, |
| 2719 | self) |
| 2720 | |
| 2721 | class TranslationUnit(ClangObject): |
| 2722 | """Represents a source code translation unit. |
| 2723 | |
| 2724 | This is one of the main types in the API. Any time you wish to interact |
| 2725 | with Clang's representation of a source file, you typically start with a |
| 2726 | translation unit. |
| 2727 | """ |
| 2728 | |
| 2729 | # Default parsing mode. |
| 2730 | PARSE_NONE = 0 |
| 2731 | |
| 2732 | # Instruct the parser to create a detailed processing record containing |
| 2733 | # metadata not normally retained. |
| 2734 | PARSE_DETAILED_PROCESSING_RECORD = 1 |
| 2735 | |
| 2736 | # Indicates that the translation unit is incomplete. This is typically used |
| 2737 | # when parsing headers. |
| 2738 | PARSE_INCOMPLETE = 2 |
| 2739 | |
| 2740 | # Instruct the parser to create a pre-compiled preamble for the translation |
| 2741 | # unit. This caches the preamble (included files at top of source file). |
| 2742 | # This is useful if the translation unit will be reparsed and you don't |
| 2743 | # want to incur the overhead of reparsing the preamble. |
| 2744 | PARSE_PRECOMPILED_PREAMBLE = 4 |
| 2745 | |
| 2746 | # Cache code completion information on parse. This adds time to parsing but |
| 2747 | # speeds up code completion. |
| 2748 | PARSE_CACHE_COMPLETION_RESULTS = 8 |
| 2749 | |
| 2750 | # Flags with values 16 and 32 are deprecated and intentionally omitted. |
| 2751 | |
| 2752 | # Do not parse function bodies. This is useful if you only care about |
| 2753 | # searching for declarations/definitions. |
| 2754 | PARSE_SKIP_FUNCTION_BODIES = 64 |
| 2755 | |
| 2756 | # Used to indicate that brief documentation comments should be included |
| 2757 | # into the set of code completions returned from this translation unit. |
| 2758 | PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128 |
| 2759 | |
| 2760 | @classmethod |
| 2761 | def from_source(cls, filename, args=None, unsaved_files=None, options=0, |
| 2762 | index=None): |
| 2763 | """Create a TranslationUnit by parsing source. |
| 2764 | |
| 2765 | This is capable of processing source code both from files on the |
| 2766 | filesystem as well as in-memory contents. |
| 2767 | |
| 2768 | Command-line arguments that would be passed to clang are specified as |
| 2769 | a list via args. These can be used to specify include paths, warnings, |
| 2770 | etc. e.g. ["-Wall", "-I/path/to/include"]. |
| 2771 | |
| 2772 | In-memory file content can be provided via unsaved_files. This is an |
| 2773 | iterable of 2-tuples. The first element is the filename (str or |
| 2774 | PathLike). The second element defines the content. Content can be |
| 2775 | provided as str source code or as file objects (anything with a read() |
| 2776 | method). If a file object is being used, content will be read until EOF |
| 2777 | and the read cursor will not be reset to its original position. |
| 2778 | |
| 2779 | options is a bitwise or of TranslationUnit.PARSE_XXX flags which will |
| 2780 | control parsing behavior. |
| 2781 | |
| 2782 | index is an Index instance to utilize. If not provided, a new Index |
| 2783 | will be created for this TranslationUnit. |
| 2784 | |
| 2785 | To parse source from the filesystem, the filename of the file to parse |
| 2786 | is specified by the filename argument. Or, filename could be None and |
| 2787 | the args list would contain the filename(s) to parse. |
| 2788 | |
| 2789 | To parse source from an in-memory buffer, set filename to the virtual |
| 2790 | filename you wish to associate with this source (e.g. "test.c"). The |
| 2791 | contents of that file are then provided in unsaved_files. |
| 2792 | |
| 2793 | If an error occurs, a TranslationUnitLoadError is raised. |
| 2794 | |
| 2795 | Please note that a TranslationUnit with parser errors may be returned. |
| 2796 | It is the caller's responsibility to check tu.diagnostics for errors. |
| 2797 | |
| 2798 | Also note that Clang infers the source language from the extension of |
| 2799 | the input filename. If you pass in source code containing a C++ class |
| 2800 | declaration with the filename "test.c" parsing will fail. |
| 2801 | """ |
| 2802 | if args is None: |
| 2803 | args = [] |
| 2804 | |
| 2805 | if unsaved_files is None: |
| 2806 | unsaved_files = [] |
| 2807 | |
| 2808 | if index is None: |
| 2809 | index = Index.create() |
| 2810 | |
| 2811 | args_array = None |
| 2812 | if len(args) > 0: |
| 2813 | args_array = (c_char_p * len(args))(*[b(x) for x in args]) |
| 2814 | |
| 2815 | unsaved_array = None |
| 2816 | if len(unsaved_files) > 0: |
| 2817 | unsaved_array = (_CXUnsavedFile * len(unsaved_files))() |
| 2818 | for i, (name, contents) in enumerate(unsaved_files): |
| 2819 | if hasattr(contents, "read"): |
| 2820 | contents = contents.read() |
| 2821 | contents = b(contents) |
| 2822 | unsaved_array[i].name = b(fspath(name)) |
| 2823 | unsaved_array[i].contents = contents |
| 2824 | unsaved_array[i].length = len(contents) |
| 2825 | |
| 2826 | ptr = conf.lib.clang_parseTranslationUnit(index, |
| 2827 | fspath(filename) if filename is not None else None, |
| 2828 | args_array, |
| 2829 | len(args), unsaved_array, |
| 2830 | len(unsaved_files), options) |
| 2831 | |
| 2832 | if not ptr: |
| 2833 | raise TranslationUnitLoadError("Error parsing translation unit.") |
| 2834 | |
| 2835 | return cls(ptr, index=index) |
| 2836 | |
| 2837 | @classmethod |
| 2838 | def from_ast_file(cls, filename, index=None): |
| 2839 | """Create a TranslationUnit instance from a saved AST file. |
| 2840 | |
| 2841 | A previously-saved AST file (provided with -emit-ast or |
| 2842 | TranslationUnit.save()) is loaded from the filename specified. |
| 2843 | |
| 2844 | If the file cannot be loaded, a TranslationUnitLoadError will be |
| 2845 | raised. |
| 2846 | |
| 2847 | index is optional and is the Index instance to use. If not provided, |
| 2848 | a default Index will be created. |
| 2849 | |
| 2850 | filename can be str or PathLike. |
| 2851 | """ |
| 2852 | if index is None: |
| 2853 | index = Index.create() |
| 2854 | |
| 2855 | ptr = conf.lib.clang_createTranslationUnit(index, fspath(filename)) |
| 2856 | if not ptr: |
| 2857 | raise TranslationUnitLoadError(filename) |
| 2858 | |
| 2859 | return cls(ptr=ptr, index=index) |
| 2860 | |
| 2861 | def __init__(self, ptr, index): |
| 2862 | """Create a TranslationUnit instance. |
| 2863 | |
| 2864 | TranslationUnits should be created using one of the from_* @classmethod |
| 2865 | functions above. __init__ is only called internally. |
| 2866 | """ |
| 2867 | assert isinstance(index, Index) |
| 2868 | self.index = index |
| 2869 | ClangObject.__init__(self, ptr) |
| 2870 | |
| 2871 | def __del__(self): |
| 2872 | conf.lib.clang_disposeTranslationUnit(self) |
| 2873 | |
| 2874 | @property |
| 2875 | def cursor(self): |
| 2876 | """Retrieve the cursor that represents the given translation unit.""" |
| 2877 | return conf.lib.clang_getTranslationUnitCursor(self) |
| 2878 | |
| 2879 | @property |
| 2880 | def spelling(self): |
| 2881 | """Get the original translation unit source file name.""" |
| 2882 | return conf.lib.clang_getTranslationUnitSpelling(self) |
| 2883 | |
| 2884 | def get_includes(self): |
| 2885 | """ |
| 2886 | Return an iterable sequence of FileInclusion objects that describe the |
| 2887 | sequence of inclusions in a translation unit. The first object in |
| 2888 | this sequence is always the input file. Note that this method will not |
| 2889 | recursively iterate over header files included through precompiled |
| 2890 | headers. |
| 2891 | """ |
| 2892 | def visitor(fobj, lptr, depth, includes): |
| 2893 | if depth > 0: |
| 2894 | loc = lptr.contents |
| 2895 | includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) |
| 2896 | |
| 2897 | # Automatically adapt CIndex/ctype pointers to python objects |
| 2898 | includes = [] |
| 2899 | conf.lib.clang_getInclusions(self, |
| 2900 | callbacks['translation_unit_includes'](visitor), includes) |
| 2901 | |
| 2902 | return iter(includes) |
| 2903 | |
| 2904 | def get_file(self, filename): |
| 2905 | """Obtain a File from this translation unit.""" |
| 2906 | |
| 2907 | return File.from_name(self, filename) |
| 2908 | |
| 2909 | def get_location(self, filename, position): |
| 2910 | """Obtain a SourceLocation for a file in this translation unit. |
| 2911 | |
| 2912 | The position can be specified by passing: |
| 2913 | |
| 2914 | - Integer file offset. Initial file offset is 0. |
| 2915 | - 2-tuple of (line number, column number). Initial file position is |
| 2916 | (0, 0) |
| 2917 | """ |
| 2918 | f = self.get_file(filename) |
| 2919 | |
| 2920 | if isinstance(position, int): |
| 2921 | return SourceLocation.from_offset(self, f, position) |
| 2922 | |
| 2923 | return SourceLocation.from_position(self, f, position[0], position[1]) |
| 2924 | |
| 2925 | def get_extent(self, filename, locations): |
| 2926 | """Obtain a SourceRange from this translation unit. |
| 2927 | |
| 2928 | The bounds of the SourceRange must ultimately be defined by a start and |
| 2929 | end SourceLocation. For the locations argument, you can pass: |
| 2930 | |
| 2931 | - 2 SourceLocation instances in a 2-tuple or list. |
| 2932 | - 2 int file offsets via a 2-tuple or list. |
| 2933 | - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. |
| 2934 | |
| 2935 | e.g. |
| 2936 | |
| 2937 | get_extent('foo.c', (5, 10)) |
| 2938 | get_extent('foo.c', ((1, 1), (1, 15))) |
| 2939 | """ |
| 2940 | f = self.get_file(filename) |
| 2941 | |
| 2942 | if len(locations) < 2: |
| 2943 | raise Exception('Must pass object with at least 2 elements') |
| 2944 | |
| 2945 | start_location, end_location = locations |
| 2946 | |
| 2947 | if hasattr(start_location, '__len__'): |
| 2948 | start_location = SourceLocation.from_position(self, f, |
| 2949 | start_location[0], start_location[1]) |
| 2950 | elif isinstance(start_location, int): |
| 2951 | start_location = SourceLocation.from_offset(self, f, |
| 2952 | start_location) |
| 2953 | |
| 2954 | if hasattr(end_location, '__len__'): |
| 2955 | end_location = SourceLocation.from_position(self, f, |
| 2956 | end_location[0], end_location[1]) |
| 2957 | elif isinstance(end_location, int): |
| 2958 | end_location = SourceLocation.from_offset(self, f, end_location) |
| 2959 | |
| 2960 | assert isinstance(start_location, SourceLocation) |
| 2961 | assert isinstance(end_location, SourceLocation) |
| 2962 | |
| 2963 | return SourceRange.from_locations(start_location, end_location) |
| 2964 | |
| 2965 | @property |
| 2966 | def diagnostics(self): |
| 2967 | """ |
| 2968 | Return an iterable (and indexable) object containing the diagnostics. |
| 2969 | """ |
| 2970 | class DiagIterator(object): |
| 2971 | def __init__(self, tu): |
| 2972 | self.tu = tu |
| 2973 | |
| 2974 | def __len__(self): |
| 2975 | return int(conf.lib.clang_getNumDiagnostics(self.tu)) |
| 2976 | |
| 2977 | def __getitem__(self, key): |
| 2978 | diag = conf.lib.clang_getDiagnostic(self.tu, key) |
| 2979 | if not diag: |
| 2980 | raise IndexError |
| 2981 | return Diagnostic(diag) |
| 2982 | |
| 2983 | return DiagIterator(self) |
| 2984 | |
| 2985 | def reparse(self, unsaved_files=None, options=0): |
| 2986 | """ |
| 2987 | Reparse an already parsed translation unit. |
| 2988 | |
| 2989 | In-memory contents for files can be provided by passing a list of pairs |
| 2990 | as unsaved_files, the first items should be the filenames to be mapped |
| 2991 | and the second should be the contents to be substituted for the |
| 2992 | file. The contents may be passed as strings or file objects. |
| 2993 | """ |
| 2994 | if unsaved_files is None: |
| 2995 | unsaved_files = [] |
| 2996 | |
| 2997 | unsaved_files_array = 0 |
| 2998 | if len(unsaved_files): |
| 2999 | unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() |
| 3000 | for i,(name,contents) in enumerate(unsaved_files): |
| 3001 | if hasattr(contents, "read"): |
| 3002 | contents = contents.read() |
| 3003 | contents = b(contents) |
| 3004 | unsaved_files_array[i].name = b(fspath(name)) |
| 3005 | unsaved_files_array[i].contents = contents |
| 3006 | unsaved_files_array[i].length = len(contents) |
| 3007 | ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files), |
| 3008 | unsaved_files_array, options) |
| 3009 | |
| 3010 | def save(self, filename): |
| 3011 | """Saves the TranslationUnit to a file. |
| 3012 | |
| 3013 | This is equivalent to passing -emit-ast to the clang frontend. The |
| 3014 | saved file can be loaded back into a TranslationUnit. Or, if it |
| 3015 | corresponds to a header, it can be used as a pre-compiled header file. |
| 3016 | |
| 3017 | If an error occurs while saving, a TranslationUnitSaveError is raised. |
| 3018 | If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means |
| 3019 | the constructed TranslationUnit was not valid at time of save. In this |
| 3020 | case, the reason(s) why should be available via |
| 3021 | TranslationUnit.diagnostics(). |
| 3022 | |
| 3023 | filename -- The path to save the translation unit to (str or PathLike). |
| 3024 | """ |
| 3025 | options = conf.lib.clang_defaultSaveOptions(self) |
| 3026 | result = int(conf.lib.clang_saveTranslationUnit(self, fspath(filename), |
| 3027 | options)) |
| 3028 | if result != 0: |
| 3029 | raise TranslationUnitSaveError(result, |
| 3030 | 'Error saving TranslationUnit.') |
| 3031 | |
| 3032 | def codeComplete(self, path, line, column, unsaved_files=None, |
| 3033 | include_macros=False, include_code_patterns=False, |
| 3034 | include_brief_comments=False): |
| 3035 | """ |
| 3036 | Code complete in this translation unit. |
| 3037 | |
| 3038 | In-memory contents for files can be provided by passing a list of pairs |
| 3039 | as unsaved_files, the first items should be the filenames to be mapped |
| 3040 | and the second should be the contents to be substituted for the |
| 3041 | file. The contents may be passed as strings or file objects. |
| 3042 | """ |
| 3043 | options = 0 |
| 3044 | |
| 3045 | if include_macros: |
| 3046 | options += 1 |
| 3047 | |
| 3048 | if include_code_patterns: |
| 3049 | options += 2 |
| 3050 | |
| 3051 | if include_brief_comments: |
| 3052 | options += 4 |
| 3053 | |
| 3054 | if unsaved_files is None: |
| 3055 | unsaved_files = [] |
| 3056 | |
| 3057 | unsaved_files_array = 0 |
| 3058 | if len(unsaved_files): |
| 3059 | unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() |
| 3060 | for i,(name,contents) in enumerate(unsaved_files): |
| 3061 | if hasattr(contents, "read"): |
| 3062 | contents = contents.read() |
| 3063 | contents = b(contents) |
| 3064 | unsaved_files_array[i].name = b(fspath(name)) |
| 3065 | unsaved_files_array[i].contents = contents |
| 3066 | unsaved_files_array[i].length = len(contents) |
| 3067 | ptr = conf.lib.clang_codeCompleteAt(self, fspath(path), line, column, |
| 3068 | unsaved_files_array, len(unsaved_files), options) |
| 3069 | if ptr: |
| 3070 | return CodeCompletionResults(ptr) |
| 3071 | return None |
| 3072 | |
| 3073 | def get_tokens(self, locations=None, extent=None): |
| 3074 | """Obtain tokens in this translation unit. |
| 3075 | |
| 3076 | This is a generator for Token instances. The caller specifies a range |
| 3077 | of source code to obtain tokens for. The range can be specified as a |
| 3078 | 2-tuple of SourceLocation or as a SourceRange. If both are defined, |
| 3079 | behavior is undefined. |
| 3080 | """ |
| 3081 | if locations is not None: |
| 3082 | extent = SourceRange(start=locations[0], end=locations[1]) |
| 3083 | |
| 3084 | return TokenGroup.get_tokens(self, extent) |
| 3085 | |
| 3086 | class File(ClangObject): |
| 3087 | """ |
| 3088 | The File class represents a particular source file that is part of a |
| 3089 | translation unit. |
| 3090 | """ |
| 3091 | |
| 3092 | @staticmethod |
| 3093 | def from_name(translation_unit, file_name): |
| 3094 | """Retrieve a file handle within the given translation unit.""" |
| 3095 | return File(conf.lib.clang_getFile(translation_unit, fspath(file_name))) |
| 3096 | |
| 3097 | @property |
| 3098 | def name(self): |
| 3099 | """Return the complete file and path name of the file.""" |
| 3100 | return conf.lib.clang_getFileName(self) |
| 3101 | |
| 3102 | @property |
| 3103 | def time(self): |
| 3104 | """Return the last modification time of the file.""" |
| 3105 | return conf.lib.clang_getFileTime(self) |
| 3106 | |
| 3107 | def __str__(self): |
| 3108 | return self.name |
| 3109 | |
| 3110 | def __repr__(self): |
| 3111 | return "<File: %s>" % (self.name) |
| 3112 | |
| 3113 | @staticmethod |
| 3114 | def from_result(res, fn, args): |
| 3115 | assert isinstance(res, c_object_p) |
| 3116 | res = File(res) |
| 3117 | |
| 3118 | # Copy a reference to the TranslationUnit to prevent premature GC. |
| 3119 | res._tu = args[0]._tu |
| 3120 | return res |
| 3121 | |
| 3122 | class FileInclusion(object): |
| 3123 | """ |
| 3124 | The FileInclusion class represents the inclusion of one source file by |
| 3125 | another via a '#include' directive or as the input file for the translation |
| 3126 | unit. This class provides information about the included file, the including |
| 3127 | file, the location of the '#include' directive and the depth of the included |
| 3128 | file in the stack. Note that the input file has depth 0. |
| 3129 | """ |
| 3130 | |
| 3131 | def __init__(self, src, tgt, loc, depth): |
| 3132 | self.source = src |
| 3133 | self.include = tgt |
| 3134 | self.location = loc |
| 3135 | self.depth = depth |
| 3136 | |
| 3137 | @property |
| 3138 | def is_input_file(self): |
| 3139 | """True if the included file is the input file.""" |
| 3140 | return self.depth == 0 |
| 3141 | |
| 3142 | class CompilationDatabaseError(Exception): |
| 3143 | """Represents an error that occurred when working with a CompilationDatabase |
| 3144 | |
| 3145 | Each error is associated to an enumerated value, accessible under |
| 3146 | e.cdb_error. Consumers can compare the value with one of the ERROR_ |
| 3147 | constants in this class. |
| 3148 | """ |
| 3149 | |
| 3150 | # An unknown error occurred |
| 3151 | ERROR_UNKNOWN = 0 |
| 3152 | |
| 3153 | # The database could not be loaded |
| 3154 | ERROR_CANNOTLOADDATABASE = 1 |
| 3155 | |
| 3156 | def __init__(self, enumeration, message): |
| 3157 | assert isinstance(enumeration, int) |
| 3158 | |
| 3159 | if enumeration > 1: |
| 3160 | raise Exception("Encountered undefined CompilationDatabase error " |
| 3161 | "constant: %d. Please file a bug to have this " |
| 3162 | "value supported." % enumeration) |
| 3163 | |
| 3164 | self.cdb_error = enumeration |
| 3165 | Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) |
| 3166 | |
| 3167 | class CompileCommand(object): |
| 3168 | """Represents the compile command used to build a file""" |
| 3169 | def __init__(self, cmd, ccmds): |
| 3170 | self.cmd = cmd |
| 3171 | # Keep a reference to the originating CompileCommands |
| 3172 | # to prevent garbage collection |
| 3173 | self.ccmds = ccmds |
| 3174 | |
| 3175 | @property |
| 3176 | def directory(self): |
| 3177 | """Get the working directory for this CompileCommand""" |
| 3178 | return conf.lib.clang_CompileCommand_getDirectory(self.cmd) |
| 3179 | |
| 3180 | @property |
| 3181 | def filename(self): |
| 3182 | """Get the working filename for this CompileCommand""" |
| 3183 | return conf.lib.clang_CompileCommand_getFilename(self.cmd) |
| 3184 | |
| 3185 | @property |
| 3186 | def arguments(self): |
| 3187 | """ |
| 3188 | Get an iterable object providing each argument in the |
| 3189 | command line for the compiler invocation as a _CXString. |
| 3190 | |
| 3191 | Invariant : the first argument is the compiler executable |
| 3192 | """ |
| 3193 | length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd) |
| 3194 | for i in range(length): |
| 3195 | yield conf.lib.clang_CompileCommand_getArg(self.cmd, i) |
| 3196 | |
| 3197 | class CompileCommands(object): |
| 3198 | """ |
| 3199 | CompileCommands is an iterable object containing all CompileCommand |
| 3200 | that can be used for building a specific file. |
| 3201 | """ |
| 3202 | def __init__(self, ccmds): |
| 3203 | self.ccmds = ccmds |
| 3204 | |
| 3205 | def __del__(self): |
| 3206 | conf.lib.clang_CompileCommands_dispose(self.ccmds) |
| 3207 | |
| 3208 | def __len__(self): |
| 3209 | return int(conf.lib.clang_CompileCommands_getSize(self.ccmds)) |
| 3210 | |
| 3211 | def __getitem__(self, i): |
| 3212 | cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i) |
| 3213 | if not cc: |
| 3214 | raise IndexError |
| 3215 | return CompileCommand(cc, self) |
| 3216 | |
| 3217 | @staticmethod |
| 3218 | def from_result(res, fn, args): |
| 3219 | if not res: |
| 3220 | return None |
| 3221 | return CompileCommands(res) |
| 3222 | |
| 3223 | class CompilationDatabase(ClangObject): |
| 3224 | """ |
| 3225 | The CompilationDatabase is a wrapper class around |
| 3226 | clang::tooling::CompilationDatabase |
| 3227 | |
| 3228 | It enables querying how a specific source file can be built. |
| 3229 | """ |
| 3230 | |
| 3231 | def __del__(self): |
| 3232 | conf.lib.clang_CompilationDatabase_dispose(self) |
| 3233 | |
| 3234 | @staticmethod |
| 3235 | def from_result(res, fn, args): |
| 3236 | if not res: |
| 3237 | raise CompilationDatabaseError(0, |
| 3238 | "CompilationDatabase loading failed") |
| 3239 | return CompilationDatabase(res) |
| 3240 | |
| 3241 | @staticmethod |
| 3242 | def fromDirectory(buildDir): |
| 3243 | """Builds a CompilationDatabase from the database found in buildDir""" |
| 3244 | errorCode = c_uint() |
| 3245 | try: |
| 3246 | cdb = conf.lib.clang_CompilationDatabase_fromDirectory(fspath(buildDir), |
| 3247 | byref(errorCode)) |
| 3248 | except CompilationDatabaseError as e: |
| 3249 | raise CompilationDatabaseError(int(errorCode.value), |
| 3250 | "CompilationDatabase loading failed") |
| 3251 | return cdb |
| 3252 | |
| 3253 | def getCompileCommands(self, filename): |
| 3254 | """ |
| 3255 | Get an iterable object providing all the CompileCommands available to |
| 3256 | build filename. Returns None if filename is not found in the database. |
| 3257 | """ |
| 3258 | return conf.lib.clang_CompilationDatabase_getCompileCommands(self, |
| 3259 | fspath(filename)) |
| 3260 | |
| 3261 | def getAllCompileCommands(self): |
| 3262 | """ |
| 3263 | Get an iterable object providing all the CompileCommands available from |
| 3264 | the database. |
| 3265 | """ |
| 3266 | return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self) |
| 3267 | |
| 3268 | |
| 3269 | class Token(Structure): |
| 3270 | """Represents a single token from the preprocessor. |
| 3271 | |
| 3272 | Tokens are effectively segments of source code. Source code is first parsed |
| 3273 | into tokens before being converted into the AST and Cursors. |
| 3274 | |
| 3275 | Tokens are obtained from parsed TranslationUnit instances. You currently |
| 3276 | can't create tokens manually. |
| 3277 | """ |
| 3278 | _fields_ = [ |
| 3279 | ('int_data', c_uint * 4), |
| 3280 | ('ptr_data', c_void_p) |
| 3281 | ] |
| 3282 | |
| 3283 | @property |
| 3284 | def spelling(self): |
| 3285 | """The spelling of this token. |
| 3286 | |
| 3287 | This is the textual representation of the token in source. |
| 3288 | """ |
| 3289 | return conf.lib.clang_getTokenSpelling(self._tu, self) |
| 3290 | |
| 3291 | @property |
| 3292 | def kind(self): |
| 3293 | """Obtain the TokenKind of the current token.""" |
| 3294 | return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) |
| 3295 | |
| 3296 | @property |
| 3297 | def location(self): |
| 3298 | """The SourceLocation this Token occurs at.""" |
| 3299 | return conf.lib.clang_getTokenLocation(self._tu, self) |
| 3300 | |
| 3301 | @property |
| 3302 | def extent(self): |
| 3303 | """The SourceRange this Token occupies.""" |
| 3304 | return conf.lib.clang_getTokenExtent(self._tu, self) |
| 3305 | |
| 3306 | @property |
| 3307 | def cursor(self): |
| 3308 | """The Cursor this Token corresponds to.""" |
| 3309 | cursor = Cursor() |
| 3310 | cursor._tu = self._tu |
| 3311 | |
| 3312 | conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor)) |
| 3313 | |
| 3314 | return cursor |
| 3315 | |
| 3316 | # Now comes the plumbing to hook up the C library. |
| 3317 | |
| 3318 | # Register callback types in common container. |
| 3319 | callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p, |
| 3320 | POINTER(SourceLocation), c_uint, py_object) |
| 3321 | callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object) |
| 3322 | callbacks['fields_visit'] = CFUNCTYPE(c_int, Cursor, py_object) |
| 3323 | |
| 3324 | # Functions strictly alphabetical order. |
| 3325 | functionList = [ |
| 3326 | ("clang_annotateTokens", |
| 3327 | [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]), |
| 3328 | |
| 3329 | ("clang_CompilationDatabase_dispose", |
| 3330 | [c_object_p]), |
| 3331 | |
| 3332 | ("clang_CompilationDatabase_fromDirectory", |
| 3333 | [c_interop_string, POINTER(c_uint)], |
| 3334 | c_object_p, |
| 3335 | CompilationDatabase.from_result), |
| 3336 | |
| 3337 | ("clang_CompilationDatabase_getAllCompileCommands", |
| 3338 | [c_object_p], |
| 3339 | c_object_p, |
| 3340 | CompileCommands.from_result), |
| 3341 | |
| 3342 | ("clang_CompilationDatabase_getCompileCommands", |
| 3343 | [c_object_p, c_interop_string], |
| 3344 | c_object_p, |
| 3345 | CompileCommands.from_result), |
| 3346 | |
| 3347 | ("clang_CompileCommands_dispose", |
| 3348 | [c_object_p]), |
| 3349 | |
| 3350 | ("clang_CompileCommands_getCommand", |
| 3351 | [c_object_p, c_uint], |
| 3352 | c_object_p), |
| 3353 | |
| 3354 | ("clang_CompileCommands_getSize", |
| 3355 | [c_object_p], |
| 3356 | c_uint), |
| 3357 | |
| 3358 | ("clang_CompileCommand_getArg", |
| 3359 | [c_object_p, c_uint], |
| 3360 | _CXString, |
| 3361 | _CXString.from_result), |
| 3362 | |
| 3363 | ("clang_CompileCommand_getDirectory", |
| 3364 | [c_object_p], |
| 3365 | _CXString, |
| 3366 | _CXString.from_result), |
| 3367 | |
| 3368 | ("clang_CompileCommand_getFilename", |
| 3369 | [c_object_p], |
| 3370 | _CXString, |
| 3371 | _CXString.from_result), |
| 3372 | |
| 3373 | ("clang_CompileCommand_getNumArgs", |
| 3374 | [c_object_p], |
| 3375 | c_uint), |
| 3376 | |
| 3377 | ("clang_codeCompleteAt", |
| 3378 | [TranslationUnit, c_interop_string, c_int, c_int, c_void_p, c_int, c_int], |
| 3379 | POINTER(CCRStructure)), |
| 3380 | |
| 3381 | ("clang_codeCompleteGetDiagnostic", |
| 3382 | [CodeCompletionResults, c_int], |
| 3383 | Diagnostic), |
| 3384 | |
| 3385 | ("clang_codeCompleteGetNumDiagnostics", |
| 3386 | [CodeCompletionResults], |
| 3387 | c_int), |
| 3388 | |
| 3389 | ("clang_createIndex", |
| 3390 | [c_int, c_int], |
| 3391 | c_object_p), |
| 3392 | |
| 3393 | ("clang_createTranslationUnit", |
| 3394 | [Index, c_interop_string], |
| 3395 | c_object_p), |
| 3396 | |
| 3397 | ("clang_CXXConstructor_isConvertingConstructor", |
| 3398 | [Cursor], |
| 3399 | bool), |
| 3400 | |
| 3401 | ("clang_CXXConstructor_isCopyConstructor", |
| 3402 | [Cursor], |
| 3403 | bool), |
| 3404 | |
| 3405 | ("clang_CXXConstructor_isDefaultConstructor", |
| 3406 | [Cursor], |
| 3407 | bool), |
| 3408 | |
| 3409 | ("clang_CXXConstructor_isMoveConstructor", |
| 3410 | [Cursor], |
| 3411 | bool), |
| 3412 | |
| 3413 | ("clang_CXXField_isMutable", |
| 3414 | [Cursor], |
| 3415 | bool), |
| 3416 | |
| 3417 | ("clang_CXXMethod_isConst", |
| 3418 | [Cursor], |
| 3419 | bool), |
| 3420 | |
| 3421 | ("clang_CXXMethod_isDefaulted", |
| 3422 | [Cursor], |
| 3423 | bool), |
| 3424 | |
| 3425 | ("clang_CXXMethod_isPureVirtual", |
| 3426 | [Cursor], |
| 3427 | bool), |
| 3428 | |
| 3429 | ("clang_CXXMethod_isStatic", |
| 3430 | [Cursor], |
| 3431 | bool), |
| 3432 | |
| 3433 | ("clang_CXXMethod_isVirtual", |
| 3434 | [Cursor], |
| 3435 | bool), |
| 3436 | |
| 3437 | ("clang_CXXRecord_isAbstract", |
| 3438 | [Cursor], |
| 3439 | bool), |
| 3440 | |
| 3441 | ("clang_EnumDecl_isScoped", |
| 3442 | [Cursor], |
| 3443 | bool), |
| 3444 | |
| 3445 | ("clang_defaultDiagnosticDisplayOptions", |
| 3446 | [], |
| 3447 | c_uint), |
| 3448 | |
| 3449 | ("clang_defaultSaveOptions", |
| 3450 | [TranslationUnit], |
| 3451 | c_uint), |
| 3452 | |
| 3453 | ("clang_disposeCodeCompleteResults", |
| 3454 | [CodeCompletionResults]), |
| 3455 | |
| 3456 | # ("clang_disposeCXTUResourceUsage", |
| 3457 | # [CXTUResourceUsage]), |
| 3458 | |
| 3459 | ("clang_disposeDiagnostic", |
| 3460 | [Diagnostic]), |
| 3461 | |
| 3462 | ("clang_disposeIndex", |
| 3463 | [Index]), |
| 3464 | |
| 3465 | ("clang_disposeString", |
| 3466 | [_CXString]), |
| 3467 | |
| 3468 | ("clang_disposeTokens", |
| 3469 | [TranslationUnit, POINTER(Token), c_uint]), |
| 3470 | |
| 3471 | ("clang_disposeTranslationUnit", |
| 3472 | [TranslationUnit]), |
| 3473 | |
| 3474 | ("clang_equalCursors", |
| 3475 | [Cursor, Cursor], |
| 3476 | bool), |
| 3477 | |
| 3478 | ("clang_equalLocations", |
| 3479 | [SourceLocation, SourceLocation], |
| 3480 | bool), |
| 3481 | |
| 3482 | ("clang_equalRanges", |
| 3483 | [SourceRange, SourceRange], |
| 3484 | bool), |
| 3485 | |
| 3486 | ("clang_equalTypes", |
| 3487 | [Type, Type], |
| 3488 | bool), |
| 3489 | |
| 3490 | ("clang_formatDiagnostic", |
| 3491 | [Diagnostic, c_uint], |
| 3492 | _CXString, |
| 3493 | _CXString.from_result), |
| 3494 | |
| 3495 | ("clang_getArgType", |
| 3496 | [Type, c_uint], |
| 3497 | Type, |
| 3498 | Type.from_result), |
| 3499 | |
| 3500 | ("clang_getArrayElementType", |
| 3501 | [Type], |
| 3502 | Type, |
| 3503 | Type.from_result), |
| 3504 | |
| 3505 | ("clang_getArraySize", |
| 3506 | [Type], |
| 3507 | c_longlong), |
| 3508 | |
| 3509 | ("clang_getFieldDeclBitWidth", |
| 3510 | [Cursor], |
| 3511 | c_int), |
| 3512 | |
| 3513 | ("clang_getCanonicalCursor", |
| 3514 | [Cursor], |
| 3515 | Cursor, |
| 3516 | Cursor.from_cursor_result), |
| 3517 | |
| 3518 | ("clang_getCanonicalType", |
| 3519 | [Type], |
| 3520 | Type, |
| 3521 | Type.from_result), |
| 3522 | |
| 3523 | ("clang_getChildDiagnostics", |
| 3524 | [Diagnostic], |
| 3525 | c_object_p), |
| 3526 | |
| 3527 | ("clang_getCompletionAvailability", |
| 3528 | [c_void_p], |
| 3529 | c_int), |
| 3530 | |
| 3531 | ("clang_getCompletionBriefComment", |
| 3532 | [c_void_p], |
| 3533 | _CXString, |
| 3534 | _CXString.from_result), |
| 3535 | |
| 3536 | ("clang_getCompletionChunkCompletionString", |
| 3537 | [c_void_p, c_int], |
| 3538 | c_object_p), |
| 3539 | |
| 3540 | ("clang_getCompletionChunkKind", |
| 3541 | [c_void_p, c_int], |
| 3542 | c_int), |
| 3543 | |
| 3544 | ("clang_getCompletionChunkText", |
| 3545 | [c_void_p, c_int], |
| 3546 | _CXString, |
| 3547 | _CXString.from_result), |
| 3548 | |
| 3549 | ("clang_getCompletionPriority", |
| 3550 | [c_void_p], |
| 3551 | c_int), |
| 3552 | |
| 3553 | ("clang_getCString", |
| 3554 | [_CXString], |
| 3555 | c_interop_string, |
| 3556 | c_interop_string.to_python_string), |
| 3557 | |
| 3558 | ("clang_getCursor", |
| 3559 | [TranslationUnit, SourceLocation], |
| 3560 | Cursor), |
| 3561 | |
| 3562 | ("clang_getCursorAvailability", |
| 3563 | [Cursor], |
| 3564 | c_int), |
| 3565 | |
| 3566 | ("clang_getCursorDefinition", |
| 3567 | [Cursor], |
| 3568 | Cursor, |
| 3569 | Cursor.from_result), |
| 3570 | |
| 3571 | ("clang_getCursorDisplayName", |
| 3572 | [Cursor], |
| 3573 | _CXString, |
| 3574 | _CXString.from_result), |
| 3575 | |
| 3576 | ("clang_getCursorExtent", |
| 3577 | [Cursor], |
| 3578 | SourceRange), |
| 3579 | |
| 3580 | ("clang_getCursorLexicalParent", |
| 3581 | [Cursor], |
| 3582 | Cursor, |
| 3583 | Cursor.from_cursor_result), |
| 3584 | |
| 3585 | ("clang_getCursorLocation", |
| 3586 | [Cursor], |
| 3587 | SourceLocation), |
| 3588 | |
| 3589 | ("clang_getCursorReferenced", |
| 3590 | [Cursor], |
| 3591 | Cursor, |
| 3592 | Cursor.from_result), |
| 3593 | |
| 3594 | ("clang_getCursorReferenceNameRange", |
| 3595 | [Cursor, c_uint, c_uint], |
| 3596 | SourceRange), |
| 3597 | |
| 3598 | ("clang_getCursorResultType", |
| 3599 | [Cursor], |
| 3600 | Type, |
| 3601 | Type.from_result), |
| 3602 | |
| 3603 | ("clang_getCursorSemanticParent", |
| 3604 | [Cursor], |
| 3605 | Cursor, |
| 3606 | Cursor.from_cursor_result), |
| 3607 | |
| 3608 | ("clang_getCursorSpelling", |
| 3609 | [Cursor], |
| 3610 | _CXString, |
| 3611 | _CXString.from_result), |
| 3612 | |
| 3613 | ("clang_getCursorType", |
| 3614 | [Cursor], |
| 3615 | Type, |
| 3616 | Type.from_result), |
| 3617 | |
| 3618 | ("clang_getCursorUSR", |
| 3619 | [Cursor], |
| 3620 | _CXString, |
| 3621 | _CXString.from_result), |
| 3622 | |
| 3623 | ("clang_Cursor_getMangling", |
| 3624 | [Cursor], |
| 3625 | _CXString, |
| 3626 | _CXString.from_result), |
| 3627 | |
| 3628 | # ("clang_getCXTUResourceUsage", |
| 3629 | # [TranslationUnit], |
| 3630 | # CXTUResourceUsage), |
| 3631 | |
| 3632 | ("clang_getCXXAccessSpecifier", |
| 3633 | [Cursor], |
| 3634 | c_uint), |
| 3635 | |
| 3636 | ("clang_getDeclObjCTypeEncoding", |
| 3637 | [Cursor], |
| 3638 | _CXString, |
| 3639 | _CXString.from_result), |
| 3640 | |
| 3641 | ("clang_getDiagnostic", |
| 3642 | [c_object_p, c_uint], |
| 3643 | c_object_p), |
| 3644 | |
| 3645 | ("clang_getDiagnosticCategory", |
| 3646 | [Diagnostic], |
| 3647 | c_uint), |
| 3648 | |
| 3649 | ("clang_getDiagnosticCategoryText", |
| 3650 | [Diagnostic], |
| 3651 | _CXString, |
| 3652 | _CXString.from_result), |
| 3653 | |
| 3654 | ("clang_getDiagnosticFixIt", |
| 3655 | [Diagnostic, c_uint, POINTER(SourceRange)], |
| 3656 | _CXString, |
| 3657 | _CXString.from_result), |
| 3658 | |
| 3659 | ("clang_getDiagnosticInSet", |
| 3660 | [c_object_p, c_uint], |
| 3661 | c_object_p), |
| 3662 | |
| 3663 | ("clang_getDiagnosticLocation", |
| 3664 | [Diagnostic], |
| 3665 | SourceLocation), |
| 3666 | |
| 3667 | ("clang_getDiagnosticNumFixIts", |
| 3668 | [Diagnostic], |
| 3669 | c_uint), |
| 3670 | |
| 3671 | ("clang_getDiagnosticNumRanges", |
| 3672 | [Diagnostic], |
| 3673 | c_uint), |
| 3674 | |
| 3675 | ("clang_getDiagnosticOption", |
| 3676 | [Diagnostic, POINTER(_CXString)], |
| 3677 | _CXString, |
| 3678 | _CXString.from_result), |
| 3679 | |
| 3680 | ("clang_getDiagnosticRange", |
| 3681 | [Diagnostic, c_uint], |
| 3682 | SourceRange), |
| 3683 | |
| 3684 | ("clang_getDiagnosticSeverity", |
| 3685 | [Diagnostic], |
| 3686 | c_int), |
| 3687 | |
| 3688 | ("clang_getDiagnosticSpelling", |
| 3689 | [Diagnostic], |
| 3690 | _CXString, |
| 3691 | _CXString.from_result), |
| 3692 | |
| 3693 | ("clang_getElementType", |
| 3694 | [Type], |
| 3695 | Type, |
| 3696 | Type.from_result), |
| 3697 | |
| 3698 | ("clang_getEnumConstantDeclUnsignedValue", |
| 3699 | [Cursor], |
| 3700 | c_ulonglong), |
| 3701 | |
| 3702 | ("clang_getEnumConstantDeclValue", |
| 3703 | [Cursor], |
| 3704 | c_longlong), |
| 3705 | |
| 3706 | ("clang_getEnumDeclIntegerType", |
| 3707 | [Cursor], |
| 3708 | Type, |
| 3709 | Type.from_result), |
| 3710 | |
| 3711 | ("clang_getFile", |
| 3712 | [TranslationUnit, c_interop_string], |
| 3713 | c_object_p), |
| 3714 | |
| 3715 | ("clang_getFileName", |
| 3716 | [File], |
| 3717 | _CXString, |
| 3718 | _CXString.from_result), |
| 3719 | |
| 3720 | ("clang_getFileTime", |
| 3721 | [File], |
| 3722 | c_uint), |
| 3723 | |
| 3724 | ("clang_getIBOutletCollectionType", |
| 3725 | [Cursor], |
| 3726 | Type, |
| 3727 | Type.from_result), |
| 3728 | |
| 3729 | ("clang_getIncludedFile", |
| 3730 | [Cursor], |
| 3731 | c_object_p, |
| 3732 | File.from_result), |
| 3733 | |
| 3734 | ("clang_getInclusions", |
| 3735 | [TranslationUnit, callbacks['translation_unit_includes'], py_object]), |
| 3736 | |
| 3737 | ("clang_getInstantiationLocation", |
| 3738 | [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint), |
| 3739 | POINTER(c_uint)]), |
| 3740 | |
| 3741 | ("clang_getLocation", |
| 3742 | [TranslationUnit, File, c_uint, c_uint], |
| 3743 | SourceLocation), |
| 3744 | |
| 3745 | ("clang_getLocationForOffset", |
| 3746 | [TranslationUnit, File, c_uint], |
| 3747 | SourceLocation), |
| 3748 | |
| 3749 | ("clang_getNullCursor", |
| 3750 | None, |
| 3751 | Cursor), |
| 3752 | |
| 3753 | ("clang_getNumArgTypes", |
| 3754 | [Type], |
| 3755 | c_uint), |
| 3756 | |
| 3757 | ("clang_getNumCompletionChunks", |
| 3758 | [c_void_p], |
| 3759 | c_int), |
| 3760 | |
| 3761 | ("clang_getNumDiagnostics", |
| 3762 | [c_object_p], |
| 3763 | c_uint), |
| 3764 | |
| 3765 | ("clang_getNumDiagnosticsInSet", |
| 3766 | [c_object_p], |
| 3767 | c_uint), |
| 3768 | |
| 3769 | ("clang_getNumElements", |
| 3770 | [Type], |
| 3771 | c_longlong), |
| 3772 | |
| 3773 | ("clang_getNumOverloadedDecls", |
| 3774 | [Cursor], |
| 3775 | c_uint), |
| 3776 | |
| 3777 | ("clang_getOverloadedDecl", |
| 3778 | [Cursor, c_uint], |
| 3779 | Cursor, |
| 3780 | Cursor.from_cursor_result), |
| 3781 | |
| 3782 | ("clang_getPointeeType", |
| 3783 | [Type], |
| 3784 | Type, |
| 3785 | Type.from_result), |
| 3786 | |
| 3787 | ("clang_getRange", |
| 3788 | [SourceLocation, SourceLocation], |
| 3789 | SourceRange), |
| 3790 | |
| 3791 | ("clang_getRangeEnd", |
| 3792 | [SourceRange], |
| 3793 | SourceLocation), |
| 3794 | |
| 3795 | ("clang_getRangeStart", |
| 3796 | [SourceRange], |
| 3797 | SourceLocation), |
| 3798 | |
| 3799 | ("clang_getResultType", |
| 3800 | [Type], |
| 3801 | Type, |
| 3802 | Type.from_result), |
| 3803 | |
| 3804 | ("clang_getSpecializedCursorTemplate", |
| 3805 | [Cursor], |
| 3806 | Cursor, |
| 3807 | Cursor.from_cursor_result), |
| 3808 | |
| 3809 | ("clang_getTemplateCursorKind", |
| 3810 | [Cursor], |
| 3811 | c_uint), |
| 3812 | |
| 3813 | ("clang_getTokenExtent", |
| 3814 | [TranslationUnit, Token], |
| 3815 | SourceRange), |
| 3816 | |
| 3817 | ("clang_getTokenKind", |
| 3818 | [Token], |
| 3819 | c_uint), |
| 3820 | |
| 3821 | ("clang_getTokenLocation", |
| 3822 | [TranslationUnit, Token], |
| 3823 | SourceLocation), |
| 3824 | |
| 3825 | ("clang_getTokenSpelling", |
| 3826 | [TranslationUnit, Token], |
| 3827 | _CXString, |
| 3828 | _CXString.from_result), |
| 3829 | |
| 3830 | ("clang_getTranslationUnitCursor", |
| 3831 | [TranslationUnit], |
| 3832 | Cursor, |
| 3833 | Cursor.from_result), |
| 3834 | |
| 3835 | ("clang_getTranslationUnitSpelling", |
| 3836 | [TranslationUnit], |
| 3837 | _CXString, |
| 3838 | _CXString.from_result), |
| 3839 | |
| 3840 | ("clang_getTUResourceUsageName", |
| 3841 | [c_uint], |
| 3842 | c_interop_string, |
| 3843 | c_interop_string.to_python_string), |
| 3844 | |
| 3845 | ("clang_getTypeDeclaration", |
| 3846 | [Type], |
| 3847 | Cursor, |
| 3848 | Cursor.from_result), |
| 3849 | |
| 3850 | ("clang_getTypedefDeclUnderlyingType", |
| 3851 | [Cursor], |
| 3852 | Type, |
| 3853 | Type.from_result), |
| 3854 | |
| 3855 | ("clang_getTypedefName", |
| 3856 | [Type], |
| 3857 | _CXString, |
| 3858 | _CXString.from_result), |
| 3859 | |
| 3860 | ("clang_getTypeKindSpelling", |
| 3861 | [c_uint], |
| 3862 | _CXString, |
| 3863 | _CXString.from_result), |
| 3864 | |
| 3865 | ("clang_getTypeSpelling", |
| 3866 | [Type], |
| 3867 | _CXString, |
| 3868 | _CXString.from_result), |
| 3869 | |
| 3870 | ("clang_hashCursor", |
| 3871 | [Cursor], |
| 3872 | c_uint), |
| 3873 | |
| 3874 | ("clang_isAttribute", |
| 3875 | [CursorKind], |
| 3876 | bool), |
| 3877 | |
| 3878 | ("clang_isConstQualifiedType", |
| 3879 | [Type], |
| 3880 | bool), |
| 3881 | |
| 3882 | ("clang_isCursorDefinition", |
| 3883 | [Cursor], |
| 3884 | bool), |
| 3885 | |
| 3886 | ("clang_isDeclaration", |
| 3887 | [CursorKind], |
| 3888 | bool), |
| 3889 | |
| 3890 | ("clang_isExpression", |
| 3891 | [CursorKind], |
| 3892 | bool), |
| 3893 | |
| 3894 | ("clang_isFileMultipleIncludeGuarded", |
| 3895 | [TranslationUnit, File], |
| 3896 | bool), |
| 3897 | |
| 3898 | ("clang_isFunctionTypeVariadic", |
| 3899 | [Type], |
| 3900 | bool), |
| 3901 | |
| 3902 | ("clang_isInvalid", |
| 3903 | [CursorKind], |
| 3904 | bool), |
| 3905 | |
| 3906 | ("clang_isPODType", |
| 3907 | [Type], |
| 3908 | bool), |
| 3909 | |
| 3910 | ("clang_isPreprocessing", |
| 3911 | [CursorKind], |
| 3912 | bool), |
| 3913 | |
| 3914 | ("clang_isReference", |
| 3915 | [CursorKind], |
| 3916 | bool), |
| 3917 | |
| 3918 | ("clang_isRestrictQualifiedType", |
| 3919 | [Type], |
| 3920 | bool), |
| 3921 | |
| 3922 | ("clang_isStatement", |
| 3923 | [CursorKind], |
| 3924 | bool), |
| 3925 | |
| 3926 | ("clang_isTranslationUnit", |
| 3927 | [CursorKind], |
| 3928 | bool), |
| 3929 | |
| 3930 | ("clang_isUnexposed", |
| 3931 | [CursorKind], |
| 3932 | bool), |
| 3933 | |
| 3934 | ("clang_isVirtualBase", |
| 3935 | [Cursor], |
| 3936 | bool), |
| 3937 | |
| 3938 | ("clang_isVolatileQualifiedType", |
| 3939 | [Type], |
| 3940 | bool), |
| 3941 | |
| 3942 | ("clang_parseTranslationUnit", |
| 3943 | [Index, c_interop_string, c_void_p, c_int, c_void_p, c_int, c_int], |
| 3944 | c_object_p), |
| 3945 | |
| 3946 | ("clang_reparseTranslationUnit", |
| 3947 | [TranslationUnit, c_int, c_void_p, c_int], |
| 3948 | c_int), |
| 3949 | |
| 3950 | ("clang_saveTranslationUnit", |
| 3951 | [TranslationUnit, c_interop_string, c_uint], |
| 3952 | c_int), |
| 3953 | |
| 3954 | ("clang_tokenize", |
| 3955 | [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]), |
| 3956 | |
| 3957 | ("clang_visitChildren", |
| 3958 | [Cursor, callbacks['cursor_visit'], py_object], |
| 3959 | c_uint), |
| 3960 | |
| 3961 | ("clang_Cursor_getNumArguments", |
| 3962 | [Cursor], |
| 3963 | c_int), |
| 3964 | |
| 3965 | ("clang_Cursor_getArgument", |
| 3966 | [Cursor, c_uint], |
| 3967 | Cursor, |
| 3968 | Cursor.from_result), |
| 3969 | |
| 3970 | ("clang_Cursor_getNumTemplateArguments", |
| 3971 | [Cursor], |
| 3972 | c_int), |
| 3973 | |
| 3974 | ("clang_Cursor_getTemplateArgumentKind", |
| 3975 | [Cursor, c_uint], |
| 3976 | TemplateArgumentKind.from_id), |
| 3977 | |
| 3978 | ("clang_Cursor_getTemplateArgumentType", |
| 3979 | [Cursor, c_uint], |
| 3980 | Type, |
| 3981 | Type.from_result), |
| 3982 | |
| 3983 | ("clang_Cursor_getTemplateArgumentValue", |
| 3984 | [Cursor, c_uint], |
| 3985 | c_longlong), |
| 3986 | |
| 3987 | ("clang_Cursor_getTemplateArgumentUnsignedValue", |
| 3988 | [Cursor, c_uint], |
| 3989 | c_ulonglong), |
| 3990 | |
| 3991 | ("clang_Cursor_isAnonymous", |
| 3992 | [Cursor], |
| 3993 | bool), |
| 3994 | |
| 3995 | ("clang_Cursor_isBitField", |
| 3996 | [Cursor], |
| 3997 | bool), |
| 3998 | |
| 3999 | ("clang_Cursor_getBriefCommentText", |
| 4000 | [Cursor], |
| 4001 | _CXString, |
| 4002 | _CXString.from_result), |
| 4003 | |
| 4004 | ("clang_Cursor_getRawCommentText", |
| 4005 | [Cursor], |
| 4006 | _CXString, |
| 4007 | _CXString.from_result), |
| 4008 | |
| 4009 | ("clang_Cursor_getOffsetOfField", |
| 4010 | [Cursor], |
| 4011 | c_longlong), |
| 4012 | |
| 4013 | ("clang_Type_getAlignOf", |
| 4014 | [Type], |
| 4015 | c_longlong), |
| 4016 | |
| 4017 | ("clang_Type_getClassType", |
| 4018 | [Type], |
| 4019 | Type, |
| 4020 | Type.from_result), |
| 4021 | |
| 4022 | ("clang_Type_getNumTemplateArguments", |
| 4023 | [Type], |
| 4024 | c_int), |
| 4025 | |
| 4026 | ("clang_Type_getTemplateArgumentAsType", |
| 4027 | [Type, c_uint], |
| 4028 | Type, |
| 4029 | Type.from_result), |
| 4030 | |
| 4031 | ("clang_Type_getOffsetOf", |
| 4032 | [Type, c_interop_string], |
| 4033 | c_longlong), |
| 4034 | |
| 4035 | ("clang_Type_getSizeOf", |
| 4036 | [Type], |
| 4037 | c_longlong), |
| 4038 | |
| 4039 | ("clang_Type_getCXXRefQualifier", |
| 4040 | [Type], |
| 4041 | c_uint), |
| 4042 | |
| 4043 | ("clang_Type_getNamedType", |
| 4044 | [Type], |
| 4045 | Type, |
| 4046 | Type.from_result), |
| 4047 | |
| 4048 | ("clang_Type_visitFields", |
| 4049 | [Type, callbacks['fields_visit'], py_object], |
| 4050 | c_uint), |
| 4051 | ] |
| 4052 | |
| 4053 | class LibclangError(Exception): |
| 4054 | def __init__(self, message): |
| 4055 | self.m = message |
| 4056 | |
| 4057 | def __str__(self): |
| 4058 | return self.m |
| 4059 | |
| 4060 | def register_function(lib, item, ignore_errors): |
| 4061 | # A function may not exist, if these bindings are used with an older or |
| 4062 | # incompatible version of libclang.so. |
| 4063 | try: |
| 4064 | func = getattr(lib, item[0]) |
| 4065 | except AttributeError as e: |
| 4066 | msg = str(e) + ". Please ensure that your python bindings are "\ |
| 4067 | "compatible with your libclang.so version." |
| 4068 | if ignore_errors: |
| 4069 | return |
| 4070 | raise LibclangError(msg) |
| 4071 | |
| 4072 | if len(item) >= 2: |
| 4073 | func.argtypes = item[1] |
| 4074 | |
| 4075 | if len(item) >= 3: |
| 4076 | func.restype = item[2] |
| 4077 | |
| 4078 | if len(item) == 4: |
| 4079 | func.errcheck = item[3] |
| 4080 | |
| 4081 | def register_functions(lib, ignore_errors): |
| 4082 | """Register function prototypes with a libclang library instance. |
| 4083 | |
| 4084 | This must be called as part of library instantiation so Python knows how |
| 4085 | to call out to the shared library. |
| 4086 | """ |
| 4087 | |
| 4088 | def register(item): |
| 4089 | return register_function(lib, item, ignore_errors) |
| 4090 | |
| 4091 | for f in functionList: |
| 4092 | register(f) |
| 4093 | |
| 4094 | class Config(object): |
| 4095 | library_path = None |
| 4096 | library_file = None |
| 4097 | compatibility_check = True |
| 4098 | loaded = False |
| 4099 | |
| 4100 | @staticmethod |
| 4101 | def set_library_path(path): |
| 4102 | """Set the path in which to search for libclang""" |
| 4103 | if Config.loaded: |
| 4104 | raise Exception("library path must be set before before using " \ |
| 4105 | "any other functionalities in libclang.") |
| 4106 | |
| 4107 | Config.library_path = fspath(path) |
| 4108 | |
| 4109 | @staticmethod |
| 4110 | def set_library_file(filename): |
| 4111 | """Set the exact location of libclang""" |
| 4112 | if Config.loaded: |
| 4113 | raise Exception("library file must be set before before using " \ |
| 4114 | "any other functionalities in libclang.") |
| 4115 | |
| 4116 | Config.library_file = fspath(filename) |
| 4117 | |
| 4118 | @staticmethod |
| 4119 | def set_compatibility_check(check_status): |
| 4120 | """ Perform compatibility check when loading libclang |
| 4121 | |
| 4122 | The python bindings are only tested and evaluated with the version of |
| 4123 | libclang they are provided with. To ensure correct behavior a (limited) |
| 4124 | compatibility check is performed when loading the bindings. This check |
| 4125 | will throw an exception, as soon as it fails. |
| 4126 | |
| 4127 | In case these bindings are used with an older version of libclang, parts |
| 4128 | that have been stable between releases may still work. Users of the |
| 4129 | python bindings can disable the compatibility check. This will cause |
| 4130 | the python bindings to load, even though they are written for a newer |
| 4131 | version of libclang. Failures now arise if unsupported or incompatible |
| 4132 | features are accessed. The user is required to test themselves if the |
| 4133 | features they are using are available and compatible between different |
| 4134 | libclang versions. |
| 4135 | """ |
| 4136 | if Config.loaded: |
| 4137 | raise Exception("compatibility_check must be set before before " \ |
| 4138 | "using any other functionalities in libclang.") |
| 4139 | |
| 4140 | Config.compatibility_check = check_status |
| 4141 | |
| 4142 | @CachedProperty |
| 4143 | def lib(self): |
| 4144 | lib = self.get_cindex_library() |
| 4145 | register_functions(lib, not Config.compatibility_check) |
| 4146 | Config.loaded = True |
| 4147 | return lib |
| 4148 | |
| 4149 | def get_filename(self): |
| 4150 | if Config.library_file: |
| 4151 | return Config.library_file |
| 4152 | |
| 4153 | import platform |
| 4154 | name = platform.system() |
| 4155 | |
| 4156 | if name == 'Darwin': |
| 4157 | file = 'libclang.dylib' |
| 4158 | elif name == 'Windows': |
| 4159 | file = 'libclang.dll' |
| 4160 | else: |
| 4161 | file = 'libclang.so' |
| 4162 | |
| 4163 | if Config.library_path: |
| 4164 | file = Config.library_path + '/' + file |
| 4165 | |
| 4166 | return file |
| 4167 | |
| 4168 | def get_cindex_library(self): |
| 4169 | try: |
| 4170 | library = cdll.LoadLibrary(self.get_filename()) |
| 4171 | except OSError as e: |
| 4172 | msg = str(e) + ". To provide a path to libclang use " \ |
| 4173 | "Config.set_library_path() or " \ |
| 4174 | "Config.set_library_file()." |
| 4175 | raise LibclangError(msg) |
| 4176 | |
| 4177 | return library |
| 4178 | |
| 4179 | def function_exists(self, name): |
| 4180 | try: |
| 4181 | getattr(self.lib, name) |
| 4182 | except AttributeError: |
| 4183 | return False |
| 4184 | |
| 4185 | return True |
| 4186 | |
| 4187 | def register_enumerations(): |
| 4188 | for name, value in clang.enumerations.TokenKinds: |
| 4189 | TokenKind.register(value, name) |
| 4190 | |
| 4191 | conf = Config() |
| 4192 | register_enumerations() |
| 4193 | |
| 4194 | __all__ = [ |
| 4195 | 'AvailabilityKind', |
| 4196 | 'Config', |
| 4197 | 'CodeCompletionResults', |
| 4198 | 'CompilationDatabase', |
| 4199 | 'CompileCommands', |
| 4200 | 'CompileCommand', |
| 4201 | 'CursorKind', |
| 4202 | 'Cursor', |
| 4203 | 'Diagnostic', |
| 4204 | 'File', |
| 4205 | 'FixIt', |
| 4206 | 'Index', |
| 4207 | 'LinkageKind', |
| 4208 | 'SourceLocation', |
| 4209 | 'SourceRange', |
| 4210 | 'TLSKind', |
| 4211 | 'TokenKind', |
| 4212 | 'Token', |
| 4213 | 'TranslationUnitLoadError', |
| 4214 | 'TranslationUnit', |
| 4215 | 'TypeKind', |
| 4216 | 'Type', |
| 4217 | ] |
| 4218 | |