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 74 c_object_p = POINTER(c_void_p)
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. 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. 104 ERROR_TRANSLATION_ERRORS = 2
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)
118 Exception.__init__(self,
'Error %d: %s' % (enumeration, message))
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. 137 def __get__(self, instance, instance_type=None):
148 """Helper for transforming CXString results.""" 150 _fields_ = [(
"spelling", c_char_p), (
"free", c_int)]
153 conf.lib.clang_disposeString(self)
158 return conf.lib.clang_getCString(res)
162 A SourceLocation represents a particular location within a source file. 164 _fields_ = [(
"ptr_data", c_void_p * 2), (
"int_data", c_uint)]
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))
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)
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.""" 204 """Get the line represented by this source location.""" 209 """Get the column represented by this source location.""" 214 """Get the file offset represented by this source location.""" 218 return conf.lib.clang_equalLocations(self, other)
221 return not self.
__eq__(other)
225 filename = self.
file.name
228 return "<SourceLocation file %r, line %r, column %r>" % (
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)]
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)
264 return conf.lib.clang_equalRanges(self, other)
267 return not self.
__eq__(other)
270 """Useful to detect the Token/Lexer bug""" 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):
280 if self.
start.line < other.line < self.
end.line:
282 elif self.
start.line == other.line:
284 if self.
start.column <= other.column:
286 elif other.line == self.
end.line:
288 if other.column <= self.
end.column:
293 return "<SourceRange start %r, end %r>" % (self.
start, self.
end)
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. 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)
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)
349 return int(conf.lib.clang_getDiagnosticNumFixIts(self.
diag))
351 def __getitem__(self, key):
353 value = conf.lib.clang_getDiagnosticFixIt(self.
diag, key,
358 return FixIt(range, value)
360 return FixItIterator(self)
364 class ChildDiagnosticsIterator:
366 self.
diag_set = conf.lib.clang_getChildDiagnostics(diag)
369 return int(conf.lib.clang_getNumDiagnosticsInSet(self.
diag_set))
371 def __getitem__(self, key):
372 diag = conf.lib.clang_getDiagnosticInSet(self.
diag_set, key)
377 return ChildDiagnosticsIterator(self)
381 """The category number for this diagnostic or 0 if unavailable.""" 382 return conf.lib.clang_getDiagnosticCategory(self)
386 """The string name of the category for this diagnostic.""" 387 return conf.lib.clang_getDiagnosticCategoryText(self)
391 """The command-line option that enables this diagnostic.""" 392 return conf.lib.clang_getDiagnosticOption(self,
None)
396 """The command-line option that disables this diagnostic.""" 398 conf.lib.clang_getDiagnosticOption(self, byref(disable))
400 return conf.lib.clang_getCString(disable)
403 return "<Diagnostic severity %r, location %r, spelling %r>" % (
411 A FixIt represents a transformation to be applied to the source to 412 "fix-it". The fix-it shouldbe applied by replacing the given source range 413 with the given value. 421 return "<FixIt range %r, value %r>" % (self.
range, self.
value)
424 """Helper class to facilitate token management. 426 Tokens are allocated from libclang in chunks. They must be disposed of as a 429 One purpose of this class is for instances to represent groups of allocated 430 tokens. Each token in a group contains a reference back to an instance of 431 this class. When all tokens from a group are garbage collected, it allows 432 this class to be garbage collected. When this class is garbage collected, 433 it calls the libclang destructor which invalidates all tokens in the group. 435 You should not instantiate this class outside of this module. 447 """Helper method to return all tokens in an extent. 449 This functionality is needed multiple places in this module. We define 450 it here because it seems like a logical place. 452 tokens_memory = POINTER(Token)()
453 tokens_count = c_uint()
455 conf.lib.clang_tokenize(tu, extent, byref(tokens_memory),
458 count = int(tokens_count.value)
465 tokens_array =
cast(tokens_memory, POINTER(Token * count)).contents
467 token_group =
TokenGroup(tu, tokens_memory, tokens_count)
469 for i
in range(0, count):
471 token.int_data = tokens_array[i].int_data
472 token.ptr_data = tokens_array[i].ptr_data
474 token._group = token_group
479 """Describes a specific type of a Token.""" 484 """Create a new TokenKind instance from a numeric value and a name.""" 489 return 'TokenKind.%s' % (self.
name,)
493 """Obtain a registered TokenKind instance from its value.""" 494 result = TokenKind._value_map.get(value,
None)
497 raise ValueError(
'Unknown TokenKind: %d' % value)
503 """Register a new TokenKind enumeration. 505 This should only be called at module load time by code within this 508 if value
in TokenKind._value_map:
509 raise ValueError(
'TokenKind already registered: %d' % value)
512 TokenKind._value_map[value] = kind
518 Common base class for named enumerations held in sync with Index.h values. 520 Subclasses must define their own _kinds and _name_map members, as: 523 These values hold the per-subclass instances and value-to-name mappings, 529 if value >=
len(self.__class__._kinds):
530 self.__class__._kinds += [
None] * (value -
len(self.__class__._kinds) + 1)
531 if self.__class__._kinds[value]
is not None:
532 raise ValueError(
'{0} value {1} already loaded'.
format(
533 str(self.__class__), value))
535 self.__class__._kinds[value] = self
536 self.__class__._name_map =
None 544 """Get the enumeration name of this cursor kind.""" 547 for key, value
in list(self.__class__.__dict__.items()):
554 if id >=
len(cls._kinds)
or cls._kinds[id]
is None:
555 raise ValueError(
'Unknown template argument kind %d' % id)
556 return cls._kinds[id]
559 return '%s.%s' % (self.__class__, self.
name,)
564 A CursorKind describes the kind of entity that a cursor points to. 573 """Return all CursorKind enumeration instances.""" 574 return [_f
for _f
in CursorKind._kinds
if _f]
577 """Test if this is a declaration kind.""" 578 return conf.lib.clang_isDeclaration(self)
581 """Test if this is a reference kind.""" 582 return conf.lib.clang_isReference(self)
585 """Test if this is an expression kind.""" 586 return conf.lib.clang_isExpression(self)
589 """Test if this is a statement kind.""" 590 return conf.lib.clang_isStatement(self)
593 """Test if this is an attribute kind.""" 594 return conf.lib.clang_isAttribute(self)
597 """Test if this is an invalid kind.""" 598 return conf.lib.clang_isInvalid(self)
601 """Test if this is a translation unit kind.""" 602 return conf.lib.clang_isTranslationUnit(self)
605 """Test if this is a preprocessing kind.""" 606 return conf.lib.clang_isPreprocessing(self)
609 """Test if this is an unexposed kind.""" 610 return conf.lib.clang_isUnexposed(self)
613 return 'CursorKind.%s' % (self.
name,)
718 CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION =
CursorKind(32)
1190 CursorKind.OMP_DISTRIBUTE_PARALLELFOR_DIRECTIVE =
CursorKind(266)
1193 CursorKind.OMP_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE =
CursorKind(267)
1199 CursorKind.OMP_TARGET_PARALLEL_FOR_SIMD_DIRECTIVE =
CursorKind(269)
1270 A TemplateArgumentKind describes the kind of entity that a template argument 1288 The Cursor class represents a reference to an element within the AST. It 1289 acts as a kind of iterator. 1291 _fields_ = [(
"_kind_id", c_int), (
"xdata", c_int), (
"data", c_void_p * 3)]
1297 cursor = conf.lib.clang_getCursor(tu, location)
1303 return conf.lib.clang_equalCursors(self, other)
1306 return not self.
__eq__(other)
1310 Returns true if the declaration pointed at by the cursor is also a 1311 definition of that entity. 1313 return conf.lib.clang_isCursorDefinition(self)
1316 """Returns True if the cursor refers to a C++ member function or member 1317 function template that is declared 'const'. 1319 return conf.lib.clang_CXXMethod_isConst(self)
1322 """Returns True if the cursor refers to a C++ converting constructor. 1324 return conf.lib.clang_CXXConstructor_isConvertingConstructor(self)
1327 """Returns True if the cursor refers to a C++ copy constructor. 1329 return conf.lib.clang_CXXConstructor_isCopyConstructor(self)
1332 """Returns True if the cursor refers to a C++ default constructor. 1334 return conf.lib.clang_CXXConstructor_isDefaultConstructor(self)
1337 """Returns True if the cursor refers to a C++ move constructor. 1339 return conf.lib.clang_CXXConstructor_isMoveConstructor(self)
1342 """Returns True if the cursor refers to a C++ member function or member 1343 function template that is declared '= default'. 1345 return conf.lib.clang_CXXMethod_isDefaulted(self)
1348 """Returns True if the cursor refers to a C++ field that is declared 1351 return conf.lib.clang_CXXField_isMutable(self)
1354 """Returns True if the cursor refers to a C++ member function or member 1355 function template that is declared pure virtual. 1357 return conf.lib.clang_CXXMethod_isPureVirtual(self)
1360 """Returns True if the cursor refers to a C++ member function or member 1361 function template that is declared 'static'. 1363 return conf.lib.clang_CXXMethod_isStatic(self)
1366 """Returns True if the cursor refers to a C++ member function or member 1367 function template that is declared 'virtual'. 1369 return conf.lib.clang_CXXMethod_isVirtual(self)
1373 If the cursor is a reference to a declaration or a declaration of 1374 some entity, return a cursor that points to the definition of that 1379 return conf.lib.clang_getCursorDefinition(self)
1382 """Return the Unified Symbol Resultion (USR) for the entity referenced 1383 by the given cursor (or None). 1385 A Unified Symbol Resolution (USR) is a string that identifies a 1386 particular entity (function, class, variable, etc.) within a 1387 program. USRs can be compared across translation units to determine, 1388 e.g., when references in one translation refer to an entity defined in 1389 another translation unit.""" 1390 return conf.lib.clang_getCursorUSR(self)
1394 """Return the kind of this cursor.""" 1395 return CursorKind.from_id(self._kind_id)
1399 """Return the spelling of the entity pointed at by the cursor.""" 1400 if not hasattr(self,
'_spelling'):
1408 Return the display name for the entity referenced by this cursor. 1410 The display name contains extra information that helps identify the 1411 cursor, such as the parameters of a function or template or the 1412 arguments of a class template specialization. 1414 if not hasattr(self,
'_displayname'):
1421 """Return the mangled name for the entity referenced by this cursor.""" 1422 if not hasattr(self,
'_mangled_name'):
1430 Return the source location (the starting character) of the entity 1431 pointed at by the cursor. 1434 self.
_loc = conf.lib.clang_getCursorLocation(self)
1441 Return the source range (the range of text) occupied by the entity 1442 pointed at by the cursor. 1444 if not hasattr(self,
'_extent'):
1445 self.
_extent = conf.lib.clang_getCursorExtent(self)
1452 Retrieves the storage class (if any) of the entity pointed at by the 1455 if not hasattr(self,
'_storage_class'):
1463 Retrieves the access specifier (if any) of the entity pointed at by the 1466 if not hasattr(self,
'_access_specifier'):
1474 Retrieve the Type (if any) of the entity pointed at by the cursor. 1476 if not hasattr(self,
'_type'):
1477 self.
_type = conf.lib.clang_getCursorType(self)
1483 """Return the canonical Cursor corresponding to this Cursor. 1485 The canonical cursor is the cursor which is representative for the 1486 underlying entity. For example, if you have multiple forward 1487 declarations for the same class, the canonical cursor for the forward 1488 declarations will be identical. 1490 if not hasattr(self,
'_canonical'):
1497 """Retrieve the Type of the result for this Cursor.""" 1498 if not hasattr(self,
'_result_type'):
1505 """Return the underlying type of a typedef declaration. 1507 Returns a Type for the typedef this cursor is a declaration for. If 1508 the current cursor is not a typedef, this raises. 1510 if not hasattr(self,
'_underlying_type'):
1511 assert self.
kind.is_declaration()
1513 conf.lib.clang_getTypedefDeclUnderlyingType(self)
1519 """Return the integer type of an enum declaration. 1521 Returns a Type corresponding to an integer. If the cursor is not for an 1524 if not hasattr(self,
'_enum_type'):
1525 assert self.
kind == CursorKind.ENUM_DECL
1532 """Return the value of an enum constant.""" 1533 if not hasattr(self,
'_enum_value'):
1534 assert self.
kind == CursorKind.ENUM_CONSTANT_DECL
1537 underlying_type = self.
type 1538 if underlying_type.kind == TypeKind.ENUM:
1539 underlying_type = underlying_type.get_declaration().enum_type
1540 if underlying_type.kind
in (TypeKind.CHAR_U,
1550 conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
1552 self.
_enum_value = conf.lib.clang_getEnumConstantDeclValue(self)
1557 """Return the Objective-C type encoding as a str.""" 1558 if not hasattr(self,
'_objc_type_encoding'):
1560 conf.lib.clang_getDeclObjCTypeEncoding(self)
1566 """Returns a hash of the cursor as an int.""" 1567 if not hasattr(self,
'_hash'):
1568 self.
_hash = conf.lib.clang_hashCursor(self)
1574 """Return the semantic parent for this cursor.""" 1575 if not hasattr(self,
'_semantic_parent'):
1582 """Return the lexical parent for this cursor.""" 1583 if not hasattr(self,
'_lexical_parent'):
1590 """Returns the TranslationUnit to which this Cursor belongs.""" 1598 For a cursor that is a reference, returns a cursor 1599 representing the entity that it references. 1601 if not hasattr(self,
'_referenced'):
1608 """Returns the brief comment text associated with that Cursor""" 1609 return conf.lib.clang_Cursor_getBriefCommentText(self)
1613 """Returns the raw comment text associated with that Cursor""" 1614 return conf.lib.clang_Cursor_getRawCommentText(self)
1617 """Return an iterator for accessing the arguments of this cursor.""" 1618 num_args = conf.lib.clang_Cursor_getNumArguments(self)
1619 for i
in range(0, num_args):
1620 yield conf.lib.clang_Cursor_getArgument(self, i)
1623 """Returns the number of template args associated with this cursor.""" 1624 return conf.lib.clang_Cursor_getNumTemplateArguments(self)
1627 """Returns the TemplateArgumentKind for the indicated template 1629 return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num)
1632 """Returns the CXType for the indicated template argument.""" 1633 return conf.lib.clang_Cursor_getTemplateArgumentType(self, num)
1636 """Returns the value of the indicated arg as a signed 64b integer.""" 1637 return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num)
1640 """Returns the value of the indicated arg as an unsigned 64b integer.""" 1641 return conf.lib.clang_Cursor_getTemplateArgumentUnsignedValue(self, num)
1644 """Return an iterator for accessing the children of this cursor.""" 1647 def visitor(child, parent, children):
1650 assert child != conf.lib.clang_getNullCursor()
1653 child._tu = self._tu
1654 children.append(child)
1657 conf.lib.clang_visitChildren(self, callbacks[
'cursor_visit'](visitor),
1659 return iter(children)
1662 """Depth-first preorder walk over the cursor and its descendants. 1668 for descendant
in child.walk_preorder():
1672 """Obtain Token instances formulating that compose this Cursor. 1674 This is a generator for Token instances. It returns all tokens which 1675 occupy the extent this cursor occupies. 1677 return TokenGroup.get_tokens(self._tu, self.
extent)
1680 """Returns the offsetof the FIELD_DECL pointed by this Cursor.""" 1681 return conf.lib.clang_Cursor_getOffsetOfField(self)
1685 Check if the record is anonymous. 1687 if self.
kind == CursorKind.FIELD_DECL:
1689 return conf.lib.clang_Cursor_isAnonymous(self)
1693 Check if the field is a bitfield. 1695 return conf.lib.clang_Cursor_isBitField(self)
1699 Retrieve the width of a bitfield. 1701 return conf.lib.clang_getFieldDeclBitWidth(self)
1707 if res == conf.lib.clang_getNullCursor():
1718 if hasattr(arg,
'translation_unit'):
1719 tu = arg.translation_unit
1722 assert tu
is not None 1730 if res == conf.lib.clang_getNullCursor():
1733 res._tu = args[0]._tu
1738 Describes the storage class of a declaration 1746 if value >=
len(StorageClass._kinds):
1747 StorageClass._kinds += [
None] * (value -
len(StorageClass._kinds) + 1)
1748 if StorageClass._kinds[value]
is not None:
1749 raise ValueError(
'StorageClass already loaded')
1751 StorageClass._kinds[value] = self
1752 StorageClass._name_map =
None 1759 """Get the enumeration name of this storage class.""" 1762 for key,value
in list(StorageClass.__dict__.items()):
1769 if id >=
len(StorageClass._kinds)
or not StorageClass._kinds[id]:
1770 raise ValueError(
'Unknown storage class %d' % id)
1771 return StorageClass._kinds[id]
1774 return 'StorageClass.%s' % (self.
name,)
1790 Describes the access of a C++ class member 1801 return 'AccessSpecifier.%s' % (self.
name,)
1813 Describes the kind of type. 1822 """Retrieve the spelling of this TypeKind.""" 1823 return conf.lib.clang_getTypeKindSpelling(self.
value)
1826 return 'TypeKind.%s' % (self.
name,)
1862 TypeKind.BLOCKPOINTER =
TypeKind(102)
1863 TypeKind.LVALUEREFERENCE =
TypeKind(103)
1864 TypeKind.RVALUEREFERENCE =
TypeKind(104)
1868 TypeKind.OBJCINTERFACE =
TypeKind(108)
1869 TypeKind.OBJCOBJECTPOINTER =
TypeKind(109)
1870 TypeKind.FUNCTIONNOPROTO =
TypeKind(110)
1871 TypeKind.FUNCTIONPROTO =
TypeKind(111)
1872 TypeKind.CONSTANTARRAY =
TypeKind(112)
1874 TypeKind.INCOMPLETEARRAY =
TypeKind(114)
1875 TypeKind.VARIABLEARRAY =
TypeKind(115)
1876 TypeKind.DEPENDENTSIZEDARRAY =
TypeKind(116)
1877 TypeKind.MEMBERPOINTER =
TypeKind(117)
1879 TypeKind.ELABORATED =
TypeKind(119)
1882 """Describes a specific ref-qualifier of a type.""" 1892 return 'RefQualifierKind.%s' % (self.
name,)
1900 The type of an element in the abstract syntax tree. 1902 _fields_ = [(
"_kind_id", c_int), (
"data", c_void_p * 2)]
1906 """Return the kind of this type.""" 1907 return TypeKind.from_id(self._kind_id)
1910 """Retrieve a container for the non-variadic arguments for this type. 1912 The returned object is iterable and indexable. Each item in the 1913 container is a Type instance. 1915 class ArgumentsIterator(collections.Sequence):
1916 def __init__(self, parent):
1922 self.
length = conf.lib.clang_getNumArgTypes(self.
parent)
1926 def __getitem__(self, key):
1929 raise TypeError(
"Must supply a non-negative int.")
1932 raise IndexError(
"Only non-negative indexes are accepted.")
1934 if key >=
len(self):
1935 raise IndexError(
"Index greater than container length: " 1936 "%d > %d" % ( key,
len(self) ))
1938 result = conf.lib.clang_getArgType(self.
parent, key)
1939 if result.kind == TypeKind.INVALID:
1940 raise IndexError(
"Argument could not be retrieved.")
1944 assert self.
kind == TypeKind.FUNCTIONPROTO
1945 return ArgumentsIterator(self)
1949 """Retrieve the Type of elements within this Type. 1951 If accessed on a type that is not an array, complex, or vector type, an 1952 exception will be raised. 1954 result = conf.lib.clang_getElementType(self)
1955 if result.kind == TypeKind.INVALID:
1956 raise Exception(
'Element type not available on this type.')
1962 """Retrieve the number of elements in this type. 1966 If the Type is not an array or vector, this raises. 1968 result = conf.lib.clang_getNumElements(self)
1970 raise Exception(
'Type does not have elements.')
1976 """The TranslationUnit to which this Type is associated.""" 1987 if hasattr(arg,
'translation_unit'):
1988 tu = arg.translation_unit
1991 assert tu
is not None 1998 Return the canonical type for a Type. 2000 Clang's type system explicitly models typedefs and all the 2001 ways a specific type can be represented. The canonical type 2002 is the underlying type with all the "sugar" removed. For 2003 example, if 'T' is a typedef for 'int', the canonical type for 2006 return conf.lib.clang_getCanonicalType(self)
2009 """Determine whether a Type has the "const" qualifier set. 2011 This does not look through typedefs that may have added "const" 2012 at a different level. 2014 return conf.lib.clang_isConstQualifiedType(self)
2017 """Determine whether a Type has the "volatile" qualifier set. 2019 This does not look through typedefs that may have added "volatile" 2020 at a different level. 2022 return conf.lib.clang_isVolatileQualifiedType(self)
2025 """Determine whether a Type has the "restrict" qualifier set. 2027 This does not look through typedefs that may have added "restrict" at 2030 return conf.lib.clang_isRestrictQualifiedType(self)
2033 """Determine whether this function Type is a variadic function type.""" 2034 assert self.
kind == TypeKind.FUNCTIONPROTO
2036 return conf.lib.clang_isFunctionTypeVariadic(self)
2039 """Determine whether this Type represents plain old data (POD).""" 2040 return conf.lib.clang_isPODType(self)
2044 For pointer types, returns the type of the pointee. 2046 return conf.lib.clang_getPointeeType(self)
2050 Return the cursor for the declaration of the given type. 2052 return conf.lib.clang_getTypeDeclaration(self)
2056 Retrieve the result type associated with a function type. 2058 return conf.lib.clang_getResultType(self)
2062 Retrieve the type of the elements of the array type. 2064 return conf.lib.clang_getArrayElementType(self)
2068 Retrieve the size of the constant array. 2070 return conf.lib.clang_getArraySize(self)
2074 Retrieve the class type of the member pointer type. 2076 return conf.lib.clang_Type_getClassType(self)
2080 Retrieve the type named by the qualified-id. 2082 return conf.lib.clang_Type_getNamedType(self)
2085 Retrieve the alignment of the record. 2087 return conf.lib.clang_Type_getAlignOf(self)
2091 Retrieve the size of the record. 2093 return conf.lib.clang_Type_getSizeOf(self)
2097 Retrieve the offset of a field in the record. 2099 return conf.lib.clang_Type_getOffsetOf(self, c_char_p(fieldname))
2103 Retrieve the ref-qualifier of the type. 2105 return RefQualifierKind.from_id(
2106 conf.lib.clang_Type_getCXXRefQualifier(self))
2109 """Return an iterator for accessing the fields of this type.""" 2111 def visitor(field, children):
2112 assert field != conf.lib.clang_getNullCursor()
2115 field._tu = self._tu
2116 fields.append(field)
2119 conf.lib.clang_Type_visitFields(self,
2120 callbacks[
'fields_visit'](visitor), fields)
2125 """Retrieve the spelling of this Type.""" 2126 return conf.lib.clang_getTypeSpelling(self)
2132 return conf.lib.clang_equalTypes(self, other)
2135 return not self.
__eq__(other)
2145 A helper for Clang objects. This class helps act as an intermediary for 2146 the ctypes library and the Clang CIndex library. 2157 """Helper for passing unsaved file arguments.""" 2158 _fields_ = [(
"name", c_char_p), (
"contents", c_char_p), (
'length', c_ulong)]
2196 return "<ChunkKind: %s>" % self
2199 self.
cs = completionString
2210 return conf.lib.clang_getCompletionChunkText(self.
cs, self.
key).spelling
2219 conf.lib.clang_getCompletionChunkKind(self.
cs, self.
key)
2228 res = conf.lib.clang_getCompletionChunkCompletionString(self.
cs,
2251 completionChunkKindMap = {
2283 return "<Availability: %s>" % self
2290 return conf.lib.clang_getNumCompletionChunks(self.
obj)
2299 return conf.lib.clang_getCompletionPriority(self.
obj)
2303 res = conf.lib.clang_getCompletionAvailability(self.
obj)
2304 return availabilityKinds[res]
2308 if conf.function_exists(
"clang_getCompletionBriefComment"):
2309 return conf.lib.clang_getCompletionBriefComment(self.
obj)
2313 return " | ".
join([
str(a)
for a
in self]) \
2318 availabilityKinds = {
2325 _fields_ = [(
'cursorKind', c_int), (
'completionString', c_object_p)]
2332 return CursorKind.from_id(self.cursorKind)
2339 _fields_ = [(
'results', POINTER(CodeCompletionResult)),
2340 (
'numResults', c_int)]
2343 return self.numResults
2346 if len(self) <= key:
2349 return self.results[key]
2353 assert isinstance(ptr, POINTER(CCRStructure))
and ptr
2360 conf.lib.clang_disposeCodeCompleteResults(self)
2364 return self.
ptr.contents
2368 class DiagnosticsItr:
2374 conf.lib.clang_codeCompleteGetNumDiagnostics(self.
ccr))
2376 def __getitem__(self, key):
2377 return conf.lib.clang_codeCompleteGetDiagnostic(self.
ccr, key)
2379 return DiagnosticsItr(self)
2384 The Index type provides the primary interface to the Clang CIndex library, 2385 primarily by providing an interface for reading and parsing translation 2394 excludeDecls -- Exclude local declarations from translation units. 2396 return Index(conf.lib.clang_createIndex(excludeDecls, 0))
2399 conf.lib.clang_disposeIndex(self)
2402 """Load a TranslationUnit from the given AST file.""" 2403 return TranslationUnit.from_ast_file(path, self)
2405 def parse(self, path, args=None, unsaved_files=None, options = 0):
2406 """Load the translation unit from the given source code file by running 2407 clang and generating the AST before loading. Additional command line 2408 parameters can be passed to clang via the args parameter. 2410 In-memory contents for files can be provided by passing a list of pairs 2411 to as unsaved_files, the first item should be the filenames to be mapped 2412 and the second should be the contents to be substituted for the 2413 file. The contents may be passed as strings or file objects. 2415 If an error was encountered during parsing, a TranslationUnitLoadError 2418 return TranslationUnit.from_source(path, args, unsaved_files, options,
2422 """Represents a source code translation unit. 2424 This is one of the main types in the API. Any time you wish to interact 2425 with Clang's representation of a source file, you typically start with a 2434 PARSE_DETAILED_PROCESSING_RECORD = 1
2438 PARSE_INCOMPLETE = 2
2444 PARSE_PRECOMPILED_PREAMBLE = 4
2448 PARSE_CACHE_COMPLETION_RESULTS = 8
2454 PARSE_SKIP_FUNCTION_BODIES = 64
2458 PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128
2461 def from_source(cls, filename, args=None, unsaved_files=None, options=0,
2463 """Create a TranslationUnit by parsing source. 2465 This is capable of processing source code both from files on the 2466 filesystem as well as in-memory contents. 2468 Command-line arguments that would be passed to clang are specified as 2469 a list via args. These can be used to specify include paths, warnings, 2470 etc. e.g. ["-Wall", "-I/path/to/include"]. 2472 In-memory file content can be provided via unsaved_files. This is an 2473 iterable of 2-tuples. The first element is the str filename. The 2474 second element defines the content. Content can be provided as str 2475 source code or as file objects (anything with a read() method). If 2476 a file object is being used, content will be read until EOF and the 2477 read cursor will not be reset to its original position. 2479 options is a bitwise or of TranslationUnit.PARSE_XXX flags which will 2480 control parsing behavior. 2482 index is an Index instance to utilize. If not provided, a new Index 2483 will be created for this TranslationUnit. 2485 To parse source from the filesystem, the filename of the file to parse 2486 is specified by the filename argument. Or, filename could be None and 2487 the args list would contain the filename(s) to parse. 2489 To parse source from an in-memory buffer, set filename to the virtual 2490 filename you wish to associate with this source (e.g. "test.c"). The 2491 contents of that file are then provided in unsaved_files. 2493 If an error occurs, a TranslationUnitLoadError is raised. 2495 Please note that a TranslationUnit with parser errors may be returned. 2496 It is the caller's responsibility to check tu.diagnostics for errors. 2498 Also note that Clang infers the source language from the extension of 2499 the input filename. If you pass in source code containing a C++ class 2500 declaration with the filename "test.c" parsing will fail. 2505 if unsaved_files
is None:
2509 index = Index.create()
2512 filename = filename.encode(
'utf8')
2514 args_length =
len(args)
2516 args = (arg.encode(
'utf8')
if isinstance(arg, str)
else arg
2518 args_array = (c_char_p * args_length)(* args)
2520 unsaved_array =
None 2521 if len(unsaved_files) > 0:
2522 unsaved_array = (_CXUnsavedFile *
len(unsaved_files))()
2523 for i, (name, contents)
in enumerate(unsaved_files):
2525 contents = contents.read()
2527 unsaved_array[i].name = name
2528 unsaved_array[i].contents = contents
2529 unsaved_array[i].length =
len(contents)
2531 ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array,
2532 args_length, unsaved_array,
2533 len(unsaved_files), options)
2538 return cls(ptr, index=index)
2542 """Create a TranslationUnit instance from a saved AST file. 2544 A previously-saved AST file (provided with -emit-ast or 2545 TranslationUnit.save()) is loaded from the filename specified. 2547 If the file cannot be loaded, a TranslationUnitLoadError will be 2550 index is optional and is the Index instance to use. If not provided, 2551 a default Index will be created. 2554 index = Index.create()
2556 ptr = conf.lib.clang_createTranslationUnit(index, filename)
2560 return cls(ptr=ptr, index=index)
2563 """Create a TranslationUnit instance. 2565 TranslationUnits should be created using one of the from_* @classmethod 2566 functions above. __init__ is only called internally. 2570 ClangObject.__init__(self, ptr)
2573 conf.lib.clang_disposeTranslationUnit(self)
2577 """Retrieve the cursor that represents the given translation unit.""" 2578 return conf.lib.clang_getTranslationUnitCursor(self)
2582 """Get the original translation unit source file name.""" 2583 return conf.lib.clang_getTranslationUnitSpelling(self)
2587 Return an iterable sequence of FileInclusion objects that describe the 2588 sequence of inclusions in a translation unit. The first object in 2589 this sequence is always the input file. Note that this method will not 2590 recursively iterate over header files included through precompiled 2593 def visitor(fobj, lptr, depth, includes):
2600 conf.lib.clang_getInclusions(self,
2601 callbacks[
'translation_unit_includes'](visitor), includes)
2603 return iter(includes)
2606 """Obtain a File from this translation unit.""" 2608 return File.from_name(self, filename)
2611 """Obtain a SourceLocation for a file in this translation unit. 2613 The position can be specified by passing: 2615 - Integer file offset. Initial file offset is 0. 2616 - 2-tuple of (line number, column number). Initial file position is 2622 return SourceLocation.from_offset(self, f, position)
2624 return SourceLocation.from_position(self, f, position[0], position[1])
2627 """Obtain a SourceRange from this translation unit. 2629 The bounds of the SourceRange must ultimately be defined by a start and 2630 end SourceLocation. For the locations argument, you can pass: 2632 - 2 SourceLocation instances in a 2-tuple or list. 2633 - 2 int file offsets via a 2-tuple or list. 2634 - 2 2-tuple or lists of (line, column) pairs in a 2-tuple or list. 2638 get_extent('foo.c', (5, 10)) 2639 get_extent('foo.c', ((1, 1), (1, 15))) 2643 if len(locations) < 2:
2644 raise Exception(
'Must pass object with at least 2 elements')
2646 start_location, end_location = locations
2648 if hasattr(start_location,
'__len__'):
2649 start_location = SourceLocation.from_position(self, f,
2650 start_location[0], start_location[1])
2652 start_location = SourceLocation.from_offset(self, f,
2655 if hasattr(end_location,
'__len__'):
2656 end_location = SourceLocation.from_position(self, f,
2657 end_location[0], end_location[1])
2659 end_location = SourceLocation.from_offset(self, f, end_location)
2661 assert isinstance(start_location, SourceLocation)
2662 assert isinstance(end_location, SourceLocation)
2664 return SourceRange.from_locations(start_location, end_location)
2669 Return an iterable (and indexable) object containing the diagnostics. 2676 return int(conf.lib.clang_getNumDiagnostics(self.
tu))
2678 def __getitem__(self, key):
2679 diag = conf.lib.clang_getDiagnostic(self.
tu, key)
2684 return DiagIterator(self)
2688 Reparse an already parsed translation unit. 2690 In-memory contents for files can be provided by passing a list of pairs 2691 as unsaved_files, the first items should be the filenames to be mapped 2692 and the second should be the contents to be substituted for the 2693 file. The contents may be passed as strings or file objects. 2695 if unsaved_files
is None:
2698 unsaved_files_array = 0
2699 if len(unsaved_files):
2700 unsaved_files_array = (_CXUnsavedFile *
len(unsaved_files))()
2701 for i,(name,value)
in enumerate(unsaved_files):
2705 value = value.read()
2708 raise TypeError(
'Unexpected unsaved file contents.')
2709 unsaved_files_array[i].name = name
2710 unsaved_files_array[i].contents = value
2711 unsaved_files_array[i].length =
len(value)
2712 ptr = conf.lib.clang_reparseTranslationUnit(self,
len(unsaved_files),
2713 unsaved_files_array, options)
2716 """Saves the TranslationUnit to a file. 2718 This is equivalent to passing -emit-ast to the clang frontend. The 2719 saved file can be loaded back into a TranslationUnit. Or, if it 2720 corresponds to a header, it can be used as a pre-compiled header file. 2722 If an error occurs while saving, a TranslationUnitSaveError is raised. 2723 If the error was TranslationUnitSaveError.ERROR_INVALID_TU, this means 2724 the constructed TranslationUnit was not valid at time of save. In this 2725 case, the reason(s) why should be available via 2726 TranslationUnit.diagnostics(). 2728 filename -- The path to save the translation unit to. 2730 options = conf.lib.clang_defaultSaveOptions(self)
2731 result = int(conf.lib.clang_saveTranslationUnit(self, filename,
2735 'Error saving TranslationUnit.')
2737 def codeComplete(self, path, line, column, unsaved_files=None,
2738 include_macros=False, include_code_patterns=False,
2739 include_brief_comments=False):
2741 Code complete in this translation unit. 2743 In-memory contents for files can be provided by passing a list of pairs 2744 as unsaved_files, the first items should be the filenames to be mapped 2745 and the second should be the contents to be substituted for the 2746 file. The contents may be passed as strings or file objects. 2753 if include_code_patterns:
2756 if include_brief_comments:
2759 if unsaved_files
is None:
2762 unsaved_files_array = 0
2763 if len(unsaved_files):
2764 unsaved_files_array = (_CXUnsavedFile *
len(unsaved_files))()
2765 for i,(name,value)
in enumerate(unsaved_files):
2769 value = value.read()
2772 raise TypeError(
'Unexpected unsaved file contents.')
2773 unsaved_files_array[i].name = name
2774 unsaved_files_array[i].contents = value
2775 unsaved_files_array[i].length =
len(value)
2776 ptr = conf.lib.clang_codeCompleteAt(self, path, line, column,
2777 unsaved_files_array,
len(unsaved_files), options)
2783 """Obtain tokens in this translation unit. 2785 This is a generator for Token instances. The caller specifies a range 2786 of source code to obtain tokens for. The range can be specified as a 2787 2-tuple of SourceLocation or as a SourceRange. If both are defined, 2788 behavior is undefined. 2790 if locations
is not None:
2791 extent =
SourceRange(start=locations[0], end=locations[1])
2793 return TokenGroup.get_tokens(self, extent)
2797 The File class represents a particular source file that is part of a 2803 """Retrieve a file handle within the given translation unit.""" 2804 return File(conf.lib.clang_getFile(translation_unit, file_name))
2808 """Return the complete file and path name of the file.""" 2809 return conf.lib.clang_getCString(conf.lib.clang_getFileName(self))
2813 """Return the last modification time of the file.""" 2814 return conf.lib.clang_getFileTime(self)
2820 return "<File: %s>" % (self.
name)
2827 res._tu = args[0]._tu
2832 The FileInclusion class represents the inclusion of one source file by 2833 another via a '#include' directive or as the input file for the translation 2834 unit. This class provides information about the included file, the including 2835 file, the location of the '#include' directive and the depth of the included 2836 file in the stack. Note that the input file has depth 0. 2847 """True if the included file is the input file.""" 2848 return self.
depth == 0
2851 """Represents an error that occurred when working with a CompilationDatabase 2853 Each error is associated to an enumerated value, accessible under 2854 e.cdb_error. Consumers can compare the value with one of the ERROR_ 2855 constants in this class. 2862 ERROR_CANNOTLOADDATABASE = 1
2868 raise Exception(
"Encountered undefined CompilationDatabase error " 2869 "constant: %d. Please file a bug to have this " 2870 "value supported." % enumeration)
2873 Exception.__init__(self,
'Error %d: %s' % (enumeration, message))
2876 """Represents the compile command used to build a file""" 2885 """Get the working directory for this CompileCommand""" 2886 return conf.lib.clang_CompileCommand_getDirectory(self.
cmd)
2890 """Get the working filename for this CompileCommand""" 2891 return conf.lib.clang_CompileCommand_getFilename(self.
cmd)
2896 Get an iterable object providing each argument in the 2897 command line for the compiler invocation as a _CXString. 2899 Invariant : the first argument is the compiler executable 2901 length = conf.lib.clang_CompileCommand_getNumArgs(self.
cmd)
2902 for i
in range(length):
2903 yield conf.lib.clang_CompileCommand_getArg(self.
cmd, i)
2907 CompileCommands is an iterable object containing all CompileCommand 2908 that can be used for building a specific file. 2914 conf.lib.clang_CompileCommands_dispose(self.
ccmds)
2917 return int(conf.lib.clang_CompileCommands_getSize(self.
ccmds))
2920 cc = conf.lib.clang_CompileCommands_getCommand(self.
ccmds, i)
2933 The CompilationDatabase is a wrapper class around 2934 clang::tooling::CompilationDatabase 2936 It enables querying how a specific source file can be built. 2940 conf.lib.clang_CompilationDatabase_dispose(self)
2946 "CompilationDatabase loading failed")
2951 """Builds a CompilationDatabase from the database found in buildDir""" 2952 errorCode = c_uint()
2954 cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
2956 except CompilationDatabaseError
as e:
2958 "CompilationDatabase loading failed")
2963 Get an iterable object providing all the CompileCommands available to 2964 build filename. Returns None if filename is not found in the database. 2966 return conf.lib.clang_CompilationDatabase_getCompileCommands(self,
2971 Get an iterable object providing all the CompileCommands available from 2974 return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self)
2978 """Represents a single token from the preprocessor. 2980 Tokens are effectively segments of source code. Source code is first parsed 2981 into tokens before being converted into the AST and Cursors. 2983 Tokens are obtained from parsed TranslationUnit instances. You currently 2984 can't create tokens manually. 2987 (
'int_data', c_uint * 4),
2988 (
'ptr_data', c_void_p)
2993 """The spelling of this token. 2995 This is the textual representation of the token in source. 2997 return conf.lib.clang_getTokenSpelling(self._tu, self)
3001 """Obtain the TokenKind of the current token.""" 3002 return TokenKind.from_value(conf.lib.clang_getTokenKind(self))
3006 """The SourceLocation this Token occurs at.""" 3007 return conf.lib.clang_getTokenLocation(self._tu, self)
3011 """The SourceRange this Token occupies.""" 3012 return conf.lib.clang_getTokenExtent(self._tu, self)
3016 """The Cursor this Token corresponds to.""" 3019 conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
3026 callbacks[
'translation_unit_includes'] = CFUNCTYPE(
None, c_object_p,
3027 POINTER(SourceLocation), c_uint, py_object)
3028 callbacks[
'cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
3029 callbacks[
'fields_visit'] = CFUNCTYPE(c_int, Cursor, py_object)
3033 (
"clang_annotateTokens",
3034 [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]),
3036 (
"clang_CompilationDatabase_dispose",
3039 (
"clang_CompilationDatabase_fromDirectory",
3040 [c_char_p, POINTER(c_uint)],
3042 CompilationDatabase.from_result),
3044 (
"clang_CompilationDatabase_getAllCompileCommands",
3047 CompileCommands.from_result),
3049 (
"clang_CompilationDatabase_getCompileCommands",
3050 [c_object_p, c_char_p],
3052 CompileCommands.from_result),
3054 (
"clang_CompileCommands_dispose",
3057 (
"clang_CompileCommands_getCommand",
3058 [c_object_p, c_uint],
3061 (
"clang_CompileCommands_getSize",
3065 (
"clang_CompileCommand_getArg",
3066 [c_object_p, c_uint],
3068 _CXString.from_result),
3070 (
"clang_CompileCommand_getDirectory",
3073 _CXString.from_result),
3075 (
"clang_CompileCommand_getFilename",
3078 _CXString.from_result),
3080 (
"clang_CompileCommand_getNumArgs",
3084 (
"clang_codeCompleteAt",
3085 [TranslationUnit, c_char_p, c_int, c_int, c_void_p, c_int, c_int],
3086 POINTER(CCRStructure)),
3088 (
"clang_codeCompleteGetDiagnostic",
3089 [CodeCompletionResults, c_int],
3092 (
"clang_codeCompleteGetNumDiagnostics",
3093 [CodeCompletionResults],
3096 (
"clang_createIndex",
3100 (
"clang_createTranslationUnit",
3104 (
"clang_CXXConstructor_isConvertingConstructor",
3108 (
"clang_CXXConstructor_isCopyConstructor",
3112 (
"clang_CXXConstructor_isDefaultConstructor",
3116 (
"clang_CXXConstructor_isMoveConstructor",
3120 (
"clang_CXXField_isMutable",
3124 (
"clang_CXXMethod_isConst",
3128 (
"clang_CXXMethod_isDefaulted",
3132 (
"clang_CXXMethod_isPureVirtual",
3136 (
"clang_CXXMethod_isStatic",
3140 (
"clang_CXXMethod_isVirtual",
3144 (
"clang_defaultDiagnosticDisplayOptions",
3148 (
"clang_defaultSaveOptions",
3152 (
"clang_disposeCodeCompleteResults",
3153 [CodeCompletionResults]),
3158 (
"clang_disposeDiagnostic",
3161 (
"clang_disposeIndex",
3164 (
"clang_disposeString",
3167 (
"clang_disposeTokens",
3168 [TranslationUnit, POINTER(Token), c_uint]),
3170 (
"clang_disposeTranslationUnit",
3173 (
"clang_equalCursors",
3177 (
"clang_equalLocations",
3178 [SourceLocation, SourceLocation],
3181 (
"clang_equalRanges",
3182 [SourceRange, SourceRange],
3185 (
"clang_equalTypes",
3189 (
"clang_formatDiagnostic",
3190 [Diagnostic, c_uint],
3193 (
"clang_getArgType",
3198 (
"clang_getArrayElementType",
3203 (
"clang_getArraySize",
3207 (
"clang_getFieldDeclBitWidth",
3211 (
"clang_getCanonicalCursor",
3214 Cursor.from_cursor_result),
3216 (
"clang_getCanonicalType",
3221 (
"clang_getChildDiagnostics",
3225 (
"clang_getCompletionAvailability",
3229 (
"clang_getCompletionBriefComment",
3233 (
"clang_getCompletionChunkCompletionString",
3237 (
"clang_getCompletionChunkKind",
3241 (
"clang_getCompletionChunkText",
3245 (
"clang_getCompletionPriority",
3249 (
"clang_getCString",
3254 [TranslationUnit, SourceLocation],
3257 (
"clang_getCursorDefinition",
3260 Cursor.from_result),
3262 (
"clang_getCursorDisplayName",
3265 _CXString.from_result),
3267 (
"clang_getCursorExtent",
3271 (
"clang_getCursorLexicalParent",
3274 Cursor.from_cursor_result),
3276 (
"clang_getCursorLocation",
3280 (
"clang_getCursorReferenced",
3283 Cursor.from_result),
3285 (
"clang_getCursorReferenceNameRange",
3286 [Cursor, c_uint, c_uint],
3289 (
"clang_getCursorSemanticParent",
3292 Cursor.from_cursor_result),
3294 (
"clang_getCursorSpelling",
3297 _CXString.from_result),
3299 (
"clang_getCursorType",
3304 (
"clang_getCursorUSR",
3307 _CXString.from_result),
3309 (
"clang_Cursor_getMangling",
3312 _CXString.from_result),
3318 (
"clang_getCXXAccessSpecifier",
3322 (
"clang_getDeclObjCTypeEncoding",
3325 _CXString.from_result),
3327 (
"clang_getDiagnostic",
3328 [c_object_p, c_uint],
3331 (
"clang_getDiagnosticCategory",
3335 (
"clang_getDiagnosticCategoryText",
3338 _CXString.from_result),
3340 (
"clang_getDiagnosticFixIt",
3341 [Diagnostic, c_uint, POINTER(SourceRange)],
3343 _CXString.from_result),
3345 (
"clang_getDiagnosticInSet",
3346 [c_object_p, c_uint],
3349 (
"clang_getDiagnosticLocation",
3353 (
"clang_getDiagnosticNumFixIts",
3357 (
"clang_getDiagnosticNumRanges",
3361 (
"clang_getDiagnosticOption",
3362 [Diagnostic, POINTER(_CXString)],
3364 _CXString.from_result),
3366 (
"clang_getDiagnosticRange",
3367 [Diagnostic, c_uint],
3370 (
"clang_getDiagnosticSeverity",
3374 (
"clang_getDiagnosticSpelling",
3377 _CXString.from_result),
3379 (
"clang_getElementType",
3384 (
"clang_getEnumConstantDeclUnsignedValue",
3388 (
"clang_getEnumConstantDeclValue",
3392 (
"clang_getEnumDeclIntegerType",
3398 [TranslationUnit, c_char_p],
3401 (
"clang_getFileName",
3405 (
"clang_getFileTime",
3409 (
"clang_getIBOutletCollectionType",
3414 (
"clang_getIncludedFile",
3417 File.from_cursor_result),
3419 (
"clang_getInclusions",
3420 [TranslationUnit, callbacks[
'translation_unit_includes'], py_object]),
3422 (
"clang_getInstantiationLocation",
3423 [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint),
3426 (
"clang_getLocation",
3427 [TranslationUnit, File, c_uint, c_uint],
3430 (
"clang_getLocationForOffset",
3431 [TranslationUnit, File, c_uint],
3434 (
"clang_getNullCursor",
3438 (
"clang_getNumArgTypes",
3442 (
"clang_getNumCompletionChunks",
3446 (
"clang_getNumDiagnostics",
3450 (
"clang_getNumDiagnosticsInSet",
3454 (
"clang_getNumElements",
3458 (
"clang_getNumOverloadedDecls",
3462 (
"clang_getOverloadedDecl",
3465 Cursor.from_cursor_result),
3467 (
"clang_getPointeeType",
3473 [SourceLocation, SourceLocation],
3476 (
"clang_getRangeEnd",
3480 (
"clang_getRangeStart",
3484 (
"clang_getResultType",
3489 (
"clang_getSpecializedCursorTemplate",
3492 Cursor.from_cursor_result),
3494 (
"clang_getTemplateCursorKind",
3498 (
"clang_getTokenExtent",
3499 [TranslationUnit, Token],
3502 (
"clang_getTokenKind",
3506 (
"clang_getTokenLocation",
3507 [TranslationUnit, Token],
3510 (
"clang_getTokenSpelling",
3511 [TranslationUnit, Token],
3513 _CXString.from_result),
3515 (
"clang_getTranslationUnitCursor",
3518 Cursor.from_result),
3520 (
"clang_getTranslationUnitSpelling",
3523 _CXString.from_result),
3525 (
"clang_getTUResourceUsageName",
3529 (
"clang_getTypeDeclaration",
3532 Cursor.from_result),
3534 (
"clang_getTypedefDeclUnderlyingType",
3539 (
"clang_getTypeKindSpelling",
3542 _CXString.from_result),
3544 (
"clang_getTypeSpelling",
3547 _CXString.from_result),
3549 (
"clang_hashCursor",
3553 (
"clang_isAttribute",
3557 (
"clang_isConstQualifiedType",
3561 (
"clang_isCursorDefinition",
3565 (
"clang_isDeclaration",
3569 (
"clang_isExpression",
3573 (
"clang_isFileMultipleIncludeGuarded",
3574 [TranslationUnit, File],
3577 (
"clang_isFunctionTypeVariadic",
3589 (
"clang_isPreprocessing",
3593 (
"clang_isReference",
3597 (
"clang_isRestrictQualifiedType",
3601 (
"clang_isStatement",
3605 (
"clang_isTranslationUnit",
3609 (
"clang_isUnexposed",
3613 (
"clang_isVirtualBase",
3617 (
"clang_isVolatileQualifiedType",
3621 (
"clang_parseTranslationUnit",
3622 [Index, c_char_p, c_void_p, c_int, c_void_p, c_int, c_int],
3625 (
"clang_reparseTranslationUnit",
3626 [TranslationUnit, c_int, c_void_p, c_int],
3629 (
"clang_saveTranslationUnit",
3630 [TranslationUnit, c_char_p, c_uint],
3634 [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]),
3636 (
"clang_visitChildren",
3637 [Cursor, callbacks[
'cursor_visit'], py_object],
3640 (
"clang_Cursor_getNumArguments",
3644 (
"clang_Cursor_getArgument",
3647 Cursor.from_result),
3649 (
"clang_Cursor_getNumTemplateArguments",
3653 (
"clang_Cursor_getTemplateArgumentKind",
3655 TemplateArgumentKind.from_id),
3657 (
"clang_Cursor_getTemplateArgumentType",
3662 (
"clang_Cursor_getTemplateArgumentValue",
3666 (
"clang_Cursor_getTemplateArgumentUnsignedValue",
3670 (
"clang_Cursor_isAnonymous",
3674 (
"clang_Cursor_isBitField",
3678 (
"clang_Cursor_getBriefCommentText",
3681 _CXString.from_result),
3683 (
"clang_Cursor_getRawCommentText",
3686 _CXString.from_result),
3688 (
"clang_Cursor_getOffsetOfField",
3692 (
"clang_Type_getAlignOf",
3696 (
"clang_Type_getClassType",
3701 (
"clang_Type_getOffsetOf",
3705 (
"clang_Type_getSizeOf",
3709 (
"clang_Type_getCXXRefQualifier",
3713 (
"clang_Type_getNamedType",
3718 (
"clang_Type_visitFields",
3719 [Type, callbacks[
'fields_visit'], py_object],
3735 except AttributeError
as e:
3736 msg =
str(e) +
". Please ensure that your python bindings are "\
3737 "compatible with your libclang.so version." 3743 func.argtypes = item[1]
3746 func.restype = item[2]
3749 func.errcheck = item[3]
3752 """Register function prototypes with a libclang library instance. 3754 This must be called as part of library instantiation so Python knows how 3755 to call out to the shared library. 3761 for f
in functionList:
3767 compatibility_check =
False 3772 """Set the path in which to search for libclang""" 3774 raise Exception(
"library path must be set before before using " \
3775 "any other functionalities in libclang.")
3777 Config.library_path = path
3781 """Set the exact location of libclang""" 3783 raise Exception(
"library file must be set before before using " \
3784 "any other functionalities in libclang.")
3786 Config.library_file = filename
3790 """ Perform compatibility check when loading libclang 3792 The python bindings are only tested and evaluated with the version of 3793 libclang they are provided with. To ensure correct behavior a (limited) 3794 compatibility check is performed when loading the bindings. This check 3795 will throw an exception, as soon as it fails. 3797 In case these bindings are used with an older version of libclang, parts 3798 that have been stable between releases may still work. Users of the 3799 python bindings can disable the compatibility check. This will cause 3800 the python bindings to load, even though they are written for a newer 3801 version of libclang. Failures now arise if unsupported or incompatible 3802 features are accessed. The user is required to test themselves if the 3803 features they are using are available and compatible between different 3807 raise Exception(
"compatibility_check must be set before before " \
3808 "using any other functionalities in libclang.")
3810 Config.compatibility_check = check_status
3816 Config.loaded =
True 3820 if Config.library_file:
3821 return Config.library_file
3824 name = platform.system()
3826 if name ==
'Darwin':
3827 file =
'libclang.dylib' 3828 elif name ==
'Windows':
3829 file =
'libclang.dll' 3831 file =
'libclang.so' 3833 if Config.library_path:
3834 file = Config.library_path +
'/' + file
3841 except OSError
as e:
3842 msg =
str(e) +
". To provide a path to libclang use " \
3843 "Config.set_library_path() or " \
3844 "Config.set_library_file()." 3852 except AttributeError:
3858 for name, value
in clang.enumerations.TokenKinds:
3859 TokenKind.register(value, name)
3866 'CodeCompletionResults',
3867 'CompilationDatabase',
3880 'TranslationUnitLoadError',
def get_location(self, filename, position)
def fromDirectory(buildDir)
def getAllCompileCommands(self)
def from_result(res, fn, args)
def get_tokens(self, locations=None, extent=None)
def codeComplete(self, path, line, column, unsaved_files=None, include_macros=False, include_code_patterns=False, include_brief_comments=False)
def reparse(self, unsaved_files=None, options=0)
object getattr(handle obj, handle name)
def isKindPlaceHolder(self)
def register_enumerations()
def get_template_argument_type(self, num)
def __init__(self, src, tgt, loc, depth)
def set_compatibility_check(check_status)
def is_restrict_qualified(self)
def from_result(res, fn, args)
def is_static_method(self)
def set_library_file(filename)
def is_const_method(self)
def from_location(tu, location)
def category_number(self)
def is_translation_unit(self)
def semantic_parent(self)
def __init__(self, value)
def __init__(self, value)
def isKindResultType(self)
def access_specifier(self)
def _get_instantiation(self)
def is_function_variadic(self)
auto format(const std::locale &loc, const CharT *fmt, const Streamable &tp) -> decltype(to_stream(std::declval< std::basic_ostream< CharT > &>(), fmt, tp), std::basic_string< CharT >
def underlying_typedef_type(self)
def is_mutable_field(self)
def get_bitfield_width(self)
def get_field_offsetof(self)
def from_result(res, fn, args)
def __getitem__(self, key)
def is_default_constructor(self)
def register(value, name)
def create(excludeDecls=False)
def is_virtual_method(self)
def register_functions(lib, ignore_errors)
def __init__(self, tu, memory, count)
def __init__(self, enumeration, message)
def get_ref_qualifier(self)
def register_function(lib, item, ignore_errors)
def parse(self, path, args=None, unsaved_files=None, options=0)
def from_position(tu, file, line, column)
return isinstance(obj, type)
def is_copy_constructor(self)
def __init__(self, enumeration, message)
def translation_unit(self)
def from_source(cls, filename, args=None, unsaved_files=None, options=0, index=None)
def __init__(self, range, value)
def get_offset(self, fieldname)
def __init__(self, completionString, key)
def __get__(self, instance, instance_type=None)
def get_tokens(tu, extent)
def from_locations(start, end)
def get_cindex_library(self)
def is_const_qualified(self)
def getCompileCommands(self, filename)
def from_cursor_result(res, fn, args)
def is_pure_virtual_method(self)
def get_num_template_arguments(self)
def __getitem__(self, key)
def isKindInformative(self)
def get_array_element_type(self)
def from_result(res, fn, args)
def is_default_method(self)
def get_template_argument_kind(self, num)
def get_file(self, filename)
const detail::type_info * type
def is_move_constructor(self)
def __init__(self, value, name)
def __init__(self, message)
def set_library_path(path)
def __init__(self, ccmds)
def isKindTypedText(self)
def objc_type_encoding(self)
def is_converting_constructor(self)
def __init__(self, wrapped)
iterator iter(handle obj)
T cast(const handle &handle)
def get_template_argument_unsigned_value(self, num)
def from_cursor_result(res, fn, args)
def is_volatile_qualified(self)
def __contains__(self, other)
def function_exists(self, name)
def __init__(self, cmd, ccmds)
def from_name(translation_unit, file_name)
void print(Args &&...args)
def translation_unit(self)
def from_result(res, fn, args)
void setattr(handle obj, handle name, handle value)
def get_declaration(self)
def from_ast_file(cls, filename, index=None)
std::string join(const T &v, std::string delim=",")
Simple function to join a string.
def is_preprocessing(self)
bool hasattr(handle obj, handle name)
def __init__(self, ptr, index)
def get_template_argument_value(self, num)
def from_offset(tu, file, offset)
def get_extent(self, filename, locations)