cindex.py revision c23cb2d3e8af8354d43517283d3efb2cb0681f49
1#===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===# 2# 3# The LLVM Compiler Infrastructure 4# 5# This file is distributed under the University of Illinois Open Source 6# License. See LICENSE.TXT for details. 7# 8#===------------------------------------------------------------------------===# 9 10r""" 11Clang Indexing Library Bindings 12=============================== 13 14This module provides an interface to the Clang indexing library. It is a 15low-level interface to the indexing library which attempts to match the Clang 16API directly while also being "pythonic". Notable differences from the C API 17are: 18 19 * string results are returned as Python strings, not CXString objects. 20 21 * null cursors are translated to None. 22 23 * access to child cursors is done via iteration, not visitation. 24 25The major indexing objects are: 26 27 Index 28 29 The top-level object which manages some global library state. 30 31 TranslationUnit 32 33 High-level object encapsulating the AST for a single translation unit. These 34 can be loaded from .ast files or parsed on the fly. 35 36 Cursor 37 38 Generic object for representing a node in the AST. 39 40 SourceRange, SourceLocation, and File 41 42 Objects representing information about the input source. 43 44Most object information is exposed using properties, when the underlying API 45call is efficient. 46""" 47 48# TODO 49# ==== 50# 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 * 66import collections 67 68import clang.enumerations 69 70# ctypes doesn't implicitly convert c_void_p to the appropriate wrapper 71# object. This is a problem, because it means that from_parameter will see an 72# integer and pass the wrong value on platforms where int != void*. Work around 73# this by marshalling object arguments as void**. 74c_object_p = POINTER(c_void_p) 75 76callbacks = {} 77 78### Exception Classes ### 79 80class TranslationUnitLoadError(Exception): 81 """Represents an error that occurred when loading a TranslationUnit. 82 83 This is raised in the case where a TranslationUnit could not be 84 instantiated due to failure in the libclang library. 85 86 FIXME: Make libclang expose additional error information in this scenario. 87 """ 88 pass 89 90class TranslationUnitSaveError(Exception): 91 """Represents an error that occurred when saving a TranslationUnit. 92 93 Each error has associated with it an enumerated value, accessible under 94 e.save_error. Consumers can compare the value with one of the ERROR_ 95 constants in this class. 96 """ 97 98 # Indicates that an unknown error occurred. This typically indicates that 99 # I/O failed during save. 100 ERROR_UNKNOWN = 1 101 102 # Indicates that errors during translation prevented saving. The errors 103 # should be available via the TranslationUnit's diagnostics. 104 ERROR_TRANSLATION_ERRORS = 2 105 106 # Indicates that the translation unit was somehow invalid. 107 ERROR_INVALID_TU = 3 108 109 def __init__(self, enumeration, message): 110 assert isinstance(enumeration, int) 111 112 if enumeration < 1 or enumeration > 3: 113 raise Exception("Encountered undefined TranslationUnit save error " 114 "constant: %d. Please file a bug to have this " 115 "value supported." % enumeration) 116 117 self.save_error = enumeration 118 Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) 119 120### Structures and Utility Classes ### 121 122class CachedProperty(object): 123 """Decorator that lazy-loads the value of a property. 124 125 The first time the property is accessed, the original property function is 126 executed. The value it returns is set as the new value of that instance's 127 property, replacing the original method. 128 """ 129 130 def __init__(self, wrapped): 131 self.wrapped = wrapped 132 try: 133 self.__doc__ = wrapped.__doc__ 134 except: 135 pass 136 137 def __get__(self, instance, instance_type=None): 138 if instance is None: 139 return self 140 141 value = self.wrapped(instance) 142 setattr(instance, self.wrapped.__name__, value) 143 144 return value 145 146 147class _CXString(Structure): 148 """Helper for transforming CXString results.""" 149 150 _fields_ = [("spelling", c_char_p), ("free", c_int)] 151 152 def __del__(self): 153 conf.lib.clang_disposeString(self) 154 155 @staticmethod 156 def from_result(res, fn, args): 157 assert isinstance(res, _CXString) 158 return conf.lib.clang_getCString(res) 159 160class SourceLocation(Structure): 161 """ 162 A SourceLocation represents a particular location within a source file. 163 """ 164 _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)] 165 _data = None 166 167 def _get_instantiation(self): 168 if self._data is None: 169 f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint() 170 conf.lib.clang_getInstantiationLocation(self, byref(f), byref(l), 171 byref(c), byref(o)) 172 if f: 173 f = File(f) 174 else: 175 f = None 176 self._data = (f, int(l.value), int(c.value), int(o.value)) 177 return self._data 178 179 @staticmethod 180 def from_position(tu, file, line, column): 181 """ 182 Retrieve the source location associated with a given file/line/column in 183 a particular translation unit. 184 """ 185 return conf.lib.clang_getLocation(tu, file, line, column) 186 187 @staticmethod 188 def from_offset(tu, file, offset): 189 """Retrieve a SourceLocation from a given character offset. 190 191 tu -- TranslationUnit file belongs to 192 file -- File instance to obtain offset from 193 offset -- Integer character offset within file 194 """ 195 return conf.lib.clang_getLocationForOffset(tu, file, offset) 196 197 @property 198 def file(self): 199 """Get the file represented by this source location.""" 200 return self._get_instantiation()[0] 201 202 @property 203 def line(self): 204 """Get the line represented by this source location.""" 205 return self._get_instantiation()[1] 206 207 @property 208 def column(self): 209 """Get the column represented by this source location.""" 210 return self._get_instantiation()[2] 211 212 @property 213 def offset(self): 214 """Get the file offset represented by this source location.""" 215 return self._get_instantiation()[3] 216 217 def __eq__(self, other): 218 return conf.lib.clang_equalLocations(self, other) 219 220 def __ne__(self, other): 221 return not self.__eq__(other) 222 223 def __repr__(self): 224 if self.file: 225 filename = self.file.name 226 else: 227 filename = None 228 return "<SourceLocation file %r, line %r, column %r>" % ( 229 filename, self.line, self.column) 230 231class SourceRange(Structure): 232 """ 233 A SourceRange describes a range of source locations within the source 234 code. 235 """ 236 _fields_ = [ 237 ("ptr_data", c_void_p * 2), 238 ("begin_int_data", c_uint), 239 ("end_int_data", c_uint)] 240 241 # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes 242 # object. 243 @staticmethod 244 def from_locations(start, end): 245 return conf.lib.clang_getRange(start, end) 246 247 @property 248 def start(self): 249 """ 250 Return a SourceLocation representing the first character within a 251 source range. 252 """ 253 return conf.lib.clang_getRangeStart(self) 254 255 @property 256 def end(self): 257 """ 258 Return a SourceLocation representing the last character within a 259 source range. 260 """ 261 return conf.lib.clang_getRangeEnd(self) 262 263 def __eq__(self, other): 264 return conf.lib.clang_equalRanges(self, other) 265 266 def __ne__(self, other): 267 return not self.__eq__(other) 268 269 def __repr__(self): 270 return "<SourceRange start %r, end %r>" % (self.start, self.end) 271 272class Diagnostic(object): 273 """ 274 A Diagnostic is a single instance of a Clang diagnostic. It includes the 275 diagnostic severity, the message, the location the diagnostic occurred, as 276 well as additional source ranges and associated fix-it hints. 277 """ 278 279 Ignored = 0 280 Note = 1 281 Warning = 2 282 Error = 3 283 Fatal = 4 284 285 def __init__(self, ptr): 286 self.ptr = ptr 287 288 def __del__(self): 289 conf.lib.clang_disposeDiagnostic(self) 290 291 @property 292 def severity(self): 293 return conf.lib.clang_getDiagnosticSeverity(self) 294 295 @property 296 def location(self): 297 return conf.lib.clang_getDiagnosticLocation(self) 298 299 @property 300 def spelling(self): 301 return conf.lib.clang_getDiagnosticSpelling(self) 302 303 @property 304 def ranges(self): 305 class RangeIterator: 306 def __init__(self, diag): 307 self.diag = diag 308 309 def __len__(self): 310 return int(conf.lib.clang_getDiagnosticNumRanges(self.diag)) 311 312 def __getitem__(self, key): 313 if (key >= len(self)): 314 raise IndexError 315 return conf.lib.clang_getDiagnosticRange(self.diag, key) 316 317 return RangeIterator(self) 318 319 @property 320 def fixits(self): 321 class FixItIterator: 322 def __init__(self, diag): 323 self.diag = diag 324 325 def __len__(self): 326 return int(conf.lib.clang_getDiagnosticNumFixIts(self.diag)) 327 328 def __getitem__(self, key): 329 range = SourceRange() 330 value = conf.lib.clang_getDiagnosticFixIt(self.diag, key, 331 byref(range)) 332 if len(value) == 0: 333 raise IndexError 334 335 return FixIt(range, value) 336 337 return FixItIterator(self) 338 339 @property 340 def category_number(self): 341 """The category number for this diagnostic.""" 342 return conf.lib.clang_getDiagnosticCategory(self) 343 344 @property 345 def category_name(self): 346 """The string name of the category for this diagnostic.""" 347 return conf.lib.clang_getDiagnosticCategoryName(self.category_number) 348 349 @property 350 def option(self): 351 """The command-line option that enables this diagnostic.""" 352 return conf.lib.clang_getDiagnosticOption(self, None) 353 354 @property 355 def disable_option(self): 356 """The command-line option that disables this diagnostic.""" 357 disable = _CXString() 358 conf.lib.clang_getDiagnosticOption(self, byref(disable)) 359 360 return conf.lib.clang_getCString(disable) 361 362 def __repr__(self): 363 return "<Diagnostic severity %r, location %r, spelling %r>" % ( 364 self.severity, self.location, self.spelling) 365 366 def from_param(self): 367 return self.ptr 368 369class FixIt(object): 370 """ 371 A FixIt represents a transformation to be applied to the source to 372 "fix-it". The fix-it shouldbe applied by replacing the given source range 373 with the given value. 374 """ 375 376 def __init__(self, range, value): 377 self.range = range 378 self.value = value 379 380 def __repr__(self): 381 return "<FixIt range %r, value %r>" % (self.range, self.value) 382 383class TokenGroup(object): 384 """Helper class to facilitate token management. 385 386 Tokens are allocated from libclang in chunks. They must be disposed of as a 387 collective group. 388 389 One purpose of this class is for instances to represent groups of allocated 390 tokens. Each token in a group contains a reference back to an instance of 391 this class. When all tokens from a group are garbage collected, it allows 392 this class to be garbage collected. When this class is garbage collected, 393 it calls the libclang destructor which invalidates all tokens in the group. 394 395 You should not instantiate this class outside of this module. 396 """ 397 def __init__(self, tu, memory, count): 398 self._tu = tu 399 self._memory = memory 400 self._count = count 401 402 def __del__(self): 403 conf.lib.clang_disposeTokens(self._tu, self._memory, self._count) 404 405 @staticmethod 406 def get_tokens(tu, extent): 407 """Helper method to return all tokens in an extent. 408 409 This functionality is needed multiple places in this module. We define 410 it here because it seems like a logical place. 411 """ 412 tokens_memory = POINTER(Token)() 413 tokens_count = c_uint() 414 415 conf.lib.clang_tokenize(tu, extent, byref(tokens_memory), 416 byref(tokens_count)) 417 418 count = int(tokens_count.value) 419 420 # If we get no tokens, no memory was allocated. Be sure not to return 421 # anything and potentially call a destructor on nothing. 422 if count < 1: 423 return 424 425 tokens_array = cast(tokens_memory, POINTER(Token * count)).contents 426 427 token_group = TokenGroup(tu, tokens_memory, tokens_count) 428 429 for i in xrange(0, count): 430 token = Token() 431 token.int_data = tokens_array[i].int_data 432 token.ptr_data = tokens_array[i].ptr_data 433 token._tu = tu 434 token._group = token_group 435 436 yield token 437 438class TokenKind(object): 439 """Describes a specific type of a Token.""" 440 441 _value_map = {} # int -> TokenKind 442 443 def __init__(self, value, name): 444 """Create a new TokenKind instance from a numeric value and a name.""" 445 self.value = value 446 self.name = name 447 448 def __repr__(self): 449 return 'TokenKind.%s' % (self.name,) 450 451 @staticmethod 452 def from_value(value): 453 """Obtain a registered TokenKind instance from its value.""" 454 result = TokenKind._value_map.get(value, None) 455 456 if result is None: 457 raise ValueError('Unknown TokenKind: %d' % value) 458 459 return result 460 461 @staticmethod 462 def register(value, name): 463 """Register a new TokenKind enumeration. 464 465 This should only be called at module load time by code within this 466 package. 467 """ 468 if value in TokenKind._value_map: 469 raise ValueError('TokenKind already registered: %d' % value) 470 471 kind = TokenKind(value, name) 472 TokenKind._value_map[value] = kind 473 setattr(TokenKind, name, kind) 474 475### Cursor Kinds ### 476 477class CursorKind(object): 478 """ 479 A CursorKind describes the kind of entity that a cursor points to. 480 """ 481 482 # The unique kind objects, indexed by id. 483 _kinds = [] 484 _name_map = None 485 486 def __init__(self, value): 487 if value >= len(CursorKind._kinds): 488 CursorKind._kinds += [None] * (value - len(CursorKind._kinds) + 1) 489 if CursorKind._kinds[value] is not None: 490 raise ValueError,'CursorKind already loaded' 491 self.value = value 492 CursorKind._kinds[value] = self 493 CursorKind._name_map = None 494 495 def from_param(self): 496 return self.value 497 498 @property 499 def name(self): 500 """Get the enumeration name of this cursor kind.""" 501 if self._name_map is None: 502 self._name_map = {} 503 for key,value in CursorKind.__dict__.items(): 504 if isinstance(value,CursorKind): 505 self._name_map[value] = key 506 return self._name_map[self] 507 508 @staticmethod 509 def from_id(id): 510 if id >= len(CursorKind._kinds) or CursorKind._kinds[id] is None: 511 raise ValueError,'Unknown cursor kind %d' % id 512 return CursorKind._kinds[id] 513 514 @staticmethod 515 def get_all_kinds(): 516 """Return all CursorKind enumeration instances.""" 517 return filter(None, CursorKind._kinds) 518 519 def is_declaration(self): 520 """Test if this is a declaration kind.""" 521 return conf.lib.clang_isDeclaration(self) 522 523 def is_reference(self): 524 """Test if this is a reference kind.""" 525 return conf.lib.clang_isReference(self) 526 527 def is_expression(self): 528 """Test if this is an expression kind.""" 529 return conf.lib.clang_isExpression(self) 530 531 def is_statement(self): 532 """Test if this is a statement kind.""" 533 return conf.lib.clang_isStatement(self) 534 535 def is_attribute(self): 536 """Test if this is an attribute kind.""" 537 return conf.lib.clang_isAttribute(self) 538 539 def is_invalid(self): 540 """Test if this is an invalid kind.""" 541 return conf.lib.clang_isInvalid(self) 542 543 def is_translation_unit(self): 544 """Test if this is a translation unit kind.""" 545 return conf.lib.clang_isTranslationUnit(self) 546 547 def is_preprocessing(self): 548 """Test if this is a preprocessing kind.""" 549 return conf.lib.clang_isPreprocessing(self) 550 551 def is_unexposed(self): 552 """Test if this is an unexposed kind.""" 553 return conf.lib.clang_isUnexposed(self) 554 555 def __repr__(self): 556 return 'CursorKind.%s' % (self.name,) 557 558# FIXME: Is there a nicer way to expose this enumeration? We could potentially 559# represent the nested structure, or even build a class hierarchy. The main 560# things we want for sure are (a) simple external access to kinds, (b) a place 561# to hang a description and name, (c) easy to keep in sync with Index.h. 562 563### 564# Declaration Kinds 565 566# A declaration whose specific kind is not exposed via this interface. 567# 568# Unexposed declarations have the same operations as any other kind of 569# declaration; one can extract their location information, spelling, find their 570# definitions, etc. However, the specific kind of the declaration is not 571# reported. 572CursorKind.UNEXPOSED_DECL = CursorKind(1) 573 574# A C or C++ struct. 575CursorKind.STRUCT_DECL = CursorKind(2) 576 577# A C or C++ union. 578CursorKind.UNION_DECL = CursorKind(3) 579 580# A C++ class. 581CursorKind.CLASS_DECL = CursorKind(4) 582 583# An enumeration. 584CursorKind.ENUM_DECL = CursorKind(5) 585 586# A field (in C) or non-static data member (in C++) in a struct, union, or C++ 587# class. 588CursorKind.FIELD_DECL = CursorKind(6) 589 590# An enumerator constant. 591CursorKind.ENUM_CONSTANT_DECL = CursorKind(7) 592 593# A function. 594CursorKind.FUNCTION_DECL = CursorKind(8) 595 596# A variable. 597CursorKind.VAR_DECL = CursorKind(9) 598 599# A function or method parameter. 600CursorKind.PARM_DECL = CursorKind(10) 601 602# An Objective-C @interface. 603CursorKind.OBJC_INTERFACE_DECL = CursorKind(11) 604 605# An Objective-C @interface for a category. 606CursorKind.OBJC_CATEGORY_DECL = CursorKind(12) 607 608# An Objective-C @protocol declaration. 609CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13) 610 611# An Objective-C @property declaration. 612CursorKind.OBJC_PROPERTY_DECL = CursorKind(14) 613 614# An Objective-C instance variable. 615CursorKind.OBJC_IVAR_DECL = CursorKind(15) 616 617# An Objective-C instance method. 618CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16) 619 620# An Objective-C class method. 621CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17) 622 623# An Objective-C @implementation. 624CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18) 625 626# An Objective-C @implementation for a category. 627CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19) 628 629# A typedef. 630CursorKind.TYPEDEF_DECL = CursorKind(20) 631 632# A C++ class method. 633CursorKind.CXX_METHOD = CursorKind(21) 634 635# A C++ namespace. 636CursorKind.NAMESPACE = CursorKind(22) 637 638# A linkage specification, e.g. 'extern "C"'. 639CursorKind.LINKAGE_SPEC = CursorKind(23) 640 641# A C++ constructor. 642CursorKind.CONSTRUCTOR = CursorKind(24) 643 644# A C++ destructor. 645CursorKind.DESTRUCTOR = CursorKind(25) 646 647# A C++ conversion function. 648CursorKind.CONVERSION_FUNCTION = CursorKind(26) 649 650# A C++ template type parameter 651CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27) 652 653# A C++ non-type template paramater. 654CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28) 655 656# A C++ template template parameter. 657CursorKind.TEMPLATE_TEMPLATE_PARAMETER = CursorKind(29) 658 659# A C++ function template. 660CursorKind.FUNCTION_TEMPLATE = CursorKind(30) 661 662# A C++ class template. 663CursorKind.CLASS_TEMPLATE = CursorKind(31) 664 665# A C++ class template partial specialization. 666CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32) 667 668# A C++ namespace alias declaration. 669CursorKind.NAMESPACE_ALIAS = CursorKind(33) 670 671# A C++ using directive 672CursorKind.USING_DIRECTIVE = CursorKind(34) 673 674# A C++ using declaration 675CursorKind.USING_DECLARATION = CursorKind(35) 676 677# A Type alias decl. 678CursorKind.TYPE_ALIAS_DECL = CursorKind(36) 679 680# A Objective-C synthesize decl 681CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37) 682 683# A Objective-C dynamic decl 684CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38) 685 686# A C++ access specifier decl. 687CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39) 688 689 690### 691# Reference Kinds 692 693CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40) 694CursorKind.OBJC_PROTOCOL_REF = CursorKind(41) 695CursorKind.OBJC_CLASS_REF = CursorKind(42) 696 697# A reference to a type declaration. 698# 699# A type reference occurs anywhere where a type is named but not 700# declared. For example, given: 701# typedef unsigned size_type; 702# size_type size; 703# 704# The typedef is a declaration of size_type (CXCursor_TypedefDecl), 705# while the type of the variable "size" is referenced. The cursor 706# referenced by the type of size is the typedef for size_type. 707CursorKind.TYPE_REF = CursorKind(43) 708CursorKind.CXX_BASE_SPECIFIER = CursorKind(44) 709 710# A reference to a class template, function template, template 711# template parameter, or class template partial specialization. 712CursorKind.TEMPLATE_REF = CursorKind(45) 713 714# A reference to a namespace or namepsace alias. 715CursorKind.NAMESPACE_REF = CursorKind(46) 716 717# A reference to a member of a struct, union, or class that occurs in 718# some non-expression context, e.g., a designated initializer. 719CursorKind.MEMBER_REF = CursorKind(47) 720 721# A reference to a labeled statement. 722CursorKind.LABEL_REF = CursorKind(48) 723 724# A reference to a set of overloaded functions or function templates 725# that has not yet been resolved to a specific function or function template. 726CursorKind.OVERLOADED_DECL_REF = CursorKind(49) 727 728# A reference to a variable that occurs in some non-expression 729# context, e.g., a C++ lambda capture list. 730CursorKind.VARIABLE_REF = CursorKind(50) 731 732### 733# Invalid/Error Kinds 734 735CursorKind.INVALID_FILE = CursorKind(70) 736CursorKind.NO_DECL_FOUND = CursorKind(71) 737CursorKind.NOT_IMPLEMENTED = CursorKind(72) 738CursorKind.INVALID_CODE = CursorKind(73) 739 740### 741# Expression Kinds 742 743# An expression whose specific kind is not exposed via this interface. 744# 745# Unexposed expressions have the same operations as any other kind of 746# expression; one can extract their location information, spelling, children, 747# etc. However, the specific kind of the expression is not reported. 748CursorKind.UNEXPOSED_EXPR = CursorKind(100) 749 750# An expression that refers to some value declaration, such as a function, 751# varible, or enumerator. 752CursorKind.DECL_REF_EXPR = CursorKind(101) 753 754# An expression that refers to a member of a struct, union, class, Objective-C 755# class, etc. 756CursorKind.MEMBER_REF_EXPR = CursorKind(102) 757 758# An expression that calls a function. 759CursorKind.CALL_EXPR = CursorKind(103) 760 761# An expression that sends a message to an Objective-C object or class. 762CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104) 763 764# An expression that represents a block literal. 765CursorKind.BLOCK_EXPR = CursorKind(105) 766 767# An integer literal. 768CursorKind.INTEGER_LITERAL = CursorKind(106) 769 770# A floating point number literal. 771CursorKind.FLOATING_LITERAL = CursorKind(107) 772 773# An imaginary number literal. 774CursorKind.IMAGINARY_LITERAL = CursorKind(108) 775 776# A string literal. 777CursorKind.STRING_LITERAL = CursorKind(109) 778 779# A character literal. 780CursorKind.CHARACTER_LITERAL = CursorKind(110) 781 782# A parenthesized expression, e.g. "(1)". 783# 784# This AST node is only formed if full location information is requested. 785CursorKind.PAREN_EXPR = CursorKind(111) 786 787# This represents the unary-expression's (except sizeof and 788# alignof). 789CursorKind.UNARY_OPERATOR = CursorKind(112) 790 791# [C99 6.5.2.1] Array Subscripting. 792CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113) 793 794# A builtin binary operation expression such as "x + y" or 795# "x <= y". 796CursorKind.BINARY_OPERATOR = CursorKind(114) 797 798# Compound assignment such as "+=". 799CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115) 800 801# The ?: ternary operator. 802CursorKind.CONDITIONAL_OPERATOR = CursorKind(116) 803 804# An explicit cast in C (C99 6.5.4) or a C-style cast in C++ 805# (C++ [expr.cast]), which uses the syntax (Type)expr. 806# 807# For example: (int)f. 808CursorKind.CSTYLE_CAST_EXPR = CursorKind(117) 809 810# [C99 6.5.2.5] 811CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118) 812 813# Describes an C or C++ initializer list. 814CursorKind.INIT_LIST_EXPR = CursorKind(119) 815 816# The GNU address of label extension, representing &&label. 817CursorKind.ADDR_LABEL_EXPR = CursorKind(120) 818 819# This is the GNU Statement Expression extension: ({int X=4; X;}) 820CursorKind.StmtExpr = CursorKind(121) 821 822# Represents a C11 generic selection. 823CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122) 824 825# Implements the GNU __null extension, which is a name for a null 826# pointer constant that has integral type (e.g., int or long) and is the same 827# size and alignment as a pointer. 828# 829# The __null extension is typically only used by system headers, which define 830# NULL as __null in C++ rather than using 0 (which is an integer that may not 831# match the size of a pointer). 832CursorKind.GNU_NULL_EXPR = CursorKind(123) 833 834# C++'s static_cast<> expression. 835CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124) 836 837# C++'s dynamic_cast<> expression. 838CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125) 839 840# C++'s reinterpret_cast<> expression. 841CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126) 842 843# C++'s const_cast<> expression. 844CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127) 845 846# Represents an explicit C++ type conversion that uses "functional" 847# notion (C++ [expr.type.conv]). 848# 849# Example: 850# \code 851# x = int(0.5); 852# \endcode 853CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128) 854 855# A C++ typeid expression (C++ [expr.typeid]). 856CursorKind.CXX_TYPEID_EXPR = CursorKind(129) 857 858# [C++ 2.13.5] C++ Boolean Literal. 859CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130) 860 861# [C++0x 2.14.7] C++ Pointer Literal. 862CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131) 863 864# Represents the "this" expression in C++ 865CursorKind.CXX_THIS_EXPR = CursorKind(132) 866 867# [C++ 15] C++ Throw Expression. 868# 869# This handles 'throw' and 'throw' assignment-expression. When 870# assignment-expression isn't present, Op will be null. 871CursorKind.CXX_THROW_EXPR = CursorKind(133) 872 873# A new expression for memory allocation and constructor calls, e.g: 874# "new CXXNewExpr(foo)". 875CursorKind.CXX_NEW_EXPR = CursorKind(134) 876 877# A delete expression for memory deallocation and destructor calls, 878# e.g. "delete[] pArray". 879CursorKind.CXX_DELETE_EXPR = CursorKind(135) 880 881# Represents a unary expression. 882CursorKind.CXX_UNARY_EXPR = CursorKind(136) 883 884# ObjCStringLiteral, used for Objective-C string literals i.e. "foo". 885CursorKind.OBJC_STRING_LITERAL = CursorKind(137) 886 887# ObjCEncodeExpr, used for in Objective-C. 888CursorKind.OBJC_ENCODE_EXPR = CursorKind(138) 889 890# ObjCSelectorExpr used for in Objective-C. 891CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139) 892 893# Objective-C's protocol expression. 894CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140) 895 896# An Objective-C "bridged" cast expression, which casts between 897# Objective-C pointers and C pointers, transferring ownership in the process. 898# 899# \code 900# NSString *str = (__bridge_transfer NSString *)CFCreateString(); 901# \endcode 902CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141) 903 904# Represents a C++0x pack expansion that produces a sequence of 905# expressions. 906# 907# A pack expansion expression contains a pattern (which itself is an 908# expression) followed by an ellipsis. For example: 909CursorKind.PACK_EXPANSION_EXPR = CursorKind(142) 910 911# Represents an expression that computes the length of a parameter 912# pack. 913CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143) 914 915# Represents a C++ lambda expression that produces a local function 916# object. 917# 918# \code 919# void abssort(float *x, unsigned N) { 920# std::sort(x, x + N, 921# [](float a, float b) { 922# return std::abs(a) < std::abs(b); 923# }); 924# } 925# \endcode 926CursorKind.LAMBDA_EXPR = CursorKind(144) 927 928# Objective-c Boolean Literal. 929CursorKind.OBJ_BOOL_LITERAL_EXPR = CursorKind(145) 930 931# Represents the "self" expression in a ObjC method. 932CursorKind.OBJ_SELF_EXPR = CursorKind(146) 933 934 935# A statement whose specific kind is not exposed via this interface. 936# 937# Unexposed statements have the same operations as any other kind of statement; 938# one can extract their location information, spelling, children, etc. However, 939# the specific kind of the statement is not reported. 940CursorKind.UNEXPOSED_STMT = CursorKind(200) 941 942# A labelled statement in a function. 943CursorKind.LABEL_STMT = CursorKind(201) 944 945# A compound statement 946CursorKind.COMPOUND_STMT = CursorKind(202) 947 948# A case statement. 949CursorKind.CASE_STMT = CursorKind(203) 950 951# A default statement. 952CursorKind.DEFAULT_STMT = CursorKind(204) 953 954# An if statement. 955CursorKind.IF_STMT = CursorKind(205) 956 957# A switch statement. 958CursorKind.SWITCH_STMT = CursorKind(206) 959 960# A while statement. 961CursorKind.WHILE_STMT = CursorKind(207) 962 963# A do statement. 964CursorKind.DO_STMT = CursorKind(208) 965 966# A for statement. 967CursorKind.FOR_STMT = CursorKind(209) 968 969# A goto statement. 970CursorKind.GOTO_STMT = CursorKind(210) 971 972# An indirect goto statement. 973CursorKind.INDIRECT_GOTO_STMT = CursorKind(211) 974 975# A continue statement. 976CursorKind.CONTINUE_STMT = CursorKind(212) 977 978# A break statement. 979CursorKind.BREAK_STMT = CursorKind(213) 980 981# A return statement. 982CursorKind.RETURN_STMT = CursorKind(214) 983 984# A GNU-style inline assembler statement. 985CursorKind.ASM_STMT = CursorKind(215) 986 987# Objective-C's overall @try-@catch-@finally statement. 988CursorKind.OBJC_AT_TRY_STMT = CursorKind(216) 989 990# Objective-C's @catch statement. 991CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217) 992 993# Objective-C's @finally statement. 994CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218) 995 996# Objective-C's @throw statement. 997CursorKind.OBJC_AT_THROW_STMT = CursorKind(219) 998 999# Objective-C's @synchronized statement. 1000CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220) 1001 1002# Objective-C's autorealease pool statement. 1003CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221) 1004 1005# Objective-C's for collection statement. 1006CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222) 1007 1008# C++'s catch statement. 1009CursorKind.CXX_CATCH_STMT = CursorKind(223) 1010 1011# C++'s try statement. 1012CursorKind.CXX_TRY_STMT = CursorKind(224) 1013 1014# C++'s for (* : *) statement. 1015CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225) 1016 1017# Windows Structured Exception Handling's try statement. 1018CursorKind.SEH_TRY_STMT = CursorKind(226) 1019 1020# Windows Structured Exception Handling's except statement. 1021CursorKind.SEH_EXCEPT_STMT = CursorKind(227) 1022 1023# Windows Structured Exception Handling's finally statement. 1024CursorKind.SEH_FINALLY_STMT = CursorKind(228) 1025 1026# A MS inline assembly statement extension. 1027CursorKind.MS_ASM_STMT = CursorKind(229) 1028 1029# The null statement. 1030CursorKind.NULL_STMT = CursorKind(230) 1031 1032# Adaptor class for mixing declarations with statements and expressions. 1033CursorKind.DECL_STMT = CursorKind(231) 1034 1035### 1036# Other Kinds 1037 1038# Cursor that represents the translation unit itself. 1039# 1040# The translation unit cursor exists primarily to act as the root cursor for 1041# traversing the contents of a translation unit. 1042CursorKind.TRANSLATION_UNIT = CursorKind(300) 1043 1044### 1045# Attributes 1046 1047# An attribute whoe specific kind is note exposed via this interface 1048CursorKind.UNEXPOSED_ATTR = CursorKind(400) 1049 1050CursorKind.IB_ACTION_ATTR = CursorKind(401) 1051CursorKind.IB_OUTLET_ATTR = CursorKind(402) 1052CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403) 1053 1054CursorKind.CXX_FINAL_ATTR = CursorKind(404) 1055CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405) 1056CursorKind.ANNOTATE_ATTR = CursorKind(406) 1057CursorKind.ASM_LABEL_ATTR = CursorKind(407) 1058CursorKind.PACKED_ATTR = CursorKind(408) 1059 1060### 1061# Preprocessing 1062CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500) 1063CursorKind.MACRO_DEFINITION = CursorKind(501) 1064CursorKind.MACRO_INSTANTIATION = CursorKind(502) 1065CursorKind.INCLUSION_DIRECTIVE = CursorKind(503) 1066 1067### 1068# Extra declaration 1069 1070# A module import declaration. 1071CursorKind.MODULE_IMPORT_DECL = CursorKind(600) 1072 1073### Cursors ### 1074 1075class Cursor(Structure): 1076 """ 1077 The Cursor class represents a reference to an element within the AST. It 1078 acts as a kind of iterator. 1079 """ 1080 _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)] 1081 1082 @staticmethod 1083 def from_location(tu, location): 1084 # We store a reference to the TU in the instance so the TU won't get 1085 # collected before the cursor. 1086 cursor = conf.lib.clang_getCursor(tu, location) 1087 cursor._tu = tu 1088 1089 return cursor 1090 1091 def __eq__(self, other): 1092 return conf.lib.clang_equalCursors(self, other) 1093 1094 def __ne__(self, other): 1095 return not self.__eq__(other) 1096 1097 def is_definition(self): 1098 """ 1099 Returns true if the declaration pointed at by the cursor is also a 1100 definition of that entity. 1101 """ 1102 return conf.lib.clang_isCursorDefinition(self) 1103 1104 def is_static_method(self): 1105 """Returns True if the cursor refers to a C++ member function or member 1106 function template that is declared 'static'. 1107 """ 1108 return conf.lib.clang_CXXMethod_isStatic(self) 1109 1110 def get_definition(self): 1111 """ 1112 If the cursor is a reference to a declaration or a declaration of 1113 some entity, return a cursor that points to the definition of that 1114 entity. 1115 """ 1116 # TODO: Should probably check that this is either a reference or 1117 # declaration prior to issuing the lookup. 1118 return conf.lib.clang_getCursorDefinition(self) 1119 1120 def get_usr(self): 1121 """Return the Unified Symbol Resultion (USR) for the entity referenced 1122 by the given cursor (or None). 1123 1124 A Unified Symbol Resolution (USR) is a string that identifies a 1125 particular entity (function, class, variable, etc.) within a 1126 program. USRs can be compared across translation units to determine, 1127 e.g., when references in one translation refer to an entity defined in 1128 another translation unit.""" 1129 return conf.lib.clang_getCursorUSR(self) 1130 1131 @property 1132 def kind(self): 1133 """Return the kind of this cursor.""" 1134 return CursorKind.from_id(self._kind_id) 1135 1136 @property 1137 def spelling(self): 1138 """Return the spelling of the entity pointed at by the cursor.""" 1139 if not self.kind.is_declaration(): 1140 # FIXME: clang_getCursorSpelling should be fixed to not assert on 1141 # this, for consistency with clang_getCursorUSR. 1142 return None 1143 if not hasattr(self, '_spelling'): 1144 self._spelling = conf.lib.clang_getCursorSpelling(self) 1145 1146 return self._spelling 1147 1148 @property 1149 def displayname(self): 1150 """ 1151 Return the display name for the entity referenced by this cursor. 1152 1153 The display name contains extra information that helps identify the cursor, 1154 such as the parameters of a function or template or the arguments of a 1155 class template specialization. 1156 """ 1157 if not hasattr(self, '_displayname'): 1158 self._displayname = conf.lib.clang_getCursorDisplayName(self) 1159 1160 return self._displayname 1161 1162 @property 1163 def location(self): 1164 """ 1165 Return the source location (the starting character) of the entity 1166 pointed at by the cursor. 1167 """ 1168 if not hasattr(self, '_loc'): 1169 self._loc = conf.lib.clang_getCursorLocation(self) 1170 1171 return self._loc 1172 1173 @property 1174 def extent(self): 1175 """ 1176 Return the source range (the range of text) occupied by the entity 1177 pointed at by the cursor. 1178 """ 1179 if not hasattr(self, '_extent'): 1180 self._extent = conf.lib.clang_getCursorExtent(self) 1181 1182 return self._extent 1183 1184 @property 1185 def type(self): 1186 """ 1187 Retrieve the Type (if any) of the entity pointed at by the cursor. 1188 """ 1189 if not hasattr(self, '_type'): 1190 self._type = conf.lib.clang_getCursorType(self) 1191 1192 return self._type 1193 1194 @property 1195 def canonical(self): 1196 """Return the canonical Cursor corresponding to this Cursor. 1197 1198 The canonical cursor is the cursor which is representative for the 1199 underlying entity. For example, if you have multiple forward 1200 declarations for the same class, the canonical cursor for the forward 1201 declarations will be identical. 1202 """ 1203 if not hasattr(self, '_canonical'): 1204 self._canonical = conf.lib.clang_getCanonicalCursor(self) 1205 1206 return self._canonical 1207 1208 @property 1209 def result_type(self): 1210 """Retrieve the Type of the result for this Cursor.""" 1211 if not hasattr(self, '_result_type'): 1212 self._result_type = conf.lib.clang_getResultType(self.type) 1213 1214 return self._result_type 1215 1216 @property 1217 def underlying_typedef_type(self): 1218 """Return the underlying type of a typedef declaration. 1219 1220 Returns a Type for the typedef this cursor is a declaration for. If 1221 the current cursor is not a typedef, this raises. 1222 """ 1223 if not hasattr(self, '_underlying_type'): 1224 assert self.kind.is_declaration() 1225 self._underlying_type = \ 1226 conf.lib.clang_getTypedefDeclUnderlyingType(self) 1227 1228 return self._underlying_type 1229 1230 @property 1231 def enum_type(self): 1232 """Return the integer type of an enum declaration. 1233 1234 Returns a Type corresponding to an integer. If the cursor is not for an 1235 enum, this raises. 1236 """ 1237 if not hasattr(self, '_enum_type'): 1238 assert self.kind == CursorKind.ENUM_DECL 1239 self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self) 1240 1241 return self._enum_type 1242 1243 @property 1244 def enum_value(self): 1245 """Return the value of an enum constant.""" 1246 if not hasattr(self, '_enum_value'): 1247 assert self.kind == CursorKind.ENUM_CONSTANT_DECL 1248 # Figure out the underlying type of the enum to know if it 1249 # is a signed or unsigned quantity. 1250 underlying_type = self.type 1251 if underlying_type.kind == TypeKind.ENUM: 1252 underlying_type = underlying_type.get_declaration().enum_type 1253 if underlying_type.kind in (TypeKind.CHAR_U, 1254 TypeKind.UCHAR, 1255 TypeKind.CHAR16, 1256 TypeKind.CHAR32, 1257 TypeKind.USHORT, 1258 TypeKind.UINT, 1259 TypeKind.ULONG, 1260 TypeKind.ULONGLONG, 1261 TypeKind.UINT128): 1262 self._enum_value = \ 1263 conf.lib.clang_getEnumConstantDeclUnsignedValue(self) 1264 else: 1265 self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self) 1266 return self._enum_value 1267 1268 @property 1269 def objc_type_encoding(self): 1270 """Return the Objective-C type encoding as a str.""" 1271 if not hasattr(self, '_objc_type_encoding'): 1272 self._objc_type_encoding = \ 1273 conf.lib.clang_getDeclObjCTypeEncoding(self) 1274 1275 return self._objc_type_encoding 1276 1277 @property 1278 def hash(self): 1279 """Returns a hash of the cursor as an int.""" 1280 if not hasattr(self, '_hash'): 1281 self._hash = conf.lib.clang_hashCursor(self) 1282 1283 return self._hash 1284 1285 @property 1286 def semantic_parent(self): 1287 """Return the semantic parent for this cursor.""" 1288 if not hasattr(self, '_semantic_parent'): 1289 self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self) 1290 1291 return self._semantic_parent 1292 1293 @property 1294 def lexical_parent(self): 1295 """Return the lexical parent for this cursor.""" 1296 if not hasattr(self, '_lexical_parent'): 1297 self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self) 1298 1299 return self._lexical_parent 1300 1301 @property 1302 def translation_unit(self): 1303 """Returns the TranslationUnit to which this Cursor belongs.""" 1304 # If this triggers an AttributeError, the instance was not properly 1305 # created. 1306 return self._tu 1307 1308 @property 1309 def referenced(self): 1310 """ 1311 For a cursor that is a reference, returns a cursor 1312 representing the entity that it references. 1313 """ 1314 if not hasattr(self, '_referenced'): 1315 self._referenced = conf.lib.clang_getCursorReferenced(self) 1316 1317 return self._referenced 1318 1319 @property 1320 def brief_comment(self): 1321 """Returns the brief comment text associated with that Cursor""" 1322 return conf.lib.clang_Cursor_getBriefCommentText(self) 1323 1324 @property 1325 def raw_comment(self): 1326 """Returns the raw comment text associated with that Cursor""" 1327 return conf.lib.clang_Cursor_getRawCommentText(self) 1328 1329 def get_arguments(self): 1330 """Return an iterator for accessing the arguments of this cursor.""" 1331 num_args = conf.lib.clang_Cursor_getNumArguments(self) 1332 for i in range(0, num_args): 1333 yield conf.lib.clang_Cursor_getArgument(self, i) 1334 1335 def get_children(self): 1336 """Return an iterator for accessing the children of this cursor.""" 1337 1338 # FIXME: Expose iteration from CIndex, PR6125. 1339 def visitor(child, parent, children): 1340 # FIXME: Document this assertion in API. 1341 # FIXME: There should just be an isNull method. 1342 assert child != conf.lib.clang_getNullCursor() 1343 1344 # Create reference to TU so it isn't GC'd before Cursor. 1345 child._tu = self._tu 1346 children.append(child) 1347 return 1 # continue 1348 children = [] 1349 conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor), 1350 children) 1351 return iter(children) 1352 1353 def get_tokens(self): 1354 """Obtain Token instances formulating that compose this Cursor. 1355 1356 This is a generator for Token instances. It returns all tokens which 1357 occupy the extent this cursor occupies. 1358 """ 1359 return TokenGroup.get_tokens(self._tu, self.extent) 1360 1361 def is_bitfield(self): 1362 """ 1363 Check if the field is a bitfield. 1364 """ 1365 return conf.lib.clang_Cursor_isBitField(self) 1366 1367 def get_bitfield_width(self): 1368 """ 1369 Retrieve the width of a bitfield. 1370 """ 1371 return conf.lib.clang_getFieldDeclBitWidth(self) 1372 1373 @staticmethod 1374 def from_result(res, fn, args): 1375 assert isinstance(res, Cursor) 1376 # FIXME: There should just be an isNull method. 1377 if res == conf.lib.clang_getNullCursor(): 1378 return None 1379 1380 # Store a reference to the TU in the Python object so it won't get GC'd 1381 # before the Cursor. 1382 tu = None 1383 for arg in args: 1384 if isinstance(arg, TranslationUnit): 1385 tu = arg 1386 break 1387 1388 if hasattr(arg, 'translation_unit'): 1389 tu = arg.translation_unit 1390 break 1391 1392 assert tu is not None 1393 1394 res._tu = tu 1395 return res 1396 1397 @staticmethod 1398 def from_cursor_result(res, fn, args): 1399 assert isinstance(res, Cursor) 1400 if res == conf.lib.clang_getNullCursor(): 1401 return None 1402 1403 res._tu = args[0]._tu 1404 return res 1405 1406### Type Kinds ### 1407 1408class TypeKind(object): 1409 """ 1410 Describes the kind of type. 1411 """ 1412 1413 # The unique kind objects, indexed by id. 1414 _kinds = [] 1415 _name_map = None 1416 1417 def __init__(self, value): 1418 if value >= len(TypeKind._kinds): 1419 TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1) 1420 if TypeKind._kinds[value] is not None: 1421 raise ValueError,'TypeKind already loaded' 1422 self.value = value 1423 TypeKind._kinds[value] = self 1424 TypeKind._name_map = None 1425 1426 def from_param(self): 1427 return self.value 1428 1429 @property 1430 def name(self): 1431 """Get the enumeration name of this cursor kind.""" 1432 if self._name_map is None: 1433 self._name_map = {} 1434 for key,value in TypeKind.__dict__.items(): 1435 if isinstance(value,TypeKind): 1436 self._name_map[value] = key 1437 return self._name_map[self] 1438 1439 @property 1440 def spelling(self): 1441 """Retrieve the spelling of this TypeKind.""" 1442 return conf.lib.clang_getTypeKindSpelling(self.value) 1443 1444 @staticmethod 1445 def from_id(id): 1446 if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None: 1447 raise ValueError,'Unknown type kind %d' % id 1448 return TypeKind._kinds[id] 1449 1450 def __repr__(self): 1451 return 'TypeKind.%s' % (self.name,) 1452 1453TypeKind.INVALID = TypeKind(0) 1454TypeKind.UNEXPOSED = TypeKind(1) 1455TypeKind.VOID = TypeKind(2) 1456TypeKind.BOOL = TypeKind(3) 1457TypeKind.CHAR_U = TypeKind(4) 1458TypeKind.UCHAR = TypeKind(5) 1459TypeKind.CHAR16 = TypeKind(6) 1460TypeKind.CHAR32 = TypeKind(7) 1461TypeKind.USHORT = TypeKind(8) 1462TypeKind.UINT = TypeKind(9) 1463TypeKind.ULONG = TypeKind(10) 1464TypeKind.ULONGLONG = TypeKind(11) 1465TypeKind.UINT128 = TypeKind(12) 1466TypeKind.CHAR_S = TypeKind(13) 1467TypeKind.SCHAR = TypeKind(14) 1468TypeKind.WCHAR = TypeKind(15) 1469TypeKind.SHORT = TypeKind(16) 1470TypeKind.INT = TypeKind(17) 1471TypeKind.LONG = TypeKind(18) 1472TypeKind.LONGLONG = TypeKind(19) 1473TypeKind.INT128 = TypeKind(20) 1474TypeKind.FLOAT = TypeKind(21) 1475TypeKind.DOUBLE = TypeKind(22) 1476TypeKind.LONGDOUBLE = TypeKind(23) 1477TypeKind.NULLPTR = TypeKind(24) 1478TypeKind.OVERLOAD = TypeKind(25) 1479TypeKind.DEPENDENT = TypeKind(26) 1480TypeKind.OBJCID = TypeKind(27) 1481TypeKind.OBJCCLASS = TypeKind(28) 1482TypeKind.OBJCSEL = TypeKind(29) 1483TypeKind.COMPLEX = TypeKind(100) 1484TypeKind.POINTER = TypeKind(101) 1485TypeKind.BLOCKPOINTER = TypeKind(102) 1486TypeKind.LVALUEREFERENCE = TypeKind(103) 1487TypeKind.RVALUEREFERENCE = TypeKind(104) 1488TypeKind.RECORD = TypeKind(105) 1489TypeKind.ENUM = TypeKind(106) 1490TypeKind.TYPEDEF = TypeKind(107) 1491TypeKind.OBJCINTERFACE = TypeKind(108) 1492TypeKind.OBJCOBJECTPOINTER = TypeKind(109) 1493TypeKind.FUNCTIONNOPROTO = TypeKind(110) 1494TypeKind.FUNCTIONPROTO = TypeKind(111) 1495TypeKind.CONSTANTARRAY = TypeKind(112) 1496TypeKind.VECTOR = TypeKind(113) 1497TypeKind.INCOMPLETEARRAY = TypeKind(114) 1498TypeKind.VARIABLEARRAY = TypeKind(115) 1499TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116) 1500TypeKind.MEMBERPOINTER = TypeKind(117) 1501 1502class Type(Structure): 1503 """ 1504 The type of an element in the abstract syntax tree. 1505 """ 1506 _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)] 1507 1508 @property 1509 def kind(self): 1510 """Return the kind of this type.""" 1511 return TypeKind.from_id(self._kind_id) 1512 1513 def argument_types(self): 1514 """Retrieve a container for the non-variadic arguments for this type. 1515 1516 The returned object is iterable and indexable. Each item in the 1517 container is a Type instance. 1518 """ 1519 class ArgumentsIterator(collections.Sequence): 1520 def __init__(self, parent): 1521 self.parent = parent 1522 self.length = None 1523 1524 def __len__(self): 1525 if self.length is None: 1526 self.length = conf.lib.clang_getNumArgTypes(self.parent) 1527 1528 return self.length 1529 1530 def __getitem__(self, key): 1531 # FIXME Support slice objects. 1532 if not isinstance(key, int): 1533 raise TypeError("Must supply a non-negative int.") 1534 1535 if key < 0: 1536 raise IndexError("Only non-negative indexes are accepted.") 1537 1538 if key >= len(self): 1539 raise IndexError("Index greater than container length: " 1540 "%d > %d" % ( key, len(self) )) 1541 1542 result = conf.lib.clang_getArgType(self.parent, key) 1543 if result.kind == TypeKind.INVALID: 1544 raise IndexError("Argument could not be retrieved.") 1545 1546 return result 1547 1548 assert self.kind == TypeKind.FUNCTIONPROTO 1549 return ArgumentsIterator(self) 1550 1551 @property 1552 def element_type(self): 1553 """Retrieve the Type of elements within this Type. 1554 1555 If accessed on a type that is not an array, complex, or vector type, an 1556 exception will be raised. 1557 """ 1558 result = conf.lib.clang_getElementType(self) 1559 if result.kind == TypeKind.INVALID: 1560 raise Exception('Element type not available on this type.') 1561 1562 return result 1563 1564 @property 1565 def element_count(self): 1566 """Retrieve the number of elements in this type. 1567 1568 Returns an int. 1569 1570 If the Type is not an array or vector, this raises. 1571 """ 1572 result = conf.lib.clang_getNumElements(self) 1573 if result < 0: 1574 raise Exception('Type does not have elements.') 1575 1576 return result 1577 1578 @property 1579 def translation_unit(self): 1580 """The TranslationUnit to which this Type is associated.""" 1581 # If this triggers an AttributeError, the instance was not properly 1582 # instantiated. 1583 return self._tu 1584 1585 @staticmethod 1586 def from_result(res, fn, args): 1587 assert isinstance(res, Type) 1588 1589 tu = None 1590 for arg in args: 1591 if hasattr(arg, 'translation_unit'): 1592 tu = arg.translation_unit 1593 break 1594 1595 assert tu is not None 1596 res._tu = tu 1597 1598 return res 1599 1600 def get_canonical(self): 1601 """ 1602 Return the canonical type for a Type. 1603 1604 Clang's type system explicitly models typedefs and all the 1605 ways a specific type can be represented. The canonical type 1606 is the underlying type with all the "sugar" removed. For 1607 example, if 'T' is a typedef for 'int', the canonical type for 1608 'T' would be 'int'. 1609 """ 1610 return conf.lib.clang_getCanonicalType(self) 1611 1612 def is_const_qualified(self): 1613 """Determine whether a Type has the "const" qualifier set. 1614 1615 This does not look through typedefs that may have added "const" 1616 at a different level. 1617 """ 1618 return conf.lib.clang_isConstQualifiedType(self) 1619 1620 def is_volatile_qualified(self): 1621 """Determine whether a Type has the "volatile" qualifier set. 1622 1623 This does not look through typedefs that may have added "volatile" 1624 at a different level. 1625 """ 1626 return conf.lib.clang_isVolatileQualifiedType(self) 1627 1628 def is_restrict_qualified(self): 1629 """Determine whether a Type has the "restrict" qualifier set. 1630 1631 This does not look through typedefs that may have added "restrict" at 1632 a different level. 1633 """ 1634 return conf.lib.clang_isRestrictQualifiedType(self) 1635 1636 def is_function_variadic(self): 1637 """Determine whether this function Type is a variadic function type.""" 1638 assert self.kind == TypeKind.FUNCTIONPROTO 1639 1640 return conf.lib.clang_isFunctionTypeVariadic(self) 1641 1642 def is_pod(self): 1643 """Determine whether this Type represents plain old data (POD).""" 1644 return conf.lib.clang_isPODType(self) 1645 1646 def get_pointee(self): 1647 """ 1648 For pointer types, returns the type of the pointee. 1649 """ 1650 return conf.lib.clang_getPointeeType(self) 1651 1652 def get_declaration(self): 1653 """ 1654 Return the cursor for the declaration of the given type. 1655 """ 1656 return conf.lib.clang_getTypeDeclaration(self) 1657 1658 def get_result(self): 1659 """ 1660 Retrieve the result type associated with a function type. 1661 """ 1662 return conf.lib.clang_getResultType(self) 1663 1664 def get_array_element_type(self): 1665 """ 1666 Retrieve the type of the elements of the array type. 1667 """ 1668 return conf.lib.clang_getArrayElementType(self) 1669 1670 def get_array_size(self): 1671 """ 1672 Retrieve the size of the constant array. 1673 """ 1674 return conf.lib.clang_getArraySize(self) 1675 1676 def get_class_type(self): 1677 """ 1678 Retrieve the class type of the member pointer type. 1679 """ 1680 return conf.lib.clang_Type_getClassType(self) 1681 1682 def get_align(self): 1683 """ 1684 Retrieve the alignment of the record. 1685 """ 1686 return conf.lib.clang_Type_getAlignOf(self) 1687 1688 def get_size(self): 1689 """ 1690 Retrieve the size of the record. 1691 """ 1692 return conf.lib.clang_Type_getSizeOf(self) 1693 1694 def get_offset(self, fieldname): 1695 """ 1696 Retrieve the offset of a field in the record. 1697 """ 1698 return conf.lib.clang_Type_getOffsetOf(self, c_char_p(fieldname)) 1699 1700 @property 1701 def spelling(self): 1702 """Retrieve the spelling of this Type.""" 1703 return conf.lib.clang_getTypeSpelling(self) 1704 1705 def __eq__(self, other): 1706 if type(other) != type(self): 1707 return False 1708 1709 return conf.lib.clang_equalTypes(self, other) 1710 1711 def __ne__(self, other): 1712 return not self.__eq__(other) 1713 1714## CIndex Objects ## 1715 1716# CIndex objects (derived from ClangObject) are essentially lightweight 1717# wrappers attached to some underlying object, which is exposed via CIndex as 1718# a void*. 1719 1720class ClangObject(object): 1721 """ 1722 A helper for Clang objects. This class helps act as an intermediary for 1723 the ctypes library and the Clang CIndex library. 1724 """ 1725 def __init__(self, obj): 1726 assert isinstance(obj, c_object_p) and obj 1727 self.obj = self._as_parameter_ = obj 1728 1729 def from_param(self): 1730 return self._as_parameter_ 1731 1732 1733class _CXUnsavedFile(Structure): 1734 """Helper for passing unsaved file arguments.""" 1735 _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)] 1736 1737# Functions calls through the python interface are rather slow. Fortunately, 1738# for most symboles, we do not need to perform a function call. Their spelling 1739# never changes and is consequently provided by this spelling cache. 1740SpellingCache = { 1741 # 0: CompletionChunk.Kind("Optional"), 1742 # 1: CompletionChunk.Kind("TypedText"), 1743 # 2: CompletionChunk.Kind("Text"), 1744 # 3: CompletionChunk.Kind("Placeholder"), 1745 # 4: CompletionChunk.Kind("Informative"), 1746 # 5 : CompletionChunk.Kind("CurrentParameter"), 1747 6: '(', # CompletionChunk.Kind("LeftParen"), 1748 7: ')', # CompletionChunk.Kind("RightParen"), 1749 8: ']', # CompletionChunk.Kind("LeftBracket"), 1750 9: ']', # CompletionChunk.Kind("RightBracket"), 1751 10: '{', # CompletionChunk.Kind("LeftBrace"), 1752 11: '}', # CompletionChunk.Kind("RightBrace"), 1753 12: '<', # CompletionChunk.Kind("LeftAngle"), 1754 13: '>', # CompletionChunk.Kind("RightAngle"), 1755 14: ', ', # CompletionChunk.Kind("Comma"), 1756 # 15: CompletionChunk.Kind("ResultType"), 1757 16: ':', # CompletionChunk.Kind("Colon"), 1758 17: ';', # CompletionChunk.Kind("SemiColon"), 1759 18: '=', # CompletionChunk.Kind("Equal"), 1760 19: ' ', # CompletionChunk.Kind("HorizontalSpace"), 1761 # 20: CompletionChunk.Kind("VerticalSpace") 1762} 1763 1764class CompletionChunk: 1765 class Kind: 1766 def __init__(self, name): 1767 self.name = name 1768 1769 def __str__(self): 1770 return self.name 1771 1772 def __repr__(self): 1773 return "<ChunkKind: %s>" % self 1774 1775 def __init__(self, completionString, key): 1776 self.cs = completionString 1777 self.key = key 1778 self.__kindNumberCache = -1 1779 1780 def __repr__(self): 1781 return "{'" + self.spelling + "', " + str(self.kind) + "}" 1782 1783 @CachedProperty 1784 def spelling(self): 1785 if self.__kindNumber in SpellingCache: 1786 return SpellingCache[self.__kindNumber] 1787 return conf.lib.clang_getCompletionChunkText(self.cs, self.key).spelling 1788 1789 # We do not use @CachedProperty here, as the manual implementation is 1790 # apparently still significantly faster. Please profile carefully if you 1791 # would like to add CachedProperty back. 1792 @property 1793 def __kindNumber(self): 1794 if self.__kindNumberCache == -1: 1795 self.__kindNumberCache = \ 1796 conf.lib.clang_getCompletionChunkKind(self.cs, self.key) 1797 return self.__kindNumberCache 1798 1799 @CachedProperty 1800 def kind(self): 1801 return completionChunkKindMap[self.__kindNumber] 1802 1803 @CachedProperty 1804 def string(self): 1805 res = conf.lib.clang_getCompletionChunkCompletionString(self.cs, 1806 self.key) 1807 1808 if (res): 1809 return CompletionString(res) 1810 else: 1811 None 1812 1813 def isKindOptional(self): 1814 return self.__kindNumber == 0 1815 1816 def isKindTypedText(self): 1817 return self.__kindNumber == 1 1818 1819 def isKindPlaceHolder(self): 1820 return self.__kindNumber == 3 1821 1822 def isKindInformative(self): 1823 return self.__kindNumber == 4 1824 1825 def isKindResultType(self): 1826 return self.__kindNumber == 15 1827 1828completionChunkKindMap = { 1829 0: CompletionChunk.Kind("Optional"), 1830 1: CompletionChunk.Kind("TypedText"), 1831 2: CompletionChunk.Kind("Text"), 1832 3: CompletionChunk.Kind("Placeholder"), 1833 4: CompletionChunk.Kind("Informative"), 1834 5: CompletionChunk.Kind("CurrentParameter"), 1835 6: CompletionChunk.Kind("LeftParen"), 1836 7: CompletionChunk.Kind("RightParen"), 1837 8: CompletionChunk.Kind("LeftBracket"), 1838 9: CompletionChunk.Kind("RightBracket"), 1839 10: CompletionChunk.Kind("LeftBrace"), 1840 11: CompletionChunk.Kind("RightBrace"), 1841 12: CompletionChunk.Kind("LeftAngle"), 1842 13: CompletionChunk.Kind("RightAngle"), 1843 14: CompletionChunk.Kind("Comma"), 1844 15: CompletionChunk.Kind("ResultType"), 1845 16: CompletionChunk.Kind("Colon"), 1846 17: CompletionChunk.Kind("SemiColon"), 1847 18: CompletionChunk.Kind("Equal"), 1848 19: CompletionChunk.Kind("HorizontalSpace"), 1849 20: CompletionChunk.Kind("VerticalSpace")} 1850 1851class CompletionString(ClangObject): 1852 class Availability: 1853 def __init__(self, name): 1854 self.name = name 1855 1856 def __str__(self): 1857 return self.name 1858 1859 def __repr__(self): 1860 return "<Availability: %s>" % self 1861 1862 def __len__(self): 1863 self.num_chunks 1864 1865 @CachedProperty 1866 def num_chunks(self): 1867 return conf.lib.clang_getNumCompletionChunks(self.obj) 1868 1869 def __getitem__(self, key): 1870 if self.num_chunks <= key: 1871 raise IndexError 1872 return CompletionChunk(self.obj, key) 1873 1874 @property 1875 def priority(self): 1876 return conf.lib.clang_getCompletionPriority(self.obj) 1877 1878 @property 1879 def availability(self): 1880 res = conf.lib.clang_getCompletionAvailability(self.obj) 1881 return availabilityKinds[res] 1882 1883 @property 1884 def briefComment(self): 1885 if conf.function_exists("clang_getCompletionBriefComment"): 1886 return conf.lib.clang_getCompletionBriefComment(self.obj) 1887 return _CXString() 1888 1889 def __repr__(self): 1890 return " | ".join([str(a) for a in self]) \ 1891 + " || Priority: " + str(self.priority) \ 1892 + " || Availability: " + str(self.availability) \ 1893 + " || Brief comment: " + str(self.briefComment.spelling) 1894 1895availabilityKinds = { 1896 0: CompletionChunk.Kind("Available"), 1897 1: CompletionChunk.Kind("Deprecated"), 1898 2: CompletionChunk.Kind("NotAvailable"), 1899 3: CompletionChunk.Kind("NotAccessible")} 1900 1901class CodeCompletionResult(Structure): 1902 _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)] 1903 1904 def __repr__(self): 1905 return str(CompletionString(self.completionString)) 1906 1907 @property 1908 def kind(self): 1909 return CursorKind.from_id(self.cursorKind) 1910 1911 @property 1912 def string(self): 1913 return CompletionString(self.completionString) 1914 1915class CCRStructure(Structure): 1916 _fields_ = [('results', POINTER(CodeCompletionResult)), 1917 ('numResults', c_int)] 1918 1919 def __len__(self): 1920 return self.numResults 1921 1922 def __getitem__(self, key): 1923 if len(self) <= key: 1924 raise IndexError 1925 1926 return self.results[key] 1927 1928class CodeCompletionResults(ClangObject): 1929 def __init__(self, ptr): 1930 assert isinstance(ptr, POINTER(CCRStructure)) and ptr 1931 self.ptr = self._as_parameter_ = ptr 1932 1933 def from_param(self): 1934 return self._as_parameter_ 1935 1936 def __del__(self): 1937 conf.lib.clang_disposeCodeCompleteResults(self) 1938 1939 @property 1940 def results(self): 1941 return self.ptr.contents 1942 1943 @property 1944 def diagnostics(self): 1945 class DiagnosticsItr: 1946 def __init__(self, ccr): 1947 self.ccr= ccr 1948 1949 def __len__(self): 1950 return int(\ 1951 conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr)) 1952 1953 def __getitem__(self, key): 1954 return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key) 1955 1956 return DiagnosticsItr(self) 1957 1958 1959class Index(ClangObject): 1960 """ 1961 The Index type provides the primary interface to the Clang CIndex library, 1962 primarily by providing an interface for reading and parsing translation 1963 units. 1964 """ 1965 1966 @staticmethod 1967 def create(excludeDecls=False): 1968 """ 1969 Create a new Index. 1970 Parameters: 1971 excludeDecls -- Exclude local declarations from translation units. 1972 """ 1973 return Index(conf.lib.clang_createIndex(excludeDecls, 0)) 1974 1975 def __del__(self): 1976 conf.lib.clang_disposeIndex(self) 1977 1978 def read(self, path): 1979 """Load a TranslationUnit from the given AST file.""" 1980 return TranslationUnit.from_ast_file(path, self) 1981 1982 def parse(self, path, args=None, unsaved_files=None, options = 0): 1983 """Load the translation unit from the given source code file by running 1984 clang and generating the AST before loading. Additional command line 1985 parameters can be passed to clang via the args parameter. 1986 1987 In-memory contents for files can be provided by passing a list of pairs 1988 to as unsaved_files, the first item should be the filenames to be mapped 1989 and the second should be the contents to be substituted for the 1990 file. The contents may be passed as strings or file objects. 1991 1992 If an error was encountered during parsing, a TranslationUnitLoadError 1993 will be raised. 1994 """ 1995 return TranslationUnit.from_source(path, args, unsaved_files, options, 1996 self) 1997 1998class TranslationUnit(ClangObject): 1999 """Represents a source code translation unit. 2000 2001 This is one of the main types in the API. Any time you wish to interact 2002 with Clang's representation of a source file, you typically start with a 2003 translation unit. 2004 """ 2005 2006 # Default parsing mode. 2007 PARSE_NONE = 0 2008 2009 # Instruct the parser to create a detailed processing record containing 2010 # metadata not normally retained. 2011 PARSE_DETAILED_PROCESSING_RECORD = 1 2012 2013 # Indicates that the translation unit is incomplete. This is typically used 2014 # when parsing headers. 2015 PARSE_INCOMPLETE = 2 2016 2017 # Instruct the parser to create a pre-compiled preamble for the translation 2018 # unit. This caches the preamble (included files at top of source file). 2019 # This is useful if the translation unit will be reparsed and you don't 2020 # want to incur the overhead of reparsing the preamble. 2021 PARSE_PRECOMPILED_PREAMBLE = 4 2022 2023 # Cache code completion information on parse. This adds time to parsing but 2024 # speeds up code completion. 2025 PARSE_CACHE_COMPLETION_RESULTS = 8 2026 2027 # Flags with values 16 and 32 are deprecated and intentionally omitted. 2028 2029 # Do not parse function bodies. This is useful if you only care about 2030 # searching for declarations/definitions. 2031 PARSE_SKIP_FUNCTION_BODIES = 64 2032 2033 # Used to indicate that brief documentation comments should be included 2034 # into the set of code completions returned from this translation unit. 2035 PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128 2036 2037 @classmethod 2038 def from_source(cls, filename, args=None, unsaved_files=None, options=0, 2039 index=None): 2040 """Create a TranslationUnit by parsing source. 2041 2042 This is capable of processing source code both from files on the 2043 filesystem as well as in-memory contents. 2044 2045 Command-line arguments that would be passed to clang are specified as 2046 a list via args. These can be used to specify include paths, warnings, 2047 etc. e.g. ["-Wall", "-I/path/to/include"]. 2048 2049 In-memory file content can be provided via unsaved_files. This is an 2050 iterable of 2-tuples. The first element is the str filename. The 2051 second element defines the content. Content can be provided as str 2052 source code or as file objects (anything with a read() method). If 2053 a file object is being used, content will be read until EOF and the 2054 read cursor will not be reset to its original position. 2055 2056 options is a bitwise or of TranslationUnit.PARSE_XXX flags which will 2057 control parsing behavior. 2058 2059 index is an Index instance to utilize. If not provided, a new Index 2060 will be created for this TranslationUnit. 2061 2062 To parse source from the filesystem, the filename of the file to parse 2063 is specified by the filename argument. Or, filename could be None and 2064 the args list would contain the filename(s) to parse. 2065 2066 To parse source from an in-memory buffer, set filename to the virtual 2067 filename you wish to associate with this source (e.g. "test.c"). The 2068 contents of that file are then provided in unsaved_files. 2069 2070 If an error occurs, a TranslationUnitLoadError is raised. 2071 2072 Please note that a TranslationUnit with parser errors may be returned. 2073 It is the caller's responsibility to check tu.diagnostics for errors. 2074 2075 Also note that Clang infers the source language from the extension of 2076 the input filename. If you pass in source code containing a C++ class 2077 declaration with the filename "test.c" parsing will fail. 2078 """ 2079 if args is None: 2080 args = [] 2081 2082 if unsaved_files is None: 2083 unsaved_files = [] 2084 2085 if index is None: 2086 index = Index.create() 2087 2088 args_array = None 2089 if len(args) > 0: 2090 args_array = (c_char_p * len(args))(* args) 2091 2092 unsaved_array = None 2093 if len(unsaved_files) > 0: 2094 unsaved_array = (_CXUnsavedFile * len(unsaved_files))() 2095 for i, (name, contents) in enumerate(unsaved_files): 2096 if hasattr(contents, "read"): 2097 contents = contents.read() 2098 2099 unsaved_array[i].name = name 2100 unsaved_array[i].contents = contents 2101 unsaved_array[i].length = len(contents) 2102 2103 ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array, 2104 len(args), unsaved_array, 2105 len(unsaved_files), options) 2106 2107 if not ptr: 2108 raise TranslationUnitLoadError("Error parsing translation unit.") 2109 2110 return cls(ptr, index=index) 2111 2112 @classmethod 2113 def from_ast_file(cls, filename, index=None): 2114 """Create a TranslationUnit instance from a saved AST file. 2115 2116 A previously-saved AST file (provided with -emit-ast or 2117 TranslationUnit.save()) is loaded from the filename specified. 2118 2119 If the file cannot be loaded, a TranslationUnitLoadError will be 2120 raised. 2121 2122 index is optional and is the Index instance to use. If not provided, 2123 a default Index will be created. 2124 """ 2125 if index is None: 2126 index = Index.create() 2127 2128 ptr = conf.lib.clang_createTranslationUnit(index, filename) 2129 if not ptr: 2130 raise TranslationUnitLoadError(filename) 2131 2132 return cls(ptr=ptr, index=index) 2133 2134 def __init__(self, ptr, index): 2135 """Create a TranslationUnit instance. 2136 2137 TranslationUnits should be created using one of the from_* @classmethod 2138 functions above. __init__ is only called internally. 2139 """ 2140 assert isinstance(index, Index) 2141 2142 ClangObject.__init__(self, ptr) 2143 2144 def __del__(self): 2145 conf.lib.clang_disposeTranslationUnit(self) 2146 2147 @property 2148 def cursor(self): 2149 """Retrieve the cursor that represents the given translation unit.""" 2150 return conf.lib.clang_getTranslationUnitCursor(self) 2151 2152 @property 2153 def spelling(self): 2154 """Get the original translation unit source file name.""" 2155 return conf.lib.clang_getTranslationUnitSpelling(self) 2156 2157 def get_includes(self): 2158 """ 2159 Return an iterable sequence of FileInclusion objects that describe the 2160 sequence of inclusions in a translation unit. The first object in 2161 this sequence is always the input file. Note that this method will not 2162 recursively iterate over header files included through precompiled 2163 headers. 2164 """ 2165 def visitor(fobj, lptr, depth, includes): 2166 if depth > 0: 2167 loc = lptr.contents 2168 includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) 2169 2170 # Automatically adapt CIndex/ctype pointers to python objects 2171 includes = [] 2172 conf.lib.clang_getInclusions(self, 2173 callbacks['translation_unit_includes'](visitor), includes) 2174 2175 return iter(includes) 2176 2177 def get_file(self, filename): 2178 """Obtain a File from this translation unit.""" 2179 2180 return File.from_name(self, filename) 2181 2182 def get_location(self, filename, position): 2183 """Obtain a SourceLocation for a file in this translation unit. 2184 2185 The position can be specified by passing: 2186 2187 - Integer file offset. Initial file offset is 0. 2188 - 2-tuple of (line number, column number). Initial file position is 2189 (0, 0) 2190 """ 2191 f = self.get_file(filename) 2192 2193 if isinstance(position, int): 2194 return SourceLocation.from_offset(self, f, position) 2195 2196 return SourceLocation.from_position(self, f, position[0], position[1]) 2197 2198 def get_extent(self, filename, locations): 2199 """Obtain a SourceRange from this translation unit. 2200 2201 The bounds of the SourceRange must ultimately be defined by a start and 2202 end SourceLocation. For the locations argument, you can pass: 2203 2204 - 2 SourceLocation instances in a 2-tuple or list. 2205 - 2 int file offsets via a 2-tuple or list. 2206 - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. 2207 2208 e.g. 2209 2210 get_extent('foo.c', (5, 10)) 2211 get_extent('foo.c', ((1, 1), (1, 15))) 2212 """ 2213 f = self.get_file(filename) 2214 2215 if len(locations) < 2: 2216 raise Exception('Must pass object with at least 2 elements') 2217 2218 start_location, end_location = locations 2219 2220 if hasattr(start_location, '__len__'): 2221 start_location = SourceLocation.from_position(self, f, 2222 start_location[0], start_location[1]) 2223 elif isinstance(start_location, int): 2224 start_location = SourceLocation.from_offset(self, f, 2225 start_location) 2226 2227 if hasattr(end_location, '__len__'): 2228 end_location = SourceLocation.from_position(self, f, 2229 end_location[0], end_location[1]) 2230 elif isinstance(end_location, int): 2231 end_location = SourceLocation.from_offset(self, f, end_location) 2232 2233 assert isinstance(start_location, SourceLocation) 2234 assert isinstance(end_location, SourceLocation) 2235 2236 return SourceRange.from_locations(start_location, end_location) 2237 2238 @property 2239 def diagnostics(self): 2240 """ 2241 Return an iterable (and indexable) object containing the diagnostics. 2242 """ 2243 class DiagIterator: 2244 def __init__(self, tu): 2245 self.tu = tu 2246 2247 def __len__(self): 2248 return int(conf.lib.clang_getNumDiagnostics(self.tu)) 2249 2250 def __getitem__(self, key): 2251 diag = conf.lib.clang_getDiagnostic(self.tu, key) 2252 if not diag: 2253 raise IndexError 2254 return Diagnostic(diag) 2255 2256 return DiagIterator(self) 2257 2258 def reparse(self, unsaved_files=None, options=0): 2259 """ 2260 Reparse an already parsed translation unit. 2261 2262 In-memory contents for files can be provided by passing a list of pairs 2263 as unsaved_files, the first items should be the filenames to be mapped 2264 and the second should be the contents to be substituted for the 2265 file. The contents may be passed as strings or file objects. 2266 """ 2267 if unsaved_files is None: 2268 unsaved_files = [] 2269 2270 unsaved_files_array = 0 2271 if len(unsaved_files): 2272 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() 2273 for i,(name,value) in enumerate(unsaved_files): 2274 if not isinstance(value, str): 2275 # FIXME: It would be great to support an efficient version 2276 # of this, one day. 2277 value = value.read() 2278 print value 2279 if not isinstance(value, str): 2280 raise TypeError,'Unexpected unsaved file contents.' 2281 unsaved_files_array[i].name = name 2282 unsaved_files_array[i].contents = value 2283 unsaved_files_array[i].length = len(value) 2284 ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files), 2285 unsaved_files_array, options) 2286 2287 def save(self, filename): 2288 """Saves the TranslationUnit to a file. 2289 2290 This is equivalent to passing -emit-ast to the clang frontend. The 2291 saved file can be loaded back into a TranslationUnit. Or, if it 2292 corresponds to a header, it can be used as a pre-compiled header file. 2293 2294 If an error occurs while saving, a TranslationUnitSaveError is raised. 2295 If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means 2296 the constructed TranslationUnit was not valid at time of save. In this 2297 case, the reason(s) why should be available via 2298 TranslationUnit.diagnostics(). 2299 2300 filename -- The path to save the translation unit to. 2301 """ 2302 options = conf.lib.clang_defaultSaveOptions(self) 2303 result = int(conf.lib.clang_saveTranslationUnit(self, filename, 2304 options)) 2305 if result != 0: 2306 raise TranslationUnitSaveError(result, 2307 'Error saving TranslationUnit.') 2308 2309 def codeComplete(self, path, line, column, unsaved_files=None, 2310 include_macros=False, include_code_patterns=False, 2311 include_brief_comments=False): 2312 """ 2313 Code complete in this translation unit. 2314 2315 In-memory contents for files can be provided by passing a list of pairs 2316 as unsaved_files, the first items should be the filenames to be mapped 2317 and the second should be the contents to be substituted for the 2318 file. The contents may be passed as strings or file objects. 2319 """ 2320 options = 0 2321 2322 if include_macros: 2323 options += 1 2324 2325 if include_code_patterns: 2326 options += 2 2327 2328 if include_brief_comments: 2329 options += 4 2330 2331 if unsaved_files is None: 2332 unsaved_files = [] 2333 2334 unsaved_files_array = 0 2335 if len(unsaved_files): 2336 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() 2337 for i,(name,value) in enumerate(unsaved_files): 2338 if not isinstance(value, str): 2339 # FIXME: It would be great to support an efficient version 2340 # of this, one day. 2341 value = value.read() 2342 print value 2343 if not isinstance(value, str): 2344 raise TypeError,'Unexpected unsaved file contents.' 2345 unsaved_files_array[i].name = name 2346 unsaved_files_array[i].contents = value 2347 unsaved_files_array[i].length = len(value) 2348 ptr = conf.lib.clang_codeCompleteAt(self, path, line, column, 2349 unsaved_files_array, len(unsaved_files), options) 2350 if ptr: 2351 return CodeCompletionResults(ptr) 2352 return None 2353 2354 def get_tokens(self, locations=None, extent=None): 2355 """Obtain tokens in this translation unit. 2356 2357 This is a generator for Token instances. The caller specifies a range 2358 of source code to obtain tokens for. The range can be specified as a 2359 2-tuple of SourceLocation or as a SourceRange. If both are defined, 2360 behavior is undefined. 2361 """ 2362 if locations is not None: 2363 extent = SourceRange(start=locations[0], end=locations[1]) 2364 2365 return TokenGroup.get_tokens(self, extent) 2366 2367class File(ClangObject): 2368 """ 2369 The File class represents a particular source file that is part of a 2370 translation unit. 2371 """ 2372 2373 @staticmethod 2374 def from_name(translation_unit, file_name): 2375 """Retrieve a file handle within the given translation unit.""" 2376 return File(conf.lib.clang_getFile(translation_unit, file_name)) 2377 2378 @property 2379 def name(self): 2380 """Return the complete file and path name of the file.""" 2381 return conf.lib.clang_getCString(conf.lib.clang_getFileName(self)) 2382 2383 @property 2384 def time(self): 2385 """Return the last modification time of the file.""" 2386 return conf.lib.clang_getFileTime(self) 2387 2388 def __str__(self): 2389 return self.name 2390 2391 def __repr__(self): 2392 return "<File: %s>" % (self.name) 2393 2394 @staticmethod 2395 def from_cursor_result(res, fn, args): 2396 assert isinstance(res, File) 2397 2398 # Copy a reference to the TranslationUnit to prevent premature GC. 2399 res._tu = args[0]._tu 2400 return res 2401 2402class FileInclusion(object): 2403 """ 2404 The FileInclusion class represents the inclusion of one source file by 2405 another via a '#include' directive or as the input file for the translation 2406 unit. This class provides information about the included file, the including 2407 file, the location of the '#include' directive and the depth of the included 2408 file in the stack. Note that the input file has depth 0. 2409 """ 2410 2411 def __init__(self, src, tgt, loc, depth): 2412 self.source = src 2413 self.include = tgt 2414 self.location = loc 2415 self.depth = depth 2416 2417 @property 2418 def is_input_file(self): 2419 """True if the included file is the input file.""" 2420 return self.depth == 0 2421 2422class CompilationDatabaseError(Exception): 2423 """Represents an error that occurred when working with a CompilationDatabase 2424 2425 Each error is associated to an enumerated value, accessible under 2426 e.cdb_error. Consumers can compare the value with one of the ERROR_ 2427 constants in this class. 2428 """ 2429 2430 # An unknown error occured 2431 ERROR_UNKNOWN = 0 2432 2433 # The database could not be loaded 2434 ERROR_CANNOTLOADDATABASE = 1 2435 2436 def __init__(self, enumeration, message): 2437 assert isinstance(enumeration, int) 2438 2439 if enumeration > 1: 2440 raise Exception("Encountered undefined CompilationDatabase error " 2441 "constant: %d. Please file a bug to have this " 2442 "value supported." % enumeration) 2443 2444 self.cdb_error = enumeration 2445 Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) 2446 2447class CompileCommand(object): 2448 """Represents the compile command used to build a file""" 2449 def __init__(self, cmd, ccmds): 2450 self.cmd = cmd 2451 # Keep a reference to the originating CompileCommands 2452 # to prevent garbage collection 2453 self.ccmds = ccmds 2454 2455 @property 2456 def directory(self): 2457 """Get the working directory for this CompileCommand""" 2458 return conf.lib.clang_CompileCommand_getDirectory(self.cmd) 2459 2460 @property 2461 def arguments(self): 2462 """ 2463 Get an iterable object providing each argument in the 2464 command line for the compiler invocation as a _CXString. 2465 2466 Invariant : the first argument is the compiler executable 2467 """ 2468 length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd) 2469 for i in xrange(length): 2470 yield conf.lib.clang_CompileCommand_getArg(self.cmd, i) 2471 2472class CompileCommands(object): 2473 """ 2474 CompileCommands is an iterable object containing all CompileCommand 2475 that can be used for building a specific file. 2476 """ 2477 def __init__(self, ccmds): 2478 self.ccmds = ccmds 2479 2480 def __del__(self): 2481 conf.lib.clang_CompileCommands_dispose(self.ccmds) 2482 2483 def __len__(self): 2484 return int(conf.lib.clang_CompileCommands_getSize(self.ccmds)) 2485 2486 def __getitem__(self, i): 2487 cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i) 2488 if not cc: 2489 raise IndexError 2490 return CompileCommand(cc, self) 2491 2492 @staticmethod 2493 def from_result(res, fn, args): 2494 if not res: 2495 return None 2496 return CompileCommands(res) 2497 2498class CompilationDatabase(ClangObject): 2499 """ 2500 The CompilationDatabase is a wrapper class around 2501 clang::tooling::CompilationDatabase 2502 2503 It enables querying how a specific source file can be built. 2504 """ 2505 2506 def __del__(self): 2507 conf.lib.clang_CompilationDatabase_dispose(self) 2508 2509 @staticmethod 2510 def from_result(res, fn, args): 2511 if not res: 2512 raise CompilationDatabaseError(0, 2513 "CompilationDatabase loading failed") 2514 return CompilationDatabase(res) 2515 2516 @staticmethod 2517 def fromDirectory(buildDir): 2518 """Builds a CompilationDatabase from the database found in buildDir""" 2519 errorCode = c_uint() 2520 try: 2521 cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir, 2522 byref(errorCode)) 2523 except CompilationDatabaseError as e: 2524 raise CompilationDatabaseError(int(errorCode.value), 2525 "CompilationDatabase loading failed") 2526 return cdb 2527 2528 def getCompileCommands(self, filename): 2529 """ 2530 Get an iterable object providing all the CompileCommands available to 2531 build filename. Returns None if filename is not found in the database. 2532 """ 2533 return conf.lib.clang_CompilationDatabase_getCompileCommands(self, 2534 filename) 2535 2536class Token(Structure): 2537 """Represents a single token from the preprocessor. 2538 2539 Tokens are effectively segments of source code. Source code is first parsed 2540 into tokens before being converted into the AST and Cursors. 2541 2542 Tokens are obtained from parsed TranslationUnit instances. You currently 2543 can't create tokens manually. 2544 """ 2545 _fields_ = [ 2546 ('int_data', c_uint * 4), 2547 ('ptr_data', c_void_p) 2548 ] 2549 2550 @property 2551 def spelling(self): 2552 """The spelling of this token. 2553 2554 This is the textual representation of the token in source. 2555 """ 2556 return conf.lib.clang_getTokenSpelling(self._tu, self) 2557 2558 @property 2559 def kind(self): 2560 """Obtain the TokenKind of the current token.""" 2561 return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) 2562 2563 @property 2564 def location(self): 2565 """The SourceLocation this Token occurs at.""" 2566 return conf.lib.clang_getTokenLocation(self._tu, self) 2567 2568 @property 2569 def extent(self): 2570 """The SourceRange this Token occupies.""" 2571 return conf.lib.clang_getTokenExtent(self._tu, self) 2572 2573 @property 2574 def cursor(self): 2575 """The Cursor this Token corresponds to.""" 2576 cursor = Cursor() 2577 2578 conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor)) 2579 2580 return cursor 2581 2582# Now comes the plumbing to hook up the C library. 2583 2584# Register callback types in common container. 2585callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p, 2586 POINTER(SourceLocation), c_uint, py_object) 2587callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object) 2588 2589# Functions strictly alphabetical order. 2590functionList = [ 2591 ("clang_annotateTokens", 2592 [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]), 2593 2594 ("clang_CompilationDatabase_dispose", 2595 [c_object_p]), 2596 2597 ("clang_CompilationDatabase_fromDirectory", 2598 [c_char_p, POINTER(c_uint)], 2599 c_object_p, 2600 CompilationDatabase.from_result), 2601 2602 ("clang_CompilationDatabase_getCompileCommands", 2603 [c_object_p, c_char_p], 2604 c_object_p, 2605 CompileCommands.from_result), 2606 2607 ("clang_CompileCommands_dispose", 2608 [c_object_p]), 2609 2610 ("clang_CompileCommands_getCommand", 2611 [c_object_p, c_uint], 2612 c_object_p), 2613 2614 ("clang_CompileCommands_getSize", 2615 [c_object_p], 2616 c_uint), 2617 2618 ("clang_CompileCommand_getArg", 2619 [c_object_p, c_uint], 2620 _CXString, 2621 _CXString.from_result), 2622 2623 ("clang_CompileCommand_getDirectory", 2624 [c_object_p], 2625 _CXString, 2626 _CXString.from_result), 2627 2628 ("clang_CompileCommand_getNumArgs", 2629 [c_object_p], 2630 c_uint), 2631 2632 ("clang_codeCompleteAt", 2633 [TranslationUnit, c_char_p, c_int, c_int, c_void_p, c_int, c_int], 2634 POINTER(CCRStructure)), 2635 2636 ("clang_codeCompleteGetDiagnostic", 2637 [CodeCompletionResults, c_int], 2638 Diagnostic), 2639 2640 ("clang_codeCompleteGetNumDiagnostics", 2641 [CodeCompletionResults], 2642 c_int), 2643 2644 ("clang_createIndex", 2645 [c_int, c_int], 2646 c_object_p), 2647 2648 ("clang_createTranslationUnit", 2649 [Index, c_char_p], 2650 c_object_p), 2651 2652 ("clang_CXXMethod_isPureVirtual", 2653 [Cursor], 2654 bool), 2655 2656 ("clang_CXXMethod_isStatic", 2657 [Cursor], 2658 bool), 2659 2660 ("clang_CXXMethod_isVirtual", 2661 [Cursor], 2662 bool), 2663 2664 ("clang_defaultSaveOptions", 2665 [TranslationUnit], 2666 c_uint), 2667 2668 ("clang_disposeCodeCompleteResults", 2669 [CodeCompletionResults]), 2670 2671# ("clang_disposeCXTUResourceUsage", 2672# [CXTUResourceUsage]), 2673 2674 ("clang_disposeDiagnostic", 2675 [Diagnostic]), 2676 2677 ("clang_disposeIndex", 2678 [Index]), 2679 2680 ("clang_disposeString", 2681 [_CXString]), 2682 2683 ("clang_disposeTokens", 2684 [TranslationUnit, POINTER(Token), c_uint]), 2685 2686 ("clang_disposeTranslationUnit", 2687 [TranslationUnit]), 2688 2689 ("clang_equalCursors", 2690 [Cursor, Cursor], 2691 bool), 2692 2693 ("clang_equalLocations", 2694 [SourceLocation, SourceLocation], 2695 bool), 2696 2697 ("clang_equalRanges", 2698 [SourceRange, SourceRange], 2699 bool), 2700 2701 ("clang_equalTypes", 2702 [Type, Type], 2703 bool), 2704 2705 ("clang_getArgType", 2706 [Type, c_uint], 2707 Type, 2708 Type.from_result), 2709 2710 ("clang_getArrayElementType", 2711 [Type], 2712 Type, 2713 Type.from_result), 2714 2715 ("clang_getArraySize", 2716 [Type], 2717 c_longlong), 2718 2719 ("clang_Type_getClassType", 2720 [Type], 2721 Type, 2722 Type.from_result), 2723 2724 ("clang_getFieldDeclBitWidth", 2725 [Cursor], 2726 c_int), 2727 2728 ("clang_getCanonicalCursor", 2729 [Cursor], 2730 Cursor, 2731 Cursor.from_cursor_result), 2732 2733 ("clang_getCanonicalType", 2734 [Type], 2735 Type, 2736 Type.from_result), 2737 2738 ("clang_getCompletionAvailability", 2739 [c_void_p], 2740 c_int), 2741 2742 ("clang_getCompletionBriefComment", 2743 [c_void_p], 2744 _CXString), 2745 2746 ("clang_getCompletionChunkCompletionString", 2747 [c_void_p, c_int], 2748 c_object_p), 2749 2750 ("clang_getCompletionChunkKind", 2751 [c_void_p, c_int], 2752 c_int), 2753 2754 ("clang_getCompletionChunkText", 2755 [c_void_p, c_int], 2756 _CXString), 2757 2758 ("clang_getCompletionPriority", 2759 [c_void_p], 2760 c_int), 2761 2762 ("clang_getCString", 2763 [_CXString], 2764 c_char_p), 2765 2766 ("clang_getCursor", 2767 [TranslationUnit, SourceLocation], 2768 Cursor), 2769 2770 ("clang_getCursorDefinition", 2771 [Cursor], 2772 Cursor, 2773 Cursor.from_result), 2774 2775 ("clang_getCursorDisplayName", 2776 [Cursor], 2777 _CXString, 2778 _CXString.from_result), 2779 2780 ("clang_getCursorExtent", 2781 [Cursor], 2782 SourceRange), 2783 2784 ("clang_getCursorLexicalParent", 2785 [Cursor], 2786 Cursor, 2787 Cursor.from_cursor_result), 2788 2789 ("clang_getCursorLocation", 2790 [Cursor], 2791 SourceLocation), 2792 2793 ("clang_getCursorReferenced", 2794 [Cursor], 2795 Cursor, 2796 Cursor.from_result), 2797 2798 ("clang_getCursorReferenceNameRange", 2799 [Cursor, c_uint, c_uint], 2800 SourceRange), 2801 2802 ("clang_getCursorSemanticParent", 2803 [Cursor], 2804 Cursor, 2805 Cursor.from_cursor_result), 2806 2807 ("clang_getCursorSpelling", 2808 [Cursor], 2809 _CXString, 2810 _CXString.from_result), 2811 2812 ("clang_getCursorType", 2813 [Cursor], 2814 Type, 2815 Type.from_result), 2816 2817 ("clang_getCursorUSR", 2818 [Cursor], 2819 _CXString, 2820 _CXString.from_result), 2821 2822# ("clang_getCXTUResourceUsage", 2823# [TranslationUnit], 2824# CXTUResourceUsage), 2825 2826 ("clang_getCXXAccessSpecifier", 2827 [Cursor], 2828 c_uint), 2829 2830 ("clang_getDeclObjCTypeEncoding", 2831 [Cursor], 2832 _CXString, 2833 _CXString.from_result), 2834 2835 ("clang_getDiagnostic", 2836 [c_object_p, c_uint], 2837 c_object_p), 2838 2839 ("clang_getDiagnosticCategory", 2840 [Diagnostic], 2841 c_uint), 2842 2843 ("clang_getDiagnosticCategoryName", 2844 [c_uint], 2845 _CXString, 2846 _CXString.from_result), 2847 2848 ("clang_getDiagnosticFixIt", 2849 [Diagnostic, c_uint, POINTER(SourceRange)], 2850 _CXString, 2851 _CXString.from_result), 2852 2853 ("clang_getDiagnosticLocation", 2854 [Diagnostic], 2855 SourceLocation), 2856 2857 ("clang_getDiagnosticNumFixIts", 2858 [Diagnostic], 2859 c_uint), 2860 2861 ("clang_getDiagnosticNumRanges", 2862 [Diagnostic], 2863 c_uint), 2864 2865 ("clang_getDiagnosticOption", 2866 [Diagnostic, POINTER(_CXString)], 2867 _CXString, 2868 _CXString.from_result), 2869 2870 ("clang_getDiagnosticRange", 2871 [Diagnostic, c_uint], 2872 SourceRange), 2873 2874 ("clang_getDiagnosticSeverity", 2875 [Diagnostic], 2876 c_int), 2877 2878 ("clang_getDiagnosticSpelling", 2879 [Diagnostic], 2880 _CXString, 2881 _CXString.from_result), 2882 2883 ("clang_getElementType", 2884 [Type], 2885 Type, 2886 Type.from_result), 2887 2888 ("clang_getEnumConstantDeclUnsignedValue", 2889 [Cursor], 2890 c_ulonglong), 2891 2892 ("clang_getEnumConstantDeclValue", 2893 [Cursor], 2894 c_longlong), 2895 2896 ("clang_getEnumDeclIntegerType", 2897 [Cursor], 2898 Type, 2899 Type.from_result), 2900 2901 ("clang_getFile", 2902 [TranslationUnit, c_char_p], 2903 c_object_p), 2904 2905 ("clang_getFileName", 2906 [File], 2907 _CXString), # TODO go through _CXString.from_result? 2908 2909 ("clang_getFileTime", 2910 [File], 2911 c_uint), 2912 2913 ("clang_getIBOutletCollectionType", 2914 [Cursor], 2915 Type, 2916 Type.from_result), 2917 2918 ("clang_getIncludedFile", 2919 [Cursor], 2920 File, 2921 File.from_cursor_result), 2922 2923 ("clang_getInclusions", 2924 [TranslationUnit, callbacks['translation_unit_includes'], py_object]), 2925 2926 ("clang_getInstantiationLocation", 2927 [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint), 2928 POINTER(c_uint)]), 2929 2930 ("clang_getLocation", 2931 [TranslationUnit, File, c_uint, c_uint], 2932 SourceLocation), 2933 2934 ("clang_getLocationForOffset", 2935 [TranslationUnit, File, c_uint], 2936 SourceLocation), 2937 2938 ("clang_getNullCursor", 2939 None, 2940 Cursor), 2941 2942 ("clang_getNumArgTypes", 2943 [Type], 2944 c_uint), 2945 2946 ("clang_getNumCompletionChunks", 2947 [c_void_p], 2948 c_int), 2949 2950 ("clang_getNumDiagnostics", 2951 [c_object_p], 2952 c_uint), 2953 2954 ("clang_getNumElements", 2955 [Type], 2956 c_longlong), 2957 2958 ("clang_getNumOverloadedDecls", 2959 [Cursor], 2960 c_uint), 2961 2962 ("clang_getOverloadedDecl", 2963 [Cursor, c_uint], 2964 Cursor, 2965 Cursor.from_cursor_result), 2966 2967 ("clang_getPointeeType", 2968 [Type], 2969 Type, 2970 Type.from_result), 2971 2972 ("clang_getRange", 2973 [SourceLocation, SourceLocation], 2974 SourceRange), 2975 2976 ("clang_getRangeEnd", 2977 [SourceRange], 2978 SourceLocation), 2979 2980 ("clang_getRangeStart", 2981 [SourceRange], 2982 SourceLocation), 2983 2984 ("clang_getResultType", 2985 [Type], 2986 Type, 2987 Type.from_result), 2988 2989 ("clang_getSpecializedCursorTemplate", 2990 [Cursor], 2991 Cursor, 2992 Cursor.from_cursor_result), 2993 2994 ("clang_getTemplateCursorKind", 2995 [Cursor], 2996 c_uint), 2997 2998 ("clang_getTokenExtent", 2999 [TranslationUnit, Token], 3000 SourceRange), 3001 3002 ("clang_getTokenKind", 3003 [Token], 3004 c_uint), 3005 3006 ("clang_getTokenLocation", 3007 [TranslationUnit, Token], 3008 SourceLocation), 3009 3010 ("clang_getTokenSpelling", 3011 [TranslationUnit, Token], 3012 _CXString, 3013 _CXString.from_result), 3014 3015 ("clang_getTranslationUnitCursor", 3016 [TranslationUnit], 3017 Cursor, 3018 Cursor.from_result), 3019 3020 ("clang_getTranslationUnitSpelling", 3021 [TranslationUnit], 3022 _CXString, 3023 _CXString.from_result), 3024 3025 ("clang_getTUResourceUsageName", 3026 [c_uint], 3027 c_char_p), 3028 3029 ("clang_getTypeDeclaration", 3030 [Type], 3031 Cursor, 3032 Cursor.from_result), 3033 3034 ("clang_getTypedefDeclUnderlyingType", 3035 [Cursor], 3036 Type, 3037 Type.from_result), 3038 3039 ("clang_getTypeKindSpelling", 3040 [c_uint], 3041 _CXString, 3042 _CXString.from_result), 3043 3044 ("clang_getTypeSpelling", 3045 [Type], 3046 _CXString, 3047 _CXString.from_result), 3048 3049 ("clang_hashCursor", 3050 [Cursor], 3051 c_uint), 3052 3053 ("clang_isAttribute", 3054 [CursorKind], 3055 bool), 3056 3057 ("clang_isConstQualifiedType", 3058 [Type], 3059 bool), 3060 3061 ("clang_isCursorDefinition", 3062 [Cursor], 3063 bool), 3064 3065 ("clang_isDeclaration", 3066 [CursorKind], 3067 bool), 3068 3069 ("clang_isExpression", 3070 [CursorKind], 3071 bool), 3072 3073 ("clang_isFileMultipleIncludeGuarded", 3074 [TranslationUnit, File], 3075 bool), 3076 3077 ("clang_isFunctionTypeVariadic", 3078 [Type], 3079 bool), 3080 3081 ("clang_isInvalid", 3082 [CursorKind], 3083 bool), 3084 3085 ("clang_isPODType", 3086 [Type], 3087 bool), 3088 3089 ("clang_isPreprocessing", 3090 [CursorKind], 3091 bool), 3092 3093 ("clang_isReference", 3094 [CursorKind], 3095 bool), 3096 3097 ("clang_isRestrictQualifiedType", 3098 [Type], 3099 bool), 3100 3101 ("clang_isStatement", 3102 [CursorKind], 3103 bool), 3104 3105 ("clang_isTranslationUnit", 3106 [CursorKind], 3107 bool), 3108 3109 ("clang_isUnexposed", 3110 [CursorKind], 3111 bool), 3112 3113 ("clang_isVirtualBase", 3114 [Cursor], 3115 bool), 3116 3117 ("clang_isVolatileQualifiedType", 3118 [Type], 3119 bool), 3120 3121 ("clang_parseTranslationUnit", 3122 [Index, c_char_p, c_void_p, c_int, c_void_p, c_int, c_int], 3123 c_object_p), 3124 3125 ("clang_reparseTranslationUnit", 3126 [TranslationUnit, c_int, c_void_p, c_int], 3127 c_int), 3128 3129 ("clang_saveTranslationUnit", 3130 [TranslationUnit, c_char_p, c_uint], 3131 c_int), 3132 3133 ("clang_tokenize", 3134 [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]), 3135 3136 ("clang_visitChildren", 3137 [Cursor, callbacks['cursor_visit'], py_object], 3138 c_uint), 3139 3140 ("clang_Cursor_getNumArguments", 3141 [Cursor], 3142 c_int), 3143 3144 ("clang_Cursor_getArgument", 3145 [Cursor, c_uint], 3146 Cursor, 3147 Cursor.from_result), 3148 3149 ("clang_Cursor_isBitField", 3150 [Cursor], 3151 bool), 3152 3153 ("clang_Cursor_getBriefCommentText", 3154 [Cursor], 3155 _CXString, 3156 _CXString.from_result), 3157 3158 ("clang_Cursor_getRawCommentText", 3159 [Cursor], 3160 _CXString, 3161 _CXString.from_result), 3162 3163 ("clang_Type_getAlignOf", 3164 [Type], 3165 c_longlong), 3166 3167 ("clang_Type_getOffsetOf", 3168 [Type, c_char_p], 3169 c_longlong), 3170 3171 ("clang_Type_getSizeOf", 3172 [Type], 3173 c_longlong), 3174] 3175 3176class LibclangError(Exception): 3177 def __init__(self, message): 3178 self.m = message 3179 3180 def __str__(self): 3181 return self.m 3182 3183def register_function(lib, item, ignore_errors): 3184 # A function may not exist, if these bindings are used with an older or 3185 # incompatible version of libclang.so. 3186 try: 3187 func = getattr(lib, item[0]) 3188 except AttributeError as e: 3189 msg = str(e) + ". Please ensure that your python bindings are "\ 3190 "compatible with your libclang.so version." 3191 if ignore_errors: 3192 return 3193 raise LibclangError(msg) 3194 3195 if len(item) >= 2: 3196 func.argtypes = item[1] 3197 3198 if len(item) >= 3: 3199 func.restype = item[2] 3200 3201 if len(item) == 4: 3202 func.errcheck = item[3] 3203 3204def register_functions(lib, ignore_errors): 3205 """Register function prototypes with a libclang library instance. 3206 3207 This must be called as part of library instantiation so Python knows how 3208 to call out to the shared library. 3209 """ 3210 3211 def register(item): 3212 return register_function(lib, item, ignore_errors) 3213 3214 map(register, functionList) 3215 3216class Config: 3217 library_path = None 3218 library_file = None 3219 compatibility_check = True 3220 loaded = False 3221 3222 @staticmethod 3223 def set_library_path(path): 3224 """Set the path in which to search for libclang""" 3225 if Config.loaded: 3226 raise Exception("library path must be set before before using " \ 3227 "any other functionalities in libclang.") 3228 3229 Config.library_path = path 3230 3231 @staticmethod 3232 def set_library_file(filename): 3233 """Set the exact location of libclang""" 3234 if Config.loaded: 3235 raise Exception("library file must be set before before using " \ 3236 "any other functionalities in libclang.") 3237 3238 Config.library_file = filename 3239 3240 @staticmethod 3241 def set_compatibility_check(check_status): 3242 """ Perform compatibility check when loading libclang 3243 3244 The python bindings are only tested and evaluated with the version of 3245 libclang they are provided with. To ensure correct behavior a (limited) 3246 compatibility check is performed when loading the bindings. This check 3247 will throw an exception, as soon as it fails. 3248 3249 In case these bindings are used with an older version of libclang, parts 3250 that have been stable between releases may still work. Users of the 3251 python bindings can disable the compatibility check. This will cause 3252 the python bindings to load, even though they are written for a newer 3253 version of libclang. Failures now arise if unsupported or incompatible 3254 features are accessed. The user is required to test himself if the 3255 features he is using are available and compatible between different 3256 libclang versions. 3257 """ 3258 if Config.loaded: 3259 raise Exception("compatibility_check must be set before before " \ 3260 "using any other functionalities in libclang.") 3261 3262 Config.compatibility_check = check_status 3263 3264 @CachedProperty 3265 def lib(self): 3266 lib = self.get_cindex_library() 3267 register_functions(lib, not Config.compatibility_check) 3268 Config.loaded = True 3269 return lib 3270 3271 def get_filename(self): 3272 if Config.library_file: 3273 return Config.library_file 3274 3275 import platform 3276 name = platform.system() 3277 3278 if name == 'Darwin': 3279 file = 'libclang.dylib' 3280 elif name == 'Windows': 3281 file = 'libclang.dll' 3282 else: 3283 file = 'libclang.so' 3284 3285 if Config.library_path: 3286 file = Config.library_path + '/' + file 3287 3288 return file 3289 3290 def get_cindex_library(self): 3291 try: 3292 library = cdll.LoadLibrary(self.get_filename()) 3293 except OSError as e: 3294 msg = str(e) + ". To provide a path to libclang use " \ 3295 "Config.set_library_path() or " \ 3296 "Config.set_library_file()." 3297 raise LibclangError(msg) 3298 3299 return library 3300 3301 def function_exists(self, name): 3302 try: 3303 getattr(self.lib, name) 3304 except AttributeError: 3305 return False 3306 3307 return True 3308 3309def register_enumerations(): 3310 for name, value in clang.enumerations.TokenKinds: 3311 TokenKind.register(value, name) 3312 3313conf = Config() 3314register_enumerations() 3315 3316__all__ = [ 3317 'Config', 3318 'CodeCompletionResults', 3319 'CompilationDatabase', 3320 'CompileCommands', 3321 'CompileCommand', 3322 'CursorKind', 3323 'Cursor', 3324 'Diagnostic', 3325 'File', 3326 'FixIt', 3327 'Index', 3328 'SourceLocation', 3329 'SourceRange', 3330 'TokenKind', 3331 'Token', 3332 'TranslationUnitLoadError', 3333 'TranslationUnit', 3334 'TypeKind', 3335 'Type', 3336] 3337