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