cindex.py revision 4439478c38222bb56d42a9afe4c6c51cb8b593d2
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 68def get_cindex_library(): 69 # FIXME: It's probably not the case that the library is actually found in 70 # this location. We need a better system of identifying and loading the 71 # CIndex library. It could be on path or elsewhere, or versioned, etc. 72 import platform 73 name = platform.system() 74 if name == 'Darwin': 75 return cdll.LoadLibrary('libclang.dylib') 76 elif name == 'Windows': 77 return cdll.LoadLibrary('libclang.dll') 78 else: 79 return cdll.LoadLibrary('libclang.so') 80 81# ctypes doesn't implicitly convert c_void_p to the appropriate wrapper 82# object. This is a problem, because it means that from_parameter will see an 83# integer and pass the wrong value on platforms where int != void*. Work around 84# this by marshalling object arguments as void**. 85c_object_p = POINTER(c_void_p) 86 87lib = get_cindex_library() 88 89### Exception Classes ### 90 91class TranslationUnitLoadError(Exception): 92 """Represents an error that occurred when loading a TranslationUnit. 93 94 This is raised in the case where a TranslationUnit could not be 95 instantiated due to failure in the libclang library. 96 97 FIXME: Make libclang expose additional error information in this scenario. 98 """ 99 pass 100 101class TranslationUnitSaveError(Exception): 102 """Represents an error that occurred when saving a TranslationUnit. 103 104 Each error has associated with it an enumerated value, accessible under 105 e.save_error. Consumers can compare the value with one of the ERROR_ 106 constants in this class. 107 """ 108 109 # Indicates that an unknown error occurred. This typically indicates that 110 # I/O failed during save. 111 ERROR_UNKNOWN = 1 112 113 # Indicates that errors during translation prevented saving. The errors 114 # should be available via the TranslationUnit's diagnostics. 115 ERROR_TRANSLATION_ERRORS = 2 116 117 # Indicates that the translation unit was somehow invalid. 118 ERROR_INVALID_TU = 3 119 120 def __init__(self, enumeration, message): 121 assert isinstance(enumeration, int) 122 123 if enumeration < 1 or enumeration > 3: 124 raise Exception("Encountered undefined TranslationUnit save error " 125 "constant: %d. Please file a bug to have this " 126 "value supported." % enumeration) 127 128 self.save_error = enumeration 129 Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) 130 131### Structures and Utility Classes ### 132 133class _CXString(Structure): 134 """Helper for transforming CXString results.""" 135 136 _fields_ = [("spelling", c_char_p), ("free", c_int)] 137 138 def __del__(self): 139 _CXString_dispose(self) 140 141 @staticmethod 142 def from_result(res, fn, args): 143 assert isinstance(res, _CXString) 144 return _CXString_getCString(res) 145 146class SourceLocation(Structure): 147 """ 148 A SourceLocation represents a particular location within a source file. 149 """ 150 _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)] 151 _data = None 152 153 def _get_instantiation(self): 154 if self._data is None: 155 f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint() 156 SourceLocation_loc(self, byref(f), byref(l), byref(c), byref(o)) 157 if f: 158 f = File(f) 159 else: 160 f = None 161 self._data = (f, int(l.value), int(c.value), int(o.value)) 162 return self._data 163 164 @staticmethod 165 def from_position(tu, file, line, column): 166 """ 167 Retrieve the source location associated with a given file/line/column in 168 a particular translation unit. 169 """ 170 return SourceLocation_getLocation(tu, file, line, column) 171 172 @staticmethod 173 def from_offset(tu, file, offset): 174 """Retrieve a SourceLocation from a given character offset. 175 176 tu -- TranslationUnit file belongs to 177 file -- File instance to obtain offset from 178 offset -- Integer character offset within file 179 """ 180 return SourceLocation_getLocationForOffset(tu, file, offset) 181 182 @property 183 def file(self): 184 """Get the file represented by this source location.""" 185 return self._get_instantiation()[0] 186 187 @property 188 def line(self): 189 """Get the line represented by this source location.""" 190 return self._get_instantiation()[1] 191 192 @property 193 def column(self): 194 """Get the column represented by this source location.""" 195 return self._get_instantiation()[2] 196 197 @property 198 def offset(self): 199 """Get the file offset represented by this source location.""" 200 return self._get_instantiation()[3] 201 202 def __eq__(self, other): 203 return SourceLocation_equalLocations(self, other) 204 205 def __ne__(self, other): 206 return not self.__eq__(other) 207 208 def __repr__(self): 209 if self.file: 210 filename = self.file.name 211 else: 212 filename = None 213 return "<SourceLocation file %r, line %r, column %r>" % ( 214 filename, self.line, self.column) 215 216class SourceRange(Structure): 217 """ 218 A SourceRange describes a range of source locations within the source 219 code. 220 """ 221 _fields_ = [ 222 ("ptr_data", c_void_p * 2), 223 ("begin_int_data", c_uint), 224 ("end_int_data", c_uint)] 225 226 # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes 227 # object. 228 @staticmethod 229 def from_locations(start, end): 230 return SourceRange_getRange(start, end) 231 232 @property 233 def start(self): 234 """ 235 Return a SourceLocation representing the first character within a 236 source range. 237 """ 238 return SourceRange_start(self) 239 240 @property 241 def end(self): 242 """ 243 Return a SourceLocation representing the last character within a 244 source range. 245 """ 246 return SourceRange_end(self) 247 248 def __eq__(self, other): 249 return SourceRange_equalRanges(self, other) 250 251 def __ne__(self, other): 252 return not self.__eq__(other) 253 254 def __repr__(self): 255 return "<SourceRange start %r, end %r>" % (self.start, self.end) 256 257class Diagnostic(object): 258 """ 259 A Diagnostic is a single instance of a Clang diagnostic. It includes the 260 diagnostic severity, the message, the location the diagnostic occurred, as 261 well as additional source ranges and associated fix-it hints. 262 """ 263 264 Ignored = 0 265 Note = 1 266 Warning = 2 267 Error = 3 268 Fatal = 4 269 270 def __init__(self, ptr): 271 self.ptr = ptr 272 273 def __del__(self): 274 _clang_disposeDiagnostic(self) 275 276 @property 277 def severity(self): 278 return _clang_getDiagnosticSeverity(self) 279 280 @property 281 def location(self): 282 return _clang_getDiagnosticLocation(self) 283 284 @property 285 def spelling(self): 286 return _clang_getDiagnosticSpelling(self) 287 288 @property 289 def ranges(self): 290 class RangeIterator: 291 def __init__(self, diag): 292 self.diag = diag 293 294 def __len__(self): 295 return int(_clang_getDiagnosticNumRanges(self.diag)) 296 297 def __getitem__(self, key): 298 if (key >= len(self)): 299 raise IndexError 300 return _clang_getDiagnosticRange(self.diag, key) 301 302 return RangeIterator(self) 303 304 @property 305 def fixits(self): 306 class FixItIterator: 307 def __init__(self, diag): 308 self.diag = diag 309 310 def __len__(self): 311 return int(_clang_getDiagnosticNumFixIts(self.diag)) 312 313 def __getitem__(self, key): 314 range = SourceRange() 315 value = _clang_getDiagnosticFixIt(self.diag, key, byref(range)) 316 if len(value) == 0: 317 raise IndexError 318 319 return FixIt(range, value) 320 321 return FixItIterator(self) 322 323 @property 324 def category_number(self): 325 """The category number for this diagnostic.""" 326 return _clang_getDiagnosticCategory(self) 327 328 @property 329 def category_name(self): 330 """The string name of the category for this diagnostic.""" 331 return _clang_getDiagnosticCategoryName(self.category_number) 332 333 @property 334 def option(self): 335 """The command-line option that enables this diagnostic.""" 336 return _clang_getDiagnosticOption(self, None) 337 338 @property 339 def disable_option(self): 340 """The command-line option that disables this diagnostic.""" 341 disable = _CXString() 342 _clang_getDiagnosticOption(self, byref(disable)) 343 344 return _CXString_getCString(disable) 345 346 def __repr__(self): 347 return "<Diagnostic severity %r, location %r, spelling %r>" % ( 348 self.severity, self.location, self.spelling) 349 350 def from_param(self): 351 return self.ptr 352 353class FixIt(object): 354 """ 355 A FixIt represents a transformation to be applied to the source to 356 "fix-it". The fix-it shouldbe applied by replacing the given source range 357 with the given value. 358 """ 359 360 def __init__(self, range, value): 361 self.range = range 362 self.value = value 363 364 def __repr__(self): 365 return "<FixIt range %r, value %r>" % (self.range, self.value) 366 367### Cursor Kinds ### 368 369class CursorKind(object): 370 """ 371 A CursorKind describes the kind of entity that a cursor points to. 372 """ 373 374 # The unique kind objects, indexed by id. 375 _kinds = [] 376 _name_map = None 377 378 def __init__(self, value): 379 if value >= len(CursorKind._kinds): 380 CursorKind._kinds += [None] * (value - len(CursorKind._kinds) + 1) 381 if CursorKind._kinds[value] is not None: 382 raise ValueError,'CursorKind already loaded' 383 self.value = value 384 CursorKind._kinds[value] = self 385 CursorKind._name_map = None 386 387 def from_param(self): 388 return self.value 389 390 @property 391 def name(self): 392 """Get the enumeration name of this cursor kind.""" 393 if self._name_map is None: 394 self._name_map = {} 395 for key,value in CursorKind.__dict__.items(): 396 if isinstance(value,CursorKind): 397 self._name_map[value] = key 398 return self._name_map[self] 399 400 @staticmethod 401 def from_id(id): 402 if id >= len(CursorKind._kinds) or CursorKind._kinds[id] is None: 403 raise ValueError,'Unknown cursor kind' 404 return CursorKind._kinds[id] 405 406 @staticmethod 407 def get_all_kinds(): 408 """Return all CursorKind enumeration instances.""" 409 return filter(None, CursorKind._kinds) 410 411 def is_declaration(self): 412 """Test if this is a declaration kind.""" 413 return CursorKind_is_decl(self) 414 415 def is_reference(self): 416 """Test if this is a reference kind.""" 417 return CursorKind_is_ref(self) 418 419 def is_expression(self): 420 """Test if this is an expression kind.""" 421 return CursorKind_is_expr(self) 422 423 def is_statement(self): 424 """Test if this is a statement kind.""" 425 return CursorKind_is_stmt(self) 426 427 def is_attribute(self): 428 """Test if this is an attribute kind.""" 429 return CursorKind_is_attribute(self) 430 431 def is_invalid(self): 432 """Test if this is an invalid kind.""" 433 return CursorKind_is_inv(self) 434 435 def is_translation_unit(self): 436 """Test if this is a translation unit kind.""" 437 return CursorKind_is_translation_unit(self) 438 439 def is_preprocessing(self): 440 """Test if this is a preprocessing kind.""" 441 return CursorKind_is_preprocessing(self) 442 443 def is_unexposed(self): 444 """Test if this is an unexposed kind.""" 445 return CursorKind_is_unexposed(self) 446 447 def __repr__(self): 448 return 'CursorKind.%s' % (self.name,) 449 450# FIXME: Is there a nicer way to expose this enumeration? We could potentially 451# represent the nested structure, or even build a class hierarchy. The main 452# things we want for sure are (a) simple external access to kinds, (b) a place 453# to hang a description and name, (c) easy to keep in sync with Index.h. 454 455### 456# Declaration Kinds 457 458# A declaration whose specific kind is not exposed via this interface. 459# 460# Unexposed declarations have the same operations as any other kind of 461# declaration; one can extract their location information, spelling, find their 462# definitions, etc. However, the specific kind of the declaration is not 463# reported. 464CursorKind.UNEXPOSED_DECL = CursorKind(1) 465 466# A C or C++ struct. 467CursorKind.STRUCT_DECL = CursorKind(2) 468 469# A C or C++ union. 470CursorKind.UNION_DECL = CursorKind(3) 471 472# A C++ class. 473CursorKind.CLASS_DECL = CursorKind(4) 474 475# An enumeration. 476CursorKind.ENUM_DECL = CursorKind(5) 477 478# A field (in C) or non-static data member (in C++) in a struct, union, or C++ 479# class. 480CursorKind.FIELD_DECL = CursorKind(6) 481 482# An enumerator constant. 483CursorKind.ENUM_CONSTANT_DECL = CursorKind(7) 484 485# A function. 486CursorKind.FUNCTION_DECL = CursorKind(8) 487 488# A variable. 489CursorKind.VAR_DECL = CursorKind(9) 490 491# A function or method parameter. 492CursorKind.PARM_DECL = CursorKind(10) 493 494# An Objective-C @interface. 495CursorKind.OBJC_INTERFACE_DECL = CursorKind(11) 496 497# An Objective-C @interface for a category. 498CursorKind.OBJC_CATEGORY_DECL = CursorKind(12) 499 500# An Objective-C @protocol declaration. 501CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13) 502 503# An Objective-C @property declaration. 504CursorKind.OBJC_PROPERTY_DECL = CursorKind(14) 505 506# An Objective-C instance variable. 507CursorKind.OBJC_IVAR_DECL = CursorKind(15) 508 509# An Objective-C instance method. 510CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16) 511 512# An Objective-C class method. 513CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17) 514 515# An Objective-C @implementation. 516CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18) 517 518# An Objective-C @implementation for a category. 519CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19) 520 521# A typedef. 522CursorKind.TYPEDEF_DECL = CursorKind(20) 523 524# A C++ class method. 525CursorKind.CXX_METHOD = CursorKind(21) 526 527# A C++ namespace. 528CursorKind.NAMESPACE = CursorKind(22) 529 530# A linkage specification, e.g. 'extern "C"'. 531CursorKind.LINKAGE_SPEC = CursorKind(23) 532 533# A C++ constructor. 534CursorKind.CONSTRUCTOR = CursorKind(24) 535 536# A C++ destructor. 537CursorKind.DESTRUCTOR = CursorKind(25) 538 539# A C++ conversion function. 540CursorKind.CONVERSION_FUNCTION = CursorKind(26) 541 542# A C++ template type parameter 543CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27) 544 545# A C++ non-type template paramater. 546CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28) 547 548# A C++ template template parameter. 549CursorKind.TEMPLATE_TEMPLATE_PARAMTER = CursorKind(29) 550 551# A C++ function template. 552CursorKind.FUNCTION_TEMPLATE = CursorKind(30) 553 554# A C++ class template. 555CursorKind.CLASS_TEMPLATE = CursorKind(31) 556 557# A C++ class template partial specialization. 558CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32) 559 560# A C++ namespace alias declaration. 561CursorKind.NAMESPACE_ALIAS = CursorKind(33) 562 563# A C++ using directive 564CursorKind.USING_DIRECTIVE = CursorKind(34) 565 566# A C++ using declaration 567CursorKind.USING_DECLARATION = CursorKind(35) 568 569# A Type alias decl. 570CursorKind.TYPE_ALIAS_DECL = CursorKind(36) 571 572# A Objective-C synthesize decl 573CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37) 574 575# A Objective-C dynamic decl 576CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38) 577 578# A C++ access specifier decl. 579CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39) 580 581 582### 583# Reference Kinds 584 585CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40) 586CursorKind.OBJC_PROTOCOL_REF = CursorKind(41) 587CursorKind.OBJC_CLASS_REF = CursorKind(42) 588 589# A reference to a type declaration. 590# 591# A type reference occurs anywhere where a type is named but not 592# declared. For example, given: 593# typedef unsigned size_type; 594# size_type size; 595# 596# The typedef is a declaration of size_type (CXCursor_TypedefDecl), 597# while the type of the variable "size" is referenced. The cursor 598# referenced by the type of size is the typedef for size_type. 599CursorKind.TYPE_REF = CursorKind(43) 600CursorKind.CXX_BASE_SPECIFIER = CursorKind(44) 601 602# A reference to a class template, function template, template 603# template parameter, or class template partial specialization. 604CursorKind.TEMPLATE_REF = CursorKind(45) 605 606# A reference to a namespace or namepsace alias. 607CursorKind.NAMESPACE_REF = CursorKind(46) 608 609# A reference to a member of a struct, union, or class that occurs in 610# some non-expression context, e.g., a designated initializer. 611CursorKind.MEMBER_REF = CursorKind(47) 612 613# A reference to a labeled statement. 614CursorKind.LABEL_REF = CursorKind(48) 615 616# A reference toa a set of overloaded functions or function templates 617# that has not yet been resolved to a specific function or function template. 618CursorKind.OVERLOADED_DECL_REF = CursorKind(49) 619 620### 621# Invalid/Error Kinds 622 623CursorKind.INVALID_FILE = CursorKind(70) 624CursorKind.NO_DECL_FOUND = CursorKind(71) 625CursorKind.NOT_IMPLEMENTED = CursorKind(72) 626CursorKind.INVALID_CODE = CursorKind(73) 627 628### 629# Expression Kinds 630 631# An expression whose specific kind is not exposed via this interface. 632# 633# Unexposed expressions have the same operations as any other kind of 634# expression; one can extract their location information, spelling, children, 635# etc. However, the specific kind of the expression is not reported. 636CursorKind.UNEXPOSED_EXPR = CursorKind(100) 637 638# An expression that refers to some value declaration, such as a function, 639# varible, or enumerator. 640CursorKind.DECL_REF_EXPR = CursorKind(101) 641 642# An expression that refers to a member of a struct, union, class, Objective-C 643# class, etc. 644CursorKind.MEMBER_REF_EXPR = CursorKind(102) 645 646# An expression that calls a function. 647CursorKind.CALL_EXPR = CursorKind(103) 648 649# An expression that sends a message to an Objective-C object or class. 650CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104) 651 652# An expression that represents a block literal. 653CursorKind.BLOCK_EXPR = CursorKind(105) 654 655# An integer literal. 656CursorKind.INTEGER_LITERAL = CursorKind(106) 657 658# A floating point number literal. 659CursorKind.FLOATING_LITERAL = CursorKind(107) 660 661# An imaginary number literal. 662CursorKind.IMAGINARY_LITERAL = CursorKind(108) 663 664# A string literal. 665CursorKind.STRING_LITERAL = CursorKind(109) 666 667# A character literal. 668CursorKind.CHARACTER_LITERAL = CursorKind(110) 669 670# A parenthesized expression, e.g. "(1)". 671# 672# This AST node is only formed if full location information is requested. 673CursorKind.PAREN_EXPR = CursorKind(111) 674 675# This represents the unary-expression's (except sizeof and 676# alignof). 677CursorKind.UNARY_OPERATOR = CursorKind(112) 678 679# [C99 6.5.2.1] Array Subscripting. 680CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113) 681 682# A builtin binary operation expression such as "x + y" or 683# "x <= y". 684CursorKind.BINARY_OPERATOR = CursorKind(114) 685 686# Compound assignment such as "+=". 687CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115) 688 689# The ?: ternary operator. 690CursorKind.CONDITIONAL_OPERATOR = CursorKind(116) 691 692# An explicit cast in C (C99 6.5.4) or a C-style cast in C++ 693# (C++ [expr.cast]), which uses the syntax (Type)expr. 694# 695# For example: (int)f. 696CursorKind.CSTYLE_CAST_EXPR = CursorKind(117) 697 698# [C99 6.5.2.5] 699CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118) 700 701# Describes an C or C++ initializer list. 702CursorKind.INIT_LIST_EXPR = CursorKind(119) 703 704# The GNU address of label extension, representing &&label. 705CursorKind.ADDR_LABEL_EXPR = CursorKind(120) 706 707# This is the GNU Statement Expression extension: ({int X=4; X;}) 708CursorKind.StmtExpr = CursorKind(121) 709 710# Represents a C11 generic selection. 711CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122) 712 713# Implements the GNU __null extension, which is a name for a null 714# pointer constant that has integral type (e.g., int or long) and is the same 715# size and alignment as a pointer. 716# 717# The __null extension is typically only used by system headers, which define 718# NULL as __null in C++ rather than using 0 (which is an integer that may not 719# match the size of a pointer). 720CursorKind.GNU_NULL_EXPR = CursorKind(123) 721 722# C++'s static_cast<> expression. 723CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124) 724 725# C++'s dynamic_cast<> expression. 726CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125) 727 728# C++'s reinterpret_cast<> expression. 729CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126) 730 731# C++'s const_cast<> expression. 732CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127) 733 734# Represents an explicit C++ type conversion that uses "functional" 735# notion (C++ [expr.type.conv]). 736# 737# Example: 738# \code 739# x = int(0.5); 740# \endcode 741CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128) 742 743# A C++ typeid expression (C++ [expr.typeid]). 744CursorKind.CXX_TYPEID_EXPR = CursorKind(129) 745 746# [C++ 2.13.5] C++ Boolean Literal. 747CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130) 748 749# [C++0x 2.14.7] C++ Pointer Literal. 750CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131) 751 752# Represents the "this" expression in C++ 753CursorKind.CXX_THIS_EXPR = CursorKind(132) 754 755# [C++ 15] C++ Throw Expression. 756# 757# This handles 'throw' and 'throw' assignment-expression. When 758# assignment-expression isn't present, Op will be null. 759CursorKind.CXX_THROW_EXPR = CursorKind(133) 760 761# A new expression for memory allocation and constructor calls, e.g: 762# "new CXXNewExpr(foo)". 763CursorKind.CXX_NEW_EXPR = CursorKind(134) 764 765# A delete expression for memory deallocation and destructor calls, 766# e.g. "delete[] pArray". 767CursorKind.CXX_DELETE_EXPR = CursorKind(135) 768 769# Represents a unary expression. 770CursorKind.CXX_UNARY_EXPR = CursorKind(136) 771 772# ObjCStringLiteral, used for Objective-C string literals i.e. "foo". 773CursorKind.OBJC_STRING_LITERAL = CursorKind(137) 774 775# ObjCEncodeExpr, used for in Objective-C. 776CursorKind.OBJC_ENCODE_EXPR = CursorKind(138) 777 778# ObjCSelectorExpr used for in Objective-C. 779CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139) 780 781# Objective-C's protocol expression. 782CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140) 783 784# An Objective-C "bridged" cast expression, which casts between 785# Objective-C pointers and C pointers, transferring ownership in the process. 786# 787# \code 788# NSString *str = (__bridge_transfer NSString *)CFCreateString(); 789# \endcode 790CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141) 791 792# Represents a C++0x pack expansion that produces a sequence of 793# expressions. 794# 795# A pack expansion expression contains a pattern (which itself is an 796# expression) followed by an ellipsis. For example: 797CursorKind.PACK_EXPANSION_EXPR = CursorKind(142) 798 799# Represents an expression that computes the length of a parameter 800# pack. 801CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143) 802 803# A statement whose specific kind is not exposed via this interface. 804# 805# Unexposed statements have the same operations as any other kind of statement; 806# one can extract their location information, spelling, children, etc. However, 807# the specific kind of the statement is not reported. 808CursorKind.UNEXPOSED_STMT = CursorKind(200) 809 810# A labelled statement in a function. 811CursorKind.LABEL_STMT = CursorKind(201) 812 813# A compound statement 814CursorKind.COMPOUND_STMT = CursorKind(202) 815 816# A case statement. 817CursorKind.CASE_STMT = CursorKind(203) 818 819# A default statement. 820CursorKind.DEFAULT_STMT = CursorKind(204) 821 822# An if statement. 823CursorKind.IF_STMT = CursorKind(205) 824 825# A switch statement. 826CursorKind.SWITCH_STMT = CursorKind(206) 827 828# A while statement. 829CursorKind.WHILE_STMT = CursorKind(207) 830 831# A do statement. 832CursorKind.DO_STMT = CursorKind(208) 833 834# A for statement. 835CursorKind.FOR_STMT = CursorKind(209) 836 837# A goto statement. 838CursorKind.GOTO_STMT = CursorKind(210) 839 840# An indirect goto statement. 841CursorKind.INDIRECT_GOTO_STMT = CursorKind(211) 842 843# A continue statement. 844CursorKind.CONTINUE_STMT = CursorKind(212) 845 846# A break statement. 847CursorKind.BREAK_STMT = CursorKind(213) 848 849# A return statement. 850CursorKind.RETURN_STMT = CursorKind(214) 851 852# A GNU-style inline assembler statement. 853CursorKind.ASM_STMT = CursorKind(215) 854 855# Objective-C's overall @try-@catch-@finally statement. 856CursorKind.OBJC_AT_TRY_STMT = CursorKind(216) 857 858# Objective-C's @catch statement. 859CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217) 860 861# Objective-C's @finally statement. 862CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218) 863 864# Objective-C's @throw statement. 865CursorKind.OBJC_AT_THROW_STMT = CursorKind(219) 866 867# Objective-C's @synchronized statement. 868CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220) 869 870# Objective-C's autorealease pool statement. 871CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221) 872 873# Objective-C's for collection statement. 874CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222) 875 876# C++'s catch statement. 877CursorKind.CXX_CATCH_STMT = CursorKind(223) 878 879# C++'s try statement. 880CursorKind.CXX_TRY_STMT = CursorKind(224) 881 882# C++'s for (* : *) statement. 883CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225) 884 885# Windows Structured Exception Handling's try statement. 886CursorKind.SEH_TRY_STMT = CursorKind(226) 887 888# Windows Structured Exception Handling's except statement. 889CursorKind.SEH_EXCEPT_STMT = CursorKind(227) 890 891# Windows Structured Exception Handling's finally statement. 892CursorKind.SEH_FINALLY_STMT = CursorKind(228) 893 894# The null statement. 895CursorKind.NULL_STMT = CursorKind(230) 896 897# Adaptor class for mixing declarations with statements and expressions. 898CursorKind.DECL_STMT = CursorKind(231) 899 900### 901# Other Kinds 902 903# Cursor that represents the translation unit itself. 904# 905# The translation unit cursor exists primarily to act as the root cursor for 906# traversing the contents of a translation unit. 907CursorKind.TRANSLATION_UNIT = CursorKind(300) 908 909### 910# Attributes 911 912# An attribute whoe specific kind is note exposed via this interface 913CursorKind.UNEXPOSED_ATTR = CursorKind(400) 914 915CursorKind.IB_ACTION_ATTR = CursorKind(401) 916CursorKind.IB_OUTLET_ATTR = CursorKind(402) 917CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403) 918 919CursorKind.CXX_FINAL_ATTR = CursorKind(404) 920CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405) 921CursorKind.ANNOTATE_ATTR = CursorKind(406) 922CursorKind.ASM_LABEL_ATTR = CursorKind(407) 923 924### 925# Preprocessing 926CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500) 927CursorKind.MACRO_DEFINITION = CursorKind(501) 928CursorKind.MACRO_INSTANTIATION = CursorKind(502) 929CursorKind.INCLUSION_DIRECTIVE = CursorKind(503) 930 931### Cursors ### 932 933class Cursor(Structure): 934 """ 935 The Cursor class represents a reference to an element within the AST. It 936 acts as a kind of iterator. 937 """ 938 _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)] 939 940 @staticmethod 941 def from_location(tu, location): 942 # We store a reference to the TU in the instance so the TU won't get 943 # collected before the cursor. 944 cursor = Cursor_get(tu, location) 945 cursor._tu = tu 946 947 return cursor 948 949 def __eq__(self, other): 950 return Cursor_eq(self, other) 951 952 def __ne__(self, other): 953 return not self.__eq__(other) 954 955 def is_definition(self): 956 """ 957 Returns true if the declaration pointed at by the cursor is also a 958 definition of that entity. 959 """ 960 return Cursor_is_def(self) 961 962 def is_static_method(self): 963 """Returns True if the cursor refers to a C++ member function or member 964 function template that is declared 'static'. 965 """ 966 return Cursor_is_static_method(self) 967 968 def get_definition(self): 969 """ 970 If the cursor is a reference to a declaration or a declaration of 971 some entity, return a cursor that points to the definition of that 972 entity. 973 """ 974 # TODO: Should probably check that this is either a reference or 975 # declaration prior to issuing the lookup. 976 return Cursor_def(self) 977 978 def get_usr(self): 979 """Return the Unified Symbol Resultion (USR) for the entity referenced 980 by the given cursor (or None). 981 982 A Unified Symbol Resolution (USR) is a string that identifies a 983 particular entity (function, class, variable, etc.) within a 984 program. USRs can be compared across translation units to determine, 985 e.g., when references in one translation refer to an entity defined in 986 another translation unit.""" 987 return Cursor_usr(self) 988 989 @property 990 def kind(self): 991 """Return the kind of this cursor.""" 992 return CursorKind.from_id(self._kind_id) 993 994 @property 995 def spelling(self): 996 """Return the spelling of the entity pointed at by the cursor.""" 997 if not self.kind.is_declaration(): 998 # FIXME: clang_getCursorSpelling should be fixed to not assert on 999 # this, for consistency with clang_getCursorUSR. 1000 return None 1001 if not hasattr(self, '_spelling'): 1002 self._spelling = Cursor_spelling(self) 1003 return self._spelling 1004 1005 @property 1006 def displayname(self): 1007 """ 1008 Return the display name for the entity referenced by this cursor. 1009 1010 The display name contains extra information that helps identify the cursor, 1011 such as the parameters of a function or template or the arguments of a 1012 class template specialization. 1013 """ 1014 if not hasattr(self, '_displayname'): 1015 self._displayname = Cursor_displayname(self) 1016 return self._displayname 1017 1018 @property 1019 def location(self): 1020 """ 1021 Return the source location (the starting character) of the entity 1022 pointed at by the cursor. 1023 """ 1024 if not hasattr(self, '_loc'): 1025 self._loc = Cursor_loc(self) 1026 return self._loc 1027 1028 @property 1029 def extent(self): 1030 """ 1031 Return the source range (the range of text) occupied by the entity 1032 pointed at by the cursor. 1033 """ 1034 if not hasattr(self, '_extent'): 1035 self._extent = Cursor_extent(self) 1036 return self._extent 1037 1038 @property 1039 def type(self): 1040 """ 1041 Retrieve the Type (if any) of the entity pointed at by the cursor. 1042 """ 1043 if not hasattr(self, '_type'): 1044 self._type = Cursor_type(self) 1045 return self._type 1046 1047 @property 1048 def canonical(self): 1049 """Return the canonical Cursor corresponding to this Cursor. 1050 1051 The canonical cursor is the cursor which is representative for the 1052 underlying entity. For example, if you have multiple forward 1053 declarations for the same class, the canonical cursor for the forward 1054 declarations will be identical. 1055 """ 1056 if not hasattr(self, '_canonical'): 1057 self._canonical = Cursor_canonical(self) 1058 1059 return self._canonical 1060 1061 @property 1062 def result_type(self): 1063 """Retrieve the Type of the result for this Cursor.""" 1064 if not hasattr(self, '_result_type'): 1065 self._result_type = Type_get_result(self.type) 1066 1067 return self._result_type 1068 1069 @property 1070 def underlying_typedef_type(self): 1071 """Return the underlying type of a typedef declaration. 1072 1073 Returns a Type for the typedef this cursor is a declaration for. If 1074 the current cursor is not a typedef, this raises. 1075 """ 1076 if not hasattr(self, '_underlying_type'): 1077 assert self.kind.is_declaration() 1078 self._underlying_type = Cursor_underlying_type(self) 1079 1080 return self._underlying_type 1081 1082 @property 1083 def enum_type(self): 1084 """Return the integer type of an enum declaration. 1085 1086 Returns a Type corresponding to an integer. If the cursor is not for an 1087 enum, this raises. 1088 """ 1089 if not hasattr(self, '_enum_type'): 1090 assert self.kind == CursorKind.ENUM_DECL 1091 self._enum_type = Cursor_enum_type(self) 1092 1093 return self._enum_type 1094 1095 @property 1096 def enum_value(self): 1097 """Return the value of an enum constant.""" 1098 if not hasattr(self, '_enum_value'): 1099 assert self.kind == CursorKind.ENUM_CONSTANT_DECL 1100 # Figure out the underlying type of the enum to know if it 1101 # is a signed or unsigned quantity. 1102 underlying_type = self.type 1103 if underlying_type.kind == TypeKind.ENUM: 1104 underlying_type = underlying_type.get_declaration().enum_type 1105 if underlying_type.kind in (TypeKind.CHAR_U, 1106 TypeKind.UCHAR, 1107 TypeKind.CHAR16, 1108 TypeKind.CHAR32, 1109 TypeKind.USHORT, 1110 TypeKind.UINT, 1111 TypeKind.ULONG, 1112 TypeKind.ULONGLONG, 1113 TypeKind.UINT128): 1114 self._enum_value = Cursor_enum_const_decl_unsigned(self) 1115 else: 1116 self._enum_value = Cursor_enum_const_decl(self) 1117 return self._enum_value 1118 1119 @property 1120 def objc_type_encoding(self): 1121 """Return the Objective-C type encoding as a str.""" 1122 if not hasattr(self, '_objc_type_encoding'): 1123 self._objc_type_encoding = Cursor_objc_type_encoding(self) 1124 1125 return self._objc_type_encoding 1126 1127 @property 1128 def hash(self): 1129 """Returns a hash of the cursor as an int.""" 1130 if not hasattr(self, '_hash'): 1131 self._hash = Cursor_hash(self) 1132 1133 return self._hash 1134 1135 @property 1136 def semantic_parent(self): 1137 """Return the semantic parent for this cursor.""" 1138 if not hasattr(self, '_semantic_parent'): 1139 self._semantic_parent = Cursor_semantic_parent(self) 1140 1141 return self._semantic_parent 1142 1143 @property 1144 def lexical_parent(self): 1145 """Return the lexical parent for this cursor.""" 1146 if not hasattr(self, '_lexical_parent'): 1147 self._lexical_parent = Cursor_lexical_parent(self) 1148 1149 return self._lexical_parent 1150 1151 @property 1152 def translation_unit(self): 1153 """Returns the TranslationUnit to which this Cursor belongs.""" 1154 # If this triggers an AttributeError, the instance was not properly 1155 # created. 1156 return self._tu 1157 1158 def get_children(self): 1159 """Return an iterator for accessing the children of this cursor.""" 1160 1161 # FIXME: Expose iteration from CIndex, PR6125. 1162 def visitor(child, parent, children): 1163 # FIXME: Document this assertion in API. 1164 # FIXME: There should just be an isNull method. 1165 assert child != Cursor_null() 1166 1167 # Create reference to TU so it isn't GC'd before Cursor. 1168 child._tu = self._tu 1169 children.append(child) 1170 return 1 # continue 1171 children = [] 1172 Cursor_visit(self, Cursor_visit_callback(visitor), children) 1173 return iter(children) 1174 1175 @staticmethod 1176 def from_result(res, fn, args): 1177 assert isinstance(res, Cursor) 1178 # FIXME: There should just be an isNull method. 1179 if res == Cursor_null(): 1180 return None 1181 1182 # Store a reference to the TU in the Python object so it won't get GC'd 1183 # before the Cursor. 1184 tu = None 1185 for arg in args: 1186 if isinstance(arg, TranslationUnit): 1187 tu = arg 1188 break 1189 1190 if hasattr(arg, 'translation_unit'): 1191 tu = arg.translation_unit 1192 break 1193 1194 assert tu is not None 1195 1196 res._tu = tu 1197 return res 1198 1199 1200### Type Kinds ### 1201 1202class TypeKind(object): 1203 """ 1204 Describes the kind of type. 1205 """ 1206 1207 # The unique kind objects, indexed by id. 1208 _kinds = [] 1209 _name_map = None 1210 1211 def __init__(self, value): 1212 if value >= len(TypeKind._kinds): 1213 TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1) 1214 if TypeKind._kinds[value] is not None: 1215 raise ValueError,'TypeKind already loaded' 1216 self.value = value 1217 TypeKind._kinds[value] = self 1218 TypeKind._name_map = None 1219 1220 def from_param(self): 1221 return self.value 1222 1223 @property 1224 def name(self): 1225 """Get the enumeration name of this cursor kind.""" 1226 if self._name_map is None: 1227 self._name_map = {} 1228 for key,value in TypeKind.__dict__.items(): 1229 if isinstance(value,TypeKind): 1230 self._name_map[value] = key 1231 return self._name_map[self] 1232 1233 @property 1234 def spelling(self): 1235 """Retrieve the spelling of this TypeKind.""" 1236 return TypeKind_spelling(self.value) 1237 1238 @staticmethod 1239 def from_id(id): 1240 if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None: 1241 raise ValueError,'Unknown type kind %d' % id 1242 return TypeKind._kinds[id] 1243 1244 def __repr__(self): 1245 return 'TypeKind.%s' % (self.name,) 1246 1247TypeKind_spelling = lib.clang_getTypeKindSpelling 1248TypeKind_spelling.argtypes = [c_uint] 1249TypeKind_spelling.restype = _CXString 1250TypeKind_spelling.errcheck = _CXString.from_result 1251 1252 1253TypeKind.INVALID = TypeKind(0) 1254TypeKind.UNEXPOSED = TypeKind(1) 1255TypeKind.VOID = TypeKind(2) 1256TypeKind.BOOL = TypeKind(3) 1257TypeKind.CHAR_U = TypeKind(4) 1258TypeKind.UCHAR = TypeKind(5) 1259TypeKind.CHAR16 = TypeKind(6) 1260TypeKind.CHAR32 = TypeKind(7) 1261TypeKind.USHORT = TypeKind(8) 1262TypeKind.UINT = TypeKind(9) 1263TypeKind.ULONG = TypeKind(10) 1264TypeKind.ULONGLONG = TypeKind(11) 1265TypeKind.UINT128 = TypeKind(12) 1266TypeKind.CHAR_S = TypeKind(13) 1267TypeKind.SCHAR = TypeKind(14) 1268TypeKind.WCHAR = TypeKind(15) 1269TypeKind.SHORT = TypeKind(16) 1270TypeKind.INT = TypeKind(17) 1271TypeKind.LONG = TypeKind(18) 1272TypeKind.LONGLONG = TypeKind(19) 1273TypeKind.INT128 = TypeKind(20) 1274TypeKind.FLOAT = TypeKind(21) 1275TypeKind.DOUBLE = TypeKind(22) 1276TypeKind.LONGDOUBLE = TypeKind(23) 1277TypeKind.NULLPTR = TypeKind(24) 1278TypeKind.OVERLOAD = TypeKind(25) 1279TypeKind.DEPENDENT = TypeKind(26) 1280TypeKind.OBJCID = TypeKind(27) 1281TypeKind.OBJCCLASS = TypeKind(28) 1282TypeKind.OBJCSEL = TypeKind(29) 1283TypeKind.COMPLEX = TypeKind(100) 1284TypeKind.POINTER = TypeKind(101) 1285TypeKind.BLOCKPOINTER = TypeKind(102) 1286TypeKind.LVALUEREFERENCE = TypeKind(103) 1287TypeKind.RVALUEREFERENCE = TypeKind(104) 1288TypeKind.RECORD = TypeKind(105) 1289TypeKind.ENUM = TypeKind(106) 1290TypeKind.TYPEDEF = TypeKind(107) 1291TypeKind.OBJCINTERFACE = TypeKind(108) 1292TypeKind.OBJCOBJECTPOINTER = TypeKind(109) 1293TypeKind.FUNCTIONNOPROTO = TypeKind(110) 1294TypeKind.FUNCTIONPROTO = TypeKind(111) 1295TypeKind.CONSTANTARRAY = TypeKind(112) 1296TypeKind.VECTOR = TypeKind(113) 1297 1298class Type(Structure): 1299 """ 1300 The type of an element in the abstract syntax tree. 1301 """ 1302 _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)] 1303 1304 @property 1305 def kind(self): 1306 """Return the kind of this type.""" 1307 return TypeKind.from_id(self._kind_id) 1308 1309 def argument_types(self): 1310 """Retrieve a container for the non-variadic arguments for this type. 1311 1312 The returned object is iterable and indexable. Each item in the 1313 container is a Type instance. 1314 """ 1315 class ArgumentsIterator(collections.Sequence): 1316 def __init__(self, parent): 1317 self.parent = parent 1318 self.length = None 1319 1320 def __len__(self): 1321 if self.length is None: 1322 self.length = Type_get_num_arg_types(self.parent) 1323 1324 return self.length 1325 1326 def __getitem__(self, key): 1327 # FIXME Support slice objects. 1328 if not isinstance(key, int): 1329 raise TypeError("Must supply a non-negative int.") 1330 1331 if key < 0: 1332 raise IndexError("Only non-negative indexes are accepted.") 1333 1334 if key >= len(self): 1335 raise IndexError("Index greater than container length: " 1336 "%d > %d" % ( key, len(self) )) 1337 1338 result = Type_get_arg_type(self.parent, key) 1339 if result.kind == TypeKind.INVALID: 1340 raise IndexError("Argument could not be retrieved.") 1341 1342 return result 1343 1344 assert self.kind == TypeKind.FUNCTIONPROTO 1345 return ArgumentsIterator(self) 1346 1347 @property 1348 def element_type(self): 1349 """Retrieve the Type of elements within this Type. 1350 1351 If accessed on a type that is not an array, complex, or vector type, an 1352 exception will be raised. 1353 """ 1354 result = Type_get_element_type(self) 1355 if result.kind == TypeKind.INVALID: 1356 raise Exception('Element type not available on this type.') 1357 1358 return result 1359 1360 @property 1361 def element_count(self): 1362 """Retrieve the number of elements in this type. 1363 1364 Returns an int. 1365 1366 If the Type is not an array or vector, this raises. 1367 """ 1368 result = Type_get_num_elements(self) 1369 if result < 0: 1370 raise Exception('Type does not have elements.') 1371 1372 return result 1373 1374 @property 1375 def translation_unit(self): 1376 """The TranslationUnit to which this Type is associated.""" 1377 # If this triggers an AttributeError, the instance was not properly 1378 # instantiated. 1379 return self._tu 1380 1381 @staticmethod 1382 def from_result(res, fn, args): 1383 assert isinstance(res, Type) 1384 1385 tu = None 1386 for arg in args: 1387 if hasattr(arg, 'translation_unit'): 1388 tu = arg.translation_unit 1389 break 1390 1391 assert tu is not None 1392 res._tu = tu 1393 1394 return res 1395 1396 def get_canonical(self): 1397 """ 1398 Return the canonical type for a Type. 1399 1400 Clang's type system explicitly models typedefs and all the 1401 ways a specific type can be represented. The canonical type 1402 is the underlying type with all the "sugar" removed. For 1403 example, if 'T' is a typedef for 'int', the canonical type for 1404 'T' would be 'int'. 1405 """ 1406 return Type_get_canonical(self) 1407 1408 def is_const_qualified(self): 1409 """Determine whether a Type has the "const" qualifier set. 1410 1411 This does not look through typedefs that may have added "const" 1412 at a different level. 1413 """ 1414 return Type_is_const_qualified(self) 1415 1416 def is_volatile_qualified(self): 1417 """Determine whether a Type has the "volatile" qualifier set. 1418 1419 This does not look through typedefs that may have added "volatile" 1420 at a different level. 1421 """ 1422 return Type_is_volatile_qualified(self) 1423 1424 def is_restrict_qualified(self): 1425 """Determine whether a Type has the "restrict" qualifier set. 1426 1427 This does not look through typedefs that may have added "restrict" at 1428 a different level. 1429 """ 1430 return Type_is_restrict_qualified(self) 1431 1432 def is_function_variadic(self): 1433 """Determine whether this function Type is a variadic function type.""" 1434 assert self.kind == TypeKind.FUNCTIONPROTO 1435 1436 return Type_is_variadic(self) 1437 1438 def is_pod(self): 1439 """Determine whether this Type represents plain old data (POD).""" 1440 return Type_is_pod(self) 1441 1442 def get_pointee(self): 1443 """ 1444 For pointer types, returns the type of the pointee. 1445 """ 1446 return Type_get_pointee(self) 1447 1448 def get_declaration(self): 1449 """ 1450 Return the cursor for the declaration of the given type. 1451 """ 1452 return Type_get_declaration(self) 1453 1454 def get_result(self): 1455 """ 1456 Retrieve the result type associated with a function type. 1457 """ 1458 return Type_get_result(self) 1459 1460 def get_array_element_type(self): 1461 """ 1462 Retrieve the type of the elements of the array type. 1463 """ 1464 return Type_get_array_element(self) 1465 1466 def get_array_size(self): 1467 """ 1468 Retrieve the size of the constant array. 1469 """ 1470 return Type_get_array_size(self) 1471 1472 def __eq__(self, other): 1473 if type(other) != type(self): 1474 return False 1475 1476 return Type_equal(self, other) 1477 1478 def __ne__(self, other): 1479 return not self.__eq__(other) 1480 1481## CIndex Objects ## 1482 1483# CIndex objects (derived from ClangObject) are essentially lightweight 1484# wrappers attached to some underlying object, which is exposed via CIndex as 1485# a void*. 1486 1487class ClangObject(object): 1488 """ 1489 A helper for Clang objects. This class helps act as an intermediary for 1490 the ctypes library and the Clang CIndex library. 1491 """ 1492 def __init__(self, obj): 1493 assert isinstance(obj, c_object_p) and obj 1494 self.obj = self._as_parameter_ = obj 1495 1496 def from_param(self): 1497 return self._as_parameter_ 1498 1499 1500class _CXUnsavedFile(Structure): 1501 """Helper for passing unsaved file arguments.""" 1502 _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)] 1503 1504## Diagnostic Conversion ## 1505 1506_clang_getNumDiagnostics = lib.clang_getNumDiagnostics 1507_clang_getNumDiagnostics.argtypes = [c_object_p] 1508_clang_getNumDiagnostics.restype = c_uint 1509 1510_clang_getDiagnostic = lib.clang_getDiagnostic 1511_clang_getDiagnostic.argtypes = [c_object_p, c_uint] 1512_clang_getDiagnostic.restype = c_object_p 1513 1514_clang_disposeDiagnostic = lib.clang_disposeDiagnostic 1515_clang_disposeDiagnostic.argtypes = [Diagnostic] 1516 1517_clang_getDiagnosticSeverity = lib.clang_getDiagnosticSeverity 1518_clang_getDiagnosticSeverity.argtypes = [Diagnostic] 1519_clang_getDiagnosticSeverity.restype = c_int 1520 1521_clang_getDiagnosticLocation = lib.clang_getDiagnosticLocation 1522_clang_getDiagnosticLocation.argtypes = [Diagnostic] 1523_clang_getDiagnosticLocation.restype = SourceLocation 1524 1525_clang_getDiagnosticSpelling = lib.clang_getDiagnosticSpelling 1526_clang_getDiagnosticSpelling.argtypes = [Diagnostic] 1527_clang_getDiagnosticSpelling.restype = _CXString 1528_clang_getDiagnosticSpelling.errcheck = _CXString.from_result 1529 1530_clang_getDiagnosticNumRanges = lib.clang_getDiagnosticNumRanges 1531_clang_getDiagnosticNumRanges.argtypes = [Diagnostic] 1532_clang_getDiagnosticNumRanges.restype = c_uint 1533 1534_clang_getDiagnosticRange = lib.clang_getDiagnosticRange 1535_clang_getDiagnosticRange.argtypes = [Diagnostic, c_uint] 1536_clang_getDiagnosticRange.restype = SourceRange 1537 1538_clang_getDiagnosticNumFixIts = lib.clang_getDiagnosticNumFixIts 1539_clang_getDiagnosticNumFixIts.argtypes = [Diagnostic] 1540_clang_getDiagnosticNumFixIts.restype = c_uint 1541 1542_clang_getDiagnosticFixIt = lib.clang_getDiagnosticFixIt 1543_clang_getDiagnosticFixIt.argtypes = [Diagnostic, c_uint, POINTER(SourceRange)] 1544_clang_getDiagnosticFixIt.restype = _CXString 1545_clang_getDiagnosticFixIt.errcheck = _CXString.from_result 1546 1547_clang_getDiagnosticCategory = lib.clang_getDiagnosticCategory 1548_clang_getDiagnosticCategory.argtypes = [Diagnostic] 1549_clang_getDiagnosticCategory.restype = c_uint 1550 1551_clang_getDiagnosticCategoryName = lib.clang_getDiagnosticCategoryName 1552_clang_getDiagnosticCategoryName.argtypes = [c_uint] 1553_clang_getDiagnosticCategoryName.restype = _CXString 1554_clang_getDiagnosticCategoryName.errcheck = _CXString.from_result 1555 1556_clang_getDiagnosticOption = lib.clang_getDiagnosticOption 1557_clang_getDiagnosticOption.argtypes = [Diagnostic, POINTER(_CXString)] 1558_clang_getDiagnosticOption.restype = _CXString 1559_clang_getDiagnosticOption.errcheck = _CXString.from_result 1560 1561### 1562 1563class CompletionChunk: 1564 class Kind: 1565 def __init__(self, name): 1566 self.name = name 1567 1568 def __str__(self): 1569 return self.name 1570 1571 def __repr__(self): 1572 return "<ChunkKind: %s>" % self 1573 1574 def __init__(self, completionString, key): 1575 self.cs = completionString 1576 self.key = key 1577 1578 def __repr__(self): 1579 return "{'" + self.spelling + "', " + str(self.kind) + "}" 1580 1581 @property 1582 def spelling(self): 1583 return _clang_getCompletionChunkText(self.cs, self.key).spelling 1584 1585 @property 1586 def kind(self): 1587 res = _clang_getCompletionChunkKind(self.cs, self.key) 1588 return completionChunkKindMap[res] 1589 1590 @property 1591 def string(self): 1592 res = _clang_getCompletionChunkCompletionString(self.cs, self.key) 1593 1594 if (res): 1595 return CompletionString(res) 1596 else: 1597 None 1598 1599 def isKindOptional(self): 1600 return self.kind == completionChunkKindMap[0] 1601 1602 def isKindTypedText(self): 1603 return self.kind == completionChunkKindMap[1] 1604 1605 def isKindPlaceHolder(self): 1606 return self.kind == completionChunkKindMap[3] 1607 1608 def isKindInformative(self): 1609 return self.kind == completionChunkKindMap[4] 1610 1611 def isKindResultType(self): 1612 return self.kind == completionChunkKindMap[15] 1613 1614completionChunkKindMap = { 1615 0: CompletionChunk.Kind("Optional"), 1616 1: CompletionChunk.Kind("TypedText"), 1617 2: CompletionChunk.Kind("Text"), 1618 3: CompletionChunk.Kind("Placeholder"), 1619 4: CompletionChunk.Kind("Informative"), 1620 5: CompletionChunk.Kind("CurrentParameter"), 1621 6: CompletionChunk.Kind("LeftParen"), 1622 7: CompletionChunk.Kind("RightParen"), 1623 8: CompletionChunk.Kind("LeftBracket"), 1624 9: CompletionChunk.Kind("RightBracket"), 1625 10: CompletionChunk.Kind("LeftBrace"), 1626 11: CompletionChunk.Kind("RightBrace"), 1627 12: CompletionChunk.Kind("LeftAngle"), 1628 13: CompletionChunk.Kind("RightAngle"), 1629 14: CompletionChunk.Kind("Comma"), 1630 15: CompletionChunk.Kind("ResultType"), 1631 16: CompletionChunk.Kind("Colon"), 1632 17: CompletionChunk.Kind("SemiColon"), 1633 18: CompletionChunk.Kind("Equal"), 1634 19: CompletionChunk.Kind("HorizontalSpace"), 1635 20: CompletionChunk.Kind("VerticalSpace")} 1636 1637class CompletionString(ClangObject): 1638 class Availability: 1639 def __init__(self, name): 1640 self.name = name 1641 1642 def __str__(self): 1643 return self.name 1644 1645 def __repr__(self): 1646 return "<Availability: %s>" % self 1647 1648 def __len__(self): 1649 return _clang_getNumCompletionChunks(self.obj) 1650 1651 def __getitem__(self, key): 1652 if len(self) <= key: 1653 raise IndexError 1654 return CompletionChunk(self.obj, key) 1655 1656 @property 1657 def priority(self): 1658 return _clang_getCompletionPriority(self.obj) 1659 1660 @property 1661 def availability(self): 1662 res = _clang_getCompletionAvailability(self.obj) 1663 return availabilityKinds[res] 1664 1665 def __repr__(self): 1666 return " | ".join([str(a) for a in self]) \ 1667 + " || Priority: " + str(self.priority) \ 1668 + " || Availability: " + str(self.availability) 1669 1670availabilityKinds = { 1671 0: CompletionChunk.Kind("Available"), 1672 1: CompletionChunk.Kind("Deprecated"), 1673 2: CompletionChunk.Kind("NotAvailable")} 1674 1675class CodeCompletionResult(Structure): 1676 _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)] 1677 1678 def __repr__(self): 1679 return str(CompletionString(self.completionString)) 1680 1681 @property 1682 def kind(self): 1683 return CursorKind.from_id(self.cursorKind) 1684 1685 @property 1686 def string(self): 1687 return CompletionString(self.completionString) 1688 1689class CCRStructure(Structure): 1690 _fields_ = [('results', POINTER(CodeCompletionResult)), 1691 ('numResults', c_int)] 1692 1693 def __len__(self): 1694 return self.numResults 1695 1696 def __getitem__(self, key): 1697 if len(self) <= key: 1698 raise IndexError 1699 1700 return self.results[key] 1701 1702class CodeCompletionResults(ClangObject): 1703 def __init__(self, ptr): 1704 assert isinstance(ptr, POINTER(CCRStructure)) and ptr 1705 self.ptr = self._as_parameter_ = ptr 1706 1707 def from_param(self): 1708 return self._as_parameter_ 1709 1710 def __del__(self): 1711 CodeCompletionResults_dispose(self) 1712 1713 @property 1714 def results(self): 1715 return self.ptr.contents 1716 1717 @property 1718 def diagnostics(self): 1719 class DiagnosticsItr: 1720 def __init__(self, ccr): 1721 self.ccr= ccr 1722 1723 def __len__(self): 1724 return int(_clang_codeCompleteGetNumDiagnostics(self.ccr)) 1725 1726 def __getitem__(self, key): 1727 return _clang_codeCompleteGetDiagnostic(self.ccr, key) 1728 1729 return DiagnosticsItr(self) 1730 1731 1732class Index(ClangObject): 1733 """ 1734 The Index type provides the primary interface to the Clang CIndex library, 1735 primarily by providing an interface for reading and parsing translation 1736 units. 1737 """ 1738 1739 @staticmethod 1740 def create(excludeDecls=False): 1741 """ 1742 Create a new Index. 1743 Parameters: 1744 excludeDecls -- Exclude local declarations from translation units. 1745 """ 1746 return Index(Index_create(excludeDecls, 0)) 1747 1748 def __del__(self): 1749 Index_dispose(self) 1750 1751 def read(self, path): 1752 """Load a TranslationUnit from the given AST file.""" 1753 return TranslationUnit.from_ast(path, self) 1754 1755 def parse(self, path, args=None, unsaved_files=None, options = 0): 1756 """Load the translation unit from the given source code file by running 1757 clang and generating the AST before loading. Additional command line 1758 parameters can be passed to clang via the args parameter. 1759 1760 In-memory contents for files can be provided by passing a list of pairs 1761 to as unsaved_files, the first item should be the filenames to be mapped 1762 and the second should be the contents to be substituted for the 1763 file. The contents may be passed as strings or file objects. 1764 1765 If an error was encountered during parsing, a TranslationUnitLoadError 1766 will be raised. 1767 """ 1768 return TranslationUnit.from_source(path, args, unsaved_files, options, 1769 self) 1770 1771class TranslationUnit(ClangObject): 1772 """Represents a source code translation unit. 1773 1774 This is one of the main types in the API. Any time you wish to interact 1775 with Clang's representation of a source file, you typically start with a 1776 translation unit. 1777 """ 1778 1779 # Default parsing mode. 1780 PARSE_NONE = 0 1781 1782 # Instruct the parser to create a detailed processing record containing 1783 # metadata not normally retained. 1784 PARSE_DETAILED_PROCESSING_RECORD = 1 1785 1786 # Indicates that the translation unit is incomplete. This is typically used 1787 # when parsing headers. 1788 PARSE_INCOMPLETE = 2 1789 1790 # Instruct the parser to create a pre-compiled preamble for the translation 1791 # unit. This caches the preamble (included files at top of source file). 1792 # This is useful if the translation unit will be reparsed and you don't 1793 # want to incur the overhead of reparsing the preamble. 1794 PARSE_PRECOMPILED_PREAMBLE = 4 1795 1796 # Cache code completion information on parse. This adds time to parsing but 1797 # speeds up code completion. 1798 PARSE_CACHE_COMPLETION_RESULTS = 8 1799 1800 # Flags with values 16 and 32 are deprecated and intentionally omitted. 1801 1802 # Do not parse function bodies. This is useful if you only care about 1803 # searching for declarations/definitions. 1804 PARSE_SKIP_FUNCTION_BODIES = 64 1805 1806 @classmethod 1807 def from_source(cls, filename, args=None, unsaved_files=None, options=0, 1808 index=None): 1809 """Create a TranslationUnit by parsing source. 1810 1811 This is capable of processing source code both from files on the 1812 filesystem as well as in-memory contents. 1813 1814 Command-line arguments that would be passed to clang are specified as 1815 a list via args. These can be used to specify include paths, warnings, 1816 etc. e.g. ["-Wall", "-I/path/to/include"]. 1817 1818 In-memory file content can be provided via unsaved_files. This is an 1819 iterable of 2-tuples. The first element is the str filename. The 1820 second element defines the content. Content can be provided as str 1821 source code or as file objects (anything with a read() method). If 1822 a file object is being used, content will be read until EOF and the 1823 read cursor will not be reset to its original position. 1824 1825 options is a bitwise or of TranslationUnit.PARSE_XXX flags which will 1826 control parsing behavior. 1827 1828 index is an Index instance to utilize. If not provided, a new Index 1829 will be created for this TranslationUnit. 1830 1831 To parse source from the filesystem, the filename of the file to parse 1832 is specified by the filename argument. Or, filename could be None and 1833 the args list would contain the filename(s) to parse. 1834 1835 To parse source from an in-memory buffer, set filename to the virtual 1836 filename you wish to associate with this source (e.g. "test.c"). The 1837 contents of that file are then provided in unsaved_files. 1838 1839 If an error occurs, a TranslationUnitLoadError is raised. 1840 1841 Please note that a TranslationUnit with parser errors may be returned. 1842 It is the caller's responsibility to check tu.diagnostics for errors. 1843 1844 Also note that Clang infers the source language from the extension of 1845 the input filename. If you pass in source code containing a C++ class 1846 declaration with the filename "test.c" parsing will fail. 1847 """ 1848 if args is None: 1849 args = [] 1850 1851 if unsaved_files is None: 1852 unsaved_files = [] 1853 1854 if index is None: 1855 index = Index.create() 1856 1857 args_array = None 1858 if len(args) > 0: 1859 args_array = (c_char_p * len(args))(* args) 1860 1861 unsaved_array = None 1862 if len(unsaved_files) > 0: 1863 unsaved_array = (_CXUnsavedFile * len(unsaved_files))() 1864 for i, (name, contents) in enumerate(unsaved_files): 1865 if hasattr(contents, "read"): 1866 contents = contents.read() 1867 1868 unsaved_array[i].name = name 1869 unsaved_array[i].contents = contents 1870 unsaved_array[i].length = len(contents) 1871 1872 ptr = TranslationUnit_parse(index, filename, args_array, len(args), 1873 unsaved_array, len(unsaved_files), 1874 options) 1875 1876 if ptr is None: 1877 raise TranslationUnitLoadError("Error parsing translation unit.") 1878 1879 return cls(ptr, index=index) 1880 1881 @classmethod 1882 def from_ast_file(cls, filename, index=None): 1883 """Create a TranslationUnit instance from a saved AST file. 1884 1885 A previously-saved AST file (provided with -emit-ast or 1886 TranslationUnit.save()) is loaded from the filename specified. 1887 1888 If the file cannot be loaded, a TranslationUnitLoadError will be 1889 raised. 1890 1891 index is optional and is the Index instance to use. If not provided, 1892 a default Index will be created. 1893 """ 1894 if index is None: 1895 index = Index.create() 1896 1897 ptr = TranslationUnit_read(index, filename) 1898 if ptr is None: 1899 raise TranslationUnitLoadError(filename) 1900 1901 return cls(ptr=ptr, index=index) 1902 1903 def __init__(self, ptr, index): 1904 """Create a TranslationUnit instance. 1905 1906 TranslationUnits should be created using one of the from_* @classmethod 1907 functions above. __init__ is only called internally. 1908 """ 1909 assert isinstance(index, Index) 1910 1911 ClangObject.__init__(self, ptr) 1912 1913 def __del__(self): 1914 TranslationUnit_dispose(self) 1915 1916 @property 1917 def cursor(self): 1918 """Retrieve the cursor that represents the given translation unit.""" 1919 return TranslationUnit_cursor(self) 1920 1921 @property 1922 def spelling(self): 1923 """Get the original translation unit source file name.""" 1924 return TranslationUnit_spelling(self) 1925 1926 def get_includes(self): 1927 """ 1928 Return an iterable sequence of FileInclusion objects that describe the 1929 sequence of inclusions in a translation unit. The first object in 1930 this sequence is always the input file. Note that this method will not 1931 recursively iterate over header files included through precompiled 1932 headers. 1933 """ 1934 def visitor(fobj, lptr, depth, includes): 1935 if depth > 0: 1936 loc = lptr.contents 1937 includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) 1938 1939 # Automatically adapt CIndex/ctype pointers to python objects 1940 includes = [] 1941 TranslationUnit_includes(self, 1942 TranslationUnit_includes_callback(visitor), 1943 includes) 1944 return iter(includes) 1945 1946 @property 1947 def diagnostics(self): 1948 """ 1949 Return an iterable (and indexable) object containing the diagnostics. 1950 """ 1951 class DiagIterator: 1952 def __init__(self, tu): 1953 self.tu = tu 1954 1955 def __len__(self): 1956 return int(_clang_getNumDiagnostics(self.tu)) 1957 1958 def __getitem__(self, key): 1959 diag = _clang_getDiagnostic(self.tu, key) 1960 if not diag: 1961 raise IndexError 1962 return Diagnostic(diag) 1963 1964 return DiagIterator(self) 1965 1966 def reparse(self, unsaved_files=None, options=0): 1967 """ 1968 Reparse an already parsed translation unit. 1969 1970 In-memory contents for files can be provided by passing a list of pairs 1971 as unsaved_files, the first items should be the filenames to be mapped 1972 and the second should be the contents to be substituted for the 1973 file. The contents may be passed as strings or file objects. 1974 """ 1975 if unsaved_files is None: 1976 unsaved_files = [] 1977 1978 unsaved_files_array = 0 1979 if len(unsaved_files): 1980 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() 1981 for i,(name,value) in enumerate(unsaved_files): 1982 if not isinstance(value, str): 1983 # FIXME: It would be great to support an efficient version 1984 # of this, one day. 1985 value = value.read() 1986 print value 1987 if not isinstance(value, str): 1988 raise TypeError,'Unexpected unsaved file contents.' 1989 unsaved_files_array[i].name = name 1990 unsaved_files_array[i].contents = value 1991 unsaved_files_array[i].length = len(value) 1992 ptr = TranslationUnit_reparse(self, len(unsaved_files), 1993 unsaved_files_array, 1994 options) 1995 1996 def save(self, filename): 1997 """Saves the TranslationUnit to a file. 1998 1999 This is equivalent to passing -emit-ast to the clang frontend. The 2000 saved file can be loaded back into a TranslationUnit. Or, if it 2001 corresponds to a header, it can be used as a pre-compiled header file. 2002 2003 If an error occurs while saving, a TranslationUnitSaveError is raised. 2004 If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means 2005 the constructed TranslationUnit was not valid at time of save. In this 2006 case, the reason(s) why should be available via 2007 TranslationUnit.diagnostics(). 2008 2009 filename -- The path to save the translation unit to. 2010 """ 2011 options = TranslationUnit_defaultSaveOptions(self) 2012 result = int(TranslationUnit_save(self, filename, options)) 2013 if result != 0: 2014 raise TranslationUnitSaveError(result, 2015 'Error saving TranslationUnit.') 2016 2017 def codeComplete(self, path, line, column, unsaved_files=None, options=0): 2018 """ 2019 Code complete in this translation unit. 2020 2021 In-memory contents for files can be provided by passing a list of pairs 2022 as unsaved_files, the first items should be the filenames to be mapped 2023 and the second should be the contents to be substituted for the 2024 file. The contents may be passed as strings or file objects. 2025 """ 2026 if unsaved_files is None: 2027 unsaved_files = [] 2028 2029 unsaved_files_array = 0 2030 if len(unsaved_files): 2031 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() 2032 for i,(name,value) in enumerate(unsaved_files): 2033 if not isinstance(value, str): 2034 # FIXME: It would be great to support an efficient version 2035 # of this, one day. 2036 value = value.read() 2037 print value 2038 if not isinstance(value, str): 2039 raise TypeError,'Unexpected unsaved file contents.' 2040 unsaved_files_array[i].name = name 2041 unsaved_files_array[i].contents = value 2042 unsaved_files_array[i].length = len(value) 2043 ptr = TranslationUnit_codeComplete(self, path, 2044 line, column, 2045 unsaved_files_array, 2046 len(unsaved_files), 2047 options) 2048 if ptr: 2049 return CodeCompletionResults(ptr) 2050 return None 2051 2052class File(ClangObject): 2053 """ 2054 The File class represents a particular source file that is part of a 2055 translation unit. 2056 """ 2057 2058 @staticmethod 2059 def from_name(translation_unit, file_name): 2060 """Retrieve a file handle within the given translation unit.""" 2061 return File(File_getFile(translation_unit, file_name)) 2062 2063 @property 2064 def name(self): 2065 """Return the complete file and path name of the file.""" 2066 return _CXString_getCString(File_name(self)) 2067 2068 @property 2069 def time(self): 2070 """Return the last modification time of the file.""" 2071 return File_time(self) 2072 2073 def __str__(self): 2074 return self.name 2075 2076 def __repr__(self): 2077 return "<File: %s>" % (self.name) 2078 2079class FileInclusion(object): 2080 """ 2081 The FileInclusion class represents the inclusion of one source file by 2082 another via a '#include' directive or as the input file for the translation 2083 unit. This class provides information about the included file, the including 2084 file, the location of the '#include' directive and the depth of the included 2085 file in the stack. Note that the input file has depth 0. 2086 """ 2087 2088 def __init__(self, src, tgt, loc, depth): 2089 self.source = src 2090 self.include = tgt 2091 self.location = loc 2092 self.depth = depth 2093 2094 @property 2095 def is_input_file(self): 2096 """True if the included file is the input file.""" 2097 return self.depth == 0 2098 2099class CompilationDatabaseError(Exception): 2100 """Represents an error that occurred when working with a CompilationDatabase 2101 2102 Each error is associated to an enumerated value, accessible under 2103 e.cdb_error. Consumers can compare the value with one of the ERROR_ 2104 constants in this class. 2105 """ 2106 2107 # An unknown error occured 2108 ERROR_UNKNOWN = 0 2109 2110 # The database could not be loaded 2111 ERROR_CANNOTLOADDATABASE = 1 2112 2113 def __init__(self, enumeration, message): 2114 assert isinstance(enumeration, int) 2115 2116 if enumeration > 1: 2117 raise Exception("Encountered undefined CompilationDatabase error " 2118 "constant: %d. Please file a bug to have this " 2119 "value supported." % enumeration) 2120 2121 self.cdb_error = enumeration 2122 Exception.__init__(self, 'Error %d: %s' % (enumeration, message)) 2123 2124class CompileCommand(object): 2125 """Represents the compile command used to build a file""" 2126 def __init__(self, cmd, ccmds): 2127 self.cmd = cmd 2128 # Keep a reference to the originating CompileCommands 2129 # to prevent garbage collection 2130 self.ccmds = ccmds 2131 2132 @property 2133 def directory(self): 2134 """Get the working directory for this CompileCommand""" 2135 return CompileCommand_getDirectory(self.cmd).spelling 2136 2137 @property 2138 def arguments(self): 2139 """ 2140 Get an iterable object providing each argument in the 2141 command line for the compiler invocation as a _CXString. 2142 2143 Invariants : 2144 - the first argument is the compiler executable 2145 - the last argument is the file being compiled 2146 """ 2147 length = CompileCommand_getNumArgs(self.cmd) 2148 for i in xrange(length): 2149 yield CompileCommand_getArg(self.cmd, i) 2150 2151class CompileCommands(object): 2152 """ 2153 CompileCommands is an iterable object containing all CompileCommand 2154 that can be used for building a specific file. 2155 """ 2156 def __init__(self, ccmds): 2157 self.ccmds = ccmds 2158 2159 def __del__(self): 2160 CompileCommands_dispose(self.ccmds) 2161 2162 def __len__(self): 2163 return int(CompileCommands_getSize(self.ccmds)) 2164 2165 def __getitem__(self, i): 2166 cc = CompileCommands_getCommand(self.ccmds, i) 2167 if cc is None: 2168 raise IndexError 2169 return CompileCommand(cc, self) 2170 2171 @staticmethod 2172 def from_result(res, fn, args): 2173 if not res: 2174 return None 2175 return CompileCommands(res) 2176 2177class CompilationDatabase(ClangObject): 2178 """ 2179 The CompilationDatabase is a wrapper class around 2180 clang::tooling::CompilationDatabase 2181 2182 It enables querying how a specific source file can be built. 2183 """ 2184 2185 def __del__(self): 2186 CompilationDatabase_dispose(self) 2187 2188 @staticmethod 2189 def from_result(res, fn, args): 2190 if not res: 2191 raise CompilationDatabaseError(0, 2192 "CompilationDatabase loading failed") 2193 return CompilationDatabase(res) 2194 2195 @staticmethod 2196 def fromDirectory(buildDir): 2197 """Builds a CompilationDatabase from the database found in buildDir""" 2198 errorCode = c_uint() 2199 try: 2200 cdb = CompilationDatabase_fromDirectory(buildDir, byref(errorCode)) 2201 except CompilationDatabaseError as e: 2202 raise CompilationDatabaseError(int(errorCode.value), 2203 "CompilationDatabase loading failed") 2204 return cdb 2205 2206 def getCompileCommands(self, filename): 2207 """ 2208 Get an iterable object providing all the CompileCommands available to 2209 build filename. Returns None if filename is not found in the database. 2210 """ 2211 return CompilationDatabase_getCompileCommands(self, filename) 2212 2213# Additional Functions and Types 2214 2215# String Functions 2216_CXString_dispose = lib.clang_disposeString 2217_CXString_dispose.argtypes = [_CXString] 2218 2219_CXString_getCString = lib.clang_getCString 2220_CXString_getCString.argtypes = [_CXString] 2221_CXString_getCString.restype = c_char_p 2222 2223# Source Location Functions 2224SourceLocation_loc = lib.clang_getInstantiationLocation 2225SourceLocation_loc.argtypes = [SourceLocation, POINTER(c_object_p), 2226 POINTER(c_uint), POINTER(c_uint), 2227 POINTER(c_uint)] 2228 2229SourceLocation_getLocation = lib.clang_getLocation 2230SourceLocation_getLocation.argtypes = [TranslationUnit, File, c_uint, c_uint] 2231SourceLocation_getLocation.restype = SourceLocation 2232 2233SourceLocation_equalLocations = lib.clang_equalLocations 2234SourceLocation_equalLocations.argtypes = [SourceLocation, SourceLocation] 2235SourceLocation_equalLocations.restype = bool 2236 2237SourceLocation_getLocationForOffset = lib.clang_getLocationForOffset 2238SourceLocation_getLocationForOffset.argtypes = [TranslationUnit, File, c_uint] 2239SourceLocation_getLocationForOffset.restype = SourceLocation 2240 2241# Source Range Functions 2242SourceRange_getRange = lib.clang_getRange 2243SourceRange_getRange.argtypes = [SourceLocation, SourceLocation] 2244SourceRange_getRange.restype = SourceRange 2245 2246SourceRange_start = lib.clang_getRangeStart 2247SourceRange_start.argtypes = [SourceRange] 2248SourceRange_start.restype = SourceLocation 2249 2250SourceRange_end = lib.clang_getRangeEnd 2251SourceRange_end.argtypes = [SourceRange] 2252SourceRange_end.restype = SourceLocation 2253 2254SourceRange_equalRanges = lib.clang_equalRanges 2255SourceRange_equalRanges.argtypes = [SourceRange, SourceRange] 2256SourceRange_equalRanges.restype = bool 2257 2258# CursorKind Functions 2259CursorKind_is_decl = lib.clang_isDeclaration 2260CursorKind_is_decl.argtypes = [CursorKind] 2261CursorKind_is_decl.restype = bool 2262 2263CursorKind_is_ref = lib.clang_isReference 2264CursorKind_is_ref.argtypes = [CursorKind] 2265CursorKind_is_ref.restype = bool 2266 2267CursorKind_is_expr = lib.clang_isExpression 2268CursorKind_is_expr.argtypes = [CursorKind] 2269CursorKind_is_expr.restype = bool 2270 2271CursorKind_is_stmt = lib.clang_isStatement 2272CursorKind_is_stmt.argtypes = [CursorKind] 2273CursorKind_is_stmt.restype = bool 2274 2275CursorKind_is_attribute = lib.clang_isAttribute 2276CursorKind_is_attribute.argtypes = [CursorKind] 2277CursorKind_is_attribute.restype = bool 2278 2279CursorKind_is_inv = lib.clang_isInvalid 2280CursorKind_is_inv.argtypes = [CursorKind] 2281CursorKind_is_inv.restype = bool 2282 2283CursorKind_is_translation_unit = lib.clang_isTranslationUnit 2284CursorKind_is_translation_unit.argtypes = [CursorKind] 2285CursorKind_is_translation_unit.restype = bool 2286 2287CursorKind_is_preprocessing = lib.clang_isPreprocessing 2288CursorKind_is_preprocessing.argtypes = [CursorKind] 2289CursorKind_is_preprocessing.restype = bool 2290 2291CursorKind_is_unexposed = lib.clang_isUnexposed 2292CursorKind_is_unexposed.argtypes = [CursorKind] 2293CursorKind_is_unexposed.restype = bool 2294 2295# Cursor Functions 2296# TODO: Implement this function 2297Cursor_get = lib.clang_getCursor 2298Cursor_get.argtypes = [TranslationUnit, SourceLocation] 2299Cursor_get.restype = Cursor 2300 2301Cursor_null = lib.clang_getNullCursor 2302Cursor_null.restype = Cursor 2303 2304Cursor_usr = lib.clang_getCursorUSR 2305Cursor_usr.argtypes = [Cursor] 2306Cursor_usr.restype = _CXString 2307Cursor_usr.errcheck = _CXString.from_result 2308 2309Cursor_is_def = lib.clang_isCursorDefinition 2310Cursor_is_def.argtypes = [Cursor] 2311Cursor_is_def.restype = bool 2312 2313Cursor_is_static_method = lib.clang_CXXMethod_isStatic 2314Cursor_is_static_method.argtypes = [Cursor] 2315Cursor_is_static_method.restype = bool 2316 2317Cursor_def = lib.clang_getCursorDefinition 2318Cursor_def.argtypes = [Cursor] 2319Cursor_def.restype = Cursor 2320Cursor_def.errcheck = Cursor.from_result 2321 2322Cursor_eq = lib.clang_equalCursors 2323Cursor_eq.argtypes = [Cursor, Cursor] 2324Cursor_eq.restype = bool 2325 2326Cursor_hash = lib.clang_hashCursor 2327Cursor_hash.argtypes = [Cursor] 2328Cursor_hash.restype = c_uint 2329 2330Cursor_spelling = lib.clang_getCursorSpelling 2331Cursor_spelling.argtypes = [Cursor] 2332Cursor_spelling.restype = _CXString 2333Cursor_spelling.errcheck = _CXString.from_result 2334 2335Cursor_displayname = lib.clang_getCursorDisplayName 2336Cursor_displayname.argtypes = [Cursor] 2337Cursor_displayname.restype = _CXString 2338Cursor_displayname.errcheck = _CXString.from_result 2339 2340Cursor_loc = lib.clang_getCursorLocation 2341Cursor_loc.argtypes = [Cursor] 2342Cursor_loc.restype = SourceLocation 2343 2344Cursor_extent = lib.clang_getCursorExtent 2345Cursor_extent.argtypes = [Cursor] 2346Cursor_extent.restype = SourceRange 2347 2348Cursor_ref = lib.clang_getCursorReferenced 2349Cursor_ref.argtypes = [Cursor] 2350Cursor_ref.restype = Cursor 2351Cursor_ref.errcheck = Cursor.from_result 2352 2353Cursor_canonical = lib.clang_getCanonicalCursor 2354Cursor_canonical.argtypes = [Cursor] 2355Cursor_canonical.restype = Cursor 2356Cursor_canonical.errcheck = Cursor.from_result 2357 2358Cursor_type = lib.clang_getCursorType 2359Cursor_type.argtypes = [Cursor] 2360Cursor_type.restype = Type 2361Cursor_type.errcheck = Type.from_result 2362 2363Cursor_underlying_type = lib.clang_getTypedefDeclUnderlyingType 2364Cursor_underlying_type.argtypes = [Cursor] 2365Cursor_underlying_type.restype = Type 2366Cursor_underlying_type.errcheck = Type.from_result 2367 2368Cursor_enum_type = lib.clang_getEnumDeclIntegerType 2369Cursor_enum_type.argtypes = [Cursor] 2370Cursor_enum_type.restype = Type 2371Cursor_enum_type.errcheck = Type.from_result 2372 2373Cursor_enum_const_decl = lib.clang_getEnumConstantDeclValue 2374Cursor_enum_const_decl.argtypes = [Cursor] 2375Cursor_enum_const_decl.restype = c_longlong 2376 2377Cursor_enum_const_decl_unsigned = lib.clang_getEnumConstantDeclUnsignedValue 2378Cursor_enum_const_decl_unsigned.argtypes = [Cursor] 2379Cursor_enum_const_decl_unsigned.restype = c_ulonglong 2380 2381Cursor_objc_type_encoding = lib.clang_getDeclObjCTypeEncoding 2382Cursor_objc_type_encoding.argtypes = [Cursor] 2383Cursor_objc_type_encoding.restype = _CXString 2384Cursor_objc_type_encoding.errcheck = _CXString.from_result 2385 2386Cursor_semantic_parent = lib.clang_getCursorSemanticParent 2387Cursor_semantic_parent.argtypes = [Cursor] 2388Cursor_semantic_parent.restype = Cursor 2389Cursor_semantic_parent.errcheck = Cursor.from_result 2390 2391Cursor_lexical_parent = lib.clang_getCursorLexicalParent 2392Cursor_lexical_parent.argtypes = [Cursor] 2393Cursor_lexical_parent.restype = Cursor 2394Cursor_lexical_parent.errcheck = Cursor.from_result 2395 2396Cursor_visit_callback = CFUNCTYPE(c_int, Cursor, Cursor, py_object) 2397Cursor_visit = lib.clang_visitChildren 2398Cursor_visit.argtypes = [Cursor, Cursor_visit_callback, py_object] 2399Cursor_visit.restype = c_uint 2400 2401# Type Functions 2402Type_get_canonical = lib.clang_getCanonicalType 2403Type_get_canonical.argtypes = [Type] 2404Type_get_canonical.restype = Type 2405Type_get_canonical.errcheck = Type.from_result 2406 2407Type_is_const_qualified = lib.clang_isConstQualifiedType 2408Type_is_const_qualified.argtypes = [Type] 2409Type_is_const_qualified.restype = bool 2410 2411Type_is_volatile_qualified = lib.clang_isVolatileQualifiedType 2412Type_is_volatile_qualified.argtypes = [Type] 2413Type_is_volatile_qualified.restype = bool 2414 2415Type_is_restrict_qualified = lib.clang_isRestrictQualifiedType 2416Type_is_restrict_qualified.argtypes = [Type] 2417Type_is_restrict_qualified.restype = bool 2418 2419Type_is_pod = lib.clang_isPODType 2420Type_is_pod.argtypes = [Type] 2421Type_is_pod.restype = bool 2422 2423Type_is_variadic = lib.clang_isFunctionTypeVariadic 2424Type_is_variadic.argtypes = [Type] 2425Type_is_variadic.restype = bool 2426 2427Type_get_pointee = lib.clang_getPointeeType 2428Type_get_pointee.argtypes = [Type] 2429Type_get_pointee.restype = Type 2430Type_get_pointee.errcheck = Type.from_result 2431 2432Type_get_declaration = lib.clang_getTypeDeclaration 2433Type_get_declaration.argtypes = [Type] 2434Type_get_declaration.restype = Cursor 2435Type_get_declaration.errcheck = Cursor.from_result 2436 2437Type_get_result = lib.clang_getResultType 2438Type_get_result.argtypes = [Type] 2439Type_get_result.restype = Type 2440Type_get_result.errcheck = Type.from_result 2441 2442Type_get_num_arg_types = lib.clang_getNumArgTypes 2443Type_get_num_arg_types.argtypes = [Type] 2444Type_get_num_arg_types.restype = c_uint 2445 2446Type_get_arg_type = lib.clang_getArgType 2447Type_get_arg_type.argtypes = [Type, c_uint] 2448Type_get_arg_type.restype = Type 2449Type_get_arg_type.errcheck = Type.from_result 2450Type_get_element_type = lib.clang_getElementType 2451 2452Type_get_element_type.argtypes = [Type] 2453Type_get_element_type.restype = Type 2454Type_get_element_type.errcheck = Type.from_result 2455 2456Type_get_num_elements = lib.clang_getNumElements 2457Type_get_num_elements.argtypes = [Type] 2458Type_get_num_elements.restype = c_longlong 2459 2460Type_get_array_element = lib.clang_getArrayElementType 2461Type_get_array_element.argtypes = [Type] 2462Type_get_array_element.restype = Type 2463Type_get_array_element.errcheck = Type.from_result 2464 2465Type_get_array_size = lib.clang_getArraySize 2466Type_get_array_size.argtype = [Type] 2467Type_get_array_size.restype = c_longlong 2468 2469Type_equal = lib.clang_equalTypes 2470Type_equal.argtypes = [Type, Type] 2471Type_equal.restype = bool 2472 2473# Index Functions 2474Index_create = lib.clang_createIndex 2475Index_create.argtypes = [c_int, c_int] 2476Index_create.restype = c_object_p 2477 2478Index_dispose = lib.clang_disposeIndex 2479Index_dispose.argtypes = [Index] 2480 2481# Translation Unit Functions 2482TranslationUnit_read = lib.clang_createTranslationUnit 2483TranslationUnit_read.argtypes = [Index, c_char_p] 2484TranslationUnit_read.restype = c_object_p 2485 2486TranslationUnit_parse = lib.clang_parseTranslationUnit 2487TranslationUnit_parse.argtypes = [Index, c_char_p, c_void_p, 2488 c_int, c_void_p, c_int, c_int] 2489TranslationUnit_parse.restype = c_object_p 2490 2491TranslationUnit_reparse = lib.clang_reparseTranslationUnit 2492TranslationUnit_reparse.argtypes = [TranslationUnit, c_int, c_void_p, c_int] 2493TranslationUnit_reparse.restype = c_int 2494 2495TranslationUnit_codeComplete = lib.clang_codeCompleteAt 2496TranslationUnit_codeComplete.argtypes = [TranslationUnit, c_char_p, c_int, 2497 c_int, c_void_p, c_int, c_int] 2498TranslationUnit_codeComplete.restype = POINTER(CCRStructure) 2499 2500TranslationUnit_cursor = lib.clang_getTranslationUnitCursor 2501TranslationUnit_cursor.argtypes = [TranslationUnit] 2502TranslationUnit_cursor.restype = Cursor 2503TranslationUnit_cursor.errcheck = Cursor.from_result 2504 2505TranslationUnit_spelling = lib.clang_getTranslationUnitSpelling 2506TranslationUnit_spelling.argtypes = [TranslationUnit] 2507TranslationUnit_spelling.restype = _CXString 2508TranslationUnit_spelling.errcheck = _CXString.from_result 2509 2510TranslationUnit_dispose = lib.clang_disposeTranslationUnit 2511TranslationUnit_dispose.argtypes = [TranslationUnit] 2512 2513TranslationUnit_includes_callback = CFUNCTYPE(None, 2514 c_object_p, 2515 POINTER(SourceLocation), 2516 c_uint, py_object) 2517TranslationUnit_includes = lib.clang_getInclusions 2518TranslationUnit_includes.argtypes = [TranslationUnit, 2519 TranslationUnit_includes_callback, 2520 py_object] 2521 2522TranslationUnit_defaultSaveOptions = lib.clang_defaultSaveOptions 2523TranslationUnit_defaultSaveOptions.argtypes = [TranslationUnit] 2524TranslationUnit_defaultSaveOptions.restype = c_uint 2525 2526TranslationUnit_save = lib.clang_saveTranslationUnit 2527TranslationUnit_save.argtypes = [TranslationUnit, c_char_p, c_uint] 2528TranslationUnit_save.restype = c_int 2529 2530# File Functions 2531File_getFile = lib.clang_getFile 2532File_getFile.argtypes = [TranslationUnit, c_char_p] 2533File_getFile.restype = c_object_p 2534 2535File_name = lib.clang_getFileName 2536File_name.argtypes = [File] 2537File_name.restype = _CXString 2538 2539File_time = lib.clang_getFileTime 2540File_time.argtypes = [File] 2541File_time.restype = c_uint 2542 2543# Code completion 2544 2545CodeCompletionResults_dispose = lib.clang_disposeCodeCompleteResults 2546CodeCompletionResults_dispose.argtypes = [CodeCompletionResults] 2547 2548_clang_codeCompleteGetNumDiagnostics = lib.clang_codeCompleteGetNumDiagnostics 2549_clang_codeCompleteGetNumDiagnostics.argtypes = [CodeCompletionResults] 2550_clang_codeCompleteGetNumDiagnostics.restype = c_int 2551 2552_clang_codeCompleteGetDiagnostic = lib.clang_codeCompleteGetDiagnostic 2553_clang_codeCompleteGetDiagnostic.argtypes = [CodeCompletionResults, c_int] 2554_clang_codeCompleteGetDiagnostic.restype = Diagnostic 2555 2556_clang_getCompletionChunkText = lib.clang_getCompletionChunkText 2557_clang_getCompletionChunkText.argtypes = [c_void_p, c_int] 2558_clang_getCompletionChunkText.restype = _CXString 2559 2560_clang_getCompletionChunkKind = lib.clang_getCompletionChunkKind 2561_clang_getCompletionChunkKind.argtypes = [c_void_p, c_int] 2562_clang_getCompletionChunkKind.restype = c_int 2563 2564_clang_getCompletionChunkCompletionString = lib.clang_getCompletionChunkCompletionString 2565_clang_getCompletionChunkCompletionString.argtypes = [c_void_p, c_int] 2566_clang_getCompletionChunkCompletionString.restype = c_object_p 2567 2568_clang_getNumCompletionChunks = lib.clang_getNumCompletionChunks 2569_clang_getNumCompletionChunks.argtypes = [c_void_p] 2570_clang_getNumCompletionChunks.restype = c_int 2571 2572_clang_getCompletionAvailability = lib.clang_getCompletionAvailability 2573_clang_getCompletionAvailability.argtypes = [c_void_p] 2574_clang_getCompletionAvailability.restype = c_int 2575 2576_clang_getCompletionPriority = lib.clang_getCompletionPriority 2577_clang_getCompletionPriority.argtypes = [c_void_p] 2578_clang_getCompletionPriority.restype = c_int 2579 2580# Compilation Database 2581CompilationDatabase_fromDirectory = lib.clang_tooling_CompilationDatabase_fromDirectory 2582CompilationDatabase_fromDirectory.argtypes = [c_char_p, POINTER(c_uint)] 2583CompilationDatabase_fromDirectory.restype = c_object_p 2584CompilationDatabase_fromDirectory.errcheck = CompilationDatabase.from_result 2585 2586CompilationDatabase_dispose = lib.clang_tooling_CompilationDatabase_dispose 2587CompilationDatabase_dispose.argtypes = [c_object_p] 2588 2589CompilationDatabase_getCompileCommands = lib.clang_tooling_CompilationDatabase_getCompileCommands 2590CompilationDatabase_getCompileCommands.argtypes = [c_object_p, c_char_p] 2591CompilationDatabase_getCompileCommands.restype = c_object_p 2592CompilationDatabase_getCompileCommands.errcheck = CompileCommands.from_result 2593 2594CompileCommands_dispose = lib.clang_tooling_CompileCommands_dispose 2595CompileCommands_dispose.argtypes = [c_object_p] 2596 2597CompileCommands_getSize = lib.clang_tooling_CompileCommands_getSize 2598CompileCommands_getSize.argtypes = [c_object_p] 2599CompileCommands_getSize.restype = c_uint 2600 2601CompileCommands_getCommand = lib.clang_tooling_CompileCommands_getCommand 2602CompileCommands_getCommand.argtypes = [c_object_p, c_uint] 2603CompileCommands_getCommand.restype = c_object_p 2604 2605CompileCommand_getDirectory = lib.clang_tooling_CompileCommand_getDirectory 2606CompileCommand_getDirectory.argtypes = [c_object_p] 2607CompileCommand_getDirectory.restype = _CXString 2608 2609CompileCommand_getNumArgs = lib.clang_tooling_CompileCommand_getNumArgs 2610CompileCommand_getNumArgs.argtypes = [c_object_p] 2611CompileCommand_getNumArgs.restype = c_uint 2612 2613CompileCommand_getArg = lib.clang_tooling_CompileCommand_getArg 2614CompileCommand_getArg.argtypes = [c_object_p, c_uint] 2615CompileCommand_getArg.restype = _CXString 2616 2617__all__ = [ 2618 'CodeCompletionResults', 2619 'CompilationDatabase', 2620 'CompileCommands', 2621 'CompileCommand', 2622 'CursorKind', 2623 'Cursor', 2624 'Diagnostic', 2625 'File', 2626 'FixIt', 2627 'Index', 2628 'SourceLocation', 2629 'SourceRange', 2630 'TranslationUnitLoadError', 2631 'TranslationUnit', 2632 'TypeKind', 2633 'Type', 2634] 2635