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