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