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