cindex.py revision 2283b4664b004aae034b08f305ad2bc1dff9868e
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 underlying_typedef_type(self): 1028 """Return the underlying type of a typedef declaration. 1029 1030 Returns a Type for the typedef this cursor is a declaration for. If 1031 the current cursor is not a typedef, this raises. 1032 """ 1033 if not hasattr(self, '_underlying_type'): 1034 assert self.kind.is_declaration() 1035 self._underlying_type = Cursor_underlying_type(self) 1036 1037 return self._underlying_type 1038 1039 @property 1040 def enum_type(self): 1041 """Return the integer type of an enum declaration. 1042 1043 Returns a Type corresponding to an integer. If the cursor is not for an 1044 enum, this raises. 1045 """ 1046 if not hasattr(self, '_enum_type'): 1047 assert self.kind == CursorKind.ENUM_DECL 1048 self._enum_type = Cursor_enum_type(self) 1049 1050 return self._enum_type 1051 1052 @property 1053 def enum_value(self): 1054 """Return the value of an enum constant.""" 1055 if not hasattr(self, '_enum_value'): 1056 assert self.kind == CursorKind.ENUM_CONSTANT_DECL 1057 # Figure out the underlying type of the enum to know if it 1058 # is a signed or unsigned quantity. 1059 underlying_type = self.type 1060 if underlying_type.kind == TypeKind.ENUM: 1061 underlying_type = underlying_type.get_declaration().enum_type 1062 if underlying_type.kind in (TypeKind.CHAR_U, 1063 TypeKind.UCHAR, 1064 TypeKind.CHAR16, 1065 TypeKind.CHAR32, 1066 TypeKind.USHORT, 1067 TypeKind.UINT, 1068 TypeKind.ULONG, 1069 TypeKind.ULONGLONG, 1070 TypeKind.UINT128): 1071 self._enum_value = Cursor_enum_const_decl_unsigned(self) 1072 else: 1073 self._enum_value = Cursor_enum_const_decl(self) 1074 return self._enum_value 1075 1076 @property 1077 def objc_type_encoding(self): 1078 """Return the Objective-C type encoding as a str.""" 1079 if not hasattr(self, '_objc_type_encoding'): 1080 self._objc_type_encoding = Cursor_objc_type_encoding(self) 1081 1082 return self._objc_type_encoding 1083 1084 @property 1085 def hash(self): 1086 """Returns a hash of the cursor as an int.""" 1087 if not hasattr(self, '_hash'): 1088 self._hash = Cursor_hash(self) 1089 1090 return self._hash 1091 1092 @property 1093 def semantic_parent(self): 1094 """Return the semantic parent for this cursor.""" 1095 if not hasattr(self, '_semantic_parent'): 1096 self._semantic_parent = Cursor_semantic_parent(self) 1097 1098 return self._semantic_parent 1099 1100 @property 1101 def lexical_parent(self): 1102 """Return the lexical parent for this cursor.""" 1103 if not hasattr(self, '_lexical_parent'): 1104 self._lexical_parent = Cursor_lexical_parent(self) 1105 1106 return self._lexical_parent 1107 1108 def get_children(self): 1109 """Return an iterator for accessing the children of this cursor.""" 1110 1111 # FIXME: Expose iteration from CIndex, PR6125. 1112 def visitor(child, parent, children): 1113 # FIXME: Document this assertion in API. 1114 # FIXME: There should just be an isNull method. 1115 assert child != Cursor_null() 1116 children.append(child) 1117 return 1 # continue 1118 children = [] 1119 Cursor_visit(self, Cursor_visit_callback(visitor), children) 1120 return iter(children) 1121 1122 @staticmethod 1123 def from_result(res, fn, args): 1124 assert isinstance(res, Cursor) 1125 # FIXME: There should just be an isNull method. 1126 if res == Cursor_null(): 1127 return None 1128 return res 1129 1130 1131### Type Kinds ### 1132 1133class TypeKind(object): 1134 """ 1135 Describes the kind of type. 1136 """ 1137 1138 # The unique kind objects, indexed by id. 1139 _kinds = [] 1140 _name_map = None 1141 1142 def __init__(self, value): 1143 if value >= len(TypeKind._kinds): 1144 TypeKind._kinds += [None] * (value - len(TypeKind._kinds) + 1) 1145 if TypeKind._kinds[value] is not None: 1146 raise ValueError,'TypeKind already loaded' 1147 self.value = value 1148 TypeKind._kinds[value] = self 1149 TypeKind._name_map = None 1150 1151 def from_param(self): 1152 return self.value 1153 1154 @property 1155 def name(self): 1156 """Get the enumeration name of this cursor kind.""" 1157 if self._name_map is None: 1158 self._name_map = {} 1159 for key,value in TypeKind.__dict__.items(): 1160 if isinstance(value,TypeKind): 1161 self._name_map[value] = key 1162 return self._name_map[self] 1163 1164 @property 1165 def spelling(self): 1166 """Retrieve the spelling of this TypeKind.""" 1167 return TypeKind_spelling(self.value) 1168 1169 @staticmethod 1170 def from_id(id): 1171 if id >= len(TypeKind._kinds) or TypeKind._kinds[id] is None: 1172 raise ValueError,'Unknown type kind %d' % id 1173 return TypeKind._kinds[id] 1174 1175 def __repr__(self): 1176 return 'TypeKind.%s' % (self.name,) 1177 1178TypeKind_spelling = lib.clang_getTypeKindSpelling 1179TypeKind_spelling.argtypes = [c_uint] 1180TypeKind_spelling.restype = _CXString 1181TypeKind_spelling.errcheck = _CXString.from_result 1182 1183 1184TypeKind.INVALID = TypeKind(0) 1185TypeKind.UNEXPOSED = TypeKind(1) 1186TypeKind.VOID = TypeKind(2) 1187TypeKind.BOOL = TypeKind(3) 1188TypeKind.CHAR_U = TypeKind(4) 1189TypeKind.UCHAR = TypeKind(5) 1190TypeKind.CHAR16 = TypeKind(6) 1191TypeKind.CHAR32 = TypeKind(7) 1192TypeKind.USHORT = TypeKind(8) 1193TypeKind.UINT = TypeKind(9) 1194TypeKind.ULONG = TypeKind(10) 1195TypeKind.ULONGLONG = TypeKind(11) 1196TypeKind.UINT128 = TypeKind(12) 1197TypeKind.CHAR_S = TypeKind(13) 1198TypeKind.SCHAR = TypeKind(14) 1199TypeKind.WCHAR = TypeKind(15) 1200TypeKind.SHORT = TypeKind(16) 1201TypeKind.INT = TypeKind(17) 1202TypeKind.LONG = TypeKind(18) 1203TypeKind.LONGLONG = TypeKind(19) 1204TypeKind.INT128 = TypeKind(20) 1205TypeKind.FLOAT = TypeKind(21) 1206TypeKind.DOUBLE = TypeKind(22) 1207TypeKind.LONGDOUBLE = TypeKind(23) 1208TypeKind.NULLPTR = TypeKind(24) 1209TypeKind.OVERLOAD = TypeKind(25) 1210TypeKind.DEPENDENT = TypeKind(26) 1211TypeKind.OBJCID = TypeKind(27) 1212TypeKind.OBJCCLASS = TypeKind(28) 1213TypeKind.OBJCSEL = TypeKind(29) 1214TypeKind.COMPLEX = TypeKind(100) 1215TypeKind.POINTER = TypeKind(101) 1216TypeKind.BLOCKPOINTER = TypeKind(102) 1217TypeKind.LVALUEREFERENCE = TypeKind(103) 1218TypeKind.RVALUEREFERENCE = TypeKind(104) 1219TypeKind.RECORD = TypeKind(105) 1220TypeKind.ENUM = TypeKind(106) 1221TypeKind.TYPEDEF = TypeKind(107) 1222TypeKind.OBJCINTERFACE = TypeKind(108) 1223TypeKind.OBJCOBJECTPOINTER = TypeKind(109) 1224TypeKind.FUNCTIONNOPROTO = TypeKind(110) 1225TypeKind.FUNCTIONPROTO = TypeKind(111) 1226TypeKind.CONSTANTARRAY = TypeKind(112) 1227TypeKind.VECTOR = TypeKind(113) 1228 1229class Type(Structure): 1230 """ 1231 The type of an element in the abstract syntax tree. 1232 """ 1233 _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)] 1234 1235 @property 1236 def kind(self): 1237 """Return the kind of this type.""" 1238 return TypeKind.from_id(self._kind_id) 1239 1240 def argument_types(self): 1241 """Retrieve a container for the non-variadic arguments for this type. 1242 1243 The returned object is iterable and indexable. Each item in the 1244 container is a Type instance. 1245 """ 1246 class ArgumentsIterator(collections.Sequence): 1247 def __init__(self, parent): 1248 self.parent = parent 1249 self.length = None 1250 1251 def __len__(self): 1252 if self.length is None: 1253 self.length = Type_get_num_arg_types(self.parent) 1254 1255 return self.length 1256 1257 def __getitem__(self, key): 1258 # FIXME Support slice objects. 1259 if not isinstance(key, int): 1260 raise TypeError("Must supply a non-negative int.") 1261 1262 if key < 0: 1263 raise IndexError("Only non-negative indexes are accepted.") 1264 1265 if key >= len(self): 1266 raise IndexError("Index greater than container length: " 1267 "%d > %d" % ( key, len(self) )) 1268 1269 result = Type_get_arg_type(self.parent, key) 1270 if result.kind == TypeKind.INVALID: 1271 raise IndexError("Argument could not be retrieved.") 1272 1273 return result 1274 1275 assert self.kind == TypeKind.FUNCTIONPROTO 1276 return ArgumentsIterator(self) 1277 1278 @property 1279 def element_type(self): 1280 """Retrieve the Type of elements within this Type. 1281 1282 If accessed on a type that is not an array, complex, or vector type, an 1283 exception will be raised. 1284 """ 1285 result = Type_get_element_type(self) 1286 if result.kind == TypeKind.INVALID: 1287 raise Exception('Element type not available on this type.') 1288 1289 return result 1290 1291 @property 1292 def element_count(self): 1293 """Retrieve the number of elements in this type. 1294 1295 Returns an int. 1296 1297 If the Type is not an array or vector, this raises. 1298 """ 1299 result = Type_get_num_elements(self) 1300 if result < 0: 1301 raise Exception('Type does not have elements.') 1302 1303 return result 1304 1305 @staticmethod 1306 def from_result(res, fn, args): 1307 assert isinstance(res, Type) 1308 return res 1309 1310 def get_canonical(self): 1311 """ 1312 Return the canonical type for a Type. 1313 1314 Clang's type system explicitly models typedefs and all the 1315 ways a specific type can be represented. The canonical type 1316 is the underlying type with all the "sugar" removed. For 1317 example, if 'T' is a typedef for 'int', the canonical type for 1318 'T' would be 'int'. 1319 """ 1320 return Type_get_canonical(self) 1321 1322 def is_const_qualified(self): 1323 """Determine whether a Type has the "const" qualifier set. 1324 1325 This does not look through typedefs that may have added "const" 1326 at a different level. 1327 """ 1328 return Type_is_const_qualified(self) 1329 1330 def is_volatile_qualified(self): 1331 """Determine whether a Type has the "volatile" qualifier set. 1332 1333 This does not look through typedefs that may have added "volatile" 1334 at a different level. 1335 """ 1336 return Type_is_volatile_qualified(self) 1337 1338 def is_restrict_qualified(self): 1339 """Determine whether a Type has the "restrict" qualifier set. 1340 1341 This does not look through typedefs that may have added "restrict" at 1342 a different level. 1343 """ 1344 return Type_is_restrict_qualified(self) 1345 1346 def is_function_variadic(self): 1347 """Determine whether this function Type is a variadic function type.""" 1348 assert self.kind == TypeKind.FUNCTIONPROTO 1349 1350 return Type_is_variadic(self) 1351 1352 def is_pod(self): 1353 """Determine whether this Type represents plain old data (POD).""" 1354 return Type_is_pod(self) 1355 1356 def get_pointee(self): 1357 """ 1358 For pointer types, returns the type of the pointee. 1359 """ 1360 return Type_get_pointee(self) 1361 1362 def get_declaration(self): 1363 """ 1364 Return the cursor for the declaration of the given type. 1365 """ 1366 return Type_get_declaration(self) 1367 1368 def get_result(self): 1369 """ 1370 Retrieve the result type associated with a function type. 1371 """ 1372 return Type_get_result(self) 1373 1374 def get_array_element_type(self): 1375 """ 1376 Retrieve the type of the elements of the array type. 1377 """ 1378 return Type_get_array_element(self) 1379 1380 def get_array_size(self): 1381 """ 1382 Retrieve the size of the constant array. 1383 """ 1384 return Type_get_array_size(self) 1385 1386 def __eq__(self, other): 1387 if type(other) != type(self): 1388 return False 1389 1390 return Type_equal(self, other) 1391 1392 def __ne__(self, other): 1393 return not self.__eq__(other) 1394 1395## CIndex Objects ## 1396 1397# CIndex objects (derived from ClangObject) are essentially lightweight 1398# wrappers attached to some underlying object, which is exposed via CIndex as 1399# a void*. 1400 1401class ClangObject(object): 1402 """ 1403 A helper for Clang objects. This class helps act as an intermediary for 1404 the ctypes library and the Clang CIndex library. 1405 """ 1406 def __init__(self, obj): 1407 assert isinstance(obj, c_object_p) and obj 1408 self.obj = self._as_parameter_ = obj 1409 1410 def from_param(self): 1411 return self._as_parameter_ 1412 1413 1414class _CXUnsavedFile(Structure): 1415 """Helper for passing unsaved file arguments.""" 1416 _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)] 1417 1418## Diagnostic Conversion ## 1419 1420_clang_getNumDiagnostics = lib.clang_getNumDiagnostics 1421_clang_getNumDiagnostics.argtypes = [c_object_p] 1422_clang_getNumDiagnostics.restype = c_uint 1423 1424_clang_getDiagnostic = lib.clang_getDiagnostic 1425_clang_getDiagnostic.argtypes = [c_object_p, c_uint] 1426_clang_getDiagnostic.restype = c_object_p 1427 1428_clang_disposeDiagnostic = lib.clang_disposeDiagnostic 1429_clang_disposeDiagnostic.argtypes = [Diagnostic] 1430 1431_clang_getDiagnosticSeverity = lib.clang_getDiagnosticSeverity 1432_clang_getDiagnosticSeverity.argtypes = [Diagnostic] 1433_clang_getDiagnosticSeverity.restype = c_int 1434 1435_clang_getDiagnosticLocation = lib.clang_getDiagnosticLocation 1436_clang_getDiagnosticLocation.argtypes = [Diagnostic] 1437_clang_getDiagnosticLocation.restype = SourceLocation 1438 1439_clang_getDiagnosticSpelling = lib.clang_getDiagnosticSpelling 1440_clang_getDiagnosticSpelling.argtypes = [Diagnostic] 1441_clang_getDiagnosticSpelling.restype = _CXString 1442_clang_getDiagnosticSpelling.errcheck = _CXString.from_result 1443 1444_clang_getDiagnosticNumRanges = lib.clang_getDiagnosticNumRanges 1445_clang_getDiagnosticNumRanges.argtypes = [Diagnostic] 1446_clang_getDiagnosticNumRanges.restype = c_uint 1447 1448_clang_getDiagnosticRange = lib.clang_getDiagnosticRange 1449_clang_getDiagnosticRange.argtypes = [Diagnostic, c_uint] 1450_clang_getDiagnosticRange.restype = SourceRange 1451 1452_clang_getDiagnosticNumFixIts = lib.clang_getDiagnosticNumFixIts 1453_clang_getDiagnosticNumFixIts.argtypes = [Diagnostic] 1454_clang_getDiagnosticNumFixIts.restype = c_uint 1455 1456_clang_getDiagnosticFixIt = lib.clang_getDiagnosticFixIt 1457_clang_getDiagnosticFixIt.argtypes = [Diagnostic, c_uint, POINTER(SourceRange)] 1458_clang_getDiagnosticFixIt.restype = _CXString 1459_clang_getDiagnosticFixIt.errcheck = _CXString.from_result 1460 1461_clang_getDiagnosticCategory = lib.clang_getDiagnosticCategory 1462_clang_getDiagnosticCategory.argtypes = [Diagnostic] 1463_clang_getDiagnosticCategory.restype = c_uint 1464 1465_clang_getDiagnosticCategoryName = lib.clang_getDiagnosticCategoryName 1466_clang_getDiagnosticCategoryName.argtypes = [c_uint] 1467_clang_getDiagnosticCategoryName.restype = _CXString 1468_clang_getDiagnosticCategoryName.errcheck = _CXString.from_result 1469 1470_clang_getDiagnosticOption = lib.clang_getDiagnosticOption 1471_clang_getDiagnosticOption.argtypes = [Diagnostic, POINTER(_CXString)] 1472_clang_getDiagnosticOption.restype = _CXString 1473_clang_getDiagnosticOption.errcheck = _CXString.from_result 1474 1475### 1476 1477class CompletionChunk: 1478 class Kind: 1479 def __init__(self, name): 1480 self.name = name 1481 1482 def __str__(self): 1483 return self.name 1484 1485 def __repr__(self): 1486 return "<ChunkKind: %s>" % self 1487 1488 def __init__(self, completionString, key): 1489 self.cs = completionString 1490 self.key = key 1491 1492 def __repr__(self): 1493 return "{'" + self.spelling + "', " + str(self.kind) + "}" 1494 1495 @property 1496 def spelling(self): 1497 return _clang_getCompletionChunkText(self.cs, self.key).spelling 1498 1499 @property 1500 def kind(self): 1501 res = _clang_getCompletionChunkKind(self.cs, self.key) 1502 return completionChunkKindMap[res] 1503 1504 @property 1505 def string(self): 1506 res = _clang_getCompletionChunkCompletionString(self.cs, self.key) 1507 1508 if (res): 1509 return CompletionString(res) 1510 else: 1511 None 1512 1513 def isKindOptional(self): 1514 return self.kind == completionChunkKindMap[0] 1515 1516 def isKindTypedText(self): 1517 return self.kind == completionChunkKindMap[1] 1518 1519 def isKindPlaceHolder(self): 1520 return self.kind == completionChunkKindMap[3] 1521 1522 def isKindInformative(self): 1523 return self.kind == completionChunkKindMap[4] 1524 1525 def isKindResultType(self): 1526 return self.kind == completionChunkKindMap[15] 1527 1528completionChunkKindMap = { 1529 0: CompletionChunk.Kind("Optional"), 1530 1: CompletionChunk.Kind("TypedText"), 1531 2: CompletionChunk.Kind("Text"), 1532 3: CompletionChunk.Kind("Placeholder"), 1533 4: CompletionChunk.Kind("Informative"), 1534 5: CompletionChunk.Kind("CurrentParameter"), 1535 6: CompletionChunk.Kind("LeftParen"), 1536 7: CompletionChunk.Kind("RightParen"), 1537 8: CompletionChunk.Kind("LeftBracket"), 1538 9: CompletionChunk.Kind("RightBracket"), 1539 10: CompletionChunk.Kind("LeftBrace"), 1540 11: CompletionChunk.Kind("RightBrace"), 1541 12: CompletionChunk.Kind("LeftAngle"), 1542 13: CompletionChunk.Kind("RightAngle"), 1543 14: CompletionChunk.Kind("Comma"), 1544 15: CompletionChunk.Kind("ResultType"), 1545 16: CompletionChunk.Kind("Colon"), 1546 17: CompletionChunk.Kind("SemiColon"), 1547 18: CompletionChunk.Kind("Equal"), 1548 19: CompletionChunk.Kind("HorizontalSpace"), 1549 20: CompletionChunk.Kind("VerticalSpace")} 1550 1551class CompletionString(ClangObject): 1552 class Availability: 1553 def __init__(self, name): 1554 self.name = name 1555 1556 def __str__(self): 1557 return self.name 1558 1559 def __repr__(self): 1560 return "<Availability: %s>" % self 1561 1562 def __len__(self): 1563 return _clang_getNumCompletionChunks(self.obj) 1564 1565 def __getitem__(self, key): 1566 if len(self) <= key: 1567 raise IndexError 1568 return CompletionChunk(self.obj, key) 1569 1570 @property 1571 def priority(self): 1572 return _clang_getCompletionPriority(self.obj) 1573 1574 @property 1575 def availability(self): 1576 res = _clang_getCompletionAvailability(self.obj) 1577 return availabilityKinds[res] 1578 1579 def __repr__(self): 1580 return " | ".join([str(a) for a in self]) \ 1581 + " || Priority: " + str(self.priority) \ 1582 + " || Availability: " + str(self.availability) 1583 1584availabilityKinds = { 1585 0: CompletionChunk.Kind("Available"), 1586 1: CompletionChunk.Kind("Deprecated"), 1587 2: CompletionChunk.Kind("NotAvailable")} 1588 1589class CodeCompletionResult(Structure): 1590 _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)] 1591 1592 def __repr__(self): 1593 return str(CompletionString(self.completionString)) 1594 1595 @property 1596 def kind(self): 1597 return CursorKind.from_id(self.cursorKind) 1598 1599 @property 1600 def string(self): 1601 return CompletionString(self.completionString) 1602 1603class CCRStructure(Structure): 1604 _fields_ = [('results', POINTER(CodeCompletionResult)), 1605 ('numResults', c_int)] 1606 1607 def __len__(self): 1608 return self.numResults 1609 1610 def __getitem__(self, key): 1611 if len(self) <= key: 1612 raise IndexError 1613 1614 return self.results[key] 1615 1616class CodeCompletionResults(ClangObject): 1617 def __init__(self, ptr): 1618 assert isinstance(ptr, POINTER(CCRStructure)) and ptr 1619 self.ptr = self._as_parameter_ = ptr 1620 1621 def from_param(self): 1622 return self._as_parameter_ 1623 1624 def __del__(self): 1625 CodeCompletionResults_dispose(self) 1626 1627 @property 1628 def results(self): 1629 return self.ptr.contents 1630 1631 @property 1632 def diagnostics(self): 1633 class DiagnosticsItr: 1634 def __init__(self, ccr): 1635 self.ccr= ccr 1636 1637 def __len__(self): 1638 return int(_clang_codeCompleteGetNumDiagnostics(self.ccr)) 1639 1640 def __getitem__(self, key): 1641 return _clang_codeCompleteGetDiagnostic(self.ccr, key) 1642 1643 return DiagnosticsItr(self) 1644 1645 1646class Index(ClangObject): 1647 """ 1648 The Index type provides the primary interface to the Clang CIndex library, 1649 primarily by providing an interface for reading and parsing translation 1650 units. 1651 """ 1652 1653 @staticmethod 1654 def create(excludeDecls=False): 1655 """ 1656 Create a new Index. 1657 Parameters: 1658 excludeDecls -- Exclude local declarations from translation units. 1659 """ 1660 return Index(Index_create(excludeDecls, 0)) 1661 1662 def __del__(self): 1663 Index_dispose(self) 1664 1665 def read(self, path): 1666 """Load a TranslationUnit from the given AST file.""" 1667 return TranslationUnit.from_ast(path, self) 1668 1669 def parse(self, path, args=None, unsaved_files=None, options = 0): 1670 """Load the translation unit from the given source code file by running 1671 clang and generating the AST before loading. Additional command line 1672 parameters can be passed to clang via the args parameter. 1673 1674 In-memory contents for files can be provided by passing a list of pairs 1675 to as unsaved_files, the first item should be the filenames to be mapped 1676 and the second should be the contents to be substituted for the 1677 file. The contents may be passed as strings or file objects. 1678 1679 If an error was encountered during parsing, a TranslationUnitLoadError 1680 will be raised. 1681 """ 1682 return TranslationUnit.from_source(path, args, unsaved_files, options, 1683 self) 1684 1685class TranslationUnit(ClangObject): 1686 """Represents a source code translation unit. 1687 1688 This is one of the main types in the API. Any time you wish to interact 1689 with Clang's representation of a source file, you typically start with a 1690 translation unit. 1691 """ 1692 1693 # Default parsing mode. 1694 PARSE_NONE = 0 1695 1696 # Instruct the parser to create a detailed processing record containing 1697 # metadata not normally retained. 1698 PARSE_DETAILED_PROCESSING_RECORD = 1 1699 1700 # Indicates that the translation unit is incomplete. This is typically used 1701 # when parsing headers. 1702 PARSE_INCOMPLETE = 2 1703 1704 # Instruct the parser to create a pre-compiled preamble for the translation 1705 # unit. This caches the preamble (included files at top of source file). 1706 # This is useful if the translation unit will be reparsed and you don't 1707 # want to incur the overhead of reparsing the preamble. 1708 PARSE_PRECOMPILED_PREAMBLE = 4 1709 1710 # Cache code completion information on parse. This adds time to parsing but 1711 # speeds up code completion. 1712 PARSE_CACHE_COMPLETION_RESULTS = 8 1713 1714 # Flags with values 16 and 32 are deprecated and intentionally omitted. 1715 1716 # Do not parse function bodies. This is useful if you only care about 1717 # searching for declarations/definitions. 1718 PARSE_SKIP_FUNCTION_BODIES = 64 1719 1720 @classmethod 1721 def from_source(cls, filename, args=None, unsaved_files=None, options=0, 1722 index=None): 1723 """Create a TranslationUnit by parsing source. 1724 1725 This is capable of processing source code both from files on the 1726 filesystem as well as in-memory contents. 1727 1728 Command-line arguments that would be passed to clang are specified as 1729 a list via args. These can be used to specify include paths, warnings, 1730 etc. e.g. ["-Wall", "-I/path/to/include"]. 1731 1732 In-memory file content can be provided via unsaved_files. This is an 1733 iterable of 2-tuples. The first element is the str filename. The 1734 second element defines the content. Content can be provided as str 1735 source code or as file objects (anything with a read() method). If 1736 a file object is being used, content will be read until EOF and the 1737 read cursor will not be reset to its original position. 1738 1739 options is a bitwise or of TranslationUnit.PARSE_XXX flags which will 1740 control parsing behavior. 1741 1742 index is an Index instance to utilize. If not provided, a new Index 1743 will be created for this TranslationUnit. 1744 1745 To parse source from the filesystem, the filename of the file to parse 1746 is specified by the filename argument. Or, filename could be None and 1747 the args list would contain the filename(s) to parse. 1748 1749 To parse source from an in-memory buffer, set filename to the virtual 1750 filename you wish to associate with this source (e.g. "test.c"). The 1751 contents of that file are then provided in unsaved_files. 1752 1753 If an error occurs, a TranslationUnitLoadError is raised. 1754 1755 Please note that a TranslationUnit with parser errors may be returned. 1756 It is the caller's responsibility to check tu.diagnostics for errors. 1757 1758 Also note that Clang infers the source language from the extension of 1759 the input filename. If you pass in source code containing a C++ class 1760 declaration with the filename "test.c" parsing will fail. 1761 """ 1762 if args is None: 1763 args = [] 1764 1765 if unsaved_files is None: 1766 unsaved_files = [] 1767 1768 if index is None: 1769 index = Index.create() 1770 1771 args_array = None 1772 if len(args) > 0: 1773 args_array = (c_char_p * len(args))(* args) 1774 1775 unsaved_array = None 1776 if len(unsaved_files) > 0: 1777 unsaved_array = (_CXUnsavedFile * len(unsaved_files))() 1778 for i, (name, contents) in enumerate(unsaved_files): 1779 if hasattr(contents, "read"): 1780 contents = contents.read() 1781 1782 unsaved_array[i].name = name 1783 unsaved_array[i].contents = contents 1784 unsaved_array[i].length = len(contents) 1785 1786 ptr = TranslationUnit_parse(index, filename, args_array, len(args), 1787 unsaved_array, len(unsaved_files), 1788 options) 1789 1790 if ptr is None: 1791 raise TranslationUnitLoadError("Error parsing translation unit.") 1792 1793 return cls(ptr, index=index) 1794 1795 @classmethod 1796 def from_ast_file(cls, filename, index=None): 1797 """Create a TranslationUnit instance from a saved AST file. 1798 1799 A previously-saved AST file (provided with -emit-ast or 1800 TranslationUnit.save()) is loaded from the filename specified. 1801 1802 If the file cannot be loaded, a TranslationUnitLoadError will be 1803 raised. 1804 1805 index is optional and is the Index instance to use. If not provided, 1806 a default Index will be created. 1807 """ 1808 if index is None: 1809 index = Index.create() 1810 1811 ptr = TranslationUnit_read(index, filename) 1812 if ptr is None: 1813 raise TranslationUnitLoadError(filename) 1814 1815 return cls(ptr=ptr, index=index) 1816 1817 def __init__(self, ptr, index): 1818 """Create a TranslationUnit instance. 1819 1820 TranslationUnits should be created using one of the from_* @classmethod 1821 functions above. __init__ is only called internally. 1822 """ 1823 assert isinstance(index, Index) 1824 1825 ClangObject.__init__(self, ptr) 1826 1827 def __del__(self): 1828 TranslationUnit_dispose(self) 1829 1830 @property 1831 def cursor(self): 1832 """Retrieve the cursor that represents the given translation unit.""" 1833 return TranslationUnit_cursor(self) 1834 1835 @property 1836 def spelling(self): 1837 """Get the original translation unit source file name.""" 1838 return TranslationUnit_spelling(self) 1839 1840 def get_includes(self): 1841 """ 1842 Return an iterable sequence of FileInclusion objects that describe the 1843 sequence of inclusions in a translation unit. The first object in 1844 this sequence is always the input file. Note that this method will not 1845 recursively iterate over header files included through precompiled 1846 headers. 1847 """ 1848 def visitor(fobj, lptr, depth, includes): 1849 if depth > 0: 1850 loc = lptr.contents 1851 includes.append(FileInclusion(loc.file, File(fobj), loc, depth)) 1852 1853 # Automatically adapt CIndex/ctype pointers to python objects 1854 includes = [] 1855 TranslationUnit_includes(self, 1856 TranslationUnit_includes_callback(visitor), 1857 includes) 1858 return iter(includes) 1859 1860 @property 1861 def diagnostics(self): 1862 """ 1863 Return an iterable (and indexable) object containing the diagnostics. 1864 """ 1865 class DiagIterator: 1866 def __init__(self, tu): 1867 self.tu = tu 1868 1869 def __len__(self): 1870 return int(_clang_getNumDiagnostics(self.tu)) 1871 1872 def __getitem__(self, key): 1873 diag = _clang_getDiagnostic(self.tu, key) 1874 if not diag: 1875 raise IndexError 1876 return Diagnostic(diag) 1877 1878 return DiagIterator(self) 1879 1880 def reparse(self, unsaved_files=None, options=0): 1881 """ 1882 Reparse an already parsed translation unit. 1883 1884 In-memory contents for files can be provided by passing a list of pairs 1885 as unsaved_files, the first items should be the filenames to be mapped 1886 and the second should be the contents to be substituted for the 1887 file. The contents may be passed as strings or file objects. 1888 """ 1889 if unsaved_files is None: 1890 unsaved_files = [] 1891 1892 unsaved_files_array = 0 1893 if len(unsaved_files): 1894 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() 1895 for i,(name,value) in enumerate(unsaved_files): 1896 if not isinstance(value, str): 1897 # FIXME: It would be great to support an efficient version 1898 # of this, one day. 1899 value = value.read() 1900 print value 1901 if not isinstance(value, str): 1902 raise TypeError,'Unexpected unsaved file contents.' 1903 unsaved_files_array[i].name = name 1904 unsaved_files_array[i].contents = value 1905 unsaved_files_array[i].length = len(value) 1906 ptr = TranslationUnit_reparse(self, len(unsaved_files), 1907 unsaved_files_array, 1908 options) 1909 1910 def save(self, filename): 1911 """Saves the TranslationUnit to a file. 1912 1913 This is equivalent to passing -emit-ast to the clang frontend. The 1914 saved file can be loaded back into a TranslationUnit. Or, if it 1915 corresponds to a header, it can be used as a pre-compiled header file. 1916 1917 If an error occurs while saving, a TranslationUnitSaveError is raised. 1918 If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means 1919 the constructed TranslationUnit was not valid at time of save. In this 1920 case, the reason(s) why should be available via 1921 TranslationUnit.diagnostics(). 1922 1923 filename -- The path to save the translation unit to. 1924 """ 1925 options = TranslationUnit_defaultSaveOptions(self) 1926 result = int(TranslationUnit_save(self, filename, options)) 1927 if result != 0: 1928 raise TranslationUnitSaveError(result, 1929 'Error saving TranslationUnit.') 1930 1931 def codeComplete(self, path, line, column, unsaved_files=None, options=0): 1932 """ 1933 Code complete in this translation unit. 1934 1935 In-memory contents for files can be provided by passing a list of pairs 1936 as unsaved_files, the first items should be the filenames to be mapped 1937 and the second should be the contents to be substituted for the 1938 file. The contents may be passed as strings or file objects. 1939 """ 1940 if unsaved_files is None: 1941 unsaved_files = [] 1942 1943 unsaved_files_array = 0 1944 if len(unsaved_files): 1945 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))() 1946 for i,(name,value) in enumerate(unsaved_files): 1947 if not isinstance(value, str): 1948 # FIXME: It would be great to support an efficient version 1949 # of this, one day. 1950 value = value.read() 1951 print value 1952 if not isinstance(value, str): 1953 raise TypeError,'Unexpected unsaved file contents.' 1954 unsaved_files_array[i].name = name 1955 unsaved_files_array[i].contents = value 1956 unsaved_files_array[i].length = len(value) 1957 ptr = TranslationUnit_codeComplete(self, path, 1958 line, column, 1959 unsaved_files_array, 1960 len(unsaved_files), 1961 options) 1962 if ptr: 1963 return CodeCompletionResults(ptr) 1964 return None 1965 1966class File(ClangObject): 1967 """ 1968 The File class represents a particular source file that is part of a 1969 translation unit. 1970 """ 1971 1972 @staticmethod 1973 def from_name(translation_unit, file_name): 1974 """Retrieve a file handle within the given translation unit.""" 1975 return File(File_getFile(translation_unit, file_name)) 1976 1977 @property 1978 def name(self): 1979 """Return the complete file and path name of the file.""" 1980 return _CXString_getCString(File_name(self)) 1981 1982 @property 1983 def time(self): 1984 """Return the last modification time of the file.""" 1985 return File_time(self) 1986 1987 def __str__(self): 1988 return self.name 1989 1990 def __repr__(self): 1991 return "<File: %s>" % (self.name) 1992 1993class FileInclusion(object): 1994 """ 1995 The FileInclusion class represents the inclusion of one source file by 1996 another via a '#include' directive or as the input file for the translation 1997 unit. This class provides information about the included file, the including 1998 file, the location of the '#include' directive and the depth of the included 1999 file in the stack. Note that the input file has depth 0. 2000 """ 2001 2002 def __init__(self, src, tgt, loc, depth): 2003 self.source = src 2004 self.include = tgt 2005 self.location = loc 2006 self.depth = depth 2007 2008 @property 2009 def is_input_file(self): 2010 """True if the included file is the input file.""" 2011 return self.depth == 0 2012 2013# Additional Functions and Types 2014 2015# String Functions 2016_CXString_dispose = lib.clang_disposeString 2017_CXString_dispose.argtypes = [_CXString] 2018 2019_CXString_getCString = lib.clang_getCString 2020_CXString_getCString.argtypes = [_CXString] 2021_CXString_getCString.restype = c_char_p 2022 2023# Source Location Functions 2024SourceLocation_loc = lib.clang_getInstantiationLocation 2025SourceLocation_loc.argtypes = [SourceLocation, POINTER(c_object_p), 2026 POINTER(c_uint), POINTER(c_uint), 2027 POINTER(c_uint)] 2028 2029SourceLocation_getLocation = lib.clang_getLocation 2030SourceLocation_getLocation.argtypes = [TranslationUnit, File, c_uint, c_uint] 2031SourceLocation_getLocation.restype = SourceLocation 2032 2033SourceLocation_equalLocations = lib.clang_equalLocations 2034SourceLocation_equalLocations.argtypes = [SourceLocation, SourceLocation] 2035SourceLocation_equalLocations.restype = bool 2036 2037# Source Range Functions 2038SourceRange_getRange = lib.clang_getRange 2039SourceRange_getRange.argtypes = [SourceLocation, SourceLocation] 2040SourceRange_getRange.restype = SourceRange 2041 2042SourceRange_start = lib.clang_getRangeStart 2043SourceRange_start.argtypes = [SourceRange] 2044SourceRange_start.restype = SourceLocation 2045 2046SourceRange_end = lib.clang_getRangeEnd 2047SourceRange_end.argtypes = [SourceRange] 2048SourceRange_end.restype = SourceLocation 2049 2050SourceRange_equalRanges = lib.clang_equalRanges 2051SourceRange_equalRanges.argtypes = [SourceRange, SourceRange] 2052SourceRange_equalRanges.restype = bool 2053 2054# CursorKind Functions 2055CursorKind_is_decl = lib.clang_isDeclaration 2056CursorKind_is_decl.argtypes = [CursorKind] 2057CursorKind_is_decl.restype = bool 2058 2059CursorKind_is_ref = lib.clang_isReference 2060CursorKind_is_ref.argtypes = [CursorKind] 2061CursorKind_is_ref.restype = bool 2062 2063CursorKind_is_expr = lib.clang_isExpression 2064CursorKind_is_expr.argtypes = [CursorKind] 2065CursorKind_is_expr.restype = bool 2066 2067CursorKind_is_stmt = lib.clang_isStatement 2068CursorKind_is_stmt.argtypes = [CursorKind] 2069CursorKind_is_stmt.restype = bool 2070 2071CursorKind_is_attribute = lib.clang_isAttribute 2072CursorKind_is_attribute.argtypes = [CursorKind] 2073CursorKind_is_attribute.restype = bool 2074 2075CursorKind_is_inv = lib.clang_isInvalid 2076CursorKind_is_inv.argtypes = [CursorKind] 2077CursorKind_is_inv.restype = bool 2078 2079CursorKind_is_translation_unit = lib.clang_isTranslationUnit 2080CursorKind_is_translation_unit.argtypes = [CursorKind] 2081CursorKind_is_translation_unit.restype = bool 2082 2083CursorKind_is_preprocessing = lib.clang_isPreprocessing 2084CursorKind_is_preprocessing.argtypes = [CursorKind] 2085CursorKind_is_preprocessing.restype = bool 2086 2087CursorKind_is_unexposed = lib.clang_isUnexposed 2088CursorKind_is_unexposed.argtypes = [CursorKind] 2089CursorKind_is_unexposed.restype = bool 2090 2091# Cursor Functions 2092# TODO: Implement this function 2093Cursor_get = lib.clang_getCursor 2094Cursor_get.argtypes = [TranslationUnit, SourceLocation] 2095Cursor_get.restype = Cursor 2096 2097Cursor_null = lib.clang_getNullCursor 2098Cursor_null.restype = Cursor 2099 2100Cursor_usr = lib.clang_getCursorUSR 2101Cursor_usr.argtypes = [Cursor] 2102Cursor_usr.restype = _CXString 2103Cursor_usr.errcheck = _CXString.from_result 2104 2105Cursor_is_def = lib.clang_isCursorDefinition 2106Cursor_is_def.argtypes = [Cursor] 2107Cursor_is_def.restype = bool 2108 2109Cursor_def = lib.clang_getCursorDefinition 2110Cursor_def.argtypes = [Cursor] 2111Cursor_def.restype = Cursor 2112Cursor_def.errcheck = Cursor.from_result 2113 2114Cursor_eq = lib.clang_equalCursors 2115Cursor_eq.argtypes = [Cursor, Cursor] 2116Cursor_eq.restype = bool 2117 2118Cursor_hash = lib.clang_hashCursor 2119Cursor_hash.argtypes = [Cursor] 2120Cursor_hash.restype = c_uint 2121 2122Cursor_spelling = lib.clang_getCursorSpelling 2123Cursor_spelling.argtypes = [Cursor] 2124Cursor_spelling.restype = _CXString 2125Cursor_spelling.errcheck = _CXString.from_result 2126 2127Cursor_displayname = lib.clang_getCursorDisplayName 2128Cursor_displayname.argtypes = [Cursor] 2129Cursor_displayname.restype = _CXString 2130Cursor_displayname.errcheck = _CXString.from_result 2131 2132Cursor_loc = lib.clang_getCursorLocation 2133Cursor_loc.argtypes = [Cursor] 2134Cursor_loc.restype = SourceLocation 2135 2136Cursor_extent = lib.clang_getCursorExtent 2137Cursor_extent.argtypes = [Cursor] 2138Cursor_extent.restype = SourceRange 2139 2140Cursor_ref = lib.clang_getCursorReferenced 2141Cursor_ref.argtypes = [Cursor] 2142Cursor_ref.restype = Cursor 2143Cursor_ref.errcheck = Cursor.from_result 2144 2145Cursor_type = lib.clang_getCursorType 2146Cursor_type.argtypes = [Cursor] 2147Cursor_type.restype = Type 2148Cursor_type.errcheck = Type.from_result 2149 2150Cursor_underlying_type = lib.clang_getTypedefDeclUnderlyingType 2151Cursor_underlying_type.argtypes = [Cursor] 2152Cursor_underlying_type.restype = Type 2153Cursor_underlying_type.errcheck = Type.from_result 2154 2155Cursor_enum_type = lib.clang_getEnumDeclIntegerType 2156Cursor_enum_type.argtypes = [Cursor] 2157Cursor_enum_type.restype = Type 2158Cursor_enum_type.errcheck = Type.from_result 2159 2160Cursor_enum_const_decl = lib.clang_getEnumConstantDeclValue 2161Cursor_enum_const_decl.argtypes = [Cursor] 2162Cursor_enum_const_decl.restype = c_longlong 2163 2164Cursor_enum_const_decl_unsigned = lib.clang_getEnumConstantDeclUnsignedValue 2165Cursor_enum_const_decl_unsigned.argtypes = [Cursor] 2166Cursor_enum_const_decl_unsigned.restype = c_ulonglong 2167 2168Cursor_objc_type_encoding = lib.clang_getDeclObjCTypeEncoding 2169Cursor_objc_type_encoding.argtypes = [Cursor] 2170Cursor_objc_type_encoding.restype = _CXString 2171Cursor_objc_type_encoding.errcheck = _CXString.from_result 2172 2173Cursor_semantic_parent = lib.clang_getCursorSemanticParent 2174Cursor_semantic_parent.argtypes = [Cursor] 2175Cursor_semantic_parent.restype = Cursor 2176Cursor_semantic_parent.errcheck = Cursor.from_result 2177 2178Cursor_lexical_parent = lib.clang_getCursorLexicalParent 2179Cursor_lexical_parent.argtypes = [Cursor] 2180Cursor_lexical_parent.restype = Cursor 2181Cursor_lexical_parent.errcheck = Cursor.from_result 2182 2183Cursor_visit_callback = CFUNCTYPE(c_int, Cursor, Cursor, py_object) 2184Cursor_visit = lib.clang_visitChildren 2185Cursor_visit.argtypes = [Cursor, Cursor_visit_callback, py_object] 2186Cursor_visit.restype = c_uint 2187 2188# Type Functions 2189Type_get_canonical = lib.clang_getCanonicalType 2190Type_get_canonical.argtypes = [Type] 2191Type_get_canonical.restype = Type 2192Type_get_canonical.errcheck = Type.from_result 2193 2194Type_is_const_qualified = lib.clang_isConstQualifiedType 2195Type_is_const_qualified.argtypes = [Type] 2196Type_is_const_qualified.restype = bool 2197 2198Type_is_volatile_qualified = lib.clang_isVolatileQualifiedType 2199Type_is_volatile_qualified.argtypes = [Type] 2200Type_is_volatile_qualified.restype = bool 2201 2202Type_is_restrict_qualified = lib.clang_isRestrictQualifiedType 2203Type_is_restrict_qualified.argtypes = [Type] 2204Type_is_restrict_qualified.restype = bool 2205 2206Type_is_pod = lib.clang_isPODType 2207Type_is_pod.argtypes = [Type] 2208Type_is_pod.restype = bool 2209 2210Type_is_variadic = lib.clang_isFunctionTypeVariadic 2211Type_is_variadic.argtypes = [Type] 2212Type_is_variadic.restype = bool 2213 2214Type_get_pointee = lib.clang_getPointeeType 2215Type_get_pointee.argtypes = [Type] 2216Type_get_pointee.restype = Type 2217Type_get_pointee.errcheck = Type.from_result 2218 2219Type_get_declaration = lib.clang_getTypeDeclaration 2220Type_get_declaration.argtypes = [Type] 2221Type_get_declaration.restype = Cursor 2222Type_get_declaration.errcheck = Cursor.from_result 2223 2224Type_get_result = lib.clang_getResultType 2225Type_get_result.argtypes = [Type] 2226Type_get_result.restype = Type 2227Type_get_result.errcheck = Type.from_result 2228 2229Type_get_num_arg_types = lib.clang_getNumArgTypes 2230Type_get_num_arg_types.argtypes = [Type] 2231Type_get_num_arg_types.restype = c_uint 2232 2233Type_get_arg_type = lib.clang_getArgType 2234Type_get_arg_type.argtypes = [Type, c_uint] 2235Type_get_arg_type.restype = Type 2236Type_get_arg_type.errcheck = Type.from_result 2237Type_get_element_type = lib.clang_getElementType 2238 2239Type_get_element_type.argtypes = [Type] 2240Type_get_element_type.restype = Type 2241Type_get_element_type.errcheck = Type.from_result 2242 2243Type_get_num_elements = lib.clang_getNumElements 2244Type_get_num_elements.argtypes = [Type] 2245Type_get_num_elements.restype = c_longlong 2246 2247Type_get_array_element = lib.clang_getArrayElementType 2248Type_get_array_element.argtypes = [Type] 2249Type_get_array_element.restype = Type 2250Type_get_array_element.errcheck = Type.from_result 2251 2252Type_get_array_size = lib.clang_getArraySize 2253Type_get_array_size.argtype = [Type] 2254Type_get_array_size.restype = c_longlong 2255 2256Type_equal = lib.clang_equalTypes 2257Type_equal.argtypes = [Type, Type] 2258Type_equal.restype = bool 2259 2260# Index Functions 2261Index_create = lib.clang_createIndex 2262Index_create.argtypes = [c_int, c_int] 2263Index_create.restype = c_object_p 2264 2265Index_dispose = lib.clang_disposeIndex 2266Index_dispose.argtypes = [Index] 2267 2268# Translation Unit Functions 2269TranslationUnit_read = lib.clang_createTranslationUnit 2270TranslationUnit_read.argtypes = [Index, c_char_p] 2271TranslationUnit_read.restype = c_object_p 2272 2273TranslationUnit_parse = lib.clang_parseTranslationUnit 2274TranslationUnit_parse.argtypes = [Index, c_char_p, c_void_p, 2275 c_int, c_void_p, c_int, c_int] 2276TranslationUnit_parse.restype = c_object_p 2277 2278TranslationUnit_reparse = lib.clang_reparseTranslationUnit 2279TranslationUnit_reparse.argtypes = [TranslationUnit, c_int, c_void_p, c_int] 2280TranslationUnit_reparse.restype = c_int 2281 2282TranslationUnit_codeComplete = lib.clang_codeCompleteAt 2283TranslationUnit_codeComplete.argtypes = [TranslationUnit, c_char_p, c_int, 2284 c_int, c_void_p, c_int, c_int] 2285TranslationUnit_codeComplete.restype = POINTER(CCRStructure) 2286 2287TranslationUnit_cursor = lib.clang_getTranslationUnitCursor 2288TranslationUnit_cursor.argtypes = [TranslationUnit] 2289TranslationUnit_cursor.restype = Cursor 2290TranslationUnit_cursor.errcheck = Cursor.from_result 2291 2292TranslationUnit_spelling = lib.clang_getTranslationUnitSpelling 2293TranslationUnit_spelling.argtypes = [TranslationUnit] 2294TranslationUnit_spelling.restype = _CXString 2295TranslationUnit_spelling.errcheck = _CXString.from_result 2296 2297TranslationUnit_dispose = lib.clang_disposeTranslationUnit 2298TranslationUnit_dispose.argtypes = [TranslationUnit] 2299 2300TranslationUnit_includes_callback = CFUNCTYPE(None, 2301 c_object_p, 2302 POINTER(SourceLocation), 2303 c_uint, py_object) 2304TranslationUnit_includes = lib.clang_getInclusions 2305TranslationUnit_includes.argtypes = [TranslationUnit, 2306 TranslationUnit_includes_callback, 2307 py_object] 2308 2309TranslationUnit_defaultSaveOptions = lib.clang_defaultSaveOptions 2310TranslationUnit_defaultSaveOptions.argtypes = [TranslationUnit] 2311TranslationUnit_defaultSaveOptions.restype = c_uint 2312 2313TranslationUnit_save = lib.clang_saveTranslationUnit 2314TranslationUnit_save.argtypes = [TranslationUnit, c_char_p, c_uint] 2315TranslationUnit_save.restype = c_int 2316 2317# File Functions 2318File_getFile = lib.clang_getFile 2319File_getFile.argtypes = [TranslationUnit, c_char_p] 2320File_getFile.restype = c_object_p 2321 2322File_name = lib.clang_getFileName 2323File_name.argtypes = [File] 2324File_name.restype = _CXString 2325 2326File_time = lib.clang_getFileTime 2327File_time.argtypes = [File] 2328File_time.restype = c_uint 2329 2330# Code completion 2331 2332CodeCompletionResults_dispose = lib.clang_disposeCodeCompleteResults 2333CodeCompletionResults_dispose.argtypes = [CodeCompletionResults] 2334 2335_clang_codeCompleteGetNumDiagnostics = lib.clang_codeCompleteGetNumDiagnostics 2336_clang_codeCompleteGetNumDiagnostics.argtypes = [CodeCompletionResults] 2337_clang_codeCompleteGetNumDiagnostics.restype = c_int 2338 2339_clang_codeCompleteGetDiagnostic = lib.clang_codeCompleteGetDiagnostic 2340_clang_codeCompleteGetDiagnostic.argtypes = [CodeCompletionResults, c_int] 2341_clang_codeCompleteGetDiagnostic.restype = Diagnostic 2342 2343_clang_getCompletionChunkText = lib.clang_getCompletionChunkText 2344_clang_getCompletionChunkText.argtypes = [c_void_p, c_int] 2345_clang_getCompletionChunkText.restype = _CXString 2346 2347_clang_getCompletionChunkKind = lib.clang_getCompletionChunkKind 2348_clang_getCompletionChunkKind.argtypes = [c_void_p, c_int] 2349_clang_getCompletionChunkKind.restype = c_int 2350 2351_clang_getCompletionChunkCompletionString = lib.clang_getCompletionChunkCompletionString 2352_clang_getCompletionChunkCompletionString.argtypes = [c_void_p, c_int] 2353_clang_getCompletionChunkCompletionString.restype = c_object_p 2354 2355_clang_getNumCompletionChunks = lib.clang_getNumCompletionChunks 2356_clang_getNumCompletionChunks.argtypes = [c_void_p] 2357_clang_getNumCompletionChunks.restype = c_int 2358 2359_clang_getCompletionAvailability = lib.clang_getCompletionAvailability 2360_clang_getCompletionAvailability.argtypes = [c_void_p] 2361_clang_getCompletionAvailability.restype = c_int 2362 2363_clang_getCompletionPriority = lib.clang_getCompletionPriority 2364_clang_getCompletionPriority.argtypes = [c_void_p] 2365_clang_getCompletionPriority.restype = c_int 2366 2367 2368__all__ = [ 2369 'CodeCompletionResults', 2370 'CursorKind', 2371 'Cursor', 2372 'Diagnostic', 2373 'File', 2374 'FixIt', 2375 'Index', 2376 'SourceLocation', 2377 'SourceRange', 2378 'TranslationUnitLoadError', 2379 'TranslationUnit', 2380 'TypeKind', 2381 'Type', 2382] 2383