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