cindex.py revision eca36d1ae23d0e4c46a3c2c2b91a19f4a2f8055d
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' 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 toa a set of overloaded functions or function templates 725# that has not yet been resolved to a specific function or function template. 726CursorKind.OVERLOADED_DECL_REF = CursorKind(49) 727 728### 729# Invalid/Error Kinds 730 731CursorKind.INVALID_FILE = CursorKind(70) 732CursorKind.NO_DECL_FOUND = CursorKind(71) 733CursorKind.NOT_IMPLEMENTED = CursorKind(72) 734CursorKind.INVALID_CODE = CursorKind(73) 735 736### 737# Expression Kinds 738 739# An expression whose specific kind is not exposed via this interface. 740# 741# Unexposed expressions have the same operations as any other kind of 742# expression; one can extract their location information, spelling, children, 743# etc. However, the specific kind of the expression is not reported. 744CursorKind.UNEXPOSED_EXPR = CursorKind(100) 745 746# An expression that refers to some value declaration, such as a function, 747# varible, or enumerator. 748CursorKind.DECL_REF_EXPR = CursorKind(101) 749 750# An expression that refers to a member of a struct, union, class, Objective-C 751# class, etc. 752CursorKind.MEMBER_REF_EXPR = CursorKind(102) 753 754# An expression that calls a function. 755CursorKind.CALL_EXPR = CursorKind(103) 756 757# An expression that sends a message to an Objective-C object or class. 758CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104) 759 760# An expression that represents a block literal. 761CursorKind.BLOCK_EXPR = CursorKind(105) 762 763# An integer literal. 764CursorKind.INTEGER_LITERAL = CursorKind(106) 765 766# A floating point number literal. 767CursorKind.FLOATING_LITERAL = CursorKind(107) 768 769# An imaginary number literal. 770CursorKind.IMAGINARY_LITERAL = CursorKind(108) 771 772# A string literal. 773CursorKind.STRING_LITERAL = CursorKind(109) 774 775# A character literal. 776CursorKind.CHARACTER_LITERAL = CursorKind(110) 777 778# A parenthesized expression, e.g. "(1)". 779# 780# This AST node is only formed if full location information is requested. 781CursorKind.PAREN_EXPR = CursorKind(111) 782 783# This represents the unary-expression's (except sizeof and 784# alignof). 785CursorKind.UNARY_OPERATOR = CursorKind(112) 786 787# [C99 6.5.2.1] Array Subscripting. 788CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113) 789 790# A builtin binary operation expression such as "x + y" or 791# "x <= y". 792CursorKind.BINARY_OPERATOR = CursorKind(114) 793 794# Compound assignment such as "+=". 795CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115) 796 797# The ?: ternary operator. 798CursorKind.CONDITIONAL_OPERATOR = CursorKind(116) 799 800# An explicit cast in C (C99 6.5.4) or a C-style cast in C++ 801# (C++ [expr.cast]), which uses the syntax (Type)expr. 802# 803# For example: (int)f. 804CursorKind.CSTYLE_CAST_EXPR = CursorKind(117) 805 806# [C99 6.5.2.5] 807CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118) 808 809# Describes an C or C++ initializer list. 810CursorKind.INIT_LIST_EXPR = CursorKind(119) 811 812# The GNU address of label extension, representing &&label. 813CursorKind.ADDR_LABEL_EXPR = CursorKind(120) 814 815# This is the GNU Statement Expression extension: ({int X=4; X;}) 816CursorKind.StmtExpr = CursorKind(121) 817 818# Represents a C11 generic selection. 819CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122) 820 821# Implements the GNU __null extension, which is a name for a null 822# pointer constant that has integral type (e.g., int or long) and is the same 823# size and alignment as a pointer. 824# 825# The __null extension is typically only used by system headers, which define 826# NULL as __null in C++ rather than using 0 (which is an integer that may not 827# match the size of a pointer). 828CursorKind.GNU_NULL_EXPR = CursorKind(123) 829 830# C++'s static_cast<> expression. 831CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124) 832 833# C++'s dynamic_cast<> expression. 834CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125) 835 836# C++'s reinterpret_cast<> expression. 837CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126) 838 839# C++'s const_cast<> expression. 840CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127) 841 842# Represents an explicit C++ type conversion that uses "functional" 843# notion (C++ [expr.type.conv]). 844# 845# Example: 846# \code 847# x = int(0.5); 848# \endcode 849CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128) 850 851# A C++ typeid expression (C++ [expr.typeid]). 852CursorKind.CXX_TYPEID_EXPR = CursorKind(129) 853 854# [C++ 2.13.5] C++ Boolean Literal. 855CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130) 856 857# [C++0x 2.14.7] C++ Pointer Literal. 858CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131) 859 860# Represents the "this" expression in C++ 861CursorKind.CXX_THIS_EXPR = CursorKind(132) 862 863# [C++ 15] C++ Throw Expression. 864# 865# This handles 'throw' and 'throw' assignment-expression. When 866# assignment-expression isn't present, Op will be null. 867CursorKind.CXX_THROW_EXPR = CursorKind(133) 868 869# A new expression for memory allocation and constructor calls, e.g: 870# "new CXXNewExpr(foo)". 871CursorKind.CXX_NEW_EXPR = CursorKind(134) 872 873# A delete expression for memory deallocation and destructor calls, 874# e.g. "delete[] pArray". 875CursorKind.CXX_DELETE_EXPR = CursorKind(135) 876 877# Represents a unary expression. 878CursorKind.CXX_UNARY_EXPR = CursorKind(136) 879 880# ObjCStringLiteral, used for Objective-C string literals i.e. "foo". 881CursorKind.OBJC_STRING_LITERAL = CursorKind(137) 882 883# ObjCEncodeExpr, used for in Objective-C. 884CursorKind.OBJC_ENCODE_EXPR = CursorKind(138) 885 886# ObjCSelectorExpr used for in Objective-C. 887CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139) 888 889# Objective-C's protocol expression. 890CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140) 891 892# An Objective-C "bridged" cast expression, which casts between 893# Objective-C pointers and C pointers, transferring ownership in the process. 894# 895# \code 896# NSString *str = (__bridge_transfer NSString *)CFCreateString(); 897# \endcode 898CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141) 899 900# Represents a C++0x pack expansion that produces a sequence of 901# expressions. 902# 903# A pack expansion expression contains a pattern (which itself is an 904# expression) followed by an ellipsis. For example: 905CursorKind.PACK_EXPANSION_EXPR = CursorKind(142) 906 907# Represents an expression that computes the length of a parameter 908# pack. 909CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143) 910 911# A statement whose specific kind is not exposed via this interface. 912# 913# Unexposed statements have the same operations as any other kind of statement; 914# one can extract their location information, spelling, children, etc. However, 915# the specific kind of the statement is not reported. 916CursorKind.UNEXPOSED_STMT = CursorKind(200) 917 918# A labelled statement in a function. 919CursorKind.LABEL_STMT = CursorKind(201) 920 921# A compound statement 922CursorKind.COMPOUND_STMT = CursorKind(202) 923 924# A case statement. 925CursorKind.CASE_STMT = CursorKind(203) 926 927# A default statement. 928CursorKind.DEFAULT_STMT = CursorKind(204) 929 930# An if statement. 931CursorKind.IF_STMT = CursorKind(205) 932 933# A switch statement. 934CursorKind.SWITCH_STMT = CursorKind(206) 935 936# A while statement. 937CursorKind.WHILE_STMT = CursorKind(207) 938 939# A do statement. 940CursorKind.DO_STMT = CursorKind(208) 941 942# A for statement. 943CursorKind.FOR_STMT = CursorKind(209) 944 945# A goto statement. 946CursorKind.GOTO_STMT = CursorKind(210) 947 948# An indirect goto statement. 949CursorKind.INDIRECT_GOTO_STMT = CursorKind(211) 950 951# A continue statement. 952CursorKind.CONTINUE_STMT = CursorKind(212) 953 954# A break statement. 955CursorKind.BREAK_STMT = CursorKind(213) 956 957# A return statement. 958CursorKind.RETURN_STMT = CursorKind(214) 959 960# A GNU-style inline assembler statement. 961CursorKind.ASM_STMT = CursorKind(215) 962 963# Objective-C's overall @try-@catch-@finally statement. 964CursorKind.OBJC_AT_TRY_STMT = CursorKind(216) 965 966# Objective-C's @catch statement. 967CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217) 968 969# Objective-C's @finally statement. 970CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218) 971 972# Objective-C's @throw statement. 973CursorKind.OBJC_AT_THROW_STMT = CursorKind(219) 974 975# Objective-C's @synchronized statement. 976CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220) 977 978# Objective-C's autorealease pool statement. 979CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221) 980 981# Objective-C's for collection statement. 982CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222) 983 984# C++'s catch statement. 985CursorKind.CXX_CATCH_STMT = CursorKind(223) 986 987# C++'s try statement. 988CursorKind.CXX_TRY_STMT = CursorKind(224) 989 990# C++'s for (* : *) statement. 991CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225) 992 993# Windows Structured Exception Handling's try statement. 994CursorKind.SEH_TRY_STMT = CursorKind(226) 995 996# Windows Structured Exception Handling's except statement. 997CursorKind.SEH_EXCEPT_STMT = CursorKind(227) 998 999# Windows Structured Exception Handling's finally statement. 1000CursorKind.SEH_FINALLY_STMT = CursorKind(228) 1001 1002# The null statement. 1003CursorKind.NULL_STMT = CursorKind(230) 1004 1005# Adaptor class for mixing declarations with statements and expressions. 1006CursorKind.DECL_STMT = CursorKind(231) 1007 1008### 1009# Other Kinds 1010 1011# Cursor that represents the translation unit itself. 1012# 1013# The translation unit cursor exists primarily to act as the root cursor for 1014# traversing the contents of a translation unit. 1015CursorKind.TRANSLATION_UNIT = CursorKind(300) 1016 1017### 1018# Attributes 1019 1020# An attribute whoe specific kind is note exposed via this interface 1021CursorKind.UNEXPOSED_ATTR = CursorKind(400) 1022 1023CursorKind.IB_ACTION_ATTR = CursorKind(401) 1024CursorKind.IB_OUTLET_ATTR = CursorKind(402) 1025CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403) 1026 1027CursorKind.CXX_FINAL_ATTR = CursorKind(404) 1028CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405) 1029CursorKind.ANNOTATE_ATTR = CursorKind(406) 1030CursorKind.ASM_LABEL_ATTR = CursorKind(407) 1031 1032### 1033# Preprocessing 1034CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500) 1035CursorKind.MACRO_DEFINITION = CursorKind(501) 1036CursorKind.MACRO_INSTANTIATION = CursorKind(502) 1037CursorKind.INCLUSION_DIRECTIVE = CursorKind(503) 1038 1039### Cursors ### 1040 1041class Cursor(Structure): 1042 """ 1043 The Cursor class represents a reference to an element within the AST. It 1044 acts as a kind of iterator. 1045 """ 1046 _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)] 1047 1048 @staticmethod 1049 def from_location(tu, location): 1050 # We store a reference to the TU in the instance so the TU won't get 1051 # collected before the cursor. 1052 cursor = conf.lib.clang_getCursor(tu, location) 1053 cursor._tu = tu 1054 1055 return cursor 1056 1057 def __eq__(self, other): 1058 return conf.lib.clang_equalCursors(self, other) 1059 1060 def __ne__(self, other): 1061 return not self.__eq__(other) 1062 1063 def is_definition(self): 1064 """ 1065 Returns true if the declaration pointed at by the cursor is also a 1066 definition of that entity. 1067 """ 1068 return conf.lib.clang_isCursorDefinition(self) 1069 1070 def is_static_method(self): 1071 """Returns True if the cursor refers to a C++ member function or member 1072 function template that is declared 'static'. 1073 """ 1074 return conf.lib.clang_CXXMethod_isStatic(self) 1075 1076 def get_definition(self): 1077 """ 1078 If the cursor is a reference to a declaration or a declaration of 1079 some entity, return a cursor that points to the definition of that 1080 entity. 1081 """ 1082 # TODO: Should probably check that this is either a reference or 1083 # declaration prior to issuing the lookup. 1084 return conf.lib.clang_getCursorDefinition(self) 1085 1086 def get_usr(self): 1087 """Return the Unified Symbol Resultion (USR) for the entity referenced 1088 by the given cursor (or None). 1089 1090 A Unified Symbol Resolution (USR) is a string that identifies a 1091 particular entity (function, class, variable, etc.) within a 1092 program. USRs can be compared across translation units to determine, 1093 e.g., when references in one translation refer to an entity defined in 1094 another translation unit.""" 1095 return conf.lib.clang_getCursorUSR(self) 1096 1097 @property 1098 def kind(self): 1099 """Return the kind of this cursor.""" 1100 return CursorKind.from_id(self._kind_id) 1101 1102 @property 1103 def spelling(self): 1104 """Return the spelling of the entity pointed at by the cursor.""" 1105 if not self.kind.is_declaration(): 1106 # FIXME: clang_getCursorSpelling should be fixed to not assert on 1107 # this, for consistency with clang_getCursorUSR. 1108 return None 1109 if not hasattr(self, '_spelling'): 1110 self._spelling = conf.lib.clang_getCursorSpelling(self) 1111 1112 return self._spelling 1113 1114 @property 1115 def displayname(self): 1116 """ 1117 Return the display name for the entity referenced by this cursor. 1118 1119 The display name contains extra information that helps identify the cursor, 1120 such as the parameters of a function or template or the arguments of a 1121 class template specialization. 1122 """ 1123 if not hasattr(self, '_displayname'): 1124 self._displayname = conf.lib.clang_getCursorDisplayName(self) 1125 1126 return self._displayname 1127 1128 @property 1129 def location(self): 1130 """ 1131 Return the source location (the starting character) of the entity 1132 pointed at by the cursor. 1133 """ 1134 if not hasattr(self, '_loc'): 1135 self._loc = conf.lib.clang_getCursorLocation(self) 1136 1137 return self._loc 1138 1139 @property 1140 def extent(self): 1141 """ 1142 Return the source range (the range of text) occupied by the entity 1143 pointed at by the cursor. 1144 """ 1145 if not hasattr(self, '_extent'): 1146 self._extent = conf.lib.clang_getCursorExtent(self) 1147 1148 return self._extent 1149 1150 @property 1151 def type(self): 1152 """ 1153 Retrieve the Type (if any) of the entity pointed at by the cursor. 1154 """ 1155 if not hasattr(self, '_type'): 1156 self._type = conf.lib.clang_getCursorType(self) 1157 1158 return self._type 1159 1160 @property 1161 def canonical(self): 1162 """Return the canonical Cursor corresponding to this Cursor. 1163 1164 The canonical cursor is the cursor which is representative for the 1165 underlying entity. For example, if you have multiple forward 1166 declarations for the same class, the canonical cursor for the forward 1167 declarations will be identical. 1168 """ 1169 if not hasattr(self, '_canonical'): 1170 self._canonical = conf.lib.clang_getCanonicalCursor(self) 1171 1172 return self._canonical 1173 1174 @property 1175 def result_type(self): 1176 """Retrieve the Type of the result for this Cursor.""" 1177 if not hasattr(self, '_result_type'): 1178 self._result_type = conf.lib.clang_getResultType(self.type) 1179 1180 return self._result_type 1181 1182 @property 1183 def underlying_typedef_type(self): 1184 """Return the underlying type of a typedef declaration. 1185 1186 Returns a Type for the typedef this cursor is a declaration for. If 1187 the current cursor is not a typedef, this raises. 1188 """ 1189 if not hasattr(self, '_underlying_type'): 1190 assert self.kind.is_declaration() 1191 self._underlying_type = \ 1192 conf.lib.clang_getTypedefDeclUnderlyingType(self) 1193 1194 return self._underlying_type 1195 1196 @property 1197 def enum_type(self): 1198 """Return the integer type of an enum declaration. 1199 1200 Returns a Type corresponding to an integer. If the cursor is not for an 1201 enum, this raises. 1202 """ 1203 if not hasattr(self, '_enum_type'): 1204 assert self.kind == CursorKind.ENUM_DECL 1205 self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self) 1206 1207 return self._enum_type 1208 1209 @property 1210 def enum_value(self): 1211 """Return the value of an enum constant.""" 1212 if not hasattr(self, '_enum_value'): 1213 assert self.kind == CursorKind.ENUM_CONSTANT_DECL 1214 # Figure out the underlying type of the enum to know if it 1215 # is a signed or unsigned quantity. 1216 underlying_type = self.type 1217 if underlying_type.kind == TypeKind.ENUM: 1218 underlying_type = underlying_type.get_declaration().enum_type 1219 if underlying_type.kind in (TypeKind.CHAR_U, 1220 TypeKind.UCHAR, 1221 TypeKind.CHAR16, 1222 TypeKind.CHAR32, 1223 TypeKind.USHORT, 1224 TypeKind.UINT, 1225 TypeKind.ULONG, 1226 TypeKind.ULONGLONG, 1227 TypeKind.UINT128): 1228 self._enum_value = \ 1229 conf.lib.clang_getEnumConstantDeclUnsignedValue(self) 1230 else: 1231 self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self) 1232 return self._enum_value 1233 1234 @property 1235 def objc_type_encoding(self): 1236 """Return the Objective-C type encoding as a str.""" 1237 if not hasattr(self, '_objc_type_encoding'): 1238 self._objc_type_encoding = \ 1239 conf.lib.clang_getDeclObjCTypeEncoding(self) 1240 1241 return self._objc_type_encoding 1242 1243 @property 1244 def hash(self): 1245 """Returns a hash of the cursor as an int.""" 1246 if not hasattr(self, '_hash'): 1247 self._hash = conf.lib.clang_hashCursor(self) 1248 1249 return self._hash 1250 1251 @property 1252 def semantic_parent(self): 1253 """Return the semantic parent for this cursor.""" 1254 if not hasattr(self, '_semantic_parent'): 1255 self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self) 1256 1257 return self._semantic_parent 1258 1259 @property 1260 def lexical_parent(self): 1261 """Return the lexical parent for this cursor.""" 1262 if not hasattr(self, '_lexical_parent'): 1263 self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self) 1264 1265 return self._lexical_parent 1266 1267 @property 1268 def translation_unit(self): 1269 """Returns the TranslationUnit to which this Cursor belongs.""" 1270 # If this triggers an AttributeError, the instance was not properly 1271 # created. 1272 return self._tu 1273 1274 @property 1275 def referenced(self): 1276 """ 1277 For a cursor that is a reference, returns a cursor 1278 representing the entity that it references. 1279 """ 1280 if not hasattr(self, '_referenced'): 1281 self._referenced = conf.lib.clang_getCursorReferenced(self) 1282 1283 return self._referenced 1284 1285 def get_arguments(self): 1286 """Return an iterator for accessing the arguments of this cursor.""" 1287 num_args = conf.lib.clang_Cursor_getNumArguments(self) 1288 for i in range(0, num_args): 1289 yield conf.lib.clang_Cursor_getArgument(self, i) 1290 1291 def get_children(self): 1292 """Return an iterator for accessing the children of this cursor.""" 1293 1294 # FIXME: Expose iteration from CIndex, PR6125. 1295 def visitor(child, parent, children): 1296 # FIXME: Document this assertion in API. 1297 # FIXME: There should just be an isNull method. 1298 assert child != conf.lib.clang_getNullCursor() 1299 1300 # Create reference to TU so it isn't GC'd before Cursor. 1301 child._tu = self._tu 1302 children.append(child) 1303 return 1 # continue 1304 children = [] 1305 conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor), 1306 children) 1307 return iter(children) 1308 1309 def get_tokens(self): 1310 """Obtain Token instances formulating that compose this Cursor. 1311 1312 This is a generator for Token instances. It returns all tokens which 1313 occupy the extent this cursor occupies. 1314 """ 1315 return TokenGroup.get_tokens(self._tu, self.extent) 1316 1317 @staticmethod 1318 def from_result(res, fn, args): 1319 assert isinstance(res, Cursor) 1320 # FIXME: There should just be an isNull method. 1321 if res == conf.lib.clang_getNullCursor(): 1322 return None 1323 1324 # Store a reference to the TU in the Python object so it won't get GC'd 1325 # before the Cursor. 1326 tu = None 1327 for arg in args: 1328 if isinstance(arg, TranslationUnit): 1329 tu = arg 1330 break 1331 1332 if hasattr(arg, 'translation_unit'): 1333 tu = arg.translation_unit 1334 break 1335 1336 assert tu is not None 1337 1338 res._tu = tu 1339 return res 1340 1341 @staticmethod 1342 def from_cursor_result(res, fn, args): 1343 assert isinstance(res, Cursor) 1344 if res == conf.lib.clang_getNullCursor(): 1345 return None 1346 1347 res._tu = args[0]._tu 1348 return res 1349 1350### Type Kinds ### 1351 1352class TypeKind(object): 1353 """ 1354 Describes the kind of type. 1355 """ 1356 1357 # The unique kind objects, indexed by id. 1358 _kinds = [] 1359 _name_map = None 1360 1361 def __init__(self, value): 1362 if value >= len(TypeKind._kinds): 1363 TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1) 1364 if TypeKind._kinds[value] is not None: 1365 raise ValueError,'TypeKind already loaded' 1366 self.value = value 1367 TypeKind._kinds[value] = self 1368 TypeKind._name_map = None 1369 1370 def from_param(self): 1371 return self.value 1372 1373 @property 1374 def name(self): 1375 """Get the enumeration name of this cursor kind.""" 1376 if self._name_map is None: 1377 self._name_map = {} 1378 for key,value in TypeKind.__dict__.items(): 1379 if isinstance(value,TypeKind): 1380 self._name_map[value] = key 1381 return self._name_map[self] 1382 1383 @property 1384 def spelling(self): 1385 """Retrieve the spelling of this TypeKind.""" 1386 return conf.lib.clang_getTypeKindSpelling(self.value) 1387 1388 @staticmethod 1389 def from_id(id): 1390 if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None: 1391 raise ValueError,'Unknown type kind %d' % id 1392 return TypeKind._kinds[id] 1393 1394 def __repr__(self): 1395 return 'TypeKind.%s' % (self.name,) 1396 1397TypeKind.INVALID = TypeKind(0) 1398TypeKind.UNEXPOSED = TypeKind(1) 1399TypeKind.VOID = TypeKind(2) 1400TypeKind.BOOL = TypeKind(3) 1401TypeKind.CHAR_U = TypeKind(4) 1402TypeKind.UCHAR = TypeKind(5) 1403TypeKind.CHAR16 = TypeKind(6) 1404TypeKind.CHAR32 = TypeKind(7) 1405TypeKind.USHORT = TypeKind(8) 1406TypeKind.UINT = TypeKind(9) 1407TypeKind.ULONG = TypeKind(10) 1408TypeKind.ULONGLONG = TypeKind(11) 1409TypeKind.UINT128 = TypeKind(12) 1410TypeKind.CHAR_S = TypeKind(13) 1411TypeKind.SCHAR = TypeKind(14) 1412TypeKind.WCHAR = TypeKind(15) 1413TypeKind.SHORT = TypeKind(16) 1414TypeKind.INT = TypeKind(17) 1415TypeKind.LONG = TypeKind(18) 1416TypeKind.LONGLONG = TypeKind(19) 1417TypeKind.INT128 = TypeKind(20) 1418TypeKind.FLOAT = TypeKind(21) 1419TypeKind.DOUBLE = TypeKind(22) 1420TypeKind.LONGDOUBLE = TypeKind(23) 1421TypeKind.NULLPTR = TypeKind(24) 1422TypeKind.OVERLOAD = TypeKind(25) 1423TypeKind.DEPENDENT = TypeKind(26) 1424TypeKind.OBJCID = TypeKind(27) 1425TypeKind.OBJCCLASS = TypeKind(28) 1426TypeKind.OBJCSEL = TypeKind(29) 1427TypeKind.COMPLEX = TypeKind(100) 1428TypeKind.POINTER = TypeKind(101) 1429TypeKind.BLOCKPOINTER = TypeKind(102) 1430TypeKind.LVALUEREFERENCE = TypeKind(103) 1431TypeKind.RVALUEREFERENCE = TypeKind(104) 1432TypeKind.RECORD = TypeKind(105) 1433TypeKind.ENUM = TypeKind(106) 1434TypeKind.TYPEDEF = TypeKind(107) 1435TypeKind.OBJCINTERFACE = TypeKind(108) 1436TypeKind.OBJCOBJECTPOINTER = TypeKind(109) 1437TypeKind.FUNCTIONNOPROTO = TypeKind(110) 1438TypeKind.FUNCTIONPROTO = TypeKind(111) 1439TypeKind.CONSTANTARRAY = TypeKind(112) 1440TypeKind.VECTOR = TypeKind(113) 1441 1442class Type(Structure): 1443 """ 1444 The type of an element in the abstract syntax tree. 1445 """ 1446 _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)] 1447 1448 @property 1449 def kind(self): 1450 """Return the kind of this type.""" 1451 return TypeKind.from_id(self._kind_id) 1452 1453 def argument_types(self): 1454 """Retrieve a container for the non-variadic arguments for this type. 1455 1456 The returned object is iterable and indexable. Each item in the 1457 container is a Type instance. 1458 """ 1459 class ArgumentsIterator(collections.Sequence): 1460 def __init__(self, parent): 1461 self.parent = parent 1462 self.length = None 1463 1464 def __len__(self): 1465 if self.length is None: 1466 self.length = conf.lib.clang_getNumArgTypes(self.parent) 1467 1468 return self.length 1469 1470 def __getitem__(self, key): 1471 # FIXME Support slice objects. 1472 if not isinstance(key, int): 1473 raise TypeError("Must supply a non-negative int.") 1474 1475 if key < 0: 1476 raise IndexError("Only non-negative indexes are accepted.") 1477 1478 if key >= len(self): 1479 raise IndexError("Index greater than container length: " 1480 "%d > %d" % ( key, len(self) )) 1481 1482 result = conf.lib.clang_getArgType(self.parent, key) 1483 if result.kind == TypeKind.INVALID: 1484 raise IndexError("Argument could not be retrieved.") 1485 1486 return result 1487 1488 assert self.kind == TypeKind.FUNCTIONPROTO 1489 return ArgumentsIterator(self) 1490 1491 @property 1492 def element_type(self): 1493 """Retrieve the Type of elements within this Type. 1494 1495 If accessed on a type that is not an array, complex, or vector type, an 1496 exception will be raised. 1497 """ 1498 result = conf.lib.clang_getElementType(self) 1499 if result.kind == TypeKind.INVALID: 1500 raise Exception('Element type not available on this type.') 1501 1502 return result 1503 1504 @property 1505 def element_count(self): 1506 """Retrieve the number of elements in this type. 1507 1508 Returns an int. 1509 1510 If the Type is not an array or vector, this raises. 1511 """ 1512 result = conf.lib.clang_getNumElements(self) 1513 if result < 0: 1514 raise Exception('Type does not have elements.') 1515 1516 return result 1517 1518 @property 1519 def translation_unit(self): 1520 """The TranslationUnit to which this Type is associated.""" 1521 # If this triggers an AttributeError, the instance was not properly 1522 # instantiated. 1523 return self._tu 1524 1525 @staticmethod 1526 def from_result(res, fn, args): 1527 assert isinstance(res, Type) 1528 1529 tu = None 1530 for arg in args: 1531 if hasattr(arg, 'translation_unit'): 1532 tu = arg.translation_unit 1533 break 1534 1535 assert tu is not None 1536 res._tu = tu 1537 1538 return res 1539 1540 def get_canonical(self): 1541 """ 1542 Return the canonical type for a Type. 1543 1544 Clang's type system explicitly models typedefs and all the 1545 ways a specific type can be represented. The canonical type 1546 is the underlying type with all the "sugar" removed. For 1547 example, if 'T' is a typedef for 'int', the canonical type for 1548 'T' would be 'int'. 1549 """ 1550 return conf.lib.clang_getCanonicalType(self) 1551 1552 def is_const_qualified(self): 1553 """Determine whether a Type has the "const" qualifier set. 1554 1555 This does not look through typedefs that may have added "const" 1556 at a different level. 1557 """ 1558 return conf.lib.clang_isConstQualifiedType(self) 1559 1560 def is_volatile_qualified(self): 1561 """Determine whether a Type has the "volatile" qualifier set. 1562 1563 This does not look through typedefs that may have added "volatile" 1564 at a different level. 1565 """ 1566 return conf.lib.clang_isVolatileQualifiedType(self) 1567 1568 def is_restrict_qualified(self): 1569 """Determine whether a Type has the "restrict" qualifier set. 1570 1571 This does not look through typedefs that may have added "restrict" at 1572 a different level. 1573 """ 1574 return conf.lib.clang_isRestrictQualifiedType(self) 1575 1576 def is_function_variadic(self): 1577 """Determine whether this function Type is a variadic function type.""" 1578 assert self.kind == TypeKind.FUNCTIONPROTO 1579 1580 return conf.lib.clang_isFunctionTypeVariadic(self) 1581 1582 def is_pod(self): 1583 """Determine whether this Type represents plain old data (POD).""" 1584 return conf.lib.clang_isPODType(self) 1585 1586 def get_pointee(self): 1587 """ 1588 For pointer types, returns the type of the pointee. 1589 """ 1590 return conf.lib.clang_getPointeeType(self) 1591 1592 def get_declaration(self): 1593 """ 1594 Return the cursor for the declaration of the given type. 1595 """ 1596 return conf.lib.clang_getTypeDeclaration(self) 1597 1598 def get_result(self): 1599 """ 1600 Retrieve the result type associated with a function type. 1601 """ 1602 return conf.lib.clang_getResultType(self) 1603 1604 def get_array_element_type(self): 1605 """ 1606 Retrieve the type of the elements of the array type. 1607 """ 1608 return conf.lib.clang_getArrayElementType(self) 1609 1610 def get_array_size(self): 1611 """ 1612 Retrieve the size of the constant array. 1613 """ 1614 return conf.lib.clang_getArraySize(self) 1615 1616 def __eq__(self, other): 1617 if type(other) != type(self): 1618 return False 1619 1620 return conf.lib.clang_equalTypes(self, other) 1621 1622 def __ne__(self, other): 1623 return not self.__eq__(other) 1624 1625## CIndex Objects ## 1626 1627# CIndex objects (derived from ClangObject) are essentially lightweight 1628# wrappers attached to some underlying object, which is exposed via CIndex as 1629# a void*. 1630 1631class ClangObject(object): 1632 """ 1633 A helper for Clang objects. This class helps act as an intermediary for 1634 the ctypes library and the Clang CIndex library. 1635 """ 1636 def __init__(self, obj): 1637 assert isinstance(obj, c_object_p) and obj 1638 self.obj = self._as_parameter_ = obj 1639 1640 def from_param(self): 1641 return self._as_parameter_ 1642 1643 1644class _CXUnsavedFile(Structure): 1645 """Helper for passing unsaved file arguments.""" 1646 _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)] 1647 1648class CompletionChunk: 1649 class Kind: 1650 def __init__(self, name): 1651 self.name = name 1652 1653 def __str__(self): 1654 return self.name 1655 1656 def __repr__(self): 1657 return "<ChunkKind: %s>" % self 1658 1659 def __init__(self, completionString, key): 1660 self.cs = completionString 1661 self.key = key 1662 self.__kindNumberCache = -1 1663 1664 def __repr__(self): 1665 return "{'" + self.spelling + "', " + str(self.kind) + "}" 1666 1667 @CachedProperty 1668 def spelling(self): 1669 return conf.lib.clang_getCompletionChunkText(self.cs, self.key).spelling 1670 1671 # We do not use @CachedProperty here, as the manual implementation is 1672 # apparently still significantly faster. Please profile carefully if you 1673 # would like to add CachedProperty back. 1674 @property 1675 def __kindNumber(self): 1676 if self.__kindNumberCache == -1: 1677 self.__kindNumberCache = \ 1678 conf.lib.clang_getCompletionChunkKind(self.cs, self.key) 1679 return self.__kindNumberCache 1680 1681 @CachedProperty 1682 def kind(self): 1683 return completionChunkKindMap[self.__kindNumber] 1684 1685 @CachedProperty 1686 def string(self): 1687 res = conf.lib.clang_getCompletionChunkCompletionString(self.cs, 1688 self.key) 1689 1690 if (res): 1691 return CompletionString(res) 1692 else: 1693 None 1694 1695 def isKindOptional(self): 1696 return self.__kindNumber == 0 1697 1698 def isKindTypedText(self): 1699 return self.__kindNumber == 1 1700 1701 def isKindPlaceHolder(self): 1702 return self.__kindNumber == 3 1703 1704 def isKindInformative(self): 1705 return self.__kindNumber == 4 1706 1707 def isKindResultType(self): 1708 return self.__kindNumber == 15 1709 1710completionChunkKindMap = { 1711 0: CompletionChunk.Kind("Optional"), 1712 1: CompletionChunk.Kind("TypedText"), 1713 2: CompletionChunk.Kind("Text"), 1714 3: CompletionChunk.Kind("Placeholder"), 1715 4: CompletionChunk.Kind("Informative"), 1716 5: CompletionChunk.Kind("CurrentParameter"), 1717 6: CompletionChunk.Kind("LeftParen"), 1718 7: CompletionChunk.Kind("RightParen"), 1719 8: CompletionChunk.Kind("LeftBracket"), 1720 9: CompletionChunk.Kind("RightBracket"), 1721 10: CompletionChunk.Kind("LeftBrace"), 1722 11: CompletionChunk.Kind("RightBrace"), 1723 12: CompletionChunk.Kind("LeftAngle"), 1724 13: CompletionChunk.Kind("RightAngle"), 1725 14: CompletionChunk.Kind("Comma"), 1726 15: CompletionChunk.Kind("ResultType"), 1727 16: CompletionChunk.Kind("Colon"), 1728 17: CompletionChunk.Kind("SemiColon"), 1729 18: CompletionChunk.Kind("Equal"), 1730 19: CompletionChunk.Kind("HorizontalSpace"), 1731 20: CompletionChunk.Kind("VerticalSpace")} 1732 1733class CompletionString(ClangObject): 1734 class Availability: 1735 def __init__(self, name): 1736 self.name = name 1737 1738 def __str__(self): 1739 return self.name 1740 1741 def __repr__(self): 1742 return "<Availability: %s>" % self 1743 1744 def __len__(self): 1745 self.num_chunks 1746 1747 @CachedProperty 1748 def num_chunks(self): 1749 return conf.lib.clang_getNumCompletionChunks(self.obj) 1750 1751 def __getitem__(self, key): 1752 if self.num_chunks <= key: 1753 raise IndexError 1754 return CompletionChunk(self.obj, key) 1755 1756 @property 1757 def priority(self): 1758 return conf.lib.clang_getCompletionPriority(self.obj) 1759 1760 @property 1761 def availability(self): 1762 res = conf.lib.clang_getCompletionAvailability(self.obj) 1763 return availabilityKinds[res] 1764 1765 @property 1766 def briefComment(self): 1767 if conf.function_exists("clang_getCompletionBriefComment"): 1768 return conf.lib.clang_getCompletionBriefComment(self.obj) 1769 return _CXString() 1770 1771 def __repr__(self): 1772 return " | ".join([str(a) for a in self]) \ 1773 + " || Priority: " + str(self.priority) \ 1774 + " || Availability: " + str(self.availability) \ 1775 + " || Brief comment: " + str(self.briefComment.spelling) 1776 1777availabilityKinds = { 1778 0: CompletionChunk.Kind("Available"), 1779 1: CompletionChunk.Kind("Deprecated"), 1780 2: CompletionChunk.Kind("NotAvailable"), 1781 3: CompletionChunk.Kind("NotAccessible")} 1782 1783class CodeCompletionResult(Structure): 1784 _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)] 1785 1786 def __repr__(self): 1787 return str(CompletionString(self.completionString)) 1788 1789 @property 1790 def kind(self): 1791 return CursorKind.from_id(self.cursorKind) 1792 1793 @property 1794 def string(self): 1795 return CompletionString(self.completionString) 1796 1797class CCRStructure(Structure): 1798 _fields_ = [('results', POINTER(CodeCompletionResult)), 1799 ('numResults', c_int)] 1800 1801 def __len__(self): 1802 return self.numResults 1803 1804 def __getitem__(self, key): 1805 if len(self) <= key: 1806 raise IndexError 1807 1808 return self.results[key] 1809 1810class CodeCompletionResults(ClangObject): 1811 def __init__(self, ptr): 1812 assert isinstance(ptr, POINTER(CCRStructure)) and ptr 1813 self.ptr = self._as_parameter_ = ptr 1814 1815 def from_param(self): 1816 return self._as_parameter_ 1817 1818 def __del__(self): 1819 conf.lib.clang_disposeCodeCompleteResults(self) 1820 1821 @property 1822 def results(self): 1823 return self.ptr.contents 1824 1825 @property 1826 def diagnostics(self): 1827 class DiagnosticsItr: 1828 def __init__(self, ccr): 1829 self.ccr= ccr 1830 1831 def __len__(self): 1832 return int(\ 1833 conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr)) 1834 1835 def __getitem__(self, key): 1836 return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key) 1837 1838 return DiagnosticsItr(self) 1839 1840 1841class Index(ClangObject): 1842 """ 1843 The Index type provides the primary interface to the Clang CIndex library, 1844 primarily by providing an interface for reading and parsing translation 1845 units. 1846 """ 1847 1848 @staticmethod 1849 def create(excludeDecls=False): 1850 """ 1851 Create a new Index. 1852 Parameters: 1853 excludeDecls -- Exclude local declarations from translation units. 1854 """ 1855 return Index(conf.lib.clang_createIndex(excludeDecls, 0)) 1856 1857 def __del__(self): 1858 conf.lib.clang_disposeIndex(self) 1859 1860 def read(self, path): 1861 """Load a TranslationUnit from the given AST file.""" 1862 return TranslationUnit.from_ast(path, self) 1863 1864 def parse(self, path, args=None, unsaved_files=None, options = 0): 1865 """Load the translation unit from the given source code file by running 1866 clang and generating the AST before loading. Additional command line 1867 parameters can be passed to clang via the args parameter. 1868 1869 In-memory contents for files can be provided by passing a list of pairs 1870 to as unsaved_files, the first item should be the filenames to be mapped 1871 and the second should be the contents to be substituted for the 1872 file. The contents may be passed as strings or file objects. 1873 1874 If an error was encountered during parsing, a TranslationUnitLoadError 1875 will be raised. 1876 """ 1877 return TranslationUnit.from_source(path, args, unsaved_files, options, 1878 self) 1879 1880class TranslationUnit(ClangObject): 1881 """Represents a source code translation unit. 1882 1883 This is one of the main types in the API. Any time you wish to interact 1884 with Clang's representation of a source file, you typically start with a 1885 translation unit. 1886 """ 1887 1888 # Default parsing mode. 1889 PARSE_NONE = 0 1890 1891 # Instruct the parser to create a detailed processing record containing 1892 # metadata not normally retained. 1893 PARSE_DETAILED_PROCESSING_RECORD = 1 1894 1895 # Indicates that the translation unit is incomplete. This is typically used 1896 # when parsing headers. 1897 PARSE_INCOMPLETE = 2 1898 1899 # Instruct the parser to create a pre-compiled preamble for the translation 1900 # unit. This caches the preamble (included files at top of source file). 1901 # This is useful if the translation unit will be reparsed and you don't 1902 # want to incur the overhead of reparsing the preamble. 1903 PARSE_PRECOMPILED_PREAMBLE = 4 1904 1905 # Cache code completion information on parse. This adds time to parsing but 1906 # speeds up code completion. 1907 PARSE_CACHE_COMPLETION_RESULTS = 8 1908 1909 # Flags with values 16 and 32 are deprecated and intentionally omitted. 1910 1911 # Do not parse function bodies. This is useful if you only care about 1912 # searching for declarations/definitions. 1913 PARSE_SKIP_FUNCTION_BODIES = 64 1914 1915 # Used to indicate that brief documentation comments should be included 1916 # into the set of code completions returned from this translation unit. 1917 PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128 1918 1919 @classmethod 1920 def from_source(cls, filename, args=None, unsaved_files=None, options=0, 1921 index=None): 1922 """Create a TranslationUnit by parsing source. 1923 1924 This is capable of processing source code both from files on the 1925 filesystem as well as in-memory contents. 1926 1927 Command-line arguments that would be passed to clang are specified as 1928 a list via args. These can be used to specify include paths, warnings, 1929 etc. e.g. ["-Wall", "-I/path/to/include"]. 1930 1931 In-memory file content can be provided via unsaved_files. This is an 1932 iterable of 2-tuples. The first element is the str filename. The 1933 second element defines the content. Content can be provided as str 1934 source code or as file objects (anything with a read() method). If 1935 a file object is being used, content will be read until EOF and the 1936 read cursor will not be reset to its original position. 1937 1938 options is a bitwise or of TranslationUnit.PARSE_XXX flags which will 1939 control parsing behavior. 1940 1941 index is an Index instance to utilize. If not provided, a new Index 1942 will be created for this TranslationUnit. 1943 1944 To parse source from the filesystem, the filename of the file to parse 1945 is specified by the filename argument. Or, filename could be None and 1946 the args list would contain the filename(s) to parse. 1947 1948 To parse source from an in-memory buffer, set filename to the virtual 1949 filename you wish to associate with this source (e.g. "test.c"). The 1950 contents of that file are then provided in unsaved_files. 1951 1952 If an error occurs, a TranslationUnitLoadError is raised. 1953 1954 Please note that a TranslationUnit with parser errors may be returned. 1955 It is the caller's responsibility to check tu.diagnostics for errors. 1956 1957 Also note that Clang infers the source language from the extension of 1958 the input filename. If you pass in source code containing a C++ class 1959 declaration with the filename "test.c" parsing will fail. 1960 """ 1961 if args is None: 1962 args = [] 1963 1964 if unsaved_files is None: 1965 unsaved_files = [] 1966 1967 if index is None: 1968 index = Index.create() 1969 1970 args_array = None 1971 if len(args) > 0: 1972 args_array = (c_char_p * len(args))(* args) 1973 1974 unsaved_array = None 1975 if len(unsaved_files) > 0: 1976 unsaved_array = (_CXUnsavedFile * len(unsaved_files))() 1977 for i, (name, contents) in enumerate(unsaved_files): 1978 if hasattr(contents, "read"): 1979 contents = contents.read() 1980 1981 unsaved_array[i].name = name 1982 unsaved_array[i].contents = contents 1983 unsaved_array[i].length = len(contents) 1984 1985 ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array, 1986 len(args), unsaved_array, 1987 len(unsaved_files), options) 1988 1989 if ptr is None: 1990 raise TranslationUnitLoadError("Error parsing translation unit.") 1991 1992 return cls(ptr, index=index) 1993 1994 @classmethod 1995 def from_ast_file(cls, filename, index=None): 1996 """Create a TranslationUnit instance from a saved AST file. 1997 1998 A previously-saved AST file (provided with -emit-ast or 1999 TranslationUnit.save()) is loaded from the filename specified. 2000 2001 If the file cannot be loaded, a TranslationUnitLoadError will be 2002 raised. 2003 2004 index is optional and is the Index instance to use. If not provided, 2005 a default Index will be created. 2006 """ 2007 if index is None: 2008 index = Index.create() 2009 2010 ptr = conf.lib.clang_createTranslationUnit(index, filename) 2011 if ptr is None: 2012 raise TranslationUnitLoadError(filename) 2013 2014 return cls(ptr=ptr, index=index) 2015 2016 def __init__(self, ptr, index): 2017 """Create a TranslationUnit instance. 2018 2019 TranslationUnits should be created using one of the from_* @classmethod 2020 functions above. __init__ is only called internally. 2021 """ 2022 assert isinstance(index, Index) 2023 2024 ClangObject.__init__(self, ptr) 2025 2026 def __del__(self): 2027 conf.lib.clang_disposeTranslationUnit(self) 2028 2029 @property 2030 def cursor(self): 2031 """Retrieve the cursor that represents the given translation unit.""" 2032 return conf.lib.clang_getTranslationUnitCursor(self) 2033 2034 @property 2035 def spelling(self): 2036 """Get the original translation unit source file name.""" 2037 return conf.lib.clang_getTranslationUnitSpelling(self) 2038 2039 def get_includes(self): 2040 """ 2041 Return an iterable sequence of FileInclusion objects that describe the 2042 sequence of inclusions in a translation unit. The first object in 2043 this sequence is always the input file. Note that this method will not 2044 recursively iterate over header files included through precompiled 2045 headers. 2046 """ 2047 def visitor(fobj, lptr, depth, includes): 2048 if depth > 0: 2049 loc = lptr.contents 2050 includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) 2051 2052 # Automatically adapt CIndex/ctype pointers to python objects 2053 includes = [] 2054 conf.lib.clang_getInclusions(self, 2055 callbacks['translation_unit_includes'](visitor), includes) 2056 2057 return iter(includes) 2058 2059 def get_file(self, filename): 2060 """Obtain a File from this translation unit.""" 2061 2062 return File.from_name(self, filename) 2063 2064 def get_location(self, filename, position): 2065 """Obtain a SourceLocation for a file in this translation unit. 2066 2067 The position can be specified by passing: 2068 2069 - Integer file offset. Initial file offset is 0. 2070 - 2-tuple of (line number, column number). Initial file position is 2071 (0, 0) 2072 """ 2073 f = self.get_file(filename) 2074 2075 if isinstance(position, int): 2076 return SourceLocation.from_offset(self, f, position) 2077 2078 return SourceLocation.from_position(self, f, position[0], position[1]) 2079 2080 def get_extent(self, filename, locations): 2081 """Obtain a SourceRange from this translation unit. 2082 2083 The bounds of the SourceRange must ultimately be defined by a start and 2084 end SourceLocation. For the locations argument, you can pass: 2085 2086 - 2 SourceLocation instances in a 2-tuple or list. 2087 - 2 int file offsets via a 2-tuple or list. 2088 - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. 2089 2090 e.g. 2091 2092 get_extent('foo.c', (5, 10)) 2093 get_extent('foo.c', ((1, 1), (1, 15))) 2094 """ 2095 f = self.get_file(filename) 2096 2097 if len(locations) < 2: 2098 raise Exception('Must pass object with at least 2 elements') 2099 2100 start_location, end_location = locations 2101 2102 if hasattr(start_location, '__len__'): 2103 start_location = SourceLocation.from_position(self, f, 2104 start_location[0], start_location[1]) 2105 elif isinstance(start_location, int): 2106 start_location = SourceLocation.from_offset(self, f, 2107 start_location) 2108 2109 if hasattr(end_location, '__len__'): 2110 end_location = SourceLocation.from_position(self, f, 2111 end_location[0], end_location[1]) 2112 elif isinstance(end_location, int): 2113 end_location = SourceLocation.from_offset(self, f, end_location) 2114 2115 assert isinstance(start_location, SourceLocation) 2116 assert isinstance(end_location, SourceLocation) 2117 2118 return SourceRange.from_locations(start_location, end_location) 2119 2120 @property 2121 def diagnostics(self): 2122 """ 2123 Return an iterable (and indexable) object containing the diagnostics. 2124 """ 2125 class DiagIterator: 2126 def __init__(self, tu): 2127 self.tu = tu 2128 2129 def __len__(self): 2130 return int(conf.lib.clang_getNumDiagnostics(self.tu)) 2131 2132 def __getitem__(self, key): 2133 diag = conf.lib.clang_getDiagnostic(self.tu, key) 2134 if not diag: 2135 raise IndexError 2136 return Diagnostic(diag) 2137 2138 return DiagIterator(self) 2139 2140 def reparse(self, unsaved_files=None, options=0): 2141 """ 2142 Reparse an already parsed translation unit. 2143 2144 In-memory contents for files can be provided by passing a list of pairs 2145 as unsaved_files, the first items should be the filenames to be mapped 2146 and the second should be the contents to be substituted for the 2147 file. The contents may be passed as strings or file objects. 2148 """ 2149 if unsaved_files is None: 2150 unsaved_files = [] 2151 2152 unsaved_files_array = 0 2153 if len(unsaved_files): 2154 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() 2155 for i,(name,value) in enumerate(unsaved_files): 2156 if not isinstance(value, str): 2157 # FIXME: It would be great to support an efficient version 2158 # of this, one day. 2159 value = value.read() 2160 print value 2161 if not isinstance(value, str): 2162 raise TypeError,'Unexpected unsaved file contents.' 2163 unsaved_files_array[i].name = name 2164 unsaved_files_array[i].contents = value 2165 unsaved_files_array[i].length = len(value) 2166 ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files), 2167 unsaved_files_array, options) 2168 2169 def save(self, filename): 2170 """Saves the TranslationUnit to a file. 2171 2172 This is equivalent to passing -emit-ast to the clang frontend. The 2173 saved file can be loaded back into a TranslationUnit. Or, if it 2174 corresponds to a header, it can be used as a pre-compiled header file. 2175 2176 If an error occurs while saving, a TranslationUnitSaveError is raised. 2177 If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means 2178 the constructed TranslationUnit was not valid at time of save. In this 2179 case, the reason(s) why should be available via 2180 TranslationUnit.diagnostics(). 2181 2182 filename -- The path to save the translation unit to. 2183 """ 2184 options = conf.lib.clang_defaultSaveOptions(self) 2185 result = int(conf.lib.clang_saveTranslationUnit(self, filename, 2186 options)) 2187 if result != 0: 2188 raise TranslationUnitSaveError(result, 2189 'Error saving TranslationUnit.') 2190 2191 def codeComplete(self, path, line, column, unsaved_files=None, 2192 include_macros=False, include_code_patterns=False, 2193 include_brief_comments=False): 2194 """ 2195 Code complete in this translation unit. 2196 2197 In-memory contents for files can be provided by passing a list of pairs 2198 as unsaved_files, the first items should be the filenames to be mapped 2199 and the second should be the contents to be substituted for the 2200 file. The contents may be passed as strings or file objects. 2201 """ 2202 options = 0 2203 2204 if include_macros: 2205 options += 1 2206 2207 if include_code_patterns: 2208 options += 2 2209 2210 if include_brief_comments: 2211 options += 4 2212 2213 if unsaved_files is None: 2214 unsaved_files = [] 2215 2216 unsaved_files_array = 0 2217 if len(unsaved_files): 2218 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() 2219 for i,(name,value) in enumerate(unsaved_files): 2220 if not isinstance(value, str): 2221 # FIXME: It would be great to support an efficient version 2222 # of this, one day. 2223 value = value.read() 2224 print value 2225 if not isinstance(value, str): 2226 raise TypeError,'Unexpected unsaved file contents.' 2227 unsaved_files_array[i].name = name 2228 unsaved_files_array[i].contents = value 2229 unsaved_files_array[i].length = len(value) 2230 ptr = conf.lib.clang_codeCompleteAt(self, path, line, column, 2231 unsaved_files_array, len(unsaved_files), options) 2232 if ptr: 2233 return CodeCompletionResults(ptr) 2234 return None 2235 2236 def get_tokens(self, locations=None, extent=None): 2237 """Obtain tokens in this translation unit. 2238 2239 This is a generator for Token instances. The caller specifies a range 2240 of source code to obtain tokens for. The range can be specified as a 2241 2-tuple of SourceLocation or as a SourceRange. If both are defined, 2242 behavior is undefined. 2243 """ 2244 if locations is not None: 2245 extent = SourceRange(start=locations[0], end=locations[1]) 2246 2247 return TokenGroup.get_tokens(self, extent) 2248 2249class File(ClangObject): 2250 """ 2251 The File class represents a particular source file that is part of a 2252 translation unit. 2253 """ 2254 2255 @staticmethod 2256 def from_name(translation_unit, file_name): 2257 """Retrieve a file handle within the given translation unit.""" 2258 return File(conf.lib.clang_getFile(translation_unit, file_name)) 2259 2260 @property 2261 def name(self): 2262 """Return the complete file and path name of the file.""" 2263 return conf.lib.clang_getCString(conf.lib.clang_getFileName(self)) 2264 2265 @property 2266 def time(self): 2267 """Return the last modification time of the file.""" 2268 return conf.lib.clang_getFileTime(self) 2269 2270 def __str__(self): 2271 return self.name 2272 2273 def __repr__(self): 2274 return "<File: %s>" % (self.name) 2275 2276 @staticmethod 2277 def from_cursor_result(res, fn, args): 2278 assert isinstance(res, File) 2279 2280 # Copy a reference to the TranslationUnit to prevent premature GC. 2281 res._tu = args[0]._tu 2282 return res 2283 2284class FileInclusion(object): 2285 """ 2286 The FileInclusion class represents the inclusion of one source file by 2287 another via a '#include' directive or as the input file for the translation 2288 unit. This class provides information about the included file, the including 2289 file, the location of the '#include' directive and the depth of the included 2290 file in the stack. Note that the input file has depth 0. 2291 """ 2292 2293 def __init__(self, src, tgt, loc, depth): 2294 self.source = src 2295 self.include = tgt 2296 self.location = loc 2297 self.depth = depth 2298 2299 @property 2300 def is_input_file(self): 2301 """True if the included file is the input file.""" 2302 return self.depth == 0 2303 2304class CompilationDatabaseError(Exception): 2305 """Represents an error that occurred when working with a CompilationDatabase 2306 2307 Each error is associated to an enumerated value, accessible under 2308 e.cdb_error. Consumers can compare the value with one of the ERROR_ 2309 constants in this class. 2310 """ 2311 2312 # An unknown error occured 2313 ERROR_UNKNOWN = 0 2314 2315 # The database could not be loaded 2316 ERROR_CANNOTLOADDATABASE = 1 2317 2318 def __init__(self, enumeration, message): 2319 assert isinstance(enumeration, int) 2320 2321 if enumeration > 1: 2322 raise Exception("Encountered undefined CompilationDatabase error " 2323 "constant: %d. Please file a bug to have this " 2324 "value supported." % enumeration) 2325 2326 self.cdb_error = enumeration 2327 Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) 2328 2329class CompileCommand(object): 2330 """Represents the compile command used to build a file""" 2331 def __init__(self, cmd, ccmds): 2332 self.cmd = cmd 2333 # Keep a reference to the originating CompileCommands 2334 # to prevent garbage collection 2335 self.ccmds = ccmds 2336 2337 @property 2338 def directory(self): 2339 """Get the working directory for this CompileCommand""" 2340 return conf.lib.clang_CompileCommand_getDirectory(self.cmd) 2341 2342 @property 2343 def arguments(self): 2344 """ 2345 Get an iterable object providing each argument in the 2346 command line for the compiler invocation as a _CXString. 2347 2348 Invariant : the first argument is the compiler executable 2349 """ 2350 length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd) 2351 for i in xrange(length): 2352 yield conf.lib.clang_CompileCommand_getArg(self.cmd, i) 2353 2354class CompileCommands(object): 2355 """ 2356 CompileCommands is an iterable object containing all CompileCommand 2357 that can be used for building a specific file. 2358 """ 2359 def __init__(self, ccmds): 2360 self.ccmds = ccmds 2361 2362 def __del__(self): 2363 conf.lib.clang_CompileCommands_dispose(self.ccmds) 2364 2365 def __len__(self): 2366 return int(conf.lib.clang_CompileCommands_getSize(self.ccmds)) 2367 2368 def __getitem__(self, i): 2369 cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i) 2370 if not cc: 2371 raise IndexError 2372 return CompileCommand(cc, self) 2373 2374 @staticmethod 2375 def from_result(res, fn, args): 2376 if not res: 2377 return None 2378 return CompileCommands(res) 2379 2380class CompilationDatabase(ClangObject): 2381 """ 2382 The CompilationDatabase is a wrapper class around 2383 clang::tooling::CompilationDatabase 2384 2385 It enables querying how a specific source file can be built. 2386 """ 2387 2388 def __del__(self): 2389 conf.lib.clang_CompilationDatabase_dispose(self) 2390 2391 @staticmethod 2392 def from_result(res, fn, args): 2393 if not res: 2394 raise CompilationDatabaseError(0, 2395 "CompilationDatabase loading failed") 2396 return CompilationDatabase(res) 2397 2398 @staticmethod 2399 def fromDirectory(buildDir): 2400 """Builds a CompilationDatabase from the database found in buildDir""" 2401 errorCode = c_uint() 2402 try: 2403 cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir, 2404 byref(errorCode)) 2405 except CompilationDatabaseError as e: 2406 raise CompilationDatabaseError(int(errorCode.value), 2407 "CompilationDatabase loading failed") 2408 return cdb 2409 2410 def getCompileCommands(self, filename): 2411 """ 2412 Get an iterable object providing all the CompileCommands available to 2413 build filename. Returns None if filename is not found in the database. 2414 """ 2415 return conf.lib.clang_CompilationDatabase_getCompileCommands(self, 2416 filename) 2417 2418class Token(Structure): 2419 """Represents a single token from the preprocessor. 2420 2421 Tokens are effectively segments of source code. Source code is first parsed 2422 into tokens before being converted into the AST and Cursors. 2423 2424 Tokens are obtained from parsed TranslationUnit instances. You currently 2425 can't create tokens manually. 2426 """ 2427 _fields_ = [ 2428 ('int_data', c_uint * 4), 2429 ('ptr_data', c_void_p) 2430 ] 2431 2432 @property 2433 def spelling(self): 2434 """The spelling of this token. 2435 2436 This is the textual representation of the token in source. 2437 """ 2438 return conf.lib.clang_getTokenSpelling(self._tu, self) 2439 2440 @property 2441 def kind(self): 2442 """Obtain the TokenKind of the current token.""" 2443 return TokenKind.from_value(conf.lib.clang_getTokenKind(self)) 2444 2445 @property 2446 def location(self): 2447 """The SourceLocation this Token occurs at.""" 2448 return conf.lib.clang_getTokenLocation(self._tu, self) 2449 2450 @property 2451 def extent(self): 2452 """The SourceRange this Token occupies.""" 2453 return conf.lib.clang_getTokenExtent(self._tu, self) 2454 2455 @property 2456 def cursor(self): 2457 """The Cursor this Token corresponds to.""" 2458 cursor = Cursor() 2459 2460 conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor)) 2461 2462 return cursor 2463 2464# Now comes the plumbing to hook up the C library. 2465 2466# Register callback types in common container. 2467callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p, 2468 POINTER(SourceLocation), c_uint, py_object) 2469callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object) 2470 2471# Functions strictly alphabetical order. 2472functionList = [ 2473 ("clang_annotateTokens", 2474 [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]), 2475 2476 ("clang_CompilationDatabase_dispose", 2477 [c_object_p]), 2478 2479 ("clang_CompilationDatabase_fromDirectory", 2480 [c_char_p, POINTER(c_uint)], 2481 c_object_p, 2482 CompilationDatabase.from_result), 2483 2484 ("clang_CompilationDatabase_getCompileCommands", 2485 [c_object_p, c_char_p], 2486 c_object_p, 2487 CompileCommands.from_result), 2488 2489 ("clang_CompileCommands_dispose", 2490 [c_object_p]), 2491 2492 ("clang_CompileCommands_getCommand", 2493 [c_object_p, c_uint], 2494 c_object_p), 2495 2496 ("clang_CompileCommands_getSize", 2497 [c_object_p], 2498 c_uint), 2499 2500 ("clang_CompileCommand_getArg", 2501 [c_object_p, c_uint], 2502 _CXString, 2503 _CXString.from_result), 2504 2505 ("clang_CompileCommand_getDirectory", 2506 [c_object_p], 2507 _CXString, 2508 _CXString.from_result), 2509 2510 ("clang_CompileCommand_getNumArgs", 2511 [c_object_p], 2512 c_uint), 2513 2514 ("clang_codeCompleteAt", 2515 [TranslationUnit, c_char_p, c_int, c_int, c_void_p, c_int, c_int], 2516 POINTER(CCRStructure)), 2517 2518 ("clang_codeCompleteGetDiagnostic", 2519 [CodeCompletionResults, c_int], 2520 Diagnostic), 2521 2522 ("clang_codeCompleteGetNumDiagnostics", 2523 [CodeCompletionResults], 2524 c_int), 2525 2526 ("clang_createIndex", 2527 [c_int, c_int], 2528 c_object_p), 2529 2530 ("clang_createTranslationUnit", 2531 [Index, c_char_p], 2532 c_object_p), 2533 2534 ("clang_CXXMethod_isStatic", 2535 [Cursor], 2536 bool), 2537 2538 ("clang_CXXMethod_isVirtual", 2539 [Cursor], 2540 bool), 2541 2542 ("clang_defaultSaveOptions", 2543 [TranslationUnit], 2544 c_uint), 2545 2546 ("clang_disposeCodeCompleteResults", 2547 [CodeCompletionResults]), 2548 2549# ("clang_disposeCXTUResourceUsage", 2550# [CXTUResourceUsage]), 2551 2552 ("clang_disposeDiagnostic", 2553 [Diagnostic]), 2554 2555 ("clang_disposeIndex", 2556 [Index]), 2557 2558 ("clang_disposeString", 2559 [_CXString]), 2560 2561 ("clang_disposeTokens", 2562 [TranslationUnit, POINTER(Token), c_uint]), 2563 2564 ("clang_disposeTranslationUnit", 2565 [TranslationUnit]), 2566 2567 ("clang_equalCursors", 2568 [Cursor, Cursor], 2569 bool), 2570 2571 ("clang_equalLocations", 2572 [SourceLocation, SourceLocation], 2573 bool), 2574 2575 ("clang_equalRanges", 2576 [SourceRange, SourceRange], 2577 bool), 2578 2579 ("clang_equalTypes", 2580 [Type, Type], 2581 bool), 2582 2583 ("clang_getArgType", 2584 [Type, c_uint], 2585 Type, 2586 Type.from_result), 2587 2588 ("clang_getArrayElementType", 2589 [Type], 2590 Type, 2591 Type.from_result), 2592 2593 ("clang_getArraySize", 2594 [Type], 2595 c_longlong), 2596 2597 ("clang_getCanonicalCursor", 2598 [Cursor], 2599 Cursor, 2600 Cursor.from_cursor_result), 2601 2602 ("clang_getCanonicalType", 2603 [Type], 2604 Type, 2605 Type.from_result), 2606 2607 ("clang_getCompletionAvailability", 2608 [c_void_p], 2609 c_int), 2610 2611 ("clang_getCompletionBriefComment", 2612 [c_void_p], 2613 _CXString), 2614 2615 ("clang_getCompletionChunkCompletionString", 2616 [c_void_p, c_int], 2617 c_object_p), 2618 2619 ("clang_getCompletionChunkKind", 2620 [c_void_p, c_int], 2621 c_int), 2622 2623 ("clang_getCompletionChunkText", 2624 [c_void_p, c_int], 2625 _CXString), 2626 2627 ("clang_getCompletionPriority", 2628 [c_void_p], 2629 c_int), 2630 2631 ("clang_getCString", 2632 [_CXString], 2633 c_char_p), 2634 2635 ("clang_getCursor", 2636 [TranslationUnit, SourceLocation], 2637 Cursor), 2638 2639 ("clang_getCursorDefinition", 2640 [Cursor], 2641 Cursor, 2642 Cursor.from_result), 2643 2644 ("clang_getCursorDisplayName", 2645 [Cursor], 2646 _CXString, 2647 _CXString.from_result), 2648 2649 ("clang_getCursorExtent", 2650 [Cursor], 2651 SourceRange), 2652 2653 ("clang_getCursorLexicalParent", 2654 [Cursor], 2655 Cursor, 2656 Cursor.from_cursor_result), 2657 2658 ("clang_getCursorLocation", 2659 [Cursor], 2660 SourceLocation), 2661 2662 ("clang_getCursorReferenced", 2663 [Cursor], 2664 Cursor, 2665 Cursor.from_result), 2666 2667 ("clang_getCursorReferenceNameRange", 2668 [Cursor, c_uint, c_uint], 2669 SourceRange), 2670 2671 ("clang_getCursorSemanticParent", 2672 [Cursor], 2673 Cursor, 2674 Cursor.from_cursor_result), 2675 2676 ("clang_getCursorSpelling", 2677 [Cursor], 2678 _CXString, 2679 _CXString.from_result), 2680 2681 ("clang_getCursorType", 2682 [Cursor], 2683 Type, 2684 Type.from_result), 2685 2686 ("clang_getCursorUSR", 2687 [Cursor], 2688 _CXString, 2689 _CXString.from_result), 2690 2691# ("clang_getCXTUResourceUsage", 2692# [TranslationUnit], 2693# CXTUResourceUsage), 2694 2695 ("clang_getCXXAccessSpecifier", 2696 [Cursor], 2697 c_uint), 2698 2699 ("clang_getDeclObjCTypeEncoding", 2700 [Cursor], 2701 _CXString, 2702 _CXString.from_result), 2703 2704 ("clang_getDiagnostic", 2705 [c_object_p, c_uint], 2706 c_object_p), 2707 2708 ("clang_getDiagnosticCategory", 2709 [Diagnostic], 2710 c_uint), 2711 2712 ("clang_getDiagnosticCategoryName", 2713 [c_uint], 2714 _CXString, 2715 _CXString.from_result), 2716 2717 ("clang_getDiagnosticFixIt", 2718 [Diagnostic, c_uint, POINTER(SourceRange)], 2719 _CXString, 2720 _CXString.from_result), 2721 2722 ("clang_getDiagnosticLocation", 2723 [Diagnostic], 2724 SourceLocation), 2725 2726 ("clang_getDiagnosticNumFixIts", 2727 [Diagnostic], 2728 c_uint), 2729 2730 ("clang_getDiagnosticNumRanges", 2731 [Diagnostic], 2732 c_uint), 2733 2734 ("clang_getDiagnosticOption", 2735 [Diagnostic, POINTER(_CXString)], 2736 _CXString, 2737 _CXString.from_result), 2738 2739 ("clang_getDiagnosticRange", 2740 [Diagnostic, c_uint], 2741 SourceRange), 2742 2743 ("clang_getDiagnosticSeverity", 2744 [Diagnostic], 2745 c_int), 2746 2747 ("clang_getDiagnosticSpelling", 2748 [Diagnostic], 2749 _CXString, 2750 _CXString.from_result), 2751 2752 ("clang_getElementType", 2753 [Type], 2754 Type, 2755 Type.from_result), 2756 2757 ("clang_getEnumConstantDeclUnsignedValue", 2758 [Cursor], 2759 c_ulonglong), 2760 2761 ("clang_getEnumConstantDeclValue", 2762 [Cursor], 2763 c_longlong), 2764 2765 ("clang_getEnumDeclIntegerType", 2766 [Cursor], 2767 Type, 2768 Type.from_result), 2769 2770 ("clang_getFile", 2771 [TranslationUnit, c_char_p], 2772 c_object_p), 2773 2774 ("clang_getFileName", 2775 [File], 2776 _CXString), # TODO go through _CXString.from_result? 2777 2778 ("clang_getFileTime", 2779 [File], 2780 c_uint), 2781 2782 ("clang_getIBOutletCollectionType", 2783 [Cursor], 2784 Type, 2785 Type.from_result), 2786 2787 ("clang_getIncludedFile", 2788 [Cursor], 2789 File, 2790 File.from_cursor_result), 2791 2792 ("clang_getInclusions", 2793 [TranslationUnit, callbacks['translation_unit_includes'], py_object]), 2794 2795 ("clang_getInstantiationLocation", 2796 [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint), 2797 POINTER(c_uint)]), 2798 2799 ("clang_getLocation", 2800 [TranslationUnit, File, c_uint, c_uint], 2801 SourceLocation), 2802 2803 ("clang_getLocationForOffset", 2804 [TranslationUnit, File, c_uint], 2805 SourceLocation), 2806 2807 ("clang_getNullCursor", 2808 None, 2809 Cursor), 2810 2811 ("clang_getNumArgTypes", 2812 [Type], 2813 c_uint), 2814 2815 ("clang_getNumCompletionChunks", 2816 [c_void_p], 2817 c_int), 2818 2819 ("clang_getNumDiagnostics", 2820 [c_object_p], 2821 c_uint), 2822 2823 ("clang_getNumElements", 2824 [Type], 2825 c_longlong), 2826 2827 ("clang_getNumOverloadedDecls", 2828 [Cursor], 2829 c_uint), 2830 2831 ("clang_getOverloadedDecl", 2832 [Cursor, c_uint], 2833 Cursor, 2834 Cursor.from_cursor_result), 2835 2836 ("clang_getPointeeType", 2837 [Type], 2838 Type, 2839 Type.from_result), 2840 2841 ("clang_getRange", 2842 [SourceLocation, SourceLocation], 2843 SourceRange), 2844 2845 ("clang_getRangeEnd", 2846 [SourceRange], 2847 SourceLocation), 2848 2849 ("clang_getRangeStart", 2850 [SourceRange], 2851 SourceLocation), 2852 2853 ("clang_getResultType", 2854 [Type], 2855 Type, 2856 Type.from_result), 2857 2858 ("clang_getSpecializedCursorTemplate", 2859 [Cursor], 2860 Cursor, 2861 Cursor.from_cursor_result), 2862 2863 ("clang_getTemplateCursorKind", 2864 [Cursor], 2865 c_uint), 2866 2867 ("clang_getTokenExtent", 2868 [TranslationUnit, Token], 2869 SourceRange), 2870 2871 ("clang_getTokenKind", 2872 [Token], 2873 c_uint), 2874 2875 ("clang_getTokenLocation", 2876 [TranslationUnit, Token], 2877 SourceLocation), 2878 2879 ("clang_getTokenSpelling", 2880 [TranslationUnit, Token], 2881 _CXString, 2882 _CXString.from_result), 2883 2884 ("clang_getTranslationUnitCursor", 2885 [TranslationUnit], 2886 Cursor, 2887 Cursor.from_result), 2888 2889 ("clang_getTranslationUnitSpelling", 2890 [TranslationUnit], 2891 _CXString, 2892 _CXString.from_result), 2893 2894 ("clang_getTUResourceUsageName", 2895 [c_uint], 2896 c_char_p), 2897 2898 ("clang_getTypeDeclaration", 2899 [Type], 2900 Cursor, 2901 Cursor.from_result), 2902 2903 ("clang_getTypedefDeclUnderlyingType", 2904 [Cursor], 2905 Type, 2906 Type.from_result), 2907 2908 ("clang_getTypeKindSpelling", 2909 [c_uint], 2910 _CXString, 2911 _CXString.from_result), 2912 2913 ("clang_hashCursor", 2914 [Cursor], 2915 c_uint), 2916 2917 ("clang_isAttribute", 2918 [CursorKind], 2919 bool), 2920 2921 ("clang_isConstQualifiedType", 2922 [Type], 2923 bool), 2924 2925 ("clang_isCursorDefinition", 2926 [Cursor], 2927 bool), 2928 2929 ("clang_isDeclaration", 2930 [CursorKind], 2931 bool), 2932 2933 ("clang_isExpression", 2934 [CursorKind], 2935 bool), 2936 2937 ("clang_isFileMultipleIncludeGuarded", 2938 [TranslationUnit, File], 2939 bool), 2940 2941 ("clang_isFunctionTypeVariadic", 2942 [Type], 2943 bool), 2944 2945 ("clang_isInvalid", 2946 [CursorKind], 2947 bool), 2948 2949 ("clang_isPODType", 2950 [Type], 2951 bool), 2952 2953 ("clang_isPreprocessing", 2954 [CursorKind], 2955 bool), 2956 2957 ("clang_isReference", 2958 [CursorKind], 2959 bool), 2960 2961 ("clang_isRestrictQualifiedType", 2962 [Type], 2963 bool), 2964 2965 ("clang_isStatement", 2966 [CursorKind], 2967 bool), 2968 2969 ("clang_isTranslationUnit", 2970 [CursorKind], 2971 bool), 2972 2973 ("clang_isUnexposed", 2974 [CursorKind], 2975 bool), 2976 2977 ("clang_isVirtualBase", 2978 [Cursor], 2979 bool), 2980 2981 ("clang_isVolatileQualifiedType", 2982 [Type], 2983 bool), 2984 2985 ("clang_parseTranslationUnit", 2986 [Index, c_char_p, c_void_p, c_int, c_void_p, c_int, c_int], 2987 c_object_p), 2988 2989 ("clang_reparseTranslationUnit", 2990 [TranslationUnit, c_int, c_void_p, c_int], 2991 c_int), 2992 2993 ("clang_saveTranslationUnit", 2994 [TranslationUnit, c_char_p, c_uint], 2995 c_int), 2996 2997 ("clang_tokenize", 2998 [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]), 2999 3000 ("clang_visitChildren", 3001 [Cursor, callbacks['cursor_visit'], py_object], 3002 c_uint), 3003 3004 ("clang_Cursor_getNumArguments", 3005 [Cursor], 3006 c_int), 3007 3008 ("clang_Cursor_getArgument", 3009 [Cursor, c_uint], 3010 Cursor, 3011 Cursor.from_result), 3012] 3013 3014class LibclangError(Exception): 3015 def __init__(self, message): 3016 self.m = message 3017 3018 def __str__(self): 3019 return self.m 3020 3021def register_function(lib, item, ignore_errors): 3022 # A function may not exist, if these bindings are used with an older or 3023 # incompatible version of libclang.so. 3024 try: 3025 func = getattr(lib, item[0]) 3026 except AttributeError as e: 3027 msg = str(e) + ". Please ensure that your python bindings are "\ 3028 "compatible with your libclang.so version." 3029 if ignore_errors: 3030 return 3031 raise LibclangError(msg) 3032 3033 if len(item) >= 2: 3034 func.argtypes = item[1] 3035 3036 if len(item) >= 3: 3037 func.restype = item[2] 3038 3039 if len(item) == 4: 3040 func.errcheck = item[3] 3041 3042def register_functions(lib, ignore_errors): 3043 """Register function prototypes with a libclang library instance. 3044 3045 This must be called as part of library instantiation so Python knows how 3046 to call out to the shared library. 3047 """ 3048 3049 def register(item): 3050 return register_function(lib, item, ignore_errors) 3051 3052 map(register, functionList) 3053 3054class Config: 3055 library_path = None 3056 library_file = None 3057 compatibility_check = True 3058 loaded = False 3059 3060 @staticmethod 3061 def set_library_path(path): 3062 """Set the path in which to search for libclang""" 3063 if Config.loaded: 3064 raise Exception("library path must be set before before using " \ 3065 "any other functionalities in libclang.") 3066 3067 Config.library_path = path 3068 3069 @staticmethod 3070 def set_library_file(filename): 3071 """Set the exact location of libclang""" 3072 if Config.loaded: 3073 raise Exception("library file must be set before before using " \ 3074 "any other functionalities in libclang.") 3075 3076 Config.library_file = filename 3077 3078 @staticmethod 3079 def set_compatibility_check(check_status): 3080 """ Perform compatibility check when loading libclang 3081 3082 The python bindings are only tested and evaluated with the version of 3083 libclang they are provided with. To ensure correct behavior a (limited) 3084 compatibility check is performed when loading the bindings. This check 3085 will throw an exception, as soon as it fails. 3086 3087 In case these bindings are used with an older version of libclang, parts 3088 that have been stable between releases may still work. Users of the 3089 python bindings can disable the compatibility check. This will cause 3090 the python bindings to load, even though they are written for a newer 3091 version of libclang. Failures now arise if unsupported or incompatible 3092 features are accessed. The user is required to test himself if the 3093 features he is using are available and compatible between different 3094 libclang versions. 3095 """ 3096 if Config.loaded: 3097 raise Exception("compatibility_check must be set before before " \ 3098 "using any other functionalities in libclang.") 3099 3100 Config.compatibility_check = check_status 3101 3102 @CachedProperty 3103 def lib(self): 3104 lib = self.get_cindex_library() 3105 register_functions(lib, not Config.compatibility_check) 3106 Config.loaded = True 3107 return lib 3108 3109 def get_filename(self): 3110 if Config.library_file: 3111 return Config.library_file 3112 3113 import platform 3114 name = platform.system() 3115 3116 if name == 'Darwin': 3117 file = 'libclang.dylib' 3118 elif name == 'Windows': 3119 file = 'libclang.dll' 3120 else: 3121 file = 'libclang.so' 3122 3123 if Config.library_path: 3124 file = Config.library_path + '/' + file 3125 3126 return file 3127 3128 def get_cindex_library(self): 3129 try: 3130 library = cdll.LoadLibrary(self.get_filename()) 3131 except OSError as e: 3132 msg = str(e) + ". To provide a path to libclang use " \ 3133 "Config.set_library_path() or " \ 3134 "Config.set_library_file()." 3135 raise LibclangError(msg) 3136 3137 return library 3138 3139 def function_exists(self, name): 3140 try: 3141 getattr(self.lib, name) 3142 except AttributeError: 3143 return False 3144 3145 return True 3146 3147def register_enumerations(): 3148 for name, value in clang.enumerations.TokenKinds: 3149 TokenKind.register(value, name) 3150 3151conf = Config() 3152register_enumerations() 3153 3154__all__ = [ 3155 'Config', 3156 'CodeCompletionResults', 3157 'CompilationDatabase', 3158 'CompileCommands', 3159 'CompileCommand', 3160 'CursorKind', 3161 'Cursor', 3162 'Diagnostic', 3163 'File', 3164 'FixIt', 3165 'Index', 3166 'SourceLocation', 3167 'SourceRange', 3168 'TokenKind', 3169 'Token', 3170 'TranslationUnitLoadError', 3171 'TranslationUnit', 3172 'TypeKind', 3173 'Type', 3174] 3175