SemaCodeComplete.cpp 155 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231
  1. //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the code-completion semantic actions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "Sema.h"
  14. #include "Lookup.h"
  15. #include "clang/Sema/CodeCompleteConsumer.h"
  16. #include "clang/Sema/ExternalSemaSource.h"
  17. #include "clang/AST/ExprCXX.h"
  18. #include "clang/AST/ExprObjC.h"
  19. #include "clang/Lex/MacroInfo.h"
  20. #include "clang/Lex/Preprocessor.h"
  21. #include "llvm/ADT/SmallPtrSet.h"
  22. #include "llvm/ADT/StringExtras.h"
  23. #include "llvm/ADT/StringSwitch.h"
  24. #include <list>
  25. #include <map>
  26. #include <vector>
  27. using namespace clang;
  28. namespace {
  29. /// \brief A container of code-completion results.
  30. class ResultBuilder {
  31. public:
  32. /// \brief The type of a name-lookup filter, which can be provided to the
  33. /// name-lookup routines to specify which declarations should be included in
  34. /// the result set (when it returns true) and which declarations should be
  35. /// filtered out (returns false).
  36. typedef bool (ResultBuilder::*LookupFilter)(NamedDecl *) const;
  37. typedef CodeCompleteConsumer::Result Result;
  38. private:
  39. /// \brief The actual results we have found.
  40. std::vector<Result> Results;
  41. /// \brief A record of all of the declarations we have found and placed
  42. /// into the result set, used to ensure that no declaration ever gets into
  43. /// the result set twice.
  44. llvm::SmallPtrSet<Decl*, 16> AllDeclsFound;
  45. typedef std::pair<NamedDecl *, unsigned> DeclIndexPair;
  46. /// \brief An entry in the shadow map, which is optimized to store
  47. /// a single (declaration, index) mapping (the common case) but
  48. /// can also store a list of (declaration, index) mappings.
  49. class ShadowMapEntry {
  50. typedef llvm::SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
  51. /// \brief Contains either the solitary NamedDecl * or a vector
  52. /// of (declaration, index) pairs.
  53. llvm::PointerUnion<NamedDecl *, DeclIndexPairVector*> DeclOrVector;
  54. /// \brief When the entry contains a single declaration, this is
  55. /// the index associated with that entry.
  56. unsigned SingleDeclIndex;
  57. public:
  58. ShadowMapEntry() : DeclOrVector(), SingleDeclIndex(0) { }
  59. void Add(NamedDecl *ND, unsigned Index) {
  60. if (DeclOrVector.isNull()) {
  61. // 0 - > 1 elements: just set the single element information.
  62. DeclOrVector = ND;
  63. SingleDeclIndex = Index;
  64. return;
  65. }
  66. if (NamedDecl *PrevND = DeclOrVector.dyn_cast<NamedDecl *>()) {
  67. // 1 -> 2 elements: create the vector of results and push in the
  68. // existing declaration.
  69. DeclIndexPairVector *Vec = new DeclIndexPairVector;
  70. Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
  71. DeclOrVector = Vec;
  72. }
  73. // Add the new element to the end of the vector.
  74. DeclOrVector.get<DeclIndexPairVector*>()->push_back(
  75. DeclIndexPair(ND, Index));
  76. }
  77. void Destroy() {
  78. if (DeclIndexPairVector *Vec
  79. = DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
  80. delete Vec;
  81. DeclOrVector = ((NamedDecl *)0);
  82. }
  83. }
  84. // Iteration.
  85. class iterator;
  86. iterator begin() const;
  87. iterator end() const;
  88. };
  89. /// \brief A mapping from declaration names to the declarations that have
  90. /// this name within a particular scope and their index within the list of
  91. /// results.
  92. typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
  93. /// \brief The semantic analysis object for which results are being
  94. /// produced.
  95. Sema &SemaRef;
  96. /// \brief If non-NULL, a filter function used to remove any code-completion
  97. /// results that are not desirable.
  98. LookupFilter Filter;
  99. /// \brief Whether we should allow declarations as
  100. /// nested-name-specifiers that would otherwise be filtered out.
  101. bool AllowNestedNameSpecifiers;
  102. /// \brief If set, the type that we would prefer our resulting value
  103. /// declarations to have.
  104. ///
  105. /// Closely matching the preferred type gives a boost to a result's
  106. /// priority.
  107. CanQualType PreferredType;
  108. /// \brief A list of shadow maps, which is used to model name hiding at
  109. /// different levels of, e.g., the inheritance hierarchy.
  110. std::list<ShadowMap> ShadowMaps;
  111. void AdjustResultPriorityForPreferredType(Result &R);
  112. public:
  113. explicit ResultBuilder(Sema &SemaRef, LookupFilter Filter = 0)
  114. : SemaRef(SemaRef), Filter(Filter), AllowNestedNameSpecifiers(false) { }
  115. /// \brief Whether we should include code patterns in the completion
  116. /// results.
  117. bool includeCodePatterns() const {
  118. return SemaRef.CodeCompleter &&
  119. SemaRef.CodeCompleter->includeCodePatterns();
  120. }
  121. /// \brief Set the filter used for code-completion results.
  122. void setFilter(LookupFilter Filter) {
  123. this->Filter = Filter;
  124. }
  125. typedef std::vector<Result>::iterator iterator;
  126. iterator begin() { return Results.begin(); }
  127. iterator end() { return Results.end(); }
  128. Result *data() { return Results.empty()? 0 : &Results.front(); }
  129. unsigned size() const { return Results.size(); }
  130. bool empty() const { return Results.empty(); }
  131. /// \brief Specify the preferred type.
  132. void setPreferredType(QualType T) {
  133. PreferredType = SemaRef.Context.getCanonicalType(T);
  134. }
  135. /// \brief Specify whether nested-name-specifiers are allowed.
  136. void allowNestedNameSpecifiers(bool Allow = true) {
  137. AllowNestedNameSpecifiers = Allow;
  138. }
  139. /// \brief Determine whether the given declaration is at all interesting
  140. /// as a code-completion result.
  141. ///
  142. /// \param ND the declaration that we are inspecting.
  143. ///
  144. /// \param AsNestedNameSpecifier will be set true if this declaration is
  145. /// only interesting when it is a nested-name-specifier.
  146. bool isInterestingDecl(NamedDecl *ND, bool &AsNestedNameSpecifier) const;
  147. /// \brief Check whether the result is hidden by the Hiding declaration.
  148. ///
  149. /// \returns true if the result is hidden and cannot be found, false if
  150. /// the hidden result could still be found. When false, \p R may be
  151. /// modified to describe how the result can be found (e.g., via extra
  152. /// qualification).
  153. bool CheckHiddenResult(Result &R, DeclContext *CurContext,
  154. NamedDecl *Hiding);
  155. /// \brief Add a new result to this result set (if it isn't already in one
  156. /// of the shadow maps), or replace an existing result (for, e.g., a
  157. /// redeclaration).
  158. ///
  159. /// \param CurContext the result to add (if it is unique).
  160. ///
  161. /// \param R the context in which this result will be named.
  162. void MaybeAddResult(Result R, DeclContext *CurContext = 0);
  163. /// \brief Add a new result to this result set, where we already know
  164. /// the hiding declation (if any).
  165. ///
  166. /// \param R the result to add (if it is unique).
  167. ///
  168. /// \param CurContext the context in which this result will be named.
  169. ///
  170. /// \param Hiding the declaration that hides the result.
  171. ///
  172. /// \param InBaseClass whether the result was found in a base
  173. /// class of the searched context.
  174. void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
  175. bool InBaseClass);
  176. /// \brief Add a new non-declaration result to this result set.
  177. void AddResult(Result R);
  178. /// \brief Enter into a new scope.
  179. void EnterNewScope();
  180. /// \brief Exit from the current scope.
  181. void ExitScope();
  182. /// \brief Ignore this declaration, if it is seen again.
  183. void Ignore(Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
  184. /// \name Name lookup predicates
  185. ///
  186. /// These predicates can be passed to the name lookup functions to filter the
  187. /// results of name lookup. All of the predicates have the same type, so that
  188. ///
  189. //@{
  190. bool IsOrdinaryName(NamedDecl *ND) const;
  191. bool IsOrdinaryNonTypeName(NamedDecl *ND) const;
  192. bool IsIntegralConstantValue(NamedDecl *ND) const;
  193. bool IsOrdinaryNonValueName(NamedDecl *ND) const;
  194. bool IsNestedNameSpecifier(NamedDecl *ND) const;
  195. bool IsEnum(NamedDecl *ND) const;
  196. bool IsClassOrStruct(NamedDecl *ND) const;
  197. bool IsUnion(NamedDecl *ND) const;
  198. bool IsNamespace(NamedDecl *ND) const;
  199. bool IsNamespaceOrAlias(NamedDecl *ND) const;
  200. bool IsType(NamedDecl *ND) const;
  201. bool IsMember(NamedDecl *ND) const;
  202. bool IsObjCIvar(NamedDecl *ND) const;
  203. bool IsObjCMessageReceiver(NamedDecl *ND) const;
  204. //@}
  205. };
  206. }
  207. class ResultBuilder::ShadowMapEntry::iterator {
  208. llvm::PointerUnion<NamedDecl*, const DeclIndexPair*> DeclOrIterator;
  209. unsigned SingleDeclIndex;
  210. public:
  211. typedef DeclIndexPair value_type;
  212. typedef value_type reference;
  213. typedef std::ptrdiff_t difference_type;
  214. typedef std::input_iterator_tag iterator_category;
  215. class pointer {
  216. DeclIndexPair Value;
  217. public:
  218. pointer(const DeclIndexPair &Value) : Value(Value) { }
  219. const DeclIndexPair *operator->() const {
  220. return &Value;
  221. }
  222. };
  223. iterator() : DeclOrIterator((NamedDecl *)0), SingleDeclIndex(0) { }
  224. iterator(NamedDecl *SingleDecl, unsigned Index)
  225. : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) { }
  226. iterator(const DeclIndexPair *Iterator)
  227. : DeclOrIterator(Iterator), SingleDeclIndex(0) { }
  228. iterator &operator++() {
  229. if (DeclOrIterator.is<NamedDecl *>()) {
  230. DeclOrIterator = (NamedDecl *)0;
  231. SingleDeclIndex = 0;
  232. return *this;
  233. }
  234. const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair*>();
  235. ++I;
  236. DeclOrIterator = I;
  237. return *this;
  238. }
  239. iterator operator++(int) {
  240. iterator tmp(*this);
  241. ++(*this);
  242. return tmp;
  243. }
  244. reference operator*() const {
  245. if (NamedDecl *ND = DeclOrIterator.dyn_cast<NamedDecl *>())
  246. return reference(ND, SingleDeclIndex);
  247. return *DeclOrIterator.get<const DeclIndexPair*>();
  248. }
  249. pointer operator->() const {
  250. return pointer(**this);
  251. }
  252. friend bool operator==(const iterator &X, const iterator &Y) {
  253. return X.DeclOrIterator.getOpaqueValue()
  254. == Y.DeclOrIterator.getOpaqueValue() &&
  255. X.SingleDeclIndex == Y.SingleDeclIndex;
  256. }
  257. friend bool operator!=(const iterator &X, const iterator &Y) {
  258. return !(X == Y);
  259. }
  260. };
  261. ResultBuilder::ShadowMapEntry::iterator
  262. ResultBuilder::ShadowMapEntry::begin() const {
  263. if (DeclOrVector.isNull())
  264. return iterator();
  265. if (NamedDecl *ND = DeclOrVector.dyn_cast<NamedDecl *>())
  266. return iterator(ND, SingleDeclIndex);
  267. return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
  268. }
  269. ResultBuilder::ShadowMapEntry::iterator
  270. ResultBuilder::ShadowMapEntry::end() const {
  271. if (DeclOrVector.is<NamedDecl *>() || DeclOrVector.isNull())
  272. return iterator();
  273. return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
  274. }
  275. /// \brief Compute the qualification required to get from the current context
  276. /// (\p CurContext) to the target context (\p TargetContext).
  277. ///
  278. /// \param Context the AST context in which the qualification will be used.
  279. ///
  280. /// \param CurContext the context where an entity is being named, which is
  281. /// typically based on the current scope.
  282. ///
  283. /// \param TargetContext the context in which the named entity actually
  284. /// resides.
  285. ///
  286. /// \returns a nested name specifier that refers into the target context, or
  287. /// NULL if no qualification is needed.
  288. static NestedNameSpecifier *
  289. getRequiredQualification(ASTContext &Context,
  290. DeclContext *CurContext,
  291. DeclContext *TargetContext) {
  292. llvm::SmallVector<DeclContext *, 4> TargetParents;
  293. for (DeclContext *CommonAncestor = TargetContext;
  294. CommonAncestor && !CommonAncestor->Encloses(CurContext);
  295. CommonAncestor = CommonAncestor->getLookupParent()) {
  296. if (CommonAncestor->isTransparentContext() ||
  297. CommonAncestor->isFunctionOrMethod())
  298. continue;
  299. TargetParents.push_back(CommonAncestor);
  300. }
  301. NestedNameSpecifier *Result = 0;
  302. while (!TargetParents.empty()) {
  303. DeclContext *Parent = TargetParents.back();
  304. TargetParents.pop_back();
  305. if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Parent))
  306. Result = NestedNameSpecifier::Create(Context, Result, Namespace);
  307. else if (TagDecl *TD = dyn_cast<TagDecl>(Parent))
  308. Result = NestedNameSpecifier::Create(Context, Result,
  309. false,
  310. Context.getTypeDeclType(TD).getTypePtr());
  311. }
  312. return Result;
  313. }
  314. bool ResultBuilder::isInterestingDecl(NamedDecl *ND,
  315. bool &AsNestedNameSpecifier) const {
  316. AsNestedNameSpecifier = false;
  317. ND = ND->getUnderlyingDecl();
  318. unsigned IDNS = ND->getIdentifierNamespace();
  319. // Skip unnamed entities.
  320. if (!ND->getDeclName())
  321. return false;
  322. // Friend declarations and declarations introduced due to friends are never
  323. // added as results.
  324. if (IDNS & (Decl::IDNS_OrdinaryFriend | Decl::IDNS_TagFriend))
  325. return false;
  326. // Class template (partial) specializations are never added as results.
  327. if (isa<ClassTemplateSpecializationDecl>(ND) ||
  328. isa<ClassTemplatePartialSpecializationDecl>(ND))
  329. return false;
  330. // Using declarations themselves are never added as results.
  331. if (isa<UsingDecl>(ND))
  332. return false;
  333. // Some declarations have reserved names that we don't want to ever show.
  334. if (const IdentifierInfo *Id = ND->getIdentifier()) {
  335. // __va_list_tag is a freak of nature. Find it and skip it.
  336. if (Id->isStr("__va_list_tag") || Id->isStr("__builtin_va_list"))
  337. return false;
  338. // Filter out names reserved for the implementation (C99 7.1.3,
  339. // C++ [lib.global.names]) if they come from a system header.
  340. //
  341. // FIXME: Add predicate for this.
  342. if (Id->getLength() >= 2) {
  343. const char *Name = Id->getNameStart();
  344. if (Name[0] == '_' &&
  345. (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')) &&
  346. (ND->getLocation().isInvalid() ||
  347. SemaRef.SourceMgr.isInSystemHeader(
  348. SemaRef.SourceMgr.getSpellingLoc(ND->getLocation()))))
  349. return false;
  350. }
  351. }
  352. // C++ constructors are never found by name lookup.
  353. if (isa<CXXConstructorDecl>(ND))
  354. return false;
  355. // Filter out any unwanted results.
  356. if (Filter && !(this->*Filter)(ND)) {
  357. // Check whether it is interesting as a nested-name-specifier.
  358. if (AllowNestedNameSpecifiers && SemaRef.getLangOptions().CPlusPlus &&
  359. IsNestedNameSpecifier(ND) &&
  360. (Filter != &ResultBuilder::IsMember ||
  361. (isa<CXXRecordDecl>(ND) &&
  362. cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
  363. AsNestedNameSpecifier = true;
  364. return true;
  365. }
  366. return false;
  367. }
  368. if (Filter == &ResultBuilder::IsNestedNameSpecifier)
  369. AsNestedNameSpecifier = true;
  370. // ... then it must be interesting!
  371. return true;
  372. }
  373. bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
  374. NamedDecl *Hiding) {
  375. // In C, there is no way to refer to a hidden name.
  376. // FIXME: This isn't true; we can find a tag name hidden by an ordinary
  377. // name if we introduce the tag type.
  378. if (!SemaRef.getLangOptions().CPlusPlus)
  379. return true;
  380. DeclContext *HiddenCtx = R.Declaration->getDeclContext()->getLookupContext();
  381. // There is no way to qualify a name declared in a function or method.
  382. if (HiddenCtx->isFunctionOrMethod())
  383. return true;
  384. if (HiddenCtx == Hiding->getDeclContext()->getLookupContext())
  385. return true;
  386. // We can refer to the result with the appropriate qualification. Do it.
  387. R.Hidden = true;
  388. R.QualifierIsInformative = false;
  389. if (!R.Qualifier)
  390. R.Qualifier = getRequiredQualification(SemaRef.Context,
  391. CurContext,
  392. R.Declaration->getDeclContext());
  393. return false;
  394. }
  395. enum SimplifiedTypeClass {
  396. STC_Arithmetic,
  397. STC_Array,
  398. STC_Block,
  399. STC_Function,
  400. STC_ObjectiveC,
  401. STC_Other,
  402. STC_Pointer,
  403. STC_Record,
  404. STC_Void
  405. };
  406. /// \brief A simplified classification of types used to determine whether two
  407. /// types are "similar enough" when adjusting priorities.
  408. static SimplifiedTypeClass getSimplifiedTypeClass(CanQualType T) {
  409. switch (T->getTypeClass()) {
  410. case Type::Builtin:
  411. switch (cast<BuiltinType>(T)->getKind()) {
  412. case BuiltinType::Void:
  413. return STC_Void;
  414. case BuiltinType::NullPtr:
  415. return STC_Pointer;
  416. case BuiltinType::Overload:
  417. case BuiltinType::Dependent:
  418. case BuiltinType::UndeducedAuto:
  419. return STC_Other;
  420. case BuiltinType::ObjCId:
  421. case BuiltinType::ObjCClass:
  422. case BuiltinType::ObjCSel:
  423. return STC_ObjectiveC;
  424. default:
  425. return STC_Arithmetic;
  426. }
  427. return STC_Other;
  428. case Type::Complex:
  429. return STC_Arithmetic;
  430. case Type::Pointer:
  431. return STC_Pointer;
  432. case Type::BlockPointer:
  433. return STC_Block;
  434. case Type::LValueReference:
  435. case Type::RValueReference:
  436. return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
  437. case Type::ConstantArray:
  438. case Type::IncompleteArray:
  439. case Type::VariableArray:
  440. case Type::DependentSizedArray:
  441. return STC_Array;
  442. case Type::DependentSizedExtVector:
  443. case Type::Vector:
  444. case Type::ExtVector:
  445. return STC_Arithmetic;
  446. case Type::FunctionProto:
  447. case Type::FunctionNoProto:
  448. return STC_Function;
  449. case Type::Record:
  450. return STC_Record;
  451. case Type::Enum:
  452. return STC_Arithmetic;
  453. case Type::ObjCObject:
  454. case Type::ObjCInterface:
  455. case Type::ObjCObjectPointer:
  456. return STC_ObjectiveC;
  457. default:
  458. return STC_Other;
  459. }
  460. }
  461. /// \brief Get the type that a given expression will have if this declaration
  462. /// is used as an expression in its "typical" code-completion form.
  463. static QualType getDeclUsageType(ASTContext &C, NamedDecl *ND) {
  464. ND = cast<NamedDecl>(ND->getUnderlyingDecl());
  465. if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
  466. return C.getTypeDeclType(Type);
  467. if (ObjCInterfaceDecl *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
  468. return C.getObjCInterfaceType(Iface);
  469. QualType T;
  470. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
  471. T = Function->getCallResultType();
  472. else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
  473. T = Method->getSendResultType();
  474. else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
  475. T = FunTmpl->getTemplatedDecl()->getCallResultType();
  476. else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
  477. T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
  478. else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
  479. T = Property->getType();
  480. else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
  481. T = Value->getType();
  482. else
  483. return QualType();
  484. return T.getNonReferenceType();
  485. }
  486. void ResultBuilder::AdjustResultPriorityForPreferredType(Result &R) {
  487. QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
  488. if (T.isNull())
  489. return;
  490. CanQualType TC = SemaRef.Context.getCanonicalType(T);
  491. // Check for exactly-matching types (modulo qualifiers).
  492. if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
  493. R.Priority /= CCF_ExactTypeMatch;
  494. // Check for nearly-matching types, based on classification of each.
  495. else if ((getSimplifiedTypeClass(PreferredType)
  496. == getSimplifiedTypeClass(TC)) &&
  497. !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
  498. R.Priority /= CCF_SimilarTypeMatch;
  499. }
  500. void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
  501. assert(!ShadowMaps.empty() && "Must enter into a results scope");
  502. if (R.Kind != Result::RK_Declaration) {
  503. // For non-declaration results, just add the result.
  504. Results.push_back(R);
  505. return;
  506. }
  507. // Look through using declarations.
  508. if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
  509. MaybeAddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext);
  510. return;
  511. }
  512. Decl *CanonDecl = R.Declaration->getCanonicalDecl();
  513. unsigned IDNS = CanonDecl->getIdentifierNamespace();
  514. bool AsNestedNameSpecifier = false;
  515. if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
  516. return;
  517. ShadowMap &SMap = ShadowMaps.back();
  518. ShadowMapEntry::iterator I, IEnd;
  519. ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
  520. if (NamePos != SMap.end()) {
  521. I = NamePos->second.begin();
  522. IEnd = NamePos->second.end();
  523. }
  524. for (; I != IEnd; ++I) {
  525. NamedDecl *ND = I->first;
  526. unsigned Index = I->second;
  527. if (ND->getCanonicalDecl() == CanonDecl) {
  528. // This is a redeclaration. Always pick the newer declaration.
  529. Results[Index].Declaration = R.Declaration;
  530. // We're done.
  531. return;
  532. }
  533. }
  534. // This is a new declaration in this scope. However, check whether this
  535. // declaration name is hidden by a similarly-named declaration in an outer
  536. // scope.
  537. std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
  538. --SMEnd;
  539. for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
  540. ShadowMapEntry::iterator I, IEnd;
  541. ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
  542. if (NamePos != SM->end()) {
  543. I = NamePos->second.begin();
  544. IEnd = NamePos->second.end();
  545. }
  546. for (; I != IEnd; ++I) {
  547. // A tag declaration does not hide a non-tag declaration.
  548. if (I->first->hasTagIdentifierNamespace() &&
  549. (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
  550. Decl::IDNS_ObjCProtocol)))
  551. continue;
  552. // Protocols are in distinct namespaces from everything else.
  553. if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
  554. || (IDNS & Decl::IDNS_ObjCProtocol)) &&
  555. I->first->getIdentifierNamespace() != IDNS)
  556. continue;
  557. // The newly-added result is hidden by an entry in the shadow map.
  558. if (CheckHiddenResult(R, CurContext, I->first))
  559. return;
  560. break;
  561. }
  562. }
  563. // Make sure that any given declaration only shows up in the result set once.
  564. if (!AllDeclsFound.insert(CanonDecl))
  565. return;
  566. // If the filter is for nested-name-specifiers, then this result starts a
  567. // nested-name-specifier.
  568. if (AsNestedNameSpecifier) {
  569. R.StartsNestedNameSpecifier = true;
  570. R.Priority = CCP_NestedNameSpecifier;
  571. } else if (!PreferredType.isNull())
  572. AdjustResultPriorityForPreferredType(R);
  573. // If this result is supposed to have an informative qualifier, add one.
  574. if (R.QualifierIsInformative && !R.Qualifier &&
  575. !R.StartsNestedNameSpecifier) {
  576. DeclContext *Ctx = R.Declaration->getDeclContext();
  577. if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
  578. R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
  579. else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
  580. R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
  581. SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
  582. else
  583. R.QualifierIsInformative = false;
  584. }
  585. // Insert this result into the set of results and into the current shadow
  586. // map.
  587. SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
  588. Results.push_back(R);
  589. }
  590. void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
  591. NamedDecl *Hiding, bool InBaseClass = false) {
  592. if (R.Kind != Result::RK_Declaration) {
  593. // For non-declaration results, just add the result.
  594. Results.push_back(R);
  595. return;
  596. }
  597. // Look through using declarations.
  598. if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
  599. AddResult(Result(Using->getTargetDecl(), R.Qualifier), CurContext, Hiding);
  600. return;
  601. }
  602. bool AsNestedNameSpecifier = false;
  603. if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
  604. return;
  605. if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
  606. return;
  607. // Make sure that any given declaration only shows up in the result set once.
  608. if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()))
  609. return;
  610. // If the filter is for nested-name-specifiers, then this result starts a
  611. // nested-name-specifier.
  612. if (AsNestedNameSpecifier) {
  613. R.StartsNestedNameSpecifier = true;
  614. R.Priority = CCP_NestedNameSpecifier;
  615. }
  616. else if (Filter == &ResultBuilder::IsMember && !R.Qualifier && InBaseClass &&
  617. isa<CXXRecordDecl>(R.Declaration->getDeclContext()
  618. ->getLookupContext()))
  619. R.QualifierIsInformative = true;
  620. // If this result is supposed to have an informative qualifier, add one.
  621. if (R.QualifierIsInformative && !R.Qualifier &&
  622. !R.StartsNestedNameSpecifier) {
  623. DeclContext *Ctx = R.Declaration->getDeclContext();
  624. if (NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
  625. R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, Namespace);
  626. else if (TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
  627. R.Qualifier = NestedNameSpecifier::Create(SemaRef.Context, 0, false,
  628. SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
  629. else
  630. R.QualifierIsInformative = false;
  631. }
  632. // Adjust the priority if this result comes from a base class.
  633. if (InBaseClass)
  634. R.Priority += CCD_InBaseClass;
  635. if (!PreferredType.isNull())
  636. AdjustResultPriorityForPreferredType(R);
  637. // Insert this result into the set of results.
  638. Results.push_back(R);
  639. }
  640. void ResultBuilder::AddResult(Result R) {
  641. assert(R.Kind != Result::RK_Declaration &&
  642. "Declaration results need more context");
  643. Results.push_back(R);
  644. }
  645. /// \brief Enter into a new scope.
  646. void ResultBuilder::EnterNewScope() {
  647. ShadowMaps.push_back(ShadowMap());
  648. }
  649. /// \brief Exit from the current scope.
  650. void ResultBuilder::ExitScope() {
  651. for (ShadowMap::iterator E = ShadowMaps.back().begin(),
  652. EEnd = ShadowMaps.back().end();
  653. E != EEnd;
  654. ++E)
  655. E->second.Destroy();
  656. ShadowMaps.pop_back();
  657. }
  658. /// \brief Determines whether this given declaration will be found by
  659. /// ordinary name lookup.
  660. bool ResultBuilder::IsOrdinaryName(NamedDecl *ND) const {
  661. ND = cast<NamedDecl>(ND->getUnderlyingDecl());
  662. unsigned IDNS = Decl::IDNS_Ordinary;
  663. if (SemaRef.getLangOptions().CPlusPlus)
  664. IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
  665. else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
  666. return true;
  667. return ND->getIdentifierNamespace() & IDNS;
  668. }
  669. /// \brief Determines whether this given declaration will be found by
  670. /// ordinary name lookup but is not a type name.
  671. bool ResultBuilder::IsOrdinaryNonTypeName(NamedDecl *ND) const {
  672. ND = cast<NamedDecl>(ND->getUnderlyingDecl());
  673. if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND))
  674. return false;
  675. unsigned IDNS = Decl::IDNS_Ordinary;
  676. if (SemaRef.getLangOptions().CPlusPlus)
  677. IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
  678. else if (SemaRef.getLangOptions().ObjC1 && isa<ObjCIvarDecl>(ND))
  679. return true;
  680. return ND->getIdentifierNamespace() & IDNS;
  681. }
  682. bool ResultBuilder::IsIntegralConstantValue(NamedDecl *ND) const {
  683. if (!IsOrdinaryNonTypeName(ND))
  684. return 0;
  685. if (ValueDecl *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
  686. if (VD->getType()->isIntegralOrEnumerationType())
  687. return true;
  688. return false;
  689. }
  690. /// \brief Determines whether this given declaration will be found by
  691. /// ordinary name lookup.
  692. bool ResultBuilder::IsOrdinaryNonValueName(NamedDecl *ND) const {
  693. ND = cast<NamedDecl>(ND->getUnderlyingDecl());
  694. unsigned IDNS = Decl::IDNS_Ordinary;
  695. if (SemaRef.getLangOptions().CPlusPlus)
  696. IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
  697. return (ND->getIdentifierNamespace() & IDNS) &&
  698. !isa<ValueDecl>(ND) && !isa<FunctionTemplateDecl>(ND) &&
  699. !isa<ObjCPropertyDecl>(ND);
  700. }
  701. /// \brief Determines whether the given declaration is suitable as the
  702. /// start of a C++ nested-name-specifier, e.g., a class or namespace.
  703. bool ResultBuilder::IsNestedNameSpecifier(NamedDecl *ND) const {
  704. // Allow us to find class templates, too.
  705. if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
  706. ND = ClassTemplate->getTemplatedDecl();
  707. return SemaRef.isAcceptableNestedNameSpecifier(ND);
  708. }
  709. /// \brief Determines whether the given declaration is an enumeration.
  710. bool ResultBuilder::IsEnum(NamedDecl *ND) const {
  711. return isa<EnumDecl>(ND);
  712. }
  713. /// \brief Determines whether the given declaration is a class or struct.
  714. bool ResultBuilder::IsClassOrStruct(NamedDecl *ND) const {
  715. // Allow us to find class templates, too.
  716. if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
  717. ND = ClassTemplate->getTemplatedDecl();
  718. if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
  719. return RD->getTagKind() == TTK_Class ||
  720. RD->getTagKind() == TTK_Struct;
  721. return false;
  722. }
  723. /// \brief Determines whether the given declaration is a union.
  724. bool ResultBuilder::IsUnion(NamedDecl *ND) const {
  725. // Allow us to find class templates, too.
  726. if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
  727. ND = ClassTemplate->getTemplatedDecl();
  728. if (RecordDecl *RD = dyn_cast<RecordDecl>(ND))
  729. return RD->getTagKind() == TTK_Union;
  730. return false;
  731. }
  732. /// \brief Determines whether the given declaration is a namespace.
  733. bool ResultBuilder::IsNamespace(NamedDecl *ND) const {
  734. return isa<NamespaceDecl>(ND);
  735. }
  736. /// \brief Determines whether the given declaration is a namespace or
  737. /// namespace alias.
  738. bool ResultBuilder::IsNamespaceOrAlias(NamedDecl *ND) const {
  739. return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
  740. }
  741. /// \brief Determines whether the given declaration is a type.
  742. bool ResultBuilder::IsType(NamedDecl *ND) const {
  743. return isa<TypeDecl>(ND);
  744. }
  745. /// \brief Determines which members of a class should be visible via
  746. /// "." or "->". Only value declarations, nested name specifiers, and
  747. /// using declarations thereof should show up.
  748. bool ResultBuilder::IsMember(NamedDecl *ND) const {
  749. if (UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(ND))
  750. ND = Using->getTargetDecl();
  751. return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
  752. isa<ObjCPropertyDecl>(ND);
  753. }
  754. static bool isObjCReceiverType(ASTContext &C, QualType T) {
  755. T = C.getCanonicalType(T);
  756. switch (T->getTypeClass()) {
  757. case Type::ObjCObject:
  758. case Type::ObjCInterface:
  759. case Type::ObjCObjectPointer:
  760. return true;
  761. case Type::Builtin:
  762. switch (cast<BuiltinType>(T)->getKind()) {
  763. case BuiltinType::ObjCId:
  764. case BuiltinType::ObjCClass:
  765. case BuiltinType::ObjCSel:
  766. return true;
  767. default:
  768. break;
  769. }
  770. return false;
  771. default:
  772. break;
  773. }
  774. if (!C.getLangOptions().CPlusPlus)
  775. return false;
  776. // FIXME: We could perform more analysis here to determine whether a
  777. // particular class type has any conversions to Objective-C types. For now,
  778. // just accept all class types.
  779. return T->isDependentType() || T->isRecordType();
  780. }
  781. bool ResultBuilder::IsObjCMessageReceiver(NamedDecl *ND) const {
  782. QualType T = getDeclUsageType(SemaRef.Context, ND);
  783. if (T.isNull())
  784. return false;
  785. T = SemaRef.Context.getBaseElementType(T);
  786. return isObjCReceiverType(SemaRef.Context, T);
  787. }
  788. /// \rief Determines whether the given declaration is an Objective-C
  789. /// instance variable.
  790. bool ResultBuilder::IsObjCIvar(NamedDecl *ND) const {
  791. return isa<ObjCIvarDecl>(ND);
  792. }
  793. namespace {
  794. /// \brief Visible declaration consumer that adds a code-completion result
  795. /// for each visible declaration.
  796. class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
  797. ResultBuilder &Results;
  798. DeclContext *CurContext;
  799. public:
  800. CodeCompletionDeclConsumer(ResultBuilder &Results, DeclContext *CurContext)
  801. : Results(Results), CurContext(CurContext) { }
  802. virtual void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, bool InBaseClass) {
  803. Results.AddResult(ND, CurContext, Hiding, InBaseClass);
  804. }
  805. };
  806. }
  807. /// \brief Add type specifiers for the current language as keyword results.
  808. static void AddTypeSpecifierResults(const LangOptions &LangOpts,
  809. ResultBuilder &Results) {
  810. typedef CodeCompleteConsumer::Result Result;
  811. Results.AddResult(Result("short", CCP_Type));
  812. Results.AddResult(Result("long", CCP_Type));
  813. Results.AddResult(Result("signed", CCP_Type));
  814. Results.AddResult(Result("unsigned", CCP_Type));
  815. Results.AddResult(Result("void", CCP_Type));
  816. Results.AddResult(Result("char", CCP_Type));
  817. Results.AddResult(Result("int", CCP_Type));
  818. Results.AddResult(Result("float", CCP_Type));
  819. Results.AddResult(Result("double", CCP_Type));
  820. Results.AddResult(Result("enum", CCP_Type));
  821. Results.AddResult(Result("struct", CCP_Type));
  822. Results.AddResult(Result("union", CCP_Type));
  823. Results.AddResult(Result("const", CCP_Type));
  824. Results.AddResult(Result("volatile", CCP_Type));
  825. if (LangOpts.C99) {
  826. // C99-specific
  827. Results.AddResult(Result("_Complex", CCP_Type));
  828. Results.AddResult(Result("_Imaginary", CCP_Type));
  829. Results.AddResult(Result("_Bool", CCP_Type));
  830. Results.AddResult(Result("restrict", CCP_Type));
  831. }
  832. if (LangOpts.CPlusPlus) {
  833. // C++-specific
  834. Results.AddResult(Result("bool", CCP_Type));
  835. Results.AddResult(Result("class", CCP_Type));
  836. Results.AddResult(Result("wchar_t", CCP_Type));
  837. // typename qualified-id
  838. CodeCompletionString *Pattern = new CodeCompletionString;
  839. Pattern->AddTypedTextChunk("typename");
  840. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  841. Pattern->AddPlaceholderChunk("qualifier");
  842. Pattern->AddTextChunk("::");
  843. Pattern->AddPlaceholderChunk("name");
  844. Results.AddResult(Result(Pattern));
  845. if (LangOpts.CPlusPlus0x) {
  846. Results.AddResult(Result("auto", CCP_Type));
  847. Results.AddResult(Result("char16_t", CCP_Type));
  848. Results.AddResult(Result("char32_t", CCP_Type));
  849. CodeCompletionString *Pattern = new CodeCompletionString;
  850. Pattern->AddTypedTextChunk("decltype");
  851. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  852. Pattern->AddPlaceholderChunk("expression");
  853. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  854. Results.AddResult(Result(Pattern));
  855. }
  856. }
  857. // GNU extensions
  858. if (LangOpts.GNUMode) {
  859. // FIXME: Enable when we actually support decimal floating point.
  860. // Results.AddResult(Result("_Decimal32"));
  861. // Results.AddResult(Result("_Decimal64"));
  862. // Results.AddResult(Result("_Decimal128"));
  863. CodeCompletionString *Pattern = new CodeCompletionString;
  864. Pattern->AddTypedTextChunk("typeof");
  865. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  866. Pattern->AddPlaceholderChunk("expression");
  867. Results.AddResult(Result(Pattern));
  868. Pattern = new CodeCompletionString;
  869. Pattern->AddTypedTextChunk("typeof");
  870. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  871. Pattern->AddPlaceholderChunk("type");
  872. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  873. Results.AddResult(Result(Pattern));
  874. }
  875. }
  876. static void AddStorageSpecifiers(Action::CodeCompletionContext CCC,
  877. const LangOptions &LangOpts,
  878. ResultBuilder &Results) {
  879. typedef CodeCompleteConsumer::Result Result;
  880. // Note: we don't suggest either "auto" or "register", because both
  881. // are pointless as storage specifiers. Elsewhere, we suggest "auto"
  882. // in C++0x as a type specifier.
  883. Results.AddResult(Result("extern"));
  884. Results.AddResult(Result("static"));
  885. }
  886. static void AddFunctionSpecifiers(Action::CodeCompletionContext CCC,
  887. const LangOptions &LangOpts,
  888. ResultBuilder &Results) {
  889. typedef CodeCompleteConsumer::Result Result;
  890. switch (CCC) {
  891. case Action::CCC_Class:
  892. case Action::CCC_MemberTemplate:
  893. if (LangOpts.CPlusPlus) {
  894. Results.AddResult(Result("explicit"));
  895. Results.AddResult(Result("friend"));
  896. Results.AddResult(Result("mutable"));
  897. Results.AddResult(Result("virtual"));
  898. }
  899. // Fall through
  900. case Action::CCC_ObjCInterface:
  901. case Action::CCC_ObjCImplementation:
  902. case Action::CCC_Namespace:
  903. case Action::CCC_Template:
  904. if (LangOpts.CPlusPlus || LangOpts.C99)
  905. Results.AddResult(Result("inline"));
  906. break;
  907. case Action::CCC_ObjCInstanceVariableList:
  908. case Action::CCC_Expression:
  909. case Action::CCC_Statement:
  910. case Action::CCC_ForInit:
  911. case Action::CCC_Condition:
  912. case Action::CCC_RecoveryInFunction:
  913. break;
  914. }
  915. }
  916. static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
  917. static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
  918. static void AddObjCVisibilityResults(const LangOptions &LangOpts,
  919. ResultBuilder &Results,
  920. bool NeedAt);
  921. static void AddObjCImplementationResults(const LangOptions &LangOpts,
  922. ResultBuilder &Results,
  923. bool NeedAt);
  924. static void AddObjCInterfaceResults(const LangOptions &LangOpts,
  925. ResultBuilder &Results,
  926. bool NeedAt);
  927. static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
  928. static void AddTypedefResult(ResultBuilder &Results) {
  929. CodeCompletionString *Pattern = new CodeCompletionString;
  930. Pattern->AddTypedTextChunk("typedef");
  931. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  932. Pattern->AddPlaceholderChunk("type");
  933. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  934. Pattern->AddPlaceholderChunk("name");
  935. Results.AddResult(CodeCompleteConsumer::Result(Pattern));
  936. }
  937. static bool WantTypesInContext(Action::CodeCompletionContext CCC,
  938. const LangOptions &LangOpts) {
  939. if (LangOpts.CPlusPlus)
  940. return true;
  941. switch (CCC) {
  942. case Action::CCC_Namespace:
  943. case Action::CCC_Class:
  944. case Action::CCC_ObjCInstanceVariableList:
  945. case Action::CCC_Template:
  946. case Action::CCC_MemberTemplate:
  947. case Action::CCC_Statement:
  948. case Action::CCC_RecoveryInFunction:
  949. return true;
  950. case Action::CCC_ObjCInterface:
  951. case Action::CCC_ObjCImplementation:
  952. case Action::CCC_Expression:
  953. case Action::CCC_Condition:
  954. return false;
  955. case Action::CCC_ForInit:
  956. return LangOpts.ObjC1 || LangOpts.C99;
  957. }
  958. return false;
  959. }
  960. /// \brief Add language constructs that show up for "ordinary" names.
  961. static void AddOrdinaryNameResults(Action::CodeCompletionContext CCC,
  962. Scope *S,
  963. Sema &SemaRef,
  964. ResultBuilder &Results) {
  965. typedef CodeCompleteConsumer::Result Result;
  966. switch (CCC) {
  967. case Action::CCC_Namespace:
  968. if (SemaRef.getLangOptions().CPlusPlus) {
  969. CodeCompletionString *Pattern = 0;
  970. if (Results.includeCodePatterns()) {
  971. // namespace <identifier> { declarations }
  972. CodeCompletionString *Pattern = new CodeCompletionString;
  973. Pattern->AddTypedTextChunk("namespace");
  974. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  975. Pattern->AddPlaceholderChunk("identifier");
  976. Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
  977. Pattern->AddPlaceholderChunk("declarations");
  978. Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
  979. Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
  980. Results.AddResult(Result(Pattern));
  981. }
  982. // namespace identifier = identifier ;
  983. Pattern = new CodeCompletionString;
  984. Pattern->AddTypedTextChunk("namespace");
  985. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  986. Pattern->AddPlaceholderChunk("name");
  987. Pattern->AddChunk(CodeCompletionString::CK_Equal);
  988. Pattern->AddPlaceholderChunk("namespace");
  989. Results.AddResult(Result(Pattern));
  990. // Using directives
  991. Pattern = new CodeCompletionString;
  992. Pattern->AddTypedTextChunk("using");
  993. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  994. Pattern->AddTextChunk("namespace");
  995. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  996. Pattern->AddPlaceholderChunk("identifier");
  997. Results.AddResult(Result(Pattern));
  998. // asm(string-literal)
  999. Pattern = new CodeCompletionString;
  1000. Pattern->AddTypedTextChunk("asm");
  1001. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1002. Pattern->AddPlaceholderChunk("string-literal");
  1003. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1004. Results.AddResult(Result(Pattern));
  1005. if (Results.includeCodePatterns()) {
  1006. // Explicit template instantiation
  1007. Pattern = new CodeCompletionString;
  1008. Pattern->AddTypedTextChunk("template");
  1009. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1010. Pattern->AddPlaceholderChunk("declaration");
  1011. Results.AddResult(Result(Pattern));
  1012. }
  1013. }
  1014. if (SemaRef.getLangOptions().ObjC1)
  1015. AddObjCTopLevelResults(Results, true);
  1016. AddTypedefResult(Results);
  1017. // Fall through
  1018. case Action::CCC_Class:
  1019. if (SemaRef.getLangOptions().CPlusPlus) {
  1020. // Using declaration
  1021. CodeCompletionString *Pattern = new CodeCompletionString;
  1022. Pattern->AddTypedTextChunk("using");
  1023. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1024. Pattern->AddPlaceholderChunk("qualifier");
  1025. Pattern->AddTextChunk("::");
  1026. Pattern->AddPlaceholderChunk("name");
  1027. Results.AddResult(Result(Pattern));
  1028. // using typename qualifier::name (only in a dependent context)
  1029. if (SemaRef.CurContext->isDependentContext()) {
  1030. Pattern = new CodeCompletionString;
  1031. Pattern->AddTypedTextChunk("using");
  1032. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1033. Pattern->AddTextChunk("typename");
  1034. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1035. Pattern->AddPlaceholderChunk("qualifier");
  1036. Pattern->AddTextChunk("::");
  1037. Pattern->AddPlaceholderChunk("name");
  1038. Results.AddResult(Result(Pattern));
  1039. }
  1040. if (CCC == Action::CCC_Class) {
  1041. AddTypedefResult(Results);
  1042. // public:
  1043. Pattern = new CodeCompletionString;
  1044. Pattern->AddTypedTextChunk("public");
  1045. Pattern->AddChunk(CodeCompletionString::CK_Colon);
  1046. Results.AddResult(Result(Pattern));
  1047. // protected:
  1048. Pattern = new CodeCompletionString;
  1049. Pattern->AddTypedTextChunk("protected");
  1050. Pattern->AddChunk(CodeCompletionString::CK_Colon);
  1051. Results.AddResult(Result(Pattern));
  1052. // private:
  1053. Pattern = new CodeCompletionString;
  1054. Pattern->AddTypedTextChunk("private");
  1055. Pattern->AddChunk(CodeCompletionString::CK_Colon);
  1056. Results.AddResult(Result(Pattern));
  1057. }
  1058. }
  1059. // Fall through
  1060. case Action::CCC_Template:
  1061. case Action::CCC_MemberTemplate:
  1062. if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
  1063. // template < parameters >
  1064. CodeCompletionString *Pattern = new CodeCompletionString;
  1065. Pattern->AddTypedTextChunk("template");
  1066. Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
  1067. Pattern->AddPlaceholderChunk("parameters");
  1068. Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
  1069. Results.AddResult(Result(Pattern));
  1070. }
  1071. AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
  1072. AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
  1073. break;
  1074. case Action::CCC_ObjCInterface:
  1075. AddObjCInterfaceResults(SemaRef.getLangOptions(), Results, true);
  1076. AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
  1077. AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
  1078. break;
  1079. case Action::CCC_ObjCImplementation:
  1080. AddObjCImplementationResults(SemaRef.getLangOptions(), Results, true);
  1081. AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
  1082. AddFunctionSpecifiers(CCC, SemaRef.getLangOptions(), Results);
  1083. break;
  1084. case Action::CCC_ObjCInstanceVariableList:
  1085. AddObjCVisibilityResults(SemaRef.getLangOptions(), Results, true);
  1086. break;
  1087. case Action::CCC_RecoveryInFunction:
  1088. case Action::CCC_Statement: {
  1089. AddTypedefResult(Results);
  1090. CodeCompletionString *Pattern = 0;
  1091. if (SemaRef.getLangOptions().CPlusPlus && Results.includeCodePatterns()) {
  1092. Pattern = new CodeCompletionString;
  1093. Pattern->AddTypedTextChunk("try");
  1094. Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
  1095. Pattern->AddPlaceholderChunk("statements");
  1096. Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
  1097. Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
  1098. Pattern->AddTextChunk("catch");
  1099. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1100. Pattern->AddPlaceholderChunk("declaration");
  1101. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1102. Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
  1103. Pattern->AddPlaceholderChunk("statements");
  1104. Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
  1105. Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
  1106. Results.AddResult(Result(Pattern));
  1107. }
  1108. if (SemaRef.getLangOptions().ObjC1)
  1109. AddObjCStatementResults(Results, true);
  1110. if (Results.includeCodePatterns()) {
  1111. // if (condition) { statements }
  1112. Pattern = new CodeCompletionString;
  1113. Pattern->AddTypedTextChunk("if");
  1114. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1115. if (SemaRef.getLangOptions().CPlusPlus)
  1116. Pattern->AddPlaceholderChunk("condition");
  1117. else
  1118. Pattern->AddPlaceholderChunk("expression");
  1119. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1120. Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
  1121. Pattern->AddPlaceholderChunk("statements");
  1122. Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
  1123. Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
  1124. Results.AddResult(Result(Pattern));
  1125. // switch (condition) { }
  1126. Pattern = new CodeCompletionString;
  1127. Pattern->AddTypedTextChunk("switch");
  1128. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1129. if (SemaRef.getLangOptions().CPlusPlus)
  1130. Pattern->AddPlaceholderChunk("condition");
  1131. else
  1132. Pattern->AddPlaceholderChunk("expression");
  1133. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1134. Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
  1135. Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
  1136. Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
  1137. Results.AddResult(Result(Pattern));
  1138. }
  1139. // Switch-specific statements.
  1140. if (!SemaRef.getSwitchStack().empty()) {
  1141. // case expression:
  1142. Pattern = new CodeCompletionString;
  1143. Pattern->AddTypedTextChunk("case");
  1144. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1145. Pattern->AddPlaceholderChunk("expression");
  1146. Pattern->AddChunk(CodeCompletionString::CK_Colon);
  1147. Results.AddResult(Result(Pattern));
  1148. // default:
  1149. Pattern = new CodeCompletionString;
  1150. Pattern->AddTypedTextChunk("default");
  1151. Pattern->AddChunk(CodeCompletionString::CK_Colon);
  1152. Results.AddResult(Result(Pattern));
  1153. }
  1154. if (Results.includeCodePatterns()) {
  1155. /// while (condition) { statements }
  1156. Pattern = new CodeCompletionString;
  1157. Pattern->AddTypedTextChunk("while");
  1158. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1159. if (SemaRef.getLangOptions().CPlusPlus)
  1160. Pattern->AddPlaceholderChunk("condition");
  1161. else
  1162. Pattern->AddPlaceholderChunk("expression");
  1163. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1164. Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
  1165. Pattern->AddPlaceholderChunk("statements");
  1166. Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
  1167. Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
  1168. Results.AddResult(Result(Pattern));
  1169. // do { statements } while ( expression );
  1170. Pattern = new CodeCompletionString;
  1171. Pattern->AddTypedTextChunk("do");
  1172. Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
  1173. Pattern->AddPlaceholderChunk("statements");
  1174. Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
  1175. Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
  1176. Pattern->AddTextChunk("while");
  1177. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1178. Pattern->AddPlaceholderChunk("expression");
  1179. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1180. Results.AddResult(Result(Pattern));
  1181. // for ( for-init-statement ; condition ; expression ) { statements }
  1182. Pattern = new CodeCompletionString;
  1183. Pattern->AddTypedTextChunk("for");
  1184. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1185. if (SemaRef.getLangOptions().CPlusPlus || SemaRef.getLangOptions().C99)
  1186. Pattern->AddPlaceholderChunk("init-statement");
  1187. else
  1188. Pattern->AddPlaceholderChunk("init-expression");
  1189. Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
  1190. Pattern->AddPlaceholderChunk("condition");
  1191. Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
  1192. Pattern->AddPlaceholderChunk("inc-expression");
  1193. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1194. Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
  1195. Pattern->AddPlaceholderChunk("statements");
  1196. Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
  1197. Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
  1198. Results.AddResult(Result(Pattern));
  1199. }
  1200. if (S->getContinueParent()) {
  1201. // continue ;
  1202. Pattern = new CodeCompletionString;
  1203. Pattern->AddTypedTextChunk("continue");
  1204. Results.AddResult(Result(Pattern));
  1205. }
  1206. if (S->getBreakParent()) {
  1207. // break ;
  1208. Pattern = new CodeCompletionString;
  1209. Pattern->AddTypedTextChunk("break");
  1210. Results.AddResult(Result(Pattern));
  1211. }
  1212. // "return expression ;" or "return ;", depending on whether we
  1213. // know the function is void or not.
  1214. bool isVoid = false;
  1215. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
  1216. isVoid = Function->getResultType()->isVoidType();
  1217. else if (ObjCMethodDecl *Method
  1218. = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
  1219. isVoid = Method->getResultType()->isVoidType();
  1220. else if (SemaRef.getCurBlock() &&
  1221. !SemaRef.getCurBlock()->ReturnType.isNull())
  1222. isVoid = SemaRef.getCurBlock()->ReturnType->isVoidType();
  1223. Pattern = new CodeCompletionString;
  1224. Pattern->AddTypedTextChunk("return");
  1225. if (!isVoid) {
  1226. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1227. Pattern->AddPlaceholderChunk("expression");
  1228. }
  1229. Results.AddResult(Result(Pattern));
  1230. // goto identifier ;
  1231. Pattern = new CodeCompletionString;
  1232. Pattern->AddTypedTextChunk("goto");
  1233. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1234. Pattern->AddPlaceholderChunk("label");
  1235. Results.AddResult(Result(Pattern));
  1236. // Using directives
  1237. Pattern = new CodeCompletionString;
  1238. Pattern->AddTypedTextChunk("using");
  1239. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1240. Pattern->AddTextChunk("namespace");
  1241. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1242. Pattern->AddPlaceholderChunk("identifier");
  1243. Results.AddResult(Result(Pattern));
  1244. }
  1245. // Fall through (for statement expressions).
  1246. case Action::CCC_ForInit:
  1247. case Action::CCC_Condition:
  1248. AddStorageSpecifiers(CCC, SemaRef.getLangOptions(), Results);
  1249. // Fall through: conditions and statements can have expressions.
  1250. case Action::CCC_Expression: {
  1251. CodeCompletionString *Pattern = 0;
  1252. if (SemaRef.getLangOptions().CPlusPlus) {
  1253. // 'this', if we're in a non-static member function.
  1254. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(SemaRef.CurContext))
  1255. if (!Method->isStatic())
  1256. Results.AddResult(Result("this"));
  1257. // true, false
  1258. Results.AddResult(Result("true"));
  1259. Results.AddResult(Result("false"));
  1260. // dynamic_cast < type-id > ( expression )
  1261. Pattern = new CodeCompletionString;
  1262. Pattern->AddTypedTextChunk("dynamic_cast");
  1263. Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
  1264. Pattern->AddPlaceholderChunk("type");
  1265. Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
  1266. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1267. Pattern->AddPlaceholderChunk("expression");
  1268. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1269. Results.AddResult(Result(Pattern));
  1270. // static_cast < type-id > ( expression )
  1271. Pattern = new CodeCompletionString;
  1272. Pattern->AddTypedTextChunk("static_cast");
  1273. Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
  1274. Pattern->AddPlaceholderChunk("type");
  1275. Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
  1276. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1277. Pattern->AddPlaceholderChunk("expression");
  1278. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1279. Results.AddResult(Result(Pattern));
  1280. // reinterpret_cast < type-id > ( expression )
  1281. Pattern = new CodeCompletionString;
  1282. Pattern->AddTypedTextChunk("reinterpret_cast");
  1283. Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
  1284. Pattern->AddPlaceholderChunk("type");
  1285. Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
  1286. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1287. Pattern->AddPlaceholderChunk("expression");
  1288. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1289. Results.AddResult(Result(Pattern));
  1290. // const_cast < type-id > ( expression )
  1291. Pattern = new CodeCompletionString;
  1292. Pattern->AddTypedTextChunk("const_cast");
  1293. Pattern->AddChunk(CodeCompletionString::CK_LeftAngle);
  1294. Pattern->AddPlaceholderChunk("type");
  1295. Pattern->AddChunk(CodeCompletionString::CK_RightAngle);
  1296. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1297. Pattern->AddPlaceholderChunk("expression");
  1298. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1299. Results.AddResult(Result(Pattern));
  1300. // typeid ( expression-or-type )
  1301. Pattern = new CodeCompletionString;
  1302. Pattern->AddTypedTextChunk("typeid");
  1303. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1304. Pattern->AddPlaceholderChunk("expression-or-type");
  1305. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1306. Results.AddResult(Result(Pattern));
  1307. // new T ( ... )
  1308. Pattern = new CodeCompletionString;
  1309. Pattern->AddTypedTextChunk("new");
  1310. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1311. Pattern->AddPlaceholderChunk("type");
  1312. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1313. Pattern->AddPlaceholderChunk("expressions");
  1314. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1315. Results.AddResult(Result(Pattern));
  1316. // new T [ ] ( ... )
  1317. Pattern = new CodeCompletionString;
  1318. Pattern->AddTypedTextChunk("new");
  1319. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1320. Pattern->AddPlaceholderChunk("type");
  1321. Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
  1322. Pattern->AddPlaceholderChunk("size");
  1323. Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
  1324. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1325. Pattern->AddPlaceholderChunk("expressions");
  1326. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1327. Results.AddResult(Result(Pattern));
  1328. // delete expression
  1329. Pattern = new CodeCompletionString;
  1330. Pattern->AddTypedTextChunk("delete");
  1331. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1332. Pattern->AddPlaceholderChunk("expression");
  1333. Results.AddResult(Result(Pattern));
  1334. // delete [] expression
  1335. Pattern = new CodeCompletionString;
  1336. Pattern->AddTypedTextChunk("delete");
  1337. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1338. Pattern->AddChunk(CodeCompletionString::CK_LeftBracket);
  1339. Pattern->AddChunk(CodeCompletionString::CK_RightBracket);
  1340. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1341. Pattern->AddPlaceholderChunk("expression");
  1342. Results.AddResult(Result(Pattern));
  1343. // throw expression
  1344. Pattern = new CodeCompletionString;
  1345. Pattern->AddTypedTextChunk("throw");
  1346. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1347. Pattern->AddPlaceholderChunk("expression");
  1348. Results.AddResult(Result(Pattern));
  1349. // FIXME: Rethrow?
  1350. }
  1351. if (SemaRef.getLangOptions().ObjC1) {
  1352. // Add "super", if we're in an Objective-C class with a superclass.
  1353. if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
  1354. // The interface can be NULL.
  1355. if (ObjCInterfaceDecl *ID = Method->getClassInterface())
  1356. if (ID->getSuperClass())
  1357. Results.AddResult(Result("super"));
  1358. }
  1359. AddObjCExpressionResults(Results, true);
  1360. }
  1361. // sizeof expression
  1362. Pattern = new CodeCompletionString;
  1363. Pattern->AddTypedTextChunk("sizeof");
  1364. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  1365. Pattern->AddPlaceholderChunk("expression-or-type");
  1366. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  1367. Results.AddResult(Result(Pattern));
  1368. break;
  1369. }
  1370. }
  1371. if (WantTypesInContext(CCC, SemaRef.getLangOptions()))
  1372. AddTypeSpecifierResults(SemaRef.getLangOptions(), Results);
  1373. if (SemaRef.getLangOptions().CPlusPlus)
  1374. Results.AddResult(Result("operator"));
  1375. }
  1376. /// \brief If the given declaration has an associated type, add it as a result
  1377. /// type chunk.
  1378. static void AddResultTypeChunk(ASTContext &Context,
  1379. NamedDecl *ND,
  1380. CodeCompletionString *Result) {
  1381. if (!ND)
  1382. return;
  1383. // Determine the type of the declaration (if it has a type).
  1384. QualType T;
  1385. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND))
  1386. T = Function->getResultType();
  1387. else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND))
  1388. T = Method->getResultType();
  1389. else if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND))
  1390. T = FunTmpl->getTemplatedDecl()->getResultType();
  1391. else if (EnumConstantDecl *Enumerator = dyn_cast<EnumConstantDecl>(ND))
  1392. T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
  1393. else if (isa<UnresolvedUsingValueDecl>(ND)) {
  1394. /* Do nothing: ignore unresolved using declarations*/
  1395. } else if (ValueDecl *Value = dyn_cast<ValueDecl>(ND))
  1396. T = Value->getType();
  1397. else if (ObjCPropertyDecl *Property = dyn_cast<ObjCPropertyDecl>(ND))
  1398. T = Property->getType();
  1399. if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
  1400. return;
  1401. PrintingPolicy Policy(Context.PrintingPolicy);
  1402. Policy.AnonymousTagLocations = false;
  1403. std::string TypeStr;
  1404. T.getAsStringInternal(TypeStr, Policy);
  1405. Result->AddResultTypeChunk(TypeStr);
  1406. }
  1407. /// \brief Add function parameter chunks to the given code completion string.
  1408. static void AddFunctionParameterChunks(ASTContext &Context,
  1409. FunctionDecl *Function,
  1410. CodeCompletionString *Result) {
  1411. typedef CodeCompletionString::Chunk Chunk;
  1412. CodeCompletionString *CCStr = Result;
  1413. for (unsigned P = 0, N = Function->getNumParams(); P != N; ++P) {
  1414. ParmVarDecl *Param = Function->getParamDecl(P);
  1415. if (Param->hasDefaultArg()) {
  1416. // When we see an optional default argument, put that argument and
  1417. // the remaining default arguments into a new, optional string.
  1418. CodeCompletionString *Opt = new CodeCompletionString;
  1419. CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
  1420. CCStr = Opt;
  1421. }
  1422. if (P != 0)
  1423. CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
  1424. // Format the placeholder string.
  1425. std::string PlaceholderStr;
  1426. if (Param->getIdentifier())
  1427. PlaceholderStr = Param->getIdentifier()->getName();
  1428. Param->getType().getAsStringInternal(PlaceholderStr,
  1429. Context.PrintingPolicy);
  1430. // Add the placeholder string.
  1431. CCStr->AddPlaceholderChunk(PlaceholderStr);
  1432. }
  1433. if (const FunctionProtoType *Proto
  1434. = Function->getType()->getAs<FunctionProtoType>())
  1435. if (Proto->isVariadic())
  1436. CCStr->AddPlaceholderChunk(", ...");
  1437. }
  1438. /// \brief Add template parameter chunks to the given code completion string.
  1439. static void AddTemplateParameterChunks(ASTContext &Context,
  1440. TemplateDecl *Template,
  1441. CodeCompletionString *Result,
  1442. unsigned MaxParameters = 0) {
  1443. typedef CodeCompletionString::Chunk Chunk;
  1444. CodeCompletionString *CCStr = Result;
  1445. bool FirstParameter = true;
  1446. TemplateParameterList *Params = Template->getTemplateParameters();
  1447. TemplateParameterList::iterator PEnd = Params->end();
  1448. if (MaxParameters)
  1449. PEnd = Params->begin() + MaxParameters;
  1450. for (TemplateParameterList::iterator P = Params->begin(); P != PEnd; ++P) {
  1451. bool HasDefaultArg = false;
  1452. std::string PlaceholderStr;
  1453. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
  1454. if (TTP->wasDeclaredWithTypename())
  1455. PlaceholderStr = "typename";
  1456. else
  1457. PlaceholderStr = "class";
  1458. if (TTP->getIdentifier()) {
  1459. PlaceholderStr += ' ';
  1460. PlaceholderStr += TTP->getIdentifier()->getName();
  1461. }
  1462. HasDefaultArg = TTP->hasDefaultArgument();
  1463. } else if (NonTypeTemplateParmDecl *NTTP
  1464. = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  1465. if (NTTP->getIdentifier())
  1466. PlaceholderStr = NTTP->getIdentifier()->getName();
  1467. NTTP->getType().getAsStringInternal(PlaceholderStr,
  1468. Context.PrintingPolicy);
  1469. HasDefaultArg = NTTP->hasDefaultArgument();
  1470. } else {
  1471. assert(isa<TemplateTemplateParmDecl>(*P));
  1472. TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
  1473. // Since putting the template argument list into the placeholder would
  1474. // be very, very long, we just use an abbreviation.
  1475. PlaceholderStr = "template<...> class";
  1476. if (TTP->getIdentifier()) {
  1477. PlaceholderStr += ' ';
  1478. PlaceholderStr += TTP->getIdentifier()->getName();
  1479. }
  1480. HasDefaultArg = TTP->hasDefaultArgument();
  1481. }
  1482. if (HasDefaultArg) {
  1483. // When we see an optional default argument, put that argument and
  1484. // the remaining default arguments into a new, optional string.
  1485. CodeCompletionString *Opt = new CodeCompletionString;
  1486. CCStr->AddOptionalChunk(std::auto_ptr<CodeCompletionString>(Opt));
  1487. CCStr = Opt;
  1488. }
  1489. if (FirstParameter)
  1490. FirstParameter = false;
  1491. else
  1492. CCStr->AddChunk(Chunk(CodeCompletionString::CK_Comma));
  1493. // Add the placeholder string.
  1494. CCStr->AddPlaceholderChunk(PlaceholderStr);
  1495. }
  1496. }
  1497. /// \brief Add a qualifier to the given code-completion string, if the
  1498. /// provided nested-name-specifier is non-NULL.
  1499. static void
  1500. AddQualifierToCompletionString(CodeCompletionString *Result,
  1501. NestedNameSpecifier *Qualifier,
  1502. bool QualifierIsInformative,
  1503. ASTContext &Context) {
  1504. if (!Qualifier)
  1505. return;
  1506. std::string PrintedNNS;
  1507. {
  1508. llvm::raw_string_ostream OS(PrintedNNS);
  1509. Qualifier->print(OS, Context.PrintingPolicy);
  1510. }
  1511. if (QualifierIsInformative)
  1512. Result->AddInformativeChunk(PrintedNNS);
  1513. else
  1514. Result->AddTextChunk(PrintedNNS);
  1515. }
  1516. static void AddFunctionTypeQualsToCompletionString(CodeCompletionString *Result,
  1517. FunctionDecl *Function) {
  1518. const FunctionProtoType *Proto
  1519. = Function->getType()->getAs<FunctionProtoType>();
  1520. if (!Proto || !Proto->getTypeQuals())
  1521. return;
  1522. std::string QualsStr;
  1523. if (Proto->getTypeQuals() & Qualifiers::Const)
  1524. QualsStr += " const";
  1525. if (Proto->getTypeQuals() & Qualifiers::Volatile)
  1526. QualsStr += " volatile";
  1527. if (Proto->getTypeQuals() & Qualifiers::Restrict)
  1528. QualsStr += " restrict";
  1529. Result->AddInformativeChunk(QualsStr);
  1530. }
  1531. /// \brief If possible, create a new code completion string for the given
  1532. /// result.
  1533. ///
  1534. /// \returns Either a new, heap-allocated code completion string describing
  1535. /// how to use this result, or NULL to indicate that the string or name of the
  1536. /// result is all that is needed.
  1537. CodeCompletionString *
  1538. CodeCompleteConsumer::Result::CreateCodeCompletionString(Sema &S,
  1539. CodeCompletionString *Result) {
  1540. typedef CodeCompletionString::Chunk Chunk;
  1541. if (Kind == RK_Pattern)
  1542. return Pattern->Clone(Result);
  1543. if (!Result)
  1544. Result = new CodeCompletionString;
  1545. if (Kind == RK_Keyword) {
  1546. Result->AddTypedTextChunk(Keyword);
  1547. return Result;
  1548. }
  1549. if (Kind == RK_Macro) {
  1550. MacroInfo *MI = S.PP.getMacroInfo(Macro);
  1551. assert(MI && "Not a macro?");
  1552. Result->AddTypedTextChunk(Macro->getName());
  1553. if (!MI->isFunctionLike())
  1554. return Result;
  1555. // Format a function-like macro with placeholders for the arguments.
  1556. Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
  1557. for (MacroInfo::arg_iterator A = MI->arg_begin(), AEnd = MI->arg_end();
  1558. A != AEnd; ++A) {
  1559. if (A != MI->arg_begin())
  1560. Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
  1561. if (!MI->isVariadic() || A != AEnd - 1) {
  1562. // Non-variadic argument.
  1563. Result->AddPlaceholderChunk((*A)->getName());
  1564. continue;
  1565. }
  1566. // Variadic argument; cope with the different between GNU and C99
  1567. // variadic macros, providing a single placeholder for the rest of the
  1568. // arguments.
  1569. if ((*A)->isStr("__VA_ARGS__"))
  1570. Result->AddPlaceholderChunk("...");
  1571. else {
  1572. std::string Arg = (*A)->getName();
  1573. Arg += "...";
  1574. Result->AddPlaceholderChunk(Arg);
  1575. }
  1576. }
  1577. Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
  1578. return Result;
  1579. }
  1580. assert(Kind == RK_Declaration && "Missed a result kind?");
  1581. NamedDecl *ND = Declaration;
  1582. if (StartsNestedNameSpecifier) {
  1583. Result->AddTypedTextChunk(ND->getNameAsString());
  1584. Result->AddTextChunk("::");
  1585. return Result;
  1586. }
  1587. AddResultTypeChunk(S.Context, ND, Result);
  1588. if (FunctionDecl *Function = dyn_cast<FunctionDecl>(ND)) {
  1589. AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
  1590. S.Context);
  1591. Result->AddTypedTextChunk(Function->getNameAsString());
  1592. Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
  1593. AddFunctionParameterChunks(S.Context, Function, Result);
  1594. Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
  1595. AddFunctionTypeQualsToCompletionString(Result, Function);
  1596. return Result;
  1597. }
  1598. if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(ND)) {
  1599. AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
  1600. S.Context);
  1601. FunctionDecl *Function = FunTmpl->getTemplatedDecl();
  1602. Result->AddTypedTextChunk(Function->getNameAsString());
  1603. // Figure out which template parameters are deduced (or have default
  1604. // arguments).
  1605. llvm::SmallVector<bool, 16> Deduced;
  1606. S.MarkDeducedTemplateParameters(FunTmpl, Deduced);
  1607. unsigned LastDeducibleArgument;
  1608. for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
  1609. --LastDeducibleArgument) {
  1610. if (!Deduced[LastDeducibleArgument - 1]) {
  1611. // C++0x: Figure out if the template argument has a default. If so,
  1612. // the user doesn't need to type this argument.
  1613. // FIXME: We need to abstract template parameters better!
  1614. bool HasDefaultArg = false;
  1615. NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
  1616. LastDeducibleArgument - 1);
  1617. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
  1618. HasDefaultArg = TTP->hasDefaultArgument();
  1619. else if (NonTypeTemplateParmDecl *NTTP
  1620. = dyn_cast<NonTypeTemplateParmDecl>(Param))
  1621. HasDefaultArg = NTTP->hasDefaultArgument();
  1622. else {
  1623. assert(isa<TemplateTemplateParmDecl>(Param));
  1624. HasDefaultArg
  1625. = cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
  1626. }
  1627. if (!HasDefaultArg)
  1628. break;
  1629. }
  1630. }
  1631. if (LastDeducibleArgument) {
  1632. // Some of the function template arguments cannot be deduced from a
  1633. // function call, so we introduce an explicit template argument list
  1634. // containing all of the arguments up to the first deducible argument.
  1635. Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
  1636. AddTemplateParameterChunks(S.Context, FunTmpl, Result,
  1637. LastDeducibleArgument);
  1638. Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
  1639. }
  1640. // Add the function parameters
  1641. Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
  1642. AddFunctionParameterChunks(S.Context, Function, Result);
  1643. Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
  1644. AddFunctionTypeQualsToCompletionString(Result, Function);
  1645. return Result;
  1646. }
  1647. if (TemplateDecl *Template = dyn_cast<TemplateDecl>(ND)) {
  1648. AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
  1649. S.Context);
  1650. Result->AddTypedTextChunk(Template->getNameAsString());
  1651. Result->AddChunk(Chunk(CodeCompletionString::CK_LeftAngle));
  1652. AddTemplateParameterChunks(S.Context, Template, Result);
  1653. Result->AddChunk(Chunk(CodeCompletionString::CK_RightAngle));
  1654. return Result;
  1655. }
  1656. if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(ND)) {
  1657. Selector Sel = Method->getSelector();
  1658. if (Sel.isUnarySelector()) {
  1659. Result->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
  1660. return Result;
  1661. }
  1662. std::string SelName = Sel.getIdentifierInfoForSlot(0)->getName().str();
  1663. SelName += ':';
  1664. if (StartParameter == 0)
  1665. Result->AddTypedTextChunk(SelName);
  1666. else {
  1667. Result->AddInformativeChunk(SelName);
  1668. // If there is only one parameter, and we're past it, add an empty
  1669. // typed-text chunk since there is nothing to type.
  1670. if (Method->param_size() == 1)
  1671. Result->AddTypedTextChunk("");
  1672. }
  1673. unsigned Idx = 0;
  1674. for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
  1675. PEnd = Method->param_end();
  1676. P != PEnd; (void)++P, ++Idx) {
  1677. if (Idx > 0) {
  1678. std::string Keyword;
  1679. if (Idx > StartParameter)
  1680. Result->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1681. if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
  1682. Keyword += II->getName().str();
  1683. Keyword += ":";
  1684. if (Idx < StartParameter || AllParametersAreInformative)
  1685. Result->AddInformativeChunk(Keyword);
  1686. else if (Idx == StartParameter)
  1687. Result->AddTypedTextChunk(Keyword);
  1688. else
  1689. Result->AddTextChunk(Keyword);
  1690. }
  1691. // If we're before the starting parameter, skip the placeholder.
  1692. if (Idx < StartParameter)
  1693. continue;
  1694. std::string Arg;
  1695. (*P)->getType().getAsStringInternal(Arg, S.Context.PrintingPolicy);
  1696. Arg = "(" + Arg + ")";
  1697. if (IdentifierInfo *II = (*P)->getIdentifier())
  1698. Arg += II->getName().str();
  1699. if (DeclaringEntity)
  1700. Result->AddTextChunk(Arg);
  1701. else if (AllParametersAreInformative)
  1702. Result->AddInformativeChunk(Arg);
  1703. else
  1704. Result->AddPlaceholderChunk(Arg);
  1705. }
  1706. if (Method->isVariadic()) {
  1707. if (DeclaringEntity)
  1708. Result->AddTextChunk(", ...");
  1709. else if (AllParametersAreInformative)
  1710. Result->AddInformativeChunk(", ...");
  1711. else
  1712. Result->AddPlaceholderChunk(", ...");
  1713. }
  1714. return Result;
  1715. }
  1716. if (Qualifier)
  1717. AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
  1718. S.Context);
  1719. Result->AddTypedTextChunk(ND->getNameAsString());
  1720. return Result;
  1721. }
  1722. CodeCompletionString *
  1723. CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
  1724. unsigned CurrentArg,
  1725. Sema &S) const {
  1726. typedef CodeCompletionString::Chunk Chunk;
  1727. CodeCompletionString *Result = new CodeCompletionString;
  1728. FunctionDecl *FDecl = getFunction();
  1729. AddResultTypeChunk(S.Context, FDecl, Result);
  1730. const FunctionProtoType *Proto
  1731. = dyn_cast<FunctionProtoType>(getFunctionType());
  1732. if (!FDecl && !Proto) {
  1733. // Function without a prototype. Just give the return type and a
  1734. // highlighted ellipsis.
  1735. const FunctionType *FT = getFunctionType();
  1736. Result->AddTextChunk(
  1737. FT->getResultType().getAsString(S.Context.PrintingPolicy));
  1738. Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
  1739. Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
  1740. Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
  1741. return Result;
  1742. }
  1743. if (FDecl)
  1744. Result->AddTextChunk(FDecl->getNameAsString());
  1745. else
  1746. Result->AddTextChunk(
  1747. Proto->getResultType().getAsString(S.Context.PrintingPolicy));
  1748. Result->AddChunk(Chunk(CodeCompletionString::CK_LeftParen));
  1749. unsigned NumParams = FDecl? FDecl->getNumParams() : Proto->getNumArgs();
  1750. for (unsigned I = 0; I != NumParams; ++I) {
  1751. if (I)
  1752. Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
  1753. std::string ArgString;
  1754. QualType ArgType;
  1755. if (FDecl) {
  1756. ArgString = FDecl->getParamDecl(I)->getNameAsString();
  1757. ArgType = FDecl->getParamDecl(I)->getOriginalType();
  1758. } else {
  1759. ArgType = Proto->getArgType(I);
  1760. }
  1761. ArgType.getAsStringInternal(ArgString, S.Context.PrintingPolicy);
  1762. if (I == CurrentArg)
  1763. Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter,
  1764. ArgString));
  1765. else
  1766. Result->AddTextChunk(ArgString);
  1767. }
  1768. if (Proto && Proto->isVariadic()) {
  1769. Result->AddChunk(Chunk(CodeCompletionString::CK_Comma));
  1770. if (CurrentArg < NumParams)
  1771. Result->AddTextChunk("...");
  1772. else
  1773. Result->AddChunk(Chunk(CodeCompletionString::CK_CurrentParameter, "..."));
  1774. }
  1775. Result->AddChunk(Chunk(CodeCompletionString::CK_RightParen));
  1776. return Result;
  1777. }
  1778. namespace {
  1779. struct SortCodeCompleteResult {
  1780. typedef CodeCompleteConsumer::Result Result;
  1781. bool isEarlierDeclarationName(DeclarationName X, DeclarationName Y) const {
  1782. Selector XSel = X.getObjCSelector();
  1783. Selector YSel = Y.getObjCSelector();
  1784. if (!XSel.isNull() && !YSel.isNull()) {
  1785. // We are comparing two selectors.
  1786. unsigned N = std::min(XSel.getNumArgs(), YSel.getNumArgs());
  1787. if (N == 0)
  1788. ++N;
  1789. for (unsigned I = 0; I != N; ++I) {
  1790. IdentifierInfo *XId = XSel.getIdentifierInfoForSlot(I);
  1791. IdentifierInfo *YId = YSel.getIdentifierInfoForSlot(I);
  1792. if (!XId || !YId)
  1793. return XId && !YId;
  1794. switch (XId->getName().compare_lower(YId->getName())) {
  1795. case -1: return true;
  1796. case 1: return false;
  1797. default: break;
  1798. }
  1799. }
  1800. return XSel.getNumArgs() < YSel.getNumArgs();
  1801. }
  1802. // For non-selectors, order by kind.
  1803. if (X.getNameKind() != Y.getNameKind())
  1804. return X.getNameKind() < Y.getNameKind();
  1805. // Order identifiers by comparison of their lowercased names.
  1806. if (IdentifierInfo *XId = X.getAsIdentifierInfo())
  1807. return XId->getName().compare_lower(
  1808. Y.getAsIdentifierInfo()->getName()) < 0;
  1809. // Order overloaded operators by the order in which they appear
  1810. // in our list of operators.
  1811. if (OverloadedOperatorKind XOp = X.getCXXOverloadedOperator())
  1812. return XOp < Y.getCXXOverloadedOperator();
  1813. // Order C++0x user-defined literal operators lexically by their
  1814. // lowercased suffixes.
  1815. if (IdentifierInfo *XLit = X.getCXXLiteralIdentifier())
  1816. return XLit->getName().compare_lower(
  1817. Y.getCXXLiteralIdentifier()->getName()) < 0;
  1818. // The only stable ordering we have is to turn the name into a
  1819. // string and then compare the lower-case strings. This is
  1820. // inefficient, but thankfully does not happen too often.
  1821. return llvm::StringRef(X.getAsString()).compare_lower(
  1822. Y.getAsString()) < 0;
  1823. }
  1824. /// \brief Retrieve the name that should be used to order a result.
  1825. ///
  1826. /// If the name needs to be constructed as a string, that string will be
  1827. /// saved into Saved and the returned StringRef will refer to it.
  1828. static llvm::StringRef getOrderedName(const Result &R,
  1829. std::string &Saved) {
  1830. switch (R.Kind) {
  1831. case Result::RK_Keyword:
  1832. return R.Keyword;
  1833. case Result::RK_Pattern:
  1834. return R.Pattern->getTypedText();
  1835. case Result::RK_Macro:
  1836. return R.Macro->getName();
  1837. case Result::RK_Declaration:
  1838. // Handle declarations below.
  1839. break;
  1840. }
  1841. DeclarationName Name = R.Declaration->getDeclName();
  1842. // If the name is a simple identifier (by far the common case), or a
  1843. // zero-argument selector, just return a reference to that identifier.
  1844. if (IdentifierInfo *Id = Name.getAsIdentifierInfo())
  1845. return Id->getName();
  1846. if (Name.isObjCZeroArgSelector())
  1847. if (IdentifierInfo *Id
  1848. = Name.getObjCSelector().getIdentifierInfoForSlot(0))
  1849. return Id->getName();
  1850. Saved = Name.getAsString();
  1851. return Saved;
  1852. }
  1853. bool operator()(const Result &X, const Result &Y) const {
  1854. std::string XSaved, YSaved;
  1855. llvm::StringRef XStr = getOrderedName(X, XSaved);
  1856. llvm::StringRef YStr = getOrderedName(Y, YSaved);
  1857. int cmp = XStr.compare_lower(YStr);
  1858. if (cmp)
  1859. return cmp < 0;
  1860. // Non-hidden names precede hidden names.
  1861. if (X.Hidden != Y.Hidden)
  1862. return !X.Hidden;
  1863. // Non-nested-name-specifiers precede nested-name-specifiers.
  1864. if (X.StartsNestedNameSpecifier != Y.StartsNestedNameSpecifier)
  1865. return !X.StartsNestedNameSpecifier;
  1866. return false;
  1867. }
  1868. };
  1869. }
  1870. static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
  1871. bool TargetTypeIsPointer = false) {
  1872. typedef CodeCompleteConsumer::Result Result;
  1873. Results.EnterNewScope();
  1874. for (Preprocessor::macro_iterator M = PP.macro_begin(),
  1875. MEnd = PP.macro_end();
  1876. M != MEnd; ++M) {
  1877. unsigned Priority = CCP_Macro;
  1878. // Treat the "nil" and "NULL" macros as null pointer constants.
  1879. if (M->first->isStr("nil") || M->first->isStr("NULL")) {
  1880. Priority = CCP_Constant;
  1881. if (TargetTypeIsPointer)
  1882. Priority = Priority / CCF_SimilarTypeMatch;
  1883. }
  1884. Results.AddResult(Result(M->first, Priority));
  1885. }
  1886. Results.ExitScope();
  1887. }
  1888. static void HandleCodeCompleteResults(Sema *S,
  1889. CodeCompleteConsumer *CodeCompleter,
  1890. CodeCompleteConsumer::Result *Results,
  1891. unsigned NumResults) {
  1892. std::stable_sort(Results, Results + NumResults, SortCodeCompleteResult());
  1893. if (CodeCompleter)
  1894. CodeCompleter->ProcessCodeCompleteResults(*S, Results, NumResults);
  1895. for (unsigned I = 0; I != NumResults; ++I)
  1896. Results[I].Destroy();
  1897. }
  1898. void Sema::CodeCompleteOrdinaryName(Scope *S,
  1899. CodeCompletionContext CompletionContext) {
  1900. typedef CodeCompleteConsumer::Result Result;
  1901. ResultBuilder Results(*this);
  1902. // Determine how to filter results, e.g., so that the names of
  1903. // values (functions, enumerators, function templates, etc.) are
  1904. // only allowed where we can have an expression.
  1905. switch (CompletionContext) {
  1906. case CCC_Namespace:
  1907. case CCC_Class:
  1908. case CCC_ObjCInterface:
  1909. case CCC_ObjCImplementation:
  1910. case CCC_ObjCInstanceVariableList:
  1911. case CCC_Template:
  1912. case CCC_MemberTemplate:
  1913. Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
  1914. break;
  1915. case CCC_Expression:
  1916. case CCC_Statement:
  1917. case CCC_ForInit:
  1918. case CCC_Condition:
  1919. if (WantTypesInContext(CompletionContext, getLangOptions()))
  1920. Results.setFilter(&ResultBuilder::IsOrdinaryName);
  1921. else
  1922. Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
  1923. break;
  1924. case CCC_RecoveryInFunction:
  1925. // Unfiltered
  1926. break;
  1927. }
  1928. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  1929. LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
  1930. Results.EnterNewScope();
  1931. AddOrdinaryNameResults(CompletionContext, S, *this, Results);
  1932. Results.ExitScope();
  1933. if (CodeCompleter->includeMacros())
  1934. AddMacroResults(PP, Results);
  1935. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  1936. }
  1937. /// \brief Perform code-completion in an expression context when we know what
  1938. /// type we're looking for.
  1939. ///
  1940. /// \param IntegralConstantExpression Only permit integral constant
  1941. /// expressions.
  1942. void Sema::CodeCompleteExpression(Scope *S, QualType T,
  1943. bool IntegralConstantExpression) {
  1944. typedef CodeCompleteConsumer::Result Result;
  1945. ResultBuilder Results(*this);
  1946. if (IntegralConstantExpression)
  1947. Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
  1948. else if (WantTypesInContext(CCC_Expression, getLangOptions()))
  1949. Results.setFilter(&ResultBuilder::IsOrdinaryName);
  1950. else
  1951. Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
  1952. Results.setPreferredType(T.getNonReferenceType());
  1953. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  1954. LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
  1955. Results.EnterNewScope();
  1956. AddOrdinaryNameResults(CCC_Expression, S, *this, Results);
  1957. Results.ExitScope();
  1958. bool PreferredTypeIsPointer = false;
  1959. if (!T.isNull())
  1960. PreferredTypeIsPointer = T->isAnyPointerType() ||
  1961. T->isMemberPointerType() || T->isBlockPointerType();
  1962. if (CodeCompleter->includeMacros())
  1963. AddMacroResults(PP, Results, PreferredTypeIsPointer);
  1964. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  1965. }
  1966. static void AddObjCProperties(ObjCContainerDecl *Container,
  1967. bool AllowCategories,
  1968. DeclContext *CurContext,
  1969. ResultBuilder &Results) {
  1970. typedef CodeCompleteConsumer::Result Result;
  1971. // Add properties in this container.
  1972. for (ObjCContainerDecl::prop_iterator P = Container->prop_begin(),
  1973. PEnd = Container->prop_end();
  1974. P != PEnd;
  1975. ++P)
  1976. Results.MaybeAddResult(Result(*P, 0), CurContext);
  1977. // Add properties in referenced protocols.
  1978. if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
  1979. for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
  1980. PEnd = Protocol->protocol_end();
  1981. P != PEnd; ++P)
  1982. AddObjCProperties(*P, AllowCategories, CurContext, Results);
  1983. } else if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)){
  1984. if (AllowCategories) {
  1985. // Look through categories.
  1986. for (ObjCCategoryDecl *Category = IFace->getCategoryList();
  1987. Category; Category = Category->getNextClassCategory())
  1988. AddObjCProperties(Category, AllowCategories, CurContext, Results);
  1989. }
  1990. // Look through protocols.
  1991. for (ObjCInterfaceDecl::protocol_iterator I = IFace->protocol_begin(),
  1992. E = IFace->protocol_end();
  1993. I != E; ++I)
  1994. AddObjCProperties(*I, AllowCategories, CurContext, Results);
  1995. // Look in the superclass.
  1996. if (IFace->getSuperClass())
  1997. AddObjCProperties(IFace->getSuperClass(), AllowCategories, CurContext,
  1998. Results);
  1999. } else if (const ObjCCategoryDecl *Category
  2000. = dyn_cast<ObjCCategoryDecl>(Container)) {
  2001. // Look through protocols.
  2002. for (ObjCInterfaceDecl::protocol_iterator P = Category->protocol_begin(),
  2003. PEnd = Category->protocol_end();
  2004. P != PEnd; ++P)
  2005. AddObjCProperties(*P, AllowCategories, CurContext, Results);
  2006. }
  2007. }
  2008. void Sema::CodeCompleteMemberReferenceExpr(Scope *S, ExprTy *BaseE,
  2009. SourceLocation OpLoc,
  2010. bool IsArrow) {
  2011. if (!BaseE || !CodeCompleter)
  2012. return;
  2013. typedef CodeCompleteConsumer::Result Result;
  2014. Expr *Base = static_cast<Expr *>(BaseE);
  2015. QualType BaseType = Base->getType();
  2016. if (IsArrow) {
  2017. if (const PointerType *Ptr = BaseType->getAs<PointerType>())
  2018. BaseType = Ptr->getPointeeType();
  2019. else if (BaseType->isObjCObjectPointerType())
  2020. /*Do nothing*/ ;
  2021. else
  2022. return;
  2023. }
  2024. ResultBuilder Results(*this, &ResultBuilder::IsMember);
  2025. Results.EnterNewScope();
  2026. if (const RecordType *Record = BaseType->getAs<RecordType>()) {
  2027. // Access to a C/C++ class, struct, or union.
  2028. Results.allowNestedNameSpecifiers();
  2029. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  2030. LookupVisibleDecls(Record->getDecl(), LookupMemberName, Consumer);
  2031. if (getLangOptions().CPlusPlus) {
  2032. if (!Results.empty()) {
  2033. // The "template" keyword can follow "->" or "." in the grammar.
  2034. // However, we only want to suggest the template keyword if something
  2035. // is dependent.
  2036. bool IsDependent = BaseType->isDependentType();
  2037. if (!IsDependent) {
  2038. for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
  2039. if (DeclContext *Ctx = (DeclContext *)DepScope->getEntity()) {
  2040. IsDependent = Ctx->isDependentContext();
  2041. break;
  2042. }
  2043. }
  2044. if (IsDependent)
  2045. Results.AddResult(Result("template"));
  2046. }
  2047. }
  2048. } else if (!IsArrow && BaseType->getAsObjCInterfacePointerType()) {
  2049. // Objective-C property reference.
  2050. // Add property results based on our interface.
  2051. const ObjCObjectPointerType *ObjCPtr
  2052. = BaseType->getAsObjCInterfacePointerType();
  2053. assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
  2054. AddObjCProperties(ObjCPtr->getInterfaceDecl(), true, CurContext, Results);
  2055. // Add properties from the protocols in a qualified interface.
  2056. for (ObjCObjectPointerType::qual_iterator I = ObjCPtr->qual_begin(),
  2057. E = ObjCPtr->qual_end();
  2058. I != E; ++I)
  2059. AddObjCProperties(*I, true, CurContext, Results);
  2060. } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
  2061. (!IsArrow && BaseType->isObjCObjectType())) {
  2062. // Objective-C instance variable access.
  2063. ObjCInterfaceDecl *Class = 0;
  2064. if (const ObjCObjectPointerType *ObjCPtr
  2065. = BaseType->getAs<ObjCObjectPointerType>())
  2066. Class = ObjCPtr->getInterfaceDecl();
  2067. else
  2068. Class = BaseType->getAs<ObjCObjectType>()->getInterface();
  2069. // Add all ivars from this class and its superclasses.
  2070. if (Class) {
  2071. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  2072. Results.setFilter(&ResultBuilder::IsObjCIvar);
  2073. LookupVisibleDecls(Class, LookupMemberName, Consumer);
  2074. }
  2075. }
  2076. // FIXME: How do we cope with isa?
  2077. Results.ExitScope();
  2078. // Hand off the results found for code completion.
  2079. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2080. }
  2081. void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
  2082. if (!CodeCompleter)
  2083. return;
  2084. typedef CodeCompleteConsumer::Result Result;
  2085. ResultBuilder::LookupFilter Filter = 0;
  2086. switch ((DeclSpec::TST)TagSpec) {
  2087. case DeclSpec::TST_enum:
  2088. Filter = &ResultBuilder::IsEnum;
  2089. break;
  2090. case DeclSpec::TST_union:
  2091. Filter = &ResultBuilder::IsUnion;
  2092. break;
  2093. case DeclSpec::TST_struct:
  2094. case DeclSpec::TST_class:
  2095. Filter = &ResultBuilder::IsClassOrStruct;
  2096. break;
  2097. default:
  2098. assert(false && "Unknown type specifier kind in CodeCompleteTag");
  2099. return;
  2100. }
  2101. ResultBuilder Results(*this);
  2102. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  2103. // First pass: look for tags.
  2104. Results.setFilter(Filter);
  2105. LookupVisibleDecls(S, LookupTagName, Consumer);
  2106. // Second pass: look for nested name specifiers.
  2107. Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
  2108. LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer);
  2109. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2110. }
  2111. void Sema::CodeCompleteCase(Scope *S) {
  2112. if (getSwitchStack().empty() || !CodeCompleter)
  2113. return;
  2114. SwitchStmt *Switch = getSwitchStack().back();
  2115. if (!Switch->getCond()->getType()->isEnumeralType()) {
  2116. CodeCompleteExpression(S, Switch->getCond()->getType(), true);
  2117. return;
  2118. }
  2119. // Code-complete the cases of a switch statement over an enumeration type
  2120. // by providing the list of
  2121. EnumDecl *Enum = Switch->getCond()->getType()->getAs<EnumType>()->getDecl();
  2122. // Determine which enumerators we have already seen in the switch statement.
  2123. // FIXME: Ideally, we would also be able to look *past* the code-completion
  2124. // token, in case we are code-completing in the middle of the switch and not
  2125. // at the end. However, we aren't able to do so at the moment.
  2126. llvm::SmallPtrSet<EnumConstantDecl *, 8> EnumeratorsSeen;
  2127. NestedNameSpecifier *Qualifier = 0;
  2128. for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
  2129. SC = SC->getNextSwitchCase()) {
  2130. CaseStmt *Case = dyn_cast<CaseStmt>(SC);
  2131. if (!Case)
  2132. continue;
  2133. Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
  2134. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(CaseVal))
  2135. if (EnumConstantDecl *Enumerator
  2136. = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  2137. // We look into the AST of the case statement to determine which
  2138. // enumerator was named. Alternatively, we could compute the value of
  2139. // the integral constant expression, then compare it against the
  2140. // values of each enumerator. However, value-based approach would not
  2141. // work as well with C++ templates where enumerators declared within a
  2142. // template are type- and value-dependent.
  2143. EnumeratorsSeen.insert(Enumerator);
  2144. // If this is a qualified-id, keep track of the nested-name-specifier
  2145. // so that we can reproduce it as part of code completion, e.g.,
  2146. //
  2147. // switch (TagD.getKind()) {
  2148. // case TagDecl::TK_enum:
  2149. // break;
  2150. // case XXX
  2151. //
  2152. // At the XXX, our completions are TagDecl::TK_union,
  2153. // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
  2154. // TK_struct, and TK_class.
  2155. Qualifier = DRE->getQualifier();
  2156. }
  2157. }
  2158. if (getLangOptions().CPlusPlus && !Qualifier && EnumeratorsSeen.empty()) {
  2159. // If there are no prior enumerators in C++, check whether we have to
  2160. // qualify the names of the enumerators that we suggest, because they
  2161. // may not be visible in this scope.
  2162. Qualifier = getRequiredQualification(Context, CurContext,
  2163. Enum->getDeclContext());
  2164. // FIXME: Scoped enums need to start with "EnumDecl" as the context!
  2165. }
  2166. // Add any enumerators that have not yet been mentioned.
  2167. ResultBuilder Results(*this);
  2168. Results.EnterNewScope();
  2169. for (EnumDecl::enumerator_iterator E = Enum->enumerator_begin(),
  2170. EEnd = Enum->enumerator_end();
  2171. E != EEnd; ++E) {
  2172. if (EnumeratorsSeen.count(*E))
  2173. continue;
  2174. Results.AddResult(CodeCompleteConsumer::Result(*E, Qualifier),
  2175. CurContext, 0, false);
  2176. }
  2177. Results.ExitScope();
  2178. if (CodeCompleter->includeMacros())
  2179. AddMacroResults(PP, Results);
  2180. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2181. }
  2182. namespace {
  2183. struct IsBetterOverloadCandidate {
  2184. Sema &S;
  2185. SourceLocation Loc;
  2186. public:
  2187. explicit IsBetterOverloadCandidate(Sema &S, SourceLocation Loc)
  2188. : S(S), Loc(Loc) { }
  2189. bool
  2190. operator()(const OverloadCandidate &X, const OverloadCandidate &Y) const {
  2191. return S.isBetterOverloadCandidate(X, Y, Loc);
  2192. }
  2193. };
  2194. }
  2195. static bool anyNullArguments(Expr **Args, unsigned NumArgs) {
  2196. if (NumArgs && !Args)
  2197. return true;
  2198. for (unsigned I = 0; I != NumArgs; ++I)
  2199. if (!Args[I])
  2200. return true;
  2201. return false;
  2202. }
  2203. void Sema::CodeCompleteCall(Scope *S, ExprTy *FnIn,
  2204. ExprTy **ArgsIn, unsigned NumArgs) {
  2205. if (!CodeCompleter)
  2206. return;
  2207. // When we're code-completing for a call, we fall back to ordinary
  2208. // name code-completion whenever we can't produce specific
  2209. // results. We may want to revisit this strategy in the future,
  2210. // e.g., by merging the two kinds of results.
  2211. Expr *Fn = (Expr *)FnIn;
  2212. Expr **Args = (Expr **)ArgsIn;
  2213. // Ignore type-dependent call expressions entirely.
  2214. if (!Fn || Fn->isTypeDependent() || anyNullArguments(Args, NumArgs) ||
  2215. Expr::hasAnyTypeDependentArguments(Args, NumArgs)) {
  2216. CodeCompleteOrdinaryName(S, CCC_Expression);
  2217. return;
  2218. }
  2219. // Build an overload candidate set based on the functions we find.
  2220. SourceLocation Loc = Fn->getExprLoc();
  2221. OverloadCandidateSet CandidateSet(Loc);
  2222. // FIXME: What if we're calling something that isn't a function declaration?
  2223. // FIXME: What if we're calling a pseudo-destructor?
  2224. // FIXME: What if we're calling a member function?
  2225. typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
  2226. llvm::SmallVector<ResultCandidate, 8> Results;
  2227. Expr *NakedFn = Fn->IgnoreParenCasts();
  2228. if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn))
  2229. AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet,
  2230. /*PartialOverloading=*/ true);
  2231. else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
  2232. FunctionDecl *FDecl = dyn_cast<FunctionDecl>(DRE->getDecl());
  2233. if (FDecl) {
  2234. if (!getLangOptions().CPlusPlus ||
  2235. !FDecl->getType()->getAs<FunctionProtoType>())
  2236. Results.push_back(ResultCandidate(FDecl));
  2237. else
  2238. // FIXME: access?
  2239. AddOverloadCandidate(FDecl, DeclAccessPair::make(FDecl, AS_none),
  2240. Args, NumArgs, CandidateSet,
  2241. false, /*PartialOverloading*/true);
  2242. }
  2243. }
  2244. QualType ParamType;
  2245. if (!CandidateSet.empty()) {
  2246. // Sort the overload candidate set by placing the best overloads first.
  2247. std::stable_sort(CandidateSet.begin(), CandidateSet.end(),
  2248. IsBetterOverloadCandidate(*this, Loc));
  2249. // Add the remaining viable overload candidates as code-completion reslults.
  2250. for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
  2251. CandEnd = CandidateSet.end();
  2252. Cand != CandEnd; ++Cand) {
  2253. if (Cand->Viable)
  2254. Results.push_back(ResultCandidate(Cand->Function));
  2255. }
  2256. // From the viable candidates, try to determine the type of this parameter.
  2257. for (unsigned I = 0, N = Results.size(); I != N; ++I) {
  2258. if (const FunctionType *FType = Results[I].getFunctionType())
  2259. if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FType))
  2260. if (NumArgs < Proto->getNumArgs()) {
  2261. if (ParamType.isNull())
  2262. ParamType = Proto->getArgType(NumArgs);
  2263. else if (!Context.hasSameUnqualifiedType(
  2264. ParamType.getNonReferenceType(),
  2265. Proto->getArgType(NumArgs).getNonReferenceType())) {
  2266. ParamType = QualType();
  2267. break;
  2268. }
  2269. }
  2270. }
  2271. } else {
  2272. // Try to determine the parameter type from the type of the expression
  2273. // being called.
  2274. QualType FunctionType = Fn->getType();
  2275. if (const PointerType *Ptr = FunctionType->getAs<PointerType>())
  2276. FunctionType = Ptr->getPointeeType();
  2277. else if (const BlockPointerType *BlockPtr
  2278. = FunctionType->getAs<BlockPointerType>())
  2279. FunctionType = BlockPtr->getPointeeType();
  2280. else if (const MemberPointerType *MemPtr
  2281. = FunctionType->getAs<MemberPointerType>())
  2282. FunctionType = MemPtr->getPointeeType();
  2283. if (const FunctionProtoType *Proto
  2284. = FunctionType->getAs<FunctionProtoType>()) {
  2285. if (NumArgs < Proto->getNumArgs())
  2286. ParamType = Proto->getArgType(NumArgs);
  2287. }
  2288. }
  2289. if (ParamType.isNull())
  2290. CodeCompleteOrdinaryName(S, CCC_Expression);
  2291. else
  2292. CodeCompleteExpression(S, ParamType);
  2293. if (!Results.empty())
  2294. CodeCompleter->ProcessOverloadCandidates(*this, NumArgs, Results.data(),
  2295. Results.size());
  2296. }
  2297. void Sema::CodeCompleteInitializer(Scope *S, DeclPtrTy D) {
  2298. ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D.getAs<Decl>());
  2299. if (!VD) {
  2300. CodeCompleteOrdinaryName(S, CCC_Expression);
  2301. return;
  2302. }
  2303. CodeCompleteExpression(S, VD->getType());
  2304. }
  2305. void Sema::CodeCompleteReturn(Scope *S) {
  2306. QualType ResultType;
  2307. if (isa<BlockDecl>(CurContext)) {
  2308. if (BlockScopeInfo *BSI = getCurBlock())
  2309. ResultType = BSI->ReturnType;
  2310. } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(CurContext))
  2311. ResultType = Function->getResultType();
  2312. else if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(CurContext))
  2313. ResultType = Method->getResultType();
  2314. if (ResultType.isNull())
  2315. CodeCompleteOrdinaryName(S, CCC_Expression);
  2316. else
  2317. CodeCompleteExpression(S, ResultType);
  2318. }
  2319. void Sema::CodeCompleteAssignmentRHS(Scope *S, ExprTy *LHS) {
  2320. if (LHS)
  2321. CodeCompleteExpression(S, static_cast<Expr *>(LHS)->getType());
  2322. else
  2323. CodeCompleteOrdinaryName(S, CCC_Expression);
  2324. }
  2325. void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
  2326. bool EnteringContext) {
  2327. if (!SS.getScopeRep() || !CodeCompleter)
  2328. return;
  2329. DeclContext *Ctx = computeDeclContext(SS, EnteringContext);
  2330. if (!Ctx)
  2331. return;
  2332. // Try to instantiate any non-dependent declaration contexts before
  2333. // we look in them.
  2334. if (!isDependentScopeSpecifier(SS) && RequireCompleteDeclContext(SS, Ctx))
  2335. return;
  2336. ResultBuilder Results(*this);
  2337. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  2338. LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer);
  2339. // The "template" keyword can follow "::" in the grammar, but only
  2340. // put it into the grammar if the nested-name-specifier is dependent.
  2341. NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
  2342. if (!Results.empty() && NNS->isDependent())
  2343. Results.AddResult("template");
  2344. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2345. }
  2346. void Sema::CodeCompleteUsing(Scope *S) {
  2347. if (!CodeCompleter)
  2348. return;
  2349. ResultBuilder Results(*this, &ResultBuilder::IsNestedNameSpecifier);
  2350. Results.EnterNewScope();
  2351. // If we aren't in class scope, we could see the "namespace" keyword.
  2352. if (!S->isClassScope())
  2353. Results.AddResult(CodeCompleteConsumer::Result("namespace"));
  2354. // After "using", we can see anything that would start a
  2355. // nested-name-specifier.
  2356. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  2357. LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
  2358. Results.ExitScope();
  2359. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2360. }
  2361. void Sema::CodeCompleteUsingDirective(Scope *S) {
  2362. if (!CodeCompleter)
  2363. return;
  2364. // After "using namespace", we expect to see a namespace name or namespace
  2365. // alias.
  2366. ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
  2367. Results.EnterNewScope();
  2368. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  2369. LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
  2370. Results.ExitScope();
  2371. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2372. }
  2373. void Sema::CodeCompleteNamespaceDecl(Scope *S) {
  2374. if (!CodeCompleter)
  2375. return;
  2376. ResultBuilder Results(*this, &ResultBuilder::IsNamespace);
  2377. DeclContext *Ctx = (DeclContext *)S->getEntity();
  2378. if (!S->getParent())
  2379. Ctx = Context.getTranslationUnitDecl();
  2380. if (Ctx && Ctx->isFileContext()) {
  2381. // We only want to see those namespaces that have already been defined
  2382. // within this scope, because its likely that the user is creating an
  2383. // extended namespace declaration. Keep track of the most recent
  2384. // definition of each namespace.
  2385. std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
  2386. for (DeclContext::specific_decl_iterator<NamespaceDecl>
  2387. NS(Ctx->decls_begin()), NSEnd(Ctx->decls_end());
  2388. NS != NSEnd; ++NS)
  2389. OrigToLatest[NS->getOriginalNamespace()] = *NS;
  2390. // Add the most recent definition (or extended definition) of each
  2391. // namespace to the list of results.
  2392. Results.EnterNewScope();
  2393. for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
  2394. NS = OrigToLatest.begin(), NSEnd = OrigToLatest.end();
  2395. NS != NSEnd; ++NS)
  2396. Results.AddResult(CodeCompleteConsumer::Result(NS->second, 0),
  2397. CurContext, 0, false);
  2398. Results.ExitScope();
  2399. }
  2400. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2401. }
  2402. void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
  2403. if (!CodeCompleter)
  2404. return;
  2405. // After "namespace", we expect to see a namespace or alias.
  2406. ResultBuilder Results(*this, &ResultBuilder::IsNamespaceOrAlias);
  2407. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  2408. LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
  2409. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2410. }
  2411. void Sema::CodeCompleteOperatorName(Scope *S) {
  2412. if (!CodeCompleter)
  2413. return;
  2414. typedef CodeCompleteConsumer::Result Result;
  2415. ResultBuilder Results(*this, &ResultBuilder::IsType);
  2416. Results.EnterNewScope();
  2417. // Add the names of overloadable operators.
  2418. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  2419. if (std::strcmp(Spelling, "?")) \
  2420. Results.AddResult(Result(Spelling));
  2421. #include "clang/Basic/OperatorKinds.def"
  2422. // Add any type names visible from the current scope
  2423. Results.allowNestedNameSpecifiers();
  2424. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  2425. LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
  2426. // Add any type specifiers
  2427. AddTypeSpecifierResults(getLangOptions(), Results);
  2428. Results.ExitScope();
  2429. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2430. }
  2431. // Macro that expands to @Keyword or Keyword, depending on whether NeedAt is
  2432. // true or false.
  2433. #define OBJC_AT_KEYWORD_NAME(NeedAt,Keyword) NeedAt? "@" #Keyword : #Keyword
  2434. static void AddObjCImplementationResults(const LangOptions &LangOpts,
  2435. ResultBuilder &Results,
  2436. bool NeedAt) {
  2437. typedef CodeCompleteConsumer::Result Result;
  2438. // Since we have an implementation, we can end it.
  2439. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
  2440. CodeCompletionString *Pattern = 0;
  2441. if (LangOpts.ObjC2) {
  2442. // @dynamic
  2443. Pattern = new CodeCompletionString;
  2444. Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,dynamic));
  2445. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2446. Pattern->AddPlaceholderChunk("property");
  2447. Results.AddResult(Result(Pattern));
  2448. // @synthesize
  2449. Pattern = new CodeCompletionString;
  2450. Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synthesize));
  2451. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2452. Pattern->AddPlaceholderChunk("property");
  2453. Results.AddResult(Result(Pattern));
  2454. }
  2455. }
  2456. static void AddObjCInterfaceResults(const LangOptions &LangOpts,
  2457. ResultBuilder &Results,
  2458. bool NeedAt) {
  2459. typedef CodeCompleteConsumer::Result Result;
  2460. // Since we have an interface or protocol, we can end it.
  2461. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,end)));
  2462. if (LangOpts.ObjC2) {
  2463. // @property
  2464. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,property)));
  2465. // @required
  2466. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,required)));
  2467. // @optional
  2468. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,optional)));
  2469. }
  2470. }
  2471. static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
  2472. typedef CodeCompleteConsumer::Result Result;
  2473. CodeCompletionString *Pattern = 0;
  2474. // @class name ;
  2475. Pattern = new CodeCompletionString;
  2476. Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,class));
  2477. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2478. Pattern->AddPlaceholderChunk("name");
  2479. Results.AddResult(Result(Pattern));
  2480. if (Results.includeCodePatterns()) {
  2481. // @interface name
  2482. // FIXME: Could introduce the whole pattern, including superclasses and
  2483. // such.
  2484. Pattern = new CodeCompletionString;
  2485. Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,interface));
  2486. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2487. Pattern->AddPlaceholderChunk("class");
  2488. Results.AddResult(Result(Pattern));
  2489. // @protocol name
  2490. Pattern = new CodeCompletionString;
  2491. Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
  2492. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2493. Pattern->AddPlaceholderChunk("protocol");
  2494. Results.AddResult(Result(Pattern));
  2495. // @implementation name
  2496. Pattern = new CodeCompletionString;
  2497. Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,implementation));
  2498. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2499. Pattern->AddPlaceholderChunk("class");
  2500. Results.AddResult(Result(Pattern));
  2501. }
  2502. // @compatibility_alias name
  2503. Pattern = new CodeCompletionString;
  2504. Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,compatibility_alias));
  2505. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2506. Pattern->AddPlaceholderChunk("alias");
  2507. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2508. Pattern->AddPlaceholderChunk("class");
  2509. Results.AddResult(Result(Pattern));
  2510. }
  2511. void Sema::CodeCompleteObjCAtDirective(Scope *S, DeclPtrTy ObjCImpDecl,
  2512. bool InInterface) {
  2513. typedef CodeCompleteConsumer::Result Result;
  2514. ResultBuilder Results(*this);
  2515. Results.EnterNewScope();
  2516. if (ObjCImpDecl)
  2517. AddObjCImplementationResults(getLangOptions(), Results, false);
  2518. else if (InInterface)
  2519. AddObjCInterfaceResults(getLangOptions(), Results, false);
  2520. else
  2521. AddObjCTopLevelResults(Results, false);
  2522. Results.ExitScope();
  2523. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2524. }
  2525. static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
  2526. typedef CodeCompleteConsumer::Result Result;
  2527. CodeCompletionString *Pattern = 0;
  2528. // @encode ( type-name )
  2529. Pattern = new CodeCompletionString;
  2530. Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,encode));
  2531. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  2532. Pattern->AddPlaceholderChunk("type-name");
  2533. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  2534. Results.AddResult(Result(Pattern));
  2535. // @protocol ( protocol-name )
  2536. Pattern = new CodeCompletionString;
  2537. Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,protocol));
  2538. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  2539. Pattern->AddPlaceholderChunk("protocol-name");
  2540. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  2541. Results.AddResult(Result(Pattern));
  2542. // @selector ( selector )
  2543. Pattern = new CodeCompletionString;
  2544. Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,selector));
  2545. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  2546. Pattern->AddPlaceholderChunk("selector");
  2547. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  2548. Results.AddResult(Result(Pattern));
  2549. }
  2550. static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
  2551. typedef CodeCompleteConsumer::Result Result;
  2552. CodeCompletionString *Pattern = 0;
  2553. if (Results.includeCodePatterns()) {
  2554. // @try { statements } @catch ( declaration ) { statements } @finally
  2555. // { statements }
  2556. Pattern = new CodeCompletionString;
  2557. Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,try));
  2558. Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
  2559. Pattern->AddPlaceholderChunk("statements");
  2560. Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
  2561. Pattern->AddTextChunk("@catch");
  2562. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  2563. Pattern->AddPlaceholderChunk("parameter");
  2564. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  2565. Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
  2566. Pattern->AddPlaceholderChunk("statements");
  2567. Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
  2568. Pattern->AddTextChunk("@finally");
  2569. Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
  2570. Pattern->AddPlaceholderChunk("statements");
  2571. Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
  2572. Results.AddResult(Result(Pattern));
  2573. }
  2574. // @throw
  2575. Pattern = new CodeCompletionString;
  2576. Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,throw));
  2577. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2578. Pattern->AddPlaceholderChunk("expression");
  2579. Results.AddResult(Result(Pattern));
  2580. if (Results.includeCodePatterns()) {
  2581. // @synchronized ( expression ) { statements }
  2582. Pattern = new CodeCompletionString;
  2583. Pattern->AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt,synchronized));
  2584. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2585. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  2586. Pattern->AddPlaceholderChunk("expression");
  2587. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  2588. Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
  2589. Pattern->AddPlaceholderChunk("statements");
  2590. Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
  2591. Results.AddResult(Result(Pattern));
  2592. }
  2593. }
  2594. static void AddObjCVisibilityResults(const LangOptions &LangOpts,
  2595. ResultBuilder &Results,
  2596. bool NeedAt) {
  2597. typedef CodeCompleteConsumer::Result Result;
  2598. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,private)));
  2599. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,protected)));
  2600. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,public)));
  2601. if (LangOpts.ObjC2)
  2602. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt,package)));
  2603. }
  2604. void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
  2605. ResultBuilder Results(*this);
  2606. Results.EnterNewScope();
  2607. AddObjCVisibilityResults(getLangOptions(), Results, false);
  2608. Results.ExitScope();
  2609. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2610. }
  2611. void Sema::CodeCompleteObjCAtStatement(Scope *S) {
  2612. ResultBuilder Results(*this);
  2613. Results.EnterNewScope();
  2614. AddObjCStatementResults(Results, false);
  2615. AddObjCExpressionResults(Results, false);
  2616. Results.ExitScope();
  2617. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2618. }
  2619. void Sema::CodeCompleteObjCAtExpression(Scope *S) {
  2620. ResultBuilder Results(*this);
  2621. Results.EnterNewScope();
  2622. AddObjCExpressionResults(Results, false);
  2623. Results.ExitScope();
  2624. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2625. }
  2626. /// \brief Determine whether the addition of the given flag to an Objective-C
  2627. /// property's attributes will cause a conflict.
  2628. static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
  2629. // Check if we've already added this flag.
  2630. if (Attributes & NewFlag)
  2631. return true;
  2632. Attributes |= NewFlag;
  2633. // Check for collisions with "readonly".
  2634. if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
  2635. (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
  2636. ObjCDeclSpec::DQ_PR_assign |
  2637. ObjCDeclSpec::DQ_PR_copy |
  2638. ObjCDeclSpec::DQ_PR_retain)))
  2639. return true;
  2640. // Check for more than one of { assign, copy, retain }.
  2641. unsigned AssignCopyRetMask = Attributes & (ObjCDeclSpec::DQ_PR_assign |
  2642. ObjCDeclSpec::DQ_PR_copy |
  2643. ObjCDeclSpec::DQ_PR_retain);
  2644. if (AssignCopyRetMask &&
  2645. AssignCopyRetMask != ObjCDeclSpec::DQ_PR_assign &&
  2646. AssignCopyRetMask != ObjCDeclSpec::DQ_PR_copy &&
  2647. AssignCopyRetMask != ObjCDeclSpec::DQ_PR_retain)
  2648. return true;
  2649. return false;
  2650. }
  2651. void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
  2652. if (!CodeCompleter)
  2653. return;
  2654. unsigned Attributes = ODS.getPropertyAttributes();
  2655. typedef CodeCompleteConsumer::Result Result;
  2656. ResultBuilder Results(*this);
  2657. Results.EnterNewScope();
  2658. if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readonly))
  2659. Results.AddResult(CodeCompleteConsumer::Result("readonly"));
  2660. if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_assign))
  2661. Results.AddResult(CodeCompleteConsumer::Result("assign"));
  2662. if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_readwrite))
  2663. Results.AddResult(CodeCompleteConsumer::Result("readwrite"));
  2664. if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_retain))
  2665. Results.AddResult(CodeCompleteConsumer::Result("retain"));
  2666. if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_copy))
  2667. Results.AddResult(CodeCompleteConsumer::Result("copy"));
  2668. if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_nonatomic))
  2669. Results.AddResult(CodeCompleteConsumer::Result("nonatomic"));
  2670. if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_setter)) {
  2671. CodeCompletionString *Setter = new CodeCompletionString;
  2672. Setter->AddTypedTextChunk("setter");
  2673. Setter->AddTextChunk(" = ");
  2674. Setter->AddPlaceholderChunk("method");
  2675. Results.AddResult(CodeCompleteConsumer::Result(Setter));
  2676. }
  2677. if (!ObjCPropertyFlagConflicts(Attributes, ObjCDeclSpec::DQ_PR_getter)) {
  2678. CodeCompletionString *Getter = new CodeCompletionString;
  2679. Getter->AddTypedTextChunk("getter");
  2680. Getter->AddTextChunk(" = ");
  2681. Getter->AddPlaceholderChunk("method");
  2682. Results.AddResult(CodeCompleteConsumer::Result(Getter));
  2683. }
  2684. Results.ExitScope();
  2685. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2686. }
  2687. /// \brief Descripts the kind of Objective-C method that we want to find
  2688. /// via code completion.
  2689. enum ObjCMethodKind {
  2690. MK_Any, //< Any kind of method, provided it means other specified criteria.
  2691. MK_ZeroArgSelector, //< Zero-argument (unary) selector.
  2692. MK_OneArgSelector //< One-argument selector.
  2693. };
  2694. static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
  2695. ObjCMethodKind WantKind,
  2696. IdentifierInfo **SelIdents,
  2697. unsigned NumSelIdents) {
  2698. Selector Sel = Method->getSelector();
  2699. if (NumSelIdents > Sel.getNumArgs())
  2700. return false;
  2701. switch (WantKind) {
  2702. case MK_Any: break;
  2703. case MK_ZeroArgSelector: return Sel.isUnarySelector();
  2704. case MK_OneArgSelector: return Sel.getNumArgs() == 1;
  2705. }
  2706. for (unsigned I = 0; I != NumSelIdents; ++I)
  2707. if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
  2708. return false;
  2709. return true;
  2710. }
  2711. /// \brief Add all of the Objective-C methods in the given Objective-C
  2712. /// container to the set of results.
  2713. ///
  2714. /// The container will be a class, protocol, category, or implementation of
  2715. /// any of the above. This mether will recurse to include methods from
  2716. /// the superclasses of classes along with their categories, protocols, and
  2717. /// implementations.
  2718. ///
  2719. /// \param Container the container in which we'll look to find methods.
  2720. ///
  2721. /// \param WantInstance whether to add instance methods (only); if false, this
  2722. /// routine will add factory methods (only).
  2723. ///
  2724. /// \param CurContext the context in which we're performing the lookup that
  2725. /// finds methods.
  2726. ///
  2727. /// \param Results the structure into which we'll add results.
  2728. static void AddObjCMethods(ObjCContainerDecl *Container,
  2729. bool WantInstanceMethods,
  2730. ObjCMethodKind WantKind,
  2731. IdentifierInfo **SelIdents,
  2732. unsigned NumSelIdents,
  2733. DeclContext *CurContext,
  2734. ResultBuilder &Results) {
  2735. typedef CodeCompleteConsumer::Result Result;
  2736. for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
  2737. MEnd = Container->meth_end();
  2738. M != MEnd; ++M) {
  2739. if ((*M)->isInstanceMethod() == WantInstanceMethods) {
  2740. // Check whether the selector identifiers we've been given are a
  2741. // subset of the identifiers for this particular method.
  2742. if (!isAcceptableObjCMethod(*M, WantKind, SelIdents, NumSelIdents))
  2743. continue;
  2744. Result R = Result(*M, 0);
  2745. R.StartParameter = NumSelIdents;
  2746. R.AllParametersAreInformative = (WantKind != MK_Any);
  2747. Results.MaybeAddResult(R, CurContext);
  2748. }
  2749. }
  2750. ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
  2751. if (!IFace)
  2752. return;
  2753. // Add methods in protocols.
  2754. const ObjCList<ObjCProtocolDecl> &Protocols= IFace->getReferencedProtocols();
  2755. for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
  2756. E = Protocols.end();
  2757. I != E; ++I)
  2758. AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, NumSelIdents,
  2759. CurContext, Results);
  2760. // Add methods in categories.
  2761. for (ObjCCategoryDecl *CatDecl = IFace->getCategoryList(); CatDecl;
  2762. CatDecl = CatDecl->getNextClassCategory()) {
  2763. AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
  2764. NumSelIdents, CurContext, Results);
  2765. // Add a categories protocol methods.
  2766. const ObjCList<ObjCProtocolDecl> &Protocols
  2767. = CatDecl->getReferencedProtocols();
  2768. for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
  2769. E = Protocols.end();
  2770. I != E; ++I)
  2771. AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents,
  2772. NumSelIdents, CurContext, Results);
  2773. // Add methods in category implementations.
  2774. if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
  2775. AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
  2776. NumSelIdents, CurContext, Results);
  2777. }
  2778. // Add methods in superclass.
  2779. if (IFace->getSuperClass())
  2780. AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
  2781. SelIdents, NumSelIdents, CurContext, Results);
  2782. // Add methods in our implementation, if any.
  2783. if (ObjCImplementationDecl *Impl = IFace->getImplementation())
  2784. AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents,
  2785. NumSelIdents, CurContext, Results);
  2786. }
  2787. void Sema::CodeCompleteObjCPropertyGetter(Scope *S, DeclPtrTy ClassDecl,
  2788. DeclPtrTy *Methods,
  2789. unsigned NumMethods) {
  2790. typedef CodeCompleteConsumer::Result Result;
  2791. // Try to find the interface where getters might live.
  2792. ObjCInterfaceDecl *Class
  2793. = dyn_cast_or_null<ObjCInterfaceDecl>(ClassDecl.getAs<Decl>());
  2794. if (!Class) {
  2795. if (ObjCCategoryDecl *Category
  2796. = dyn_cast_or_null<ObjCCategoryDecl>(ClassDecl.getAs<Decl>()))
  2797. Class = Category->getClassInterface();
  2798. if (!Class)
  2799. return;
  2800. }
  2801. // Find all of the potential getters.
  2802. ResultBuilder Results(*this);
  2803. Results.EnterNewScope();
  2804. // FIXME: We need to do this because Objective-C methods don't get
  2805. // pushed into DeclContexts early enough. Argh!
  2806. for (unsigned I = 0; I != NumMethods; ++I) {
  2807. if (ObjCMethodDecl *Method
  2808. = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
  2809. if (Method->isInstanceMethod() &&
  2810. isAcceptableObjCMethod(Method, MK_ZeroArgSelector, 0, 0)) {
  2811. Result R = Result(Method, 0);
  2812. R.AllParametersAreInformative = true;
  2813. Results.MaybeAddResult(R, CurContext);
  2814. }
  2815. }
  2816. AddObjCMethods(Class, true, MK_ZeroArgSelector, 0, 0, CurContext, Results);
  2817. Results.ExitScope();
  2818. HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
  2819. }
  2820. void Sema::CodeCompleteObjCPropertySetter(Scope *S, DeclPtrTy ObjCImplDecl,
  2821. DeclPtrTy *Methods,
  2822. unsigned NumMethods) {
  2823. typedef CodeCompleteConsumer::Result Result;
  2824. // Try to find the interface where setters might live.
  2825. ObjCInterfaceDecl *Class
  2826. = dyn_cast_or_null<ObjCInterfaceDecl>(ObjCImplDecl.getAs<Decl>());
  2827. if (!Class) {
  2828. if (ObjCCategoryDecl *Category
  2829. = dyn_cast_or_null<ObjCCategoryDecl>(ObjCImplDecl.getAs<Decl>()))
  2830. Class = Category->getClassInterface();
  2831. if (!Class)
  2832. return;
  2833. }
  2834. // Find all of the potential getters.
  2835. ResultBuilder Results(*this);
  2836. Results.EnterNewScope();
  2837. // FIXME: We need to do this because Objective-C methods don't get
  2838. // pushed into DeclContexts early enough. Argh!
  2839. for (unsigned I = 0; I != NumMethods; ++I) {
  2840. if (ObjCMethodDecl *Method
  2841. = dyn_cast_or_null<ObjCMethodDecl>(Methods[I].getAs<Decl>()))
  2842. if (Method->isInstanceMethod() &&
  2843. isAcceptableObjCMethod(Method, MK_OneArgSelector, 0, 0)) {
  2844. Result R = Result(Method, 0);
  2845. R.AllParametersAreInformative = true;
  2846. Results.MaybeAddResult(R, CurContext);
  2847. }
  2848. }
  2849. AddObjCMethods(Class, true, MK_OneArgSelector, 0, 0, CurContext, Results);
  2850. Results.ExitScope();
  2851. HandleCodeCompleteResults(this, CodeCompleter,Results.data(),Results.size());
  2852. }
  2853. /// \brief When we have an expression with type "id", we may assume
  2854. /// that it has some more-specific class type based on knowledge of
  2855. /// common uses of Objective-C. This routine returns that class type,
  2856. /// or NULL if no better result could be determined.
  2857. static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
  2858. ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E);
  2859. if (!Msg)
  2860. return 0;
  2861. Selector Sel = Msg->getSelector();
  2862. if (Sel.isNull())
  2863. return 0;
  2864. IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
  2865. if (!Id)
  2866. return 0;
  2867. ObjCMethodDecl *Method = Msg->getMethodDecl();
  2868. if (!Method)
  2869. return 0;
  2870. // Determine the class that we're sending the message to.
  2871. ObjCInterfaceDecl *IFace = 0;
  2872. switch (Msg->getReceiverKind()) {
  2873. case ObjCMessageExpr::Class:
  2874. if (const ObjCObjectType *ObjType
  2875. = Msg->getClassReceiver()->getAs<ObjCObjectType>())
  2876. IFace = ObjType->getInterface();
  2877. break;
  2878. case ObjCMessageExpr::Instance: {
  2879. QualType T = Msg->getInstanceReceiver()->getType();
  2880. if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
  2881. IFace = Ptr->getInterfaceDecl();
  2882. break;
  2883. }
  2884. case ObjCMessageExpr::SuperInstance:
  2885. case ObjCMessageExpr::SuperClass:
  2886. break;
  2887. }
  2888. if (!IFace)
  2889. return 0;
  2890. ObjCInterfaceDecl *Super = IFace->getSuperClass();
  2891. if (Method->isInstanceMethod())
  2892. return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
  2893. .Case("retain", IFace)
  2894. .Case("autorelease", IFace)
  2895. .Case("copy", IFace)
  2896. .Case("copyWithZone", IFace)
  2897. .Case("mutableCopy", IFace)
  2898. .Case("mutableCopyWithZone", IFace)
  2899. .Case("awakeFromCoder", IFace)
  2900. .Case("replacementObjectFromCoder", IFace)
  2901. .Case("class", IFace)
  2902. .Case("classForCoder", IFace)
  2903. .Case("superclass", Super)
  2904. .Default(0);
  2905. return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
  2906. .Case("new", IFace)
  2907. .Case("alloc", IFace)
  2908. .Case("allocWithZone", IFace)
  2909. .Case("class", IFace)
  2910. .Case("superclass", Super)
  2911. .Default(0);
  2912. }
  2913. void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
  2914. typedef CodeCompleteConsumer::Result Result;
  2915. ResultBuilder Results(*this);
  2916. // Find anything that looks like it could be a message receiver.
  2917. Results.setFilter(&ResultBuilder::IsObjCMessageReceiver);
  2918. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  2919. Results.EnterNewScope();
  2920. LookupVisibleDecls(S, LookupOrdinaryName, Consumer);
  2921. // If we are in an Objective-C method inside a class that has a superclass,
  2922. // add "super" as an option.
  2923. if (ObjCMethodDecl *Method = getCurMethodDecl())
  2924. if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
  2925. if (Iface->getSuperClass())
  2926. Results.AddResult(Result("super"));
  2927. Results.ExitScope();
  2928. if (CodeCompleter->includeMacros())
  2929. AddMacroResults(PP, Results);
  2930. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  2931. }
  2932. void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
  2933. IdentifierInfo **SelIdents,
  2934. unsigned NumSelIdents) {
  2935. ObjCInterfaceDecl *CDecl = 0;
  2936. if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
  2937. // Figure out which interface we're in.
  2938. CDecl = CurMethod->getClassInterface();
  2939. if (!CDecl)
  2940. return;
  2941. // Find the superclass of this class.
  2942. CDecl = CDecl->getSuperClass();
  2943. if (!CDecl)
  2944. return;
  2945. if (CurMethod->isInstanceMethod()) {
  2946. // We are inside an instance method, which means that the message
  2947. // send [super ...] is actually calling an instance method on the
  2948. // current object. Build the super expression and handle this like
  2949. // an instance method.
  2950. QualType SuperTy = Context.getObjCInterfaceType(CDecl);
  2951. SuperTy = Context.getObjCObjectPointerType(SuperTy);
  2952. OwningExprResult Super
  2953. = Owned(new (Context) ObjCSuperExpr(SuperLoc, SuperTy));
  2954. return CodeCompleteObjCInstanceMessage(S, (Expr *)Super.get(),
  2955. SelIdents, NumSelIdents);
  2956. }
  2957. // Fall through to send to the superclass in CDecl.
  2958. } else {
  2959. // "super" may be the name of a type or variable. Figure out which
  2960. // it is.
  2961. IdentifierInfo *Super = &Context.Idents.get("super");
  2962. NamedDecl *ND = LookupSingleName(S, Super, SuperLoc,
  2963. LookupOrdinaryName);
  2964. if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
  2965. // "super" names an interface. Use it.
  2966. } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
  2967. if (const ObjCObjectType *Iface
  2968. = Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
  2969. CDecl = Iface->getInterface();
  2970. } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
  2971. // "super" names an unresolved type; we can't be more specific.
  2972. } else {
  2973. // Assume that "super" names some kind of value and parse that way.
  2974. CXXScopeSpec SS;
  2975. UnqualifiedId id;
  2976. id.setIdentifier(Super, SuperLoc);
  2977. OwningExprResult SuperExpr = ActOnIdExpression(S, SS, id, false, false);
  2978. return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
  2979. SelIdents, NumSelIdents);
  2980. }
  2981. // Fall through
  2982. }
  2983. TypeTy *Receiver = 0;
  2984. if (CDecl)
  2985. Receiver = Context.getObjCInterfaceType(CDecl).getAsOpaquePtr();
  2986. return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
  2987. NumSelIdents);
  2988. }
  2989. void Sema::CodeCompleteObjCClassMessage(Scope *S, TypeTy *Receiver,
  2990. IdentifierInfo **SelIdents,
  2991. unsigned NumSelIdents) {
  2992. typedef CodeCompleteConsumer::Result Result;
  2993. ObjCInterfaceDecl *CDecl = 0;
  2994. // If the given name refers to an interface type, retrieve the
  2995. // corresponding declaration.
  2996. if (Receiver) {
  2997. QualType T = GetTypeFromParser(Receiver, 0);
  2998. if (!T.isNull())
  2999. if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
  3000. CDecl = Interface->getInterface();
  3001. }
  3002. // Add all of the factory methods in this Objective-C class, its protocols,
  3003. // superclasses, categories, implementation, etc.
  3004. ResultBuilder Results(*this);
  3005. Results.EnterNewScope();
  3006. if (CDecl)
  3007. AddObjCMethods(CDecl, false, MK_Any, SelIdents, NumSelIdents, CurContext,
  3008. Results);
  3009. else {
  3010. // We're messaging "id" as a type; provide all class/factory methods.
  3011. // If we have an external source, load the entire class method
  3012. // pool from the PCH file.
  3013. if (ExternalSource) {
  3014. for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
  3015. I != N; ++I) {
  3016. Selector Sel = ExternalSource->GetExternalSelector(I);
  3017. if (Sel.isNull() || MethodPool.count(Sel))
  3018. continue;
  3019. ReadMethodPool(Sel);
  3020. }
  3021. }
  3022. for (GlobalMethodPool::iterator M = MethodPool.begin(),
  3023. MEnd = MethodPool.end();
  3024. M != MEnd; ++M) {
  3025. for (ObjCMethodList *MethList = &M->second.second;
  3026. MethList && MethList->Method;
  3027. MethList = MethList->Next) {
  3028. if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
  3029. NumSelIdents))
  3030. continue;
  3031. Result R(MethList->Method, 0);
  3032. R.StartParameter = NumSelIdents;
  3033. R.AllParametersAreInformative = false;
  3034. Results.MaybeAddResult(R, CurContext);
  3035. }
  3036. }
  3037. }
  3038. Results.ExitScope();
  3039. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  3040. }
  3041. void Sema::CodeCompleteObjCInstanceMessage(Scope *S, ExprTy *Receiver,
  3042. IdentifierInfo **SelIdents,
  3043. unsigned NumSelIdents) {
  3044. typedef CodeCompleteConsumer::Result Result;
  3045. Expr *RecExpr = static_cast<Expr *>(Receiver);
  3046. // If necessary, apply function/array conversion to the receiver.
  3047. // C99 6.7.5.3p[7,8].
  3048. DefaultFunctionArrayLvalueConversion(RecExpr);
  3049. QualType ReceiverType = RecExpr->getType();
  3050. // Build the set of methods we can see.
  3051. ResultBuilder Results(*this);
  3052. Results.EnterNewScope();
  3053. // If we're messaging an expression with type "id" or "Class", check
  3054. // whether we know something special about the receiver that allows
  3055. // us to assume a more-specific receiver type.
  3056. if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType())
  3057. if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr))
  3058. ReceiverType = Context.getObjCObjectPointerType(
  3059. Context.getObjCInterfaceType(IFace));
  3060. // Handle messages to Class. This really isn't a message to an instance
  3061. // method, so we treat it the same way we would treat a message send to a
  3062. // class method.
  3063. if (ReceiverType->isObjCClassType() ||
  3064. ReceiverType->isObjCQualifiedClassType()) {
  3065. if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
  3066. if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
  3067. AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, NumSelIdents,
  3068. CurContext, Results);
  3069. }
  3070. }
  3071. // Handle messages to a qualified ID ("id<foo>").
  3072. else if (const ObjCObjectPointerType *QualID
  3073. = ReceiverType->getAsObjCQualifiedIdType()) {
  3074. // Search protocols for instance methods.
  3075. for (ObjCObjectPointerType::qual_iterator I = QualID->qual_begin(),
  3076. E = QualID->qual_end();
  3077. I != E; ++I)
  3078. AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
  3079. Results);
  3080. }
  3081. // Handle messages to a pointer to interface type.
  3082. else if (const ObjCObjectPointerType *IFacePtr
  3083. = ReceiverType->getAsObjCInterfacePointerType()) {
  3084. // Search the class, its superclasses, etc., for instance methods.
  3085. AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
  3086. NumSelIdents, CurContext, Results);
  3087. // Search protocols for instance methods.
  3088. for (ObjCObjectPointerType::qual_iterator I = IFacePtr->qual_begin(),
  3089. E = IFacePtr->qual_end();
  3090. I != E; ++I)
  3091. AddObjCMethods(*I, true, MK_Any, SelIdents, NumSelIdents, CurContext,
  3092. Results);
  3093. }
  3094. // Handle messages to "id".
  3095. else if (ReceiverType->isObjCIdType()) {
  3096. // We're messaging "id", so provide all instance methods we know
  3097. // about as code-completion results.
  3098. // If we have an external source, load the entire class method
  3099. // pool from the PCH file.
  3100. if (ExternalSource) {
  3101. for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
  3102. I != N; ++I) {
  3103. Selector Sel = ExternalSource->GetExternalSelector(I);
  3104. if (Sel.isNull() || MethodPool.count(Sel))
  3105. continue;
  3106. ReadMethodPool(Sel);
  3107. }
  3108. }
  3109. for (GlobalMethodPool::iterator M = MethodPool.begin(),
  3110. MEnd = MethodPool.end();
  3111. M != MEnd; ++M) {
  3112. for (ObjCMethodList *MethList = &M->second.first;
  3113. MethList && MethList->Method;
  3114. MethList = MethList->Next) {
  3115. if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
  3116. NumSelIdents))
  3117. continue;
  3118. Result R(MethList->Method, 0);
  3119. R.StartParameter = NumSelIdents;
  3120. R.AllParametersAreInformative = false;
  3121. Results.MaybeAddResult(R, CurContext);
  3122. }
  3123. }
  3124. }
  3125. Results.ExitScope();
  3126. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  3127. }
  3128. /// \brief Add all of the protocol declarations that we find in the given
  3129. /// (translation unit) context.
  3130. static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
  3131. bool OnlyForwardDeclarations,
  3132. ResultBuilder &Results) {
  3133. typedef CodeCompleteConsumer::Result Result;
  3134. for (DeclContext::decl_iterator D = Ctx->decls_begin(),
  3135. DEnd = Ctx->decls_end();
  3136. D != DEnd; ++D) {
  3137. // Record any protocols we find.
  3138. if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*D))
  3139. if (!OnlyForwardDeclarations || Proto->isForwardDecl())
  3140. Results.AddResult(Result(Proto, 0), CurContext, 0, false);
  3141. // Record any forward-declared protocols we find.
  3142. if (ObjCForwardProtocolDecl *Forward
  3143. = dyn_cast<ObjCForwardProtocolDecl>(*D)) {
  3144. for (ObjCForwardProtocolDecl::protocol_iterator
  3145. P = Forward->protocol_begin(),
  3146. PEnd = Forward->protocol_end();
  3147. P != PEnd; ++P)
  3148. if (!OnlyForwardDeclarations || (*P)->isForwardDecl())
  3149. Results.AddResult(Result(*P, 0), CurContext, 0, false);
  3150. }
  3151. }
  3152. }
  3153. void Sema::CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols,
  3154. unsigned NumProtocols) {
  3155. ResultBuilder Results(*this);
  3156. Results.EnterNewScope();
  3157. // Tell the result set to ignore all of the protocols we have
  3158. // already seen.
  3159. for (unsigned I = 0; I != NumProtocols; ++I)
  3160. if (ObjCProtocolDecl *Protocol = LookupProtocol(Protocols[I].first,
  3161. Protocols[I].second))
  3162. Results.Ignore(Protocol);
  3163. // Add all protocols.
  3164. AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
  3165. Results);
  3166. Results.ExitScope();
  3167. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  3168. }
  3169. void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
  3170. ResultBuilder Results(*this);
  3171. Results.EnterNewScope();
  3172. // Add all protocols.
  3173. AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
  3174. Results);
  3175. Results.ExitScope();
  3176. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  3177. }
  3178. /// \brief Add all of the Objective-C interface declarations that we find in
  3179. /// the given (translation unit) context.
  3180. static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
  3181. bool OnlyForwardDeclarations,
  3182. bool OnlyUnimplemented,
  3183. ResultBuilder &Results) {
  3184. typedef CodeCompleteConsumer::Result Result;
  3185. for (DeclContext::decl_iterator D = Ctx->decls_begin(),
  3186. DEnd = Ctx->decls_end();
  3187. D != DEnd; ++D) {
  3188. // Record any interfaces we find.
  3189. if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*D))
  3190. if ((!OnlyForwardDeclarations || Class->isForwardDecl()) &&
  3191. (!OnlyUnimplemented || !Class->getImplementation()))
  3192. Results.AddResult(Result(Class, 0), CurContext, 0, false);
  3193. // Record any forward-declared interfaces we find.
  3194. if (ObjCClassDecl *Forward = dyn_cast<ObjCClassDecl>(*D)) {
  3195. for (ObjCClassDecl::iterator C = Forward->begin(), CEnd = Forward->end();
  3196. C != CEnd; ++C)
  3197. if ((!OnlyForwardDeclarations || C->getInterface()->isForwardDecl()) &&
  3198. (!OnlyUnimplemented || !C->getInterface()->getImplementation()))
  3199. Results.AddResult(Result(C->getInterface(), 0), CurContext,
  3200. 0, false);
  3201. }
  3202. }
  3203. }
  3204. void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
  3205. ResultBuilder Results(*this);
  3206. Results.EnterNewScope();
  3207. // Add all classes.
  3208. AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, true,
  3209. false, Results);
  3210. Results.ExitScope();
  3211. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  3212. }
  3213. void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
  3214. SourceLocation ClassNameLoc) {
  3215. ResultBuilder Results(*this);
  3216. Results.EnterNewScope();
  3217. // Make sure that we ignore the class we're currently defining.
  3218. NamedDecl *CurClass
  3219. = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
  3220. if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
  3221. Results.Ignore(CurClass);
  3222. // Add all classes.
  3223. AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
  3224. false, Results);
  3225. Results.ExitScope();
  3226. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  3227. }
  3228. void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
  3229. ResultBuilder Results(*this);
  3230. Results.EnterNewScope();
  3231. // Add all unimplemented classes.
  3232. AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
  3233. true, Results);
  3234. Results.ExitScope();
  3235. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  3236. }
  3237. void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
  3238. IdentifierInfo *ClassName,
  3239. SourceLocation ClassNameLoc) {
  3240. typedef CodeCompleteConsumer::Result Result;
  3241. ResultBuilder Results(*this);
  3242. // Ignore any categories we find that have already been implemented by this
  3243. // interface.
  3244. llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
  3245. NamedDecl *CurClass
  3246. = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
  3247. if (ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass))
  3248. for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
  3249. Category = Category->getNextClassCategory())
  3250. CategoryNames.insert(Category->getIdentifier());
  3251. // Add all of the categories we know about.
  3252. Results.EnterNewScope();
  3253. TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
  3254. for (DeclContext::decl_iterator D = TU->decls_begin(),
  3255. DEnd = TU->decls_end();
  3256. D != DEnd; ++D)
  3257. if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(*D))
  3258. if (CategoryNames.insert(Category->getIdentifier()))
  3259. Results.AddResult(Result(Category, 0), CurContext, 0, false);
  3260. Results.ExitScope();
  3261. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  3262. }
  3263. void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
  3264. IdentifierInfo *ClassName,
  3265. SourceLocation ClassNameLoc) {
  3266. typedef CodeCompleteConsumer::Result Result;
  3267. // Find the corresponding interface. If we couldn't find the interface, the
  3268. // program itself is ill-formed. However, we'll try to be helpful still by
  3269. // providing the list of all of the categories we know about.
  3270. NamedDecl *CurClass
  3271. = LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
  3272. ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
  3273. if (!Class)
  3274. return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
  3275. ResultBuilder Results(*this);
  3276. // Add all of the categories that have have corresponding interface
  3277. // declarations in this class and any of its superclasses, except for
  3278. // already-implemented categories in the class itself.
  3279. llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
  3280. Results.EnterNewScope();
  3281. bool IgnoreImplemented = true;
  3282. while (Class) {
  3283. for (ObjCCategoryDecl *Category = Class->getCategoryList(); Category;
  3284. Category = Category->getNextClassCategory())
  3285. if ((!IgnoreImplemented || !Category->getImplementation()) &&
  3286. CategoryNames.insert(Category->getIdentifier()))
  3287. Results.AddResult(Result(Category, 0), CurContext, 0, false);
  3288. Class = Class->getSuperClass();
  3289. IgnoreImplemented = false;
  3290. }
  3291. Results.ExitScope();
  3292. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  3293. }
  3294. void Sema::CodeCompleteObjCPropertyDefinition(Scope *S, DeclPtrTy ObjCImpDecl) {
  3295. typedef CodeCompleteConsumer::Result Result;
  3296. ResultBuilder Results(*this);
  3297. // Figure out where this @synthesize lives.
  3298. ObjCContainerDecl *Container
  3299. = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
  3300. if (!Container ||
  3301. (!isa<ObjCImplementationDecl>(Container) &&
  3302. !isa<ObjCCategoryImplDecl>(Container)))
  3303. return;
  3304. // Ignore any properties that have already been implemented.
  3305. for (DeclContext::decl_iterator D = Container->decls_begin(),
  3306. DEnd = Container->decls_end();
  3307. D != DEnd; ++D)
  3308. if (ObjCPropertyImplDecl *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(*D))
  3309. Results.Ignore(PropertyImpl->getPropertyDecl());
  3310. // Add any properties that we find.
  3311. Results.EnterNewScope();
  3312. if (ObjCImplementationDecl *ClassImpl
  3313. = dyn_cast<ObjCImplementationDecl>(Container))
  3314. AddObjCProperties(ClassImpl->getClassInterface(), false, CurContext,
  3315. Results);
  3316. else
  3317. AddObjCProperties(cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
  3318. false, CurContext, Results);
  3319. Results.ExitScope();
  3320. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  3321. }
  3322. void Sema::CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
  3323. IdentifierInfo *PropertyName,
  3324. DeclPtrTy ObjCImpDecl) {
  3325. typedef CodeCompleteConsumer::Result Result;
  3326. ResultBuilder Results(*this);
  3327. // Figure out where this @synthesize lives.
  3328. ObjCContainerDecl *Container
  3329. = dyn_cast_or_null<ObjCContainerDecl>(ObjCImpDecl.getAs<Decl>());
  3330. if (!Container ||
  3331. (!isa<ObjCImplementationDecl>(Container) &&
  3332. !isa<ObjCCategoryImplDecl>(Container)))
  3333. return;
  3334. // Figure out which interface we're looking into.
  3335. ObjCInterfaceDecl *Class = 0;
  3336. if (ObjCImplementationDecl *ClassImpl
  3337. = dyn_cast<ObjCImplementationDecl>(Container))
  3338. Class = ClassImpl->getClassInterface();
  3339. else
  3340. Class = cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl()
  3341. ->getClassInterface();
  3342. // Add all of the instance variables in this class and its superclasses.
  3343. Results.EnterNewScope();
  3344. for(; Class; Class = Class->getSuperClass()) {
  3345. // FIXME: We could screen the type of each ivar for compatibility with
  3346. // the property, but is that being too paternal?
  3347. for (ObjCInterfaceDecl::ivar_iterator IVar = Class->ivar_begin(),
  3348. IVarEnd = Class->ivar_end();
  3349. IVar != IVarEnd; ++IVar)
  3350. Results.AddResult(Result(*IVar, 0), CurContext, 0, false);
  3351. }
  3352. Results.ExitScope();
  3353. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  3354. }
  3355. typedef llvm::DenseMap<Selector, ObjCMethodDecl *> KnownMethodsMap;
  3356. /// \brief Find all of the methods that reside in the given container
  3357. /// (and its superclasses, protocols, etc.) that meet the given
  3358. /// criteria. Insert those methods into the map of known methods,
  3359. /// indexed by selector so they can be easily found.
  3360. static void FindImplementableMethods(ASTContext &Context,
  3361. ObjCContainerDecl *Container,
  3362. bool WantInstanceMethods,
  3363. QualType ReturnType,
  3364. bool IsInImplementation,
  3365. KnownMethodsMap &KnownMethods) {
  3366. if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
  3367. // Recurse into protocols.
  3368. const ObjCList<ObjCProtocolDecl> &Protocols
  3369. = IFace->getReferencedProtocols();
  3370. for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
  3371. E = Protocols.end();
  3372. I != E; ++I)
  3373. FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
  3374. IsInImplementation, KnownMethods);
  3375. // If we're not in the implementation of a class, also visit the
  3376. // superclass.
  3377. if (!IsInImplementation && IFace->getSuperClass())
  3378. FindImplementableMethods(Context, IFace->getSuperClass(),
  3379. WantInstanceMethods, ReturnType,
  3380. IsInImplementation, KnownMethods);
  3381. // Add methods from any class extensions (but not from categories;
  3382. // those should go into category implementations).
  3383. for (const ObjCCategoryDecl *Cat = IFace->getFirstClassExtension(); Cat;
  3384. Cat = Cat->getNextClassExtension())
  3385. FindImplementableMethods(Context, const_cast<ObjCCategoryDecl*>(Cat),
  3386. WantInstanceMethods, ReturnType,
  3387. IsInImplementation, KnownMethods);
  3388. }
  3389. if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
  3390. // Recurse into protocols.
  3391. const ObjCList<ObjCProtocolDecl> &Protocols
  3392. = Category->getReferencedProtocols();
  3393. for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
  3394. E = Protocols.end();
  3395. I != E; ++I)
  3396. FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
  3397. IsInImplementation, KnownMethods);
  3398. }
  3399. if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
  3400. // Recurse into protocols.
  3401. const ObjCList<ObjCProtocolDecl> &Protocols
  3402. = Protocol->getReferencedProtocols();
  3403. for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
  3404. E = Protocols.end();
  3405. I != E; ++I)
  3406. FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
  3407. IsInImplementation, KnownMethods);
  3408. }
  3409. // Add methods in this container. This operation occurs last because
  3410. // we want the methods from this container to override any methods
  3411. // we've previously seen with the same selector.
  3412. for (ObjCContainerDecl::method_iterator M = Container->meth_begin(),
  3413. MEnd = Container->meth_end();
  3414. M != MEnd; ++M) {
  3415. if ((*M)->isInstanceMethod() == WantInstanceMethods) {
  3416. if (!ReturnType.isNull() &&
  3417. !Context.hasSameUnqualifiedType(ReturnType, (*M)->getResultType()))
  3418. continue;
  3419. KnownMethods[(*M)->getSelector()] = *M;
  3420. }
  3421. }
  3422. }
  3423. void Sema::CodeCompleteObjCMethodDecl(Scope *S,
  3424. bool IsInstanceMethod,
  3425. TypeTy *ReturnTy,
  3426. DeclPtrTy IDecl) {
  3427. // Determine the return type of the method we're declaring, if
  3428. // provided.
  3429. QualType ReturnType = GetTypeFromParser(ReturnTy);
  3430. // Determine where we should start searching for methods, and where we
  3431. ObjCContainerDecl *SearchDecl = 0, *CurrentDecl = 0;
  3432. bool IsInImplementation = false;
  3433. if (Decl *D = IDecl.getAs<Decl>()) {
  3434. if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
  3435. SearchDecl = Impl->getClassInterface();
  3436. CurrentDecl = Impl;
  3437. IsInImplementation = true;
  3438. } else if (ObjCCategoryImplDecl *CatImpl
  3439. = dyn_cast<ObjCCategoryImplDecl>(D)) {
  3440. SearchDecl = CatImpl->getCategoryDecl();
  3441. CurrentDecl = CatImpl;
  3442. IsInImplementation = true;
  3443. } else {
  3444. SearchDecl = dyn_cast<ObjCContainerDecl>(D);
  3445. CurrentDecl = SearchDecl;
  3446. }
  3447. }
  3448. if (!SearchDecl && S) {
  3449. if (DeclContext *DC = static_cast<DeclContext *>(S->getEntity())) {
  3450. SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
  3451. CurrentDecl = SearchDecl;
  3452. }
  3453. }
  3454. if (!SearchDecl || !CurrentDecl) {
  3455. HandleCodeCompleteResults(this, CodeCompleter, 0, 0);
  3456. return;
  3457. }
  3458. // Find all of the methods that we could declare/implement here.
  3459. KnownMethodsMap KnownMethods;
  3460. FindImplementableMethods(Context, SearchDecl, IsInstanceMethod,
  3461. ReturnType, IsInImplementation, KnownMethods);
  3462. // Erase any methods that have already been declared or
  3463. // implemented here.
  3464. for (ObjCContainerDecl::method_iterator M = CurrentDecl->meth_begin(),
  3465. MEnd = CurrentDecl->meth_end();
  3466. M != MEnd; ++M) {
  3467. if ((*M)->isInstanceMethod() != IsInstanceMethod)
  3468. continue;
  3469. KnownMethodsMap::iterator Pos = KnownMethods.find((*M)->getSelector());
  3470. if (Pos != KnownMethods.end())
  3471. KnownMethods.erase(Pos);
  3472. }
  3473. // Add declarations or definitions for each of the known methods.
  3474. typedef CodeCompleteConsumer::Result Result;
  3475. ResultBuilder Results(*this);
  3476. Results.EnterNewScope();
  3477. PrintingPolicy Policy(Context.PrintingPolicy);
  3478. Policy.AnonymousTagLocations = false;
  3479. for (KnownMethodsMap::iterator M = KnownMethods.begin(),
  3480. MEnd = KnownMethods.end();
  3481. M != MEnd; ++M) {
  3482. ObjCMethodDecl *Method = M->second;
  3483. CodeCompletionString *Pattern = new CodeCompletionString;
  3484. // If the result type was not already provided, add it to the
  3485. // pattern as (type).
  3486. if (ReturnType.isNull()) {
  3487. std::string TypeStr;
  3488. Method->getResultType().getAsStringInternal(TypeStr, Policy);
  3489. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  3490. Pattern->AddTextChunk(TypeStr);
  3491. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  3492. }
  3493. Selector Sel = Method->getSelector();
  3494. // Add the first part of the selector to the pattern.
  3495. Pattern->AddTypedTextChunk(Sel.getIdentifierInfoForSlot(0)->getName());
  3496. // Add parameters to the pattern.
  3497. unsigned I = 0;
  3498. for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
  3499. PEnd = Method->param_end();
  3500. P != PEnd; (void)++P, ++I) {
  3501. // Add the part of the selector name.
  3502. if (I == 0)
  3503. Pattern->AddChunk(CodeCompletionString::CK_Colon);
  3504. else if (I < Sel.getNumArgs()) {
  3505. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  3506. Pattern->AddTextChunk(Sel.getIdentifierInfoForSlot(1)->getName());
  3507. Pattern->AddChunk(CodeCompletionString::CK_Colon);
  3508. } else
  3509. break;
  3510. // Add the parameter type.
  3511. std::string TypeStr;
  3512. (*P)->getOriginalType().getAsStringInternal(TypeStr, Policy);
  3513. Pattern->AddChunk(CodeCompletionString::CK_LeftParen);
  3514. Pattern->AddTextChunk(TypeStr);
  3515. Pattern->AddChunk(CodeCompletionString::CK_RightParen);
  3516. if (IdentifierInfo *Id = (*P)->getIdentifier())
  3517. Pattern->AddTextChunk(Id->getName());
  3518. }
  3519. if (Method->isVariadic()) {
  3520. if (Method->param_size() > 0)
  3521. Pattern->AddChunk(CodeCompletionString::CK_Comma);
  3522. Pattern->AddTextChunk("...");
  3523. }
  3524. if (IsInImplementation && Results.includeCodePatterns()) {
  3525. // We will be defining the method here, so add a compound statement.
  3526. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  3527. Pattern->AddChunk(CodeCompletionString::CK_LeftBrace);
  3528. Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
  3529. if (!Method->getResultType()->isVoidType()) {
  3530. // If the result type is not void, add a return clause.
  3531. Pattern->AddTextChunk("return");
  3532. Pattern->AddChunk(CodeCompletionString::CK_HorizontalSpace);
  3533. Pattern->AddPlaceholderChunk("expression");
  3534. Pattern->AddChunk(CodeCompletionString::CK_SemiColon);
  3535. } else
  3536. Pattern->AddPlaceholderChunk("statements");
  3537. Pattern->AddChunk(CodeCompletionString::CK_VerticalSpace);
  3538. Pattern->AddChunk(CodeCompletionString::CK_RightBrace);
  3539. }
  3540. Results.AddResult(Result(Pattern));
  3541. }
  3542. Results.ExitScope();
  3543. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  3544. }
  3545. void Sema::CodeCompleteObjCMethodDeclSelector(Scope *S,
  3546. bool IsInstanceMethod,
  3547. bool AtParameterName,
  3548. TypeTy *ReturnTy,
  3549. IdentifierInfo **SelIdents,
  3550. unsigned NumSelIdents) {
  3551. // If we have an external source, load the entire class method
  3552. // pool from the PCH file.
  3553. if (ExternalSource) {
  3554. for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
  3555. I != N; ++I) {
  3556. Selector Sel = ExternalSource->GetExternalSelector(I);
  3557. if (Sel.isNull() || MethodPool.count(Sel))
  3558. continue;
  3559. ReadMethodPool(Sel);
  3560. }
  3561. }
  3562. // Build the set of methods we can see.
  3563. typedef CodeCompleteConsumer::Result Result;
  3564. ResultBuilder Results(*this);
  3565. if (ReturnTy)
  3566. Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
  3567. Results.EnterNewScope();
  3568. for (GlobalMethodPool::iterator M = MethodPool.begin(),
  3569. MEnd = MethodPool.end();
  3570. M != MEnd; ++M) {
  3571. for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first :
  3572. &M->second.second;
  3573. MethList && MethList->Method;
  3574. MethList = MethList->Next) {
  3575. if (!isAcceptableObjCMethod(MethList->Method, MK_Any, SelIdents,
  3576. NumSelIdents))
  3577. continue;
  3578. if (AtParameterName) {
  3579. // Suggest parameter names we've seen before.
  3580. if (NumSelIdents && NumSelIdents <= MethList->Method->param_size()) {
  3581. ParmVarDecl *Param = MethList->Method->param_begin()[NumSelIdents-1];
  3582. if (Param->getIdentifier()) {
  3583. CodeCompletionString *Pattern = new CodeCompletionString;
  3584. Pattern->AddTypedTextChunk(Param->getIdentifier()->getName());
  3585. Results.AddResult(Pattern);
  3586. }
  3587. }
  3588. continue;
  3589. }
  3590. Result R(MethList->Method, 0);
  3591. R.StartParameter = NumSelIdents;
  3592. R.AllParametersAreInformative = false;
  3593. R.DeclaringEntity = true;
  3594. Results.MaybeAddResult(R, CurContext);
  3595. }
  3596. }
  3597. Results.ExitScope();
  3598. HandleCodeCompleteResults(this, CodeCompleter, Results.data(),Results.size());
  3599. }