cindex.py 125 KB

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