Scarab  2.8.1
Project 8 C++ Utility Library
cindex.py
Go to the documentation of this file.
1 #===- cindex.py - Python Indexing Library Bindings -----------*- python -*--===#
2 #
3 # The LLVM Compiler Infrastructure
4 #
5 # This file is distributed under the University of Illinois Open Source
6 # License. See LICENSE.TXT for details.
7 #
8 #===------------------------------------------------------------------------===#
9 
10 r"""
11 Clang Indexing Library Bindings
12 ===============================
13 
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
17 are:
18 
19  * string results are returned as Python strings, not CXString objects.
20 
21  * null cursors are translated to None.
22 
23  * access to child cursors is done via iteration, not visitation.
24 
25 The major indexing objects are:
26 
27  Index
28 
29  The top-level object which manages some global library state.
30 
31  TranslationUnit
32 
33  High-level object encapsulating the AST for a single translation unit. These
34  can be loaded from .ast files or parsed on the fly.
35 
36  Cursor
37 
38  Generic object for representing a node in the AST.
39 
40  SourceRange, SourceLocation, and File
41 
42  Objects representing information about the input source.
43 
44 Most object information is exposed using properties, when the underlying API
45 call is efficient.
46 """
47 
48 # TODO
49 # ====
50 #
51 # o API support for invalid translation units. Currently we can't even get the
52 # diagnostics on failure because they refer to locations in an object that
53 # will have been invalidated.
54 #
55 # o fix memory management issues (currently client must hold on to index and
56 # translation unit, or risk crashes).
57 #
58 # o expose code completion APIs.
59 #
60 # o cleanup ctypes wrapping, would be nice to separate the ctypes details more
61 # clearly, and hide from the external interface (i.e., help(cindex)).
62 #
63 # o implement additional SourceLocation, SourceRange, and File methods.
64 
65 from ctypes import *
66 import collections
67 
68 import clang.enumerations
69 
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)
75 
76 callbacks = {}
77 
78 
79 
80 class TranslationUnitLoadError(Exception):
81  """Represents an error that occurred when loading a TranslationUnit.
82 
83  This is raised in the case where a TranslationUnit could not be
84  instantiated due to failure in the libclang library.
85 
86  FIXME: Make libclang expose additional error information in this scenario.
87  """
88  pass
89 
90 class TranslationUnitSaveError(Exception):
91  """Represents an error that occurred when saving a TranslationUnit.
92 
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.
96  """
97 
98  # Indicates that an unknown error occurred. This typically indicates that
99  # I/O failed during save.
100  ERROR_UNKNOWN = 1
101 
102  # Indicates that errors during translation prevented saving. The errors
103  # should be available via the TranslationUnit's diagnostics.
104  ERROR_TRANSLATION_ERRORS = 2
105 
106  # Indicates that the translation unit was somehow invalid.
107  ERROR_INVALID_TU = 3
108 
109  def __init__(self, enumeration, message):
110  assert isinstance(enumeration, int)
111 
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)
116 
117  self.save_error = enumeration
118  Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
119 
120 
121 
122 class CachedProperty(object):
123  """Decorator that lazy-loads the value of a property.
124 
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.
128  """
129 
130  def __init__(self, wrapped):
131  self.wrapped = wrapped
132  try:
133  self.__doc__ = wrapped.__doc__
134  except:
135  pass
136 
137  def __get__(self, instance, instance_type=None):
138  if instance is None:
139  return self
140 
141  value = self.wrapped(instance)
142  setattr(instance, self.wrapped.__name__, value)
143 
144  return value
145 
146 
147 class _CXString(Structure):
148  """Helper for transforming CXString results."""
149 
150  _fields_ = [("spelling", c_char_p), ("free", c_int)]
151 
152  def __del__(self):
153  conf.lib.clang_disposeString(self)
154 
155  @staticmethod
156  def from_result(res, fn, args):
157  assert isinstance(res, _CXString)
158  return conf.lib.clang_getCString(res)
159 
160 class SourceLocation(Structure):
161  """
162  A SourceLocation represents a particular location within a source file.
163  """
164  _fields_ = [("ptr_data", c_void_p * 2), ("int_data", c_uint)]
165  _data = None
166 
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),
171  byref(c), byref(o))
172  if f:
173  f = File(f)
174  else:
175  f = None
176  self._data = (f, int(l.value), int(c.value), int(o.value))
177  return self._data
178 
179  @staticmethod
180  def from_position(tu, file, line, column):
181  """
182  Retrieve the source location associated with a given file/line/column in
183  a particular translation unit.
184  """
185  return conf.lib.clang_getLocation(tu, file, line, column)
186 
187  @staticmethod
188  def from_offset(tu, file, offset):
189  """Retrieve a SourceLocation from a given character offset.
190 
191  tu -- TranslationUnit file belongs to
192  file -- File instance to obtain offset from
193  offset -- Integer character offset within file
194  """
195  return conf.lib.clang_getLocationForOffset(tu, file, offset)
196 
197  @property
198  def file(self):
199  """Get the file represented by this source location."""
200  return self._get_instantiation()[0]
201 
202  @property
203  def line(self):
204  """Get the line represented by this source location."""
205  return self._get_instantiation()[1]
206 
207  @property
208  def column(self):
209  """Get the column represented by this source location."""
210  return self._get_instantiation()[2]
211 
212  @property
213  def offset(self):
214  """Get the file offset represented by this source location."""
215  return self._get_instantiation()[3]
216 
217  def __eq__(self, other):
218  return conf.lib.clang_equalLocations(self, other)
219 
220  def __ne__(self, other):
221  return not self.__eq__(other)
222 
223  def __repr__(self):
224  if self.file:
225  filename = self.file.name
226  else:
227  filename = None
228  return "<SourceLocation file %r, line %r, column %r>" % (
229  filename, self.line, self.column)
230 
231 class SourceRange(Structure):
232  """
233  A SourceRange describes a range of source locations within the source
234  code.
235  """
236  _fields_ = [
237  ("ptr_data", c_void_p * 2),
238  ("begin_int_data", c_uint),
239  ("end_int_data", c_uint)]
240 
241  # FIXME: Eliminate this and make normal constructor? Requires hiding ctypes
242  # object.
243  @staticmethod
244  def from_locations(start, end):
245  return conf.lib.clang_getRange(start, end)
246 
247  @property
248  def start(self):
249  """
250  Return a SourceLocation representing the first character within a
251  source range.
252  """
253  return conf.lib.clang_getRangeStart(self)
254 
255  @property
256  def end(self):
257  """
258  Return a SourceLocation representing the last character within a
259  source range.
260  """
261  return conf.lib.clang_getRangeEnd(self)
262 
263  def __eq__(self, other):
264  return conf.lib.clang_equalRanges(self, other)
265 
266  def __ne__(self, other):
267  return not self.__eq__(other)
268 
269  def __contains__(self, other):
270  """Useful to detect the Token/Lexer bug"""
271  if not isinstance(other, SourceLocation):
272  return False
273  if other.file is None and self.start.file is None:
274  pass
275  elif ( self.start.file.name != other.file.name or
276  other.file.name != self.end.file.name):
277  # same file name
278  return False
279  # same file, in between lines
280  if self.start.line < other.line < self.end.line:
281  return True
282  elif self.start.line == other.line:
283  # same file first line
284  if self.start.column <= other.column:
285  return True
286  elif other.line == self.end.line:
287  # same file last line
288  if other.column <= self.end.column:
289  return True
290  return False
291 
292  def __repr__(self):
293  return "<SourceRange start %r, end %r>" % (self.start, self.end)
294 
295 class Diagnostic(object):
296  """
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.
300  """
301 
302  Ignored = 0
303  Note = 1
304  Warning = 2
305  Error = 3
306  Fatal = 4
307 
308  def __init__(self, ptr):
309  self.ptr = ptr
310 
311  def __del__(self):
312  conf.lib.clang_disposeDiagnostic(self)
313 
314  @property
315  def severity(self):
316  return conf.lib.clang_getDiagnosticSeverity(self)
317 
318  @property
319  def location(self):
320  return conf.lib.clang_getDiagnosticLocation(self)
321 
322  @property
323  def spelling(self):
324  return conf.lib.clang_getDiagnosticSpelling(self)
325 
326  @property
327  def ranges(self):
328  class RangeIterator:
329  def __init__(self, diag):
330  self.diag = diag
331 
332  def __len__(self):
333  return int(conf.lib.clang_getDiagnosticNumRanges(self.diag))
334 
335  def __getitem__(self, key):
336  if (key >= len(self)):
337  raise IndexError
338  return conf.lib.clang_getDiagnosticRange(self.diag, key)
339 
340  return RangeIterator(self)
341 
342  @property
343  def fixits(self):
344  class FixItIterator:
345  def __init__(self, diag):
346  self.diag = diag
347 
348  def __len__(self):
349  return int(conf.lib.clang_getDiagnosticNumFixIts(self.diag))
350 
351  def __getitem__(self, key):
352  range = SourceRange()
353  value = conf.lib.clang_getDiagnosticFixIt(self.diag, key,
354  byref(range))
355  if len(value) == 0:
356  raise IndexError
357 
358  return FixIt(range, value)
359 
360  return FixItIterator(self)
361 
362  @property
363  def children(self):
364  class ChildDiagnosticsIterator:
365  def __init__(self, diag):
366  self.diag_set = conf.lib.clang_getChildDiagnostics(diag)
367 
368  def __len__(self):
369  return int(conf.lib.clang_getNumDiagnosticsInSet(self.diag_set))
370 
371  def __getitem__(self, key):
372  diag = conf.lib.clang_getDiagnosticInSet(self.diag_set, key)
373  if not diag:
374  raise IndexError
375  return Diagnostic(diag)
376 
377  return ChildDiagnosticsIterator(self)
378 
379  @property
380  def category_number(self):
381  """The category number for this diagnostic or 0 if unavailable."""
382  return conf.lib.clang_getDiagnosticCategory(self)
383 
384  @property
385  def category_name(self):
386  """The string name of the category for this diagnostic."""
387  return conf.lib.clang_getDiagnosticCategoryText(self)
388 
389  @property
390  def option(self):
391  """The command-line option that enables this diagnostic."""
392  return conf.lib.clang_getDiagnosticOption(self, None)
393 
394  @property
395  def disable_option(self):
396  """The command-line option that disables this diagnostic."""
397  disable = _CXString()
398  conf.lib.clang_getDiagnosticOption(self, byref(disable))
399 
400  return conf.lib.clang_getCString(disable)
401 
402  def __repr__(self):
403  return "<Diagnostic severity %r, location %r, spelling %r>" % (
404  self.severity, self.location, self.spelling)
405 
406  def from_param(self):
407  return self.ptr
408 
409 class FixIt(object):
410  """
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.
414  """
415 
416  def __init__(self, range, value):
417  self.range = range
418  self.value = value
419 
420  def __repr__(self):
421  return "<FixIt range %r, value %r>" % (self.range, self.value)
422 
423 class TokenGroup(object):
424  """Helper class to facilitate token management.
425 
426  Tokens are allocated from libclang in chunks. They must be disposed of as a
427  collective group.
428 
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.
434 
435  You should not instantiate this class outside of this module.
436  """
437  def __init__(self, tu, memory, count):
438  self._tu = tu
439  self._memory = memory
440  self._count = count
441 
442  def __del__(self):
443  conf.lib.clang_disposeTokens(self._tu, self._memory, self._count)
444 
445  @staticmethod
446  def get_tokens(tu, extent):
447  """Helper method to return all tokens in an extent.
448 
449  This functionality is needed multiple places in this module. We define
450  it here because it seems like a logical place.
451  """
452  tokens_memory = POINTER(Token)()
453  tokens_count = c_uint()
454 
455  conf.lib.clang_tokenize(tu, extent, byref(tokens_memory),
456  byref(tokens_count))
457 
458  count = int(tokens_count.value)
459 
460  # If we get no tokens, no memory was allocated. Be sure not to return
461  # anything and potentially call a destructor on nothing.
462  if count < 1:
463  return
464 
465  tokens_array = cast(tokens_memory, POINTER(Token * count)).contents
466 
467  token_group = TokenGroup(tu, tokens_memory, tokens_count)
468 
469  for i in range(0, count):
470  token = Token()
471  token.int_data = tokens_array[i].int_data
472  token.ptr_data = tokens_array[i].ptr_data
473  token._tu = tu
474  token._group = token_group
475 
476  yield token
477 
478 class TokenKind(object):
479  """Describes a specific type of a Token."""
480 
481  _value_map = {} # int -> TokenKind
482 
483  def __init__(self, value, name):
484  """Create a new TokenKind instance from a numeric value and a name."""
485  self.value = value
486  self.name = name
487 
488  def __repr__(self):
489  return 'TokenKind.%s' % (self.name,)
490 
491  @staticmethod
492  def from_value(value):
493  """Obtain a registered TokenKind instance from its value."""
494  result = TokenKind._value_map.get(value, None)
495 
496  if result is None:
497  raise ValueError('Unknown TokenKind: %d' % value)
498 
499  return result
500 
501  @staticmethod
502  def register(value, name):
503  """Register a new TokenKind enumeration.
504 
505  This should only be called at module load time by code within this
506  package.
507  """
508  if value in TokenKind._value_map:
509  raise ValueError('TokenKind already registered: %d' % value)
510 
511  kind = TokenKind(value, name)
512  TokenKind._value_map[value] = kind
513  setattr(TokenKind, name, kind)
514 
515 
516 class BaseEnumeration(object):
517  """
518  Common base class for named enumerations held in sync with Index.h values.
519 
520  Subclasses must define their own _kinds and _name_map members, as:
521  _kinds = []
522  _name_map = None
523  These values hold the per-subclass instances and value-to-name mappings,
524  respectively.
525 
526  """
527 
528  def __init__(self, value):
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))
534  self.value = value
535  self.__class__._kinds[value] = self
536  self.__class__._name_map = None
537 
538 
539  def from_param(self):
540  return self.value
541 
542  @property
543  def name(self):
544  """Get the enumeration name of this cursor kind."""
545  if self._name_map is None:
546  self._name_map = {}
547  for key, value in list(self.__class__.__dict__.items()):
548  if isinstance(value, self.__class__):
549  self._name_map[value] = key
550  return self._name_map[self]
551 
552  @classmethod
553  def from_id(cls, id):
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]
557 
558  def __repr__(self):
559  return '%s.%s' % (self.__class__, self.name,)
560 
561 
563  """
564  A CursorKind describes the kind of entity that a cursor points to.
565  """
566 
567  # The required BaseEnumeration declarations.
568  _kinds = []
569  _name_map = None
570 
571  @staticmethod
573  """Return all CursorKind enumeration instances."""
574  return [_f for _f in CursorKind._kinds if _f]
575 
576  def is_declaration(self):
577  """Test if this is a declaration kind."""
578  return conf.lib.clang_isDeclaration(self)
579 
580  def is_reference(self):
581  """Test if this is a reference kind."""
582  return conf.lib.clang_isReference(self)
583 
584  def is_expression(self):
585  """Test if this is an expression kind."""
586  return conf.lib.clang_isExpression(self)
587 
588  def is_statement(self):
589  """Test if this is a statement kind."""
590  return conf.lib.clang_isStatement(self)
591 
592  def is_attribute(self):
593  """Test if this is an attribute kind."""
594  return conf.lib.clang_isAttribute(self)
595 
596  def is_invalid(self):
597  """Test if this is an invalid kind."""
598  return conf.lib.clang_isInvalid(self)
599 
601  """Test if this is a translation unit kind."""
602  return conf.lib.clang_isTranslationUnit(self)
603 
604  def is_preprocessing(self):
605  """Test if this is a preprocessing kind."""
606  return conf.lib.clang_isPreprocessing(self)
607 
608  def is_unexposed(self):
609  """Test if this is an unexposed kind."""
610  return conf.lib.clang_isUnexposed(self)
611 
612  def __repr__(self):
613  return 'CursorKind.%s' % (self.name,)
614 
615 
617 
618 # A declaration whose specific kind is not exposed via this interface.
619 #
620 # Unexposed declarations have the same operations as any other kind of
621 # declaration; one can extract their location information, spelling, find their
622 # definitions, etc. However, the specific kind of the declaration is not
623 # reported.
624 CursorKind.UNEXPOSED_DECL = CursorKind(1)
625 
626 # A C or C++ struct.
627 CursorKind.STRUCT_DECL = CursorKind(2)
628 
629 # A C or C++ union.
630 CursorKind.UNION_DECL = CursorKind(3)
631 
632 # A C++ class.
633 CursorKind.CLASS_DECL = CursorKind(4)
634 
635 # An enumeration.
636 CursorKind.ENUM_DECL = CursorKind(5)
637 
638 # A field (in C) or non-static data member (in C++) in a struct, union, or C++
639 # class.
640 CursorKind.FIELD_DECL = CursorKind(6)
641 
642 # An enumerator constant.
643 CursorKind.ENUM_CONSTANT_DECL = CursorKind(7)
644 
645 # A function.
646 CursorKind.FUNCTION_DECL = CursorKind(8)
647 
648 # A variable.
649 CursorKind.VAR_DECL = CursorKind(9)
650 
651 # A function or method parameter.
652 CursorKind.PARM_DECL = CursorKind(10)
653 
654 # An Objective-C @interface.
655 CursorKind.OBJC_INTERFACE_DECL = CursorKind(11)
656 
657 # An Objective-C @interface for a category.
658 CursorKind.OBJC_CATEGORY_DECL = CursorKind(12)
659 
660 # An Objective-C @protocol declaration.
661 CursorKind.OBJC_PROTOCOL_DECL = CursorKind(13)
662 
663 # An Objective-C @property declaration.
664 CursorKind.OBJC_PROPERTY_DECL = CursorKind(14)
665 
666 # An Objective-C instance variable.
667 CursorKind.OBJC_IVAR_DECL = CursorKind(15)
668 
669 # An Objective-C instance method.
670 CursorKind.OBJC_INSTANCE_METHOD_DECL = CursorKind(16)
671 
672 # An Objective-C class method.
673 CursorKind.OBJC_CLASS_METHOD_DECL = CursorKind(17)
674 
675 # An Objective-C @implementation.
676 CursorKind.OBJC_IMPLEMENTATION_DECL = CursorKind(18)
677 
678 # An Objective-C @implementation for a category.
679 CursorKind.OBJC_CATEGORY_IMPL_DECL = CursorKind(19)
680 
681 # A typedef.
682 CursorKind.TYPEDEF_DECL = CursorKind(20)
683 
684 # A C++ class method.
685 CursorKind.CXX_METHOD = CursorKind(21)
686 
687 # A C++ namespace.
688 CursorKind.NAMESPACE = CursorKind(22)
689 
690 # A linkage specification, e.g. 'extern "C"'.
691 CursorKind.LINKAGE_SPEC = CursorKind(23)
692 
693 # A C++ constructor.
694 CursorKind.CONSTRUCTOR = CursorKind(24)
695 
696 # A C++ destructor.
697 CursorKind.DESTRUCTOR = CursorKind(25)
698 
699 # A C++ conversion function.
700 CursorKind.CONVERSION_FUNCTION = CursorKind(26)
701 
702 # A C++ template type parameter
703 CursorKind.TEMPLATE_TYPE_PARAMETER = CursorKind(27)
704 
705 # A C++ non-type template paramater.
706 CursorKind.TEMPLATE_NON_TYPE_PARAMETER = CursorKind(28)
707 
708 # A C++ template template parameter.
709 CursorKind.TEMPLATE_TEMPLATE_PARAMETER = CursorKind(29)
710 
711 # A C++ function template.
712 CursorKind.FUNCTION_TEMPLATE = CursorKind(30)
713 
714 # A C++ class template.
715 CursorKind.CLASS_TEMPLATE = CursorKind(31)
716 
717 # A C++ class template partial specialization.
718 CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION = CursorKind(32)
719 
720 # A C++ namespace alias declaration.
721 CursorKind.NAMESPACE_ALIAS = CursorKind(33)
722 
723 # A C++ using directive
724 CursorKind.USING_DIRECTIVE = CursorKind(34)
725 
726 # A C++ using declaration
727 CursorKind.USING_DECLARATION = CursorKind(35)
728 
729 # A Type alias decl.
730 CursorKind.TYPE_ALIAS_DECL = CursorKind(36)
731 
732 # A Objective-C synthesize decl
733 CursorKind.OBJC_SYNTHESIZE_DECL = CursorKind(37)
734 
735 # A Objective-C dynamic decl
736 CursorKind.OBJC_DYNAMIC_DECL = CursorKind(38)
737 
738 # A C++ access specifier decl.
739 CursorKind.CXX_ACCESS_SPEC_DECL = CursorKind(39)
740 
741 
742 
744 
745 CursorKind.OBJC_SUPER_CLASS_REF = CursorKind(40)
746 CursorKind.OBJC_PROTOCOL_REF = CursorKind(41)
747 CursorKind.OBJC_CLASS_REF = CursorKind(42)
748 
749 # A reference to a type declaration.
750 #
751 # A type reference occurs anywhere where a type is named but not
752 # declared. For example, given:
753 # typedef unsigned size_type;
754 # size_type size;
755 #
756 # The typedef is a declaration of size_type (CXCursor_TypedefDecl),
757 # while the type of the variable "size" is referenced. The cursor
758 # referenced by the type of size is the typedef for size_type.
759 CursorKind.TYPE_REF = CursorKind(43)
760 CursorKind.CXX_BASE_SPECIFIER = CursorKind(44)
761 
762 # A reference to a class template, function template, template
763 # template parameter, or class template partial specialization.
764 CursorKind.TEMPLATE_REF = CursorKind(45)
765 
766 # A reference to a namespace or namepsace alias.
767 CursorKind.NAMESPACE_REF = CursorKind(46)
768 
769 # A reference to a member of a struct, union, or class that occurs in
770 # some non-expression context, e.g., a designated initializer.
771 CursorKind.MEMBER_REF = CursorKind(47)
772 
773 # A reference to a labeled statement.
774 CursorKind.LABEL_REF = CursorKind(48)
775 
776 # A reference to a set of overloaded functions or function templates
777 # that has not yet been resolved to a specific function or function template.
778 CursorKind.OVERLOADED_DECL_REF = CursorKind(49)
779 
780 # A reference to a variable that occurs in some non-expression
781 # context, e.g., a C++ lambda capture list.
782 CursorKind.VARIABLE_REF = CursorKind(50)
783 
784 
786 
787 CursorKind.INVALID_FILE = CursorKind(70)
788 CursorKind.NO_DECL_FOUND = CursorKind(71)
789 CursorKind.NOT_IMPLEMENTED = CursorKind(72)
790 CursorKind.INVALID_CODE = CursorKind(73)
791 
792 
794 
795 # An expression whose specific kind is not exposed via this interface.
796 #
797 # Unexposed expressions have the same operations as any other kind of
798 # expression; one can extract their location information, spelling, children,
799 # etc. However, the specific kind of the expression is not reported.
800 CursorKind.UNEXPOSED_EXPR = CursorKind(100)
801 
802 # An expression that refers to some value declaration, such as a function,
803 # varible, or enumerator.
804 CursorKind.DECL_REF_EXPR = CursorKind(101)
805 
806 # An expression that refers to a member of a struct, union, class, Objective-C
807 # class, etc.
808 CursorKind.MEMBER_REF_EXPR = CursorKind(102)
809 
810 # An expression that calls a function.
811 CursorKind.CALL_EXPR = CursorKind(103)
812 
813 # An expression that sends a message to an Objective-C object or class.
814 CursorKind.OBJC_MESSAGE_EXPR = CursorKind(104)
815 
816 # An expression that represents a block literal.
817 CursorKind.BLOCK_EXPR = CursorKind(105)
818 
819 # An integer literal.
820 CursorKind.INTEGER_LITERAL = CursorKind(106)
821 
822 # A floating point number literal.
823 CursorKind.FLOATING_LITERAL = CursorKind(107)
824 
825 # An imaginary number literal.
826 CursorKind.IMAGINARY_LITERAL = CursorKind(108)
827 
828 # A string literal.
829 CursorKind.STRING_LITERAL = CursorKind(109)
830 
831 # A character literal.
832 CursorKind.CHARACTER_LITERAL = CursorKind(110)
833 
834 # A parenthesized expression, e.g. "(1)".
835 #
836 # This AST node is only formed if full location information is requested.
837 CursorKind.PAREN_EXPR = CursorKind(111)
838 
839 # This represents the unary-expression's (except sizeof and
840 # alignof).
841 CursorKind.UNARY_OPERATOR = CursorKind(112)
842 
843 # [C99 6.5.2.1] Array Subscripting.
844 CursorKind.ARRAY_SUBSCRIPT_EXPR = CursorKind(113)
845 
846 # A builtin binary operation expression such as "x + y" or
847 # "x <= y".
848 CursorKind.BINARY_OPERATOR = CursorKind(114)
849 
850 # Compound assignment such as "+=".
851 CursorKind.COMPOUND_ASSIGNMENT_OPERATOR = CursorKind(115)
852 
853 # The ?: ternary operator.
854 CursorKind.CONDITIONAL_OPERATOR = CursorKind(116)
855 
856 # An explicit cast in C (C99 6.5.4) or a C-style cast in C++
857 # (C++ [expr.cast]), which uses the syntax (Type)expr.
858 #
859 # For example: (int)f.
860 CursorKind.CSTYLE_CAST_EXPR = CursorKind(117)
861 
862 # [C99 6.5.2.5]
863 CursorKind.COMPOUND_LITERAL_EXPR = CursorKind(118)
864 
865 # Describes an C or C++ initializer list.
866 CursorKind.INIT_LIST_EXPR = CursorKind(119)
867 
868 # The GNU address of label extension, representing &&label.
869 CursorKind.ADDR_LABEL_EXPR = CursorKind(120)
870 
871 # This is the GNU Statement Expression extension: ({int X=4; X;})
872 CursorKind.StmtExpr = CursorKind(121)
873 
874 # Represents a C11 generic selection.
875 CursorKind.GENERIC_SELECTION_EXPR = CursorKind(122)
876 
877 # Implements the GNU __null extension, which is a name for a null
878 # pointer constant that has integral type (e.g., int or long) and is the same
879 # size and alignment as a pointer.
880 #
881 # The __null extension is typically only used by system headers, which define
882 # NULL as __null in C++ rather than using 0 (which is an integer that may not
883 # match the size of a pointer).
884 CursorKind.GNU_NULL_EXPR = CursorKind(123)
885 
886 # C++'s static_cast<> expression.
887 CursorKind.CXX_STATIC_CAST_EXPR = CursorKind(124)
888 
889 # C++'s dynamic_cast<> expression.
890 CursorKind.CXX_DYNAMIC_CAST_EXPR = CursorKind(125)
891 
892 # C++'s reinterpret_cast<> expression.
893 CursorKind.CXX_REINTERPRET_CAST_EXPR = CursorKind(126)
894 
895 # C++'s const_cast<> expression.
896 CursorKind.CXX_CONST_CAST_EXPR = CursorKind(127)
897 
898 # Represents an explicit C++ type conversion that uses "functional"
899 # notion (C++ [expr.type.conv]).
900 #
901 # Example:
902 # \code
903 # x = int(0.5);
904 # \endcode
905 CursorKind.CXX_FUNCTIONAL_CAST_EXPR = CursorKind(128)
906 
907 # A C++ typeid expression (C++ [expr.typeid]).
908 CursorKind.CXX_TYPEID_EXPR = CursorKind(129)
909 
910 # [C++ 2.13.5] C++ Boolean Literal.
911 CursorKind.CXX_BOOL_LITERAL_EXPR = CursorKind(130)
912 
913 # [C++0x 2.14.7] C++ Pointer Literal.
914 CursorKind.CXX_NULL_PTR_LITERAL_EXPR = CursorKind(131)
915 
916 # Represents the "this" expression in C++
917 CursorKind.CXX_THIS_EXPR = CursorKind(132)
918 
919 # [C++ 15] C++ Throw Expression.
920 #
921 # This handles 'throw' and 'throw' assignment-expression. When
922 # assignment-expression isn't present, Op will be null.
923 CursorKind.CXX_THROW_EXPR = CursorKind(133)
924 
925 # A new expression for memory allocation and constructor calls, e.g:
926 # "new CXXNewExpr(foo)".
927 CursorKind.CXX_NEW_EXPR = CursorKind(134)
928 
929 # A delete expression for memory deallocation and destructor calls,
930 # e.g. "delete[] pArray".
931 CursorKind.CXX_DELETE_EXPR = CursorKind(135)
932 
933 # Represents a unary expression.
934 CursorKind.CXX_UNARY_EXPR = CursorKind(136)
935 
936 # ObjCStringLiteral, used for Objective-C string literals i.e. "foo".
937 CursorKind.OBJC_STRING_LITERAL = CursorKind(137)
938 
939 # ObjCEncodeExpr, used for in Objective-C.
940 CursorKind.OBJC_ENCODE_EXPR = CursorKind(138)
941 
942 # ObjCSelectorExpr used for in Objective-C.
943 CursorKind.OBJC_SELECTOR_EXPR = CursorKind(139)
944 
945 # Objective-C's protocol expression.
946 CursorKind.OBJC_PROTOCOL_EXPR = CursorKind(140)
947 
948 # An Objective-C "bridged" cast expression, which casts between
949 # Objective-C pointers and C pointers, transferring ownership in the process.
950 #
951 # \code
952 # NSString *str = (__bridge_transfer NSString *)CFCreateString();
953 # \endcode
954 CursorKind.OBJC_BRIDGE_CAST_EXPR = CursorKind(141)
955 
956 # Represents a C++0x pack expansion that produces a sequence of
957 # expressions.
958 #
959 # A pack expansion expression contains a pattern (which itself is an
960 # expression) followed by an ellipsis. For example:
961 CursorKind.PACK_EXPANSION_EXPR = CursorKind(142)
962 
963 # Represents an expression that computes the length of a parameter
964 # pack.
965 CursorKind.SIZE_OF_PACK_EXPR = CursorKind(143)
966 
967 # Represents a C++ lambda expression that produces a local function
968 # object.
969 #
970 # \code
971 # void abssort(float *x, unsigned N) {
972 # std::sort(x, x + N,
973 # [](float a, float b) {
974 # return std::abs(a) < std::abs(b);
975 # });
976 # }
977 # \endcode
978 CursorKind.LAMBDA_EXPR = CursorKind(144)
979 
980 # Objective-c Boolean Literal.
981 CursorKind.OBJ_BOOL_LITERAL_EXPR = CursorKind(145)
982 
983 # Represents the "self" expression in a ObjC method.
984 CursorKind.OBJ_SELF_EXPR = CursorKind(146)
985 
986 
987 # A statement whose specific kind is not exposed via this interface.
988 #
989 # Unexposed statements have the same operations as any other kind of statement;
990 # one can extract their location information, spelling, children, etc. However,
991 # the specific kind of the statement is not reported.
992 CursorKind.UNEXPOSED_STMT = CursorKind(200)
993 
994 # A labelled statement in a function.
995 CursorKind.LABEL_STMT = CursorKind(201)
996 
997 # A compound statement
998 CursorKind.COMPOUND_STMT = CursorKind(202)
999 
1000 # A case statement.
1001 CursorKind.CASE_STMT = CursorKind(203)
1002 
1003 # A default statement.
1004 CursorKind.DEFAULT_STMT = CursorKind(204)
1005 
1006 # An if statement.
1007 CursorKind.IF_STMT = CursorKind(205)
1008 
1009 # A switch statement.
1010 CursorKind.SWITCH_STMT = CursorKind(206)
1011 
1012 # A while statement.
1013 CursorKind.WHILE_STMT = CursorKind(207)
1014 
1015 # A do statement.
1016 CursorKind.DO_STMT = CursorKind(208)
1017 
1018 # A for statement.
1019 CursorKind.FOR_STMT = CursorKind(209)
1020 
1021 # A goto statement.
1022 CursorKind.GOTO_STMT = CursorKind(210)
1023 
1024 # An indirect goto statement.
1025 CursorKind.INDIRECT_GOTO_STMT = CursorKind(211)
1026 
1027 # A continue statement.
1028 CursorKind.CONTINUE_STMT = CursorKind(212)
1029 
1030 # A break statement.
1031 CursorKind.BREAK_STMT = CursorKind(213)
1032 
1033 # A return statement.
1034 CursorKind.RETURN_STMT = CursorKind(214)
1035 
1036 # A GNU-style inline assembler statement.
1037 CursorKind.ASM_STMT = CursorKind(215)
1038 
1039 # Objective-C's overall @try-@catch-@finally statement.
1040 CursorKind.OBJC_AT_TRY_STMT = CursorKind(216)
1041 
1042 # Objective-C's @catch statement.
1043 CursorKind.OBJC_AT_CATCH_STMT = CursorKind(217)
1044 
1045 # Objective-C's @finally statement.
1046 CursorKind.OBJC_AT_FINALLY_STMT = CursorKind(218)
1047 
1048 # Objective-C's @throw statement.
1049 CursorKind.OBJC_AT_THROW_STMT = CursorKind(219)
1050 
1051 # Objective-C's @synchronized statement.
1052 CursorKind.OBJC_AT_SYNCHRONIZED_STMT = CursorKind(220)
1053 
1054 # Objective-C's autorealease pool statement.
1055 CursorKind.OBJC_AUTORELEASE_POOL_STMT = CursorKind(221)
1056 
1057 # Objective-C's for collection statement.
1058 CursorKind.OBJC_FOR_COLLECTION_STMT = CursorKind(222)
1059 
1060 # C++'s catch statement.
1061 CursorKind.CXX_CATCH_STMT = CursorKind(223)
1062 
1063 # C++'s try statement.
1064 CursorKind.CXX_TRY_STMT = CursorKind(224)
1065 
1066 # C++'s for (* : *) statement.
1067 CursorKind.CXX_FOR_RANGE_STMT = CursorKind(225)
1068 
1069 # Windows Structured Exception Handling's try statement.
1070 CursorKind.SEH_TRY_STMT = CursorKind(226)
1071 
1072 # Windows Structured Exception Handling's except statement.
1073 CursorKind.SEH_EXCEPT_STMT = CursorKind(227)
1074 
1075 # Windows Structured Exception Handling's finally statement.
1076 CursorKind.SEH_FINALLY_STMT = CursorKind(228)
1077 
1078 # A MS inline assembly statement extension.
1079 CursorKind.MS_ASM_STMT = CursorKind(229)
1080 
1081 # The null statement.
1082 CursorKind.NULL_STMT = CursorKind(230)
1083 
1084 # Adaptor class for mixing declarations with statements and expressions.
1085 CursorKind.DECL_STMT = CursorKind(231)
1086 
1087 # OpenMP parallel directive.
1088 CursorKind.OMP_PARALLEL_DIRECTIVE = CursorKind(232)
1089 
1090 # OpenMP SIMD directive.
1091 CursorKind.OMP_SIMD_DIRECTIVE = CursorKind(233)
1092 
1093 # OpenMP for directive.
1094 CursorKind.OMP_FOR_DIRECTIVE = CursorKind(234)
1095 
1096 # OpenMP sections directive.
1097 CursorKind.OMP_SECTIONS_DIRECTIVE = CursorKind(235)
1098 
1099 # OpenMP section directive.
1100 CursorKind.OMP_SECTION_DIRECTIVE = CursorKind(236)
1101 
1102 # OpenMP single directive.
1103 CursorKind.OMP_SINGLE_DIRECTIVE = CursorKind(237)
1104 
1105 # OpenMP parallel for directive.
1106 CursorKind.OMP_PARALLEL_FOR_DIRECTIVE = CursorKind(238)
1107 
1108 # OpenMP parallel sections directive.
1109 CursorKind.OMP_PARALLEL_SECTIONS_DIRECTIVE = CursorKind(239)
1110 
1111 # OpenMP task directive.
1112 CursorKind.OMP_TASK_DIRECTIVE = CursorKind(240)
1113 
1114 # OpenMP master directive.
1115 CursorKind.OMP_MASTER_DIRECTIVE = CursorKind(241)
1116 
1117 # OpenMP critical directive.
1118 CursorKind.OMP_CRITICAL_DIRECTIVE = CursorKind(242)
1119 
1120 # OpenMP taskyield directive.
1121 CursorKind.OMP_TASKYIELD_DIRECTIVE = CursorKind(243)
1122 
1123 # OpenMP barrier directive.
1124 CursorKind.OMP_BARRIER_DIRECTIVE = CursorKind(244)
1125 
1126 # OpenMP taskwait directive.
1127 CursorKind.OMP_TASKWAIT_DIRECTIVE = CursorKind(245)
1128 
1129 # OpenMP flush directive.
1130 CursorKind.OMP_FLUSH_DIRECTIVE = CursorKind(246)
1131 
1132 # Windows Structured Exception Handling's leave statement.
1133 CursorKind.SEH_LEAVE_STMT = CursorKind(247)
1134 
1135 # OpenMP ordered directive.
1136 CursorKind.OMP_ORDERED_DIRECTIVE = CursorKind(248)
1137 
1138 # OpenMP atomic directive.
1139 CursorKind.OMP_ATOMIC_DIRECTIVE = CursorKind(249)
1140 
1141 # OpenMP for SIMD directive.
1142 CursorKind.OMP_FOR_SIMD_DIRECTIVE = CursorKind(250)
1143 
1144 # OpenMP parallel for SIMD directive.
1145 CursorKind.OMP_PARALLELFORSIMD_DIRECTIVE = CursorKind(251)
1146 
1147 # OpenMP target directive.
1148 CursorKind.OMP_TARGET_DIRECTIVE = CursorKind(252)
1149 
1150 # OpenMP teams directive.
1151 CursorKind.OMP_TEAMS_DIRECTIVE = CursorKind(253)
1152 
1153 # OpenMP taskgroup directive.
1154 CursorKind.OMP_TASKGROUP_DIRECTIVE = CursorKind(254)
1155 
1156 # OpenMP cancellation point directive.
1157 CursorKind.OMP_CANCELLATION_POINT_DIRECTIVE = CursorKind(255)
1158 
1159 # OpenMP cancel directive.
1160 CursorKind.OMP_CANCEL_DIRECTIVE = CursorKind(256)
1161 
1162 # OpenMP target data directive.
1163 CursorKind.OMP_TARGET_DATA_DIRECTIVE = CursorKind(257)
1164 
1165 # OpenMP taskloop directive.
1166 CursorKind.OMP_TASK_LOOP_DIRECTIVE = CursorKind(258)
1167 
1168 # OpenMP taskloop simd directive.
1169 CursorKind.OMP_TASK_LOOP_SIMD_DIRECTIVE = CursorKind(259)
1170 
1171 # OpenMP distribute directive.
1172 CursorKind.OMP_DISTRIBUTE_DIRECTIVE = CursorKind(260)
1173 
1174 # OpenMP target enter data directive.
1175 CursorKind.OMP_TARGET_ENTER_DATA_DIRECTIVE = CursorKind(261)
1176 
1177 # OpenMP target exit data directive.
1178 CursorKind.OMP_TARGET_EXIT_DATA_DIRECTIVE = CursorKind(262)
1179 
1180 # OpenMP target parallel directive.
1181 CursorKind.OMP_TARGET_PARALLEL_DIRECTIVE = CursorKind(263)
1182 
1183 # OpenMP target parallel for directive.
1184 CursorKind.OMP_TARGET_PARALLELFOR_DIRECTIVE = CursorKind(264)
1185 
1186 # OpenMP target update directive.
1187 CursorKind.OMP_TARGET_UPDATE_DIRECTIVE = CursorKind(265)
1188 
1189 # OpenMP distribute parallel for directive.
1190 CursorKind.OMP_DISTRIBUTE_PARALLELFOR_DIRECTIVE = CursorKind(266)
1191 
1192 # OpenMP distribute parallel for simd directive.
1193 CursorKind.OMP_DISTRIBUTE_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(267)
1194 
1195 # OpenMP distribute simd directive.
1196 CursorKind.OMP_DISTRIBUTE_SIMD_DIRECTIVE = CursorKind(268)
1197 
1198 # OpenMP target parallel for simd directive.
1199 CursorKind.OMP_TARGET_PARALLEL_FOR_SIMD_DIRECTIVE = CursorKind(269)
1200 
1201 # OpenMP target simd directive.
1202 CursorKind.OMP_TARGET_SIMD_DIRECTIVE = CursorKind(270)
1203 
1204 # OpenMP teams distribute directive.
1205 CursorKind.OMP_TEAMS_DISTRIBUTE_DIRECTIVE = CursorKind(271)
1206 
1207 
1209 
1210 # Cursor that represents the translation unit itself.
1211 #
1212 # The translation unit cursor exists primarily to act as the root cursor for
1213 # traversing the contents of a translation unit.
1214 CursorKind.TRANSLATION_UNIT = CursorKind(300)
1215 
1216 
1218 
1219 # An attribute whoe specific kind is note exposed via this interface
1220 CursorKind.UNEXPOSED_ATTR = CursorKind(400)
1221 
1222 CursorKind.IB_ACTION_ATTR = CursorKind(401)
1223 CursorKind.IB_OUTLET_ATTR = CursorKind(402)
1224 CursorKind.IB_OUTLET_COLLECTION_ATTR = CursorKind(403)
1225 
1226 CursorKind.CXX_FINAL_ATTR = CursorKind(404)
1227 CursorKind.CXX_OVERRIDE_ATTR = CursorKind(405)
1228 CursorKind.ANNOTATE_ATTR = CursorKind(406)
1229 CursorKind.ASM_LABEL_ATTR = CursorKind(407)
1230 CursorKind.PACKED_ATTR = CursorKind(408)
1231 CursorKind.PURE_ATTR = CursorKind(409)
1232 CursorKind.CONST_ATTR = CursorKind(410)
1233 CursorKind.NODUPLICATE_ATTR = CursorKind(411)
1234 CursorKind.CUDACONSTANT_ATTR = CursorKind(412)
1235 CursorKind.CUDADEVICE_ATTR = CursorKind(413)
1236 CursorKind.CUDAGLOBAL_ATTR = CursorKind(414)
1237 CursorKind.CUDAHOST_ATTR = CursorKind(415)
1238 CursorKind.CUDASHARED_ATTR = CursorKind(416)
1239 
1240 CursorKind.VISIBILITY_ATTR = CursorKind(417)
1241 
1242 CursorKind.DLLEXPORT_ATTR = CursorKind(418)
1243 CursorKind.DLLIMPORT_ATTR = CursorKind(419)
1244 
1245 
1247 CursorKind.PREPROCESSING_DIRECTIVE = CursorKind(500)
1248 CursorKind.MACRO_DEFINITION = CursorKind(501)
1249 CursorKind.MACRO_INSTANTIATION = CursorKind(502)
1250 CursorKind.INCLUSION_DIRECTIVE = CursorKind(503)
1251 
1252 
1254 
1255 # A module import declaration.
1256 CursorKind.MODULE_IMPORT_DECL = CursorKind(600)
1257 # A type alias template declaration
1258 CursorKind.TYPE_ALIAS_TEMPLATE_DECL = CursorKind(601)
1259 # A static_assert or _Static_assert node
1260 CursorKind.STATIC_ASSERT = CursorKind(602)
1261 # A friend declaration
1262 CursorKind.FRIEND_DECL = CursorKind(603)
1263 
1264 # A code completion overload candidate.
1265 CursorKind.OVERLOAD_CANDIDATE = CursorKind(700)
1266 
1267 
1269  """
1270  A TemplateArgumentKind describes the kind of entity that a template argument
1271  represents.
1272  """
1273 
1274  # The required BaseEnumeration declarations.
1275  _kinds = []
1276  _name_map = None
1277 
1278 TemplateArgumentKind.NULL = TemplateArgumentKind(0)
1279 TemplateArgumentKind.TYPE = TemplateArgumentKind(1)
1280 TemplateArgumentKind.DECLARATION = TemplateArgumentKind(2)
1281 TemplateArgumentKind.NULLPTR = TemplateArgumentKind(3)
1282 TemplateArgumentKind.INTEGRAL = TemplateArgumentKind(4)
1283 
1284 
1285 
1286 class Cursor(Structure):
1287  """
1288  The Cursor class represents a reference to an element within the AST. It
1289  acts as a kind of iterator.
1290  """
1291  _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
1292 
1293  @staticmethod
1294  def from_location(tu, location):
1295  # We store a reference to the TU in the instance so the TU won't get
1296  # collected before the cursor.
1297  cursor = conf.lib.clang_getCursor(tu, location)
1298  cursor._tu = tu
1299 
1300  return cursor
1301 
1302  def __eq__(self, other):
1303  return conf.lib.clang_equalCursors(self, other)
1304 
1305  def __ne__(self, other):
1306  return not self.__eq__(other)
1307 
1308  def is_definition(self):
1309  """
1310  Returns true if the declaration pointed at by the cursor is also a
1311  definition of that entity.
1312  """
1313  return conf.lib.clang_isCursorDefinition(self)
1314 
1315  def is_const_method(self):
1316  """Returns True if the cursor refers to a C++ member function or member
1317  function template that is declared 'const'.
1318  """
1319  return conf.lib.clang_CXXMethod_isConst(self)
1320 
1322  """Returns True if the cursor refers to a C++ converting constructor.
1323  """
1324  return conf.lib.clang_CXXConstructor_isConvertingConstructor(self)
1325 
1327  """Returns True if the cursor refers to a C++ copy constructor.
1328  """
1329  return conf.lib.clang_CXXConstructor_isCopyConstructor(self)
1330 
1332  """Returns True if the cursor refers to a C++ default constructor.
1333  """
1334  return conf.lib.clang_CXXConstructor_isDefaultConstructor(self)
1335 
1337  """Returns True if the cursor refers to a C++ move constructor.
1338  """
1339  return conf.lib.clang_CXXConstructor_isMoveConstructor(self)
1340 
1342  """Returns True if the cursor refers to a C++ member function or member
1343  function template that is declared '= default'.
1344  """
1345  return conf.lib.clang_CXXMethod_isDefaulted(self)
1346 
1347  def is_mutable_field(self):
1348  """Returns True if the cursor refers to a C++ field that is declared
1349  'mutable'.
1350  """
1351  return conf.lib.clang_CXXField_isMutable(self)
1352 
1354  """Returns True if the cursor refers to a C++ member function or member
1355  function template that is declared pure virtual.
1356  """
1357  return conf.lib.clang_CXXMethod_isPureVirtual(self)
1358 
1359  def is_static_method(self):
1360  """Returns True if the cursor refers to a C++ member function or member
1361  function template that is declared 'static'.
1362  """
1363  return conf.lib.clang_CXXMethod_isStatic(self)
1364 
1366  """Returns True if the cursor refers to a C++ member function or member
1367  function template that is declared 'virtual'.
1368  """
1369  return conf.lib.clang_CXXMethod_isVirtual(self)
1370 
1371  def get_definition(self):
1372  """
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
1375  entity.
1376  """
1377  # TODO: Should probably check that this is either a reference or
1378  # declaration prior to issuing the lookup.
1379  return conf.lib.clang_getCursorDefinition(self)
1380 
1381  def get_usr(self):
1382  """Return the Unified Symbol Resultion (USR) for the entity referenced
1383  by the given cursor (or None).
1384 
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)
1391 
1392  @property
1393  def kind(self):
1394  """Return the kind of this cursor."""
1395  return CursorKind.from_id(self._kind_id)
1396 
1397  @property
1398  def spelling(self):
1399  """Return the spelling of the entity pointed at by the cursor."""
1400  if not hasattr(self, '_spelling'):
1401  self._spelling = conf.lib.clang_getCursorSpelling(self)
1402 
1403  return self._spelling
1404 
1405  @property
1406  def displayname(self):
1407  """
1408  Return the display name for the entity referenced by this cursor.
1409 
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.
1413  """
1414  if not hasattr(self, '_displayname'):
1415  self._displayname = conf.lib.clang_getCursorDisplayName(self)
1416 
1417  return self._displayname
1418 
1419  @property
1420  def mangled_name(self):
1421  """Return the mangled name for the entity referenced by this cursor."""
1422  if not hasattr(self, '_mangled_name'):
1423  self._mangled_name = conf.lib.clang_Cursor_getMangling(self)
1424 
1425  return self._mangled_name
1426 
1427  @property
1428  def location(self):
1429  """
1430  Return the source location (the starting character) of the entity
1431  pointed at by the cursor.
1432  """
1433  if not hasattr(self, '_loc'):
1434  self._loc = conf.lib.clang_getCursorLocation(self)
1435 
1436  return self._loc
1437 
1438  @property
1439  def extent(self):
1440  """
1441  Return the source range (the range of text) occupied by the entity
1442  pointed at by the cursor.
1443  """
1444  if not hasattr(self, '_extent'):
1445  self._extent = conf.lib.clang_getCursorExtent(self)
1446 
1447  return self._extent
1448 
1449  @property
1450  def storage_class(self):
1451  """
1452  Retrieves the storage class (if any) of the entity pointed at by the
1453  cursor.
1454  """
1455  if not hasattr(self, '_storage_class'):
1456  self._storage_class = conf.lib.clang_Cursor_getStorageClass(self)
1457 
1458  return StorageClass.from_id(self._storage_class)
1459 
1460  @property
1461  def access_specifier(self):
1462  """
1463  Retrieves the access specifier (if any) of the entity pointed at by the
1464  cursor.
1465  """
1466  if not hasattr(self, '_access_specifier'):
1467  self._access_specifier = conf.lib.clang_getCXXAccessSpecifier(self)
1468 
1469  return AccessSpecifier.from_id(self._access_specifier)
1470 
1471  @property
1472  def type(self):
1473  """
1474  Retrieve the Type (if any) of the entity pointed at by the cursor.
1475  """
1476  if not hasattr(self, '_type'):
1477  self._type = conf.lib.clang_getCursorType(self)
1478 
1479  return self._type
1480 
1481  @property
1482  def canonical(self):
1483  """Return the canonical Cursor corresponding to this Cursor.
1484 
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.
1489  """
1490  if not hasattr(self, '_canonical'):
1491  self._canonical = conf.lib.clang_getCanonicalCursor(self)
1492 
1493  return self._canonical
1494 
1495  @property
1496  def result_type(self):
1497  """Retrieve the Type of the result for this Cursor."""
1498  if not hasattr(self, '_result_type'):
1499  self._result_type = conf.lib.clang_getResultType(self.type)
1500 
1501  return self._result_type
1502 
1503  @property
1505  """Return the underlying type of a typedef declaration.
1506 
1507  Returns a Type for the typedef this cursor is a declaration for. If
1508  the current cursor is not a typedef, this raises.
1509  """
1510  if not hasattr(self, '_underlying_type'):
1511  assert self.kind.is_declaration()
1513  conf.lib.clang_getTypedefDeclUnderlyingType(self)
1514 
1515  return self._underlying_type
1516 
1517  @property
1518  def enum_type(self):
1519  """Return the integer type of an enum declaration.
1520 
1521  Returns a Type corresponding to an integer. If the cursor is not for an
1522  enum, this raises.
1523  """
1524  if not hasattr(self, '_enum_type'):
1525  assert self.kind == CursorKind.ENUM_DECL
1526  self._enum_type = conf.lib.clang_getEnumDeclIntegerType(self)
1527 
1528  return self._enum_type
1529 
1530  @property
1531  def enum_value(self):
1532  """Return the value of an enum constant."""
1533  if not hasattr(self, '_enum_value'):
1534  assert self.kind == CursorKind.ENUM_CONSTANT_DECL
1535  # Figure out the underlying type of the enum to know if it
1536  # is a signed or unsigned quantity.
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,
1541  TypeKind.UCHAR,
1542  TypeKind.CHAR16,
1543  TypeKind.CHAR32,
1544  TypeKind.USHORT,
1545  TypeKind.UINT,
1546  TypeKind.ULONG,
1547  TypeKind.ULONGLONG,
1548  TypeKind.UINT128):
1549  self._enum_value = \
1550  conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
1551  else:
1552  self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self)
1553  return self._enum_value
1554 
1555  @property
1557  """Return the Objective-C type encoding as a str."""
1558  if not hasattr(self, '_objc_type_encoding'):
1560  conf.lib.clang_getDeclObjCTypeEncoding(self)
1561 
1562  return self._objc_type_encoding
1563 
1564  @property
1565  def hash(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)
1569 
1570  return self._hash
1571 
1572  @property
1573  def semantic_parent(self):
1574  """Return the semantic parent for this cursor."""
1575  if not hasattr(self, '_semantic_parent'):
1576  self._semantic_parent = conf.lib.clang_getCursorSemanticParent(self)
1577 
1578  return self._semantic_parent
1579 
1580  @property
1581  def lexical_parent(self):
1582  """Return the lexical parent for this cursor."""
1583  if not hasattr(self, '_lexical_parent'):
1584  self._lexical_parent = conf.lib.clang_getCursorLexicalParent(self)
1585 
1586  return self._lexical_parent
1587 
1588  @property
1589  def translation_unit(self):
1590  """Returns the TranslationUnit to which this Cursor belongs."""
1591  # If this triggers an AttributeError, the instance was not properly
1592  # created.
1593  return self._tu
1594 
1595  @property
1596  def referenced(self):
1597  """
1598  For a cursor that is a reference, returns a cursor
1599  representing the entity that it references.
1600  """
1601  if not hasattr(self, '_referenced'):
1602  self._referenced = conf.lib.clang_getCursorReferenced(self)
1603 
1604  return self._referenced
1605 
1606  @property
1607  def brief_comment(self):
1608  """Returns the brief comment text associated with that Cursor"""
1609  return conf.lib.clang_Cursor_getBriefCommentText(self)
1610 
1611  @property
1612  def raw_comment(self):
1613  """Returns the raw comment text associated with that Cursor"""
1614  return conf.lib.clang_Cursor_getRawCommentText(self)
1615 
1616  def get_arguments(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)
1621 
1623  """Returns the number of template args associated with this cursor."""
1624  return conf.lib.clang_Cursor_getNumTemplateArguments(self)
1625 
1627  """Returns the TemplateArgumentKind for the indicated template
1628  argument."""
1629  return conf.lib.clang_Cursor_getTemplateArgumentKind(self, num)
1630 
1632  """Returns the CXType for the indicated template argument."""
1633  return conf.lib.clang_Cursor_getTemplateArgumentType(self, num)
1634 
1636  """Returns the value of the indicated arg as a signed 64b integer."""
1637  return conf.lib.clang_Cursor_getTemplateArgumentValue(self, num)
1638 
1640  """Returns the value of the indicated arg as an unsigned 64b integer."""
1641  return conf.lib.clang_Cursor_getTemplateArgumentUnsignedValue(self, num)
1642 
1643  def get_children(self):
1644  """Return an iterator for accessing the children of this cursor."""
1645 
1646  # FIXME: Expose iteration from CIndex, PR6125.
1647  def visitor(child, parent, children):
1648  # FIXME: Document this assertion in API.
1649  # FIXME: There should just be an isNull method.
1650  assert child != conf.lib.clang_getNullCursor()
1651 
1652  # Create reference to TU so it isn't GC'd before Cursor.
1653  child._tu = self._tu
1654  children.append(child)
1655  return 1 # continue
1656  children = []
1657  conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
1658  children)
1659  return iter(children)
1660 
1661  def walk_preorder(self):
1662  """Depth-first preorder walk over the cursor and its descendants.
1663 
1664  Yields cursors.
1665  """
1666  yield self
1667  for child in self.get_children():
1668  for descendant in child.walk_preorder():
1669  yield descendant
1670 
1671  def get_tokens(self):
1672  """Obtain Token instances formulating that compose this Cursor.
1673 
1674  This is a generator for Token instances. It returns all tokens which
1675  occupy the extent this cursor occupies.
1676  """
1677  return TokenGroup.get_tokens(self._tu, self.extent)
1678 
1680  """Returns the offsetof the FIELD_DECL pointed by this Cursor."""
1681  return conf.lib.clang_Cursor_getOffsetOfField(self)
1682 
1683  def is_anonymous(self):
1684  """
1685  Check if the record is anonymous.
1686  """
1687  if self.kind == CursorKind.FIELD_DECL:
1688  return self.type.get_declaration().is_anonymous()
1689  return conf.lib.clang_Cursor_isAnonymous(self)
1690 
1691  def is_bitfield(self):
1692  """
1693  Check if the field is a bitfield.
1694  """
1695  return conf.lib.clang_Cursor_isBitField(self)
1696 
1698  """
1699  Retrieve the width of a bitfield.
1700  """
1701  return conf.lib.clang_getFieldDeclBitWidth(self)
1702 
1703  @staticmethod
1704  def from_result(res, fn, args):
1705  assert isinstance(res, Cursor)
1706  # FIXME: There should just be an isNull method.
1707  if res == conf.lib.clang_getNullCursor():
1708  return None
1709 
1710  # Store a reference to the TU in the Python object so it won't get GC'd
1711  # before the Cursor.
1712  tu = None
1713  for arg in args:
1714  if isinstance(arg, TranslationUnit):
1715  tu = arg
1716  break
1717 
1718  if hasattr(arg, 'translation_unit'):
1719  tu = arg.translation_unit
1720  break
1721 
1722  assert tu is not None
1723 
1724  res._tu = tu
1725  return res
1726 
1727  @staticmethod
1728  def from_cursor_result(res, fn, args):
1729  assert isinstance(res, Cursor)
1730  if res == conf.lib.clang_getNullCursor():
1731  return None
1732 
1733  res._tu = args[0]._tu
1734  return res
1735 
1736 class StorageClass(object):
1737  """
1738  Describes the storage class of a declaration
1739  """
1740 
1741  # The unique kind objects, index by id.
1742  _kinds = []
1743  _name_map = None
1744 
1745  def __init__(self, value):
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')
1750  self.value = value
1751  StorageClass._kinds[value] = self
1752  StorageClass._name_map = None
1753 
1754  def from_param(self):
1755  return self.value
1756 
1757  @property
1758  def name(self):
1759  """Get the enumeration name of this storage class."""
1760  if self._name_map is None:
1761  self._name_map = {}
1762  for key,value in list(StorageClass.__dict__.items()):
1763  if isinstance(value,StorageClass):
1764  self._name_map[value] = key
1765  return self._name_map[self]
1766 
1767  @staticmethod
1768  def from_id(id):
1769  if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]:
1770  raise ValueError('Unknown storage class %d' % id)
1771  return StorageClass._kinds[id]
1772 
1773  def __repr__(self):
1774  return 'StorageClass.%s' % (self.name,)
1775 
1776 StorageClass.INVALID = StorageClass(0)
1777 StorageClass.NONE = StorageClass(1)
1778 StorageClass.EXTERN = StorageClass(2)
1779 StorageClass.STATIC = StorageClass(3)
1780 StorageClass.PRIVATEEXTERN = StorageClass(4)
1781 StorageClass.OPENCLWORKGROUPLOCAL = StorageClass(5)
1782 StorageClass.AUTO = StorageClass(6)
1783 StorageClass.REGISTER = StorageClass(7)
1784 
1785 
1786 
1787 
1789  """
1790  Describes the access of a C++ class member
1791  """
1792 
1793  # The unique kind objects, index by id.
1794  _kinds = []
1795  _name_map = None
1796 
1797  def from_param(self):
1798  return self.value
1799 
1800  def __repr__(self):
1801  return 'AccessSpecifier.%s' % (self.name,)
1802 
1803 AccessSpecifier.INVALID = AccessSpecifier(0)
1804 AccessSpecifier.PUBLIC = AccessSpecifier(1)
1805 AccessSpecifier.PROTECTED = AccessSpecifier(2)
1806 AccessSpecifier.PRIVATE = AccessSpecifier(3)
1807 AccessSpecifier.NONE = AccessSpecifier(4)
1808 
1809 
1810 
1812  """
1813  Describes the kind of type.
1814  """
1815 
1816  # The unique kind objects, indexed by id.
1817  _kinds = []
1818  _name_map = None
1819 
1820  @property
1821  def spelling(self):
1822  """Retrieve the spelling of this TypeKind."""
1823  return conf.lib.clang_getTypeKindSpelling(self.value)
1824 
1825  def __repr__(self):
1826  return 'TypeKind.%s' % (self.name,)
1827 
1828 TypeKind.INVALID = TypeKind(0)
1829 TypeKind.UNEXPOSED = TypeKind(1)
1830 TypeKind.VOID = TypeKind(2)
1831 TypeKind.BOOL = TypeKind(3)
1832 TypeKind.CHAR_U = TypeKind(4)
1833 TypeKind.UCHAR = TypeKind(5)
1834 TypeKind.CHAR16 = TypeKind(6)
1835 TypeKind.CHAR32 = TypeKind(7)
1836 TypeKind.USHORT = TypeKind(8)
1837 TypeKind.UINT = TypeKind(9)
1838 TypeKind.ULONG = TypeKind(10)
1839 TypeKind.ULONGLONG = TypeKind(11)
1840 TypeKind.UINT128 = TypeKind(12)
1841 TypeKind.CHAR_S = TypeKind(13)
1842 TypeKind.SCHAR = TypeKind(14)
1843 TypeKind.WCHAR = TypeKind(15)
1844 TypeKind.SHORT = TypeKind(16)
1845 TypeKind.INT = TypeKind(17)
1846 TypeKind.LONG = TypeKind(18)
1847 TypeKind.LONGLONG = TypeKind(19)
1848 TypeKind.INT128 = TypeKind(20)
1849 TypeKind.FLOAT = TypeKind(21)
1850 TypeKind.DOUBLE = TypeKind(22)
1851 TypeKind.LONGDOUBLE = TypeKind(23)
1852 TypeKind.NULLPTR = TypeKind(24)
1853 TypeKind.OVERLOAD = TypeKind(25)
1854 TypeKind.DEPENDENT = TypeKind(26)
1855 TypeKind.OBJCID = TypeKind(27)
1856 TypeKind.OBJCCLASS = TypeKind(28)
1857 TypeKind.OBJCSEL = TypeKind(29)
1858 TypeKind.FLOAT128 = TypeKind(30)
1859 TypeKind.HALF = TypeKind(31)
1860 TypeKind.COMPLEX = TypeKind(100)
1861 TypeKind.POINTER = TypeKind(101)
1862 TypeKind.BLOCKPOINTER = TypeKind(102)
1863 TypeKind.LVALUEREFERENCE = TypeKind(103)
1864 TypeKind.RVALUEREFERENCE = TypeKind(104)
1865 TypeKind.RECORD = TypeKind(105)
1866 TypeKind.ENUM = TypeKind(106)
1867 TypeKind.TYPEDEF = TypeKind(107)
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)
1873 TypeKind.VECTOR = TypeKind(113)
1874 TypeKind.INCOMPLETEARRAY = TypeKind(114)
1875 TypeKind.VARIABLEARRAY = TypeKind(115)
1876 TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116)
1877 TypeKind.MEMBERPOINTER = TypeKind(117)
1878 TypeKind.AUTO = TypeKind(118)
1879 TypeKind.ELABORATED = TypeKind(119)
1880 
1882  """Describes a specific ref-qualifier of a type."""
1883 
1884  # The unique kind objects, indexed by id.
1885  _kinds = []
1886  _name_map = None
1887 
1888  def from_param(self):
1889  return self.value
1890 
1891  def __repr__(self):
1892  return 'RefQualifierKind.%s' % (self.name,)
1893 
1894 RefQualifierKind.NONE = RefQualifierKind(0)
1895 RefQualifierKind.LVALUE = RefQualifierKind(1)
1896 RefQualifierKind.RVALUE = RefQualifierKind(2)
1897 
1898 class Type(Structure):
1899  """
1900  The type of an element in the abstract syntax tree.
1901  """
1902  _fields_ = [("_kind_id", c_int), ("data", c_void_p * 2)]
1903 
1904  @property
1905  def kind(self):
1906  """Return the kind of this type."""
1907  return TypeKind.from_id(self._kind_id)
1908 
1909  def argument_types(self):
1910  """Retrieve a container for the non-variadic arguments for this type.
1911 
1912  The returned object is iterable and indexable. Each item in the
1913  container is a Type instance.
1914  """
1915  class ArgumentsIterator(collections.Sequence):
1916  def __init__(self, parent):
1917  self.parent = parent
1918  self.length = None
1919 
1920  def __len__(self):
1921  if self.length is None:
1922  self.length = conf.lib.clang_getNumArgTypes(self.parent)
1923 
1924  return self.length
1925 
1926  def __getitem__(self, key):
1927  # FIXME Support slice objects.
1928  if not isinstance(key, int):
1929  raise TypeError("Must supply a non-negative int.")
1930 
1931  if key < 0:
1932  raise IndexError("Only non-negative indexes are accepted.")
1933 
1934  if key >= len(self):
1935  raise IndexError("Index greater than container length: "
1936  "%d > %d" % ( key, len(self) ))
1937 
1938  result = conf.lib.clang_getArgType(self.parent, key)
1939  if result.kind == TypeKind.INVALID:
1940  raise IndexError("Argument could not be retrieved.")
1941 
1942  return result
1943 
1944  assert self.kind == TypeKind.FUNCTIONPROTO
1945  return ArgumentsIterator(self)
1946 
1947  @property
1948  def element_type(self):
1949  """Retrieve the Type of elements within this Type.
1950 
1951  If accessed on a type that is not an array, complex, or vector type, an
1952  exception will be raised.
1953  """
1954  result = conf.lib.clang_getElementType(self)
1955  if result.kind == TypeKind.INVALID:
1956  raise Exception('Element type not available on this type.')
1957 
1958  return result
1959 
1960  @property
1961  def element_count(self):
1962  """Retrieve the number of elements in this type.
1963 
1964  Returns an int.
1965 
1966  If the Type is not an array or vector, this raises.
1967  """
1968  result = conf.lib.clang_getNumElements(self)
1969  if result < 0:
1970  raise Exception('Type does not have elements.')
1971 
1972  return result
1973 
1974  @property
1975  def translation_unit(self):
1976  """The TranslationUnit to which this Type is associated."""
1977  # If this triggers an AttributeError, the instance was not properly
1978  # instantiated.
1979  return self._tu
1980 
1981  @staticmethod
1982  def from_result(res, fn, args):
1983  assert isinstance(res, Type)
1984 
1985  tu = None
1986  for arg in args:
1987  if hasattr(arg, 'translation_unit'):
1988  tu = arg.translation_unit
1989  break
1990 
1991  assert tu is not None
1992  res._tu = tu
1993 
1994  return res
1995 
1996  def get_canonical(self):
1997  """
1998  Return the canonical type for a Type.
1999 
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
2004  'T' would be 'int'.
2005  """
2006  return conf.lib.clang_getCanonicalType(self)
2007 
2009  """Determine whether a Type has the "const" qualifier set.
2010 
2011  This does not look through typedefs that may have added "const"
2012  at a different level.
2013  """
2014  return conf.lib.clang_isConstQualifiedType(self)
2015 
2017  """Determine whether a Type has the "volatile" qualifier set.
2018 
2019  This does not look through typedefs that may have added "volatile"
2020  at a different level.
2021  """
2022  return conf.lib.clang_isVolatileQualifiedType(self)
2023 
2025  """Determine whether a Type has the "restrict" qualifier set.
2026 
2027  This does not look through typedefs that may have added "restrict" at
2028  a different level.
2029  """
2030  return conf.lib.clang_isRestrictQualifiedType(self)
2031 
2033  """Determine whether this function Type is a variadic function type."""
2034  assert self.kind == TypeKind.FUNCTIONPROTO
2035 
2036  return conf.lib.clang_isFunctionTypeVariadic(self)
2037 
2038  def is_pod(self):
2039  """Determine whether this Type represents plain old data (POD)."""
2040  return conf.lib.clang_isPODType(self)
2041 
2042  def get_pointee(self):
2043  """
2044  For pointer types, returns the type of the pointee.
2045  """
2046  return conf.lib.clang_getPointeeType(self)
2047 
2048  def get_declaration(self):
2049  """
2050  Return the cursor for the declaration of the given type.
2051  """
2052  return conf.lib.clang_getTypeDeclaration(self)
2053 
2054  def get_result(self):
2055  """
2056  Retrieve the result type associated with a function type.
2057  """
2058  return conf.lib.clang_getResultType(self)
2059 
2061  """
2062  Retrieve the type of the elements of the array type.
2063  """
2064  return conf.lib.clang_getArrayElementType(self)
2065 
2066  def get_array_size(self):
2067  """
2068  Retrieve the size of the constant array.
2069  """
2070  return conf.lib.clang_getArraySize(self)
2071 
2072  def get_class_type(self):
2073  """
2074  Retrieve the class type of the member pointer type.
2075  """
2076  return conf.lib.clang_Type_getClassType(self)
2077 
2078  def get_named_type(self):
2079  """
2080  Retrieve the type named by the qualified-id.
2081  """
2082  return conf.lib.clang_Type_getNamedType(self)
2083  def get_align(self):
2084  """
2085  Retrieve the alignment of the record.
2086  """
2087  return conf.lib.clang_Type_getAlignOf(self)
2088 
2089  def get_size(self):
2090  """
2091  Retrieve the size of the record.
2092  """
2093  return conf.lib.clang_Type_getSizeOf(self)
2094 
2095  def get_offset(self, fieldname):
2096  """
2097  Retrieve the offset of a field in the record.
2098  """
2099  return conf.lib.clang_Type_getOffsetOf(self, c_char_p(fieldname))
2100 
2102  """
2103  Retrieve the ref-qualifier of the type.
2104  """
2105  return RefQualifierKind.from_id(
2106  conf.lib.clang_Type_getCXXRefQualifier(self))
2107 
2108  def get_fields(self):
2109  """Return an iterator for accessing the fields of this type."""
2110 
2111  def visitor(field, children):
2112  assert field != conf.lib.clang_getNullCursor()
2113 
2114  # Create reference to TU so it isn't GC'd before Cursor.
2115  field._tu = self._tu
2116  fields.append(field)
2117  return 1 # continue
2118  fields = []
2119  conf.lib.clang_Type_visitFields(self,
2120  callbacks['fields_visit'](visitor), fields)
2121  return iter(fields)
2122 
2123  @property
2124  def spelling(self):
2125  """Retrieve the spelling of this Type."""
2126  return conf.lib.clang_getTypeSpelling(self)
2127 
2128  def __eq__(self, other):
2129  if type(other) != type(self):
2130  return False
2131 
2132  return conf.lib.clang_equalTypes(self, other)
2133 
2134  def __ne__(self, other):
2135  return not self.__eq__(other)
2136 
2137 
2138 
2139 # CIndex objects (derived from ClangObject) are essentially lightweight
2140 # wrappers attached to some underlying object, which is exposed via CIndex as
2141 # a void*.
2142 
2143 class ClangObject(object):
2144  """
2145  A helper for Clang objects. This class helps act as an intermediary for
2146  the ctypes library and the Clang CIndex library.
2147  """
2148  def __init__(self, obj):
2149  assert isinstance(obj, c_object_p) and obj
2150  self.obj = self._as_parameter_ = obj
2151 
2152  def from_param(self):
2153  return self._as_parameter_
2154 
2155 
2156 class _CXUnsavedFile(Structure):
2157  """Helper for passing unsaved file arguments."""
2158  _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
2159 
2160 # Functions calls through the python interface are rather slow. Fortunately,
2161 # for most symboles, we do not need to perform a function call. Their spelling
2162 # never changes and is consequently provided by this spelling cache.
2163 SpellingCache = {
2164  # 0: CompletionChunk.Kind("Optional"),
2165  # 1: CompletionChunk.Kind("TypedText"),
2166  # 2: CompletionChunk.Kind("Text"),
2167  # 3: CompletionChunk.Kind("Placeholder"),
2168  # 4: CompletionChunk.Kind("Informative"),
2169  # 5 : CompletionChunk.Kind("CurrentParameter"),
2170  6: '(', # CompletionChunk.Kind("LeftParen"),
2171  7: ')', # CompletionChunk.Kind("RightParen"),
2172  8: '[', # CompletionChunk.Kind("LeftBracket"),
2173  9: ']', # CompletionChunk.Kind("RightBracket"),
2174  10: '{', # CompletionChunk.Kind("LeftBrace"),
2175  11: '}', # CompletionChunk.Kind("RightBrace"),
2176  12: '<', # CompletionChunk.Kind("LeftAngle"),
2177  13: '>', # CompletionChunk.Kind("RightAngle"),
2178  14: ', ', # CompletionChunk.Kind("Comma"),
2179  # 15: CompletionChunk.Kind("ResultType"),
2180  16: ':', # CompletionChunk.Kind("Colon"),
2181  17: ';', # CompletionChunk.Kind("SemiColon"),
2182  18: '=', # CompletionChunk.Kind("Equal"),
2183  19: ' ', # CompletionChunk.Kind("HorizontalSpace"),
2184  # 20: CompletionChunk.Kind("VerticalSpace")
2185 }
2186 
2188  class Kind:
2189  def __init__(self, name):
2190  self.name = name
2191 
2192  def __str__(self):
2193  return self.name
2194 
2195  def __repr__(self):
2196  return "<ChunkKind: %s>" % self
2197 
2198  def __init__(self, completionString, key):
2199  self.cs = completionString
2200  self.key = key
2202 
2203  def __repr__(self):
2204  return "{'" + self.spelling + "', " + str(self.kind) + "}"
2205 
2206  @CachedProperty
2207  def spelling(self):
2208  if self.__kindNumber in SpellingCache:
2209  return SpellingCache[self.__kindNumber]
2210  return conf.lib.clang_getCompletionChunkText(self.cs, self.key).spelling
2211 
2212  # We do not use @CachedProperty here, as the manual implementation is
2213  # apparently still significantly faster. Please profile carefully if you
2214  # would like to add CachedProperty back.
2215  @property
2216  def __kindNumber(self):
2217  if self.__kindNumberCache == -1:
2218  self.__kindNumberCache = \
2219  conf.lib.clang_getCompletionChunkKind(self.cs, self.key)
2220  return self.__kindNumberCache
2221 
2222  @CachedProperty
2223  def kind(self):
2224  return completionChunkKindMap[self.__kindNumber]
2225 
2226  @CachedProperty
2227  def string(self):
2228  res = conf.lib.clang_getCompletionChunkCompletionString(self.cs,
2229  self.key)
2230 
2231  if (res):
2232  return CompletionString(res)
2233  else:
2234  None
2235 
2236  def isKindOptional(self):
2237  return self.__kindNumber == 0
2238 
2239  def isKindTypedText(self):
2240  return self.__kindNumber == 1
2241 
2243  return self.__kindNumber == 3
2244 
2246  return self.__kindNumber == 4
2247 
2248  def isKindResultType(self):
2249  return self.__kindNumber == 15
2250 
2251 completionChunkKindMap = {
2252  0: CompletionChunk.Kind("Optional"),
2253  1: CompletionChunk.Kind("TypedText"),
2254  2: CompletionChunk.Kind("Text"),
2255  3: CompletionChunk.Kind("Placeholder"),
2256  4: CompletionChunk.Kind("Informative"),
2257  5: CompletionChunk.Kind("CurrentParameter"),
2258  6: CompletionChunk.Kind("LeftParen"),
2259  7: CompletionChunk.Kind("RightParen"),
2260  8: CompletionChunk.Kind("LeftBracket"),
2261  9: CompletionChunk.Kind("RightBracket"),
2262  10: CompletionChunk.Kind("LeftBrace"),
2263  11: CompletionChunk.Kind("RightBrace"),
2264  12: CompletionChunk.Kind("LeftAngle"),
2265  13: CompletionChunk.Kind("RightAngle"),
2266  14: CompletionChunk.Kind("Comma"),
2267  15: CompletionChunk.Kind("ResultType"),
2268  16: CompletionChunk.Kind("Colon"),
2269  17: CompletionChunk.Kind("SemiColon"),
2270  18: CompletionChunk.Kind("Equal"),
2271  19: CompletionChunk.Kind("HorizontalSpace"),
2272  20: CompletionChunk.Kind("VerticalSpace")}
2273 
2276  def __init__(self, name):
2277  self.name = name
2278 
2279  def __str__(self):
2280  return self.name
2281 
2282  def __repr__(self):
2283  return "<Availability: %s>" % self
2284 
2285  def __len__(self):
2286  return self.num_chunks
2287 
2288  @CachedProperty
2289  def num_chunks(self):
2290  return conf.lib.clang_getNumCompletionChunks(self.obj)
2291 
2292  def __getitem__(self, key):
2293  if self.num_chunks <= key:
2294  raise IndexError
2295  return CompletionChunk(self.obj, key)
2296 
2297  @property
2298  def priority(self):
2299  return conf.lib.clang_getCompletionPriority(self.obj)
2300 
2301  @property
2302  def availability(self):
2303  res = conf.lib.clang_getCompletionAvailability(self.obj)
2304  return availabilityKinds[res]
2305 
2306  @property
2307  def briefComment(self):
2308  if conf.function_exists("clang_getCompletionBriefComment"):
2309  return conf.lib.clang_getCompletionBriefComment(self.obj)
2310  return _CXString()
2311 
2312  def __repr__(self):
2313  return " | ".join([str(a) for a in self]) \
2314  + " || Priority: " + str(self.priority) \
2315  + " || Availability: " + str(self.availability) \
2316  + " || Brief comment: " + str(self.briefComment.spelling)
2317 
2318 availabilityKinds = {
2319  0: CompletionChunk.Kind("Available"),
2320  1: CompletionChunk.Kind("Deprecated"),
2321  2: CompletionChunk.Kind("NotAvailable"),
2322  3: CompletionChunk.Kind("NotAccessible")}
2323 
2324 class CodeCompletionResult(Structure):
2325  _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
2326 
2327  def __repr__(self):
2328  return str(CompletionString(self.completionString))
2329 
2330  @property
2331  def kind(self):
2332  return CursorKind.from_id(self.cursorKind)
2333 
2334  @property
2335  def string(self):
2336  return CompletionString(self.completionString)
2337 
2338 class CCRStructure(Structure):
2339  _fields_ = [('results', POINTER(CodeCompletionResult)),
2340  ('numResults', c_int)]
2341 
2342  def __len__(self):
2343  return self.numResults
2344 
2345  def __getitem__(self, key):
2346  if len(self) <= key:
2347  raise IndexError
2348 
2349  return self.results[key]
2350 
2352  def __init__(self, ptr):
2353  assert isinstance(ptr, POINTER(CCRStructure)) and ptr
2354  self.ptr = self._as_parameter_ = ptr
2355 
2356  def from_param(self):
2357  return self._as_parameter_
2358 
2359  def __del__(self):
2360  conf.lib.clang_disposeCodeCompleteResults(self)
2361 
2362  @property
2363  def results(self):
2364  return self.ptr.contents
2365 
2366  @property
2367  def diagnostics(self):
2368  class DiagnosticsItr:
2369  def __init__(self, ccr):
2370  self.ccr= ccr
2371 
2372  def __len__(self):
2373  return int(\
2374  conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr))
2375 
2376  def __getitem__(self, key):
2377  return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key)
2378 
2379  return DiagnosticsItr(self)
2380 
2381 
2383  """
2384  The Index type provides the primary interface to the Clang CIndex library,
2385  primarily by providing an interface for reading and parsing translation
2386  units.
2387  """
2388 
2389  @staticmethod
2390  def create(excludeDecls=False):
2391  """
2392  Create a new Index.
2393  Parameters:
2394  excludeDecls -- Exclude local declarations from translation units.
2395  """
2396  return Index(conf.lib.clang_createIndex(excludeDecls, 0))
2397 
2398  def __del__(self):
2399  conf.lib.clang_disposeIndex(self)
2400 
2401  def read(self, path):
2402  """Load a TranslationUnit from the given AST file."""
2403  return TranslationUnit.from_ast_file(path, self)
2404 
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.
2409 
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.
2414 
2415  If an error was encountered during parsing, a TranslationUnitLoadError
2416  will be raised.
2417  """
2418  return TranslationUnit.from_source(path, args, unsaved_files, options,
2419  self)
2420 
2422  """Represents a source code translation unit.
2423 
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
2426  translation unit.
2427  """
2428 
2429  # Default parsing mode.
2430  PARSE_NONE = 0
2431 
2432  # Instruct the parser to create a detailed processing record containing
2433  # metadata not normally retained.
2434  PARSE_DETAILED_PROCESSING_RECORD = 1
2435 
2436  # Indicates that the translation unit is incomplete. This is typically used
2437  # when parsing headers.
2438  PARSE_INCOMPLETE = 2
2439 
2440  # Instruct the parser to create a pre-compiled preamble for the translation
2441  # unit. This caches the preamble (included files at top of source file).
2442  # This is useful if the translation unit will be reparsed and you don't
2443  # want to incur the overhead of reparsing the preamble.
2444  PARSE_PRECOMPILED_PREAMBLE = 4
2445 
2446  # Cache code completion information on parse. This adds time to parsing but
2447  # speeds up code completion.
2448  PARSE_CACHE_COMPLETION_RESULTS = 8
2449 
2450  # Flags with values 16 and 32 are deprecated and intentionally omitted.
2451 
2452  # Do not parse function bodies. This is useful if you only care about
2453  # searching for declarations/definitions.
2454  PARSE_SKIP_FUNCTION_BODIES = 64
2455 
2456  # Used to indicate that brief documentation comments should be included
2457  # into the set of code completions returned from this translation unit.
2458  PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION = 128
2459 
2460  @classmethod
2461  def from_source(cls, filename, args=None, unsaved_files=None, options=0,
2462  index=None):
2463  """Create a TranslationUnit by parsing source.
2464 
2465  This is capable of processing source code both from files on the
2466  filesystem as well as in-memory contents.
2467 
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"].
2471 
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.
2478 
2479  options is a bitwise or of TranslationUnit.PARSE_XXX flags which will
2480  control parsing behavior.
2481 
2482  index is an Index instance to utilize. If not provided, a new Index
2483  will be created for this TranslationUnit.
2484 
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.
2488 
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.
2492 
2493  If an error occurs, a TranslationUnitLoadError is raised.
2494 
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.
2497 
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.
2501  """
2502  if args is None:
2503  args = []
2504 
2505  if unsaved_files is None:
2506  unsaved_files = []
2507 
2508  if index is None:
2509  index = Index.create()
2510 
2511  if isinstance(filename, str):
2512  filename = filename.encode('utf8')
2513 
2514  args_length = len(args)
2515  if args_length > 0:
2516  args = (arg.encode('utf8') if isinstance(arg, str) else arg
2517  for arg in args)
2518  args_array = (c_char_p * args_length)(* args)
2519 
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):
2524  if hasattr(contents, "read"):
2525  contents = contents.read()
2526 
2527  unsaved_array[i].name = name
2528  unsaved_array[i].contents = contents
2529  unsaved_array[i].length = len(contents)
2530 
2531  ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array,
2532  args_length, unsaved_array,
2533  len(unsaved_files), options)
2534 
2535  if not ptr:
2536  raise TranslationUnitLoadError("Error parsing translation unit.")
2537 
2538  return cls(ptr, index=index)
2539 
2540  @classmethod
2541  def from_ast_file(cls, filename, index=None):
2542  """Create a TranslationUnit instance from a saved AST file.
2543 
2544  A previously-saved AST file (provided with -emit-ast or
2545  TranslationUnit.save()) is loaded from the filename specified.
2546 
2547  If the file cannot be loaded, a TranslationUnitLoadError will be
2548  raised.
2549 
2550  index is optional and is the Index instance to use. If not provided,
2551  a default Index will be created.
2552  """
2553  if index is None:
2554  index = Index.create()
2555 
2556  ptr = conf.lib.clang_createTranslationUnit(index, filename)
2557  if not ptr:
2558  raise TranslationUnitLoadError(filename)
2559 
2560  return cls(ptr=ptr, index=index)
2561 
2562  def __init__(self, ptr, index):
2563  """Create a TranslationUnit instance.
2564 
2565  TranslationUnits should be created using one of the from_* @classmethod
2566  functions above. __init__ is only called internally.
2567  """
2568  assert isinstance(index, Index)
2569  self.index = index
2570  ClangObject.__init__(self, ptr)
2571 
2572  def __del__(self):
2573  conf.lib.clang_disposeTranslationUnit(self)
2574 
2575  @property
2576  def cursor(self):
2577  """Retrieve the cursor that represents the given translation unit."""
2578  return conf.lib.clang_getTranslationUnitCursor(self)
2579 
2580  @property
2581  def spelling(self):
2582  """Get the original translation unit source file name."""
2583  return conf.lib.clang_getTranslationUnitSpelling(self)
2584 
2585  def get_includes(self):
2586  """
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
2591  headers.
2592  """
2593  def visitor(fobj, lptr, depth, includes):
2594  if depth > 0:
2595  loc = lptr.contents
2596  includes.append(FileInclusion(loc.file, File(fobj), loc, depth))
2597 
2598  # Automatically adapt CIndex/ctype pointers to python objects
2599  includes = []
2600  conf.lib.clang_getInclusions(self,
2601  callbacks['translation_unit_includes'](visitor), includes)
2602 
2603  return iter(includes)
2604 
2605  def get_file(self, filename):
2606  """Obtain a File from this translation unit."""
2607 
2608  return File.from_name(self, filename)
2609 
2610  def get_location(self, filename, position):
2611  """Obtain a SourceLocation for a file in this translation unit.
2612 
2613  The position can be specified by passing:
2614 
2615  - Integer file offset. Initial file offset is 0.
2616  - 2-tuple of (line number, column number). Initial file position is
2617  (0, 0)
2618  """
2619  f = self.get_file(filename)
2620 
2621  if isinstance(position, int):
2622  return SourceLocation.from_offset(self, f, position)
2623 
2624  return SourceLocation.from_position(self, f, position[0], position[1])
2625 
2626  def get_extent(self, filename, locations):
2627  """Obtain a SourceRange from this translation unit.
2628 
2629  The bounds of the SourceRange must ultimately be defined by a start and
2630  end SourceLocation. For the locations argument, you can pass:
2631 
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.
2635 
2636  e.g.
2637 
2638  get_extent('foo.c', (5, 10))
2639  get_extent('foo.c', ((1, 1), (1, 15)))
2640  """
2641  f = self.get_file(filename)
2642 
2643  if len(locations) < 2:
2644  raise Exception('Must pass object with at least 2 elements')
2645 
2646  start_location, end_location = locations
2647 
2648  if hasattr(start_location, '__len__'):
2649  start_location = SourceLocation.from_position(self, f,
2650  start_location[0], start_location[1])
2651  elif isinstance(start_location, int):
2652  start_location = SourceLocation.from_offset(self, f,
2653  start_location)
2654 
2655  if hasattr(end_location, '__len__'):
2656  end_location = SourceLocation.from_position(self, f,
2657  end_location[0], end_location[1])
2658  elif isinstance(end_location, int):
2659  end_location = SourceLocation.from_offset(self, f, end_location)
2660 
2661  assert isinstance(start_location, SourceLocation)
2662  assert isinstance(end_location, SourceLocation)
2663 
2664  return SourceRange.from_locations(start_location, end_location)
2665 
2666  @property
2667  def diagnostics(self):
2668  """
2669  Return an iterable (and indexable) object containing the diagnostics.
2670  """
2671  class DiagIterator:
2672  def __init__(self, tu):
2673  self.tu = tu
2674 
2675  def __len__(self):
2676  return int(conf.lib.clang_getNumDiagnostics(self.tu))
2677 
2678  def __getitem__(self, key):
2679  diag = conf.lib.clang_getDiagnostic(self.tu, key)
2680  if not diag:
2681  raise IndexError
2682  return Diagnostic(diag)
2683 
2684  return DiagIterator(self)
2685 
2686  def reparse(self, unsaved_files=None, options=0):
2687  """
2688  Reparse an already parsed translation unit.
2689 
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.
2694  """
2695  if unsaved_files is None:
2696  unsaved_files = []
2697 
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):
2702  if not isinstance(value, str):
2703  # FIXME: It would be great to support an efficient version
2704  # of this, one day.
2705  value = value.read()
2706  print(value)
2707  if not isinstance(value, str):
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)
2714 
2715  def save(self, filename):
2716  """Saves the TranslationUnit to a file.
2717 
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.
2721 
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().
2727 
2728  filename -- The path to save the translation unit to.
2729  """
2730  options = conf.lib.clang_defaultSaveOptions(self)
2731  result = int(conf.lib.clang_saveTranslationUnit(self, filename,
2732  options))
2733  if result != 0:
2734  raise TranslationUnitSaveError(result,
2735  'Error saving TranslationUnit.')
2736 
2737  def codeComplete(self, path, line, column, unsaved_files=None,
2738  include_macros=False, include_code_patterns=False,
2739  include_brief_comments=False):
2740  """
2741  Code complete in this translation unit.
2742 
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.
2747  """
2748  options = 0
2749 
2750  if include_macros:
2751  options += 1
2752 
2753  if include_code_patterns:
2754  options += 2
2755 
2756  if include_brief_comments:
2757  options += 4
2758 
2759  if unsaved_files is None:
2760  unsaved_files = []
2761 
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):
2766  if not isinstance(value, str):
2767  # FIXME: It would be great to support an efficient version
2768  # of this, one day.
2769  value = value.read()
2770  print(value)
2771  if not isinstance(value, str):
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)
2778  if ptr:
2779  return CodeCompletionResults(ptr)
2780  return None
2781 
2782  def get_tokens(self, locations=None, extent=None):
2783  """Obtain tokens in this translation unit.
2784 
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.
2789  """
2790  if locations is not None:
2791  extent = SourceRange(start=locations[0], end=locations[1])
2792 
2793  return TokenGroup.get_tokens(self, extent)
2794 
2796  """
2797  The File class represents a particular source file that is part of a
2798  translation unit.
2799  """
2800 
2801  @staticmethod
2802  def from_name(translation_unit, file_name):
2803  """Retrieve a file handle within the given translation unit."""
2804  return File(conf.lib.clang_getFile(translation_unit, file_name))
2805 
2806  @property
2807  def name(self):
2808  """Return the complete file and path name of the file."""
2809  return conf.lib.clang_getCString(conf.lib.clang_getFileName(self))
2810 
2811  @property
2812  def time(self):
2813  """Return the last modification time of the file."""
2814  return conf.lib.clang_getFileTime(self)
2815 
2816  def __bytes__(self):
2817  return self.name
2818 
2819  def __repr__(self):
2820  return "<File: %s>" % (self.name)
2821 
2822  @staticmethod
2823  def from_cursor_result(res, fn, args):
2824  assert isinstance(res, File)
2825 
2826  # Copy a reference to the TranslationUnit to prevent premature GC.
2827  res._tu = args[0]._tu
2828  return res
2829 
2830 class FileInclusion(object):
2831  """
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.
2837  """
2838 
2839  def __init__(self, src, tgt, loc, depth):
2840  self.source = src
2841  self.include = tgt
2842  self.location = loc
2843  self.depth = depth
2844 
2845  @property
2846  def is_input_file(self):
2847  """True if the included file is the input file."""
2848  return self.depth == 0
2849 
2850 class CompilationDatabaseError(Exception):
2851  """Represents an error that occurred when working with a CompilationDatabase
2852 
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.
2856  """
2857 
2858  # An unknown error occurred
2859  ERROR_UNKNOWN = 0
2860 
2861  # The database could not be loaded
2862  ERROR_CANNOTLOADDATABASE = 1
2863 
2864  def __init__(self, enumeration, message):
2865  assert isinstance(enumeration, int)
2866 
2867  if enumeration > 1:
2868  raise Exception("Encountered undefined CompilationDatabase error "
2869  "constant: %d. Please file a bug to have this "
2870  "value supported." % enumeration)
2871 
2872  self.cdb_error = enumeration
2873  Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
2874 
2875 class CompileCommand(object):
2876  """Represents the compile command used to build a file"""
2877  def __init__(self, cmd, ccmds):
2878  self.cmd = cmd
2879  # Keep a reference to the originating CompileCommands
2880  # to prevent garbage collection
2881  self.ccmds = ccmds
2882 
2883  @property
2884  def directory(self):
2885  """Get the working directory for this CompileCommand"""
2886  return conf.lib.clang_CompileCommand_getDirectory(self.cmd)
2887 
2888  @property
2889  def filename(self):
2890  """Get the working filename for this CompileCommand"""
2891  return conf.lib.clang_CompileCommand_getFilename(self.cmd)
2892 
2893  @property
2894  def arguments(self):
2895  """
2896  Get an iterable object providing each argument in the
2897  command line for the compiler invocation as a _CXString.
2898 
2899  Invariant : the first argument is the compiler executable
2900  """
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)
2904 
2905 class CompileCommands(object):
2906  """
2907  CompileCommands is an iterable object containing all CompileCommand
2908  that can be used for building a specific file.
2909  """
2910  def __init__(self, ccmds):
2911  self.ccmds = ccmds
2912 
2913  def __del__(self):
2914  conf.lib.clang_CompileCommands_dispose(self.ccmds)
2915 
2916  def __len__(self):
2917  return int(conf.lib.clang_CompileCommands_getSize(self.ccmds))
2918 
2919  def __getitem__(self, i):
2920  cc = conf.lib.clang_CompileCommands_getCommand(self.ccmds, i)
2921  if not cc:
2922  raise IndexError
2923  return CompileCommand(cc, self)
2924 
2925  @staticmethod
2926  def from_result(res, fn, args):
2927  if not res:
2928  return None
2929  return CompileCommands(res)
2930 
2932  """
2933  The CompilationDatabase is a wrapper class around
2934  clang::tooling::CompilationDatabase
2935 
2936  It enables querying how a specific source file can be built.
2937  """
2938 
2939  def __del__(self):
2940  conf.lib.clang_CompilationDatabase_dispose(self)
2941 
2942  @staticmethod
2943  def from_result(res, fn, args):
2944  if not res:
2945  raise CompilationDatabaseError(0,
2946  "CompilationDatabase loading failed")
2947  return CompilationDatabase(res)
2948 
2949  @staticmethod
2950  def fromDirectory(buildDir):
2951  """Builds a CompilationDatabase from the database found in buildDir"""
2952  errorCode = c_uint()
2953  try:
2954  cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
2955  byref(errorCode))
2956  except CompilationDatabaseError as e:
2957  raise CompilationDatabaseError(int(errorCode.value),
2958  "CompilationDatabase loading failed")
2959  return cdb
2960 
2961  def getCompileCommands(self, filename):
2962  """
2963  Get an iterable object providing all the CompileCommands available to
2964  build filename. Returns None if filename is not found in the database.
2965  """
2966  return conf.lib.clang_CompilationDatabase_getCompileCommands(self,
2967  filename)
2968 
2970  """
2971  Get an iterable object providing all the CompileCommands available from
2972  the database.
2973  """
2974  return conf.lib.clang_CompilationDatabase_getAllCompileCommands(self)
2975 
2976 
2977 class Token(Structure):
2978  """Represents a single token from the preprocessor.
2979 
2980  Tokens are effectively segments of source code. Source code is first parsed
2981  into tokens before being converted into the AST and Cursors.
2982 
2983  Tokens are obtained from parsed TranslationUnit instances. You currently
2984  can't create tokens manually.
2985  """
2986  _fields_ = [
2987  ('int_data', c_uint * 4),
2988  ('ptr_data', c_void_p)
2989  ]
2990 
2991  @property
2992  def spelling(self):
2993  """The spelling of this token.
2994 
2995  This is the textual representation of the token in source.
2996  """
2997  return conf.lib.clang_getTokenSpelling(self._tu, self)
2998 
2999  @property
3000  def kind(self):
3001  """Obtain the TokenKind of the current token."""
3002  return TokenKind.from_value(conf.lib.clang_getTokenKind(self))
3003 
3004  @property
3005  def location(self):
3006  """The SourceLocation this Token occurs at."""
3007  return conf.lib.clang_getTokenLocation(self._tu, self)
3008 
3009  @property
3010  def extent(self):
3011  """The SourceRange this Token occupies."""
3012  return conf.lib.clang_getTokenExtent(self._tu, self)
3013 
3014  @property
3015  def cursor(self):
3016  """The Cursor this Token corresponds to."""
3017  cursor = Cursor()
3018 
3019  conf.lib.clang_annotateTokens(self._tu, byref(self), 1, byref(cursor))
3020 
3021  return cursor
3022 
3023 # Now comes the plumbing to hook up the C library.
3024 
3025 # Register callback types in common container.
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)
3030 
3031 # Functions strictly alphabetical order.
3032 functionList = [
3033  ("clang_annotateTokens",
3034  [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]),
3035 
3036  ("clang_CompilationDatabase_dispose",
3037  [c_object_p]),
3038 
3039  ("clang_CompilationDatabase_fromDirectory",
3040  [c_char_p, POINTER(c_uint)],
3041  c_object_p,
3042  CompilationDatabase.from_result),
3043 
3044  ("clang_CompilationDatabase_getAllCompileCommands",
3045  [c_object_p],
3046  c_object_p,
3047  CompileCommands.from_result),
3048 
3049  ("clang_CompilationDatabase_getCompileCommands",
3050  [c_object_p, c_char_p],
3051  c_object_p,
3052  CompileCommands.from_result),
3053 
3054  ("clang_CompileCommands_dispose",
3055  [c_object_p]),
3056 
3057  ("clang_CompileCommands_getCommand",
3058  [c_object_p, c_uint],
3059  c_object_p),
3060 
3061  ("clang_CompileCommands_getSize",
3062  [c_object_p],
3063  c_uint),
3064 
3065  ("clang_CompileCommand_getArg",
3066  [c_object_p, c_uint],
3067  _CXString,
3068  _CXString.from_result),
3069 
3070  ("clang_CompileCommand_getDirectory",
3071  [c_object_p],
3072  _CXString,
3073  _CXString.from_result),
3074 
3075  ("clang_CompileCommand_getFilename",
3076  [c_object_p],
3077  _CXString,
3078  _CXString.from_result),
3079 
3080  ("clang_CompileCommand_getNumArgs",
3081  [c_object_p],
3082  c_uint),
3083 
3084  ("clang_codeCompleteAt",
3085  [TranslationUnit, c_char_p, c_int, c_int, c_void_p, c_int, c_int],
3086  POINTER(CCRStructure)),
3087 
3088  ("clang_codeCompleteGetDiagnostic",
3089  [CodeCompletionResults, c_int],
3090  Diagnostic),
3091 
3092  ("clang_codeCompleteGetNumDiagnostics",
3093  [CodeCompletionResults],
3094  c_int),
3095 
3096  ("clang_createIndex",
3097  [c_int, c_int],
3098  c_object_p),
3099 
3100  ("clang_createTranslationUnit",
3101  [Index, c_char_p],
3102  c_object_p),
3103 
3104  ("clang_CXXConstructor_isConvertingConstructor",
3105  [Cursor],
3106  bool),
3107 
3108  ("clang_CXXConstructor_isCopyConstructor",
3109  [Cursor],
3110  bool),
3111 
3112  ("clang_CXXConstructor_isDefaultConstructor",
3113  [Cursor],
3114  bool),
3115 
3116  ("clang_CXXConstructor_isMoveConstructor",
3117  [Cursor],
3118  bool),
3119 
3120  ("clang_CXXField_isMutable",
3121  [Cursor],
3122  bool),
3123 
3124  ("clang_CXXMethod_isConst",
3125  [Cursor],
3126  bool),
3127 
3128  ("clang_CXXMethod_isDefaulted",
3129  [Cursor],
3130  bool),
3131 
3132  ("clang_CXXMethod_isPureVirtual",
3133  [Cursor],
3134  bool),
3135 
3136  ("clang_CXXMethod_isStatic",
3137  [Cursor],
3138  bool),
3139 
3140  ("clang_CXXMethod_isVirtual",
3141  [Cursor],
3142  bool),
3143 
3144  ("clang_defaultDiagnosticDisplayOptions",
3145  [],
3146  c_uint),
3147 
3148  ("clang_defaultSaveOptions",
3149  [TranslationUnit],
3150  c_uint),
3151 
3152  ("clang_disposeCodeCompleteResults",
3153  [CodeCompletionResults]),
3154 
3155 # ("clang_disposeCXTUResourceUsage",
3156 # [CXTUResourceUsage]),
3157 
3158  ("clang_disposeDiagnostic",
3159  [Diagnostic]),
3160 
3161  ("clang_disposeIndex",
3162  [Index]),
3163 
3164  ("clang_disposeString",
3165  [_CXString]),
3166 
3167  ("clang_disposeTokens",
3168  [TranslationUnit, POINTER(Token), c_uint]),
3169 
3170  ("clang_disposeTranslationUnit",
3171  [TranslationUnit]),
3172 
3173  ("clang_equalCursors",
3174  [Cursor, Cursor],
3175  bool),
3176 
3177  ("clang_equalLocations",
3178  [SourceLocation, SourceLocation],
3179  bool),
3180 
3181  ("clang_equalRanges",
3182  [SourceRange, SourceRange],
3183  bool),
3184 
3185  ("clang_equalTypes",
3186  [Type, Type],
3187  bool),
3188 
3189  ("clang_formatDiagnostic",
3190  [Diagnostic, c_uint],
3191  _CXString),
3192 
3193  ("clang_getArgType",
3194  [Type, c_uint],
3195  Type,
3196  Type.from_result),
3197 
3198  ("clang_getArrayElementType",
3199  [Type],
3200  Type,
3201  Type.from_result),
3202 
3203  ("clang_getArraySize",
3204  [Type],
3205  c_longlong),
3206 
3207  ("clang_getFieldDeclBitWidth",
3208  [Cursor],
3209  c_int),
3210 
3211  ("clang_getCanonicalCursor",
3212  [Cursor],
3213  Cursor,
3214  Cursor.from_cursor_result),
3215 
3216  ("clang_getCanonicalType",
3217  [Type],
3218  Type,
3219  Type.from_result),
3220 
3221  ("clang_getChildDiagnostics",
3222  [Diagnostic],
3223  c_object_p),
3224 
3225  ("clang_getCompletionAvailability",
3226  [c_void_p],
3227  c_int),
3228 
3229  ("clang_getCompletionBriefComment",
3230  [c_void_p],
3231  _CXString),
3232 
3233  ("clang_getCompletionChunkCompletionString",
3234  [c_void_p, c_int],
3235  c_object_p),
3236 
3237  ("clang_getCompletionChunkKind",
3238  [c_void_p, c_int],
3239  c_int),
3240 
3241  ("clang_getCompletionChunkText",
3242  [c_void_p, c_int],
3243  _CXString),
3244 
3245  ("clang_getCompletionPriority",
3246  [c_void_p],
3247  c_int),
3248 
3249  ("clang_getCString",
3250  [_CXString],
3251  c_char_p),
3252 
3253  ("clang_getCursor",
3254  [TranslationUnit, SourceLocation],
3255  Cursor),
3256 
3257  ("clang_getCursorDefinition",
3258  [Cursor],
3259  Cursor,
3260  Cursor.from_result),
3261 
3262  ("clang_getCursorDisplayName",
3263  [Cursor],
3264  _CXString,
3265  _CXString.from_result),
3266 
3267  ("clang_getCursorExtent",
3268  [Cursor],
3269  SourceRange),
3270 
3271  ("clang_getCursorLexicalParent",
3272  [Cursor],
3273  Cursor,
3274  Cursor.from_cursor_result),
3275 
3276  ("clang_getCursorLocation",
3277  [Cursor],
3278  SourceLocation),
3279 
3280  ("clang_getCursorReferenced",
3281  [Cursor],
3282  Cursor,
3283  Cursor.from_result),
3284 
3285  ("clang_getCursorReferenceNameRange",
3286  [Cursor, c_uint, c_uint],
3287  SourceRange),
3288 
3289  ("clang_getCursorSemanticParent",
3290  [Cursor],
3291  Cursor,
3292  Cursor.from_cursor_result),
3293 
3294  ("clang_getCursorSpelling",
3295  [Cursor],
3296  _CXString,
3297  _CXString.from_result),
3298 
3299  ("clang_getCursorType",
3300  [Cursor],
3301  Type,
3302  Type.from_result),
3303 
3304  ("clang_getCursorUSR",
3305  [Cursor],
3306  _CXString,
3307  _CXString.from_result),
3308 
3309  ("clang_Cursor_getMangling",
3310  [Cursor],
3311  _CXString,
3312  _CXString.from_result),
3313 
3314 # ("clang_getCXTUResourceUsage",
3315 # [TranslationUnit],
3316 # CXTUResourceUsage),
3317 
3318  ("clang_getCXXAccessSpecifier",
3319  [Cursor],
3320  c_uint),
3321 
3322  ("clang_getDeclObjCTypeEncoding",
3323  [Cursor],
3324  _CXString,
3325  _CXString.from_result),
3326 
3327  ("clang_getDiagnostic",
3328  [c_object_p, c_uint],
3329  c_object_p),
3330 
3331  ("clang_getDiagnosticCategory",
3332  [Diagnostic],
3333  c_uint),
3334 
3335  ("clang_getDiagnosticCategoryText",
3336  [Diagnostic],
3337  _CXString,
3338  _CXString.from_result),
3339 
3340  ("clang_getDiagnosticFixIt",
3341  [Diagnostic, c_uint, POINTER(SourceRange)],
3342  _CXString,
3343  _CXString.from_result),
3344 
3345  ("clang_getDiagnosticInSet",
3346  [c_object_p, c_uint],
3347  c_object_p),
3348 
3349  ("clang_getDiagnosticLocation",
3350  [Diagnostic],
3351  SourceLocation),
3352 
3353  ("clang_getDiagnosticNumFixIts",
3354  [Diagnostic],
3355  c_uint),
3356 
3357  ("clang_getDiagnosticNumRanges",
3358  [Diagnostic],
3359  c_uint),
3360 
3361  ("clang_getDiagnosticOption",
3362  [Diagnostic, POINTER(_CXString)],
3363  _CXString,
3364  _CXString.from_result),
3365 
3366  ("clang_getDiagnosticRange",
3367  [Diagnostic, c_uint],
3368  SourceRange),
3369 
3370  ("clang_getDiagnosticSeverity",
3371  [Diagnostic],
3372  c_int),
3373 
3374  ("clang_getDiagnosticSpelling",
3375  [Diagnostic],
3376  _CXString,
3377  _CXString.from_result),
3378 
3379  ("clang_getElementType",
3380  [Type],
3381  Type,
3382  Type.from_result),
3383 
3384  ("clang_getEnumConstantDeclUnsignedValue",
3385  [Cursor],
3386  c_ulonglong),
3387 
3388  ("clang_getEnumConstantDeclValue",
3389  [Cursor],
3390  c_longlong),
3391 
3392  ("clang_getEnumDeclIntegerType",
3393  [Cursor],
3394  Type,
3395  Type.from_result),
3396 
3397  ("clang_getFile",
3398  [TranslationUnit, c_char_p],
3399  c_object_p),
3400 
3401  ("clang_getFileName",
3402  [File],
3403  _CXString), # TODO go through _CXString.from_result?
3404 
3405  ("clang_getFileTime",
3406  [File],
3407  c_uint),
3408 
3409  ("clang_getIBOutletCollectionType",
3410  [Cursor],
3411  Type,
3412  Type.from_result),
3413 
3414  ("clang_getIncludedFile",
3415  [Cursor],
3416  File,
3417  File.from_cursor_result),
3418 
3419  ("clang_getInclusions",
3420  [TranslationUnit, callbacks['translation_unit_includes'], py_object]),
3421 
3422  ("clang_getInstantiationLocation",
3423  [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint),
3424  POINTER(c_uint)]),
3425 
3426  ("clang_getLocation",
3427  [TranslationUnit, File, c_uint, c_uint],
3428  SourceLocation),
3429 
3430  ("clang_getLocationForOffset",
3431  [TranslationUnit, File, c_uint],
3432  SourceLocation),
3433 
3434  ("clang_getNullCursor",
3435  None,
3436  Cursor),
3437 
3438  ("clang_getNumArgTypes",
3439  [Type],
3440  c_uint),
3441 
3442  ("clang_getNumCompletionChunks",
3443  [c_void_p],
3444  c_int),
3445 
3446  ("clang_getNumDiagnostics",
3447  [c_object_p],
3448  c_uint),
3449 
3450  ("clang_getNumDiagnosticsInSet",
3451  [c_object_p],
3452  c_uint),
3453 
3454  ("clang_getNumElements",
3455  [Type],
3456  c_longlong),
3457 
3458  ("clang_getNumOverloadedDecls",
3459  [Cursor],
3460  c_uint),
3461 
3462  ("clang_getOverloadedDecl",
3463  [Cursor, c_uint],
3464  Cursor,
3465  Cursor.from_cursor_result),
3466 
3467  ("clang_getPointeeType",
3468  [Type],
3469  Type,
3470  Type.from_result),
3471 
3472  ("clang_getRange",
3473  [SourceLocation, SourceLocation],
3474  SourceRange),
3475 
3476  ("clang_getRangeEnd",
3477  [SourceRange],
3478  SourceLocation),
3479 
3480  ("clang_getRangeStart",
3481  [SourceRange],
3482  SourceLocation),
3483 
3484  ("clang_getResultType",
3485  [Type],
3486  Type,
3487  Type.from_result),
3488 
3489  ("clang_getSpecializedCursorTemplate",
3490  [Cursor],
3491  Cursor,
3492  Cursor.from_cursor_result),
3493 
3494  ("clang_getTemplateCursorKind",
3495  [Cursor],
3496  c_uint),
3497 
3498  ("clang_getTokenExtent",
3499  [TranslationUnit, Token],
3500  SourceRange),
3501 
3502  ("clang_getTokenKind",
3503  [Token],
3504  c_uint),
3505 
3506  ("clang_getTokenLocation",
3507  [TranslationUnit, Token],
3508  SourceLocation),
3509 
3510  ("clang_getTokenSpelling",
3511  [TranslationUnit, Token],
3512  _CXString,
3513  _CXString.from_result),
3514 
3515  ("clang_getTranslationUnitCursor",
3516  [TranslationUnit],
3517  Cursor,
3518  Cursor.from_result),
3519 
3520  ("clang_getTranslationUnitSpelling",
3521  [TranslationUnit],
3522  _CXString,
3523  _CXString.from_result),
3524 
3525  ("clang_getTUResourceUsageName",
3526  [c_uint],
3527  c_char_p),
3528 
3529  ("clang_getTypeDeclaration",
3530  [Type],
3531  Cursor,
3532  Cursor.from_result),
3533 
3534  ("clang_getTypedefDeclUnderlyingType",
3535  [Cursor],
3536  Type,
3537  Type.from_result),
3538 
3539  ("clang_getTypeKindSpelling",
3540  [c_uint],
3541  _CXString,
3542  _CXString.from_result),
3543 
3544  ("clang_getTypeSpelling",
3545  [Type],
3546  _CXString,
3547  _CXString.from_result),
3548 
3549  ("clang_hashCursor",
3550  [Cursor],
3551  c_uint),
3552 
3553  ("clang_isAttribute",
3554  [CursorKind],
3555  bool),
3556 
3557  ("clang_isConstQualifiedType",
3558  [Type],
3559  bool),
3560 
3561  ("clang_isCursorDefinition",
3562  [Cursor],
3563  bool),
3564 
3565  ("clang_isDeclaration",
3566  [CursorKind],
3567  bool),
3568 
3569  ("clang_isExpression",
3570  [CursorKind],
3571  bool),
3572 
3573  ("clang_isFileMultipleIncludeGuarded",
3574  [TranslationUnit, File],
3575  bool),
3576 
3577  ("clang_isFunctionTypeVariadic",
3578  [Type],
3579  bool),
3580 
3581  ("clang_isInvalid",
3582  [CursorKind],
3583  bool),
3584 
3585  ("clang_isPODType",
3586  [Type],
3587  bool),
3588 
3589  ("clang_isPreprocessing",
3590  [CursorKind],
3591  bool),
3592 
3593  ("clang_isReference",
3594  [CursorKind],
3595  bool),
3596 
3597  ("clang_isRestrictQualifiedType",
3598  [Type],
3599  bool),
3600 
3601  ("clang_isStatement",
3602  [CursorKind],
3603  bool),
3604 
3605  ("clang_isTranslationUnit",
3606  [CursorKind],
3607  bool),
3608 
3609  ("clang_isUnexposed",
3610  [CursorKind],
3611  bool),
3612 
3613  ("clang_isVirtualBase",
3614  [Cursor],
3615  bool),
3616 
3617  ("clang_isVolatileQualifiedType",
3618  [Type],
3619  bool),
3620 
3621  ("clang_parseTranslationUnit",
3622  [Index, c_char_p, c_void_p, c_int, c_void_p, c_int, c_int],
3623  c_object_p),
3624 
3625  ("clang_reparseTranslationUnit",
3626  [TranslationUnit, c_int, c_void_p, c_int],
3627  c_int),
3628 
3629  ("clang_saveTranslationUnit",
3630  [TranslationUnit, c_char_p, c_uint],
3631  c_int),
3632 
3633  ("clang_tokenize",
3634  [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]),
3635 
3636  ("clang_visitChildren",
3637  [Cursor, callbacks['cursor_visit'], py_object],
3638  c_uint),
3639 
3640  ("clang_Cursor_getNumArguments",
3641  [Cursor],
3642  c_int),
3643 
3644  ("clang_Cursor_getArgument",
3645  [Cursor, c_uint],
3646  Cursor,
3647  Cursor.from_result),
3648 
3649  ("clang_Cursor_getNumTemplateArguments",
3650  [Cursor],
3651  c_int),
3652 
3653  ("clang_Cursor_getTemplateArgumentKind",
3654  [Cursor, c_uint],
3655  TemplateArgumentKind.from_id),
3656 
3657  ("clang_Cursor_getTemplateArgumentType",
3658  [Cursor, c_uint],
3659  Type,
3660  Type.from_result),
3661 
3662  ("clang_Cursor_getTemplateArgumentValue",
3663  [Cursor, c_uint],
3664  c_longlong),
3665 
3666  ("clang_Cursor_getTemplateArgumentUnsignedValue",
3667  [Cursor, c_uint],
3668  c_ulonglong),
3669 
3670  ("clang_Cursor_isAnonymous",
3671  [Cursor],
3672  bool),
3673 
3674  ("clang_Cursor_isBitField",
3675  [Cursor],
3676  bool),
3677 
3678  ("clang_Cursor_getBriefCommentText",
3679  [Cursor],
3680  _CXString,
3681  _CXString.from_result),
3682 
3683  ("clang_Cursor_getRawCommentText",
3684  [Cursor],
3685  _CXString,
3686  _CXString.from_result),
3687 
3688  ("clang_Cursor_getOffsetOfField",
3689  [Cursor],
3690  c_longlong),
3691 
3692  ("clang_Type_getAlignOf",
3693  [Type],
3694  c_longlong),
3695 
3696  ("clang_Type_getClassType",
3697  [Type],
3698  Type,
3699  Type.from_result),
3700 
3701  ("clang_Type_getOffsetOf",
3702  [Type, c_char_p],
3703  c_longlong),
3704 
3705  ("clang_Type_getSizeOf",
3706  [Type],
3707  c_longlong),
3708 
3709  ("clang_Type_getCXXRefQualifier",
3710  [Type],
3711  c_uint),
3712 
3713  ("clang_Type_getNamedType",
3714  [Type],
3715  Type,
3716  Type.from_result),
3717 
3718  ("clang_Type_visitFields",
3719  [Type, callbacks['fields_visit'], py_object],
3720  c_uint),
3721 ]
3722 
3723 class LibclangError(Exception):
3724  def __init__(self, message):
3725  self.m = message
3726 
3727  def __str__(self):
3728  return self.m
3729 
3730 def register_function(lib, item, ignore_errors):
3731  # A function may not exist, if these bindings are used with an older or
3732  # incompatible version of libclang.so.
3733  try:
3734  func = getattr(lib, item[0])
3735  except AttributeError as e:
3736  msg = str(e) + ". Please ensure that your python bindings are "\
3737  "compatible with your libclang.so version."
3738  if ignore_errors:
3739  return
3740  raise LibclangError(msg)
3741 
3742  if len(item) >= 2:
3743  func.argtypes = item[1]
3744 
3745  if len(item) >= 3:
3746  func.restype = item[2]
3747 
3748  if len(item) == 4:
3749  func.errcheck = item[3]
3750 
3751 def register_functions(lib, ignore_errors):
3752  """Register function prototypes with a libclang library instance.
3753 
3754  This must be called as part of library instantiation so Python knows how
3755  to call out to the shared library.
3756  """
3757 
3758  def register(item):
3759  return register_function(lib, item, ignore_errors)
3760 
3761  for f in functionList:
3762  register(f)
3763 
3764 class Config:
3765  library_path = None
3766  library_file = None
3767  compatibility_check = False
3768  loaded = False
3769 
3770  @staticmethod
3771  def set_library_path(path):
3772  """Set the path in which to search for libclang"""
3773  if Config.loaded:
3774  raise Exception("library path must be set before before using " \
3775  "any other functionalities in libclang.")
3776 
3777  Config.library_path = path
3778 
3779  @staticmethod
3780  def set_library_file(filename):
3781  """Set the exact location of libclang"""
3782  if Config.loaded:
3783  raise Exception("library file must be set before before using " \
3784  "any other functionalities in libclang.")
3785 
3786  Config.library_file = filename
3787 
3788  @staticmethod
3789  def set_compatibility_check(check_status):
3790  """ Perform compatibility check when loading libclang
3791 
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.
3796 
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
3804  libclang versions.
3805  """
3806  if Config.loaded:
3807  raise Exception("compatibility_check must be set before before " \
3808  "using any other functionalities in libclang.")
3809 
3810  Config.compatibility_check = check_status
3811 
3812  @CachedProperty
3813  def lib(self):
3814  lib = self.get_cindex_library()
3815  register_functions(lib, not Config.compatibility_check)
3816  Config.loaded = True
3817  return lib
3818 
3819  def get_filename(self):
3820  if Config.library_file:
3821  return Config.library_file
3822 
3823  import platform
3824  name = platform.system()
3825 
3826  if name == 'Darwin':
3827  file = 'libclang.dylib'
3828  elif name == 'Windows':
3829  file = 'libclang.dll'
3830  else:
3831  file = 'libclang.so'
3832 
3833  if Config.library_path:
3834  file = Config.library_path + '/' + file
3835 
3836  return file
3837 
3839  try:
3840  library = cdll.LoadLibrary(self.get_filename())
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()."
3845  raise LibclangError(msg)
3846 
3847  return library
3848 
3849  def function_exists(self, name):
3850  try:
3851  getattr(self.lib, name)
3852  except AttributeError:
3853  return False
3854 
3855  return True
3856 
3858  for name, value in clang.enumerations.TokenKinds:
3859  TokenKind.register(value, name)
3860 
3861 conf = Config()
3863 
3864 __all__ = [
3865  'Config',
3866  'CodeCompletionResults',
3867  'CompilationDatabase',
3868  'CompileCommands',
3869  'CompileCommand',
3870  'CursorKind',
3871  'Cursor',
3872  'Diagnostic',
3873  'File',
3874  'FixIt',
3875  'Index',
3876  'SourceLocation',
3877  'SourceRange',
3878  'TokenKind',
3879  'Token',
3880  'TranslationUnitLoadError',
3881  'TranslationUnit',
3882  'TypeKind',
3883  'Type',
3884 ]
def enum_value(self)
Definition: cindex.py:1531
def canonical(self)
Definition: cindex.py:1482
def get_location(self, filename, position)
Definition: cindex.py:2610
def get_arguments(self)
Definition: cindex.py:1616
def from_result(res, fn, args)
Definition: cindex.py:156
def __eq__(self, other)
Definition: cindex.py:263
def mangled_name(self)
Definition: cindex.py:1420
def displayname(self)
Definition: cindex.py:1406
def get_tokens(self, locations=None, extent=None)
Definition: cindex.py:2782
def __getitem__(self, i)
Definition: cindex.py:2919
def referenced(self)
Definition: cindex.py:1596
def codeComplete(self, path, line, column, unsaved_files=None, include_macros=False, include_code_patterns=False, include_brief_comments=False)
Definition: cindex.py:2739
def __ne__(self, other)
Definition: cindex.py:2134
def spelling(self)
Definition: cindex.py:2124
def reparse(self, unsaved_files=None, options=0)
Definition: cindex.py:2686
object getattr(handle obj, handle name)
Definition: pytypes.h:403
def is_pod(self)
Definition: cindex.py:2038
def register_enumerations()
Definition: cindex.py:3857
def __init__(self, obj)
Definition: cindex.py:2148
def get_template_argument_type(self, num)
Definition: cindex.py:1631
def spelling(self)
Definition: cindex.py:1398
def __init__(self, src, tgt, loc, depth)
Definition: cindex.py:2839
def set_compatibility_check(check_status)
Definition: cindex.py:3789
def get_tokens(self)
Definition: cindex.py:1671
def is_attribute(self)
Definition: cindex.py:592
def is_restrict_qualified(self)
Definition: cindex.py:2024
def from_result(res, fn, args)
Definition: cindex.py:2926
def is_static_method(self)
Definition: cindex.py:1359
def set_library_file(filename)
Definition: cindex.py:3780
def is_const_method(self)
Definition: cindex.py:1315
def __repr__(self)
Definition: cindex.py:1825
def cursor(self)
Definition: cindex.py:3015
def is_reference(self)
Definition: cindex.py:580
def from_location(tu, location)
Definition: cindex.py:1294
def __ne__(self, other)
Definition: cindex.py:220
def category_number(self)
Definition: cindex.py:380
def is_translation_unit(self)
Definition: cindex.py:600
def element_type(self)
Definition: cindex.py:1948
def semantic_parent(self)
Definition: cindex.py:1573
Exception Classes ###.
Definition: cindex.py:80
def __init__(self, value)
Definition: cindex.py:1745
def __eq__(self, other)
Definition: cindex.py:2128
def __repr__(self)
Definition: cindex.py:488
def __init__(self, value)
Definition: cindex.py:528
def save(self, filename)
Definition: cindex.py:2715
def access_specifier(self)
Definition: cindex.py:1461
def is_invalid(self)
Definition: cindex.py:596
def _get_instantiation(self)
Definition: cindex.py:167
def is_function_variadic(self)
Definition: cindex.py:2032
size_t len(handle h)
Definition: pytypes.h:1361
def enum_type(self)
Definition: cindex.py:1518
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 >
Definition: date.h:5663
def get_pointee(self)
Definition: cindex.py:2042
def location(self)
Definition: cindex.py:1428
def underlying_typedef_type(self)
Definition: cindex.py:1504
def extent(self)
Definition: cindex.py:1439
def is_mutable_field(self)
Definition: cindex.py:1347
def __repr__(self)
Definition: cindex.py:402
def get_named_type(self)
Definition: cindex.py:2078
def __ne__(self, other)
Definition: cindex.py:1305
def kind(self)
Definition: cindex.py:3000
def __init__(self, ptr)
Definition: cindex.py:308
def __ne__(self, other)
Definition: cindex.py:266
def get_bitfield_width(self)
Definition: cindex.py:1697
def get_field_offsetof(self)
Definition: cindex.py:1679
def from_result(res, fn, args)
Definition: cindex.py:1982
def raw_comment(self)
Definition: cindex.py:1612
def __getitem__(self, key)
Definition: cindex.py:2292
def get_canonical(self)
Definition: cindex.py:1996
def is_statement(self)
Definition: cindex.py:588
def is_default_constructor(self)
Definition: cindex.py:1331
def get_children(self)
Definition: cindex.py:1643
def register(value, name)
Definition: cindex.py:502
def severity(self)
Definition: cindex.py:315
def get_align(self)
Definition: cindex.py:2083
def create(excludeDecls=False)
Definition: cindex.py:2390
def is_virtual_method(self)
Definition: cindex.py:1365
def register_functions(lib, ignore_errors)
Definition: cindex.py:3751
def __init__(self, tu, memory, count)
Definition: cindex.py:437
def __bytes__(self)
Definition: cindex.py:2816
def __init__(self, enumeration, message)
Definition: cindex.py:2864
def __eq__(self, other)
Definition: cindex.py:1302
def get_ref_qualifier(self)
Definition: cindex.py:2101
def is_bitfield(self)
Definition: cindex.py:1691
def spelling(self)
Definition: cindex.py:323
def __repr__(self)
Definition: cindex.py:2819
def register_function(lib, item, ignore_errors)
Definition: cindex.py:3730
def parse(self, path, args=None, unsaved_files=None, options=0)
Definition: cindex.py:2405
def __eq__(self, other)
Definition: cindex.py:217
def from_position(tu, file, line, column)
Definition: cindex.py:180
def get_filename(self)
Definition: cindex.py:3819
def children(self)
Definition: cindex.py:363
return isinstance(obj, type)
def is_copy_constructor(self)
Definition: cindex.py:1326
def __init__(self, enumeration, message)
Definition: cindex.py:109
def translation_unit(self)
Definition: cindex.py:1975
def is_declaration(self)
Definition: cindex.py:576
def from_source(cls, filename, args=None, unsaved_files=None, options=0, index=None)
Definition: cindex.py:2462
def __del__(self)
Definition: cindex.py:2398
def argument_types(self)
Definition: cindex.py:1909
def __init__(self, range, value)
Definition: cindex.py:416
def storage_class(self)
Definition: cindex.py:1450
CIndex Objects ##.
Definition: cindex.py:2143
def get_class_type(self)
Definition: cindex.py:2072
def from_param(self)
Definition: cindex.py:406
def get_offset(self, fieldname)
Definition: cindex.py:2095
def time(self)
Definition: cindex.py:2812
def get_size(self)
Definition: cindex.py:2089
def is_unexposed(self)
Definition: cindex.py:608
def brief_comment(self)
Definition: cindex.py:1607
def element_count(self)
Definition: cindex.py:1961
def get_array_size(self)
Definition: cindex.py:2066
def __init__(self, completionString, key)
Definition: cindex.py:2198
def __get__(self, instance, instance_type=None)
Definition: cindex.py:137
def get_tokens(tu, extent)
Definition: cindex.py:446
def spelling(self)
Definition: cindex.py:2992
def location(self)
Definition: cindex.py:319
def get_result(self)
Definition: cindex.py:2054
def from_locations(start, end)
Definition: cindex.py:244
def get_cindex_library(self)
Definition: cindex.py:3838
def is_const_qualified(self)
Definition: cindex.py:2008
def getCompileCommands(self, filename)
Definition: cindex.py:2961
def from_cursor_result(res, fn, args)
Definition: cindex.py:1728
def is_pure_virtual_method(self)
Definition: cindex.py:1353
def get_num_template_arguments(self)
Definition: cindex.py:1622
def __getitem__(self, key)
Definition: cindex.py:2345
def spelling(self)
Definition: cindex.py:1821
def __del__(self)
Definition: cindex.py:152
def get_array_element_type(self)
Definition: cindex.py:2060
def is_expression(self)
Definition: cindex.py:584
def from_result(res, fn, args)
Definition: cindex.py:1704
def is_default_method(self)
Definition: cindex.py:1341
def get_template_argument_kind(self, num)
Definition: cindex.py:1626
def __repr__(self)
Definition: cindex.py:420
def name(self)
Definition: cindex.py:2807
def get_file(self, filename)
Definition: cindex.py:2605
def get_fields(self)
Definition: cindex.py:2108
const detail::type_info * type
Definition: cast.h:453
def is_move_constructor(self)
Definition: cindex.py:1336
def type(self)
Definition: cindex.py:1472
def __init__(self, value, name)
Definition: cindex.py:483
def __init__(self, message)
Definition: cindex.py:3724
return os str()
def hash(self)
Definition: cindex.py:1565
def set_library_path(path)
Definition: cindex.py:3771
def __init__(self, ccmds)
Definition: cindex.py:2910
def get_usr(self)
Definition: cindex.py:1381
def objc_type_encoding(self)
Definition: cindex.py:1556
def from_value(value)
Definition: cindex.py:492
def extent(self)
Definition: cindex.py:3010
def is_converting_constructor(self)
Definition: cindex.py:1321
def lexical_parent(self)
Definition: cindex.py:1581
def __init__(self, wrapped)
Definition: cindex.py:130
iterator iter(handle obj)
Definition: pytypes.h:1394
def disable_option(self)
Definition: cindex.py:395
T cast(const handle &handle)
Definition: cast.h:1659
def get_template_argument_unsigned_value(self, num)
Definition: cindex.py:1639
def from_cursor_result(res, fn, args)
Definition: cindex.py:2823
def is_volatile_qualified(self)
Definition: cindex.py:2016
def __contains__(self, other)
Definition: cindex.py:269
def function_exists(self, name)
Definition: cindex.py:3849
def __init__(self, cmd, ccmds)
Definition: cindex.py:2877
def from_name(translation_unit, file_name)
Definition: cindex.py:2802
def lib(self)
Definition: cindex.py:3813
void print(Args &&...args)
Definition: pybind11.h:1849
def translation_unit(self)
Definition: cindex.py:1589
def is_anonymous(self)
Definition: cindex.py:1683
def location(self)
Definition: cindex.py:3005
auto range
Definition: cast.h:455
def is_definition(self)
Definition: cindex.py:1308
def get_definition(self)
Definition: cindex.py:1371
def from_result(res, fn, args)
Definition: cindex.py:2943
void setattr(handle obj, handle name, handle value)
Definition: pytypes.h:433
def __repr__(self)
Definition: cindex.py:612
def walk_preorder(self)
Definition: cindex.py:1661
def read(self, path)
Definition: cindex.py:2401
def result_type(self)
Definition: cindex.py:1496
def get_declaration(self)
Definition: cindex.py:2048
def from_ast_file(cls, filename, index=None)
Definition: cindex.py:2541
std::string join(const T &v, std::string delim=",")
Simple function to join a string.
Definition: CLI11.hpp:277
def is_preprocessing(self)
Definition: cindex.py:604
bool hasattr(handle obj, handle name)
Definition: pytypes.h:387
def __init__(self, ptr, index)
Definition: cindex.py:2562
def category_name(self)
Definition: cindex.py:385
def get_template_argument_value(self, num)
Definition: cindex.py:1635
def from_offset(tu, file, offset)
Definition: cindex.py:188
def get_extent(self, filename, locations)
Definition: cindex.py:2626