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 9r""" 10Clang Indexing Library Bindings 11=============================== 12 13This module provides an interface to the Clang indexing library. It is a 14low-level interface to the indexing library which attempts to match the Clang 15API directly while also being "pythonic". Notable differences from the C API 16are: 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 24The 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 43Most object information is exposed using properties, when the underlying API 44call is efficient. 45""" 46from __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 65from ctypes import * 66 67import clang.enumerations 68 69import os 70import sys 71if 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 111elif 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 127if sys.version_info[:2] >= (3, 7): 128 from collections import abc as collections_abc 129else: 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. 135try: 136 fspath = os.fspath 137except 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**. 145c_object_p = POINTER(c_void_p) 146 147callbacks = {} 148 149### Exception Classes ### 150 151class 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 161class 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 193class 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 218class _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 232class 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 303class 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 367class 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 504class 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 518class 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 573class 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 ### 611class 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 657class 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. 719CursorKind.UNEXPOSED_DECL = CursorKind(1) 720 721# A C or C++ struct. 722CursorKind.STRUCT_DECL = CursorKind(2) 723 724# A C or C++ union. 725CursorKind.UNION_DECL = CursorKind(3) 726 727# A C++ class. 728CursorKind.CLASS_DECL = CursorKind(4) 729 730# An enumeration. 731CursorKind.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. 735CursorKind.FIELD_DECL = CursorKind(6) 736 737# An enumerator constant. 738CursorKind.ENUM_CONSTANT_DECL = CursorKind(7) 739 740# A function. 741CursorKind.FUNCTION_DECL = CursorKind(8) 742 743# A variable. 744CursorKind.VAR_DECL = CursorKind(9) 745 746# A function or method parameter. 747CursorKind.PARM_DECL = CursorKind(10) 748 749# An Objective-C @interface. 750CursorKind.OBJC_INTERFACE_DECL = CursorKind(11) 751 752# An Objective-C @interface for a category. 753CursorKind.OBJC_CATEGORY_DECL = CursorKind(12) 754 755# An Objective-C @protocol declaration. 756CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13) 757 758# An Objective-C @property declaration. 759CursorKind.OBJC_PROPERTY_DECL = CursorKind(14) 760 761# An Objective-C instance variable. 762CursorKind.OBJC_IVAR_DECL = CursorKind(15) 763 764# An Objective-C instance method. 765CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16) 766 767# An Objective-C class method. 768CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17) 769 770# An Objective-C @implementation. 771CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18) 772 773# An Objective-C @implementation for a category. 774CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19) 775 776# A typedef. 777CursorKind.TYPEDEF_DECL = CursorKind(20) 778 779# A C++ class method. 780CursorKind.CXX_METHOD = CursorKind(21) 781 782# A C++ namespace. 783CursorKind.NAMESPACE = CursorKind(22) 784 785# A linkage specification, e.g. 'extern "C"'. 786CursorKind.LINKAGE_SPEC = CursorKind(23) 787 788# A C++ constructor. 789CursorKind.CONSTRUCTOR = CursorKind(24) 790 791# A C++ destructor. 792CursorKind.DESTRUCTOR = CursorKind(25) 793 794# A C++ conversion function. 795CursorKind.CONVERSION_FUNCTION = CursorKind(26) 796 797# A C++ template type parameter 798CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27) 799 800# A C++ non-type template parameter. 801CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28) 802 803# A C++ template template parameter. 804CursorKind.TEMPLATE_TEMPLATE_PARAMETER = CursorKind(29) 805 806# A C++ function template. 807CursorKind.FUNCTION_TEMPLATE = CursorKind(30) 808 809# A C++ class template. 810CursorKind.CLASS_TEMPLATE = CursorKind(31) 811 812# A C++ class template partial specialization. 813CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32) 814 815# A C++ namespace alias declaration. 816CursorKind.NAMESPACE_ALIAS = CursorKind(33) 817 818# A C++ using directive 819CursorKind.USING_DIRECTIVE = CursorKind(34) 820 821# A C++ using declaration 822CursorKind.USING_DECLARATION = CursorKind(35) 823 824# A Type alias decl. 825CursorKind.TYPE_ALIAS_DECL = CursorKind(36) 826 827# A Objective-C synthesize decl 828CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37) 829 830# A Objective-C dynamic decl 831CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38) 832 833# A C++ access specifier decl. 834CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39) 835 836 837### 838# Reference Kinds 839 840CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40) 841CursorKind.OBJC_PROTOCOL_REF = CursorKind(41) 842CursorKind.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. 854CursorKind.TYPE_REF = CursorKind(43) 855CursorKind.CXX_BASE_SPECIFIER = CursorKind(44) 856 857# A reference to a class template, function template, template 858# template parameter, or class template partial specialization. 859CursorKind.TEMPLATE_REF = CursorKind(45) 860 861# A reference to a namespace or namepsace alias. 862CursorKind.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. 866CursorKind.MEMBER_REF = CursorKind(47) 867 868# A reference to a labeled statement. 869CursorKind.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. 873CursorKind.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. 877CursorKind.VARIABLE_REF = CursorKind(50) 878 879### 880# Invalid/Error Kinds 881 882CursorKind.INVALID_FILE = CursorKind(70) 883CursorKind.NO_DECL_FOUND = CursorKind(71) 884CursorKind.NOT_IMPLEMENTED = CursorKind(72) 885CursorKind.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. 895CursorKind.UNEXPOSED_EXPR = CursorKind(100) 896 897# An expression that refers to some value declaration, such as a function, 898# variable, or enumerator. 899CursorKind.DECL_REF_EXPR = CursorKind(101) 900 901# An expression that refers to a member of a struct, union, class, Objective-C 902# class, etc. 903CursorKind.MEMBER_REF_EXPR = CursorKind(102) 904 905# An expression that calls a function. 906CursorKind.CALL_EXPR = CursorKind(103) 907 908# An expression that sends a message to an Objective-C object or class. 909CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104) 910 911# An expression that represents a block literal. 912CursorKind.BLOCK_EXPR = CursorKind(105) 913 914# An integer literal. 915CursorKind.INTEGER_LITERAL = CursorKind(106) 916 917# A floating point number literal. 918CursorKind.FLOATING_LITERAL = CursorKind(107) 919 920# An imaginary number literal. 921CursorKind.IMAGINARY_LITERAL = CursorKind(108) 922 923# A string literal. 924CursorKind.STRING_LITERAL = CursorKind(109) 925 926# A character literal. 927CursorKind.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. 932CursorKind.PAREN_EXPR = CursorKind(111) 933 934# This represents the unary-expression's (except sizeof and 935# alignof). 936CursorKind.UNARY_OPERATOR = CursorKind(112) 937 938# [C99 6.5.2.1] Array Subscripting. 939CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113) 940 941# A builtin binary operation expression such as "x + y" or 942# "x <= y". 943CursorKind.BINARY_OPERATOR = CursorKind(114) 944 945# Compound assignment such as "+=". 946CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115) 947 948# The ?: ternary operator. 949CursorKind.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. 955CursorKind.CSTYLE_CAST_EXPR = CursorKind(117) 956 957# [C99 6.5.2.5] 958CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118) 959 960# Describes an C or C++ initializer list. 961CursorKind.INIT_LIST_EXPR = CursorKind(119) 962 963# The GNU address of label extension, representing &&label. 964CursorKind.ADDR_LABEL_EXPR = CursorKind(120) 965 966# This is the GNU Statement Expression extension: ({int X=4; X;}) 967CursorKind.StmtExpr = CursorKind(121) 968 969# Represents a C11 generic selection. 970CursorKind.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). 979CursorKind.GNU_NULL_EXPR = CursorKind(123) 980 981# C++'s static_cast<> expression. 982CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124) 983 984# C++'s dynamic_cast<> expression. 985CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125) 986 987# C++'s reinterpret_cast<> expression. 988CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126) 989 990# C++'s const_cast<> expression. 991CursorKind.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 1000CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128) 1001 1002# A C++ typeid expression (C++ [expr.typeid]). 1003CursorKind.CXX_TYPEID_EXPR = CursorKind(129) 1004 1005# [C++ 2.13.5] C++ Boolean Literal. 1006CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130) 1007 1008# [C++0x 2.14.7] C++ Pointer Literal. 1009CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131) 1010 1011# Represents the "this" expression in C++ 1012CursorKind.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. 1018CursorKind.CXX_THROW_EXPR = CursorKind(133) 1019 1020# A new expression for memory allocation and constructor calls, e.g: 1021# "new CXXNewExpr(foo)". 1022CursorKind.CXX_NEW_EXPR = CursorKind(134) 1023 1024# A delete expression for memory deallocation and destructor calls, 1025# e.g. "delete[] pArray". 1026CursorKind.CXX_DELETE_EXPR = CursorKind(135) 1027 1028# Represents a unary expression. 1029CursorKind.CXX_UNARY_EXPR = CursorKind(136) 1030 1031# ObjCStringLiteral, used for Objective-C string literals i.e. "foo". 1032CursorKind.OBJC_STRING_LITERAL = CursorKind(137) 1033 1034# ObjCEncodeExpr, used for in Objective-C. 1035CursorKind.OBJC_ENCODE_EXPR = CursorKind(138) 1036 1037# ObjCSelectorExpr used for in Objective-C. 1038CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139) 1039 1040# Objective-C's protocol expression. 1041CursorKind.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 1049CursorKind.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: 1056CursorKind.PACK_EXPANSION_EXPR = CursorKind(142) 1057 1058# Represents an expression that computes the length of a parameter 1059# pack. 1060CursorKind.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 1073CursorKind.LAMBDA_EXPR = CursorKind(144) 1074 1075# Objective-c Boolean Literal. 1076CursorKind.OBJ_BOOL_LITERAL_EXPR = CursorKind(145) 1077 1078# Represents the "self" expression in a ObjC method. 1079CursorKind.OBJ_SELF_EXPR = CursorKind(146) 1080 1081# OpenMP 4.0 [2.4, Array Section]. 1082CursorKind.OMP_ARRAY_SECTION_EXPR = CursorKind(147) 1083 1084# Represents an @available(...) check. 1085CursorKind.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. 1093CursorKind.UNEXPOSED_STMT = CursorKind(200) 1094 1095# A labelled statement in a function. 1096CursorKind.LABEL_STMT = CursorKind(201) 1097 1098# A compound statement 1099CursorKind.COMPOUND_STMT = CursorKind(202) 1100 1101# A case statement. 1102CursorKind.CASE_STMT = CursorKind(203) 1103 1104# A default statement. 1105CursorKind.DEFAULT_STMT = CursorKind(204) 1106 1107# An if statement. 1108CursorKind.IF_STMT = CursorKind(205) 1109 1110# A switch statement. 1111CursorKind.SWITCH_STMT = CursorKind(206) 1112 1113# A while statement. 1114CursorKind.WHILE_STMT = CursorKind(207) 1115 1116# A do statement. 1117CursorKind.DO_STMT = CursorKind(208) 1118 1119# A for statement. 1120CursorKind.FOR_STMT = CursorKind(209) 1121 1122# A goto statement. 1123CursorKind.GOTO_STMT = CursorKind(210) 1124 1125# An indirect goto statement. 1126CursorKind.INDIRECT_GOTO_STMT = CursorKind(211) 1127 1128# A continue statement. 1129CursorKind.CONTINUE_STMT = CursorKind(212) 1130 1131# A break statement. 1132CursorKind.BREAK_STMT = CursorKind(213) 1133 1134# A return statement. 1135CursorKind.RETURN_STMT = CursorKind(214) 1136 1137# A GNU-style inline assembler statement. 1138CursorKind.ASM_STMT = CursorKind(215) 1139 1140# Objective-C's overall @try-@catch-@finally statement. 1141CursorKind.OBJC_AT_TRY_STMT = CursorKind(216) 1142 1143# Objective-C's @catch statement. 1144CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217) 1145 1146# Objective-C's @finally statement. 1147CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218) 1148 1149# Objective-C's @throw statement. 1150CursorKind.OBJC_AT_THROW_STMT = CursorKind(219) 1151 1152# Objective-C's @synchronized statement. 1153CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220) 1154 1155# Objective-C's autorealease pool statement. 1156CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221) 1157 1158# Objective-C's for collection statement. 1159CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222) 1160 1161# C++'s catch statement. 1162CursorKind.CXX_CATCH_STMT = CursorKind(223) 1163 1164# C++'s try statement. 1165CursorKind.CXX_TRY_STMT = CursorKind(224) 1166 1167# C++'s for (* : *) statement. 1168CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225) 1169 1170# Windows Structured Exception Handling's try statement. 1171CursorKind.SEH_TRY_STMT = CursorKind(226) 1172 1173# Windows Structured Exception Handling's except statement. 1174CursorKind.SEH_EXCEPT_STMT = CursorKind(227) 1175 1176# Windows Structured Exception Handling's finally statement. 1177CursorKind.SEH_FINALLY_STMT = CursorKind(228) 1178 1179# A MS inline assembly statement extension. 1180CursorKind.MS_ASM_STMT = CursorKind(229) 1181 1182# The null statement. 1183CursorKind.NULL_STMT = CursorKind(230) 1184 1185# Adaptor class for mixing declarations with statements and expressions. 1186CursorKind.DECL_STMT = CursorKind(231) 1187 1188# OpenMP parallel directive. 1189CursorKind.OMP_PARALLEL_DIRECTIVE = CursorKind(232) 1190 1191# OpenMP SIMD directive. 1192CursorKind.OMP_SIMD_DIRECTIVE = CursorKind(233) 1193 1194# OpenMP for directive. 1195CursorKind.OMP_FOR_DIRECTIVE = CursorKind(234) 1196 1197# OpenMP sections directive. 1198CursorKind.OMP_SECTIONS_DIRECTIVE = CursorKind(235) 1199 1200# OpenMP section directive. 1201CursorKind.OMP_SECTION_DIRECTIVE = CursorKind(236) 1202 1203# OpenMP single directive. 1204CursorKind.OMP_SINGLE_DIRECTIVE = CursorKind(237) 1205 1206# OpenMP parallel for directive. 1207CursorKind.OMP_PARALLEL_FOR_DIRECTIVE = CursorKind(238) 1208 1209# OpenMP parallel sections directive. 1210CursorKind.OMP_PARALLEL_SECTIONS_DIRECTIVE = CursorKind(239) 1211 1212# OpenMP task directive. 1213CursorKind.OMP_TASK_DIRECTIVE = CursorKind(240) 1214 1215# OpenMP master directive. 1216CursorKind.OMP_MASTER_DIRECTIVE = CursorKind(241) 1217 1218# OpenMP critical directive. 1219CursorKind.OMP_CRITICAL_DIRECTIVE = CursorKind(242) 1220 1221# OpenMP taskyield directive. 1222CursorKind.OMP_TASKYIELD_DIRECTIVE = CursorKind(243) 1223 1224# OpenMP barrier directive. 1225CursorKind.OMP_BARRIER_DIRECTIVE = CursorKind(244) 1226 1227# OpenMP taskwait directive. 1228CursorKind.OMP_TASKWAIT_DIRECTIVE = CursorKind(245) 1229 1230# OpenMP flush directive. 1231CursorKind.OMP_FLUSH_DIRECTIVE = CursorKind(246) 1232 1233# Windows Structured Exception Handling's leave statement. 1234CursorKind.SEH_LEAVE_STMT = CursorKind(247) 1235 1236# OpenMP ordered directive. 1237CursorKind.OMP_ORDERED_DIRECTIVE = CursorKind(248) 1238 1239# OpenMP atomic directive. 1240CursorKind.OMP_ATOMIC_DIRECTIVE = CursorKind(249) 1241 1242# OpenMP for SIMD directive. 1243CursorKind.OMP_FOR_SIMD_DIRECTIVE = CursorKind(250) 1244 1245# OpenMP parallel for SIMD directive. 1246CursorKind.OMP_PARALLELFORSIMD_DIRECTIVE = CursorKind(251) 1247 1248# OpenMP target directive. 1249CursorKind.OMP_TARGET_DIRECTIVE = CursorKind(252) 1250 1251# OpenMP teams directive. 1252CursorKind.OMP_TEAMS_DIRECTIVE = CursorKind(253) 1253 1254# OpenMP taskgroup directive. 1255CursorKind.OMP_TASKGROUP_DIRECTIVE = CursorKind(254) 1256 1257# OpenMP cancellation point directive. 1258CursorKind.OMP_CANCELLATION_POINT_DIRECTIVE = CursorKind(255) 1259 1260# OpenMP cancel directive. 1261CursorKind.OMP_CANCEL_DIRECTIVE = CursorKind(256) 1262 1263# OpenMP target data directive. 1264CursorKind.OMP_TARGET_DATA_DIRECTIVE = CursorKind(257) 1265 1266# OpenMP taskloop directive. 1267CursorKind.OMP_TASK_LOOP_DIRECTIVE = CursorKind(258) 1268 1269# OpenMP taskloop simd directive. 1270CursorKind.OMP_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(259) 1271 1272# OpenMP distribute directive. 1273CursorKind.OMP_DISTRIBUTE_DIRECTIVE = CursorKind(260) 1274 1275# OpenMP target enter data directive. 1276CursorKind.OMP_TARGET_ENTER_DATA_DIRECTIVE = CursorKind(261) 1277 1278# OpenMP target exit data directive. 1279CursorKind.OMP_TARGET_EXIT_DATA_DIRECTIVE = CursorKind(262) 1280 1281# OpenMP target parallel directive. 1282CursorKind.OMP_TARGET_PARALLEL_DIRECTIVE = CursorKind(263) 1283 1284# OpenMP target parallel for directive. 1285CursorKind.OMP_TARGET_PARALLELFOR_DIRECTIVE = CursorKind(264) 1286 1287# OpenMP target update directive. 1288CursorKind.OMP_TARGET_UPDATE_DIRECTIVE = CursorKind(265) 1289 1290# OpenMP distribute parallel for directive. 1291CursorKind.OMP_DISTRIBUTE_PARALLELFOR_DIRECTIVE = CursorKind(266) 1292 1293# OpenMP distribute parallel for simd directive. 1294CursorKind.OMP_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(267) 1295 1296# OpenMP distribute simd directive. 1297CursorKind.OMP_DISTRIBUTE_SIMD_DIRECTIVE = CursorKind(268) 1298 1299# OpenMP target parallel for simd directive. 1300CursorKind.OMP_TARGET_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(269) 1301 1302# OpenMP target simd directive. 1303CursorKind.OMP_TARGET_SIMD_DIRECTIVE = CursorKind(270) 1304 1305# OpenMP teams distribute directive. 1306CursorKind.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. 1315CursorKind.TRANSLATION_UNIT = CursorKind(300) 1316 1317### 1318# Attributes 1319 1320# An attribute whoe specific kind is note exposed via this interface 1321CursorKind.UNEXPOSED_ATTR = CursorKind(400) 1322 1323CursorKind.IB_ACTION_ATTR = CursorKind(401) 1324CursorKind.IB_OUTLET_ATTR = CursorKind(402) 1325CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403) 1326 1327CursorKind.CXX_FINAL_ATTR = CursorKind(404) 1328CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405) 1329CursorKind.ANNOTATE_ATTR = CursorKind(406) 1330CursorKind.ASM_LABEL_ATTR = CursorKind(407) 1331CursorKind.PACKED_ATTR = CursorKind(408) 1332CursorKind.PURE_ATTR = CursorKind(409) 1333CursorKind.CONST_ATTR = CursorKind(410) 1334CursorKind.NODUPLICATE_ATTR = CursorKind(411) 1335CursorKind.CUDACONSTANT_ATTR = CursorKind(412) 1336CursorKind.CUDADEVICE_ATTR = CursorKind(413) 1337CursorKind.CUDAGLOBAL_ATTR = CursorKind(414) 1338CursorKind.CUDAHOST_ATTR = CursorKind(415) 1339CursorKind.CUDASHARED_ATTR = CursorKind(416) 1340 1341CursorKind.VISIBILITY_ATTR = CursorKind(417) 1342 1343CursorKind.DLLEXPORT_ATTR = CursorKind(418) 1344CursorKind.DLLIMPORT_ATTR = CursorKind(419) 1345CursorKind.CONVERGENT_ATTR = CursorKind(438) 1346CursorKind.WARN_UNUSED_ATTR = CursorKind(439) 1347CursorKind.WARN_UNUSED_RESULT_ATTR = CursorKind(440) 1348CursorKind.ALIGNED_ATTR = CursorKind(441) 1349 1350### 1351# Preprocessing 1352CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500) 1353CursorKind.MACRO_DEFINITION = CursorKind(501) 1354CursorKind.MACRO_INSTANTIATION = CursorKind(502) 1355CursorKind.INCLUSION_DIRECTIVE = CursorKind(503) 1356 1357### 1358# Extra declaration 1359 1360# A module import declaration. 1361CursorKind.MODULE_IMPORT_DECL = CursorKind(600) 1362# A type alias template declaration 1363CursorKind.TYPE_ALIAS_TEMPLATE_DECL = CursorKind(601) 1364# A static_assert or _Static_assert node 1365CursorKind.STATIC_ASSERT = CursorKind(602) 1366# A friend declaration 1367CursorKind.FRIEND_DECL = CursorKind(603) 1368 1369# A code completion overload candidate. 1370CursorKind.OVERLOAD_CANDIDATE = CursorKind(700) 1371 1372### Template Argument Kinds ### 1373class 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 1383TemplateArgumentKind.NULL = TemplateArgumentKind(0) 1384TemplateArgumentKind.TYPE = TemplateArgumentKind(1) 1385TemplateArgumentKind.DECLARATION = TemplateArgumentKind(2) 1386TemplateArgumentKind.NULLPTR = TemplateArgumentKind(3) 1387TemplateArgumentKind.INTEGRAL = TemplateArgumentKind(4) 1388 1389### Exception Specification Kinds ### 1390class 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 1403ExceptionSpecificationKind.NONE = ExceptionSpecificationKind(0) 1404ExceptionSpecificationKind.DYNAMIC_NONE = ExceptionSpecificationKind(1) 1405ExceptionSpecificationKind.DYNAMIC = ExceptionSpecificationKind(2) 1406ExceptionSpecificationKind.MS_ANY = ExceptionSpecificationKind(3) 1407ExceptionSpecificationKind.BASIC_NOEXCEPT = ExceptionSpecificationKind(4) 1408ExceptionSpecificationKind.COMPUTED_NOEXCEPT = ExceptionSpecificationKind(5) 1409ExceptionSpecificationKind.UNEVALUATED = ExceptionSpecificationKind(6) 1410ExceptionSpecificationKind.UNINSTANTIATED = ExceptionSpecificationKind(7) 1411ExceptionSpecificationKind.UNPARSED = ExceptionSpecificationKind(8) 1412 1413### Cursors ### 1414 1415class 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 1920class 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 1960StorageClass.INVALID = StorageClass(0) 1961StorageClass.NONE = StorageClass(1) 1962StorageClass.EXTERN = StorageClass(2) 1963StorageClass.STATIC = StorageClass(3) 1964StorageClass.PRIVATEEXTERN = StorageClass(4) 1965StorageClass.OPENCLWORKGROUPLOCAL = StorageClass(5) 1966StorageClass.AUTO = StorageClass(6) 1967StorageClass.REGISTER = StorageClass(7) 1968 1969### Availability Kinds ### 1970 1971class 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 1983AvailabilityKind.AVAILABLE = AvailabilityKind(0) 1984AvailabilityKind.DEPRECATED = AvailabilityKind(1) 1985AvailabilityKind.NOT_AVAILABLE = AvailabilityKind(2) 1986AvailabilityKind.NOT_ACCESSIBLE = AvailabilityKind(3) 1987 1988### C++ access specifiers ### 1989 1990class 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 2005AccessSpecifier.INVALID = AccessSpecifier(0) 2006AccessSpecifier.PUBLIC = AccessSpecifier(1) 2007AccessSpecifier.PROTECTED = AccessSpecifier(2) 2008AccessSpecifier.PRIVATE = AccessSpecifier(3) 2009AccessSpecifier.NONE = AccessSpecifier(4) 2010 2011### Type Kinds ### 2012 2013class 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 2030TypeKind.INVALID = TypeKind(0) 2031TypeKind.UNEXPOSED = TypeKind(1) 2032TypeKind.VOID = TypeKind(2) 2033TypeKind.BOOL = TypeKind(3) 2034TypeKind.CHAR_U = TypeKind(4) 2035TypeKind.UCHAR = TypeKind(5) 2036TypeKind.CHAR16 = TypeKind(6) 2037TypeKind.CHAR32 = TypeKind(7) 2038TypeKind.USHORT = TypeKind(8) 2039TypeKind.UINT = TypeKind(9) 2040TypeKind.ULONG = TypeKind(10) 2041TypeKind.ULONGLONG = TypeKind(11) 2042TypeKind.UINT128 = TypeKind(12) 2043TypeKind.CHAR_S = TypeKind(13) 2044TypeKind.SCHAR = TypeKind(14) 2045TypeKind.WCHAR = TypeKind(15) 2046TypeKind.SHORT = TypeKind(16) 2047TypeKind.INT = TypeKind(17) 2048TypeKind.LONG = TypeKind(18) 2049TypeKind.LONGLONG = TypeKind(19) 2050TypeKind.INT128 = TypeKind(20) 2051TypeKind.FLOAT = TypeKind(21) 2052TypeKind.DOUBLE = TypeKind(22) 2053TypeKind.LONGDOUBLE = TypeKind(23) 2054TypeKind.NULLPTR = TypeKind(24) 2055TypeKind.OVERLOAD = TypeKind(25) 2056TypeKind.DEPENDENT = TypeKind(26) 2057TypeKind.OBJCID = TypeKind(27) 2058TypeKind.OBJCCLASS = TypeKind(28) 2059TypeKind.OBJCSEL = TypeKind(29) 2060TypeKind.FLOAT128 = TypeKind(30) 2061TypeKind.HALF = TypeKind(31) 2062TypeKind.COMPLEX = TypeKind(100) 2063TypeKind.POINTER = TypeKind(101) 2064TypeKind.BLOCKPOINTER = TypeKind(102) 2065TypeKind.LVALUEREFERENCE = TypeKind(103) 2066TypeKind.RVALUEREFERENCE = TypeKind(104) 2067TypeKind.RECORD = TypeKind(105) 2068TypeKind.ENUM = TypeKind(106) 2069TypeKind.TYPEDEF = TypeKind(107) 2070TypeKind.OBJCINTERFACE = TypeKind(108) 2071TypeKind.OBJCOBJECTPOINTER = TypeKind(109) 2072TypeKind.FUNCTIONNOPROTO = TypeKind(110) 2073TypeKind.FUNCTIONPROTO = TypeKind(111) 2074TypeKind.CONSTANTARRAY = TypeKind(112) 2075TypeKind.VECTOR = TypeKind(113) 2076TypeKind.INCOMPLETEARRAY = TypeKind(114) 2077TypeKind.VARIABLEARRAY = TypeKind(115) 2078TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116) 2079TypeKind.MEMBERPOINTER = TypeKind(117) 2080TypeKind.AUTO = TypeKind(118) 2081TypeKind.ELABORATED = TypeKind(119) 2082TypeKind.PIPE = TypeKind(120) 2083TypeKind.OCLIMAGE1DRO = TypeKind(121) 2084TypeKind.OCLIMAGE1DARRAYRO = TypeKind(122) 2085TypeKind.OCLIMAGE1DBUFFERRO = TypeKind(123) 2086TypeKind.OCLIMAGE2DRO = TypeKind(124) 2087TypeKind.OCLIMAGE2DARRAYRO = TypeKind(125) 2088TypeKind.OCLIMAGE2DDEPTHRO = TypeKind(126) 2089TypeKind.OCLIMAGE2DARRAYDEPTHRO = TypeKind(127) 2090TypeKind.OCLIMAGE2DMSAARO = TypeKind(128) 2091TypeKind.OCLIMAGE2DARRAYMSAARO = TypeKind(129) 2092TypeKind.OCLIMAGE2DMSAADEPTHRO = TypeKind(130) 2093TypeKind.OCLIMAGE2DARRAYMSAADEPTHRO = TypeKind(131) 2094TypeKind.OCLIMAGE3DRO = TypeKind(132) 2095TypeKind.OCLIMAGE1DWO = TypeKind(133) 2096TypeKind.OCLIMAGE1DARRAYWO = TypeKind(134) 2097TypeKind.OCLIMAGE1DBUFFERWO = TypeKind(135) 2098TypeKind.OCLIMAGE2DWO = TypeKind(136) 2099TypeKind.OCLIMAGE2DARRAYWO = TypeKind(137) 2100TypeKind.OCLIMAGE2DDEPTHWO = TypeKind(138) 2101TypeKind.OCLIMAGE2DARRAYDEPTHWO = TypeKind(139) 2102TypeKind.OCLIMAGE2DMSAAWO = TypeKind(140) 2103TypeKind.OCLIMAGE2DARRAYMSAAWO = TypeKind(141) 2104TypeKind.OCLIMAGE2DMSAADEPTHWO = TypeKind(142) 2105TypeKind.OCLIMAGE2DARRAYMSAADEPTHWO = TypeKind(143) 2106TypeKind.OCLIMAGE3DWO = TypeKind(144) 2107TypeKind.OCLIMAGE1DRW = TypeKind(145) 2108TypeKind.OCLIMAGE1DARRAYRW = TypeKind(146) 2109TypeKind.OCLIMAGE1DBUFFERRW = TypeKind(147) 2110TypeKind.OCLIMAGE2DRW = TypeKind(148) 2111TypeKind.OCLIMAGE2DARRAYRW = TypeKind(149) 2112TypeKind.OCLIMAGE2DDEPTHRW = TypeKind(150) 2113TypeKind.OCLIMAGE2DARRAYDEPTHRW = TypeKind(151) 2114TypeKind.OCLIMAGE2DMSAARW = TypeKind(152) 2115TypeKind.OCLIMAGE2DARRAYMSAARW = TypeKind(153) 2116TypeKind.OCLIMAGE2DMSAADEPTHRW = TypeKind(154) 2117TypeKind.OCLIMAGE2DARRAYMSAADEPTHRW = TypeKind(155) 2118TypeKind.OCLIMAGE3DRW = TypeKind(156) 2119TypeKind.OCLSAMPLER = TypeKind(157) 2120TypeKind.OCLEVENT = TypeKind(158) 2121TypeKind.OCLQUEUE = TypeKind(159) 2122TypeKind.OCLRESERVEID = TypeKind(160) 2123 2124TypeKind.EXTVECTOR = TypeKind(176) 2125 2126class RefQualifierKind(BaseEnumeration): 2127 """Describes a specific ref-qualifier of a type.""" 2128 2129 # The unique kind objects, indexed by id. 2130 _kinds = [] 2131 _name_map = None 2132 2133 def from_param(self): 2134 return self.value 2135 2136 def __repr__(self): 2137 return 'RefQualifierKind.%s' % (self.name,) 2138 2139RefQualifierKind.NONE = RefQualifierKind(0) 2140RefQualifierKind.LVALUE = RefQualifierKind(1) 2141RefQualifierKind.RVALUE = RefQualifierKind(2) 2142 2143class LinkageKind(BaseEnumeration): 2144 """Describes the kind of linkage of a cursor.""" 2145 2146 # The unique kind objects, indexed by id. 2147 _kinds = [] 2148 _name_map = None 2149 2150 def from_param(self): 2151 return self.value 2152 2153 def __repr__(self): 2154 return 'LinkageKind.%s' % (self.name,) 2155 2156LinkageKind.INVALID = LinkageKind(0) 2157LinkageKind.NO_LINKAGE = LinkageKind(1) 2158LinkageKind.INTERNAL = LinkageKind(2) 2159LinkageKind.UNIQUE_EXTERNAL = LinkageKind(3) 2160LinkageKind.EXTERNAL = LinkageKind(4) 2161 2162class TLSKind(BaseEnumeration): 2163 """Describes the kind of thread-local storage (TLS) of a cursor.""" 2164 2165 # The unique kind objects, indexed by id. 2166 _kinds = [] 2167 _name_map = None 2168 2169 def from_param(self): 2170 return self.value 2171 2172 def __repr__(self): 2173 return 'TLSKind.%s' % (self.name,) 2174 2175TLSKind.NONE = TLSKind(0) 2176TLSKind.DYNAMIC = TLSKind(1) 2177TLSKind.STATIC = TLSKind(2) 2178 2179class Type(Structure): 2180 """ 2181 The type of an element in the abstract syntax tree. 2182 """ 2183 _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)] 2184 2185 @property 2186 def kind(self): 2187 """Return the kind of this type.""" 2188 return TypeKind.from_id(self._kind_id) 2189 2190 def argument_types(self): 2191 """Retrieve a container for the non-variadic arguments for this type. 2192 2193 The returned object is iterable and indexable. Each item in the 2194 container is a Type instance. 2195 """ 2196 class ArgumentsIterator(collections_abc.Sequence): 2197 def __init__(self, parent): 2198 self.parent = parent 2199 self.length = None 2200 2201 def __len__(self): 2202 if self.length is None: 2203 self.length = conf.lib.clang_getNumArgTypes(self.parent) 2204 2205 return self.length 2206 2207 def __getitem__(self, key): 2208 # FIXME Support slice objects. 2209 if not isinstance(key, int): 2210 raise TypeError("Must supply a non-negative int.") 2211 2212 if key < 0: 2213 raise IndexError("Only non-negative indexes are accepted.") 2214 2215 if key >= len(self): 2216 raise IndexError("Index greater than container length: " 2217 "%d > %d" % ( key, len(self) )) 2218 2219 result = conf.lib.clang_getArgType(self.parent, key) 2220 if result.kind == TypeKind.INVALID: 2221 raise IndexError("Argument could not be retrieved.") 2222 2223 return result 2224 2225 assert self.kind == TypeKind.FUNCTIONPROTO 2226 return ArgumentsIterator(self) 2227 2228 @property 2229 def element_type(self): 2230 """Retrieve the Type of elements within this Type. 2231 2232 If accessed on a type that is not an array, complex, or vector type, an 2233 exception will be raised. 2234 """ 2235 result = conf.lib.clang_getElementType(self) 2236 if result.kind == TypeKind.INVALID: 2237 raise Exception('Element type not available on this type.') 2238 2239 return result 2240 2241 @property 2242 def element_count(self): 2243 """Retrieve the number of elements in this type. 2244 2245 Returns an int. 2246 2247 If the Type is not an array or vector, this raises. 2248 """ 2249 result = conf.lib.clang_getNumElements(self) 2250 if result < 0: 2251 raise Exception('Type does not have elements.') 2252 2253 return result 2254 2255 @property 2256 def translation_unit(self): 2257 """The TranslationUnit to which this Type is associated.""" 2258 # If this triggers an AttributeError, the instance was not properly 2259 # instantiated. 2260 return self._tu 2261 2262 @staticmethod 2263 def from_result(res, fn, args): 2264 assert isinstance(res, Type) 2265 2266 tu = None 2267 for arg in args: 2268 if hasattr(arg, 'translation_unit'): 2269 tu = arg.translation_unit 2270 break 2271 2272 assert tu is not None 2273 res._tu = tu 2274 2275 return res 2276 2277 def get_num_template_arguments(self): 2278 return conf.lib.clang_Type_getNumTemplateArguments(self) 2279 2280 def get_template_argument_type(self, num): 2281 return conf.lib.clang_Type_getTemplateArgumentAsType(self, num) 2282 2283 def get_canonical(self): 2284 """ 2285 Return the canonical type for a Type. 2286 2287 Clang's type system explicitly models typedefs and all the 2288 ways a specific type can be represented. The canonical type 2289 is the underlying type with all the "sugar" removed. For 2290 example, if 'T' is a typedef for 'int', the canonical type for 2291 'T' would be 'int'. 2292 """ 2293 return conf.lib.clang_getCanonicalType(self) 2294 2295 def is_const_qualified(self): 2296 """Determine whether a Type has the "const" qualifier set. 2297 2298 This does not look through typedefs that may have added "const" 2299 at a different level. 2300 """ 2301 return conf.lib.clang_isConstQualifiedType(self) 2302 2303 def is_volatile_qualified(self): 2304 """Determine whether a Type has the "volatile" qualifier set. 2305 2306 This does not look through typedefs that may have added "volatile" 2307 at a different level. 2308 """ 2309 return conf.lib.clang_isVolatileQualifiedType(self) 2310 2311 def is_restrict_qualified(self): 2312 """Determine whether a Type has the "restrict" qualifier set. 2313 2314 This does not look through typedefs that may have added "restrict" at 2315 a different level. 2316 """ 2317 return conf.lib.clang_isRestrictQualifiedType(self) 2318 2319 def is_function_variadic(self): 2320 """Determine whether this function Type is a variadic function type.""" 2321 assert self.kind == TypeKind.FUNCTIONPROTO 2322 2323 return conf.lib.clang_isFunctionTypeVariadic(self) 2324 2325 def get_address_space(self): 2326 return conf.lib.clang_getAddressSpace(self) 2327 2328 def get_typedef_name(self): 2329 return conf.lib.clang_getTypedefName(self) 2330 2331 def is_pod(self): 2332 """Determine whether this Type represents plain old data (POD).""" 2333 return conf.lib.clang_isPODType(self) 2334 2335 def get_pointee(self): 2336 """ 2337 For pointer types, returns the type of the pointee. 2338 """ 2339 return conf.lib.clang_getPointeeType(self) 2340 2341 def get_declaration(self): 2342 """ 2343 Return the cursor for the declaration of the given type. 2344 """ 2345 return conf.lib.clang_getTypeDeclaration(self) 2346 2347 def get_result(self): 2348 """ 2349 Retrieve the result type associated with a function type. 2350 """ 2351 return conf.lib.clang_getResultType(self) 2352 2353 def get_array_element_type(self): 2354 """ 2355 Retrieve the type of the elements of the array type. 2356 """ 2357 return conf.lib.clang_getArrayElementType(self) 2358 2359 def get_array_size(self): 2360 """ 2361 Retrieve the size of the constant array. 2362 """ 2363 return conf.lib.clang_getArraySize(self) 2364 2365 def get_class_type(self): 2366 """ 2367 Retrieve the class type of the member pointer type. 2368 """ 2369 return conf.lib.clang_Type_getClassType(self) 2370 2371 def get_named_type(self): 2372 """ 2373 Retrieve the type named by the qualified-id. 2374 """ 2375 return conf.lib.clang_Type_getNamedType(self) 2376 2377 def get_align(self): 2378 """ 2379 Retrieve the alignment of the record. 2380 """ 2381 return conf.lib.clang_Type_getAlignOf(self) 2382 2383 def get_size(self): 2384 """ 2385 Retrieve the size of the record. 2386 """ 2387 return conf.lib.clang_Type_getSizeOf(self) 2388 2389 def get_offset(self, fieldname): 2390 """ 2391 Retrieve the offset of a field in the record. 2392 """ 2393 return conf.lib.clang_Type_getOffsetOf(self, fieldname) 2394 2395 def get_ref_qualifier(self): 2396 """ 2397 Retrieve the ref-qualifier of the type. 2398 """ 2399 return RefQualifierKind.from_id( 2400 conf.lib.clang_Type_getCXXRefQualifier(self)) 2401 2402 def get_fields(self): 2403 """Return an iterator for accessing the fields of this type.""" 2404 2405 def visitor(field, children): 2406 assert field != conf.lib.clang_getNullCursor() 2407 2408 # Create reference to TU so it isn't GC'd before Cursor. 2409 field._tu = self._tu 2410 fields.append(field) 2411 return 1 # continue 2412 fields = [] 2413 conf.lib.clang_Type_visitFields(self, 2414 callbacks['fields_visit'](visitor), fields) 2415 return iter(fields) 2416 2417 def get_exception_specification_kind(self): 2418 """ 2419 Return the kind of the exception specification; a value from 2420 the ExceptionSpecificationKind enumeration. 2421 """ 2422 return ExceptionSpecificationKind.from_id( 2423 conf.lib.clang.getExceptionSpecificationType(self)) 2424 2425 @property 2426 def spelling(self): 2427 """Retrieve the spelling of this Type.""" 2428 return conf.lib.clang_getTypeSpelling(self) 2429 2430 def __eq__(self, other): 2431 if type(other) != type(self): 2432 return False 2433 2434 return conf.lib.clang_equalTypes(self, other) 2435 2436 def __ne__(self, other): 2437 return not self.__eq__(other) 2438 2439## CIndex Objects ## 2440 2441# CIndex objects (derived from ClangObject) are essentially lightweight 2442# wrappers attached to some underlying object, which is exposed via CIndex as 2443# a void*. 2444 2445class ClangObject(object): 2446 """ 2447 A helper for Clang objects. This class helps act as an intermediary for 2448 the ctypes library and the Clang CIndex library. 2449 """ 2450 def __init__(self, obj): 2451 assert isinstance(obj, c_object_p) and obj 2452 self.obj = self._as_parameter_ = obj 2453 2454 def from_param(self): 2455 return self._as_parameter_ 2456 2457 2458class _CXUnsavedFile(Structure): 2459 """Helper for passing unsaved file arguments.""" 2460 _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)] 2461 2462# Functions calls through the python interface are rather slow. Fortunately, 2463# for most symboles, we do not need to perform a function call. Their spelling 2464# never changes and is consequently provided by this spelling cache. 2465SpellingCache = { 2466 # 0: CompletionChunk.Kind("Optional"), 2467 # 1: CompletionChunk.Kind("TypedText"), 2468 # 2: CompletionChunk.Kind("Text"), 2469 # 3: CompletionChunk.Kind("Placeholder"), 2470 # 4: CompletionChunk.Kind("Informative"), 2471 # 5 : CompletionChunk.Kind("CurrentParameter"), 2472 6: '(', # CompletionChunk.Kind("LeftParen"), 2473 7: ')', # CompletionChunk.Kind("RightParen"), 2474 8: '[', # CompletionChunk.Kind("LeftBracket"), 2475 9: ']', # CompletionChunk.Kind("RightBracket"), 2476 10: '{', # CompletionChunk.Kind("LeftBrace"), 2477 11: '}', # CompletionChunk.Kind("RightBrace"), 2478 12: '<', # CompletionChunk.Kind("LeftAngle"), 2479 13: '>', # CompletionChunk.Kind("RightAngle"), 2480 14: ', ', # CompletionChunk.Kind("Comma"), 2481 # 15: CompletionChunk.Kind("ResultType"), 2482 16: ':', # CompletionChunk.Kind("Colon"), 2483 17: ';', # CompletionChunk.Kind("SemiColon"), 2484 18: '=', # CompletionChunk.Kind("Equal"), 2485 19: ' ', # CompletionChunk.Kind("HorizontalSpace"), 2486 # 20: CompletionChunk.Kind("VerticalSpace") 2487} 2488 2489class CompletionChunk(object): 2490 class Kind(object): 2491 def __init__(self, name): 2492 self.name = name 2493 2494 def __str__(self): 2495 return self.name 2496 2497 def __repr__(self): 2498 return "<ChunkKind: %s>" % self 2499 2500 def __init__(self, completionString, key): 2501 self.cs = completionString 2502 self.key = key 2503 self.__kindNumberCache = -1 2504 2505 def __repr__(self): 2506 return "{'" + self.spelling + "', " + str(self.kind) + "}" 2507 2508 @CachedProperty 2509 def spelling(self): 2510 if self.__kindNumber in SpellingCache: 2511 return SpellingCache[self.__kindNumber] 2512 return conf.lib.clang_getCompletionChunkText(self.cs, self.key) 2513 2514 # We do not use @CachedProperty here, as the manual implementation is 2515 # apparently still significantly faster. Please profile carefully if you 2516 # would like to add CachedProperty back. 2517 @property 2518 def __kindNumber(self): 2519 if self.__kindNumberCache == -1: 2520 self.__kindNumberCache = \ 2521 conf.lib.clang_getCompletionChunkKind(self.cs, self.key) 2522 return self.__kindNumberCache 2523 2524 @CachedProperty 2525 def kind(self): 2526 return completionChunkKindMap[self.__kindNumber] 2527 2528 @CachedProperty 2529 def string(self): 2530 res = conf.lib.clang_getCompletionChunkCompletionString(self.cs, 2531 self.key) 2532 2533 if (res): 2534 return CompletionString(res) 2535 else: 2536 None 2537 2538 def isKindOptional(self): 2539 return self.__kindNumber == 0 2540 2541 def isKindTypedText(self): 2542 return self.__kindNumber == 1 2543 2544 def isKindPlaceHolder(self): 2545 return self.__kindNumber == 3 2546 2547 def isKindInformative(self): 2548 return self.__kindNumber == 4 2549 2550 def isKindResultType(self): 2551 return self.__kindNumber == 15 2552 2553completionChunkKindMap = { 2554 0: CompletionChunk.Kind("Optional"), 2555 1: CompletionChunk.Kind("TypedText"), 2556 2: CompletionChunk.Kind("Text"), 2557 3: CompletionChunk.Kind("Placeholder"), 2558 4: CompletionChunk.Kind("Informative"), 2559 5: CompletionChunk.Kind("CurrentParameter"), 2560 6: CompletionChunk.Kind("LeftParen"), 2561 7: CompletionChunk.Kind("RightParen"), 2562 8: CompletionChunk.Kind("LeftBracket"), 2563 9: CompletionChunk.Kind("RightBracket"), 2564 10: CompletionChunk.Kind("LeftBrace"), 2565 11: CompletionChunk.Kind("RightBrace"), 2566 12: CompletionChunk.Kind("LeftAngle"), 2567 13: CompletionChunk.Kind("RightAngle"), 2568 14: CompletionChunk.Kind("Comma"), 2569 15: CompletionChunk.Kind("ResultType"), 2570 16: CompletionChunk.Kind("Colon"), 2571 17: CompletionChunk.Kind("SemiColon"), 2572 18: CompletionChunk.Kind("Equal"), 2573 19: CompletionChunk.Kind("HorizontalSpace"), 2574 20: CompletionChunk.Kind("VerticalSpace")} 2575 2576class CompletionString(ClangObject): 2577 class Availability(object): 2578 def __init__(self, name): 2579 self.name = name 2580 2581 def __str__(self): 2582 return self.name 2583 2584 def __repr__(self): 2585 return "<Availability: %s>" % self 2586 2587 def __len__(self): 2588 return self.num_chunks 2589 2590 @CachedProperty 2591 def num_chunks(self): 2592 return conf.lib.clang_getNumCompletionChunks(self.obj) 2593 2594 def __getitem__(self, key): 2595 if self.num_chunks <= key: 2596 raise IndexError 2597 return CompletionChunk(self.obj, key) 2598 2599 @property 2600 def priority(self): 2601 return conf.lib.clang_getCompletionPriority(self.obj) 2602 2603 @property 2604 def availability(self): 2605 res = conf.lib.clang_getCompletionAvailability(self.obj) 2606 return availabilityKinds[res] 2607 2608 @property 2609 def briefComment(self): 2610 if conf.function_exists("clang_getCompletionBriefComment"): 2611 return conf.lib.clang_getCompletionBriefComment(self.obj) 2612 return _CXString() 2613 2614 def __repr__(self): 2615 return " | ".join([str(a) for a in self]) \ 2616 + " || Priority: " + str(self.priority) \ 2617 + " || Availability: " + str(self.availability) \ 2618 + " || Brief comment: " + str(self.briefComment) 2619 2620availabilityKinds = { 2621 0: CompletionChunk.Kind("Available"), 2622 1: CompletionChunk.Kind("Deprecated"), 2623 2: CompletionChunk.Kind("NotAvailable"), 2624 3: CompletionChunk.Kind("NotAccessible")} 2625 2626class CodeCompletionResult(Structure): 2627 _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)] 2628 2629 def __repr__(self): 2630 return str(CompletionString(self.completionString)) 2631 2632 @property 2633 def kind(self): 2634 return CursorKind.from_id(self.cursorKind) 2635 2636 @property 2637 def string(self): 2638 return CompletionString(self.completionString) 2639 2640class CCRStructure(Structure): 2641 _fields_ = [('results', POINTER(CodeCompletionResult)), 2642 ('numResults', c_int)] 2643 2644 def __len__(self): 2645 return self.numResults 2646 2647 def __getitem__(self, key): 2648 if len(self) <= key: 2649 raise IndexError 2650 2651 return self.results[key] 2652 2653class CodeCompletionResults(ClangObject): 2654 def __init__(self, ptr): 2655 assert isinstance(ptr, POINTER(CCRStructure)) and ptr 2656 self.ptr = self._as_parameter_ = ptr 2657 2658 def from_param(self): 2659 return self._as_parameter_ 2660 2661 def __del__(self): 2662 conf.lib.clang_disposeCodeCompleteResults(self) 2663 2664 @property 2665 def results(self): 2666 return self.ptr.contents 2667 2668 @property 2669 def diagnostics(self): 2670 class DiagnosticsItr(object): 2671 def __init__(self, ccr): 2672 self.ccr= ccr 2673 2674 def __len__(self): 2675 return int(\ 2676 conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr)) 2677 2678 def __getitem__(self, key): 2679 return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key) 2680 2681 return DiagnosticsItr(self) 2682 2683 2684class Index(ClangObject): 2685 """ 2686 The Index type provides the primary interface to the Clang CIndex library, 2687 primarily by providing an interface for reading and parsing translation 2688 units. 2689 """ 2690 2691 @staticmethod 2692 def create(excludeDecls=False): 2693 """ 2694 Create a new Index. 2695 Parameters: 2696 excludeDecls -- Exclude local declarations from translation units. 2697 """ 2698 return Index(conf.lib.clang_createIndex(excludeDecls, 0)) 2699 2700 def __del__(self): 2701 conf.lib.clang_disposeIndex(self) 2702 2703 def read(self, path): 2704 """Load a TranslationUnit from the given AST file.""" 2705 return TranslationUnit.from_ast_file(path, self) 2706 2707 def parse(self, path, args=None, unsaved_files=None, options = 0): 2708 """Load the translation unit from the given source code file by running 2709 clang and generating the AST before loading. Additional command line 2710 parameters can be passed to clang via the args parameter. 2711 2712 In-memory contents for files can be provided by passing a list of pairs 2713 to as unsaved_files, the first item should be the filenames to be mapped 2714 and the second should be the contents to be substituted for the 2715 file. The contents may be passed as strings or file objects. 2716 2717 If an error was encountered during parsing, a TranslationUnitLoadError 2718 will be raised. 2719 """ 2720 return TranslationUnit.from_source(path, args, unsaved_files, options, 2721 self) 2722 2723class TranslationUnit(ClangObject): 2724 """Represents a source code translation unit. 2725 2726 This is one of the main types in the API. Any time you wish to interact 2727 with Clang's representation of a source file, you typically start with a 2728 translation unit. 2729 """ 2730 2731 # Default parsing mode. 2732 PARSE_NONE = 0 2733 2734 # Instruct the parser to create a detailed processing record containing 2735 # metadata not normally retained. 2736 PARSE_DETAILED_PROCESSING_RECORD = 1 2737 2738 # Indicates that the translation unit is incomplete. This is typically used 2739 # when parsing headers. 2740 PARSE_INCOMPLETE = 2 2741 2742 # Instruct the parser to create a pre-compiled preamble for the translation 2743 # unit. This caches the preamble (included files at top of source file). 2744 # This is useful if the translation unit will be reparsed and you don't 2745 # want to incur the overhead of reparsing the preamble. 2746 PARSE_PRECOMPILED_PREAMBLE = 4 2747 2748 # Cache code completion information on parse. This adds time to parsing but 2749 # speeds up code completion. 2750 PARSE_CACHE_COMPLETION_RESULTS = 8 2751 2752 # Flags with values 16 and 32 are deprecated and intentionally omitted. 2753 2754 # Do not parse function bodies. This is useful if you only care about 2755 # searching for declarations/definitions. 2756 PARSE_SKIP_FUNCTION_BODIES = 64 2757 2758 # Used to indicate that brief documentation comments should be included 2759 # into the set of code completions returned from this translation unit. 2760 PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128 2761 2762 @classmethod 2763 def from_source(cls, filename, args=None, unsaved_files=None, options=0, 2764 index=None): 2765 """Create a TranslationUnit by parsing source. 2766 2767 This is capable of processing source code both from files on the 2768 filesystem as well as in-memory contents. 2769 2770 Command-line arguments that would be passed to clang are specified as 2771 a list via args. These can be used to specify include paths, warnings, 2772 etc. e.g. ["-Wall", "-I/path/to/include"]. 2773 2774 In-memory file content can be provided via unsaved_files. This is an 2775 iterable of 2-tuples. The first element is the filename (str or 2776 PathLike). The second element defines the content. Content can be 2777 provided as str source code or as file objects (anything with a read() 2778 method). If a file object is being used, content will be read until EOF 2779 and the read cursor will not be reset to its original position. 2780 2781 options is a bitwise or of TranslationUnit.PARSE_XXX flags which will 2782 control parsing behavior. 2783 2784 index is an Index instance to utilize. If not provided, a new Index 2785 will be created for this TranslationUnit. 2786 2787 To parse source from the filesystem, the filename of the file to parse 2788 is specified by the filename argument. Or, filename could be None and 2789 the args list would contain the filename(s) to parse. 2790 2791 To parse source from an in-memory buffer, set filename to the virtual 2792 filename you wish to associate with this source (e.g. "test.c"). The 2793 contents of that file are then provided in unsaved_files. 2794 2795 If an error occurs, a TranslationUnitLoadError is raised. 2796 2797 Please note that a TranslationUnit with parser errors may be returned. 2798 It is the caller's responsibility to check tu.diagnostics for errors. 2799 2800 Also note that Clang infers the source language from the extension of 2801 the input filename. If you pass in source code containing a C++ class 2802 declaration with the filename "test.c" parsing will fail. 2803 """ 2804 if args is None: 2805 args = [] 2806 2807 if unsaved_files is None: 2808 unsaved_files = [] 2809 2810 if index is None: 2811 index = Index.create() 2812 2813 args_array = None 2814 if len(args) > 0: 2815 args_array = (c_char_p * len(args))(*[b(x) for x in args]) 2816 2817 unsaved_array = None 2818 if len(unsaved_files) > 0: 2819 unsaved_array = (_CXUnsavedFile * len(unsaved_files))() 2820 for i, (name, contents) in enumerate(unsaved_files): 2821 if hasattr(contents, "read"): 2822 contents = contents.read() 2823 contents = b(contents) 2824 unsaved_array[i].name = b(fspath(name)) 2825 unsaved_array[i].contents = contents 2826 unsaved_array[i].length = len(contents) 2827 2828 ptr = conf.lib.clang_parseTranslationUnit(index, 2829 fspath(filename) if filename is not None else None, 2830 args_array, 2831 len(args), unsaved_array, 2832 len(unsaved_files), options) 2833 2834 if not ptr: 2835 raise TranslationUnitLoadError("Error parsing translation unit.") 2836 2837 return cls(ptr, index=index) 2838 2839 @classmethod 2840 def from_ast_file(cls, filename, index=None): 2841 """Create a TranslationUnit instance from a saved AST file. 2842 2843 A previously-saved AST file (provided with -emit-ast or 2844 TranslationUnit.save()) is loaded from the filename specified. 2845 2846 If the file cannot be loaded, a TranslationUnitLoadError will be 2847 raised. 2848 2849 index is optional and is the Index instance to use. If not provided, 2850 a default Index will be created. 2851 2852 filename can be str or PathLike. 2853 """ 2854 if index is None: 2855 index = Index.create() 2856 2857 ptr = conf.lib.clang_createTranslationUnit(index, fspath(filename)) 2858 if not ptr: 2859 raise TranslationUnitLoadError(filename) 2860 2861 return cls(ptr=ptr, index=index) 2862 2863 def __init__(self, ptr, index): 2864 """Create a TranslationUnit instance. 2865 2866 TranslationUnits should be created using one of the from_* @classmethod 2867 functions above. __init__ is only called internally. 2868 """ 2869 assert isinstance(index, Index) 2870 self.index = index 2871 ClangObject.__init__(self, ptr) 2872 2873 def __del__(self): 2874 conf.lib.clang_disposeTranslationUnit(self) 2875 2876 @property 2877 def cursor(self): 2878 """Retrieve the cursor that represents the given translation unit.""" 2879 return conf.lib.clang_getTranslationUnitCursor(self) 2880 2881 @property 2882 def spelling(self): 2883 """Get the original translation unit source file name.""" 2884 return conf.lib.clang_getTranslationUnitSpelling(self) 2885 2886 def get_includes(self): 2887 """ 2888 Return an iterable sequence of FileInclusion objects that describe the 2889 sequence of inclusions in a translation unit. The first object in 2890 this sequence is always the input file. Note that this method will not 2891 recursively iterate over header files included through precompiled 2892 headers. 2893 """ 2894 def visitor(fobj, lptr, depth, includes): 2895 if depth > 0: 2896 loc = lptr.contents 2897 includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) 2898 2899 # Automatically adapt CIndex/ctype pointers to python objects 2900 includes = [] 2901 conf.lib.clang_getInclusions(self, 2902 callbacks['translation_unit_includes'](visitor), includes) 2903 2904 return iter(includes) 2905 2906 def get_file(self, filename): 2907 """Obtain a File from this translation unit.""" 2908 2909 return File.from_name(self, filename) 2910 2911 def get_location(self, filename, position): 2912 """Obtain a SourceLocation for a file in this translation unit. 2913 2914 The position can be specified by passing: 2915 2916 - Integer file offset. Initial file offset is 0. 2917 - 2-tuple of (line number, column number). Initial file position is 2918 (0, 0) 2919 """ 2920 f = self.get_file(filename) 2921 2922 if isinstance(position, int): 2923 return SourceLocation.from_offset(self, f, position) 2924 2925 return SourceLocation.from_position(self, f, position[0], position[1]) 2926 2927 def get_extent(self, filename, locations): 2928 """Obtain a SourceRange from this translation unit. 2929 2930 The bounds of the SourceRange must ultimately be defined by a start and 2931 end SourceLocation. For the locations argument, you can pass: 2932 2933 - 2 SourceLocation instances in a 2-tuple or list. 2934 - 2 int file offsets via a 2-tuple or list. 2935 - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. 2936 2937 e.g. 2938 2939 get_extent('foo.c', (5, 10)) 2940 get_extent('foo.c', ((1, 1), (1, 15))) 2941 """ 2942 f = self.get_file(filename) 2943 2944 if len(locations) < 2: 2945 raise Exception('Must pass object with at least 2 elements') 2946 2947 start_location, end_location = locations 2948 2949 if hasattr(start_location, '__len__'): 2950 start_location = SourceLocation.from_position(self, f, 2951 start_location[0], start_location[1]) 2952 elif isinstance(start_location, int): 2953 start_location = SourceLocation.from_offset(self, f, 2954 start_location) 2955 2956 if hasattr(end_location, '__len__'): 2957 end_location = SourceLocation.from_position(self, f, 2958 end_location[0], end_location[1]) 2959 elif isinstance(end_location, int): 2960 end_location = SourceLocation.from_offset(self, f, end_location) 2961 2962 assert isinstance(start_location, SourceLocation) 2963 assert isinstance(end_location, SourceLocation) 2964 2965 return SourceRange.from_locations(start_location, end_location) 2966 2967 @property 2968 def diagnostics(self): 2969 """ 2970 Return an iterable (and indexable) object containing the diagnostics. 2971 """ 2972 class DiagIterator(object): 2973 def __init__(self, tu): 2974 self.tu = tu 2975 2976 def __len__(self): 2977 return int(conf.lib.clang_getNumDiagnostics(self.tu)) 2978 2979 def __getitem__(self, key): 2980 diag = conf.lib.clang_getDiagnostic(self.tu, key) 2981 if not diag: 2982 raise IndexError 2983 return Diagnostic(diag) 2984 2985 return DiagIterator(self) 2986 2987 def reparse(self, unsaved_files=None, options=0): 2988 """ 2989 Reparse an already parsed translation unit. 2990 2991 In-memory contents for files can be provided by passing a list of pairs 2992 as unsaved_files, the first items should be the filenames to be mapped 2993 and the second should be the contents to be substituted for the 2994 file. The contents may be passed as strings or file objects. 2995 """ 2996 if unsaved_files is None: 2997 unsaved_files = [] 2998 2999 unsaved_files_array = 0 3000 if len(unsaved_files): 3001 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() 3002 for i,(name,contents) in enumerate(unsaved_files): 3003 if hasattr(contents, "read"): 3004 contents = contents.read() 3005 contents = b(contents) 3006 unsaved_files_array[i].name = b(fspath(name)) 3007 unsaved_files_array[i].contents = contents 3008 unsaved_files_array[i].length = len(contents) 3009 ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files), 3010 unsaved_files_array, options) 3011 3012 def save(self, filename): 3013 """Saves the TranslationUnit to a file. 3014 3015 This is equivalent to passing -emit-ast to the clang frontend. The 3016 saved file can be loaded back into a TranslationUnit. Or, if it 3017 corresponds to a header, it can be used as a pre-compiled header file. 3018 3019 If an error occurs while saving, a TranslationUnitSaveError is raised. 3020 If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means 3021 the constructed TranslationUnit was not valid at time of save. In this 3022 case, the reason(s) why should be available via 3023 TranslationUnit.diagnostics(). 3024 3025 filename -- The path to save the translation unit to (str or PathLike). 3026 """ 3027 options = conf.lib.clang_defaultSaveOptions(self) 3028 result = int(conf.lib.clang_saveTranslationUnit(self, fspath(filename), 3029 options)) 3030 if result != 0: 3031 raise TranslationUnitSaveError(result, 3032 'Error saving TranslationUnit.') 3033 3034 def codeComplete(self, path, line, column, unsaved_files=None, 3035 include_macros=False, include_code_patterns=False, 3036 include_brief_comments=False): 3037 """ 3038 Code complete in this translation unit. 3039 3040 In-memory contents for files can be provided by passing a list of pairs 3041 as unsaved_files, the first items should be the filenames to be mapped 3042 and the second should be the contents to be substituted for the 3043 file. The contents may be passed as strings or file objects. 3044 """ 3045 options = 0 3046 3047 if include_macros: 3048 options += 1 3049 3050 if include_code_patterns: 3051 options += 2 3052 3053 if include_brief_comments: 3054 options += 4 3055 3056 if unsaved_files is None: 3057 unsaved_files = [] 3058 3059 unsaved_files_array = 0 3060 if len(unsaved_files): 3061 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() 3062 for i,(name,contents) in enumerate(unsaved_files): 3063 if hasattr(contents, "read"): 3064 contents = contents.read() 3065 contents = b(contents) 3066 unsaved_files_array[i].name = b(fspath(name)) 3067 unsaved_files_array[i].contents = contents 3068 unsaved_files_array[i].length = len(contents) 3069 ptr = conf.lib.clang_codeCompleteAt(self, fspath(path), line, column, 3070 unsaved_files_array, len(unsaved_files), options) 3071 if ptr: 3072 return CodeCompletionResults(ptr) 3073 return None 3074 3075 def get_tokens(self, locations=None, extent=None): 3076 """Obtain tokens in this translation unit. 3077 3078 This is a generator for Token instances. The caller specifies a range 3079 of source code to obtain tokens for. The range can be specified as a 3080 2-tuple of SourceLocation or as a SourceRange. If both are defined, 3081 behavior is undefined. 3082 """ 3083 if locations is not None: 3084 extent = SourceRange(start=locations[0], end=locations[1]) 3085 3086 return TokenGroup.get_tokens(self, extent) 3087 3088class File(ClangObject): 3089 """ 3090 The File class represents a particular source file that is part of a 3091 translation unit. 3092 """ 3093 3094 @staticmethod 3095 def from_name(translation_unit, file_name): 3096 """Retrieve a file handle within the given translation unit.""" 3097 return File(conf.lib.clang_getFile(translation_unit, fspath(file_name))) 3098 3099 @property 3100 def name(self): 3101 """Return the complete file and path name of the file.""" 3102 return conf.lib.clang_getFileName(self) 3103 3104 @property 3105 def time(self): 3106 """Return the last modification time of the file.""" 3107 return conf.lib.clang_getFileTime(self) 3108 3109 def __str__(self): 3110 return self.name 3111 3112 def __repr__(self): 3113 return "<File: %s>" % (self.name) 3114 3115 @staticmethod 3116 def from_result(res, fn, args): 3117 assert isinstance(res, c_object_p) 3118 res = File(res) 3119 3120 # Copy a reference to the TranslationUnit to prevent premature GC. 3121 res._tu = args[0]._tu 3122 return res 3123 3124class FileInclusion(object): 3125 """ 3126 The FileInclusion class represents the inclusion of one source file by 3127 another via a '#include' directive or as the input file for the translation 3128 unit. This class provides information about the included file, the including 3129 file, the location of the '#include' directive and the depth of the included 3130 file in the stack. Note that the input file has depth 0. 3131 """ 3132 3133 def __init__(self, src, tgt, loc, depth): 3134 self.source = src 3135 self.include = tgt 3136 self.location = loc 3137 self.depth = depth 3138 3139 @property 3140 def is_input_file(self): 3141 """True if the included file is the input file.""" 3142 return self.depth == 0 3143 3144class CompilationDatabaseError(Exception): 3145 """Represents an error that occurred when working with a CompilationDatabase 3146 3147 Each error is associated to an enumerated value, accessible under 3148 e.cdb_error. Consumers can compare the value with one of the ERROR_ 3149 constants in this class. 3150 """ 3151 3152 # An unknown error occurred 3153 ERROR_UNKNOWN = 0 3154 3155 # The database could not be loaded 3156 ERROR_CANNOTLOADDATABASE = 1 3157 3158 def __init__(self, enumeration, message): 3159 assert isinstance(enumeration, int) 3160 3161 if enumeration > 1: 3162 raise Exception("Encountered undefined CompilationDatabase error " 3163 "constant: %d. Please file a bug to have this " 3164 "value supported." % enumeration) 3165 3166 self.cdb_error = enumeration 3167 Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) 3168 3169class CompileCommand(object): 3170 """Represents the compile command used to build a file""" 3171 def __init__(self, cmd, ccmds): 3172 self.cmd = cmd 3173 # Keep a reference to the originating CompileCommands 3174 # to prevent garbage collection 3175 self.ccmds = ccmds 3176 3177 @property 3178 def directory(self): 3179 """Get the working directory for this CompileCommand""" 3180 return conf.lib.clang_CompileCommand_getDirectory(self.cmd) 3181 3182 @property 3183 def filename(self): 3184 """Get the working filename for this CompileCommand""" 3185 return conf.lib.clang_CompileCommand_getFilename(self.cmd) 3186 3187 @property 3188 def arguments(self): 3189 """ 3190 Get an iterable object providing each argument in the 3191 command line for the compiler invocation as a _CXString. 3192 3193 Invariant : the first argument is the compiler executable 3194 """ 3195 length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd) 3196 for i in range(length): 3197 yield conf.lib.clang_CompileCommand_getArg(self.cmd, i) 3198 3199class CompileCommands(object): 3200 """ 3201 CompileCommands is an iterable object containing all CompileCommand 3202 that can be used for building a specific file. 3203 """ 3204 def __init__(self, ccmds): 3205 self.ccmds = ccmds 3206 3207 def __del__(self): 3208 conf.lib.clang_CompileCommands_dispose(self.ccmds) 3209 3210 def __len__(self): 3211 return int(conf.lib.clang_CompileCommands_getSize(self.ccmds)) 3212 3213 def __getitem__(self, i): 3214 cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i) 3215 if not cc: 3216 raise IndexError 3217 return CompileCommand(cc, self) 3218 3219 @staticmethod 3220 def from_result(res, fn, args): 3221 if not res: 3222 return None 3223 return CompileCommands(res) 3224 3225class CompilationDatabase(ClangObject): 3226 """ 3227 The CompilationDatabase is a wrapper class around 3228 clang::tooling::CompilationDatabase 3229 3230 It enables querying how a specific source file can be built. 3231 """ 3232 3233 def __del__(self): 3234 conf.lib.clang_CompilationDatabase_dispose(self) 3235 3236 @staticmethod 3237 def from_result(res, fn, args): 3238 if not res: 3239 raise CompilationDatabaseError(0, 3240 "CompilationDatabase loading failed") 3241 return CompilationDatabase(res) 3242 3243 @staticmethod 3244 def fromDirectory(buildDir): 3245 """Builds a CompilationDatabase from the database found in buildDir""" 3246 errorCode = c_uint() 3247 try: 3248 cdb = conf.lib.clang_CompilationDatabase_fromDirectory(fspath(buildDir), 3249 byref(errorCode)) 3250 except CompilationDatabaseError as e: 3251 raise CompilationDatabaseError(int(errorCode.value), 3252 "CompilationDatabase loading failed") 3253 return cdb 3254 3255 def getCompileCommands(self, filename): 3256 """ 3257 Get an iterable object providing all the CompileCommands available to 3258 build filename. Returns None if filename is not found in the database. 3259 """ 3260 return conf.lib.clang_CompilationDatabase_getCompileCommands(self, 3261 fspath(filename)) 3262 3263 def getAllCompileCommands(self): 3264 """ 3265 Get an iterable object providing all the CompileCommands available from 3266 the database. 3267 """ 3268 return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self) 3269 3270 3271class Token(Structure): 3272 """Represents a single token from the preprocessor. 3273 3274 Tokens are effectively segments of source code. Source code is first parsed 3275 into tokens before being converted into the AST and Cursors. 3276 3277 Tokens are obtained from parsed TranslationUnit instances. You currently 3278 can't create tokens manually. 3279 """ 3280 _fields_ = [ 3281 ('int_data', c_uint * 4), 3282 ('ptr_data', c_void_p) 3283 ] 3284 3285 @property 3286 def spelling(self): 3287 """The spelling of this token. 3288 3289 This is the textual representation of the token in source. 3290 """ 3291 return conf.lib.clang_getTokenSpelling(self._tu, self) 3292 3293 @property 3294 def kind(self): 3295 """Obtain the TokenKind of the current token.""" 3296 return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) 3297 3298 @property 3299 def location(self): 3300 """The SourceLocation this Token occurs at.""" 3301 return conf.lib.clang_getTokenLocation(self._tu, self) 3302 3303 @property 3304 def extent(self): 3305 """The SourceRange this Token occupies.""" 3306 return conf.lib.clang_getTokenExtent(self._tu, self) 3307 3308 @property 3309 def cursor(self): 3310 """The Cursor this Token corresponds to.""" 3311 cursor = Cursor() 3312 cursor._tu = self._tu 3313 3314 conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor)) 3315 3316 return cursor 3317 3318# Now comes the plumbing to hook up the C library. 3319 3320# Register callback types in common container. 3321callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p, 3322 POINTER(SourceLocation), c_uint, py_object) 3323callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object) 3324callbacks['fields_visit'] = CFUNCTYPE(c_int, Cursor, py_object) 3325 3326# Functions strictly alphabetical order. 3327functionList = [ 3328 ("clang_annotateTokens", 3329 [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]), 3330 3331 ("clang_CompilationDatabase_dispose", 3332 [c_object_p]), 3333 3334 ("clang_CompilationDatabase_fromDirectory", 3335 [c_interop_string, POINTER(c_uint)], 3336 c_object_p, 3337 CompilationDatabase.from_result), 3338 3339 ("clang_CompilationDatabase_getAllCompileCommands", 3340 [c_object_p], 3341 c_object_p, 3342 CompileCommands.from_result), 3343 3344 ("clang_CompilationDatabase_getCompileCommands", 3345 [c_object_p, c_interop_string], 3346 c_object_p, 3347 CompileCommands.from_result), 3348 3349 ("clang_CompileCommands_dispose", 3350 [c_object_p]), 3351 3352 ("clang_CompileCommands_getCommand", 3353 [c_object_p, c_uint], 3354 c_object_p), 3355 3356 ("clang_CompileCommands_getSize", 3357 [c_object_p], 3358 c_uint), 3359 3360 ("clang_CompileCommand_getArg", 3361 [c_object_p, c_uint], 3362 _CXString, 3363 _CXString.from_result), 3364 3365 ("clang_CompileCommand_getDirectory", 3366 [c_object_p], 3367 _CXString, 3368 _CXString.from_result), 3369 3370 ("clang_CompileCommand_getFilename", 3371 [c_object_p], 3372 _CXString, 3373 _CXString.from_result), 3374 3375 ("clang_CompileCommand_getNumArgs", 3376 [c_object_p], 3377 c_uint), 3378 3379 ("clang_codeCompleteAt", 3380 [TranslationUnit, c_interop_string, c_int, c_int, c_void_p, c_int, c_int], 3381 POINTER(CCRStructure)), 3382 3383 ("clang_codeCompleteGetDiagnostic", 3384 [CodeCompletionResults, c_int], 3385 Diagnostic), 3386 3387 ("clang_codeCompleteGetNumDiagnostics", 3388 [CodeCompletionResults], 3389 c_int), 3390 3391 ("clang_createIndex", 3392 [c_int, c_int], 3393 c_object_p), 3394 3395 ("clang_createTranslationUnit", 3396 [Index, c_interop_string], 3397 c_object_p), 3398 3399 ("clang_CXXConstructor_isConvertingConstructor", 3400 [Cursor], 3401 bool), 3402 3403 ("clang_CXXConstructor_isCopyConstructor", 3404 [Cursor], 3405 bool), 3406 3407 ("clang_CXXConstructor_isDefaultConstructor", 3408 [Cursor], 3409 bool), 3410 3411 ("clang_CXXConstructor_isMoveConstructor", 3412 [Cursor], 3413 bool), 3414 3415 ("clang_CXXField_isMutable", 3416 [Cursor], 3417 bool), 3418 3419 ("clang_CXXMethod_isConst", 3420 [Cursor], 3421 bool), 3422 3423 ("clang_CXXMethod_isDefaulted", 3424 [Cursor], 3425 bool), 3426 3427 ("clang_CXXMethod_isPureVirtual", 3428 [Cursor], 3429 bool), 3430 3431 ("clang_CXXMethod_isStatic", 3432 [Cursor], 3433 bool), 3434 3435 ("clang_CXXMethod_isVirtual", 3436 [Cursor], 3437 bool), 3438 3439 ("clang_CXXRecord_isAbstract", 3440 [Cursor], 3441 bool), 3442 3443 ("clang_EnumDecl_isScoped", 3444 [Cursor], 3445 bool), 3446 3447 ("clang_defaultDiagnosticDisplayOptions", 3448 [], 3449 c_uint), 3450 3451 ("clang_defaultSaveOptions", 3452 [TranslationUnit], 3453 c_uint), 3454 3455 ("clang_disposeCodeCompleteResults", 3456 [CodeCompletionResults]), 3457 3458# ("clang_disposeCXTUResourceUsage", 3459# [CXTUResourceUsage]), 3460 3461 ("clang_disposeDiagnostic", 3462 [Diagnostic]), 3463 3464 ("clang_disposeIndex", 3465 [Index]), 3466 3467 ("clang_disposeString", 3468 [_CXString]), 3469 3470 ("clang_disposeTokens", 3471 [TranslationUnit, POINTER(Token), c_uint]), 3472 3473 ("clang_disposeTranslationUnit", 3474 [TranslationUnit]), 3475 3476 ("clang_equalCursors", 3477 [Cursor, Cursor], 3478 bool), 3479 3480 ("clang_equalLocations", 3481 [SourceLocation, SourceLocation], 3482 bool), 3483 3484 ("clang_equalRanges", 3485 [SourceRange, SourceRange], 3486 bool), 3487 3488 ("clang_equalTypes", 3489 [Type, Type], 3490 bool), 3491 3492 ("clang_formatDiagnostic", 3493 [Diagnostic, c_uint], 3494 _CXString, 3495 _CXString.from_result), 3496 3497 ("clang_getArgType", 3498 [Type, c_uint], 3499 Type, 3500 Type.from_result), 3501 3502 ("clang_getArrayElementType", 3503 [Type], 3504 Type, 3505 Type.from_result), 3506 3507 ("clang_getArraySize", 3508 [Type], 3509 c_longlong), 3510 3511 ("clang_getFieldDeclBitWidth", 3512 [Cursor], 3513 c_int), 3514 3515 ("clang_getCanonicalCursor", 3516 [Cursor], 3517 Cursor, 3518 Cursor.from_cursor_result), 3519 3520 ("clang_getCanonicalType", 3521 [Type], 3522 Type, 3523 Type.from_result), 3524 3525 ("clang_getChildDiagnostics", 3526 [Diagnostic], 3527 c_object_p), 3528 3529 ("clang_getCompletionAvailability", 3530 [c_void_p], 3531 c_int), 3532 3533 ("clang_getCompletionBriefComment", 3534 [c_void_p], 3535 _CXString, 3536 _CXString.from_result), 3537 3538 ("clang_getCompletionChunkCompletionString", 3539 [c_void_p, c_int], 3540 c_object_p), 3541 3542 ("clang_getCompletionChunkKind", 3543 [c_void_p, c_int], 3544 c_int), 3545 3546 ("clang_getCompletionChunkText", 3547 [c_void_p, c_int], 3548 _CXString, 3549 _CXString.from_result), 3550 3551 ("clang_getCompletionPriority", 3552 [c_void_p], 3553 c_int), 3554 3555 ("clang_getCString", 3556 [_CXString], 3557 c_interop_string, 3558 c_interop_string.to_python_string), 3559 3560 ("clang_getCursor", 3561 [TranslationUnit, SourceLocation], 3562 Cursor), 3563 3564 ("clang_getCursorAvailability", 3565 [Cursor], 3566 c_int), 3567 3568 ("clang_getCursorDefinition", 3569 [Cursor], 3570 Cursor, 3571 Cursor.from_result), 3572 3573 ("clang_getCursorDisplayName", 3574 [Cursor], 3575 _CXString, 3576 _CXString.from_result), 3577 3578 ("clang_getCursorExtent", 3579 [Cursor], 3580 SourceRange), 3581 3582 ("clang_getCursorLexicalParent", 3583 [Cursor], 3584 Cursor, 3585 Cursor.from_cursor_result), 3586 3587 ("clang_getCursorLocation", 3588 [Cursor], 3589 SourceLocation), 3590 3591 ("clang_getCursorReferenced", 3592 [Cursor], 3593 Cursor, 3594 Cursor.from_result), 3595 3596 ("clang_getCursorReferenceNameRange", 3597 [Cursor, c_uint, c_uint], 3598 SourceRange), 3599 3600 ("clang_getCursorResultType", 3601 [Cursor], 3602 Type, 3603 Type.from_result), 3604 3605 ("clang_getCursorSemanticParent", 3606 [Cursor], 3607 Cursor, 3608 Cursor.from_cursor_result), 3609 3610 ("clang_getCursorSpelling", 3611 [Cursor], 3612 _CXString, 3613 _CXString.from_result), 3614 3615 ("clang_getCursorType", 3616 [Cursor], 3617 Type, 3618 Type.from_result), 3619 3620 ("clang_getCursorUSR", 3621 [Cursor], 3622 _CXString, 3623 _CXString.from_result), 3624 3625 ("clang_Cursor_getMangling", 3626 [Cursor], 3627 _CXString, 3628 _CXString.from_result), 3629 3630# ("clang_getCXTUResourceUsage", 3631# [TranslationUnit], 3632# CXTUResourceUsage), 3633 3634 ("clang_getCXXAccessSpecifier", 3635 [Cursor], 3636 c_uint), 3637 3638 ("clang_getDeclObjCTypeEncoding", 3639 [Cursor], 3640 _CXString, 3641 _CXString.from_result), 3642 3643 ("clang_getDiagnostic", 3644 [c_object_p, c_uint], 3645 c_object_p), 3646 3647 ("clang_getDiagnosticCategory", 3648 [Diagnostic], 3649 c_uint), 3650 3651 ("clang_getDiagnosticCategoryText", 3652 [Diagnostic], 3653 _CXString, 3654 _CXString.from_result), 3655 3656 ("clang_getDiagnosticFixIt", 3657 [Diagnostic, c_uint, POINTER(SourceRange)], 3658 _CXString, 3659 _CXString.from_result), 3660 3661 ("clang_getDiagnosticInSet", 3662 [c_object_p, c_uint], 3663 c_object_p), 3664 3665 ("clang_getDiagnosticLocation", 3666 [Diagnostic], 3667 SourceLocation), 3668 3669 ("clang_getDiagnosticNumFixIts", 3670 [Diagnostic], 3671 c_uint), 3672 3673 ("clang_getDiagnosticNumRanges", 3674 [Diagnostic], 3675 c_uint), 3676 3677 ("clang_getDiagnosticOption", 3678 [Diagnostic, POINTER(_CXString)], 3679 _CXString, 3680 _CXString.from_result), 3681 3682 ("clang_getDiagnosticRange", 3683 [Diagnostic, c_uint], 3684 SourceRange), 3685 3686 ("clang_getDiagnosticSeverity", 3687 [Diagnostic], 3688 c_int), 3689 3690 ("clang_getDiagnosticSpelling", 3691 [Diagnostic], 3692 _CXString, 3693 _CXString.from_result), 3694 3695 ("clang_getElementType", 3696 [Type], 3697 Type, 3698 Type.from_result), 3699 3700 ("clang_getEnumConstantDeclUnsignedValue", 3701 [Cursor], 3702 c_ulonglong), 3703 3704 ("clang_getEnumConstantDeclValue", 3705 [Cursor], 3706 c_longlong), 3707 3708 ("clang_getEnumDeclIntegerType", 3709 [Cursor], 3710 Type, 3711 Type.from_result), 3712 3713 ("clang_getFile", 3714 [TranslationUnit, c_interop_string], 3715 c_object_p), 3716 3717 ("clang_getFileName", 3718 [File], 3719 _CXString, 3720 _CXString.from_result), 3721 3722 ("clang_getFileTime", 3723 [File], 3724 c_uint), 3725 3726 ("clang_getIBOutletCollectionType", 3727 [Cursor], 3728 Type, 3729 Type.from_result), 3730 3731 ("clang_getIncludedFile", 3732 [Cursor], 3733 c_object_p, 3734 File.from_result), 3735 3736 ("clang_getInclusions", 3737 [TranslationUnit, callbacks['translation_unit_includes'], py_object]), 3738 3739 ("clang_getInstantiationLocation", 3740 [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint), 3741 POINTER(c_uint)]), 3742 3743 ("clang_getLocation", 3744 [TranslationUnit, File, c_uint, c_uint], 3745 SourceLocation), 3746 3747 ("clang_getLocationForOffset", 3748 [TranslationUnit, File, c_uint], 3749 SourceLocation), 3750 3751 ("clang_getNullCursor", 3752 None, 3753 Cursor), 3754 3755 ("clang_getNumArgTypes", 3756 [Type], 3757 c_uint), 3758 3759 ("clang_getNumCompletionChunks", 3760 [c_void_p], 3761 c_int), 3762 3763 ("clang_getNumDiagnostics", 3764 [c_object_p], 3765 c_uint), 3766 3767 ("clang_getNumDiagnosticsInSet", 3768 [c_object_p], 3769 c_uint), 3770 3771 ("clang_getNumElements", 3772 [Type], 3773 c_longlong), 3774 3775 ("clang_getNumOverloadedDecls", 3776 [Cursor], 3777 c_uint), 3778 3779 ("clang_getOverloadedDecl", 3780 [Cursor, c_uint], 3781 Cursor, 3782 Cursor.from_cursor_result), 3783 3784 ("clang_getPointeeType", 3785 [Type], 3786 Type, 3787 Type.from_result), 3788 3789 ("clang_getRange", 3790 [SourceLocation, SourceLocation], 3791 SourceRange), 3792 3793 ("clang_getRangeEnd", 3794 [SourceRange], 3795 SourceLocation), 3796 3797 ("clang_getRangeStart", 3798 [SourceRange], 3799 SourceLocation), 3800 3801 ("clang_getResultType", 3802 [Type], 3803 Type, 3804 Type.from_result), 3805 3806 ("clang_getSpecializedCursorTemplate", 3807 [Cursor], 3808 Cursor, 3809 Cursor.from_cursor_result), 3810 3811 ("clang_getTemplateCursorKind", 3812 [Cursor], 3813 c_uint), 3814 3815 ("clang_getTokenExtent", 3816 [TranslationUnit, Token], 3817 SourceRange), 3818 3819 ("clang_getTokenKind", 3820 [Token], 3821 c_uint), 3822 3823 ("clang_getTokenLocation", 3824 [TranslationUnit, Token], 3825 SourceLocation), 3826 3827 ("clang_getTokenSpelling", 3828 [TranslationUnit, Token], 3829 _CXString, 3830 _CXString.from_result), 3831 3832 ("clang_getTranslationUnitCursor", 3833 [TranslationUnit], 3834 Cursor, 3835 Cursor.from_result), 3836 3837 ("clang_getTranslationUnitSpelling", 3838 [TranslationUnit], 3839 _CXString, 3840 _CXString.from_result), 3841 3842 ("clang_getTUResourceUsageName", 3843 [c_uint], 3844 c_interop_string, 3845 c_interop_string.to_python_string), 3846 3847 ("clang_getTypeDeclaration", 3848 [Type], 3849 Cursor, 3850 Cursor.from_result), 3851 3852 ("clang_getTypedefDeclUnderlyingType", 3853 [Cursor], 3854 Type, 3855 Type.from_result), 3856 3857 ("clang_getTypedefName", 3858 [Type], 3859 _CXString, 3860 _CXString.from_result), 3861 3862 ("clang_getTypeKindSpelling", 3863 [c_uint], 3864 _CXString, 3865 _CXString.from_result), 3866 3867 ("clang_getTypeSpelling", 3868 [Type], 3869 _CXString, 3870 _CXString.from_result), 3871 3872 ("clang_hashCursor", 3873 [Cursor], 3874 c_uint), 3875 3876 ("clang_isAttribute", 3877 [CursorKind], 3878 bool), 3879 3880 ("clang_isConstQualifiedType", 3881 [Type], 3882 bool), 3883 3884 ("clang_isCursorDefinition", 3885 [Cursor], 3886 bool), 3887 3888 ("clang_isDeclaration", 3889 [CursorKind], 3890 bool), 3891 3892 ("clang_isExpression", 3893 [CursorKind], 3894 bool), 3895 3896 ("clang_isFileMultipleIncludeGuarded", 3897 [TranslationUnit, File], 3898 bool), 3899 3900 ("clang_isFunctionTypeVariadic", 3901 [Type], 3902 bool), 3903 3904 ("clang_isInvalid", 3905 [CursorKind], 3906 bool), 3907 3908 ("clang_isPODType", 3909 [Type], 3910 bool), 3911 3912 ("clang_isPreprocessing", 3913 [CursorKind], 3914 bool), 3915 3916 ("clang_isReference", 3917 [CursorKind], 3918 bool), 3919 3920 ("clang_isRestrictQualifiedType", 3921 [Type], 3922 bool), 3923 3924 ("clang_isStatement", 3925 [CursorKind], 3926 bool), 3927 3928 ("clang_isTranslationUnit", 3929 [CursorKind], 3930 bool), 3931 3932 ("clang_isUnexposed", 3933 [CursorKind], 3934 bool), 3935 3936 ("clang_isVirtualBase", 3937 [Cursor], 3938 bool), 3939 3940 ("clang_isVolatileQualifiedType", 3941 [Type], 3942 bool), 3943 3944 ("clang_parseTranslationUnit", 3945 [Index, c_interop_string, c_void_p, c_int, c_void_p, c_int, c_int], 3946 c_object_p), 3947 3948 ("clang_reparseTranslationUnit", 3949 [TranslationUnit, c_int, c_void_p, c_int], 3950 c_int), 3951 3952 ("clang_saveTranslationUnit", 3953 [TranslationUnit, c_interop_string, c_uint], 3954 c_int), 3955 3956 ("clang_tokenize", 3957 [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]), 3958 3959 ("clang_visitChildren", 3960 [Cursor, callbacks['cursor_visit'], py_object], 3961 c_uint), 3962 3963 ("clang_Cursor_getNumArguments", 3964 [Cursor], 3965 c_int), 3966 3967 ("clang_Cursor_getArgument", 3968 [Cursor, c_uint], 3969 Cursor, 3970 Cursor.from_result), 3971 3972 ("clang_Cursor_getNumTemplateArguments", 3973 [Cursor], 3974 c_int), 3975 3976 ("clang_Cursor_getTemplateArgumentKind", 3977 [Cursor, c_uint], 3978 TemplateArgumentKind.from_id), 3979 3980 ("clang_Cursor_getTemplateArgumentType", 3981 [Cursor, c_uint], 3982 Type, 3983 Type.from_result), 3984 3985 ("clang_Cursor_getTemplateArgumentValue", 3986 [Cursor, c_uint], 3987 c_longlong), 3988 3989 ("clang_Cursor_getTemplateArgumentUnsignedValue", 3990 [Cursor, c_uint], 3991 c_ulonglong), 3992 3993 ("clang_Cursor_isAnonymous", 3994 [Cursor], 3995 bool), 3996 3997 ("clang_Cursor_isBitField", 3998 [Cursor], 3999 bool), 4000 4001 ("clang_Cursor_getBriefCommentText", 4002 [Cursor], 4003 _CXString, 4004 _CXString.from_result), 4005 4006 ("clang_Cursor_getRawCommentText", 4007 [Cursor], 4008 _CXString, 4009 _CXString.from_result), 4010 4011 ("clang_Cursor_getOffsetOfField", 4012 [Cursor], 4013 c_longlong), 4014 4015 ("clang_Type_getAlignOf", 4016 [Type], 4017 c_longlong), 4018 4019 ("clang_Type_getClassType", 4020 [Type], 4021 Type, 4022 Type.from_result), 4023 4024 ("clang_Type_getNumTemplateArguments", 4025 [Type], 4026 c_int), 4027 4028 ("clang_Type_getTemplateArgumentAsType", 4029 [Type, c_uint], 4030 Type, 4031 Type.from_result), 4032 4033 ("clang_Type_getOffsetOf", 4034 [Type, c_interop_string], 4035 c_longlong), 4036 4037 ("clang_Type_getSizeOf", 4038 [Type], 4039 c_longlong), 4040 4041 ("clang_Type_getCXXRefQualifier", 4042 [Type], 4043 c_uint), 4044 4045 ("clang_Type_getNamedType", 4046 [Type], 4047 Type, 4048 Type.from_result), 4049 4050 ("clang_Type_visitFields", 4051 [Type, callbacks['fields_visit'], py_object], 4052 c_uint), 4053] 4054 4055class LibclangError(Exception): 4056 def __init__(self, message): 4057 self.m = message 4058 4059 def __str__(self): 4060 return self.m 4061 4062def register_function(lib, item, ignore_errors): 4063 # A function may not exist, if these bindings are used with an older or 4064 # incompatible version of libclang.so. 4065 try: 4066 func = getattr(lib, item[0]) 4067 except AttributeError as e: 4068 msg = str(e) + ". Please ensure that your python bindings are "\ 4069 "compatible with your libclang.so version." 4070 if ignore_errors: 4071 return 4072 raise LibclangError(msg) 4073 4074 if len(item) >= 2: 4075 func.argtypes = item[1] 4076 4077 if len(item) >= 3: 4078 func.restype = item[2] 4079 4080 if len(item) == 4: 4081 func.errcheck = item[3] 4082 4083def register_functions(lib, ignore_errors): 4084 """Register function prototypes with a libclang library instance. 4085 4086 This must be called as part of library instantiation so Python knows how 4087 to call out to the shared library. 4088 """ 4089 4090 def register(item): 4091 return register_function(lib, item, ignore_errors) 4092 4093 for f in functionList: 4094 register(f) 4095 4096class Config(object): 4097 library_path = None 4098 library_file = None 4099 compatibility_check = True 4100 loaded = False 4101 4102 @staticmethod 4103 def set_library_path(path): 4104 """Set the path in which to search for libclang""" 4105 if Config.loaded: 4106 raise Exception("library path must be set before before using " \ 4107 "any other functionalities in libclang.") 4108 4109 Config.library_path = fspath(path) 4110 4111 @staticmethod 4112 def set_library_file(filename): 4113 """Set the exact location of libclang""" 4114 if Config.loaded: 4115 raise Exception("library file must be set before before using " \ 4116 "any other functionalities in libclang.") 4117 4118 Config.library_file = fspath(filename) 4119 4120 @staticmethod 4121 def set_compatibility_check(check_status): 4122 """ Perform compatibility check when loading libclang 4123 4124 The python bindings are only tested and evaluated with the version of 4125 libclang they are provided with. To ensure correct behavior a (limited) 4126 compatibility check is performed when loading the bindings. This check 4127 will throw an exception, as soon as it fails. 4128 4129 In case these bindings are used with an older version of libclang, parts 4130 that have been stable between releases may still work. Users of the 4131 python bindings can disable the compatibility check. This will cause 4132 the python bindings to load, even though they are written for a newer 4133 version of libclang. Failures now arise if unsupported or incompatible 4134 features are accessed. The user is required to test themselves if the 4135 features they are using are available and compatible between different 4136 libclang versions. 4137 """ 4138 if Config.loaded: 4139 raise Exception("compatibility_check must be set before before " \ 4140 "using any other functionalities in libclang.") 4141 4142 Config.compatibility_check = check_status 4143 4144 @CachedProperty 4145 def lib(self): 4146 lib = self.get_cindex_library() 4147 register_functions(lib, not Config.compatibility_check) 4148 Config.loaded = True 4149 return lib 4150 4151 def get_filename(self): 4152 if Config.library_file: 4153 return Config.library_file 4154 4155 import platform 4156 name = platform.system() 4157 4158 if name == 'Darwin': 4159 file = 'libclang.dylib' 4160 elif name == 'Windows': 4161 file = 'libclang.dll' 4162 else: 4163 file = 'libclang.so' 4164 4165 if Config.library_path: 4166 file = Config.library_path + '/' + file 4167 4168 return file 4169 4170 def get_cindex_library(self): 4171 try: 4172 library = cdll.LoadLibrary(self.get_filename()) 4173 except OSError as e: 4174 msg = str(e) + ". To provide a path to libclang use " \ 4175 "Config.set_library_path() or " \ 4176 "Config.set_library_file()." 4177 raise LibclangError(msg) 4178 4179 return library 4180 4181 def function_exists(self, name): 4182 try: 4183 getattr(self.lib, name) 4184 except AttributeError: 4185 return False 4186 4187 return True 4188 4189def register_enumerations(): 4190 for name, value in clang.enumerations.TokenKinds: 4191 TokenKind.register(value, name) 4192 4193conf = Config() 4194register_enumerations() 4195 4196__all__ = [ 4197 'AvailabilityKind', 4198 'Config', 4199 'CodeCompletionResults', 4200 'CompilationDatabase', 4201 'CompileCommands', 4202 'CompileCommand', 4203 'CursorKind', 4204 'Cursor', 4205 'Diagnostic', 4206 'File', 4207 'FixIt', 4208 'Index', 4209 'LinkageKind', 4210 'SourceLocation', 4211 'SourceRange', 4212 'TLSKind', 4213 'TokenKind', 4214 'Token', 4215 'TranslationUnitLoadError', 4216 'TranslationUnit', 4217 'TypeKind', 4218 'Type', 4219] 4220