1 #===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===#
3 # The LLVM Compiler Infrastructure
5 # This file is distributed under the University of Illinois Open Source
6 # License. See LICENSE.TXT for details.
8 #===------------------------------------------------------------------------===#
11 Clang Indexing Library Bindings
12 ===============================
14 This module provides an interface to the Clang indexing library. It is a
15 low-level interface to the indexing library which attempts to match the Clang
16 API directly while also being "pythonic". Notable differences from the C API
19 * string results are returned as Python strings, not CXString objects.
21 * null cursors are translated to None.
23 * access to child cursors is done via iteration, not visitation.
25 The major indexing objects are:
29 The top-level object which manages some global library state.
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.
38 Generic object for representing a node in the AST.
40 SourceRange, SourceLocation, and File
42 Objects representing information about the input source.
44 Most object information is exposed using properties, when the underlying API
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.
55 # o fix memory management issues (currently client must hold on to index and
56 # translation unit, or risk crashes).
58 # o expose code completion APIs.
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)).
63 # o implement additional SourceLocation, SourceRange, and File methods.
68 import clang.enumerations
70 # ctypes doesn't implicitly convert c_void_p to the appropriate wrapper
71 # object. This is a problem, because it means that from_parameter will see an
72 # integer and pass the wrong value on platforms where int != void*. Work around
73 # this by marshalling object arguments as void**.
74 c_object_p = POINTER(c_void_p)
78 ### Exception Classes ###
80 class TranslationUnitLoadError(Exception):
81 """Represents an error that occurred when loading a TranslationUnit.
83 This is raised in the case where a TranslationUnit could not be
84 instantiated due to failure in the libclang library.
86 FIXME: Make libclang expose additional error information in this scenario.
90 class TranslationUnitSaveError(Exception):
91 """Represents an error that occurred when saving a TranslationUnit.
93 Each error has associated with it an enumerated value, accessible under
94 e.save_error. Consumers can compare the value with one of the ERROR_
95 constants in this class.
98 # Indicates that an unknown error occurred. This typically indicates that
99 # I/O failed during save.
102 # Indicates that errors during translation prevented saving. The errors
103 # should be available via the TranslationUnit's diagnostics.
104 ERROR_TRANSLATION_ERRORS = 2
106 # Indicates that the translation unit was somehow invalid.
109 def __init__(self, enumeration, message):
110 assert isinstance(enumeration, int)
112 if enumeration < 1 or enumeration > 3:
113 raise Exception("Encountered undefined TranslationUnit save error "
114 "constant: %d. Please file a bug to have this "
115 "value supported." % enumeration)
117 self.save_error = enumeration
118 Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
120 ### Structures and Utility Classes ###
122 class CachedProperty(object):
123 """Decorator that lazy-loads the value of a property.
125 The first time the property is accessed, the original property function is
126 executed. The value it returns is set as the new value of that instance's
127 property, replacing the original method.
130 def __init__(self, wrapped):
131 self.wrapped = wrapped
133 self.__doc__ = wrapped.__doc__
137 def __get__(self, instance, instance_type=None):
141 value = self.wrapped(instance)
142 setattr(instance, self.wrapped.__name__, value)
147 class _CXString(Structure):
148 """Helper for transforming CXString results."""
150 _fields_ = [("spelling", c_char_p), ("free", c_int)]
153 conf.lib.clang_disposeString(self)
156 def from_result(res, fn, args):
157 assert isinstance(res, _CXString)
158 return conf.lib.clang_getCString(res)
160 class SourceLocation(Structure):
162 A SourceLocation represents a particular location within a source file.
164 _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)]
167 def _get_instantiation(self):
168 if self._data is None:
169 f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint()
170 conf.lib.clang_getInstantiationLocation(self, byref(f), byref(l),
176 self._data = (f, int(l.value), int(c.value), int(o.value))
180 def from_position(tu, file, line, column):
182 Retrieve the source location associated with a given file/line/column in
183 a particular translation unit.
185 return conf.lib.clang_getLocation(tu, file, line, column)
188 def from_offset(tu, file, offset):
189 """Retrieve a SourceLocation from a given character offset.
191 tu -- TranslationUnit file belongs to
192 file -- File instance to obtain offset from
193 offset -- Integer character offset within file
195 return conf.lib.clang_getLocationForOffset(tu, file, offset)
199 """Get the file represented by this source location."""
200 return self._get_instantiation()[0]
204 """Get the line represented by this source location."""
205 return self._get_instantiation()[1]
209 """Get the column represented by this source location."""
210 return self._get_instantiation()[2]
214 """Get the file offset represented by this source location."""
215 return self._get_instantiation()[3]
217 def __eq__(self, other):
218 return conf.lib.clang_equalLocations(self, other)
220 def __ne__(self, other):
221 return not self.__eq__(other)
225 filename = self.file.name
228 return "<SourceLocation file %r, line %r, column %r>" % (
229 filename, self.line, self.column)
231 class SourceRange(Structure):
233 A SourceRange describes a range of source locations within the source
237 ("ptr_data", c_void_p * 2),
238 ("begin_int_data", c_uint),
239 ("end_int_data", c_uint)]
241 # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes
244 def from_locations(start, end):
245 return conf.lib.clang_getRange(start, end)
250 Return a SourceLocation representing the first character within a
253 return conf.lib.clang_getRangeStart(self)
258 Return a SourceLocation representing the last character within a
261 return conf.lib.clang_getRangeEnd(self)
263 def __eq__(self, other):
264 return conf.lib.clang_equalRanges(self, other)
266 def __ne__(self, other):
267 return not self.__eq__(other)
269 def __contains__(self, other):
270 """Useful to detect the Token/Lexer bug"""
271 if not isinstance(other, SourceLocation):
273 if other.file is None and self.start.file is None:
275 elif ( self.start.file.name != other.file.name or
276 other.file.name != self.end.file.name):
279 # same file, in between lines
280 if self.start.line < other.line < self.end.line:
282 elif self.start.line == other.line:
283 # same file first line
284 if self.start.column <= other.column:
286 elif other.line == self.end.line:
287 # same file last line
288 if other.column <= self.end.column:
293 return "<SourceRange start %r, end %r>" % (self.start, self.end)
295 class Diagnostic(object):
297 A Diagnostic is a single instance of a Clang diagnostic. It includes the
298 diagnostic severity, the message, the location the diagnostic occurred, as
299 well as additional source ranges and associated fix-it hints.
308 def __init__(self, ptr):
312 conf.lib.clang_disposeDiagnostic(self)
316 return conf.lib.clang_getDiagnosticSeverity(self)
320 return conf.lib.clang_getDiagnosticLocation(self)
324 return conf.lib.clang_getDiagnosticSpelling(self)
329 def __init__(self, diag):
333 return int(conf.lib.clang_getDiagnosticNumRanges(self.diag))
335 def __getitem__(self, key):
336 if (key >= len(self)):
338 return conf.lib.clang_getDiagnosticRange(self.diag, key)
340 return RangeIterator(self)
345 def __init__(self, diag):
349 return int(conf.lib.clang_getDiagnosticNumFixIts(self.diag))
351 def __getitem__(self, key):
352 range = SourceRange()
353 value = conf.lib.clang_getDiagnosticFixIt(self.diag, key,
358 return FixIt(range, value)
360 return FixItIterator(self)
363 def category_number(self):
364 """The category number for this diagnostic or 0 if unavailable."""
365 return conf.lib.clang_getDiagnosticCategory(self)
368 def category_name(self):
369 """The string name of the category for this diagnostic."""
370 return conf.lib.clang_getDiagnosticCategoryText(self)
374 """The command-line option that enables this diagnostic."""
375 return conf.lib.clang_getDiagnosticOption(self, None)
378 def disable_option(self):
379 """The command-line option that disables this diagnostic."""
380 disable = _CXString()
381 conf.lib.clang_getDiagnosticOption(self, byref(disable))
383 return conf.lib.clang_getCString(disable)
386 return "<Diagnostic severity %r, location %r, spelling %r>" % (
387 self.severity, self.location, self.spelling)
389 def from_param(self):
394 A FixIt represents a transformation to be applied to the source to
395 "fix-it". The fix-it shouldbe applied by replacing the given source range
396 with the given value.
399 def __init__(self, range, value):
404 return "<FixIt range %r, value %r>" % (self.range, self.value)
406 class TokenGroup(object):
407 """Helper class to facilitate token management.
409 Tokens are allocated from libclang in chunks. They must be disposed of as a
412 One purpose of this class is for instances to represent groups of allocated
413 tokens. Each token in a group contains a reference back to an instance of
414 this class. When all tokens from a group are garbage collected, it allows
415 this class to be garbage collected. When this class is garbage collected,
416 it calls the libclang destructor which invalidates all tokens in the group.
418 You should not instantiate this class outside of this module.
420 def __init__(self, tu, memory, count):
422 self._memory = memory
426 conf.lib.clang_disposeTokens(self._tu, self._memory, self._count)
429 def get_tokens(tu, extent):
430 """Helper method to return all tokens in an extent.
432 This functionality is needed multiple places in this module. We define
433 it here because it seems like a logical place.
435 tokens_memory = POINTER(Token)()
436 tokens_count = c_uint()
438 conf.lib.clang_tokenize(tu, extent, byref(tokens_memory),
441 count = int(tokens_count.value)
443 # If we get no tokens, no memory was allocated. Be sure not to return
444 # anything and potentially call a destructor on nothing.
448 tokens_array = cast(tokens_memory, POINTER(Token * count)).contents
450 token_group = TokenGroup(tu, tokens_memory, tokens_count)
452 for i in xrange(0, count):
454 token.int_data = tokens_array[i].int_data
455 token.ptr_data = tokens_array[i].ptr_data
457 token._group = token_group
461 class TokenKind(object):
462 """Describes a specific type of a Token."""
464 _value_map = {} # int -> TokenKind
466 def __init__(self, value, name):
467 """Create a new TokenKind instance from a numeric value and a name."""
472 return 'TokenKind.%s' % (self.name,)
475 def from_value(value):
476 """Obtain a registered TokenKind instance from its value."""
477 result = TokenKind._value_map.get(value, None)
480 raise ValueError('Unknown TokenKind: %d' % value)
485 def register(value, name):
486 """Register a new TokenKind enumeration.
488 This should only be called at module load time by code within this
491 if value in TokenKind._value_map:
492 raise ValueError('TokenKind already registered: %d' % value)
494 kind = TokenKind(value, name)
495 TokenKind._value_map[value] = kind
496 setattr(TokenKind, name, kind)
499 class BaseEnumeration(object):
501 Common base class for named enumerations held in sync with Index.h values.
503 Subclasses must define their own _kinds and _name_map members, as:
506 These values hold the per-subclass instances and value-to-name mappings,
511 def __init__(self, value):
512 if value >= len(self.__class__._kinds):
513 self.__class__._kinds += [None] * (value - len(self.__class__._kinds) + 1)
514 if self.__class__._kinds[value] is not None:
515 raise ValueError,'{0} value {1} already loaded'.format(
516 str(self.__class__), value)
518 self.__class__._kinds[value] = self
519 self.__class__._name_map = None
522 def from_param(self):
527 """Get the enumeration name of this cursor kind."""
528 if self._name_map is None:
530 for key, value in self.__class__.__dict__.items():
531 if isinstance(value, self.__class__):
532 self._name_map[value] = key
533 return self._name_map[self]
536 def from_id(cls, id):
537 if id >= len(cls._kinds) or cls._kinds[id] is None:
538 raise ValueError,'Unknown template argument kind %d' % id
539 return cls._kinds[id]
542 return '%s.%s' % (self.__class__, self.name,)
545 class CursorKind(BaseEnumeration):
547 A CursorKind describes the kind of entity that a cursor points to.
550 # The required BaseEnumeration declarations.
556 """Return all CursorKind enumeration instances."""
557 return filter(None, CursorKind._kinds)
559 def is_declaration(self):
560 """Test if this is a declaration kind."""
561 return conf.lib.clang_isDeclaration(self)
563 def is_reference(self):
564 """Test if this is a reference kind."""
565 return conf.lib.clang_isReference(self)
567 def is_expression(self):
568 """Test if this is an expression kind."""
569 return conf.lib.clang_isExpression(self)
571 def is_statement(self):
572 """Test if this is a statement kind."""
573 return conf.lib.clang_isStatement(self)
575 def is_attribute(self):
576 """Test if this is an attribute kind."""
577 return conf.lib.clang_isAttribute(self)
579 def is_invalid(self):
580 """Test if this is an invalid kind."""
581 return conf.lib.clang_isInvalid(self)
583 def is_translation_unit(self):
584 """Test if this is a translation unit kind."""
585 return conf.lib.clang_isTranslationUnit(self)
587 def is_preprocessing(self):
588 """Test if this is a preprocessing kind."""
589 return conf.lib.clang_isPreprocessing(self)
591 def is_unexposed(self):
592 """Test if this is an unexposed kind."""
593 return conf.lib.clang_isUnexposed(self)
596 return 'CursorKind.%s' % (self.name,)
601 # A declaration whose specific kind is not exposed via this interface.
603 # Unexposed declarations have the same operations as any other kind of
604 # declaration; one can extract their location information, spelling, find their
605 # definitions, etc. However, the specific kind of the declaration is not
607 CursorKind.UNEXPOSED_DECL = CursorKind(1)
610 CursorKind.STRUCT_DECL = CursorKind(2)
613 CursorKind.UNION_DECL = CursorKind(3)
616 CursorKind.CLASS_DECL = CursorKind(4)
619 CursorKind.ENUM_DECL = CursorKind(5)
621 # A field (in C) or non-static data member (in C++) in a struct, union, or C++
623 CursorKind.FIELD_DECL = CursorKind(6)
625 # An enumerator constant.
626 CursorKind.ENUM_CONSTANT_DECL = CursorKind(7)
629 CursorKind.FUNCTION_DECL = CursorKind(8)
632 CursorKind.VAR_DECL = CursorKind(9)
634 # A function or method parameter.
635 CursorKind.PARM_DECL = CursorKind(10)
637 # An Objective-C @interface.
638 CursorKind.OBJC_INTERFACE_DECL = CursorKind(11)
640 # An Objective-C @interface for a category.
641 CursorKind.OBJC_CATEGORY_DECL = CursorKind(12)
643 # An Objective-C @protocol declaration.
644 CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13)
646 # An Objective-C @property declaration.
647 CursorKind.OBJC_PROPERTY_DECL = CursorKind(14)
649 # An Objective-C instance variable.
650 CursorKind.OBJC_IVAR_DECL = CursorKind(15)
652 # An Objective-C instance method.
653 CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16)
655 # An Objective-C class method.
656 CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17)
658 # An Objective-C @implementation.
659 CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18)
661 # An Objective-C @implementation for a category.
662 CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19)
665 CursorKind.TYPEDEF_DECL = CursorKind(20)
667 # A C++ class method.
668 CursorKind.CXX_METHOD = CursorKind(21)
671 CursorKind.NAMESPACE = CursorKind(22)
673 # A linkage specification, e.g. 'extern "C"'.
674 CursorKind.LINKAGE_SPEC = CursorKind(23)
677 CursorKind.CONSTRUCTOR = CursorKind(24)
680 CursorKind.DESTRUCTOR = CursorKind(25)
682 # A C++ conversion function.
683 CursorKind.CONVERSION_FUNCTION = CursorKind(26)
685 # A C++ template type parameter
686 CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27)
688 # A C++ non-type template paramater.
689 CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28)
691 # A C++ template template parameter.
692 CursorKind.TEMPLATE_TEMPLATE_PARAMETER = CursorKind(29)
694 # A C++ function template.
695 CursorKind.FUNCTION_TEMPLATE = CursorKind(30)
697 # A C++ class template.
698 CursorKind.CLASS_TEMPLATE = CursorKind(31)
700 # A C++ class template partial specialization.
701 CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32)
703 # A C++ namespace alias declaration.
704 CursorKind.NAMESPACE_ALIAS = CursorKind(33)
706 # A C++ using directive
707 CursorKind.USING_DIRECTIVE = CursorKind(34)
709 # A C++ using declaration
710 CursorKind.USING_DECLARATION = CursorKind(35)
713 CursorKind.TYPE_ALIAS_DECL = CursorKind(36)
715 # A Objective-C synthesize decl
716 CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37)
718 # A Objective-C dynamic decl
719 CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38)
721 # A C++ access specifier decl.
722 CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39)
728 CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40)
729 CursorKind.OBJC_PROTOCOL_REF = CursorKind(41)
730 CursorKind.OBJC_CLASS_REF = CursorKind(42)
732 # A reference to a type declaration.
734 # A type reference occurs anywhere where a type is named but not
735 # declared. For example, given:
736 # typedef unsigned size_type;
739 # The typedef is a declaration of size_type (CXCursor_TypedefDecl),
740 # while the type of the variable "size" is referenced. The cursor
741 # referenced by the type of size is the typedef for size_type.
742 CursorKind.TYPE_REF = CursorKind(43)
743 CursorKind.CXX_BASE_SPECIFIER = CursorKind(44)
745 # A reference to a class template, function template, template
746 # template parameter, or class template partial specialization.
747 CursorKind.TEMPLATE_REF = CursorKind(45)
749 # A reference to a namespace or namepsace alias.
750 CursorKind.NAMESPACE_REF = CursorKind(46)
752 # A reference to a member of a struct, union, or class that occurs in
753 # some non-expression context, e.g., a designated initializer.
754 CursorKind.MEMBER_REF = CursorKind(47)
756 # A reference to a labeled statement.
757 CursorKind.LABEL_REF = CursorKind(48)
759 # A reference to a set of overloaded functions or function templates
760 # that has not yet been resolved to a specific function or function template.
761 CursorKind.OVERLOADED_DECL_REF = CursorKind(49)
763 # A reference to a variable that occurs in some non-expression
764 # context, e.g., a C++ lambda capture list.
765 CursorKind.VARIABLE_REF = CursorKind(50)
768 # Invalid/Error Kinds
770 CursorKind.INVALID_FILE = CursorKind(70)
771 CursorKind.NO_DECL_FOUND = CursorKind(71)
772 CursorKind.NOT_IMPLEMENTED = CursorKind(72)
773 CursorKind.INVALID_CODE = CursorKind(73)
778 # An expression whose specific kind is not exposed via this interface.
780 # Unexposed expressions have the same operations as any other kind of
781 # expression; one can extract their location information, spelling, children,
782 # etc. However, the specific kind of the expression is not reported.
783 CursorKind.UNEXPOSED_EXPR = CursorKind(100)
785 # An expression that refers to some value declaration, such as a function,
786 # varible, or enumerator.
787 CursorKind.DECL_REF_EXPR = CursorKind(101)
789 # An expression that refers to a member of a struct, union, class, Objective-C
791 CursorKind.MEMBER_REF_EXPR = CursorKind(102)
793 # An expression that calls a function.
794 CursorKind.CALL_EXPR = CursorKind(103)
796 # An expression that sends a message to an Objective-C object or class.
797 CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104)
799 # An expression that represents a block literal.
800 CursorKind.BLOCK_EXPR = CursorKind(105)
802 # An integer literal.
803 CursorKind.INTEGER_LITERAL = CursorKind(106)
805 # A floating point number literal.
806 CursorKind.FLOATING_LITERAL = CursorKind(107)
808 # An imaginary number literal.
809 CursorKind.IMAGINARY_LITERAL = CursorKind(108)
812 CursorKind.STRING_LITERAL = CursorKind(109)
814 # A character literal.
815 CursorKind.CHARACTER_LITERAL = CursorKind(110)
817 # A parenthesized expression, e.g. "(1)".
819 # This AST node is only formed if full location information is requested.
820 CursorKind.PAREN_EXPR = CursorKind(111)
822 # This represents the unary-expression's (except sizeof and
824 CursorKind.UNARY_OPERATOR = CursorKind(112)
826 # [C99 6.5.2.1] Array Subscripting.
827 CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113)
829 # A builtin binary operation expression such as "x + y" or
831 CursorKind.BINARY_OPERATOR = CursorKind(114)
833 # Compound assignment such as "+=".
834 CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115)
836 # The ?: ternary operator.
837 CursorKind.CONDITIONAL_OPERATOR = CursorKind(116)
839 # An explicit cast in C (C99 6.5.4) or a C-style cast in C++
840 # (C++ [expr.cast]), which uses the syntax (Type)expr.
842 # For example: (int)f.
843 CursorKind.CSTYLE_CAST_EXPR = CursorKind(117)
846 CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118)
848 # Describes an C or C++ initializer list.
849 CursorKind.INIT_LIST_EXPR = CursorKind(119)
851 # The GNU address of label extension, representing &&label.
852 CursorKind.ADDR_LABEL_EXPR = CursorKind(120)
854 # This is the GNU Statement Expression extension: ({int X=4; X;})
855 CursorKind.StmtExpr = CursorKind(121)
857 # Represents a C11 generic selection.
858 CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122)
860 # Implements the GNU __null extension, which is a name for a null
861 # pointer constant that has integral type (e.g., int or long) and is the same
862 # size and alignment as a pointer.
864 # The __null extension is typically only used by system headers, which define
865 # NULL as __null in C++ rather than using 0 (which is an integer that may not
866 # match the size of a pointer).
867 CursorKind.GNU_NULL_EXPR = CursorKind(123)
869 # C++'s static_cast<> expression.
870 CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124)
872 # C++'s dynamic_cast<> expression.
873 CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125)
875 # C++'s reinterpret_cast<> expression.
876 CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126)
878 # C++'s const_cast<> expression.
879 CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127)
881 # Represents an explicit C++ type conversion that uses "functional"
882 # notion (C++ [expr.type.conv]).
888 CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128)
890 # A C++ typeid expression (C++ [expr.typeid]).
891 CursorKind.CXX_TYPEID_EXPR = CursorKind(129)
893 # [C++ 2.13.5] C++ Boolean Literal.
894 CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130)
896 # [C++0x 2.14.7] C++ Pointer Literal.
897 CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131)
899 # Represents the "this" expression in C++
900 CursorKind.CXX_THIS_EXPR = CursorKind(132)
902 # [C++ 15] C++ Throw Expression.
904 # This handles 'throw' and 'throw' assignment-expression. When
905 # assignment-expression isn't present, Op will be null.
906 CursorKind.CXX_THROW_EXPR = CursorKind(133)
908 # A new expression for memory allocation and constructor calls, e.g:
909 # "new CXXNewExpr(foo)".
910 CursorKind.CXX_NEW_EXPR = CursorKind(134)
912 # A delete expression for memory deallocation and destructor calls,
913 # e.g. "delete[] pArray".
914 CursorKind.CXX_DELETE_EXPR = CursorKind(135)
916 # Represents a unary expression.
917 CursorKind.CXX_UNARY_EXPR = CursorKind(136)
919 # ObjCStringLiteral, used for Objective-C string literals i.e. "foo".
920 CursorKind.OBJC_STRING_LITERAL = CursorKind(137)
922 # ObjCEncodeExpr, used for in Objective-C.
923 CursorKind.OBJC_ENCODE_EXPR = CursorKind(138)
925 # ObjCSelectorExpr used for in Objective-C.
926 CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139)
928 # Objective-C's protocol expression.
929 CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140)
931 # An Objective-C "bridged" cast expression, which casts between
932 # Objective-C pointers and C pointers, transferring ownership in the process.
935 # NSString *str = (__bridge_transfer NSString *)CFCreateString();
937 CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141)
939 # Represents a C++0x pack expansion that produces a sequence of
942 # A pack expansion expression contains a pattern (which itself is an
943 # expression) followed by an ellipsis. For example:
944 CursorKind.PACK_EXPANSION_EXPR = CursorKind(142)
946 # Represents an expression that computes the length of a parameter
948 CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143)
950 # Represents a C++ lambda expression that produces a local function
954 # void abssort(float *x, unsigned N) {
955 # std::sort(x, x + N,
956 # [](float a, float b) {
957 # return std::abs(a) < std::abs(b);
961 CursorKind.LAMBDA_EXPR = CursorKind(144)
963 # Objective-c Boolean Literal.
964 CursorKind.OBJ_BOOL_LITERAL_EXPR = CursorKind(145)
966 # Represents the "self" expression in a ObjC method.
967 CursorKind.OBJ_SELF_EXPR = CursorKind(146)
970 # A statement whose specific kind is not exposed via this interface.
972 # Unexposed statements have the same operations as any other kind of statement;
973 # one can extract their location information, spelling, children, etc. However,
974 # the specific kind of the statement is not reported.
975 CursorKind.UNEXPOSED_STMT = CursorKind(200)
977 # A labelled statement in a function.
978 CursorKind.LABEL_STMT = CursorKind(201)
980 # A compound statement
981 CursorKind.COMPOUND_STMT = CursorKind(202)
984 CursorKind.CASE_STMT = CursorKind(203)
986 # A default statement.
987 CursorKind.DEFAULT_STMT = CursorKind(204)
990 CursorKind.IF_STMT = CursorKind(205)
992 # A switch statement.
993 CursorKind.SWITCH_STMT = CursorKind(206)
996 CursorKind.WHILE_STMT = CursorKind(207)
999 CursorKind.DO_STMT = CursorKind(208)
1002 CursorKind.FOR_STMT = CursorKind(209)
1005 CursorKind.GOTO_STMT = CursorKind(210)
1007 # An indirect goto statement.
1008 CursorKind.INDIRECT_GOTO_STMT = CursorKind(211)
1010 # A continue statement.
1011 CursorKind.CONTINUE_STMT = CursorKind(212)
1013 # A break statement.
1014 CursorKind.BREAK_STMT = CursorKind(213)
1016 # A return statement.
1017 CursorKind.RETURN_STMT = CursorKind(214)
1019 # A GNU-style inline assembler statement.
1020 CursorKind.ASM_STMT = CursorKind(215)
1022 # Objective-C's overall @try-@catch-@finally statement.
1023 CursorKind.OBJC_AT_TRY_STMT = CursorKind(216)
1025 # Objective-C's @catch statement.
1026 CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217)
1028 # Objective-C's @finally statement.
1029 CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218)
1031 # Objective-C's @throw statement.
1032 CursorKind.OBJC_AT_THROW_STMT = CursorKind(219)
1034 # Objective-C's @synchronized statement.
1035 CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220)
1037 # Objective-C's autorealease pool statement.
1038 CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221)
1040 # Objective-C's for collection statement.
1041 CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222)
1043 # C++'s catch statement.
1044 CursorKind.CXX_CATCH_STMT = CursorKind(223)
1046 # C++'s try statement.
1047 CursorKind.CXX_TRY_STMT = CursorKind(224)
1049 # C++'s for (* : *) statement.
1050 CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225)
1052 # Windows Structured Exception Handling's try statement.
1053 CursorKind.SEH_TRY_STMT = CursorKind(226)
1055 # Windows Structured Exception Handling's except statement.
1056 CursorKind.SEH_EXCEPT_STMT = CursorKind(227)
1058 # Windows Structured Exception Handling's finally statement.
1059 CursorKind.SEH_FINALLY_STMT = CursorKind(228)
1061 # A MS inline assembly statement extension.
1062 CursorKind.MS_ASM_STMT = CursorKind(229)
1064 # The null statement.
1065 CursorKind.NULL_STMT = CursorKind(230)
1067 # Adaptor class for mixing declarations with statements and expressions.
1068 CursorKind.DECL_STMT = CursorKind(231)
1073 # Cursor that represents the translation unit itself.
1075 # The translation unit cursor exists primarily to act as the root cursor for
1076 # traversing the contents of a translation unit.
1077 CursorKind.TRANSLATION_UNIT = CursorKind(300)
1082 # An attribute whoe specific kind is note exposed via this interface
1083 CursorKind.UNEXPOSED_ATTR = CursorKind(400)
1085 CursorKind.IB_ACTION_ATTR = CursorKind(401)
1086 CursorKind.IB_OUTLET_ATTR = CursorKind(402)
1087 CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403)
1089 CursorKind.CXX_FINAL_ATTR = CursorKind(404)
1090 CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405)
1091 CursorKind.ANNOTATE_ATTR = CursorKind(406)
1092 CursorKind.ASM_LABEL_ATTR = CursorKind(407)
1093 CursorKind.PACKED_ATTR = CursorKind(408)
1094 CursorKind.PURE_ATTR = CursorKind(409)
1095 CursorKind.CONST_ATTR = CursorKind(410)
1096 CursorKind.NODUPLICATE_ATTR = CursorKind(411)
1097 CursorKind.CUDACONSTANT_ATTR = CursorKind(412)
1098 CursorKind.CUDADEVICE_ATTR = CursorKind(413)
1099 CursorKind.CUDAGLOBAL_ATTR = CursorKind(414)
1100 CursorKind.CUDAHOST_ATTR = CursorKind(415)
1101 CursorKind.CUDASHARED_ATTR = CursorKind(416)
1105 CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500)
1106 CursorKind.MACRO_DEFINITION = CursorKind(501)
1107 CursorKind.MACRO_INSTANTIATION = CursorKind(502)
1108 CursorKind.INCLUSION_DIRECTIVE = CursorKind(503)
1113 # A module import declaration.
1114 CursorKind.MODULE_IMPORT_DECL = CursorKind(600)
1117 ### Template Argument Kinds ###
1118 class TemplateArgumentKind(BaseEnumeration):
1120 A TemplateArgumentKind describes the kind of entity that a template argument
1124 # The required BaseEnumeration declarations.
1128 TemplateArgumentKind.NULL = TemplateArgumentKind(0)
1129 TemplateArgumentKind.TYPE = TemplateArgumentKind(1)
1130 TemplateArgumentKind.DECLARATION = TemplateArgumentKind(2)
1131 TemplateArgumentKind.NULLPTR = TemplateArgumentKind(3)
1132 TemplateArgumentKind.INTEGRAL = TemplateArgumentKind(4)
1136 class Cursor(Structure):
1138 The Cursor class represents a reference to an element within the AST. It
1139 acts as a kind of iterator.
1141 _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
1144 def from_location(tu, location):
1145 # We store a reference to the TU in the instance so the TU won't get
1146 # collected before the cursor.
1147 cursor = conf.lib.clang_getCursor(tu, location)
1152 def __eq__(self, other):
1153 return conf.lib.clang_equalCursors(self, other)
1155 def __ne__(self, other):
1156 return not self.__eq__(other)
1158 def is_definition(self):
1160 Returns true if the declaration pointed at by the cursor is also a
1161 definition of that entity.
1163 return conf.lib.clang_isCursorDefinition(self)
1165 def is_static_method(self):
1166 """Returns True if the cursor refers to a C++ member function or member
1167 function template that is declared 'static'.
1169 return conf.lib.clang_CXXMethod_isStatic(self)
1171 def get_definition(self):
1173 If the cursor is a reference to a declaration or a declaration of
1174 some entity, return a cursor that points to the definition of that
1177 # TODO: Should probably check that this is either a reference or
1178 # declaration prior to issuing the lookup.
1179 return conf.lib.clang_getCursorDefinition(self)
1182 """Return the Unified Symbol Resultion (USR) for the entity referenced
1183 by the given cursor (or None).
1185 A Unified Symbol Resolution (USR) is a string that identifies a
1186 particular entity (function, class, variable, etc.) within a
1187 program. USRs can be compared across translation units to determine,
1188 e.g., when references in one translation refer to an entity defined in
1189 another translation unit."""
1190 return conf.lib.clang_getCursorUSR(self)
1194 """Return the kind of this cursor."""
1195 return CursorKind.from_id(self._kind_id)
1199 """Return the spelling of the entity pointed at by the cursor."""
1200 if not hasattr(self, '_spelling'):
1201 self._spelling = conf.lib.clang_getCursorSpelling(self)
1203 return self._spelling
1206 def displayname(self):
1208 Return the display name for the entity referenced by this cursor.
1210 The display name contains extra information that helps identify the
1211 cursor, such as the parameters of a function or template or the
1212 arguments of a class template specialization.
1214 if not hasattr(self, '_displayname'):
1215 self._displayname = conf.lib.clang_getCursorDisplayName(self)
1217 return self._displayname
1220 def mangled_name(self):
1221 """Return the mangled name for the entity referenced by this cursor."""
1222 if not hasattr(self, '_mangled_name'):
1223 self._mangled_name = conf.lib.clang_Cursor_getMangling(self)
1225 return self._mangled_name
1230 Return the source location (the starting character) of the entity
1231 pointed at by the cursor.
1233 if not hasattr(self, '_loc'):
1234 self._loc = conf.lib.clang_getCursorLocation(self)
1241 Return the source range (the range of text) occupied by the entity
1242 pointed at by the cursor.
1244 if not hasattr(self, '_extent'):
1245 self._extent = conf.lib.clang_getCursorExtent(self)
1250 def storage_class(self):
1252 Retrieves the storage class (if any) of the entity pointed at by the
1255 if not hasattr(self, '_storage_class'):
1256 self._storage_class = conf.lib.clang_Cursor_getStorageClass(self)
1258 return StorageClass.from_id(self._storage_class)
1261 def access_specifier(self):
1263 Retrieves the access specifier (if any) of the entity pointed at by the
1266 if not hasattr(self, '_access_specifier'):
1267 self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self)
1269 return AccessSpecifier.from_id(self._access_specifier)
1274 Retrieve the Type (if any) of the entity pointed at by the cursor.
1276 if not hasattr(self, '_type'):
1277 self._type = conf.lib.clang_getCursorType(self)
1282 def canonical(self):
1283 """Return the canonical Cursor corresponding to this Cursor.
1285 The canonical cursor is the cursor which is representative for the
1286 underlying entity. For example, if you have multiple forward
1287 declarations for the same class, the canonical cursor for the forward
1288 declarations will be identical.
1290 if not hasattr(self, '_canonical'):
1291 self._canonical = conf.lib.clang_getCanonicalCursor(self)
1293 return self._canonical
1296 def result_type(self):
1297 """Retrieve the Type of the result for this Cursor."""
1298 if not hasattr(self, '_result_type'):
1299 self._result_type = conf.lib.clang_getResultType(self.type)
1301 return self._result_type
1304 def underlying_typedef_type(self):
1305 """Return the underlying type of a typedef declaration.
1307 Returns a Type for the typedef this cursor is a declaration for. If
1308 the current cursor is not a typedef, this raises.
1310 if not hasattr(self, '_underlying_type'):
1311 assert self.kind.is_declaration()
1312 self._underlying_type = \
1313 conf.lib.clang_getTypedefDeclUnderlyingType(self)
1315 return self._underlying_type
1318 def enum_type(self):
1319 """Return the integer type of an enum declaration.
1321 Returns a Type corresponding to an integer. If the cursor is not for an
1324 if not hasattr(self, '_enum_type'):
1325 assert self.kind == CursorKind.ENUM_DECL
1326 self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self)
1328 return self._enum_type
1331 def enum_value(self):
1332 """Return the value of an enum constant."""
1333 if not hasattr(self, '_enum_value'):
1334 assert self.kind == CursorKind.ENUM_CONSTANT_DECL
1335 # Figure out the underlying type of the enum to know if it
1336 # is a signed or unsigned quantity.
1337 underlying_type = self.type
1338 if underlying_type.kind == TypeKind.ENUM:
1339 underlying_type = underlying_type.get_declaration().enum_type
1340 if underlying_type.kind in (TypeKind.CHAR_U,
1349 self._enum_value = \
1350 conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
1352 self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self)
1353 return self._enum_value
1356 def objc_type_encoding(self):
1357 """Return the Objective-C type encoding as a str."""
1358 if not hasattr(self, '_objc_type_encoding'):
1359 self._objc_type_encoding = \
1360 conf.lib.clang_getDeclObjCTypeEncoding(self)
1362 return self._objc_type_encoding
1366 """Returns a hash of the cursor as an int."""
1367 if not hasattr(self, '_hash'):
1368 self._hash = conf.lib.clang_hashCursor(self)
1373 def semantic_parent(self):
1374 """Return the semantic parent for this cursor."""
1375 if not hasattr(self, '_semantic_parent'):
1376 self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self)
1378 return self._semantic_parent
1381 def lexical_parent(self):
1382 """Return the lexical parent for this cursor."""
1383 if not hasattr(self, '_lexical_parent'):
1384 self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self)
1386 return self._lexical_parent
1389 def translation_unit(self):
1390 """Returns the TranslationUnit to which this Cursor belongs."""
1391 # If this triggers an AttributeError, the instance was not properly
1396 def referenced(self):
1398 For a cursor that is a reference, returns a cursor
1399 representing the entity that it references.
1401 if not hasattr(self, '_referenced'):
1402 self._referenced = conf.lib.clang_getCursorReferenced(self)
1404 return self._referenced
1407 def brief_comment(self):
1408 """Returns the brief comment text associated with that Cursor"""
1409 return conf.lib.clang_Cursor_getBriefCommentText(self)
1412 def raw_comment(self):
1413 """Returns the raw comment text associated with that Cursor"""
1414 return conf.lib.clang_Cursor_getRawCommentText(self)
1416 def get_arguments(self):
1417 """Return an iterator for accessing the arguments of this cursor."""
1418 num_args = conf.lib.clang_Cursor_getNumArguments(self)
1419 for i in range(0, num_args):
1420 yield conf.lib.clang_Cursor_getArgument(self, i)
1422 def get_num_template_arguments(self):
1423 """Returns the number of template args associated with this cursor."""
1424 return conf.lib.clang_Cursor_getNumTemplateArguments(self)
1426 def get_template_argument_kind(self, num):
1427 """Returns the TemplateArgumentKind for the indicated template
1429 return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num)
1431 def get_template_argument_type(self, num):
1432 """Returns the CXType for the indicated template argument."""
1433 return conf.lib.clang_Cursor_getTemplateArgumentType(self, num)
1435 def get_template_argument_value(self, num):
1436 """Returns the value of the indicated arg as a signed 64b integer."""
1437 return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num)
1439 def get_template_argument_unsigned_value(self, num):
1440 """Returns the value of the indicated arg as an unsigned 64b integer."""
1441 return conf.lib.clang_Cursor_getTemplateArgumentUnsignedValue(self, num)
1443 def get_children(self):
1444 """Return an iterator for accessing the children of this cursor."""
1446 # FIXME: Expose iteration from CIndex, PR6125.
1447 def visitor(child, parent, children):
1448 # FIXME: Document this assertion in API.
1449 # FIXME: There should just be an isNull method.
1450 assert child != conf.lib.clang_getNullCursor()
1452 # Create reference to TU so it isn't GC'd before Cursor.
1453 child._tu = self._tu
1454 children.append(child)
1457 conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
1459 return iter(children)
1461 def walk_preorder(self):
1462 """Depth-first preorder walk over the cursor and its descendants.
1467 for child in self.get_children():
1468 for descendant in child.walk_preorder():
1471 def get_tokens(self):
1472 """Obtain Token instances formulating that compose this Cursor.
1474 This is a generator for Token instances. It returns all tokens which
1475 occupy the extent this cursor occupies.
1477 return TokenGroup.get_tokens(self._tu, self.extent)
1479 def get_field_offsetof(self):
1480 """Returns the offsetof the FIELD_DECL pointed by this Cursor."""
1481 return conf.lib.clang_Cursor_getOffsetOfField(self)
1483 def is_anonymous(self):
1485 Check if the record is anonymous.
1487 if self.kind == CursorKind.FIELD_DECL:
1488 return self.type.get_declaration().is_anonymous()
1489 return conf.lib.clang_Cursor_isAnonymous(self)
1491 def is_bitfield(self):
1493 Check if the field is a bitfield.
1495 return conf.lib.clang_Cursor_isBitField(self)
1497 def get_bitfield_width(self):
1499 Retrieve the width of a bitfield.
1501 return conf.lib.clang_getFieldDeclBitWidth(self)
1504 def from_result(res, fn, args):
1505 assert isinstance(res, Cursor)
1506 # FIXME: There should just be an isNull method.
1507 if res == conf.lib.clang_getNullCursor():
1510 # Store a reference to the TU in the Python object so it won't get GC'd
1511 # before the Cursor.
1514 if isinstance(arg, TranslationUnit):
1518 if hasattr(arg, 'translation_unit'):
1519 tu = arg.translation_unit
1522 assert tu is not None
1528 def from_cursor_result(res, fn, args):
1529 assert isinstance(res, Cursor)
1530 if res == conf.lib.clang_getNullCursor():
1533 res._tu = args[0]._tu
1536 class StorageClass(object):
1538 Describes the storage class of a declaration
1541 # The unique kind objects, index by id.
1545 def __init__(self, value):
1546 if value >= len(StorageClass._kinds):
1547 StorageClass._kinds += [None] * (value - len(StorageClass._kinds) + 1)
1548 if StorageClass._kinds[value] is not None:
1549 raise ValueError,'StorageClass already loaded'
1551 StorageClass._kinds[value] = self
1552 StorageClass._name_map = None
1554 def from_param(self):
1559 """Get the enumeration name of this storage class."""
1560 if self._name_map is None:
1562 for key,value in StorageClass.__dict__.items():
1563 if isinstance(value,StorageClass):
1564 self._name_map[value] = key
1565 return self._name_map[self]
1569 if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]:
1570 raise ValueError,'Unknown storage class %d' % id
1571 return StorageClass._kinds[id]
1574 return 'StorageClass.%s' % (self.name,)
1576 StorageClass.INVALID = StorageClass(0)
1577 StorageClass.NONE = StorageClass(1)
1578 StorageClass.EXTERN = StorageClass(2)
1579 StorageClass.STATIC = StorageClass(3)
1580 StorageClass.PRIVATEEXTERN = StorageClass(4)
1581 StorageClass.OPENCLWORKGROUPLOCAL = StorageClass(5)
1582 StorageClass.AUTO = StorageClass(6)
1583 StorageClass.REGISTER = StorageClass(7)
1586 ### C++ access specifiers ###
1588 class AccessSpecifier(BaseEnumeration):
1590 Describes the access of a C++ class member
1593 # The unique kind objects, index by id.
1597 def from_param(self):
1601 return 'AccessSpecifier.%s' % (self.name,)
1603 AccessSpecifier.INVALID = AccessSpecifier(0)
1604 AccessSpecifier.PUBLIC = AccessSpecifier(1)
1605 AccessSpecifier.PROTECTED = AccessSpecifier(2)
1606 AccessSpecifier.PRIVATE = AccessSpecifier(3)
1607 AccessSpecifier.NONE = AccessSpecifier(4)
1611 class TypeKind(BaseEnumeration):
1613 Describes the kind of type.
1616 # The unique kind objects, indexed by id.
1622 """Retrieve the spelling of this TypeKind."""
1623 return conf.lib.clang_getTypeKindSpelling(self.value)
1626 return 'TypeKind.%s' % (self.name,)
1628 TypeKind.INVALID = TypeKind(0)
1629 TypeKind.UNEXPOSED = TypeKind(1)
1630 TypeKind.VOID = TypeKind(2)
1631 TypeKind.BOOL = TypeKind(3)
1632 TypeKind.CHAR_U = TypeKind(4)
1633 TypeKind.UCHAR = TypeKind(5)
1634 TypeKind.CHAR16 = TypeKind(6)
1635 TypeKind.CHAR32 = TypeKind(7)
1636 TypeKind.USHORT = TypeKind(8)
1637 TypeKind.UINT = TypeKind(9)
1638 TypeKind.ULONG = TypeKind(10)
1639 TypeKind.ULONGLONG = TypeKind(11)
1640 TypeKind.UINT128 = TypeKind(12)
1641 TypeKind.CHAR_S = TypeKind(13)
1642 TypeKind.SCHAR = TypeKind(14)
1643 TypeKind.WCHAR = TypeKind(15)
1644 TypeKind.SHORT = TypeKind(16)
1645 TypeKind.INT = TypeKind(17)
1646 TypeKind.LONG = TypeKind(18)
1647 TypeKind.LONGLONG = TypeKind(19)
1648 TypeKind.INT128 = TypeKind(20)
1649 TypeKind.FLOAT = TypeKind(21)
1650 TypeKind.DOUBLE = TypeKind(22)
1651 TypeKind.LONGDOUBLE = TypeKind(23)
1652 TypeKind.NULLPTR = TypeKind(24)
1653 TypeKind.OVERLOAD = TypeKind(25)
1654 TypeKind.DEPENDENT = TypeKind(26)
1655 TypeKind.OBJCID = TypeKind(27)
1656 TypeKind.OBJCCLASS = TypeKind(28)
1657 TypeKind.OBJCSEL = TypeKind(29)
1658 TypeKind.COMPLEX = TypeKind(100)
1659 TypeKind.POINTER = TypeKind(101)
1660 TypeKind.BLOCKPOINTER = TypeKind(102)
1661 TypeKind.LVALUEREFERENCE = TypeKind(103)
1662 TypeKind.RVALUEREFERENCE = TypeKind(104)
1663 TypeKind.RECORD = TypeKind(105)
1664 TypeKind.ENUM = TypeKind(106)
1665 TypeKind.TYPEDEF = TypeKind(107)
1666 TypeKind.OBJCINTERFACE = TypeKind(108)
1667 TypeKind.OBJCOBJECTPOINTER = TypeKind(109)
1668 TypeKind.FUNCTIONNOPROTO = TypeKind(110)
1669 TypeKind.FUNCTIONPROTO = TypeKind(111)
1670 TypeKind.CONSTANTARRAY = TypeKind(112)
1671 TypeKind.VECTOR = TypeKind(113)
1672 TypeKind.INCOMPLETEARRAY = TypeKind(114)
1673 TypeKind.VARIABLEARRAY = TypeKind(115)
1674 TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116)
1675 TypeKind.MEMBERPOINTER = TypeKind(117)
1677 class RefQualifierKind(BaseEnumeration):
1678 """Describes a specific ref-qualifier of a type."""
1680 # The unique kind objects, indexed by id.
1684 def from_param(self):
1688 return 'RefQualifierKind.%s' % (self.name,)
1690 RefQualifierKind.NONE = RefQualifierKind(0)
1691 RefQualifierKind.LVALUE = RefQualifierKind(1)
1692 RefQualifierKind.RVALUE = RefQualifierKind(2)
1694 class Type(Structure):
1696 The type of an element in the abstract syntax tree.
1698 _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)]
1702 """Return the kind of this type."""
1703 return TypeKind.from_id(self._kind_id)
1705 def argument_types(self):
1706 """Retrieve a container for the non-variadic arguments for this type.
1708 The returned object is iterable and indexable. Each item in the
1709 container is a Type instance.
1711 class ArgumentsIterator(collections.Sequence):
1712 def __init__(self, parent):
1713 self.parent = parent
1717 if self.length is None:
1718 self.length = conf.lib.clang_getNumArgTypes(self.parent)
1722 def __getitem__(self, key):
1723 # FIXME Support slice objects.
1724 if not isinstance(key, int):
1725 raise TypeError("Must supply a non-negative int.")
1728 raise IndexError("Only non-negative indexes are accepted.")
1730 if key >= len(self):
1731 raise IndexError("Index greater than container length: "
1732 "%d > %d" % ( key, len(self) ))
1734 result = conf.lib.clang_getArgType(self.parent, key)
1735 if result.kind == TypeKind.INVALID:
1736 raise IndexError("Argument could not be retrieved.")
1740 assert self.kind == TypeKind.FUNCTIONPROTO
1741 return ArgumentsIterator(self)
1744 def element_type(self):
1745 """Retrieve the Type of elements within this Type.
1747 If accessed on a type that is not an array, complex, or vector type, an
1748 exception will be raised.
1750 result = conf.lib.clang_getElementType(self)
1751 if result.kind == TypeKind.INVALID:
1752 raise Exception('Element type not available on this type.')
1757 def element_count(self):
1758 """Retrieve the number of elements in this type.
1762 If the Type is not an array or vector, this raises.
1764 result = conf.lib.clang_getNumElements(self)
1766 raise Exception('Type does not have elements.')
1771 def translation_unit(self):
1772 """The TranslationUnit to which this Type is associated."""
1773 # If this triggers an AttributeError, the instance was not properly
1778 def from_result(res, fn, args):
1779 assert isinstance(res, Type)
1783 if hasattr(arg, 'translation_unit'):
1784 tu = arg.translation_unit
1787 assert tu is not None
1792 def get_canonical(self):
1794 Return the canonical type for a Type.
1796 Clang's type system explicitly models typedefs and all the
1797 ways a specific type can be represented. The canonical type
1798 is the underlying type with all the "sugar" removed. For
1799 example, if 'T' is a typedef for 'int', the canonical type for
1802 return conf.lib.clang_getCanonicalType(self)
1804 def is_const_qualified(self):
1805 """Determine whether a Type has the "const" qualifier set.
1807 This does not look through typedefs that may have added "const"
1808 at a different level.
1810 return conf.lib.clang_isConstQualifiedType(self)
1812 def is_volatile_qualified(self):
1813 """Determine whether a Type has the "volatile" qualifier set.
1815 This does not look through typedefs that may have added "volatile"
1816 at a different level.
1818 return conf.lib.clang_isVolatileQualifiedType(self)
1820 def is_restrict_qualified(self):
1821 """Determine whether a Type has the "restrict" qualifier set.
1823 This does not look through typedefs that may have added "restrict" at
1826 return conf.lib.clang_isRestrictQualifiedType(self)
1828 def is_function_variadic(self):
1829 """Determine whether this function Type is a variadic function type."""
1830 assert self.kind == TypeKind.FUNCTIONPROTO
1832 return conf.lib.clang_isFunctionTypeVariadic(self)
1835 """Determine whether this Type represents plain old data (POD)."""
1836 return conf.lib.clang_isPODType(self)
1838 def get_pointee(self):
1840 For pointer types, returns the type of the pointee.
1842 return conf.lib.clang_getPointeeType(self)
1844 def get_declaration(self):
1846 Return the cursor for the declaration of the given type.
1848 return conf.lib.clang_getTypeDeclaration(self)
1850 def get_result(self):
1852 Retrieve the result type associated with a function type.
1854 return conf.lib.clang_getResultType(self)
1856 def get_array_element_type(self):
1858 Retrieve the type of the elements of the array type.
1860 return conf.lib.clang_getArrayElementType(self)
1862 def get_array_size(self):
1864 Retrieve the size of the constant array.
1866 return conf.lib.clang_getArraySize(self)
1868 def get_class_type(self):
1870 Retrieve the class type of the member pointer type.
1872 return conf.lib.clang_Type_getClassType(self)
1874 def get_align(self):
1876 Retrieve the alignment of the record.
1878 return conf.lib.clang_Type_getAlignOf(self)
1882 Retrieve the size of the record.
1884 return conf.lib.clang_Type_getSizeOf(self)
1886 def get_offset(self, fieldname):
1888 Retrieve the offset of a field in the record.
1890 return conf.lib.clang_Type_getOffsetOf(self, c_char_p(fieldname))
1892 def get_ref_qualifier(self):
1894 Retrieve the ref-qualifier of the type.
1896 return RefQualifierKind.from_id(
1897 conf.lib.clang_Type_getCXXRefQualifier(self))
1899 def get_fields(self):
1900 """Return an iterator for accessing the fields of this type."""
1902 def visitor(field, children):
1903 assert field != conf.lib.clang_getNullCursor()
1905 # Create reference to TU so it isn't GC'd before Cursor.
1906 field._tu = self._tu
1907 fields.append(field)
1910 conf.lib.clang_Type_visitFields(self,
1911 callbacks['fields_visit'](visitor), fields)
1916 """Retrieve the spelling of this Type."""
1917 return conf.lib.clang_getTypeSpelling(self)
1919 def __eq__(self, other):
1920 if type(other) != type(self):
1923 return conf.lib.clang_equalTypes(self, other)
1925 def __ne__(self, other):
1926 return not self.__eq__(other)
1928 ## CIndex Objects ##
1930 # CIndex objects (derived from ClangObject) are essentially lightweight
1931 # wrappers attached to some underlying object, which is exposed via CIndex as
1934 class ClangObject(object):
1936 A helper for Clang objects. This class helps act as an intermediary for
1937 the ctypes library and the Clang CIndex library.
1939 def __init__(self, obj):
1940 assert isinstance(obj, c_object_p) and obj
1941 self.obj = self._as_parameter_ = obj
1943 def from_param(self):
1944 return self._as_parameter_
1947 class _CXUnsavedFile(Structure):
1948 """Helper for passing unsaved file arguments."""
1949 _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
1951 # Functions calls through the python interface are rather slow. Fortunately,
1952 # for most symboles, we do not need to perform a function call. Their spelling
1953 # never changes and is consequently provided by this spelling cache.
1955 # 0: CompletionChunk.Kind("Optional"),
1956 # 1: CompletionChunk.Kind("TypedText"),
1957 # 2: CompletionChunk.Kind("Text"),
1958 # 3: CompletionChunk.Kind("Placeholder"),
1959 # 4: CompletionChunk.Kind("Informative"),
1960 # 5 : CompletionChunk.Kind("CurrentParameter"),
1961 6: '(', # CompletionChunk.Kind("LeftParen"),
1962 7: ')', # CompletionChunk.Kind("RightParen"),
1963 8: '[', # CompletionChunk.Kind("LeftBracket"),
1964 9: ']', # CompletionChunk.Kind("RightBracket"),
1965 10: '{', # CompletionChunk.Kind("LeftBrace"),
1966 11: '}', # CompletionChunk.Kind("RightBrace"),
1967 12: '<', # CompletionChunk.Kind("LeftAngle"),
1968 13: '>', # CompletionChunk.Kind("RightAngle"),
1969 14: ', ', # CompletionChunk.Kind("Comma"),
1970 # 15: CompletionChunk.Kind("ResultType"),
1971 16: ':', # CompletionChunk.Kind("Colon"),
1972 17: ';', # CompletionChunk.Kind("SemiColon"),
1973 18: '=', # CompletionChunk.Kind("Equal"),
1974 19: ' ', # CompletionChunk.Kind("HorizontalSpace"),
1975 # 20: CompletionChunk.Kind("VerticalSpace")
1978 class CompletionChunk:
1980 def __init__(self, name):
1987 return "<ChunkKind: %s>" % self
1989 def __init__(self, completionString, key):
1990 self.cs = completionString
1992 self.__kindNumberCache = -1
1995 return "{'" + self.spelling + "', " + str(self.kind) + "}"
1999 if self.__kindNumber in SpellingCache:
2000 return SpellingCache[self.__kindNumber]
2001 return conf.lib.clang_getCompletionChunkText(self.cs, self.key).spelling
2003 # We do not use @CachedProperty here, as the manual implementation is
2004 # apparently still significantly faster. Please profile carefully if you
2005 # would like to add CachedProperty back.
2007 def __kindNumber(self):
2008 if self.__kindNumberCache == -1:
2009 self.__kindNumberCache = \
2010 conf.lib.clang_getCompletionChunkKind(self.cs, self.key)
2011 return self.__kindNumberCache
2015 return completionChunkKindMap[self.__kindNumber]
2019 res = conf.lib.clang_getCompletionChunkCompletionString(self.cs,
2023 return CompletionString(res)
2027 def isKindOptional(self):
2028 return self.__kindNumber == 0
2030 def isKindTypedText(self):
2031 return self.__kindNumber == 1
2033 def isKindPlaceHolder(self):
2034 return self.__kindNumber == 3
2036 def isKindInformative(self):
2037 return self.__kindNumber == 4
2039 def isKindResultType(self):
2040 return self.__kindNumber == 15
2042 completionChunkKindMap = {
2043 0: CompletionChunk.Kind("Optional"),
2044 1: CompletionChunk.Kind("TypedText"),
2045 2: CompletionChunk.Kind("Text"),
2046 3: CompletionChunk.Kind("Placeholder"),
2047 4: CompletionChunk.Kind("Informative"),
2048 5: CompletionChunk.Kind("CurrentParameter"),
2049 6: CompletionChunk.Kind("LeftParen"),
2050 7: CompletionChunk.Kind("RightParen"),
2051 8: CompletionChunk.Kind("LeftBracket"),
2052 9: CompletionChunk.Kind("RightBracket"),
2053 10: CompletionChunk.Kind("LeftBrace"),
2054 11: CompletionChunk.Kind("RightBrace"),
2055 12: CompletionChunk.Kind("LeftAngle"),
2056 13: CompletionChunk.Kind("RightAngle"),
2057 14: CompletionChunk.Kind("Comma"),
2058 15: CompletionChunk.Kind("ResultType"),
2059 16: CompletionChunk.Kind("Colon"),
2060 17: CompletionChunk.Kind("SemiColon"),
2061 18: CompletionChunk.Kind("Equal"),
2062 19: CompletionChunk.Kind("HorizontalSpace"),
2063 20: CompletionChunk.Kind("VerticalSpace")}
2065 class CompletionString(ClangObject):
2067 def __init__(self, name):
2074 return "<Availability: %s>" % self
2077 return self.num_chunks
2080 def num_chunks(self):
2081 return conf.lib.clang_getNumCompletionChunks(self.obj)
2083 def __getitem__(self, key):
2084 if self.num_chunks <= key:
2086 return CompletionChunk(self.obj, key)
2090 return conf.lib.clang_getCompletionPriority(self.obj)
2093 def availability(self):
2094 res = conf.lib.clang_getCompletionAvailability(self.obj)
2095 return availabilityKinds[res]
2098 def briefComment(self):
2099 if conf.function_exists("clang_getCompletionBriefComment"):
2100 return conf.lib.clang_getCompletionBriefComment(self.obj)
2104 return " | ".join([str(a) for a in self]) \
2105 + " || Priority: " + str(self.priority) \
2106 + " || Availability: " + str(self.availability) \
2107 + " || Brief comment: " + str(self.briefComment.spelling)
2109 availabilityKinds = {
2110 0: CompletionChunk.Kind("Available"),
2111 1: CompletionChunk.Kind("Deprecated"),
2112 2: CompletionChunk.Kind("NotAvailable"),
2113 3: CompletionChunk.Kind("NotAccessible")}
2115 class CodeCompletionResult(Structure):
2116 _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
2119 return str(CompletionString(self.completionString))
2123 return CursorKind.from_id(self.cursorKind)
2127 return CompletionString(self.completionString)
2129 class CCRStructure(Structure):
2130 _fields_ = [('results', POINTER(CodeCompletionResult)),
2131 ('numResults', c_int)]
2134 return self.numResults
2136 def __getitem__(self, key):
2137 if len(self) <= key:
2140 return self.results[key]
2142 class CodeCompletionResults(ClangObject):
2143 def __init__(self, ptr):
2144 assert isinstance(ptr, POINTER(CCRStructure)) and ptr
2145 self.ptr = self._as_parameter_ = ptr
2147 def from_param(self):
2148 return self._as_parameter_
2151 conf.lib.clang_disposeCodeCompleteResults(self)
2155 return self.ptr.contents
2158 def diagnostics(self):
2159 class DiagnosticsItr:
2160 def __init__(self, ccr):
2165 conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr))
2167 def __getitem__(self, key):
2168 return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key)
2170 return DiagnosticsItr(self)
2173 class Index(ClangObject):
2175 The Index type provides the primary interface to the Clang CIndex library,
2176 primarily by providing an interface for reading and parsing translation
2181 def create(excludeDecls=False):
2185 excludeDecls -- Exclude local declarations from translation units.
2187 return Index(conf.lib.clang_createIndex(excludeDecls, 0))
2190 conf.lib.clang_disposeIndex(self)
2192 def read(self, path):
2193 """Load a TranslationUnit from the given AST file."""
2194 return TranslationUnit.from_ast_file(path, self)
2196 def parse(self, path, args=None, unsaved_files=None, options = 0):
2197 """Load the translation unit from the given source code file by running
2198 clang and generating the AST before loading. Additional command line
2199 parameters can be passed to clang via the args parameter.
2201 In-memory contents for files can be provided by passing a list of pairs
2202 to as unsaved_files, the first item should be the filenames to be mapped
2203 and the second should be the contents to be substituted for the
2204 file. The contents may be passed as strings or file objects.
2206 If an error was encountered during parsing, a TranslationUnitLoadError
2209 return TranslationUnit.from_source(path, args, unsaved_files, options,
2212 class TranslationUnit(ClangObject):
2213 """Represents a source code translation unit.
2215 This is one of the main types in the API. Any time you wish to interact
2216 with Clang's representation of a source file, you typically start with a
2220 # Default parsing mode.
2223 # Instruct the parser to create a detailed processing record containing
2224 # metadata not normally retained.
2225 PARSE_DETAILED_PROCESSING_RECORD = 1
2227 # Indicates that the translation unit is incomplete. This is typically used
2228 # when parsing headers.
2229 PARSE_INCOMPLETE = 2
2231 # Instruct the parser to create a pre-compiled preamble for the translation
2232 # unit. This caches the preamble (included files at top of source file).
2233 # This is useful if the translation unit will be reparsed and you don't
2234 # want to incur the overhead of reparsing the preamble.
2235 PARSE_PRECOMPILED_PREAMBLE = 4
2237 # Cache code completion information on parse. This adds time to parsing but
2238 # speeds up code completion.
2239 PARSE_CACHE_COMPLETION_RESULTS = 8
2241 # Flags with values 16 and 32 are deprecated and intentionally omitted.
2243 # Do not parse function bodies. This is useful if you only care about
2244 # searching for declarations/definitions.
2245 PARSE_SKIP_FUNCTION_BODIES = 64
2247 # Used to indicate that brief documentation comments should be included
2248 # into the set of code completions returned from this translation unit.
2249 PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128
2252 def from_source(cls, filename, args=None, unsaved_files=None, options=0,
2254 """Create a TranslationUnit by parsing source.
2256 This is capable of processing source code both from files on the
2257 filesystem as well as in-memory contents.
2259 Command-line arguments that would be passed to clang are specified as
2260 a list via args. These can be used to specify include paths, warnings,
2261 etc. e.g. ["-Wall", "-I/path/to/include"].
2263 In-memory file content can be provided via unsaved_files. This is an
2264 iterable of 2-tuples. The first element is the str filename. The
2265 second element defines the content. Content can be provided as str
2266 source code or as file objects (anything with a read() method). If
2267 a file object is being used, content will be read until EOF and the
2268 read cursor will not be reset to its original position.
2270 options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
2271 control parsing behavior.
2273 index is an Index instance to utilize. If not provided, a new Index
2274 will be created for this TranslationUnit.
2276 To parse source from the filesystem, the filename of the file to parse
2277 is specified by the filename argument. Or, filename could be None and
2278 the args list would contain the filename(s) to parse.
2280 To parse source from an in-memory buffer, set filename to the virtual
2281 filename you wish to associate with this source (e.g. "test.c"). The
2282 contents of that file are then provided in unsaved_files.
2284 If an error occurs, a TranslationUnitLoadError is raised.
2286 Please note that a TranslationUnit with parser errors may be returned.
2287 It is the caller's responsibility to check tu.diagnostics for errors.
2289 Also note that Clang infers the source language from the extension of
2290 the input filename. If you pass in source code containing a C++ class
2291 declaration with the filename "test.c" parsing will fail.
2296 if unsaved_files is None:
2300 index = Index.create()
2304 args_array = (c_char_p * len(args))(* args)
2306 unsaved_array = None
2307 if len(unsaved_files) > 0:
2308 unsaved_array = (_CXUnsavedFile * len(unsaved_files))()
2309 for i, (name, contents) in enumerate(unsaved_files):
2310 if hasattr(contents, "read"):
2311 contents = contents.read()
2313 unsaved_array[i].name = name
2314 unsaved_array[i].contents = contents
2315 unsaved_array[i].length = len(contents)
2317 ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array,
2318 len(args), unsaved_array,
2319 len(unsaved_files), options)
2322 raise TranslationUnitLoadError("Error parsing translation unit.")
2324 return cls(ptr, index=index)
2327 def from_ast_file(cls, filename, index=None):
2328 """Create a TranslationUnit instance from a saved AST file.
2330 A previously-saved AST file (provided with -emit-ast or
2331 TranslationUnit.save()) is loaded from the filename specified.
2333 If the file cannot be loaded, a TranslationUnitLoadError will be
2336 index is optional and is the Index instance to use. If not provided,
2337 a default Index will be created.
2340 index = Index.create()
2342 ptr = conf.lib.clang_createTranslationUnit(index, filename)
2344 raise TranslationUnitLoadError(filename)
2346 return cls(ptr=ptr, index=index)
2348 def __init__(self, ptr, index):
2349 """Create a TranslationUnit instance.
2351 TranslationUnits should be created using one of the from_* @classmethod
2352 functions above. __init__ is only called internally.
2354 assert isinstance(index, Index)
2356 ClangObject.__init__(self, ptr)
2359 conf.lib.clang_disposeTranslationUnit(self)
2363 """Retrieve the cursor that represents the given translation unit."""
2364 return conf.lib.clang_getTranslationUnitCursor(self)
2368 """Get the original translation unit source file name."""
2369 return conf.lib.clang_getTranslationUnitSpelling(self)
2371 def get_includes(self):
2373 Return an iterable sequence of FileInclusion objects that describe the
2374 sequence of inclusions in a translation unit. The first object in
2375 this sequence is always the input file. Note that this method will not
2376 recursively iterate over header files included through precompiled
2379 def visitor(fobj, lptr, depth, includes):
2382 includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
2384 # Automatically adapt CIndex/ctype pointers to python objects
2386 conf.lib.clang_getInclusions(self,
2387 callbacks['translation_unit_includes'](visitor), includes)
2389 return iter(includes)
2391 def get_file(self, filename):
2392 """Obtain a File from this translation unit."""
2394 return File.from_name(self, filename)
2396 def get_location(self, filename, position):
2397 """Obtain a SourceLocation for a file in this translation unit.
2399 The position can be specified by passing:
2401 - Integer file offset. Initial file offset is 0.
2402 - 2-tuple of (line number, column number). Initial file position is
2405 f = self.get_file(filename)
2407 if isinstance(position, int):
2408 return SourceLocation.from_offset(self, f, position)
2410 return SourceLocation.from_position(self, f, position[0], position[1])
2412 def get_extent(self, filename, locations):
2413 """Obtain a SourceRange from this translation unit.
2415 The bounds of the SourceRange must ultimately be defined by a start and
2416 end SourceLocation. For the locations argument, you can pass:
2418 - 2 SourceLocation instances in a 2-tuple or list.
2419 - 2 int file offsets via a 2-tuple or list.
2420 - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list.
2424 get_extent('foo.c', (5, 10))
2425 get_extent('foo.c', ((1, 1), (1, 15)))
2427 f = self.get_file(filename)
2429 if len(locations) < 2:
2430 raise Exception('Must pass object with at least 2 elements')
2432 start_location, end_location = locations
2434 if hasattr(start_location, '__len__'):
2435 start_location = SourceLocation.from_position(self, f,
2436 start_location[0], start_location[1])
2437 elif isinstance(start_location, int):
2438 start_location = SourceLocation.from_offset(self, f,
2441 if hasattr(end_location, '__len__'):
2442 end_location = SourceLocation.from_position(self, f,
2443 end_location[0], end_location[1])
2444 elif isinstance(end_location, int):
2445 end_location = SourceLocation.from_offset(self, f, end_location)
2447 assert isinstance(start_location, SourceLocation)
2448 assert isinstance(end_location, SourceLocation)
2450 return SourceRange.from_locations(start_location, end_location)
2453 def diagnostics(self):
2455 Return an iterable (and indexable) object containing the diagnostics.
2458 def __init__(self, tu):
2462 return int(conf.lib.clang_getNumDiagnostics(self.tu))
2464 def __getitem__(self, key):
2465 diag = conf.lib.clang_getDiagnostic(self.tu, key)
2468 return Diagnostic(diag)
2470 return DiagIterator(self)
2472 def reparse(self, unsaved_files=None, options=0):
2474 Reparse an already parsed translation unit.
2476 In-memory contents for files can be provided by passing a list of pairs
2477 as unsaved_files, the first items should be the filenames to be mapped
2478 and the second should be the contents to be substituted for the
2479 file. The contents may be passed as strings or file objects.
2481 if unsaved_files is None:
2484 unsaved_files_array = 0
2485 if len(unsaved_files):
2486 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
2487 for i,(name,value) in enumerate(unsaved_files):
2488 if not isinstance(value, str):
2489 # FIXME: It would be great to support an efficient version
2491 value = value.read()
2493 if not isinstance(value, str):
2494 raise TypeError,'Unexpected unsaved file contents.'
2495 unsaved_files_array[i].name = name
2496 unsaved_files_array[i].contents = value
2497 unsaved_files_array[i].length = len(value)
2498 ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
2499 unsaved_files_array, options)
2501 def save(self, filename):
2502 """Saves the TranslationUnit to a file.
2504 This is equivalent to passing -emit-ast to the clang frontend. The
2505 saved file can be loaded back into a TranslationUnit. Or, if it
2506 corresponds to a header, it can be used as a pre-compiled header file.
2508 If an error occurs while saving, a TranslationUnitSaveError is raised.
2509 If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means
2510 the constructed TranslationUnit was not valid at time of save. In this
2511 case, the reason(s) why should be available via
2512 TranslationUnit.diagnostics().
2514 filename -- The path to save the translation unit to.
2516 options = conf.lib.clang_defaultSaveOptions(self)
2517 result = int(conf.lib.clang_saveTranslationUnit(self, filename,
2520 raise TranslationUnitSaveError(result,
2521 'Error saving TranslationUnit.')
2523 def codeComplete(self, path, line, column, unsaved_files=None,
2524 include_macros=False, include_code_patterns=False,
2525 include_brief_comments=False):
2527 Code complete in this translation unit.
2529 In-memory contents for files can be provided by passing a list of pairs
2530 as unsaved_files, the first items should be the filenames to be mapped
2531 and the second should be the contents to be substituted for the
2532 file. The contents may be passed as strings or file objects.
2539 if include_code_patterns:
2542 if include_brief_comments:
2545 if unsaved_files is None:
2548 unsaved_files_array = 0
2549 if len(unsaved_files):
2550 unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
2551 for i,(name,value) in enumerate(unsaved_files):
2552 if not isinstance(value, str):
2553 # FIXME: It would be great to support an efficient version
2555 value = value.read()
2557 if not isinstance(value, str):
2558 raise TypeError,'Unexpected unsaved file contents.'
2559 unsaved_files_array[i].name = name
2560 unsaved_files_array[i].contents = value
2561 unsaved_files_array[i].length = len(value)
2562 ptr = conf.lib.clang_codeCompleteAt(self, path, line, column,
2563 unsaved_files_array, len(unsaved_files), options)
2565 return CodeCompletionResults(ptr)
2568 def get_tokens(self, locations=None, extent=None):
2569 """Obtain tokens in this translation unit.
2571 This is a generator for Token instances. The caller specifies a range
2572 of source code to obtain tokens for. The range can be specified as a
2573 2-tuple of SourceLocation or as a SourceRange. If both are defined,
2574 behavior is undefined.
2576 if locations is not None:
2577 extent = SourceRange(start=locations[0], end=locations[1])
2579 return TokenGroup.get_tokens(self, extent)
2581 class File(ClangObject):
2583 The File class represents a particular source file that is part of a
2588 def from_name(translation_unit, file_name):
2589 """Retrieve a file handle within the given translation unit."""
2590 return File(conf.lib.clang_getFile(translation_unit, file_name))
2594 """Return the complete file and path name of the file."""
2595 return conf.lib.clang_getCString(conf.lib.clang_getFileName(self))
2599 """Return the last modification time of the file."""
2600 return conf.lib.clang_getFileTime(self)
2606 return "<File: %s>" % (self.name)
2609 def from_cursor_result(res, fn, args):
2610 assert isinstance(res, File)
2612 # Copy a reference to the TranslationUnit to prevent premature GC.
2613 res._tu = args[0]._tu
2616 class FileInclusion(object):
2618 The FileInclusion class represents the inclusion of one source file by
2619 another via a '#include' directive or as the input file for the translation
2620 unit. This class provides information about the included file, the including
2621 file, the location of the '#include' directive and the depth of the included
2622 file in the stack. Note that the input file has depth 0.
2625 def __init__(self, src, tgt, loc, depth):
2632 def is_input_file(self):
2633 """True if the included file is the input file."""
2634 return self.depth == 0
2636 class CompilationDatabaseError(Exception):
2637 """Represents an error that occurred when working with a CompilationDatabase
2639 Each error is associated to an enumerated value, accessible under
2640 e.cdb_error. Consumers can compare the value with one of the ERROR_
2641 constants in this class.
2644 # An unknown error occurred
2647 # The database could not be loaded
2648 ERROR_CANNOTLOADDATABASE = 1
2650 def __init__(self, enumeration, message):
2651 assert isinstance(enumeration, int)
2654 raise Exception("Encountered undefined CompilationDatabase error "
2655 "constant: %d. Please file a bug to have this "
2656 "value supported." % enumeration)
2658 self.cdb_error = enumeration
2659 Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
2661 class CompileCommand(object):
2662 """Represents the compile command used to build a file"""
2663 def __init__(self, cmd, ccmds):
2665 # Keep a reference to the originating CompileCommands
2666 # to prevent garbage collection
2670 def directory(self):
2671 """Get the working directory for this CompileCommand"""
2672 return conf.lib.clang_CompileCommand_getDirectory(self.cmd)
2675 def arguments(self):
2677 Get an iterable object providing each argument in the
2678 command line for the compiler invocation as a _CXString.
2680 Invariant : the first argument is the compiler executable
2682 length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
2683 for i in xrange(length):
2684 yield conf.lib.clang_CompileCommand_getArg(self.cmd, i)
2686 class CompileCommands(object):
2688 CompileCommands is an iterable object containing all CompileCommand
2689 that can be used for building a specific file.
2691 def __init__(self, ccmds):
2695 conf.lib.clang_CompileCommands_dispose(self.ccmds)
2698 return int(conf.lib.clang_CompileCommands_getSize(self.ccmds))
2700 def __getitem__(self, i):
2701 cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i)
2704 return CompileCommand(cc, self)
2707 def from_result(res, fn, args):
2710 return CompileCommands(res)
2712 class CompilationDatabase(ClangObject):
2714 The CompilationDatabase is a wrapper class around
2715 clang::tooling::CompilationDatabase
2717 It enables querying how a specific source file can be built.
2721 conf.lib.clang_CompilationDatabase_dispose(self)
2724 def from_result(res, fn, args):
2726 raise CompilationDatabaseError(0,
2727 "CompilationDatabase loading failed")
2728 return CompilationDatabase(res)
2731 def fromDirectory(buildDir):
2732 """Builds a CompilationDatabase from the database found in buildDir"""
2733 errorCode = c_uint()
2735 cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
2737 except CompilationDatabaseError as e:
2738 raise CompilationDatabaseError(int(errorCode.value),
2739 "CompilationDatabase loading failed")
2742 def getCompileCommands(self, filename):
2744 Get an iterable object providing all the CompileCommands available to
2745 build filename. Returns None if filename is not found in the database.
2747 return conf.lib.clang_CompilationDatabase_getCompileCommands(self,
2750 def getAllCompileCommands(self):
2752 Get an iterable object providing all the CompileCommands available from
2755 return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self)
2758 class Token(Structure):
2759 """Represents a single token from the preprocessor.
2761 Tokens are effectively segments of source code. Source code is first parsed
2762 into tokens before being converted into the AST and Cursors.
2764 Tokens are obtained from parsed TranslationUnit instances. You currently
2765 can't create tokens manually.
2768 ('int_data', c_uint * 4),
2769 ('ptr_data', c_void_p)
2774 """The spelling of this token.
2776 This is the textual representation of the token in source.
2778 return conf.lib.clang_getTokenSpelling(self._tu, self)
2782 """Obtain the TokenKind of the current token."""
2783 return TokenKind.from_value(conf.lib.clang_getTokenKind(self))
2787 """The SourceLocation this Token occurs at."""
2788 return conf.lib.clang_getTokenLocation(self._tu, self)
2792 """The SourceRange this Token occupies."""
2793 return conf.lib.clang_getTokenExtent(self._tu, self)
2797 """The Cursor this Token corresponds to."""
2800 conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
2804 # Now comes the plumbing to hook up the C library.
2806 # Register callback types in common container.
2807 callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p,
2808 POINTER(SourceLocation), c_uint, py_object)
2809 callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
2810 callbacks['fields_visit'] = CFUNCTYPE(c_int, Cursor, py_object)
2812 # Functions strictly alphabetical order.
2814 ("clang_annotateTokens",
2815 [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]),
2817 ("clang_CompilationDatabase_dispose",
2820 ("clang_CompilationDatabase_fromDirectory",
2821 [c_char_p, POINTER(c_uint)],
2823 CompilationDatabase.from_result),
2825 ("clang_CompilationDatabase_getAllCompileCommands",
2828 CompileCommands.from_result),
2830 ("clang_CompilationDatabase_getCompileCommands",
2831 [c_object_p, c_char_p],
2833 CompileCommands.from_result),
2835 ("clang_CompileCommands_dispose",
2838 ("clang_CompileCommands_getCommand",
2839 [c_object_p, c_uint],
2842 ("clang_CompileCommands_getSize",
2846 ("clang_CompileCommand_getArg",
2847 [c_object_p, c_uint],
2849 _CXString.from_result),
2851 ("clang_CompileCommand_getDirectory",
2854 _CXString.from_result),
2856 ("clang_CompileCommand_getNumArgs",
2860 ("clang_codeCompleteAt",
2861 [TranslationUnit, c_char_p, c_int, c_int, c_void_p, c_int, c_int],
2862 POINTER(CCRStructure)),
2864 ("clang_codeCompleteGetDiagnostic",
2865 [CodeCompletionResults, c_int],
2868 ("clang_codeCompleteGetNumDiagnostics",
2869 [CodeCompletionResults],
2872 ("clang_createIndex",
2876 ("clang_createTranslationUnit",
2880 ("clang_CXXMethod_isPureVirtual",
2884 ("clang_CXXMethod_isStatic",
2888 ("clang_CXXMethod_isVirtual",
2892 ("clang_defaultSaveOptions",
2896 ("clang_disposeCodeCompleteResults",
2897 [CodeCompletionResults]),
2899 # ("clang_disposeCXTUResourceUsage",
2900 # [CXTUResourceUsage]),
2902 ("clang_disposeDiagnostic",
2905 ("clang_disposeIndex",
2908 ("clang_disposeString",
2911 ("clang_disposeTokens",
2912 [TranslationUnit, POINTER(Token), c_uint]),
2914 ("clang_disposeTranslationUnit",
2917 ("clang_equalCursors",
2921 ("clang_equalLocations",
2922 [SourceLocation, SourceLocation],
2925 ("clang_equalRanges",
2926 [SourceRange, SourceRange],
2929 ("clang_equalTypes",
2933 ("clang_getArgType",
2938 ("clang_getArrayElementType",
2943 ("clang_getArraySize",
2947 ("clang_getFieldDeclBitWidth",
2951 ("clang_getCanonicalCursor",
2954 Cursor.from_cursor_result),
2956 ("clang_getCanonicalType",
2961 ("clang_getCompletionAvailability",
2965 ("clang_getCompletionBriefComment",
2969 ("clang_getCompletionChunkCompletionString",
2973 ("clang_getCompletionChunkKind",
2977 ("clang_getCompletionChunkText",
2981 ("clang_getCompletionPriority",
2985 ("clang_getCString",
2990 [TranslationUnit, SourceLocation],
2993 ("clang_getCursorDefinition",
2996 Cursor.from_result),
2998 ("clang_getCursorDisplayName",
3001 _CXString.from_result),
3003 ("clang_getCursorExtent",
3007 ("clang_getCursorLexicalParent",
3010 Cursor.from_cursor_result),
3012 ("clang_getCursorLocation",
3016 ("clang_getCursorReferenced",
3019 Cursor.from_result),
3021 ("clang_getCursorReferenceNameRange",
3022 [Cursor, c_uint, c_uint],
3025 ("clang_getCursorSemanticParent",
3028 Cursor.from_cursor_result),
3030 ("clang_getCursorSpelling",
3033 _CXString.from_result),
3035 ("clang_getCursorType",
3040 ("clang_getCursorUSR",
3043 _CXString.from_result),
3045 ("clang_Cursor_getMangling",
3048 _CXString.from_result),
3050 # ("clang_getCXTUResourceUsage",
3051 # [TranslationUnit],
3052 # CXTUResourceUsage),
3054 ("clang_getCXXAccessSpecifier",
3058 ("clang_getDeclObjCTypeEncoding",
3061 _CXString.from_result),
3063 ("clang_getDiagnostic",
3064 [c_object_p, c_uint],
3067 ("clang_getDiagnosticCategory",
3071 ("clang_getDiagnosticCategoryText",
3074 _CXString.from_result),
3076 ("clang_getDiagnosticFixIt",
3077 [Diagnostic, c_uint, POINTER(SourceRange)],
3079 _CXString.from_result),
3081 ("clang_getDiagnosticLocation",
3085 ("clang_getDiagnosticNumFixIts",
3089 ("clang_getDiagnosticNumRanges",
3093 ("clang_getDiagnosticOption",
3094 [Diagnostic, POINTER(_CXString)],
3096 _CXString.from_result),
3098 ("clang_getDiagnosticRange",
3099 [Diagnostic, c_uint],
3102 ("clang_getDiagnosticSeverity",
3106 ("clang_getDiagnosticSpelling",
3109 _CXString.from_result),
3111 ("clang_getElementType",
3116 ("clang_getEnumConstantDeclUnsignedValue",
3120 ("clang_getEnumConstantDeclValue",
3124 ("clang_getEnumDeclIntegerType",
3130 [TranslationUnit, c_char_p],
3133 ("clang_getFileName",
3135 _CXString), # TODO go through _CXString.from_result?
3137 ("clang_getFileTime",
3141 ("clang_getIBOutletCollectionType",
3146 ("clang_getIncludedFile",
3149 File.from_cursor_result),
3151 ("clang_getInclusions",
3152 [TranslationUnit, callbacks['translation_unit_includes'], py_object]),
3154 ("clang_getInstantiationLocation",
3155 [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint),
3158 ("clang_getLocation",
3159 [TranslationUnit, File, c_uint, c_uint],
3162 ("clang_getLocationForOffset",
3163 [TranslationUnit, File, c_uint],
3166 ("clang_getNullCursor",
3170 ("clang_getNumArgTypes",
3174 ("clang_getNumCompletionChunks",
3178 ("clang_getNumDiagnostics",
3182 ("clang_getNumElements",
3186 ("clang_getNumOverloadedDecls",
3190 ("clang_getOverloadedDecl",
3193 Cursor.from_cursor_result),
3195 ("clang_getPointeeType",
3201 [SourceLocation, SourceLocation],
3204 ("clang_getRangeEnd",
3208 ("clang_getRangeStart",
3212 ("clang_getResultType",
3217 ("clang_getSpecializedCursorTemplate",
3220 Cursor.from_cursor_result),
3222 ("clang_getTemplateCursorKind",
3226 ("clang_getTokenExtent",
3227 [TranslationUnit, Token],
3230 ("clang_getTokenKind",
3234 ("clang_getTokenLocation",
3235 [TranslationUnit, Token],
3238 ("clang_getTokenSpelling",
3239 [TranslationUnit, Token],
3241 _CXString.from_result),
3243 ("clang_getTranslationUnitCursor",
3246 Cursor.from_result),
3248 ("clang_getTranslationUnitSpelling",
3251 _CXString.from_result),
3253 ("clang_getTUResourceUsageName",
3257 ("clang_getTypeDeclaration",
3260 Cursor.from_result),
3262 ("clang_getTypedefDeclUnderlyingType",
3267 ("clang_getTypeKindSpelling",
3270 _CXString.from_result),
3272 ("clang_getTypeSpelling",
3275 _CXString.from_result),
3277 ("clang_hashCursor",
3281 ("clang_isAttribute",
3285 ("clang_isConstQualifiedType",
3289 ("clang_isCursorDefinition",
3293 ("clang_isDeclaration",
3297 ("clang_isExpression",
3301 ("clang_isFileMultipleIncludeGuarded",
3302 [TranslationUnit, File],
3305 ("clang_isFunctionTypeVariadic",
3317 ("clang_isPreprocessing",
3321 ("clang_isReference",
3325 ("clang_isRestrictQualifiedType",
3329 ("clang_isStatement",
3333 ("clang_isTranslationUnit",
3337 ("clang_isUnexposed",
3341 ("clang_isVirtualBase",
3345 ("clang_isVolatileQualifiedType",
3349 ("clang_parseTranslationUnit",
3350 [Index, c_char_p, c_void_p, c_int, c_void_p, c_int, c_int],
3353 ("clang_reparseTranslationUnit",
3354 [TranslationUnit, c_int, c_void_p, c_int],
3357 ("clang_saveTranslationUnit",
3358 [TranslationUnit, c_char_p, c_uint],
3362 [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]),
3364 ("clang_visitChildren",
3365 [Cursor, callbacks['cursor_visit'], py_object],
3368 ("clang_Cursor_getNumArguments",
3372 ("clang_Cursor_getArgument",
3375 Cursor.from_result),
3377 ("clang_Cursor_getNumTemplateArguments",
3381 ("clang_Cursor_getTemplateArgumentKind",
3383 TemplateArgumentKind.from_id),
3385 ("clang_Cursor_getTemplateArgumentType",
3390 ("clang_Cursor_getTemplateArgumentValue",
3394 ("clang_Cursor_getTemplateArgumentUnsignedValue",
3398 ("clang_Cursor_isAnonymous",
3402 ("clang_Cursor_isBitField",
3406 ("clang_Cursor_getBriefCommentText",
3409 _CXString.from_result),
3411 ("clang_Cursor_getRawCommentText",
3414 _CXString.from_result),
3416 ("clang_Cursor_getOffsetOfField",
3420 ("clang_Type_getAlignOf",
3424 ("clang_Type_getClassType",
3429 ("clang_Type_getOffsetOf",
3433 ("clang_Type_getSizeOf",
3437 ("clang_Type_getCXXRefQualifier",
3441 ("clang_Type_visitFields",
3442 [Type, callbacks['fields_visit'], py_object],
3446 class LibclangError(Exception):
3447 def __init__(self, message):
3453 def register_function(lib, item, ignore_errors):
3454 # A function may not exist, if these bindings are used with an older or
3455 # incompatible version of libclang.so.
3457 func = getattr(lib, item[0])
3458 except AttributeError as e:
3459 msg = str(e) + ". Please ensure that your python bindings are "\
3460 "compatible with your libclang.so version."
3463 raise LibclangError(msg)
3466 func.argtypes = item[1]
3469 func.restype = item[2]
3472 func.errcheck = item[3]
3474 def register_functions(lib, ignore_errors):
3475 """Register function prototypes with a libclang library instance.
3477 This must be called as part of library instantiation so Python knows how
3478 to call out to the shared library.
3482 return register_function(lib, item, ignore_errors)
3484 map(register, functionList)
3489 compatibility_check = True
3493 def set_library_path(path):
3494 """Set the path in which to search for libclang"""
3496 raise Exception("library path must be set before before using " \
3497 "any other functionalities in libclang.")
3499 Config.library_path = path
3502 def set_library_file(filename):
3503 """Set the exact location of libclang"""
3505 raise Exception("library file must be set before before using " \
3506 "any other functionalities in libclang.")
3508 Config.library_file = filename
3511 def set_compatibility_check(check_status):
3512 """ Perform compatibility check when loading libclang
3514 The python bindings are only tested and evaluated with the version of
3515 libclang they are provided with. To ensure correct behavior a (limited)
3516 compatibility check is performed when loading the bindings. This check
3517 will throw an exception, as soon as it fails.
3519 In case these bindings are used with an older version of libclang, parts
3520 that have been stable between releases may still work. Users of the
3521 python bindings can disable the compatibility check. This will cause
3522 the python bindings to load, even though they are written for a newer
3523 version of libclang. Failures now arise if unsupported or incompatible
3524 features are accessed. The user is required to test themselves if the
3525 features they are using are available and compatible between different
3529 raise Exception("compatibility_check must be set before before " \
3530 "using any other functionalities in libclang.")
3532 Config.compatibility_check = check_status
3536 lib = self.get_cindex_library()
3537 register_functions(lib, not Config.compatibility_check)
3538 Config.loaded = True
3541 def get_filename(self):
3542 if Config.library_file:
3543 return Config.library_file
3546 name = platform.system()
3548 if name == 'Darwin':
3549 file = 'libclang.dylib'
3550 elif name == 'Windows':
3551 file = 'libclang.dll'
3553 file = 'libclang.so'
3555 if Config.library_path:
3556 file = Config.library_path + '/' + file
3560 def get_cindex_library(self):
3562 library = cdll.LoadLibrary(self.get_filename())
3563 except OSError as e:
3564 msg = str(e) + ". To provide a path to libclang use " \
3565 "Config.set_library_path() or " \
3566 "Config.set_library_file()."
3567 raise LibclangError(msg)
3571 def function_exists(self, name):
3573 getattr(self.lib, name)
3574 except AttributeError:
3579 def register_enumerations():
3580 for name, value in clang.enumerations.TokenKinds:
3581 TokenKind.register(value, name)
3584 register_enumerations()
3588 'CodeCompletionResults',
3589 'CompilationDatabase',
3602 'TranslationUnitLoadError',