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