SemaLookup.cpp 168 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568
  1. //===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
  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 implements name lookup for C, C++, Objective-C, and
  11. // Objective-C++.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Sema/Lookup.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/CXXInheritance.h"
  17. #include "clang/AST/Decl.h"
  18. #include "clang/AST/DeclCXX.h"
  19. #include "clang/AST/DeclLookups.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclTemplate.h"
  22. #include "clang/AST/Expr.h"
  23. #include "clang/AST/ExprCXX.h"
  24. #include "clang/Basic/Builtins.h"
  25. #include "clang/Basic/LangOptions.h"
  26. #include "clang/Lex/ModuleLoader.h"
  27. #include "clang/Sema/DeclSpec.h"
  28. #include "clang/Sema/ExternalSemaSource.h"
  29. #include "clang/Sema/Overload.h"
  30. #include "clang/Sema/Scope.h"
  31. #include "clang/Sema/ScopeInfo.h"
  32. #include "clang/Sema/Sema.h"
  33. #include "clang/Sema/SemaInternal.h"
  34. #include "clang/Sema/TemplateDeduction.h"
  35. #include "clang/Sema/TypoCorrection.h"
  36. #include "llvm/ADT/STLExtras.h"
  37. #include "llvm/ADT/SetVector.h"
  38. #include "llvm/ADT/SmallPtrSet.h"
  39. #include "llvm/ADT/StringMap.h"
  40. #include "llvm/ADT/TinyPtrVector.h"
  41. #include "llvm/ADT/edit_distance.h"
  42. #include "llvm/Support/ErrorHandling.h"
  43. #include <algorithm>
  44. #include <iterator>
  45. #include <limits>
  46. #include <list>
  47. #include <map>
  48. #include <set>
  49. #include <utility>
  50. #include <vector>
  51. using namespace clang;
  52. using namespace sema;
  53. namespace {
  54. class UnqualUsingEntry {
  55. const DeclContext *Nominated;
  56. const DeclContext *CommonAncestor;
  57. public:
  58. UnqualUsingEntry(const DeclContext *Nominated,
  59. const DeclContext *CommonAncestor)
  60. : Nominated(Nominated), CommonAncestor(CommonAncestor) {
  61. }
  62. const DeclContext *getCommonAncestor() const {
  63. return CommonAncestor;
  64. }
  65. const DeclContext *getNominatedNamespace() const {
  66. return Nominated;
  67. }
  68. // Sort by the pointer value of the common ancestor.
  69. struct Comparator {
  70. bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
  71. return L.getCommonAncestor() < R.getCommonAncestor();
  72. }
  73. bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
  74. return E.getCommonAncestor() < DC;
  75. }
  76. bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
  77. return DC < E.getCommonAncestor();
  78. }
  79. };
  80. };
  81. /// A collection of using directives, as used by C++ unqualified
  82. /// lookup.
  83. class UnqualUsingDirectiveSet {
  84. typedef SmallVector<UnqualUsingEntry, 8> ListTy;
  85. ListTy list;
  86. llvm::SmallPtrSet<DeclContext*, 8> visited;
  87. public:
  88. UnqualUsingDirectiveSet() {}
  89. void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
  90. // C++ [namespace.udir]p1:
  91. // During unqualified name lookup, the names appear as if they
  92. // were declared in the nearest enclosing namespace which contains
  93. // both the using-directive and the nominated namespace.
  94. DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
  95. assert(InnermostFileDC && InnermostFileDC->isFileContext());
  96. for (; S; S = S->getParent()) {
  97. // C++ [namespace.udir]p1:
  98. // A using-directive shall not appear in class scope, but may
  99. // appear in namespace scope or in block scope.
  100. DeclContext *Ctx = S->getEntity();
  101. if (Ctx && Ctx->isFileContext()) {
  102. visit(Ctx, Ctx);
  103. } else if (!Ctx || Ctx->isFunctionOrMethod()) {
  104. for (auto *I : S->using_directives())
  105. visit(I, InnermostFileDC);
  106. }
  107. }
  108. }
  109. // Visits a context and collect all of its using directives
  110. // recursively. Treats all using directives as if they were
  111. // declared in the context.
  112. //
  113. // A given context is only every visited once, so it is important
  114. // that contexts be visited from the inside out in order to get
  115. // the effective DCs right.
  116. void visit(DeclContext *DC, DeclContext *EffectiveDC) {
  117. if (!visited.insert(DC).second)
  118. return;
  119. addUsingDirectives(DC, EffectiveDC);
  120. }
  121. // Visits a using directive and collects all of its using
  122. // directives recursively. Treats all using directives as if they
  123. // were declared in the effective DC.
  124. void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
  125. DeclContext *NS = UD->getNominatedNamespace();
  126. if (!visited.insert(NS).second)
  127. return;
  128. addUsingDirective(UD, EffectiveDC);
  129. addUsingDirectives(NS, EffectiveDC);
  130. }
  131. // Adds all the using directives in a context (and those nominated
  132. // by its using directives, transitively) as if they appeared in
  133. // the given effective context.
  134. void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
  135. SmallVector<DeclContext*,4> queue;
  136. while (true) {
  137. for (auto UD : DC->using_directives()) {
  138. DeclContext *NS = UD->getNominatedNamespace();
  139. if (visited.insert(NS).second) {
  140. addUsingDirective(UD, EffectiveDC);
  141. queue.push_back(NS);
  142. }
  143. }
  144. if (queue.empty())
  145. return;
  146. DC = queue.pop_back_val();
  147. }
  148. }
  149. // Add a using directive as if it had been declared in the given
  150. // context. This helps implement C++ [namespace.udir]p3:
  151. // The using-directive is transitive: if a scope contains a
  152. // using-directive that nominates a second namespace that itself
  153. // contains using-directives, the effect is as if the
  154. // using-directives from the second namespace also appeared in
  155. // the first.
  156. void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
  157. // Find the common ancestor between the effective context and
  158. // the nominated namespace.
  159. DeclContext *Common = UD->getNominatedNamespace();
  160. while (!Common->Encloses(EffectiveDC))
  161. Common = Common->getParent();
  162. Common = Common->getPrimaryContext();
  163. list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
  164. }
  165. void done() {
  166. std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
  167. }
  168. typedef ListTy::const_iterator const_iterator;
  169. const_iterator begin() const { return list.begin(); }
  170. const_iterator end() const { return list.end(); }
  171. llvm::iterator_range<const_iterator>
  172. getNamespacesFor(DeclContext *DC) const {
  173. return llvm::make_range(std::equal_range(begin(), end(),
  174. DC->getPrimaryContext(),
  175. UnqualUsingEntry::Comparator()));
  176. }
  177. };
  178. }
  179. // Retrieve the set of identifier namespaces that correspond to a
  180. // specific kind of name lookup.
  181. static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
  182. bool CPlusPlus,
  183. bool Redeclaration) {
  184. unsigned IDNS = 0;
  185. switch (NameKind) {
  186. case Sema::LookupObjCImplicitSelfParam:
  187. case Sema::LookupOrdinaryName:
  188. case Sema::LookupRedeclarationWithLinkage:
  189. case Sema::LookupLocalFriendName:
  190. IDNS = Decl::IDNS_Ordinary;
  191. if (CPlusPlus) {
  192. IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
  193. if (Redeclaration)
  194. IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
  195. }
  196. if (Redeclaration)
  197. IDNS |= Decl::IDNS_LocalExtern;
  198. break;
  199. case Sema::LookupOperatorName:
  200. // Operator lookup is its own crazy thing; it is not the same
  201. // as (e.g.) looking up an operator name for redeclaration.
  202. assert(!Redeclaration && "cannot do redeclaration operator lookup");
  203. IDNS = Decl::IDNS_NonMemberOperator;
  204. break;
  205. case Sema::LookupTagName:
  206. if (CPlusPlus) {
  207. IDNS = Decl::IDNS_Type;
  208. // When looking for a redeclaration of a tag name, we add:
  209. // 1) TagFriend to find undeclared friend decls
  210. // 2) Namespace because they can't "overload" with tag decls.
  211. // 3) Tag because it includes class templates, which can't
  212. // "overload" with tag decls.
  213. if (Redeclaration)
  214. IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
  215. } else {
  216. IDNS = Decl::IDNS_Tag;
  217. }
  218. break;
  219. case Sema::LookupLabel:
  220. IDNS = Decl::IDNS_Label;
  221. break;
  222. case Sema::LookupMemberName:
  223. IDNS = Decl::IDNS_Member;
  224. if (CPlusPlus)
  225. IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
  226. break;
  227. case Sema::LookupNestedNameSpecifierName:
  228. IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
  229. break;
  230. case Sema::LookupNamespaceName:
  231. IDNS = Decl::IDNS_Namespace;
  232. break;
  233. case Sema::LookupUsingDeclName:
  234. assert(Redeclaration && "should only be used for redecl lookup");
  235. IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
  236. Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
  237. Decl::IDNS_LocalExtern;
  238. break;
  239. case Sema::LookupObjCProtocolName:
  240. IDNS = Decl::IDNS_ObjCProtocol;
  241. break;
  242. case Sema::LookupAnyName:
  243. IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
  244. | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
  245. | Decl::IDNS_Type;
  246. break;
  247. }
  248. return IDNS;
  249. }
  250. void LookupResult::configure() {
  251. IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
  252. isForRedeclaration());
  253. // If we're looking for one of the allocation or deallocation
  254. // operators, make sure that the implicitly-declared new and delete
  255. // operators can be found.
  256. switch (NameInfo.getName().getCXXOverloadedOperator()) {
  257. case OO_New:
  258. case OO_Delete:
  259. case OO_Array_New:
  260. case OO_Array_Delete:
  261. getSema().DeclareGlobalNewDelete();
  262. break;
  263. default:
  264. break;
  265. }
  266. // Compiler builtins are always visible, regardless of where they end
  267. // up being declared.
  268. if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
  269. if (unsigned BuiltinID = Id->getBuiltinID()) {
  270. if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
  271. AllowHidden = true;
  272. }
  273. }
  274. }
  275. bool LookupResult::sanity() const {
  276. // This function is never called by NDEBUG builds.
  277. assert(ResultKind != NotFound || Decls.size() == 0);
  278. assert(ResultKind != Found || Decls.size() == 1);
  279. assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
  280. (Decls.size() == 1 &&
  281. isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
  282. assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
  283. assert(ResultKind != Ambiguous || Decls.size() > 1 ||
  284. (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
  285. Ambiguity == AmbiguousBaseSubobjectTypes)));
  286. assert((Paths != nullptr) == (ResultKind == Ambiguous &&
  287. (Ambiguity == AmbiguousBaseSubobjectTypes ||
  288. Ambiguity == AmbiguousBaseSubobjects)));
  289. return true;
  290. }
  291. // Necessary because CXXBasePaths is not complete in Sema.h
  292. void LookupResult::deletePaths(CXXBasePaths *Paths) {
  293. delete Paths;
  294. }
  295. /// Get a representative context for a declaration such that two declarations
  296. /// will have the same context if they were found within the same scope.
  297. static DeclContext *getContextForScopeMatching(Decl *D) {
  298. // For function-local declarations, use that function as the context. This
  299. // doesn't account for scopes within the function; the caller must deal with
  300. // those.
  301. DeclContext *DC = D->getLexicalDeclContext();
  302. if (DC->isFunctionOrMethod())
  303. return DC;
  304. // Otherwise, look at the semantic context of the declaration. The
  305. // declaration must have been found there.
  306. return D->getDeclContext()->getRedeclContext();
  307. }
  308. /// Resolves the result kind of this lookup.
  309. void LookupResult::resolveKind() {
  310. unsigned N = Decls.size();
  311. // Fast case: no possible ambiguity.
  312. if (N == 0) {
  313. assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation);
  314. return;
  315. }
  316. // If there's a single decl, we need to examine it to decide what
  317. // kind of lookup this is.
  318. if (N == 1) {
  319. NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
  320. if (isa<FunctionTemplateDecl>(D))
  321. ResultKind = FoundOverloaded;
  322. else if (isa<UnresolvedUsingValueDecl>(D))
  323. ResultKind = FoundUnresolvedValue;
  324. return;
  325. }
  326. // Don't do any extra resolution if we've already resolved as ambiguous.
  327. if (ResultKind == Ambiguous) return;
  328. llvm::SmallPtrSet<NamedDecl*, 16> Unique;
  329. llvm::SmallPtrSet<QualType, 16> UniqueTypes;
  330. bool Ambiguous = false;
  331. bool HasTag = false, HasFunction = false, HasNonFunction = false;
  332. bool HasFunctionTemplate = false, HasUnresolved = false;
  333. unsigned UniqueTagIndex = 0;
  334. unsigned I = 0;
  335. while (I < N) {
  336. NamedDecl *D = Decls[I]->getUnderlyingDecl();
  337. D = cast<NamedDecl>(D->getCanonicalDecl());
  338. // Ignore an invalid declaration unless it's the only one left.
  339. if (D->isInvalidDecl() && I < N-1) {
  340. Decls[I] = Decls[--N];
  341. continue;
  342. }
  343. // Redeclarations of types via typedef can occur both within a scope
  344. // and, through using declarations and directives, across scopes. There is
  345. // no ambiguity if they all refer to the same type, so unique based on the
  346. // canonical type.
  347. if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
  348. if (!TD->getDeclContext()->isRecord()) {
  349. QualType T = getSema().Context.getTypeDeclType(TD);
  350. if (!UniqueTypes.insert(getSema().Context.getCanonicalType(T)).second) {
  351. // The type is not unique; pull something off the back and continue
  352. // at this index.
  353. Decls[I] = Decls[--N];
  354. continue;
  355. }
  356. }
  357. }
  358. if (!Unique.insert(D).second) {
  359. // If it's not unique, pull something off the back (and
  360. // continue at this index).
  361. // FIXME: This is wrong. We need to take the more recent declaration in
  362. // order to get the right type, default arguments, etc. We also need to
  363. // prefer visible declarations to hidden ones (for redeclaration lookup
  364. // in modules builds).
  365. Decls[I] = Decls[--N];
  366. continue;
  367. }
  368. // Otherwise, do some decl type analysis and then continue.
  369. if (isa<UnresolvedUsingValueDecl>(D)) {
  370. HasUnresolved = true;
  371. } else if (isa<TagDecl>(D)) {
  372. if (HasTag)
  373. Ambiguous = true;
  374. UniqueTagIndex = I;
  375. HasTag = true;
  376. } else if (isa<FunctionTemplateDecl>(D)) {
  377. HasFunction = true;
  378. HasFunctionTemplate = true;
  379. } else if (isa<FunctionDecl>(D)) {
  380. HasFunction = true;
  381. } else {
  382. if (HasNonFunction)
  383. Ambiguous = true;
  384. HasNonFunction = true;
  385. }
  386. I++;
  387. }
  388. // C++ [basic.scope.hiding]p2:
  389. // A class name or enumeration name can be hidden by the name of
  390. // an object, function, or enumerator declared in the same
  391. // scope. If a class or enumeration name and an object, function,
  392. // or enumerator are declared in the same scope (in any order)
  393. // with the same name, the class or enumeration name is hidden
  394. // wherever the object, function, or enumerator name is visible.
  395. // But it's still an error if there are distinct tag types found,
  396. // even if they're not visible. (ref?)
  397. if (HideTags && HasTag && !Ambiguous &&
  398. (HasFunction || HasNonFunction || HasUnresolved)) {
  399. if (getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
  400. getContextForScopeMatching(Decls[UniqueTagIndex ? 0 : N - 1])))
  401. Decls[UniqueTagIndex] = Decls[--N];
  402. else
  403. Ambiguous = true;
  404. }
  405. Decls.set_size(N);
  406. if (HasNonFunction && (HasFunction || HasUnresolved))
  407. Ambiguous = true;
  408. if (Ambiguous)
  409. setAmbiguous(LookupResult::AmbiguousReference);
  410. else if (HasUnresolved)
  411. ResultKind = LookupResult::FoundUnresolvedValue;
  412. else if (N > 1 || HasFunctionTemplate)
  413. ResultKind = LookupResult::FoundOverloaded;
  414. else
  415. ResultKind = LookupResult::Found;
  416. }
  417. void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
  418. CXXBasePaths::const_paths_iterator I, E;
  419. for (I = P.begin(), E = P.end(); I != E; ++I)
  420. for (DeclContext::lookup_iterator DI = I->Decls.begin(),
  421. DE = I->Decls.end(); DI != DE; ++DI)
  422. addDecl(*DI);
  423. }
  424. void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
  425. Paths = new CXXBasePaths;
  426. Paths->swap(P);
  427. addDeclsFromBasePaths(*Paths);
  428. resolveKind();
  429. setAmbiguous(AmbiguousBaseSubobjects);
  430. }
  431. void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
  432. Paths = new CXXBasePaths;
  433. Paths->swap(P);
  434. addDeclsFromBasePaths(*Paths);
  435. resolveKind();
  436. setAmbiguous(AmbiguousBaseSubobjectTypes);
  437. }
  438. void LookupResult::print(raw_ostream &Out) {
  439. Out << Decls.size() << " result(s)";
  440. if (isAmbiguous()) Out << ", ambiguous";
  441. if (Paths) Out << ", base paths present";
  442. for (iterator I = begin(), E = end(); I != E; ++I) {
  443. Out << "\n";
  444. (*I)->print(Out, 2);
  445. }
  446. }
  447. /// \brief Lookup a builtin function, when name lookup would otherwise
  448. /// fail.
  449. static bool LookupBuiltin(Sema &S, LookupResult &R) {
  450. Sema::LookupNameKind NameKind = R.getLookupKind();
  451. // If we didn't find a use of this identifier, and if the identifier
  452. // corresponds to a compiler builtin, create the decl object for the builtin
  453. // now, injecting it into translation unit scope, and return it.
  454. if (NameKind == Sema::LookupOrdinaryName ||
  455. NameKind == Sema::LookupRedeclarationWithLinkage) {
  456. IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
  457. if (II) {
  458. if (S.getLangOpts().CPlusPlus11 && S.getLangOpts().GNUMode &&
  459. II == S.getFloat128Identifier()) {
  460. // libstdc++4.7's type_traits expects type __float128 to exist, so
  461. // insert a dummy type to make that header build in gnu++11 mode.
  462. R.addDecl(S.getASTContext().getFloat128StubType());
  463. return true;
  464. }
  465. // If this is a builtin on this (or all) targets, create the decl.
  466. if (unsigned BuiltinID = II->getBuiltinID()) {
  467. // In C++, we don't have any predefined library functions like
  468. // 'malloc'. Instead, we'll just error.
  469. if (S.getLangOpts().CPlusPlus &&
  470. S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
  471. return false;
  472. if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
  473. BuiltinID, S.TUScope,
  474. R.isForRedeclaration(),
  475. R.getNameLoc())) {
  476. R.addDecl(D);
  477. return true;
  478. }
  479. }
  480. }
  481. }
  482. return false;
  483. }
  484. /// \brief Determine whether we can declare a special member function within
  485. /// the class at this point.
  486. static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
  487. // We need to have a definition for the class.
  488. if (!Class->getDefinition() || Class->isDependentContext())
  489. return false;
  490. // We can't be in the middle of defining the class.
  491. return !Class->isBeingDefined();
  492. }
  493. void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
  494. if (!CanDeclareSpecialMemberFunction(Class))
  495. return;
  496. // If the default constructor has not yet been declared, do so now.
  497. if (Class->needsImplicitDefaultConstructor())
  498. DeclareImplicitDefaultConstructor(Class);
  499. // If the copy constructor has not yet been declared, do so now.
  500. if (Class->needsImplicitCopyConstructor())
  501. DeclareImplicitCopyConstructor(Class);
  502. // If the copy assignment operator has not yet been declared, do so now.
  503. if (Class->needsImplicitCopyAssignment())
  504. DeclareImplicitCopyAssignment(Class);
  505. if (getLangOpts().CPlusPlus11) {
  506. // If the move constructor has not yet been declared, do so now.
  507. if (Class->needsImplicitMoveConstructor())
  508. DeclareImplicitMoveConstructor(Class); // might not actually do it
  509. // If the move assignment operator has not yet been declared, do so now.
  510. if (Class->needsImplicitMoveAssignment())
  511. DeclareImplicitMoveAssignment(Class); // might not actually do it
  512. }
  513. // If the destructor has not yet been declared, do so now.
  514. if (Class->needsImplicitDestructor())
  515. DeclareImplicitDestructor(Class);
  516. }
  517. /// \brief Determine whether this is the name of an implicitly-declared
  518. /// special member function.
  519. static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
  520. switch (Name.getNameKind()) {
  521. case DeclarationName::CXXConstructorName:
  522. case DeclarationName::CXXDestructorName:
  523. return true;
  524. case DeclarationName::CXXOperatorName:
  525. return Name.getCXXOverloadedOperator() == OO_Equal;
  526. default:
  527. break;
  528. }
  529. return false;
  530. }
  531. /// \brief If there are any implicit member functions with the given name
  532. /// that need to be declared in the given declaration context, do so.
  533. static void DeclareImplicitMemberFunctionsWithName(Sema &S,
  534. DeclarationName Name,
  535. const DeclContext *DC) {
  536. if (!DC)
  537. return;
  538. switch (Name.getNameKind()) {
  539. case DeclarationName::CXXConstructorName:
  540. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  541. if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
  542. CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
  543. if (Record->needsImplicitDefaultConstructor())
  544. S.DeclareImplicitDefaultConstructor(Class);
  545. if (Record->needsImplicitCopyConstructor())
  546. S.DeclareImplicitCopyConstructor(Class);
  547. if (S.getLangOpts().CPlusPlus11 &&
  548. Record->needsImplicitMoveConstructor())
  549. S.DeclareImplicitMoveConstructor(Class);
  550. }
  551. break;
  552. case DeclarationName::CXXDestructorName:
  553. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
  554. if (Record->getDefinition() && Record->needsImplicitDestructor() &&
  555. CanDeclareSpecialMemberFunction(Record))
  556. S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
  557. break;
  558. case DeclarationName::CXXOperatorName:
  559. if (Name.getCXXOverloadedOperator() != OO_Equal)
  560. break;
  561. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
  562. if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
  563. CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
  564. if (Record->needsImplicitCopyAssignment())
  565. S.DeclareImplicitCopyAssignment(Class);
  566. if (S.getLangOpts().CPlusPlus11 &&
  567. Record->needsImplicitMoveAssignment())
  568. S.DeclareImplicitMoveAssignment(Class);
  569. }
  570. }
  571. break;
  572. default:
  573. break;
  574. }
  575. }
  576. // Adds all qualifying matches for a name within a decl context to the
  577. // given lookup result. Returns true if any matches were found.
  578. static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
  579. bool Found = false;
  580. // Lazily declare C++ special member functions.
  581. if (S.getLangOpts().CPlusPlus)
  582. DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), DC);
  583. // Perform lookup into this declaration context.
  584. DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
  585. for (DeclContext::lookup_iterator I = DR.begin(), E = DR.end(); I != E;
  586. ++I) {
  587. NamedDecl *D = *I;
  588. if ((D = R.getAcceptableDecl(D))) {
  589. R.addDecl(D);
  590. Found = true;
  591. }
  592. }
  593. if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
  594. return true;
  595. if (R.getLookupName().getNameKind()
  596. != DeclarationName::CXXConversionFunctionName ||
  597. R.getLookupName().getCXXNameType()->isDependentType() ||
  598. !isa<CXXRecordDecl>(DC))
  599. return Found;
  600. // C++ [temp.mem]p6:
  601. // A specialization of a conversion function template is not found by
  602. // name lookup. Instead, any conversion function templates visible in the
  603. // context of the use are considered. [...]
  604. const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  605. if (!Record->isCompleteDefinition())
  606. return Found;
  607. for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
  608. UEnd = Record->conversion_end(); U != UEnd; ++U) {
  609. FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
  610. if (!ConvTemplate)
  611. continue;
  612. // When we're performing lookup for the purposes of redeclaration, just
  613. // add the conversion function template. When we deduce template
  614. // arguments for specializations, we'll end up unifying the return
  615. // type of the new declaration with the type of the function template.
  616. if (R.isForRedeclaration()) {
  617. R.addDecl(ConvTemplate);
  618. Found = true;
  619. continue;
  620. }
  621. // C++ [temp.mem]p6:
  622. // [...] For each such operator, if argument deduction succeeds
  623. // (14.9.2.3), the resulting specialization is used as if found by
  624. // name lookup.
  625. //
  626. // When referencing a conversion function for any purpose other than
  627. // a redeclaration (such that we'll be building an expression with the
  628. // result), perform template argument deduction and place the
  629. // specialization into the result set. We do this to avoid forcing all
  630. // callers to perform special deduction for conversion functions.
  631. TemplateDeductionInfo Info(R.getNameLoc());
  632. FunctionDecl *Specialization = nullptr;
  633. const FunctionProtoType *ConvProto
  634. = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
  635. assert(ConvProto && "Nonsensical conversion function template type");
  636. // Compute the type of the function that we would expect the conversion
  637. // function to have, if it were to match the name given.
  638. // FIXME: Calling convention!
  639. FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
  640. EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
  641. EPI.ExceptionSpec = EST_None;
  642. QualType ExpectedType
  643. = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
  644. None, EPI);
  645. // Perform template argument deduction against the type that we would
  646. // expect the function to have.
  647. if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
  648. Specialization, Info)
  649. == Sema::TDK_Success) {
  650. R.addDecl(Specialization);
  651. Found = true;
  652. }
  653. }
  654. return Found;
  655. }
  656. // Performs C++ unqualified lookup into the given file context.
  657. static bool
  658. CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
  659. DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
  660. assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
  661. // Perform direct name lookup into the LookupCtx.
  662. bool Found = LookupDirect(S, R, NS);
  663. // Perform direct name lookup into the namespaces nominated by the
  664. // using directives whose common ancestor is this namespace.
  665. for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
  666. if (LookupDirect(S, R, UUE.getNominatedNamespace()))
  667. Found = true;
  668. R.resolveKind();
  669. return Found;
  670. }
  671. static bool isNamespaceOrTranslationUnitScope(Scope *S) {
  672. if (DeclContext *Ctx = S->getEntity())
  673. return Ctx->isFileContext();
  674. return false;
  675. }
  676. // Find the next outer declaration context from this scope. This
  677. // routine actually returns the semantic outer context, which may
  678. // differ from the lexical context (encoded directly in the Scope
  679. // stack) when we are parsing a member of a class template. In this
  680. // case, the second element of the pair will be true, to indicate that
  681. // name lookup should continue searching in this semantic context when
  682. // it leaves the current template parameter scope.
  683. static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
  684. DeclContext *DC = S->getEntity();
  685. DeclContext *Lexical = nullptr;
  686. for (Scope *OuterS = S->getParent(); OuterS;
  687. OuterS = OuterS->getParent()) {
  688. if (OuterS->getEntity()) {
  689. Lexical = OuterS->getEntity();
  690. break;
  691. }
  692. }
  693. // C++ [temp.local]p8:
  694. // In the definition of a member of a class template that appears
  695. // outside of the namespace containing the class template
  696. // definition, the name of a template-parameter hides the name of
  697. // a member of this namespace.
  698. //
  699. // Example:
  700. //
  701. // namespace N {
  702. // class C { };
  703. //
  704. // template<class T> class B {
  705. // void f(T);
  706. // };
  707. // }
  708. //
  709. // template<class C> void N::B<C>::f(C) {
  710. // C b; // C is the template parameter, not N::C
  711. // }
  712. //
  713. // In this example, the lexical context we return is the
  714. // TranslationUnit, while the semantic context is the namespace N.
  715. if (!Lexical || !DC || !S->getParent() ||
  716. !S->getParent()->isTemplateParamScope())
  717. return std::make_pair(Lexical, false);
  718. // Find the outermost template parameter scope.
  719. // For the example, this is the scope for the template parameters of
  720. // template<class C>.
  721. Scope *OutermostTemplateScope = S->getParent();
  722. while (OutermostTemplateScope->getParent() &&
  723. OutermostTemplateScope->getParent()->isTemplateParamScope())
  724. OutermostTemplateScope = OutermostTemplateScope->getParent();
  725. // Find the namespace context in which the original scope occurs. In
  726. // the example, this is namespace N.
  727. DeclContext *Semantic = DC;
  728. while (!Semantic->isFileContext())
  729. Semantic = Semantic->getParent();
  730. // Find the declaration context just outside of the template
  731. // parameter scope. This is the context in which the template is
  732. // being lexically declaration (a namespace context). In the
  733. // example, this is the global scope.
  734. if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
  735. Lexical->Encloses(Semantic))
  736. return std::make_pair(Semantic, true);
  737. return std::make_pair(Lexical, false);
  738. }
  739. namespace {
  740. /// An RAII object to specify that we want to find block scope extern
  741. /// declarations.
  742. struct FindLocalExternScope {
  743. FindLocalExternScope(LookupResult &R)
  744. : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
  745. Decl::IDNS_LocalExtern) {
  746. R.setFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_Ordinary);
  747. }
  748. void restore() {
  749. R.setFindLocalExtern(OldFindLocalExtern);
  750. }
  751. ~FindLocalExternScope() {
  752. restore();
  753. }
  754. LookupResult &R;
  755. bool OldFindLocalExtern;
  756. };
  757. }
  758. bool Sema::CppLookupName(LookupResult &R, Scope *S) {
  759. assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
  760. DeclarationName Name = R.getLookupName();
  761. Sema::LookupNameKind NameKind = R.getLookupKind();
  762. // If this is the name of an implicitly-declared special member function,
  763. // go through the scope stack to implicitly declare
  764. if (isImplicitlyDeclaredMemberFunctionName(Name)) {
  765. for (Scope *PreS = S; PreS; PreS = PreS->getParent())
  766. if (DeclContext *DC = PreS->getEntity())
  767. DeclareImplicitMemberFunctionsWithName(*this, Name, DC);
  768. }
  769. // Implicitly declare member functions with the name we're looking for, if in
  770. // fact we are in a scope where it matters.
  771. Scope *Initial = S;
  772. IdentifierResolver::iterator
  773. I = IdResolver.begin(Name),
  774. IEnd = IdResolver.end();
  775. // First we lookup local scope.
  776. // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
  777. // ...During unqualified name lookup (3.4.1), the names appear as if
  778. // they were declared in the nearest enclosing namespace which contains
  779. // both the using-directive and the nominated namespace.
  780. // [Note: in this context, "contains" means "contains directly or
  781. // indirectly".
  782. //
  783. // For example:
  784. // namespace A { int i; }
  785. // void foo() {
  786. // int i;
  787. // {
  788. // using namespace A;
  789. // ++i; // finds local 'i', A::i appears at global scope
  790. // }
  791. // }
  792. //
  793. UnqualUsingDirectiveSet UDirs;
  794. bool VisitedUsingDirectives = false;
  795. bool LeftStartingScope = false;
  796. DeclContext *OutsideOfTemplateParamDC = nullptr;
  797. // When performing a scope lookup, we want to find local extern decls.
  798. FindLocalExternScope FindLocals(R);
  799. for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
  800. DeclContext *Ctx = S->getEntity();
  801. // Check whether the IdResolver has anything in this scope.
  802. bool Found = false;
  803. for (; I != IEnd && S->isDeclScope(*I); ++I) {
  804. if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
  805. if (NameKind == LookupRedeclarationWithLinkage) {
  806. // Determine whether this (or a previous) declaration is
  807. // out-of-scope.
  808. if (!LeftStartingScope && !Initial->isDeclScope(*I))
  809. LeftStartingScope = true;
  810. // If we found something outside of our starting scope that
  811. // does not have linkage, skip it. If it's a template parameter,
  812. // we still find it, so we can diagnose the invalid redeclaration.
  813. if (LeftStartingScope && !((*I)->hasLinkage()) &&
  814. !(*I)->isTemplateParameter()) {
  815. R.setShadowed();
  816. continue;
  817. }
  818. }
  819. Found = true;
  820. R.addDecl(ND);
  821. }
  822. }
  823. if (Found) {
  824. R.resolveKind();
  825. if (S->isClassScope())
  826. if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
  827. R.setNamingClass(Record);
  828. return true;
  829. }
  830. if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
  831. // C++11 [class.friend]p11:
  832. // If a friend declaration appears in a local class and the name
  833. // specified is an unqualified name, a prior declaration is
  834. // looked up without considering scopes that are outside the
  835. // innermost enclosing non-class scope.
  836. return false;
  837. }
  838. if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
  839. S->getParent() && !S->getParent()->isTemplateParamScope()) {
  840. // We've just searched the last template parameter scope and
  841. // found nothing, so look into the contexts between the
  842. // lexical and semantic declaration contexts returned by
  843. // findOuterContext(). This implements the name lookup behavior
  844. // of C++ [temp.local]p8.
  845. Ctx = OutsideOfTemplateParamDC;
  846. OutsideOfTemplateParamDC = nullptr;
  847. }
  848. if (Ctx) {
  849. DeclContext *OuterCtx;
  850. bool SearchAfterTemplateScope;
  851. std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
  852. if (SearchAfterTemplateScope)
  853. OutsideOfTemplateParamDC = OuterCtx;
  854. for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
  855. // We do not directly look into transparent contexts, since
  856. // those entities will be found in the nearest enclosing
  857. // non-transparent context.
  858. if (Ctx->isTransparentContext())
  859. continue;
  860. // We do not look directly into function or method contexts,
  861. // since all of the local variables and parameters of the
  862. // function/method are present within the Scope.
  863. if (Ctx->isFunctionOrMethod()) {
  864. // If we have an Objective-C instance method, look for ivars
  865. // in the corresponding interface.
  866. if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
  867. if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
  868. if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
  869. ObjCInterfaceDecl *ClassDeclared;
  870. if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
  871. Name.getAsIdentifierInfo(),
  872. ClassDeclared)) {
  873. if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
  874. R.addDecl(ND);
  875. R.resolveKind();
  876. return true;
  877. }
  878. }
  879. }
  880. }
  881. continue;
  882. }
  883. // If this is a file context, we need to perform unqualified name
  884. // lookup considering using directives.
  885. if (Ctx->isFileContext()) {
  886. // If we haven't handled using directives yet, do so now.
  887. if (!VisitedUsingDirectives) {
  888. // Add using directives from this context up to the top level.
  889. for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
  890. if (UCtx->isTransparentContext())
  891. continue;
  892. UDirs.visit(UCtx, UCtx);
  893. }
  894. // Find the innermost file scope, so we can add using directives
  895. // from local scopes.
  896. Scope *InnermostFileScope = S;
  897. while (InnermostFileScope &&
  898. !isNamespaceOrTranslationUnitScope(InnermostFileScope))
  899. InnermostFileScope = InnermostFileScope->getParent();
  900. UDirs.visitScopeChain(Initial, InnermostFileScope);
  901. UDirs.done();
  902. VisitedUsingDirectives = true;
  903. }
  904. if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
  905. R.resolveKind();
  906. return true;
  907. }
  908. continue;
  909. }
  910. // Perform qualified name lookup into this context.
  911. // FIXME: In some cases, we know that every name that could be found by
  912. // this qualified name lookup will also be on the identifier chain. For
  913. // example, inside a class without any base classes, we never need to
  914. // perform qualified lookup because all of the members are on top of the
  915. // identifier chain.
  916. if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
  917. return true;
  918. }
  919. }
  920. }
  921. // Stop if we ran out of scopes.
  922. // FIXME: This really, really shouldn't be happening.
  923. if (!S) return false;
  924. // If we are looking for members, no need to look into global/namespace scope.
  925. if (NameKind == LookupMemberName)
  926. return false;
  927. // Collect UsingDirectiveDecls in all scopes, and recursively all
  928. // nominated namespaces by those using-directives.
  929. //
  930. // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
  931. // don't build it for each lookup!
  932. if (!VisitedUsingDirectives) {
  933. UDirs.visitScopeChain(Initial, S);
  934. UDirs.done();
  935. }
  936. // If we're not performing redeclaration lookup, do not look for local
  937. // extern declarations outside of a function scope.
  938. if (!R.isForRedeclaration())
  939. FindLocals.restore();
  940. // Lookup namespace scope, and global scope.
  941. // Unqualified name lookup in C++ requires looking into scopes
  942. // that aren't strictly lexical, and therefore we walk through the
  943. // context as well as walking through the scopes.
  944. for (; S; S = S->getParent()) {
  945. // Check whether the IdResolver has anything in this scope.
  946. bool Found = false;
  947. for (; I != IEnd && S->isDeclScope(*I); ++I) {
  948. if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
  949. // We found something. Look for anything else in our scope
  950. // with this same name and in an acceptable identifier
  951. // namespace, so that we can construct an overload set if we
  952. // need to.
  953. Found = true;
  954. R.addDecl(ND);
  955. }
  956. }
  957. if (Found && S->isTemplateParamScope()) {
  958. R.resolveKind();
  959. return true;
  960. }
  961. DeclContext *Ctx = S->getEntity();
  962. if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
  963. S->getParent() && !S->getParent()->isTemplateParamScope()) {
  964. // We've just searched the last template parameter scope and
  965. // found nothing, so look into the contexts between the
  966. // lexical and semantic declaration contexts returned by
  967. // findOuterContext(). This implements the name lookup behavior
  968. // of C++ [temp.local]p8.
  969. Ctx = OutsideOfTemplateParamDC;
  970. OutsideOfTemplateParamDC = nullptr;
  971. }
  972. if (Ctx) {
  973. DeclContext *OuterCtx;
  974. bool SearchAfterTemplateScope;
  975. std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
  976. if (SearchAfterTemplateScope)
  977. OutsideOfTemplateParamDC = OuterCtx;
  978. for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
  979. // We do not directly look into transparent contexts, since
  980. // those entities will be found in the nearest enclosing
  981. // non-transparent context.
  982. if (Ctx->isTransparentContext())
  983. continue;
  984. // If we have a context, and it's not a context stashed in the
  985. // template parameter scope for an out-of-line definition, also
  986. // look into that context.
  987. if (!(Found && S && S->isTemplateParamScope())) {
  988. assert(Ctx->isFileContext() &&
  989. "We should have been looking only at file context here already.");
  990. // Look into context considering using-directives.
  991. if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
  992. Found = true;
  993. }
  994. if (Found) {
  995. R.resolveKind();
  996. return true;
  997. }
  998. if (R.isForRedeclaration() && !Ctx->isTransparentContext())
  999. return false;
  1000. }
  1001. }
  1002. if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
  1003. return false;
  1004. }
  1005. return !R.empty();
  1006. }
  1007. /// \brief Find the declaration that a class temploid member specialization was
  1008. /// instantiated from, or the member itself if it is an explicit specialization.
  1009. static Decl *getInstantiatedFrom(Decl *D, MemberSpecializationInfo *MSInfo) {
  1010. return MSInfo->isExplicitSpecialization() ? D : MSInfo->getInstantiatedFrom();
  1011. }
  1012. /// \brief Find the module in which the given declaration was defined.
  1013. static Module *getDefiningModule(Decl *Entity) {
  1014. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
  1015. // If this function was instantiated from a template, the defining module is
  1016. // the module containing the pattern.
  1017. if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
  1018. Entity = Pattern;
  1019. } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
  1020. if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
  1021. Entity = Pattern;
  1022. } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
  1023. if (MemberSpecializationInfo *MSInfo = ED->getMemberSpecializationInfo())
  1024. Entity = getInstantiatedFrom(ED, MSInfo);
  1025. } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
  1026. // FIXME: Map from variable template specializations back to the template.
  1027. if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo())
  1028. Entity = getInstantiatedFrom(VD, MSInfo);
  1029. }
  1030. // Walk up to the containing context. That might also have been instantiated
  1031. // from a template.
  1032. DeclContext *Context = Entity->getDeclContext();
  1033. if (Context->isFileContext())
  1034. return Entity->getOwningModule();
  1035. return getDefiningModule(cast<Decl>(Context));
  1036. }
  1037. llvm::DenseSet<Module*> &Sema::getLookupModules() {
  1038. unsigned N = ActiveTemplateInstantiations.size();
  1039. for (unsigned I = ActiveTemplateInstantiationLookupModules.size();
  1040. I != N; ++I) {
  1041. Module *M = getDefiningModule(ActiveTemplateInstantiations[I].Entity);
  1042. if (M && !LookupModulesCache.insert(M).second)
  1043. M = nullptr;
  1044. ActiveTemplateInstantiationLookupModules.push_back(M);
  1045. }
  1046. return LookupModulesCache;
  1047. }
  1048. /// \brief Determine whether a declaration is visible to name lookup.
  1049. ///
  1050. /// This routine determines whether the declaration D is visible in the current
  1051. /// lookup context, taking into account the current template instantiation
  1052. /// stack. During template instantiation, a declaration is visible if it is
  1053. /// visible from a module containing any entity on the template instantiation
  1054. /// path (by instantiating a template, you allow it to see the declarations that
  1055. /// your module can see, including those later on in your module).
  1056. bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
  1057. assert(D->isHidden() && !SemaRef.ActiveTemplateInstantiations.empty() &&
  1058. "should not call this: not in slow case");
  1059. Module *DeclModule = D->getOwningModule();
  1060. assert(DeclModule && "hidden decl not from a module");
  1061. // Find the extra places where we need to look.
  1062. llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
  1063. if (LookupModules.empty())
  1064. return false;
  1065. // If our lookup set contains the decl's module, it's visible.
  1066. if (LookupModules.count(DeclModule))
  1067. return true;
  1068. // If the declaration isn't exported, it's not visible in any other module.
  1069. if (D->isModulePrivate())
  1070. return false;
  1071. // Check whether DeclModule is transitively exported to an import of
  1072. // the lookup set.
  1073. for (llvm::DenseSet<Module *>::iterator I = LookupModules.begin(),
  1074. E = LookupModules.end();
  1075. I != E; ++I)
  1076. if ((*I)->isModuleVisible(DeclModule))
  1077. return true;
  1078. return false;
  1079. }
  1080. /// \brief Retrieve the visible declaration corresponding to D, if any.
  1081. ///
  1082. /// This routine determines whether the declaration D is visible in the current
  1083. /// module, with the current imports. If not, it checks whether any
  1084. /// redeclaration of D is visible, and if so, returns that declaration.
  1085. ///
  1086. /// \returns D, or a visible previous declaration of D, whichever is more recent
  1087. /// and visible. If no declaration of D is visible, returns null.
  1088. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
  1089. assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
  1090. for (auto RD : D->redecls()) {
  1091. if (auto ND = dyn_cast<NamedDecl>(RD)) {
  1092. // FIXME: This is wrong in the case where the previous declaration is not
  1093. // visible in the same scope as D. This needs to be done much more
  1094. // carefully.
  1095. if (LookupResult::isVisible(SemaRef, ND))
  1096. return ND;
  1097. }
  1098. }
  1099. return nullptr;
  1100. }
  1101. NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
  1102. return findAcceptableDecl(getSema(), D);
  1103. }
  1104. /// @brief Perform unqualified name lookup starting from a given
  1105. /// scope.
  1106. ///
  1107. /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
  1108. /// used to find names within the current scope. For example, 'x' in
  1109. /// @code
  1110. /// int x;
  1111. /// int f() {
  1112. /// return x; // unqualified name look finds 'x' in the global scope
  1113. /// }
  1114. /// @endcode
  1115. ///
  1116. /// Different lookup criteria can find different names. For example, a
  1117. /// particular scope can have both a struct and a function of the same
  1118. /// name, and each can be found by certain lookup criteria. For more
  1119. /// information about lookup criteria, see the documentation for the
  1120. /// class LookupCriteria.
  1121. ///
  1122. /// @param S The scope from which unqualified name lookup will
  1123. /// begin. If the lookup criteria permits, name lookup may also search
  1124. /// in the parent scopes.
  1125. ///
  1126. /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
  1127. /// look up and the lookup kind), and is updated with the results of lookup
  1128. /// including zero or more declarations and possibly additional information
  1129. /// used to diagnose ambiguities.
  1130. ///
  1131. /// @returns \c true if lookup succeeded and false otherwise.
  1132. bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
  1133. DeclarationName Name = R.getLookupName();
  1134. if (!Name) return false;
  1135. LookupNameKind NameKind = R.getLookupKind();
  1136. if (!getLangOpts().CPlusPlus) {
  1137. // Unqualified name lookup in C/Objective-C is purely lexical, so
  1138. // search in the declarations attached to the name.
  1139. if (NameKind == Sema::LookupRedeclarationWithLinkage) {
  1140. // Find the nearest non-transparent declaration scope.
  1141. while (!(S->getFlags() & Scope::DeclScope) ||
  1142. (S->getEntity() && S->getEntity()->isTransparentContext()))
  1143. S = S->getParent();
  1144. }
  1145. // When performing a scope lookup, we want to find local extern decls.
  1146. FindLocalExternScope FindLocals(R);
  1147. // Scan up the scope chain looking for a decl that matches this
  1148. // identifier that is in the appropriate namespace. This search
  1149. // should not take long, as shadowing of names is uncommon, and
  1150. // deep shadowing is extremely uncommon.
  1151. bool LeftStartingScope = false;
  1152. for (IdentifierResolver::iterator I = IdResolver.begin(Name),
  1153. IEnd = IdResolver.end();
  1154. I != IEnd; ++I)
  1155. if (NamedDecl *D = R.getAcceptableDecl(*I)) {
  1156. if (NameKind == LookupRedeclarationWithLinkage) {
  1157. // Determine whether this (or a previous) declaration is
  1158. // out-of-scope.
  1159. if (!LeftStartingScope && !S->isDeclScope(*I))
  1160. LeftStartingScope = true;
  1161. // If we found something outside of our starting scope that
  1162. // does not have linkage, skip it.
  1163. if (LeftStartingScope && !((*I)->hasLinkage())) {
  1164. R.setShadowed();
  1165. continue;
  1166. }
  1167. }
  1168. else if (NameKind == LookupObjCImplicitSelfParam &&
  1169. !isa<ImplicitParamDecl>(*I))
  1170. continue;
  1171. R.addDecl(D);
  1172. // Check whether there are any other declarations with the same name
  1173. // and in the same scope.
  1174. if (I != IEnd) {
  1175. // Find the scope in which this declaration was declared (if it
  1176. // actually exists in a Scope).
  1177. while (S && !S->isDeclScope(D))
  1178. S = S->getParent();
  1179. // If the scope containing the declaration is the translation unit,
  1180. // then we'll need to perform our checks based on the matching
  1181. // DeclContexts rather than matching scopes.
  1182. if (S && isNamespaceOrTranslationUnitScope(S))
  1183. S = nullptr;
  1184. // Compute the DeclContext, if we need it.
  1185. DeclContext *DC = nullptr;
  1186. if (!S)
  1187. DC = (*I)->getDeclContext()->getRedeclContext();
  1188. IdentifierResolver::iterator LastI = I;
  1189. for (++LastI; LastI != IEnd; ++LastI) {
  1190. if (S) {
  1191. // Match based on scope.
  1192. if (!S->isDeclScope(*LastI))
  1193. break;
  1194. } else {
  1195. // Match based on DeclContext.
  1196. DeclContext *LastDC
  1197. = (*LastI)->getDeclContext()->getRedeclContext();
  1198. if (!LastDC->Equals(DC))
  1199. break;
  1200. }
  1201. // If the declaration is in the right namespace and visible, add it.
  1202. if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
  1203. R.addDecl(LastD);
  1204. }
  1205. R.resolveKind();
  1206. }
  1207. return true;
  1208. }
  1209. } else {
  1210. // Perform C++ unqualified name lookup.
  1211. if (CppLookupName(R, S))
  1212. return true;
  1213. }
  1214. // If we didn't find a use of this identifier, and if the identifier
  1215. // corresponds to a compiler builtin, create the decl object for the builtin
  1216. // now, injecting it into translation unit scope, and return it.
  1217. if (AllowBuiltinCreation && LookupBuiltin(*this, R))
  1218. return true;
  1219. // If we didn't find a use of this identifier, the ExternalSource
  1220. // may be able to handle the situation.
  1221. // Note: some lookup failures are expected!
  1222. // See e.g. R.isForRedeclaration().
  1223. return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
  1224. }
  1225. /// @brief Perform qualified name lookup in the namespaces nominated by
  1226. /// using directives by the given context.
  1227. ///
  1228. /// C++98 [namespace.qual]p2:
  1229. /// Given X::m (where X is a user-declared namespace), or given \::m
  1230. /// (where X is the global namespace), let S be the set of all
  1231. /// declarations of m in X and in the transitive closure of all
  1232. /// namespaces nominated by using-directives in X and its used
  1233. /// namespaces, except that using-directives are ignored in any
  1234. /// namespace, including X, directly containing one or more
  1235. /// declarations of m. No namespace is searched more than once in
  1236. /// the lookup of a name. If S is the empty set, the program is
  1237. /// ill-formed. Otherwise, if S has exactly one member, or if the
  1238. /// context of the reference is a using-declaration
  1239. /// (namespace.udecl), S is the required set of declarations of
  1240. /// m. Otherwise if the use of m is not one that allows a unique
  1241. /// declaration to be chosen from S, the program is ill-formed.
  1242. ///
  1243. /// C++98 [namespace.qual]p5:
  1244. /// During the lookup of a qualified namespace member name, if the
  1245. /// lookup finds more than one declaration of the member, and if one
  1246. /// declaration introduces a class name or enumeration name and the
  1247. /// other declarations either introduce the same object, the same
  1248. /// enumerator or a set of functions, the non-type name hides the
  1249. /// class or enumeration name if and only if the declarations are
  1250. /// from the same namespace; otherwise (the declarations are from
  1251. /// different namespaces), the program is ill-formed.
  1252. static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
  1253. DeclContext *StartDC) {
  1254. assert(StartDC->isFileContext() && "start context is not a file context");
  1255. DeclContext::udir_range UsingDirectives = StartDC->using_directives();
  1256. if (UsingDirectives.begin() == UsingDirectives.end()) return false;
  1257. // We have at least added all these contexts to the queue.
  1258. llvm::SmallPtrSet<DeclContext*, 8> Visited;
  1259. Visited.insert(StartDC);
  1260. // We have not yet looked into these namespaces, much less added
  1261. // their "using-children" to the queue.
  1262. SmallVector<NamespaceDecl*, 8> Queue;
  1263. // We have already looked into the initial namespace; seed the queue
  1264. // with its using-children.
  1265. for (auto *I : UsingDirectives) {
  1266. NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
  1267. if (Visited.insert(ND).second)
  1268. Queue.push_back(ND);
  1269. }
  1270. // The easiest way to implement the restriction in [namespace.qual]p5
  1271. // is to check whether any of the individual results found a tag
  1272. // and, if so, to declare an ambiguity if the final result is not
  1273. // a tag.
  1274. bool FoundTag = false;
  1275. bool FoundNonTag = false;
  1276. LookupResult LocalR(LookupResult::Temporary, R);
  1277. bool Found = false;
  1278. while (!Queue.empty()) {
  1279. NamespaceDecl *ND = Queue.pop_back_val();
  1280. // We go through some convolutions here to avoid copying results
  1281. // between LookupResults.
  1282. bool UseLocal = !R.empty();
  1283. LookupResult &DirectR = UseLocal ? LocalR : R;
  1284. bool FoundDirect = LookupDirect(S, DirectR, ND);
  1285. if (FoundDirect) {
  1286. // First do any local hiding.
  1287. DirectR.resolveKind();
  1288. // If the local result is a tag, remember that.
  1289. if (DirectR.isSingleTagDecl())
  1290. FoundTag = true;
  1291. else
  1292. FoundNonTag = true;
  1293. // Append the local results to the total results if necessary.
  1294. if (UseLocal) {
  1295. R.addAllDecls(LocalR);
  1296. LocalR.clear();
  1297. }
  1298. }
  1299. // If we find names in this namespace, ignore its using directives.
  1300. if (FoundDirect) {
  1301. Found = true;
  1302. continue;
  1303. }
  1304. for (auto I : ND->using_directives()) {
  1305. NamespaceDecl *Nom = I->getNominatedNamespace();
  1306. if (Visited.insert(Nom).second)
  1307. Queue.push_back(Nom);
  1308. }
  1309. }
  1310. if (Found) {
  1311. if (FoundTag && FoundNonTag)
  1312. R.setAmbiguousQualifiedTagHiding();
  1313. else
  1314. R.resolveKind();
  1315. }
  1316. return Found;
  1317. }
  1318. /// \brief Callback that looks for any member of a class with the given name.
  1319. static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
  1320. CXXBasePath &Path,
  1321. void *Name) {
  1322. RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
  1323. DeclarationName N = DeclarationName::getFromOpaquePtr(Name);
  1324. Path.Decls = BaseRecord->lookup(N);
  1325. return !Path.Decls.empty();
  1326. }
  1327. /// \brief Determine whether the given set of member declarations contains only
  1328. /// static members, nested types, and enumerators.
  1329. template<typename InputIterator>
  1330. static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
  1331. Decl *D = (*First)->getUnderlyingDecl();
  1332. if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
  1333. return true;
  1334. if (isa<CXXMethodDecl>(D)) {
  1335. // Determine whether all of the methods are static.
  1336. bool AllMethodsAreStatic = true;
  1337. for(; First != Last; ++First) {
  1338. D = (*First)->getUnderlyingDecl();
  1339. if (!isa<CXXMethodDecl>(D)) {
  1340. assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
  1341. break;
  1342. }
  1343. if (!cast<CXXMethodDecl>(D)->isStatic()) {
  1344. AllMethodsAreStatic = false;
  1345. break;
  1346. }
  1347. }
  1348. if (AllMethodsAreStatic)
  1349. return true;
  1350. }
  1351. return false;
  1352. }
  1353. /// \brief Perform qualified name lookup into a given context.
  1354. ///
  1355. /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
  1356. /// names when the context of those names is explicit specified, e.g.,
  1357. /// "std::vector" or "x->member", or as part of unqualified name lookup.
  1358. ///
  1359. /// Different lookup criteria can find different names. For example, a
  1360. /// particular scope can have both a struct and a function of the same
  1361. /// name, and each can be found by certain lookup criteria. For more
  1362. /// information about lookup criteria, see the documentation for the
  1363. /// class LookupCriteria.
  1364. ///
  1365. /// \param R captures both the lookup criteria and any lookup results found.
  1366. ///
  1367. /// \param LookupCtx The context in which qualified name lookup will
  1368. /// search. If the lookup criteria permits, name lookup may also search
  1369. /// in the parent contexts or (for C++ classes) base classes.
  1370. ///
  1371. /// \param InUnqualifiedLookup true if this is qualified name lookup that
  1372. /// occurs as part of unqualified name lookup.
  1373. ///
  1374. /// \returns true if lookup succeeded, false if it failed.
  1375. bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
  1376. bool InUnqualifiedLookup) {
  1377. assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
  1378. if (!R.getLookupName())
  1379. return false;
  1380. // Make sure that the declaration context is complete.
  1381. assert((!isa<TagDecl>(LookupCtx) ||
  1382. LookupCtx->isDependentContext() ||
  1383. cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
  1384. cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
  1385. "Declaration context must already be complete!");
  1386. // Perform qualified name lookup into the LookupCtx.
  1387. if (LookupDirect(*this, R, LookupCtx)) {
  1388. R.resolveKind();
  1389. if (isa<CXXRecordDecl>(LookupCtx))
  1390. R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
  1391. return true;
  1392. }
  1393. // Don't descend into implied contexts for redeclarations.
  1394. // C++98 [namespace.qual]p6:
  1395. // In a declaration for a namespace member in which the
  1396. // declarator-id is a qualified-id, given that the qualified-id
  1397. // for the namespace member has the form
  1398. // nested-name-specifier unqualified-id
  1399. // the unqualified-id shall name a member of the namespace
  1400. // designated by the nested-name-specifier.
  1401. // See also [class.mfct]p5 and [class.static.data]p2.
  1402. if (R.isForRedeclaration())
  1403. return false;
  1404. // If this is a namespace, look it up in the implied namespaces.
  1405. if (LookupCtx->isFileContext())
  1406. return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
  1407. // If this isn't a C++ class, we aren't allowed to look into base
  1408. // classes, we're done.
  1409. CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
  1410. if (!LookupRec || !LookupRec->getDefinition())
  1411. return false;
  1412. // If we're performing qualified name lookup into a dependent class,
  1413. // then we are actually looking into a current instantiation. If we have any
  1414. // dependent base classes, then we either have to delay lookup until
  1415. // template instantiation time (at which point all bases will be available)
  1416. // or we have to fail.
  1417. if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
  1418. LookupRec->hasAnyDependentBases()) {
  1419. R.setNotFoundInCurrentInstantiation();
  1420. return false;
  1421. }
  1422. // Perform lookup into our base classes.
  1423. CXXBasePaths Paths;
  1424. Paths.setOrigin(LookupRec);
  1425. // Look for this member in our base classes
  1426. CXXRecordDecl::BaseMatchesCallback *BaseCallback = nullptr;
  1427. switch (R.getLookupKind()) {
  1428. case LookupObjCImplicitSelfParam:
  1429. case LookupOrdinaryName:
  1430. case LookupMemberName:
  1431. case LookupRedeclarationWithLinkage:
  1432. case LookupLocalFriendName:
  1433. BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
  1434. break;
  1435. case LookupTagName:
  1436. BaseCallback = &CXXRecordDecl::FindTagMember;
  1437. break;
  1438. case LookupAnyName:
  1439. BaseCallback = &LookupAnyMember;
  1440. break;
  1441. case LookupUsingDeclName:
  1442. // This lookup is for redeclarations only.
  1443. case LookupOperatorName:
  1444. case LookupNamespaceName:
  1445. case LookupObjCProtocolName:
  1446. case LookupLabel:
  1447. // These lookups will never find a member in a C++ class (or base class).
  1448. return false;
  1449. case LookupNestedNameSpecifierName:
  1450. BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
  1451. break;
  1452. }
  1453. if (!LookupRec->lookupInBases(BaseCallback,
  1454. R.getLookupName().getAsOpaquePtr(), Paths))
  1455. return false;
  1456. R.setNamingClass(LookupRec);
  1457. // C++ [class.member.lookup]p2:
  1458. // [...] If the resulting set of declarations are not all from
  1459. // sub-objects of the same type, or the set has a nonstatic member
  1460. // and includes members from distinct sub-objects, there is an
  1461. // ambiguity and the program is ill-formed. Otherwise that set is
  1462. // the result of the lookup.
  1463. QualType SubobjectType;
  1464. int SubobjectNumber = 0;
  1465. AccessSpecifier SubobjectAccess = AS_none;
  1466. for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
  1467. Path != PathEnd; ++Path) {
  1468. const CXXBasePathElement &PathElement = Path->back();
  1469. // Pick the best (i.e. most permissive i.e. numerically lowest) access
  1470. // across all paths.
  1471. SubobjectAccess = std::min(SubobjectAccess, Path->Access);
  1472. // Determine whether we're looking at a distinct sub-object or not.
  1473. if (SubobjectType.isNull()) {
  1474. // This is the first subobject we've looked at. Record its type.
  1475. SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
  1476. SubobjectNumber = PathElement.SubobjectNumber;
  1477. continue;
  1478. }
  1479. if (SubobjectType
  1480. != Context.getCanonicalType(PathElement.Base->getType())) {
  1481. // We found members of the given name in two subobjects of
  1482. // different types. If the declaration sets aren't the same, this
  1483. // lookup is ambiguous.
  1484. if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
  1485. CXXBasePaths::paths_iterator FirstPath = Paths.begin();
  1486. DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
  1487. DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
  1488. while (FirstD != FirstPath->Decls.end() &&
  1489. CurrentD != Path->Decls.end()) {
  1490. if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
  1491. (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
  1492. break;
  1493. ++FirstD;
  1494. ++CurrentD;
  1495. }
  1496. if (FirstD == FirstPath->Decls.end() &&
  1497. CurrentD == Path->Decls.end())
  1498. continue;
  1499. }
  1500. R.setAmbiguousBaseSubobjectTypes(Paths);
  1501. return true;
  1502. }
  1503. if (SubobjectNumber != PathElement.SubobjectNumber) {
  1504. // We have a different subobject of the same type.
  1505. // C++ [class.member.lookup]p5:
  1506. // A static member, a nested type or an enumerator defined in
  1507. // a base class T can unambiguously be found even if an object
  1508. // has more than one base class subobject of type T.
  1509. if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
  1510. continue;
  1511. // We have found a nonstatic member name in multiple, distinct
  1512. // subobjects. Name lookup is ambiguous.
  1513. R.setAmbiguousBaseSubobjects(Paths);
  1514. return true;
  1515. }
  1516. }
  1517. // Lookup in a base class succeeded; return these results.
  1518. for (auto *D : Paths.front().Decls) {
  1519. AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
  1520. D->getAccess());
  1521. R.addDecl(D, AS);
  1522. }
  1523. R.resolveKind();
  1524. return true;
  1525. }
  1526. /// \brief Performs qualified name lookup or special type of lookup for
  1527. /// "__super::" scope specifier.
  1528. ///
  1529. /// This routine is a convenience overload meant to be called from contexts
  1530. /// that need to perform a qualified name lookup with an optional C++ scope
  1531. /// specifier that might require special kind of lookup.
  1532. ///
  1533. /// \param R captures both the lookup criteria and any lookup results found.
  1534. ///
  1535. /// \param LookupCtx The context in which qualified name lookup will
  1536. /// search.
  1537. ///
  1538. /// \param SS An optional C++ scope-specifier.
  1539. ///
  1540. /// \returns true if lookup succeeded, false if it failed.
  1541. bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
  1542. CXXScopeSpec &SS) {
  1543. auto *NNS = SS.getScopeRep();
  1544. if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
  1545. return LookupInSuper(R, NNS->getAsRecordDecl());
  1546. else
  1547. return LookupQualifiedName(R, LookupCtx);
  1548. }
  1549. /// @brief Performs name lookup for a name that was parsed in the
  1550. /// source code, and may contain a C++ scope specifier.
  1551. ///
  1552. /// This routine is a convenience routine meant to be called from
  1553. /// contexts that receive a name and an optional C++ scope specifier
  1554. /// (e.g., "N::M::x"). It will then perform either qualified or
  1555. /// unqualified name lookup (with LookupQualifiedName or LookupName,
  1556. /// respectively) on the given name and return those results. It will
  1557. /// perform a special type of lookup for "__super::" scope specifier.
  1558. ///
  1559. /// @param S The scope from which unqualified name lookup will
  1560. /// begin.
  1561. ///
  1562. /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
  1563. ///
  1564. /// @param EnteringContext Indicates whether we are going to enter the
  1565. /// context of the scope-specifier SS (if present).
  1566. ///
  1567. /// @returns True if any decls were found (but possibly ambiguous)
  1568. bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
  1569. bool AllowBuiltinCreation, bool EnteringContext) {
  1570. if (SS && SS->isInvalid()) {
  1571. // When the scope specifier is invalid, don't even look for
  1572. // anything.
  1573. return false;
  1574. }
  1575. if (SS && SS->isSet()) {
  1576. NestedNameSpecifier *NNS = SS->getScopeRep();
  1577. if (NNS->getKind() == NestedNameSpecifier::Super)
  1578. return LookupInSuper(R, NNS->getAsRecordDecl());
  1579. if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
  1580. // We have resolved the scope specifier to a particular declaration
  1581. // contex, and will perform name lookup in that context.
  1582. if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
  1583. return false;
  1584. R.setContextRange(SS->getRange());
  1585. return LookupQualifiedName(R, DC);
  1586. }
  1587. // We could not resolve the scope specified to a specific declaration
  1588. // context, which means that SS refers to an unknown specialization.
  1589. // Name lookup can't find anything in this case.
  1590. R.setNotFoundInCurrentInstantiation();
  1591. R.setContextRange(SS->getRange());
  1592. return false;
  1593. }
  1594. // Perform unqualified name lookup starting in the given scope.
  1595. return LookupName(R, S, AllowBuiltinCreation);
  1596. }
  1597. /// \brief Perform qualified name lookup into all base classes of the given
  1598. /// class.
  1599. ///
  1600. /// \param R captures both the lookup criteria and any lookup results found.
  1601. ///
  1602. /// \param Class The context in which qualified name lookup will
  1603. /// search. Name lookup will search in all base classes merging the results.
  1604. ///
  1605. /// @returns True if any decls were found (but possibly ambiguous)
  1606. bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
  1607. for (const auto &BaseSpec : Class->bases()) {
  1608. CXXRecordDecl *RD = cast<CXXRecordDecl>(
  1609. BaseSpec.getType()->castAs<RecordType>()->getDecl());
  1610. LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
  1611. Result.setBaseObjectType(Context.getRecordType(Class));
  1612. LookupQualifiedName(Result, RD);
  1613. for (auto *Decl : Result)
  1614. R.addDecl(Decl);
  1615. }
  1616. R.resolveKind();
  1617. return !R.empty();
  1618. }
  1619. /// \brief Produce a diagnostic describing the ambiguity that resulted
  1620. /// from name lookup.
  1621. ///
  1622. /// \param Result The result of the ambiguous lookup to be diagnosed.
  1623. void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
  1624. assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
  1625. DeclarationName Name = Result.getLookupName();
  1626. SourceLocation NameLoc = Result.getNameLoc();
  1627. SourceRange LookupRange = Result.getContextRange();
  1628. switch (Result.getAmbiguityKind()) {
  1629. case LookupResult::AmbiguousBaseSubobjects: {
  1630. CXXBasePaths *Paths = Result.getBasePaths();
  1631. QualType SubobjectType = Paths->front().back().Base->getType();
  1632. Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
  1633. << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
  1634. << LookupRange;
  1635. DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
  1636. while (isa<CXXMethodDecl>(*Found) &&
  1637. cast<CXXMethodDecl>(*Found)->isStatic())
  1638. ++Found;
  1639. Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
  1640. break;
  1641. }
  1642. case LookupResult::AmbiguousBaseSubobjectTypes: {
  1643. Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
  1644. << Name << LookupRange;
  1645. CXXBasePaths *Paths = Result.getBasePaths();
  1646. std::set<Decl *> DeclsPrinted;
  1647. for (CXXBasePaths::paths_iterator Path = Paths->begin(),
  1648. PathEnd = Paths->end();
  1649. Path != PathEnd; ++Path) {
  1650. Decl *D = Path->Decls.front();
  1651. if (DeclsPrinted.insert(D).second)
  1652. Diag(D->getLocation(), diag::note_ambiguous_member_found);
  1653. }
  1654. break;
  1655. }
  1656. case LookupResult::AmbiguousTagHiding: {
  1657. Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
  1658. llvm::SmallPtrSet<NamedDecl*,8> TagDecls;
  1659. for (auto *D : Result)
  1660. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  1661. TagDecls.insert(TD);
  1662. Diag(TD->getLocation(), diag::note_hidden_tag);
  1663. }
  1664. for (auto *D : Result)
  1665. if (!isa<TagDecl>(D))
  1666. Diag(D->getLocation(), diag::note_hiding_object);
  1667. // For recovery purposes, go ahead and implement the hiding.
  1668. LookupResult::Filter F = Result.makeFilter();
  1669. while (F.hasNext()) {
  1670. if (TagDecls.count(F.next()))
  1671. F.erase();
  1672. }
  1673. F.done();
  1674. break;
  1675. }
  1676. case LookupResult::AmbiguousReference: {
  1677. Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
  1678. for (auto *D : Result)
  1679. Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
  1680. break;
  1681. }
  1682. }
  1683. }
  1684. namespace {
  1685. struct AssociatedLookup {
  1686. AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
  1687. Sema::AssociatedNamespaceSet &Namespaces,
  1688. Sema::AssociatedClassSet &Classes)
  1689. : S(S), Namespaces(Namespaces), Classes(Classes),
  1690. InstantiationLoc(InstantiationLoc) {
  1691. }
  1692. Sema &S;
  1693. Sema::AssociatedNamespaceSet &Namespaces;
  1694. Sema::AssociatedClassSet &Classes;
  1695. SourceLocation InstantiationLoc;
  1696. };
  1697. }
  1698. static void
  1699. addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
  1700. static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
  1701. DeclContext *Ctx) {
  1702. // Add the associated namespace for this class.
  1703. // We don't use DeclContext::getEnclosingNamespaceContext() as this may
  1704. // be a locally scoped record.
  1705. // We skip out of inline namespaces. The innermost non-inline namespace
  1706. // contains all names of all its nested inline namespaces anyway, so we can
  1707. // replace the entire inline namespace tree with its root.
  1708. while (Ctx->isRecord() || Ctx->isTransparentContext() ||
  1709. Ctx->isInlineNamespace())
  1710. Ctx = Ctx->getParent();
  1711. if (Ctx->isFileContext())
  1712. Namespaces.insert(Ctx->getPrimaryContext());
  1713. }
  1714. // \brief Add the associated classes and namespaces for argument-dependent
  1715. // lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
  1716. static void
  1717. addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
  1718. const TemplateArgument &Arg) {
  1719. // C++ [basic.lookup.koenig]p2, last bullet:
  1720. // -- [...] ;
  1721. switch (Arg.getKind()) {
  1722. case TemplateArgument::Null:
  1723. break;
  1724. case TemplateArgument::Type:
  1725. // [...] the namespaces and classes associated with the types of the
  1726. // template arguments provided for template type parameters (excluding
  1727. // template template parameters)
  1728. addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
  1729. break;
  1730. case TemplateArgument::Template:
  1731. case TemplateArgument::TemplateExpansion: {
  1732. // [...] the namespaces in which any template template arguments are
  1733. // defined; and the classes in which any member templates used as
  1734. // template template arguments are defined.
  1735. TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
  1736. if (ClassTemplateDecl *ClassTemplate
  1737. = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
  1738. DeclContext *Ctx = ClassTemplate->getDeclContext();
  1739. if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
  1740. Result.Classes.insert(EnclosingClass);
  1741. // Add the associated namespace for this class.
  1742. CollectEnclosingNamespace(Result.Namespaces, Ctx);
  1743. }
  1744. break;
  1745. }
  1746. case TemplateArgument::Declaration:
  1747. case TemplateArgument::Integral:
  1748. case TemplateArgument::Expression:
  1749. case TemplateArgument::NullPtr:
  1750. // [Note: non-type template arguments do not contribute to the set of
  1751. // associated namespaces. ]
  1752. break;
  1753. case TemplateArgument::Pack:
  1754. for (const auto &P : Arg.pack_elements())
  1755. addAssociatedClassesAndNamespaces(Result, P);
  1756. break;
  1757. }
  1758. }
  1759. // \brief Add the associated classes and namespaces for
  1760. // argument-dependent lookup with an argument of class type
  1761. // (C++ [basic.lookup.koenig]p2).
  1762. static void
  1763. addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
  1764. CXXRecordDecl *Class) {
  1765. // Just silently ignore anything whose name is __va_list_tag.
  1766. if (Class->getDeclName() == Result.S.VAListTagName)
  1767. return;
  1768. // C++ [basic.lookup.koenig]p2:
  1769. // [...]
  1770. // -- If T is a class type (including unions), its associated
  1771. // classes are: the class itself; the class of which it is a
  1772. // member, if any; and its direct and indirect base
  1773. // classes. Its associated namespaces are the namespaces in
  1774. // which its associated classes are defined.
  1775. // Add the class of which it is a member, if any.
  1776. DeclContext *Ctx = Class->getDeclContext();
  1777. if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
  1778. Result.Classes.insert(EnclosingClass);
  1779. // Add the associated namespace for this class.
  1780. CollectEnclosingNamespace(Result.Namespaces, Ctx);
  1781. // Add the class itself. If we've already seen this class, we don't
  1782. // need to visit base classes.
  1783. //
  1784. // FIXME: That's not correct, we may have added this class only because it
  1785. // was the enclosing class of another class, and in that case we won't have
  1786. // added its base classes yet.
  1787. if (!Result.Classes.insert(Class).second)
  1788. return;
  1789. // -- If T is a template-id, its associated namespaces and classes are
  1790. // the namespace in which the template is defined; for member
  1791. // templates, the member template's class; the namespaces and classes
  1792. // associated with the types of the template arguments provided for
  1793. // template type parameters (excluding template template parameters); the
  1794. // namespaces in which any template template arguments are defined; and
  1795. // the classes in which any member templates used as template template
  1796. // arguments are defined. [Note: non-type template arguments do not
  1797. // contribute to the set of associated namespaces. ]
  1798. if (ClassTemplateSpecializationDecl *Spec
  1799. = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
  1800. DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
  1801. if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
  1802. Result.Classes.insert(EnclosingClass);
  1803. // Add the associated namespace for this class.
  1804. CollectEnclosingNamespace(Result.Namespaces, Ctx);
  1805. const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
  1806. for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
  1807. addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
  1808. }
  1809. // Only recurse into base classes for complete types.
  1810. if (!Class->hasDefinition())
  1811. return;
  1812. // Add direct and indirect base classes along with their associated
  1813. // namespaces.
  1814. SmallVector<CXXRecordDecl *, 32> Bases;
  1815. Bases.push_back(Class);
  1816. while (!Bases.empty()) {
  1817. // Pop this class off the stack.
  1818. Class = Bases.pop_back_val();
  1819. // Visit the base classes.
  1820. for (const auto &Base : Class->bases()) {
  1821. const RecordType *BaseType = Base.getType()->getAs<RecordType>();
  1822. // In dependent contexts, we do ADL twice, and the first time around,
  1823. // the base type might be a dependent TemplateSpecializationType, or a
  1824. // TemplateTypeParmType. If that happens, simply ignore it.
  1825. // FIXME: If we want to support export, we probably need to add the
  1826. // namespace of the template in a TemplateSpecializationType, or even
  1827. // the classes and namespaces of known non-dependent arguments.
  1828. if (!BaseType)
  1829. continue;
  1830. CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
  1831. if (Result.Classes.insert(BaseDecl).second) {
  1832. // Find the associated namespace for this base class.
  1833. DeclContext *BaseCtx = BaseDecl->getDeclContext();
  1834. CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
  1835. // Make sure we visit the bases of this base class.
  1836. if (BaseDecl->bases_begin() != BaseDecl->bases_end())
  1837. Bases.push_back(BaseDecl);
  1838. }
  1839. }
  1840. }
  1841. }
  1842. // \brief Add the associated classes and namespaces for
  1843. // argument-dependent lookup with an argument of type T
  1844. // (C++ [basic.lookup.koenig]p2).
  1845. static void
  1846. addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
  1847. // C++ [basic.lookup.koenig]p2:
  1848. //
  1849. // For each argument type T in the function call, there is a set
  1850. // of zero or more associated namespaces and a set of zero or more
  1851. // associated classes to be considered. The sets of namespaces and
  1852. // classes is determined entirely by the types of the function
  1853. // arguments (and the namespace of any template template
  1854. // argument). Typedef names and using-declarations used to specify
  1855. // the types do not contribute to this set. The sets of namespaces
  1856. // and classes are determined in the following way:
  1857. SmallVector<const Type *, 16> Queue;
  1858. const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
  1859. while (true) {
  1860. switch (T->getTypeClass()) {
  1861. #define TYPE(Class, Base)
  1862. #define DEPENDENT_TYPE(Class, Base) case Type::Class:
  1863. #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
  1864. #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
  1865. #define ABSTRACT_TYPE(Class, Base)
  1866. #include "clang/AST/TypeNodes.def"
  1867. // T is canonical. We can also ignore dependent types because
  1868. // we don't need to do ADL at the definition point, but if we
  1869. // wanted to implement template export (or if we find some other
  1870. // use for associated classes and namespaces...) this would be
  1871. // wrong.
  1872. break;
  1873. // -- If T is a pointer to U or an array of U, its associated
  1874. // namespaces and classes are those associated with U.
  1875. case Type::Pointer:
  1876. T = cast<PointerType>(T)->getPointeeType().getTypePtr();
  1877. continue;
  1878. case Type::ConstantArray:
  1879. case Type::IncompleteArray:
  1880. case Type::VariableArray:
  1881. T = cast<ArrayType>(T)->getElementType().getTypePtr();
  1882. continue;
  1883. // -- If T is a fundamental type, its associated sets of
  1884. // namespaces and classes are both empty.
  1885. case Type::Builtin:
  1886. break;
  1887. // -- If T is a class type (including unions), its associated
  1888. // classes are: the class itself; the class of which it is a
  1889. // member, if any; and its direct and indirect base
  1890. // classes. Its associated namespaces are the namespaces in
  1891. // which its associated classes are defined.
  1892. case Type::Record: {
  1893. Result.S.RequireCompleteType(Result.InstantiationLoc, QualType(T, 0),
  1894. /*no diagnostic*/ 0);
  1895. CXXRecordDecl *Class
  1896. = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
  1897. addAssociatedClassesAndNamespaces(Result, Class);
  1898. break;
  1899. }
  1900. // -- If T is an enumeration type, its associated namespace is
  1901. // the namespace in which it is defined. If it is class
  1902. // member, its associated class is the member's class; else
  1903. // it has no associated class.
  1904. case Type::Enum: {
  1905. EnumDecl *Enum = cast<EnumType>(T)->getDecl();
  1906. DeclContext *Ctx = Enum->getDeclContext();
  1907. if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
  1908. Result.Classes.insert(EnclosingClass);
  1909. // Add the associated namespace for this class.
  1910. CollectEnclosingNamespace(Result.Namespaces, Ctx);
  1911. break;
  1912. }
  1913. // -- If T is a function type, its associated namespaces and
  1914. // classes are those associated with the function parameter
  1915. // types and those associated with the return type.
  1916. case Type::FunctionProto: {
  1917. const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
  1918. for (const auto &Arg : Proto->param_types())
  1919. Queue.push_back(Arg.getTypePtr());
  1920. // fallthrough
  1921. }
  1922. case Type::FunctionNoProto: {
  1923. const FunctionType *FnType = cast<FunctionType>(T);
  1924. T = FnType->getReturnType().getTypePtr();
  1925. continue;
  1926. }
  1927. // -- If T is a pointer to a member function of a class X, its
  1928. // associated namespaces and classes are those associated
  1929. // with the function parameter types and return type,
  1930. // together with those associated with X.
  1931. //
  1932. // -- If T is a pointer to a data member of class X, its
  1933. // associated namespaces and classes are those associated
  1934. // with the member type together with those associated with
  1935. // X.
  1936. case Type::MemberPointer: {
  1937. const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
  1938. // Queue up the class type into which this points.
  1939. Queue.push_back(MemberPtr->getClass());
  1940. // And directly continue with the pointee type.
  1941. T = MemberPtr->getPointeeType().getTypePtr();
  1942. continue;
  1943. }
  1944. // As an extension, treat this like a normal pointer.
  1945. case Type::BlockPointer:
  1946. T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
  1947. continue;
  1948. // References aren't covered by the standard, but that's such an
  1949. // obvious defect that we cover them anyway.
  1950. case Type::LValueReference:
  1951. case Type::RValueReference:
  1952. T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
  1953. continue;
  1954. // These are fundamental types.
  1955. case Type::Vector:
  1956. case Type::ExtVector:
  1957. case Type::Complex:
  1958. break;
  1959. // Non-deduced auto types only get here for error cases.
  1960. case Type::Auto:
  1961. break;
  1962. // If T is an Objective-C object or interface type, or a pointer to an
  1963. // object or interface type, the associated namespace is the global
  1964. // namespace.
  1965. case Type::ObjCObject:
  1966. case Type::ObjCInterface:
  1967. case Type::ObjCObjectPointer:
  1968. Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
  1969. break;
  1970. // Atomic types are just wrappers; use the associations of the
  1971. // contained type.
  1972. case Type::Atomic:
  1973. T = cast<AtomicType>(T)->getValueType().getTypePtr();
  1974. continue;
  1975. }
  1976. if (Queue.empty())
  1977. break;
  1978. T = Queue.pop_back_val();
  1979. }
  1980. }
  1981. /// \brief Find the associated classes and namespaces for
  1982. /// argument-dependent lookup for a call with the given set of
  1983. /// arguments.
  1984. ///
  1985. /// This routine computes the sets of associated classes and associated
  1986. /// namespaces searched by argument-dependent lookup
  1987. /// (C++ [basic.lookup.argdep]) for a given set of arguments.
  1988. void Sema::FindAssociatedClassesAndNamespaces(
  1989. SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
  1990. AssociatedNamespaceSet &AssociatedNamespaces,
  1991. AssociatedClassSet &AssociatedClasses) {
  1992. AssociatedNamespaces.clear();
  1993. AssociatedClasses.clear();
  1994. AssociatedLookup Result(*this, InstantiationLoc,
  1995. AssociatedNamespaces, AssociatedClasses);
  1996. // C++ [basic.lookup.koenig]p2:
  1997. // For each argument type T in the function call, there is a set
  1998. // of zero or more associated namespaces and a set of zero or more
  1999. // associated classes to be considered. The sets of namespaces and
  2000. // classes is determined entirely by the types of the function
  2001. // arguments (and the namespace of any template template
  2002. // argument).
  2003. for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
  2004. Expr *Arg = Args[ArgIdx];
  2005. if (Arg->getType() != Context.OverloadTy) {
  2006. addAssociatedClassesAndNamespaces(Result, Arg->getType());
  2007. continue;
  2008. }
  2009. // [...] In addition, if the argument is the name or address of a
  2010. // set of overloaded functions and/or function templates, its
  2011. // associated classes and namespaces are the union of those
  2012. // associated with each of the members of the set: the namespace
  2013. // in which the function or function template is defined and the
  2014. // classes and namespaces associated with its (non-dependent)
  2015. // parameter types and return type.
  2016. Arg = Arg->IgnoreParens();
  2017. if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
  2018. if (unaryOp->getOpcode() == UO_AddrOf)
  2019. Arg = unaryOp->getSubExpr();
  2020. UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
  2021. if (!ULE) continue;
  2022. for (const auto *D : ULE->decls()) {
  2023. // Look through any using declarations to find the underlying function.
  2024. const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
  2025. // Add the classes and namespaces associated with the parameter
  2026. // types and return type of this function.
  2027. addAssociatedClassesAndNamespaces(Result, FDecl->getType());
  2028. }
  2029. }
  2030. }
  2031. NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
  2032. SourceLocation Loc,
  2033. LookupNameKind NameKind,
  2034. RedeclarationKind Redecl) {
  2035. LookupResult R(*this, Name, Loc, NameKind, Redecl);
  2036. LookupName(R, S);
  2037. return R.getAsSingle<NamedDecl>();
  2038. }
  2039. /// \brief Find the protocol with the given name, if any.
  2040. ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
  2041. SourceLocation IdLoc,
  2042. RedeclarationKind Redecl) {
  2043. Decl *D = LookupSingleName(TUScope, II, IdLoc,
  2044. LookupObjCProtocolName, Redecl);
  2045. return cast_or_null<ObjCProtocolDecl>(D);
  2046. }
  2047. void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
  2048. QualType T1, QualType T2,
  2049. UnresolvedSetImpl &Functions) {
  2050. // C++ [over.match.oper]p3:
  2051. // -- The set of non-member candidates is the result of the
  2052. // unqualified lookup of operator@ in the context of the
  2053. // expression according to the usual rules for name lookup in
  2054. // unqualified function calls (3.4.2) except that all member
  2055. // functions are ignored.
  2056. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
  2057. LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
  2058. LookupName(Operators, S);
  2059. assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
  2060. Functions.append(Operators.begin(), Operators.end());
  2061. }
  2062. Sema::SpecialMemberOverloadResult *Sema::LookupSpecialMember(CXXRecordDecl *RD,
  2063. CXXSpecialMember SM,
  2064. bool ConstArg,
  2065. bool VolatileArg,
  2066. bool RValueThis,
  2067. bool ConstThis,
  2068. bool VolatileThis) {
  2069. assert(CanDeclareSpecialMemberFunction(RD) &&
  2070. "doing special member lookup into record that isn't fully complete");
  2071. RD = RD->getDefinition();
  2072. if (RValueThis || ConstThis || VolatileThis)
  2073. assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
  2074. "constructors and destructors always have unqualified lvalue this");
  2075. if (ConstArg || VolatileArg)
  2076. assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
  2077. "parameter-less special members can't have qualified arguments");
  2078. llvm::FoldingSetNodeID ID;
  2079. ID.AddPointer(RD);
  2080. ID.AddInteger(SM);
  2081. ID.AddInteger(ConstArg);
  2082. ID.AddInteger(VolatileArg);
  2083. ID.AddInteger(RValueThis);
  2084. ID.AddInteger(ConstThis);
  2085. ID.AddInteger(VolatileThis);
  2086. void *InsertPoint;
  2087. SpecialMemberOverloadResult *Result =
  2088. SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
  2089. // This was already cached
  2090. if (Result)
  2091. return Result;
  2092. Result = BumpAlloc.Allocate<SpecialMemberOverloadResult>();
  2093. Result = new (Result) SpecialMemberOverloadResult(ID);
  2094. SpecialMemberCache.InsertNode(Result, InsertPoint);
  2095. if (SM == CXXDestructor) {
  2096. if (RD->needsImplicitDestructor())
  2097. DeclareImplicitDestructor(RD);
  2098. CXXDestructorDecl *DD = RD->getDestructor();
  2099. assert(DD && "record without a destructor");
  2100. Result->setMethod(DD);
  2101. Result->setKind(DD->isDeleted() ?
  2102. SpecialMemberOverloadResult::NoMemberOrDeleted :
  2103. SpecialMemberOverloadResult::Success);
  2104. return Result;
  2105. }
  2106. // Prepare for overload resolution. Here we construct a synthetic argument
  2107. // if necessary and make sure that implicit functions are declared.
  2108. CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
  2109. DeclarationName Name;
  2110. Expr *Arg = nullptr;
  2111. unsigned NumArgs;
  2112. QualType ArgType = CanTy;
  2113. ExprValueKind VK = VK_LValue;
  2114. if (SM == CXXDefaultConstructor) {
  2115. Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
  2116. NumArgs = 0;
  2117. if (RD->needsImplicitDefaultConstructor())
  2118. DeclareImplicitDefaultConstructor(RD);
  2119. } else {
  2120. if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
  2121. Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
  2122. if (RD->needsImplicitCopyConstructor())
  2123. DeclareImplicitCopyConstructor(RD);
  2124. if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
  2125. DeclareImplicitMoveConstructor(RD);
  2126. } else {
  2127. Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
  2128. if (RD->needsImplicitCopyAssignment())
  2129. DeclareImplicitCopyAssignment(RD);
  2130. if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
  2131. DeclareImplicitMoveAssignment(RD);
  2132. }
  2133. if (ConstArg)
  2134. ArgType.addConst();
  2135. if (VolatileArg)
  2136. ArgType.addVolatile();
  2137. // This isn't /really/ specified by the standard, but it's implied
  2138. // we should be working from an RValue in the case of move to ensure
  2139. // that we prefer to bind to rvalue references, and an LValue in the
  2140. // case of copy to ensure we don't bind to rvalue references.
  2141. // Possibly an XValue is actually correct in the case of move, but
  2142. // there is no semantic difference for class types in this restricted
  2143. // case.
  2144. if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
  2145. VK = VK_LValue;
  2146. else
  2147. VK = VK_RValue;
  2148. }
  2149. OpaqueValueExpr FakeArg(SourceLocation(), ArgType, VK);
  2150. if (SM != CXXDefaultConstructor) {
  2151. NumArgs = 1;
  2152. Arg = &FakeArg;
  2153. }
  2154. // Create the object argument
  2155. QualType ThisTy = CanTy;
  2156. if (ConstThis)
  2157. ThisTy.addConst();
  2158. if (VolatileThis)
  2159. ThisTy.addVolatile();
  2160. Expr::Classification Classification =
  2161. OpaqueValueExpr(SourceLocation(), ThisTy,
  2162. RValueThis ? VK_RValue : VK_LValue).Classify(Context);
  2163. // Now we perform lookup on the name we computed earlier and do overload
  2164. // resolution. Lookup is only performed directly into the class since there
  2165. // will always be a (possibly implicit) declaration to shadow any others.
  2166. OverloadCandidateSet OCS(RD->getLocation(), OverloadCandidateSet::CSK_Normal);
  2167. DeclContext::lookup_result R = RD->lookup(Name);
  2168. if (R.empty()) {
  2169. // We might have no default constructor because we have a lambda's closure
  2170. // type, rather than because there's some other declared constructor.
  2171. // Every class has a copy/move constructor, copy/move assignment, and
  2172. // destructor.
  2173. assert(SM == CXXDefaultConstructor &&
  2174. "lookup for a constructor or assignment operator was empty");
  2175. Result->setMethod(nullptr);
  2176. Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
  2177. return Result;
  2178. }
  2179. // Copy the candidates as our processing of them may load new declarations
  2180. // from an external source and invalidate lookup_result.
  2181. SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
  2182. for (auto *Cand : Candidates) {
  2183. if (Cand->isInvalidDecl())
  2184. continue;
  2185. if (UsingShadowDecl *U = dyn_cast<UsingShadowDecl>(Cand)) {
  2186. // FIXME: [namespace.udecl]p15 says that we should only consider a
  2187. // using declaration here if it does not match a declaration in the
  2188. // derived class. We do not implement this correctly in other cases
  2189. // either.
  2190. Cand = U->getTargetDecl();
  2191. if (Cand->isInvalidDecl())
  2192. continue;
  2193. }
  2194. if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand)) {
  2195. if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
  2196. AddMethodCandidate(M, DeclAccessPair::make(M, AS_public), RD, ThisTy,
  2197. Classification, llvm::makeArrayRef(&Arg, NumArgs),
  2198. OCS, true);
  2199. else
  2200. AddOverloadCandidate(M, DeclAccessPair::make(M, AS_public),
  2201. llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
  2202. } else if (FunctionTemplateDecl *Tmpl =
  2203. dyn_cast<FunctionTemplateDecl>(Cand)) {
  2204. if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
  2205. AddMethodTemplateCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
  2206. RD, nullptr, ThisTy, Classification,
  2207. llvm::makeArrayRef(&Arg, NumArgs),
  2208. OCS, true);
  2209. else
  2210. AddTemplateOverloadCandidate(Tmpl, DeclAccessPair::make(Tmpl, AS_public),
  2211. nullptr, llvm::makeArrayRef(&Arg, NumArgs),
  2212. OCS, true);
  2213. } else {
  2214. assert(isa<UsingDecl>(Cand) && "illegal Kind of operator = Decl");
  2215. }
  2216. }
  2217. OverloadCandidateSet::iterator Best;
  2218. switch (OCS.BestViableFunction(*this, SourceLocation(), Best)) {
  2219. case OR_Success:
  2220. Result->setMethod(cast<CXXMethodDecl>(Best->Function));
  2221. Result->setKind(SpecialMemberOverloadResult::Success);
  2222. break;
  2223. case OR_Deleted:
  2224. Result->setMethod(cast<CXXMethodDecl>(Best->Function));
  2225. Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
  2226. break;
  2227. case OR_Ambiguous:
  2228. Result->setMethod(nullptr);
  2229. Result->setKind(SpecialMemberOverloadResult::Ambiguous);
  2230. break;
  2231. case OR_No_Viable_Function:
  2232. Result->setMethod(nullptr);
  2233. Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
  2234. break;
  2235. }
  2236. return Result;
  2237. }
  2238. /// \brief Look up the default constructor for the given class.
  2239. CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
  2240. SpecialMemberOverloadResult *Result =
  2241. LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
  2242. false, false);
  2243. return cast_or_null<CXXConstructorDecl>(Result->getMethod());
  2244. }
  2245. /// \brief Look up the copying constructor for the given class.
  2246. CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
  2247. unsigned Quals) {
  2248. assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
  2249. "non-const, non-volatile qualifiers for copy ctor arg");
  2250. SpecialMemberOverloadResult *Result =
  2251. LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
  2252. Quals & Qualifiers::Volatile, false, false, false);
  2253. return cast_or_null<CXXConstructorDecl>(Result->getMethod());
  2254. }
  2255. /// \brief Look up the moving constructor for the given class.
  2256. CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
  2257. unsigned Quals) {
  2258. SpecialMemberOverloadResult *Result =
  2259. LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
  2260. Quals & Qualifiers::Volatile, false, false, false);
  2261. return cast_or_null<CXXConstructorDecl>(Result->getMethod());
  2262. }
  2263. /// \brief Look up the constructors for the given class.
  2264. DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
  2265. // If the implicit constructors have not yet been declared, do so now.
  2266. if (CanDeclareSpecialMemberFunction(Class)) {
  2267. if (Class->needsImplicitDefaultConstructor())
  2268. DeclareImplicitDefaultConstructor(Class);
  2269. if (Class->needsImplicitCopyConstructor())
  2270. DeclareImplicitCopyConstructor(Class);
  2271. if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
  2272. DeclareImplicitMoveConstructor(Class);
  2273. }
  2274. CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
  2275. DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
  2276. return Class->lookup(Name);
  2277. }
  2278. /// \brief Look up the copying assignment operator for the given class.
  2279. CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
  2280. unsigned Quals, bool RValueThis,
  2281. unsigned ThisQuals) {
  2282. assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
  2283. "non-const, non-volatile qualifiers for copy assignment arg");
  2284. assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
  2285. "non-const, non-volatile qualifiers for copy assignment this");
  2286. SpecialMemberOverloadResult *Result =
  2287. LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
  2288. Quals & Qualifiers::Volatile, RValueThis,
  2289. ThisQuals & Qualifiers::Const,
  2290. ThisQuals & Qualifiers::Volatile);
  2291. return Result->getMethod();
  2292. }
  2293. /// \brief Look up the moving assignment operator for the given class.
  2294. CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
  2295. unsigned Quals,
  2296. bool RValueThis,
  2297. unsigned ThisQuals) {
  2298. assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
  2299. "non-const, non-volatile qualifiers for copy assignment this");
  2300. SpecialMemberOverloadResult *Result =
  2301. LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
  2302. Quals & Qualifiers::Volatile, RValueThis,
  2303. ThisQuals & Qualifiers::Const,
  2304. ThisQuals & Qualifiers::Volatile);
  2305. return Result->getMethod();
  2306. }
  2307. /// \brief Look for the destructor of the given class.
  2308. ///
  2309. /// During semantic analysis, this routine should be used in lieu of
  2310. /// CXXRecordDecl::getDestructor().
  2311. ///
  2312. /// \returns The destructor for this class.
  2313. CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
  2314. return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
  2315. false, false, false,
  2316. false, false)->getMethod());
  2317. }
  2318. /// LookupLiteralOperator - Determine which literal operator should be used for
  2319. /// a user-defined literal, per C++11 [lex.ext].
  2320. ///
  2321. /// Normal overload resolution is not used to select which literal operator to
  2322. /// call for a user-defined literal. Look up the provided literal operator name,
  2323. /// and filter the results to the appropriate set for the given argument types.
  2324. Sema::LiteralOperatorLookupResult
  2325. Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
  2326. ArrayRef<QualType> ArgTys,
  2327. bool AllowRaw, bool AllowTemplate,
  2328. bool AllowStringTemplate) {
  2329. LookupName(R, S);
  2330. assert(R.getResultKind() != LookupResult::Ambiguous &&
  2331. "literal operator lookup can't be ambiguous");
  2332. // Filter the lookup results appropriately.
  2333. LookupResult::Filter F = R.makeFilter();
  2334. bool FoundRaw = false;
  2335. bool FoundTemplate = false;
  2336. bool FoundStringTemplate = false;
  2337. bool FoundExactMatch = false;
  2338. while (F.hasNext()) {
  2339. Decl *D = F.next();
  2340. if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
  2341. D = USD->getTargetDecl();
  2342. // If the declaration we found is invalid, skip it.
  2343. if (D->isInvalidDecl()) {
  2344. F.erase();
  2345. continue;
  2346. }
  2347. bool IsRaw = false;
  2348. bool IsTemplate = false;
  2349. bool IsStringTemplate = false;
  2350. bool IsExactMatch = false;
  2351. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  2352. if (FD->getNumParams() == 1 &&
  2353. FD->getParamDecl(0)->getType()->getAs<PointerType>())
  2354. IsRaw = true;
  2355. else if (FD->getNumParams() == ArgTys.size()) {
  2356. IsExactMatch = true;
  2357. for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
  2358. QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
  2359. if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
  2360. IsExactMatch = false;
  2361. break;
  2362. }
  2363. }
  2364. }
  2365. }
  2366. if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
  2367. TemplateParameterList *Params = FD->getTemplateParameters();
  2368. if (Params->size() == 1)
  2369. IsTemplate = true;
  2370. else
  2371. IsStringTemplate = true;
  2372. }
  2373. if (IsExactMatch) {
  2374. FoundExactMatch = true;
  2375. AllowRaw = false;
  2376. AllowTemplate = false;
  2377. AllowStringTemplate = false;
  2378. if (FoundRaw || FoundTemplate || FoundStringTemplate) {
  2379. // Go through again and remove the raw and template decls we've
  2380. // already found.
  2381. F.restart();
  2382. FoundRaw = FoundTemplate = FoundStringTemplate = false;
  2383. }
  2384. } else if (AllowRaw && IsRaw) {
  2385. FoundRaw = true;
  2386. } else if (AllowTemplate && IsTemplate) {
  2387. FoundTemplate = true;
  2388. } else if (AllowStringTemplate && IsStringTemplate) {
  2389. FoundStringTemplate = true;
  2390. } else {
  2391. F.erase();
  2392. }
  2393. }
  2394. F.done();
  2395. // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
  2396. // parameter type, that is used in preference to a raw literal operator
  2397. // or literal operator template.
  2398. if (FoundExactMatch)
  2399. return LOLR_Cooked;
  2400. // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
  2401. // operator template, but not both.
  2402. if (FoundRaw && FoundTemplate) {
  2403. Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
  2404. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
  2405. NoteOverloadCandidate((*I)->getUnderlyingDecl()->getAsFunction());
  2406. return LOLR_Error;
  2407. }
  2408. if (FoundRaw)
  2409. return LOLR_Raw;
  2410. if (FoundTemplate)
  2411. return LOLR_Template;
  2412. if (FoundStringTemplate)
  2413. return LOLR_StringTemplate;
  2414. // Didn't find anything we could use.
  2415. Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
  2416. << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
  2417. << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
  2418. << (AllowTemplate || AllowStringTemplate);
  2419. return LOLR_Error;
  2420. }
  2421. void ADLResult::insert(NamedDecl *New) {
  2422. NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
  2423. // If we haven't yet seen a decl for this key, or the last decl
  2424. // was exactly this one, we're done.
  2425. if (Old == nullptr || Old == New) {
  2426. Old = New;
  2427. return;
  2428. }
  2429. // Otherwise, decide which is a more recent redeclaration.
  2430. FunctionDecl *OldFD = Old->getAsFunction();
  2431. FunctionDecl *NewFD = New->getAsFunction();
  2432. FunctionDecl *Cursor = NewFD;
  2433. while (true) {
  2434. Cursor = Cursor->getPreviousDecl();
  2435. // If we got to the end without finding OldFD, OldFD is the newer
  2436. // declaration; leave things as they are.
  2437. if (!Cursor) return;
  2438. // If we do find OldFD, then NewFD is newer.
  2439. if (Cursor == OldFD) break;
  2440. // Otherwise, keep looking.
  2441. }
  2442. Old = New;
  2443. }
  2444. void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
  2445. ArrayRef<Expr *> Args, ADLResult &Result) {
  2446. // Find all of the associated namespaces and classes based on the
  2447. // arguments we have.
  2448. AssociatedNamespaceSet AssociatedNamespaces;
  2449. AssociatedClassSet AssociatedClasses;
  2450. FindAssociatedClassesAndNamespaces(Loc, Args,
  2451. AssociatedNamespaces,
  2452. AssociatedClasses);
  2453. // C++ [basic.lookup.argdep]p3:
  2454. // Let X be the lookup set produced by unqualified lookup (3.4.1)
  2455. // and let Y be the lookup set produced by argument dependent
  2456. // lookup (defined as follows). If X contains [...] then Y is
  2457. // empty. Otherwise Y is the set of declarations found in the
  2458. // namespaces associated with the argument types as described
  2459. // below. The set of declarations found by the lookup of the name
  2460. // is the union of X and Y.
  2461. //
  2462. // Here, we compute Y and add its members to the overloaded
  2463. // candidate set.
  2464. for (auto *NS : AssociatedNamespaces) {
  2465. // When considering an associated namespace, the lookup is the
  2466. // same as the lookup performed when the associated namespace is
  2467. // used as a qualifier (3.4.3.2) except that:
  2468. //
  2469. // -- Any using-directives in the associated namespace are
  2470. // ignored.
  2471. //
  2472. // -- Any namespace-scope friend functions declared in
  2473. // associated classes are visible within their respective
  2474. // namespaces even if they are not visible during an ordinary
  2475. // lookup (11.4).
  2476. DeclContext::lookup_result R = NS->lookup(Name);
  2477. for (auto *D : R) {
  2478. // If the only declaration here is an ordinary friend, consider
  2479. // it only if it was declared in an associated classes.
  2480. if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
  2481. // If it's neither ordinarily visible nor a friend, we can't find it.
  2482. if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
  2483. continue;
  2484. bool DeclaredInAssociatedClass = false;
  2485. for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
  2486. DeclContext *LexDC = DI->getLexicalDeclContext();
  2487. if (isa<CXXRecordDecl>(LexDC) &&
  2488. AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
  2489. DeclaredInAssociatedClass = true;
  2490. break;
  2491. }
  2492. }
  2493. if (!DeclaredInAssociatedClass)
  2494. continue;
  2495. }
  2496. if (isa<UsingShadowDecl>(D))
  2497. D = cast<UsingShadowDecl>(D)->getTargetDecl();
  2498. if (!isa<FunctionDecl>(D) && !isa<FunctionTemplateDecl>(D))
  2499. continue;
  2500. Result.insert(D);
  2501. }
  2502. }
  2503. }
  2504. //----------------------------------------------------------------------------
  2505. // Search for all visible declarations.
  2506. //----------------------------------------------------------------------------
  2507. VisibleDeclConsumer::~VisibleDeclConsumer() { }
  2508. bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
  2509. namespace {
  2510. class ShadowContextRAII;
  2511. class VisibleDeclsRecord {
  2512. public:
  2513. /// \brief An entry in the shadow map, which is optimized to store a
  2514. /// single declaration (the common case) but can also store a list
  2515. /// of declarations.
  2516. typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
  2517. private:
  2518. /// \brief A mapping from declaration names to the declarations that have
  2519. /// this name within a particular scope.
  2520. typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
  2521. /// \brief A list of shadow maps, which is used to model name hiding.
  2522. std::list<ShadowMap> ShadowMaps;
  2523. /// \brief The declaration contexts we have already visited.
  2524. llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
  2525. friend class ShadowContextRAII;
  2526. public:
  2527. /// \brief Determine whether we have already visited this context
  2528. /// (and, if not, note that we are going to visit that context now).
  2529. bool visitedContext(DeclContext *Ctx) {
  2530. return !VisitedContexts.insert(Ctx).second;
  2531. }
  2532. bool alreadyVisitedContext(DeclContext *Ctx) {
  2533. return VisitedContexts.count(Ctx);
  2534. }
  2535. /// \brief Determine whether the given declaration is hidden in the
  2536. /// current scope.
  2537. ///
  2538. /// \returns the declaration that hides the given declaration, or
  2539. /// NULL if no such declaration exists.
  2540. NamedDecl *checkHidden(NamedDecl *ND);
  2541. /// \brief Add a declaration to the current shadow map.
  2542. void add(NamedDecl *ND) {
  2543. ShadowMaps.back()[ND->getDeclName()].push_back(ND);
  2544. }
  2545. };
  2546. /// \brief RAII object that records when we've entered a shadow context.
  2547. class ShadowContextRAII {
  2548. VisibleDeclsRecord &Visible;
  2549. typedef VisibleDeclsRecord::ShadowMap ShadowMap;
  2550. public:
  2551. ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
  2552. Visible.ShadowMaps.push_back(ShadowMap());
  2553. }
  2554. ~ShadowContextRAII() {
  2555. Visible.ShadowMaps.pop_back();
  2556. }
  2557. };
  2558. } // end anonymous namespace
  2559. NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
  2560. // Look through using declarations.
  2561. ND = ND->getUnderlyingDecl();
  2562. unsigned IDNS = ND->getIdentifierNamespace();
  2563. std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
  2564. for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
  2565. SM != SMEnd; ++SM) {
  2566. ShadowMap::iterator Pos = SM->find(ND->getDeclName());
  2567. if (Pos == SM->end())
  2568. continue;
  2569. for (auto *D : Pos->second) {
  2570. // A tag declaration does not hide a non-tag declaration.
  2571. if (D->hasTagIdentifierNamespace() &&
  2572. (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
  2573. Decl::IDNS_ObjCProtocol)))
  2574. continue;
  2575. // Protocols are in distinct namespaces from everything else.
  2576. if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
  2577. || (IDNS & Decl::IDNS_ObjCProtocol)) &&
  2578. D->getIdentifierNamespace() != IDNS)
  2579. continue;
  2580. // Functions and function templates in the same scope overload
  2581. // rather than hide. FIXME: Look for hiding based on function
  2582. // signatures!
  2583. if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
  2584. ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
  2585. SM == ShadowMaps.rbegin())
  2586. continue;
  2587. // We've found a declaration that hides this one.
  2588. return D;
  2589. }
  2590. }
  2591. return nullptr;
  2592. }
  2593. static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
  2594. bool QualifiedNameLookup,
  2595. bool InBaseClass,
  2596. VisibleDeclConsumer &Consumer,
  2597. VisibleDeclsRecord &Visited) {
  2598. if (!Ctx)
  2599. return;
  2600. // Make sure we don't visit the same context twice.
  2601. if (Visited.visitedContext(Ctx->getPrimaryContext()))
  2602. return;
  2603. if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
  2604. Result.getSema().ForceDeclarationOfImplicitMembers(Class);
  2605. // Enumerate all of the results in this context.
  2606. for (const auto &R : Ctx->lookups()) {
  2607. for (auto *I : R) {
  2608. if (NamedDecl *ND = dyn_cast<NamedDecl>(I)) {
  2609. if ((ND = Result.getAcceptableDecl(ND))) {
  2610. Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
  2611. Visited.add(ND);
  2612. }
  2613. }
  2614. }
  2615. }
  2616. // Traverse using directives for qualified name lookup.
  2617. if (QualifiedNameLookup) {
  2618. ShadowContextRAII Shadow(Visited);
  2619. for (auto I : Ctx->using_directives()) {
  2620. LookupVisibleDecls(I->getNominatedNamespace(), Result,
  2621. QualifiedNameLookup, InBaseClass, Consumer, Visited);
  2622. }
  2623. }
  2624. // Traverse the contexts of inherited C++ classes.
  2625. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
  2626. if (!Record->hasDefinition())
  2627. return;
  2628. for (const auto &B : Record->bases()) {
  2629. QualType BaseType = B.getType();
  2630. // Don't look into dependent bases, because name lookup can't look
  2631. // there anyway.
  2632. if (BaseType->isDependentType())
  2633. continue;
  2634. const RecordType *Record = BaseType->getAs<RecordType>();
  2635. if (!Record)
  2636. continue;
  2637. // FIXME: It would be nice to be able to determine whether referencing
  2638. // a particular member would be ambiguous. For example, given
  2639. //
  2640. // struct A { int member; };
  2641. // struct B { int member; };
  2642. // struct C : A, B { };
  2643. //
  2644. // void f(C *c) { c->### }
  2645. //
  2646. // accessing 'member' would result in an ambiguity. However, we
  2647. // could be smart enough to qualify the member with the base
  2648. // class, e.g.,
  2649. //
  2650. // c->B::member
  2651. //
  2652. // or
  2653. //
  2654. // c->A::member
  2655. // Find results in this base class (and its bases).
  2656. ShadowContextRAII Shadow(Visited);
  2657. LookupVisibleDecls(Record->getDecl(), Result, QualifiedNameLookup,
  2658. true, Consumer, Visited);
  2659. }
  2660. }
  2661. // Traverse the contexts of Objective-C classes.
  2662. if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
  2663. // Traverse categories.
  2664. for (auto *Cat : IFace->visible_categories()) {
  2665. ShadowContextRAII Shadow(Visited);
  2666. LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
  2667. Consumer, Visited);
  2668. }
  2669. // Traverse protocols.
  2670. for (auto *I : IFace->all_referenced_protocols()) {
  2671. ShadowContextRAII Shadow(Visited);
  2672. LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
  2673. Visited);
  2674. }
  2675. // Traverse the superclass.
  2676. if (IFace->getSuperClass()) {
  2677. ShadowContextRAII Shadow(Visited);
  2678. LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
  2679. true, Consumer, Visited);
  2680. }
  2681. // If there is an implementation, traverse it. We do this to find
  2682. // synthesized ivars.
  2683. if (IFace->getImplementation()) {
  2684. ShadowContextRAII Shadow(Visited);
  2685. LookupVisibleDecls(IFace->getImplementation(), Result,
  2686. QualifiedNameLookup, InBaseClass, Consumer, Visited);
  2687. }
  2688. } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
  2689. for (auto *I : Protocol->protocols()) {
  2690. ShadowContextRAII Shadow(Visited);
  2691. LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
  2692. Visited);
  2693. }
  2694. } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
  2695. for (auto *I : Category->protocols()) {
  2696. ShadowContextRAII Shadow(Visited);
  2697. LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
  2698. Visited);
  2699. }
  2700. // If there is an implementation, traverse it.
  2701. if (Category->getImplementation()) {
  2702. ShadowContextRAII Shadow(Visited);
  2703. LookupVisibleDecls(Category->getImplementation(), Result,
  2704. QualifiedNameLookup, true, Consumer, Visited);
  2705. }
  2706. }
  2707. }
  2708. static void LookupVisibleDecls(Scope *S, LookupResult &Result,
  2709. UnqualUsingDirectiveSet &UDirs,
  2710. VisibleDeclConsumer &Consumer,
  2711. VisibleDeclsRecord &Visited) {
  2712. if (!S)
  2713. return;
  2714. if (!S->getEntity() ||
  2715. (!S->getParent() &&
  2716. !Visited.alreadyVisitedContext(S->getEntity())) ||
  2717. (S->getEntity())->isFunctionOrMethod()) {
  2718. FindLocalExternScope FindLocals(Result);
  2719. // Walk through the declarations in this Scope.
  2720. for (auto *D : S->decls()) {
  2721. if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
  2722. if ((ND = Result.getAcceptableDecl(ND))) {
  2723. Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
  2724. Visited.add(ND);
  2725. }
  2726. }
  2727. }
  2728. // FIXME: C++ [temp.local]p8
  2729. DeclContext *Entity = nullptr;
  2730. if (S->getEntity()) {
  2731. // Look into this scope's declaration context, along with any of its
  2732. // parent lookup contexts (e.g., enclosing classes), up to the point
  2733. // where we hit the context stored in the next outer scope.
  2734. Entity = S->getEntity();
  2735. DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
  2736. for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
  2737. Ctx = Ctx->getLookupParent()) {
  2738. if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
  2739. if (Method->isInstanceMethod()) {
  2740. // For instance methods, look for ivars in the method's interface.
  2741. LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
  2742. Result.getNameLoc(), Sema::LookupMemberName);
  2743. if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
  2744. LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
  2745. /*InBaseClass=*/false, Consumer, Visited);
  2746. }
  2747. }
  2748. // We've already performed all of the name lookup that we need
  2749. // to for Objective-C methods; the next context will be the
  2750. // outer scope.
  2751. break;
  2752. }
  2753. if (Ctx->isFunctionOrMethod())
  2754. continue;
  2755. LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
  2756. /*InBaseClass=*/false, Consumer, Visited);
  2757. }
  2758. } else if (!S->getParent()) {
  2759. // Look into the translation unit scope. We walk through the translation
  2760. // unit's declaration context, because the Scope itself won't have all of
  2761. // the declarations if we loaded a precompiled header.
  2762. // FIXME: We would like the translation unit's Scope object to point to the
  2763. // translation unit, so we don't need this special "if" branch. However,
  2764. // doing so would force the normal C++ name-lookup code to look into the
  2765. // translation unit decl when the IdentifierInfo chains would suffice.
  2766. // Once we fix that problem (which is part of a more general "don't look
  2767. // in DeclContexts unless we have to" optimization), we can eliminate this.
  2768. Entity = Result.getSema().Context.getTranslationUnitDecl();
  2769. LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
  2770. /*InBaseClass=*/false, Consumer, Visited);
  2771. }
  2772. if (Entity) {
  2773. // Lookup visible declarations in any namespaces found by using
  2774. // directives.
  2775. for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
  2776. LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
  2777. Result, /*QualifiedNameLookup=*/false,
  2778. /*InBaseClass=*/false, Consumer, Visited);
  2779. }
  2780. // Lookup names in the parent scope.
  2781. ShadowContextRAII Shadow(Visited);
  2782. LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
  2783. }
  2784. void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
  2785. VisibleDeclConsumer &Consumer,
  2786. bool IncludeGlobalScope) {
  2787. // Determine the set of using directives available during
  2788. // unqualified name lookup.
  2789. Scope *Initial = S;
  2790. UnqualUsingDirectiveSet UDirs;
  2791. if (getLangOpts().CPlusPlus) {
  2792. // Find the first namespace or translation-unit scope.
  2793. while (S && !isNamespaceOrTranslationUnitScope(S))
  2794. S = S->getParent();
  2795. UDirs.visitScopeChain(Initial, S);
  2796. }
  2797. UDirs.done();
  2798. // Look for visible declarations.
  2799. LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
  2800. Result.setAllowHidden(Consumer.includeHiddenDecls());
  2801. VisibleDeclsRecord Visited;
  2802. if (!IncludeGlobalScope)
  2803. Visited.visitedContext(Context.getTranslationUnitDecl());
  2804. ShadowContextRAII Shadow(Visited);
  2805. ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
  2806. }
  2807. void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
  2808. VisibleDeclConsumer &Consumer,
  2809. bool IncludeGlobalScope) {
  2810. LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
  2811. Result.setAllowHidden(Consumer.includeHiddenDecls());
  2812. VisibleDeclsRecord Visited;
  2813. if (!IncludeGlobalScope)
  2814. Visited.visitedContext(Context.getTranslationUnitDecl());
  2815. ShadowContextRAII Shadow(Visited);
  2816. ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
  2817. /*InBaseClass=*/false, Consumer, Visited);
  2818. }
  2819. /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
  2820. /// If GnuLabelLoc is a valid source location, then this is a definition
  2821. /// of an __label__ label name, otherwise it is a normal label definition
  2822. /// or use.
  2823. LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
  2824. SourceLocation GnuLabelLoc) {
  2825. // Do a lookup to see if we have a label with this name already.
  2826. NamedDecl *Res = nullptr;
  2827. if (GnuLabelLoc.isValid()) {
  2828. // Local label definitions always shadow existing labels.
  2829. Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
  2830. Scope *S = CurScope;
  2831. PushOnScopeChains(Res, S, true);
  2832. return cast<LabelDecl>(Res);
  2833. }
  2834. // Not a GNU local label.
  2835. Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
  2836. // If we found a label, check to see if it is in the same context as us.
  2837. // When in a Block, we don't want to reuse a label in an enclosing function.
  2838. if (Res && Res->getDeclContext() != CurContext)
  2839. Res = nullptr;
  2840. if (!Res) {
  2841. // If not forward referenced or defined already, create the backing decl.
  2842. Res = LabelDecl::Create(Context, CurContext, Loc, II);
  2843. Scope *S = CurScope->getFnParent();
  2844. assert(S && "Not in a function?");
  2845. PushOnScopeChains(Res, S, true);
  2846. }
  2847. return cast<LabelDecl>(Res);
  2848. }
  2849. //===----------------------------------------------------------------------===//
  2850. // Typo correction
  2851. //===----------------------------------------------------------------------===//
  2852. static bool isCandidateViable(CorrectionCandidateCallback &CCC,
  2853. TypoCorrection &Candidate) {
  2854. Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
  2855. return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
  2856. }
  2857. static void LookupPotentialTypoResult(Sema &SemaRef,
  2858. LookupResult &Res,
  2859. IdentifierInfo *Name,
  2860. Scope *S, CXXScopeSpec *SS,
  2861. DeclContext *MemberContext,
  2862. bool EnteringContext,
  2863. bool isObjCIvarLookup,
  2864. bool FindHidden);
  2865. /// \brief Check whether the declarations found for a typo correction are
  2866. /// visible, and if none of them are, convert the correction to an 'import
  2867. /// a module' correction.
  2868. static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
  2869. if (TC.begin() == TC.end())
  2870. return;
  2871. TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
  2872. for (/**/; DI != DE; ++DI)
  2873. if (!LookupResult::isVisible(SemaRef, *DI))
  2874. break;
  2875. // Nothing to do if all decls are visible.
  2876. if (DI == DE)
  2877. return;
  2878. llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
  2879. bool AnyVisibleDecls = !NewDecls.empty();
  2880. for (/**/; DI != DE; ++DI) {
  2881. NamedDecl *VisibleDecl = *DI;
  2882. if (!LookupResult::isVisible(SemaRef, *DI))
  2883. VisibleDecl = findAcceptableDecl(SemaRef, *DI);
  2884. if (VisibleDecl) {
  2885. if (!AnyVisibleDecls) {
  2886. // Found a visible decl, discard all hidden ones.
  2887. AnyVisibleDecls = true;
  2888. NewDecls.clear();
  2889. }
  2890. NewDecls.push_back(VisibleDecl);
  2891. } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
  2892. NewDecls.push_back(*DI);
  2893. }
  2894. if (NewDecls.empty())
  2895. TC = TypoCorrection();
  2896. else {
  2897. TC.setCorrectionDecls(NewDecls);
  2898. TC.setRequiresImport(!AnyVisibleDecls);
  2899. }
  2900. }
  2901. // Fill the supplied vector with the IdentifierInfo pointers for each piece of
  2902. // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
  2903. // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
  2904. static void getNestedNameSpecifierIdentifiers(
  2905. NestedNameSpecifier *NNS,
  2906. SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
  2907. if (NestedNameSpecifier *Prefix = NNS->getPrefix())
  2908. getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
  2909. else
  2910. Identifiers.clear();
  2911. const IdentifierInfo *II = nullptr;
  2912. switch (NNS->getKind()) {
  2913. case NestedNameSpecifier::Identifier:
  2914. II = NNS->getAsIdentifier();
  2915. break;
  2916. case NestedNameSpecifier::Namespace:
  2917. if (NNS->getAsNamespace()->isAnonymousNamespace())
  2918. return;
  2919. II = NNS->getAsNamespace()->getIdentifier();
  2920. break;
  2921. case NestedNameSpecifier::NamespaceAlias:
  2922. II = NNS->getAsNamespaceAlias()->getIdentifier();
  2923. break;
  2924. case NestedNameSpecifier::TypeSpecWithTemplate:
  2925. case NestedNameSpecifier::TypeSpec:
  2926. II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
  2927. break;
  2928. case NestedNameSpecifier::Global:
  2929. case NestedNameSpecifier::Super:
  2930. return;
  2931. }
  2932. if (II)
  2933. Identifiers.push_back(II);
  2934. }
  2935. void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
  2936. DeclContext *Ctx, bool InBaseClass) {
  2937. // Don't consider hidden names for typo correction.
  2938. if (Hiding)
  2939. return;
  2940. // Only consider entities with identifiers for names, ignoring
  2941. // special names (constructors, overloaded operators, selectors,
  2942. // etc.).
  2943. IdentifierInfo *Name = ND->getIdentifier();
  2944. if (!Name)
  2945. return;
  2946. // Only consider visible declarations and declarations from modules with
  2947. // names that exactly match.
  2948. if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
  2949. !findAcceptableDecl(SemaRef, ND))
  2950. return;
  2951. FoundName(Name->getName());
  2952. }
  2953. void TypoCorrectionConsumer::FoundName(StringRef Name) {
  2954. // Compute the edit distance between the typo and the name of this
  2955. // entity, and add the identifier to the list of results.
  2956. addName(Name, nullptr);
  2957. }
  2958. void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
  2959. // Compute the edit distance between the typo and this keyword,
  2960. // and add the keyword to the list of results.
  2961. addName(Keyword, nullptr, nullptr, true);
  2962. }
  2963. void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
  2964. NestedNameSpecifier *NNS, bool isKeyword) {
  2965. // Use a simple length-based heuristic to determine the minimum possible
  2966. // edit distance. If the minimum isn't good enough, bail out early.
  2967. StringRef TypoStr = Typo->getName();
  2968. unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
  2969. if (MinED && TypoStr.size() / MinED < 3)
  2970. return;
  2971. // Compute an upper bound on the allowable edit distance, so that the
  2972. // edit-distance algorithm can short-circuit.
  2973. unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
  2974. unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
  2975. if (ED >= UpperBound) return;
  2976. TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
  2977. if (isKeyword) TC.makeKeyword();
  2978. TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
  2979. addCorrection(TC);
  2980. }
  2981. static const unsigned MaxTypoDistanceResultSets = 5;
  2982. void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
  2983. StringRef TypoStr = Typo->getName();
  2984. StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
  2985. // For very short typos, ignore potential corrections that have a different
  2986. // base identifier from the typo or which have a normalized edit distance
  2987. // longer than the typo itself.
  2988. if (TypoStr.size() < 3 &&
  2989. (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
  2990. return;
  2991. // If the correction is resolved but is not viable, ignore it.
  2992. if (Correction.isResolved()) {
  2993. checkCorrectionVisibility(SemaRef, Correction);
  2994. if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
  2995. return;
  2996. }
  2997. TypoResultList &CList =
  2998. CorrectionResults[Correction.getEditDistance(false)][Name];
  2999. if (!CList.empty() && !CList.back().isResolved())
  3000. CList.pop_back();
  3001. if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
  3002. std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
  3003. for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
  3004. RI != RIEnd; ++RI) {
  3005. // If the Correction refers to a decl already in the result list,
  3006. // replace the existing result if the string representation of Correction
  3007. // comes before the current result alphabetically, then stop as there is
  3008. // nothing more to be done to add Correction to the candidate set.
  3009. if (RI->getCorrectionDecl() == NewND) {
  3010. if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
  3011. *RI = Correction;
  3012. return;
  3013. }
  3014. }
  3015. }
  3016. if (CList.empty() || Correction.isResolved())
  3017. CList.push_back(Correction);
  3018. while (CorrectionResults.size() > MaxTypoDistanceResultSets)
  3019. CorrectionResults.erase(std::prev(CorrectionResults.end()));
  3020. }
  3021. void TypoCorrectionConsumer::addNamespaces(
  3022. const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
  3023. SearchNamespaces = true;
  3024. for (auto KNPair : KnownNamespaces)
  3025. Namespaces.addNameSpecifier(KNPair.first);
  3026. bool SSIsTemplate = false;
  3027. if (NestedNameSpecifier *NNS =
  3028. (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
  3029. if (const Type *T = NNS->getAsType())
  3030. SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
  3031. }
  3032. for (const auto *TI : SemaRef.getASTContext().types()) {
  3033. if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
  3034. CD = CD->getCanonicalDecl();
  3035. if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
  3036. !CD->isUnion() && CD->getIdentifier() &&
  3037. (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
  3038. (CD->isBeingDefined() || CD->isCompleteDefinition()))
  3039. Namespaces.addNameSpecifier(CD);
  3040. }
  3041. }
  3042. }
  3043. const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
  3044. if (++CurrentTCIndex < ValidatedCorrections.size())
  3045. return ValidatedCorrections[CurrentTCIndex];
  3046. CurrentTCIndex = ValidatedCorrections.size();
  3047. while (!CorrectionResults.empty()) {
  3048. auto DI = CorrectionResults.begin();
  3049. if (DI->second.empty()) {
  3050. CorrectionResults.erase(DI);
  3051. continue;
  3052. }
  3053. auto RI = DI->second.begin();
  3054. if (RI->second.empty()) {
  3055. DI->second.erase(RI);
  3056. performQualifiedLookups();
  3057. continue;
  3058. }
  3059. TypoCorrection TC = RI->second.pop_back_val();
  3060. if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
  3061. ValidatedCorrections.push_back(TC);
  3062. return ValidatedCorrections[CurrentTCIndex];
  3063. }
  3064. }
  3065. return ValidatedCorrections[0]; // The empty correction.
  3066. }
  3067. bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
  3068. IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
  3069. DeclContext *TempMemberContext = MemberContext;
  3070. CXXScopeSpec *TempSS = SS.get();
  3071. retry_lookup:
  3072. LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
  3073. EnteringContext,
  3074. CorrectionValidator->IsObjCIvarLookup,
  3075. Name == Typo && !Candidate.WillReplaceSpecifier());
  3076. switch (Result.getResultKind()) {
  3077. case LookupResult::NotFound:
  3078. case LookupResult::NotFoundInCurrentInstantiation:
  3079. case LookupResult::FoundUnresolvedValue:
  3080. if (TempSS) {
  3081. // Immediately retry the lookup without the given CXXScopeSpec
  3082. TempSS = nullptr;
  3083. Candidate.WillReplaceSpecifier(true);
  3084. goto retry_lookup;
  3085. }
  3086. if (TempMemberContext) {
  3087. if (SS && !TempSS)
  3088. TempSS = SS.get();
  3089. TempMemberContext = nullptr;
  3090. goto retry_lookup;
  3091. }
  3092. if (SearchNamespaces)
  3093. QualifiedResults.push_back(Candidate);
  3094. break;
  3095. case LookupResult::Ambiguous:
  3096. // We don't deal with ambiguities.
  3097. break;
  3098. case LookupResult::Found:
  3099. case LookupResult::FoundOverloaded:
  3100. // Store all of the Decls for overloaded symbols
  3101. for (auto *TRD : Result)
  3102. Candidate.addCorrectionDecl(TRD);
  3103. checkCorrectionVisibility(SemaRef, Candidate);
  3104. if (!isCandidateViable(*CorrectionValidator, Candidate)) {
  3105. if (SearchNamespaces)
  3106. QualifiedResults.push_back(Candidate);
  3107. break;
  3108. }
  3109. Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
  3110. return true;
  3111. }
  3112. return false;
  3113. }
  3114. void TypoCorrectionConsumer::performQualifiedLookups() {
  3115. unsigned TypoLen = Typo->getName().size();
  3116. for (auto QR : QualifiedResults) {
  3117. for (auto NSI : Namespaces) {
  3118. DeclContext *Ctx = NSI.DeclCtx;
  3119. const Type *NSType = NSI.NameSpecifier->getAsType();
  3120. // If the current NestedNameSpecifier refers to a class and the
  3121. // current correction candidate is the name of that class, then skip
  3122. // it as it is unlikely a qualified version of the class' constructor
  3123. // is an appropriate correction.
  3124. if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : 0) {
  3125. if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
  3126. continue;
  3127. }
  3128. TypoCorrection TC(QR);
  3129. TC.ClearCorrectionDecls();
  3130. TC.setCorrectionSpecifier(NSI.NameSpecifier);
  3131. TC.setQualifierDistance(NSI.EditDistance);
  3132. TC.setCallbackDistance(0); // Reset the callback distance
  3133. // If the current correction candidate and namespace combination are
  3134. // too far away from the original typo based on the normalized edit
  3135. // distance, then skip performing a qualified name lookup.
  3136. unsigned TmpED = TC.getEditDistance(true);
  3137. if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
  3138. TypoLen / TmpED < 3)
  3139. continue;
  3140. Result.clear();
  3141. Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
  3142. if (!SemaRef.LookupQualifiedName(Result, Ctx))
  3143. continue;
  3144. // Any corrections added below will be validated in subsequent
  3145. // iterations of the main while() loop over the Consumer's contents.
  3146. switch (Result.getResultKind()) {
  3147. case LookupResult::Found:
  3148. case LookupResult::FoundOverloaded: {
  3149. if (SS && SS->isValid()) {
  3150. std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
  3151. std::string OldQualified;
  3152. llvm::raw_string_ostream OldOStream(OldQualified);
  3153. SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
  3154. OldOStream << Typo->getName();
  3155. // If correction candidate would be an identical written qualified
  3156. // identifer, then the existing CXXScopeSpec probably included a
  3157. // typedef that didn't get accounted for properly.
  3158. if (OldOStream.str() == NewQualified)
  3159. break;
  3160. }
  3161. for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
  3162. TRD != TRDEnd; ++TRD) {
  3163. if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
  3164. NSType ? NSType->getAsCXXRecordDecl()
  3165. : nullptr,
  3166. TRD.getPair()) == Sema::AR_accessible)
  3167. TC.addCorrectionDecl(*TRD);
  3168. }
  3169. if (TC.isResolved()) {
  3170. TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
  3171. addCorrection(TC);
  3172. }
  3173. break;
  3174. }
  3175. case LookupResult::NotFound:
  3176. case LookupResult::NotFoundInCurrentInstantiation:
  3177. case LookupResult::Ambiguous:
  3178. case LookupResult::FoundUnresolvedValue:
  3179. break;
  3180. }
  3181. }
  3182. }
  3183. QualifiedResults.clear();
  3184. }
  3185. TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
  3186. ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
  3187. : Context(Context), CurContextChain(buildContextChain(CurContext)) {
  3188. if (NestedNameSpecifier *NNS =
  3189. CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
  3190. llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
  3191. NNS->print(SpecifierOStream, Context.getPrintingPolicy());
  3192. getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
  3193. }
  3194. // Build the list of identifiers that would be used for an absolute
  3195. // (from the global context) NestedNameSpecifier referring to the current
  3196. // context.
  3197. for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
  3198. CEnd = CurContextChain.rend();
  3199. C != CEnd; ++C) {
  3200. if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C))
  3201. CurContextIdentifiers.push_back(ND->getIdentifier());
  3202. }
  3203. // Add the global context as a NestedNameSpecifier
  3204. SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
  3205. NestedNameSpecifier::GlobalSpecifier(Context), 1};
  3206. DistanceMap[1].push_back(SI);
  3207. }
  3208. auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
  3209. DeclContext *Start) -> DeclContextList {
  3210. assert(Start && "Building a context chain from a null context");
  3211. DeclContextList Chain;
  3212. for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
  3213. DC = DC->getLookupParent()) {
  3214. NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
  3215. if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
  3216. !(ND && ND->isAnonymousNamespace()))
  3217. Chain.push_back(DC->getPrimaryContext());
  3218. }
  3219. return Chain;
  3220. }
  3221. unsigned
  3222. TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
  3223. DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
  3224. unsigned NumSpecifiers = 0;
  3225. for (DeclContextList::reverse_iterator C = DeclChain.rbegin(),
  3226. CEnd = DeclChain.rend();
  3227. C != CEnd; ++C) {
  3228. if (NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(*C)) {
  3229. NNS = NestedNameSpecifier::Create(Context, NNS, ND);
  3230. ++NumSpecifiers;
  3231. } else if (RecordDecl *RD = dyn_cast_or_null<RecordDecl>(*C)) {
  3232. NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
  3233. RD->getTypeForDecl());
  3234. ++NumSpecifiers;
  3235. }
  3236. }
  3237. return NumSpecifiers;
  3238. }
  3239. void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
  3240. DeclContext *Ctx) {
  3241. NestedNameSpecifier *NNS = nullptr;
  3242. unsigned NumSpecifiers = 0;
  3243. DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
  3244. DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
  3245. // Eliminate common elements from the two DeclContext chains.
  3246. for (DeclContextList::reverse_iterator C = CurContextChain.rbegin(),
  3247. CEnd = CurContextChain.rend();
  3248. C != CEnd && !NamespaceDeclChain.empty() &&
  3249. NamespaceDeclChain.back() == *C; ++C) {
  3250. NamespaceDeclChain.pop_back();
  3251. }
  3252. // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
  3253. NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
  3254. // Add an explicit leading '::' specifier if needed.
  3255. if (NamespaceDeclChain.empty()) {
  3256. // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
  3257. NNS = NestedNameSpecifier::GlobalSpecifier(Context);
  3258. NumSpecifiers =
  3259. buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
  3260. } else if (NamedDecl *ND =
  3261. dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
  3262. IdentifierInfo *Name = ND->getIdentifier();
  3263. bool SameNameSpecifier = false;
  3264. if (std::find(CurNameSpecifierIdentifiers.begin(),
  3265. CurNameSpecifierIdentifiers.end(),
  3266. Name) != CurNameSpecifierIdentifiers.end()) {
  3267. std::string NewNameSpecifier;
  3268. llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
  3269. SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
  3270. getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
  3271. NNS->print(SpecifierOStream, Context.getPrintingPolicy());
  3272. SpecifierOStream.flush();
  3273. SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
  3274. }
  3275. if (SameNameSpecifier ||
  3276. std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
  3277. Name) != CurContextIdentifiers.end()) {
  3278. // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
  3279. NNS = NestedNameSpecifier::GlobalSpecifier(Context);
  3280. NumSpecifiers =
  3281. buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
  3282. }
  3283. }
  3284. // If the built NestedNameSpecifier would be replacing an existing
  3285. // NestedNameSpecifier, use the number of component identifiers that
  3286. // would need to be changed as the edit distance instead of the number
  3287. // of components in the built NestedNameSpecifier.
  3288. if (NNS && !CurNameSpecifierIdentifiers.empty()) {
  3289. SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
  3290. getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
  3291. NumSpecifiers = llvm::ComputeEditDistance(
  3292. llvm::makeArrayRef(CurNameSpecifierIdentifiers),
  3293. llvm::makeArrayRef(NewNameSpecifierIdentifiers));
  3294. }
  3295. SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
  3296. DistanceMap[NumSpecifiers].push_back(SI);
  3297. }
  3298. /// \brief Perform name lookup for a possible result for typo correction.
  3299. static void LookupPotentialTypoResult(Sema &SemaRef,
  3300. LookupResult &Res,
  3301. IdentifierInfo *Name,
  3302. Scope *S, CXXScopeSpec *SS,
  3303. DeclContext *MemberContext,
  3304. bool EnteringContext,
  3305. bool isObjCIvarLookup,
  3306. bool FindHidden) {
  3307. Res.suppressDiagnostics();
  3308. Res.clear();
  3309. Res.setLookupName(Name);
  3310. Res.setAllowHidden(FindHidden);
  3311. if (MemberContext) {
  3312. if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
  3313. if (isObjCIvarLookup) {
  3314. if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
  3315. Res.addDecl(Ivar);
  3316. Res.resolveKind();
  3317. return;
  3318. }
  3319. }
  3320. if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(Name)) {
  3321. Res.addDecl(Prop);
  3322. Res.resolveKind();
  3323. return;
  3324. }
  3325. }
  3326. SemaRef.LookupQualifiedName(Res, MemberContext);
  3327. return;
  3328. }
  3329. SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
  3330. EnteringContext);
  3331. // Fake ivar lookup; this should really be part of
  3332. // LookupParsedName.
  3333. if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
  3334. if (Method->isInstanceMethod() && Method->getClassInterface() &&
  3335. (Res.empty() ||
  3336. (Res.isSingleResult() &&
  3337. Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
  3338. if (ObjCIvarDecl *IV
  3339. = Method->getClassInterface()->lookupInstanceVariable(Name)) {
  3340. Res.addDecl(IV);
  3341. Res.resolveKind();
  3342. }
  3343. }
  3344. }
  3345. }
  3346. /// \brief Add keywords to the consumer as possible typo corrections.
  3347. static void AddKeywordsToConsumer(Sema &SemaRef,
  3348. TypoCorrectionConsumer &Consumer,
  3349. Scope *S, CorrectionCandidateCallback &CCC,
  3350. bool AfterNestedNameSpecifier) {
  3351. if (AfterNestedNameSpecifier) {
  3352. // For 'X::', we know exactly which keywords can appear next.
  3353. Consumer.addKeywordResult("template");
  3354. if (CCC.WantExpressionKeywords)
  3355. Consumer.addKeywordResult("operator");
  3356. return;
  3357. }
  3358. if (CCC.WantObjCSuper)
  3359. Consumer.addKeywordResult("super");
  3360. if (CCC.WantTypeSpecifiers) {
  3361. // Add type-specifier keywords to the set of results.
  3362. static const char *const CTypeSpecs[] = {
  3363. "char", "const", "double", "enum", "float", "int", "long", "short",
  3364. "signed", "struct", "union", "unsigned", "void", "volatile",
  3365. "_Complex", "_Imaginary",
  3366. // storage-specifiers as well
  3367. "extern", "inline", "static", "typedef"
  3368. };
  3369. const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
  3370. for (unsigned I = 0; I != NumCTypeSpecs; ++I)
  3371. Consumer.addKeywordResult(CTypeSpecs[I]);
  3372. if (SemaRef.getLangOpts().C99)
  3373. Consumer.addKeywordResult("restrict");
  3374. if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
  3375. Consumer.addKeywordResult("bool");
  3376. else if (SemaRef.getLangOpts().C99)
  3377. Consumer.addKeywordResult("_Bool");
  3378. if (SemaRef.getLangOpts().CPlusPlus) {
  3379. Consumer.addKeywordResult("class");
  3380. Consumer.addKeywordResult("typename");
  3381. Consumer.addKeywordResult("wchar_t");
  3382. if (SemaRef.getLangOpts().CPlusPlus11) {
  3383. Consumer.addKeywordResult("char16_t");
  3384. Consumer.addKeywordResult("char32_t");
  3385. Consumer.addKeywordResult("constexpr");
  3386. Consumer.addKeywordResult("decltype");
  3387. Consumer.addKeywordResult("thread_local");
  3388. }
  3389. }
  3390. if (SemaRef.getLangOpts().GNUMode)
  3391. Consumer.addKeywordResult("typeof");
  3392. } else if (CCC.WantFunctionLikeCasts) {
  3393. static const char *const CastableTypeSpecs[] = {
  3394. "char", "double", "float", "int", "long", "short",
  3395. "signed", "unsigned", "void"
  3396. };
  3397. for (auto *kw : CastableTypeSpecs)
  3398. Consumer.addKeywordResult(kw);
  3399. }
  3400. if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
  3401. Consumer.addKeywordResult("const_cast");
  3402. Consumer.addKeywordResult("dynamic_cast");
  3403. Consumer.addKeywordResult("reinterpret_cast");
  3404. Consumer.addKeywordResult("static_cast");
  3405. }
  3406. if (CCC.WantExpressionKeywords) {
  3407. Consumer.addKeywordResult("sizeof");
  3408. if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
  3409. Consumer.addKeywordResult("false");
  3410. Consumer.addKeywordResult("true");
  3411. }
  3412. if (SemaRef.getLangOpts().CPlusPlus) {
  3413. static const char *const CXXExprs[] = {
  3414. "delete", "new", "operator", "throw", "typeid"
  3415. };
  3416. const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
  3417. for (unsigned I = 0; I != NumCXXExprs; ++I)
  3418. Consumer.addKeywordResult(CXXExprs[I]);
  3419. if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
  3420. cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
  3421. Consumer.addKeywordResult("this");
  3422. if (SemaRef.getLangOpts().CPlusPlus11) {
  3423. Consumer.addKeywordResult("alignof");
  3424. Consumer.addKeywordResult("nullptr");
  3425. }
  3426. }
  3427. if (SemaRef.getLangOpts().C11) {
  3428. // FIXME: We should not suggest _Alignof if the alignof macro
  3429. // is present.
  3430. Consumer.addKeywordResult("_Alignof");
  3431. }
  3432. }
  3433. if (CCC.WantRemainingKeywords) {
  3434. if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
  3435. // Statements.
  3436. static const char *const CStmts[] = {
  3437. "do", "else", "for", "goto", "if", "return", "switch", "while" };
  3438. const unsigned NumCStmts = llvm::array_lengthof(CStmts);
  3439. for (unsigned I = 0; I != NumCStmts; ++I)
  3440. Consumer.addKeywordResult(CStmts[I]);
  3441. if (SemaRef.getLangOpts().CPlusPlus) {
  3442. Consumer.addKeywordResult("catch");
  3443. Consumer.addKeywordResult("try");
  3444. }
  3445. if (S && S->getBreakParent())
  3446. Consumer.addKeywordResult("break");
  3447. if (S && S->getContinueParent())
  3448. Consumer.addKeywordResult("continue");
  3449. if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
  3450. Consumer.addKeywordResult("case");
  3451. Consumer.addKeywordResult("default");
  3452. }
  3453. } else {
  3454. if (SemaRef.getLangOpts().CPlusPlus) {
  3455. Consumer.addKeywordResult("namespace");
  3456. Consumer.addKeywordResult("template");
  3457. }
  3458. if (S && S->isClassScope()) {
  3459. Consumer.addKeywordResult("explicit");
  3460. Consumer.addKeywordResult("friend");
  3461. Consumer.addKeywordResult("mutable");
  3462. Consumer.addKeywordResult("private");
  3463. Consumer.addKeywordResult("protected");
  3464. Consumer.addKeywordResult("public");
  3465. Consumer.addKeywordResult("virtual");
  3466. }
  3467. }
  3468. if (SemaRef.getLangOpts().CPlusPlus) {
  3469. Consumer.addKeywordResult("using");
  3470. if (SemaRef.getLangOpts().CPlusPlus11)
  3471. Consumer.addKeywordResult("static_assert");
  3472. }
  3473. }
  3474. }
  3475. std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
  3476. const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
  3477. Scope *S, CXXScopeSpec *SS,
  3478. std::unique_ptr<CorrectionCandidateCallback> CCC,
  3479. DeclContext *MemberContext, bool EnteringContext,
  3480. const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
  3481. if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
  3482. DisableTypoCorrection)
  3483. return nullptr;
  3484. // In Microsoft mode, don't perform typo correction in a template member
  3485. // function dependent context because it interferes with the "lookup into
  3486. // dependent bases of class templates" feature.
  3487. if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
  3488. isa<CXXMethodDecl>(CurContext))
  3489. return nullptr;
  3490. // We only attempt to correct typos for identifiers.
  3491. IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
  3492. if (!Typo)
  3493. return nullptr;
  3494. // If the scope specifier itself was invalid, don't try to correct
  3495. // typos.
  3496. if (SS && SS->isInvalid())
  3497. return nullptr;
  3498. // Never try to correct typos during template deduction or
  3499. // instantiation.
  3500. if (!ActiveTemplateInstantiations.empty())
  3501. return nullptr;
  3502. // Don't try to correct 'super'.
  3503. if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
  3504. return nullptr;
  3505. // Abort if typo correction already failed for this specific typo.
  3506. IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
  3507. if (locs != TypoCorrectionFailures.end() &&
  3508. locs->second.count(TypoName.getLoc()))
  3509. return nullptr;
  3510. // Don't try to correct the identifier "vector" when in AltiVec mode.
  3511. // TODO: Figure out why typo correction misbehaves in this case, fix it, and
  3512. // remove this workaround.
  3513. if (getLangOpts().AltiVec && Typo->isStr("vector"))
  3514. return nullptr;
  3515. // Provide a stop gap for files that are just seriously broken. Trying
  3516. // to correct all typos can turn into a HUGE performance penalty, causing
  3517. // some files to take minutes to get rejected by the parser.
  3518. unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
  3519. if (Limit && TyposCorrected >= Limit)
  3520. return nullptr;
  3521. ++TyposCorrected;
  3522. // If we're handling a missing symbol error, using modules, and the
  3523. // special search all modules option is used, look for a missing import.
  3524. if (ErrorRecovery && getLangOpts().Modules &&
  3525. getLangOpts().ModulesSearchAll) {
  3526. // The following has the side effect of loading the missing module.
  3527. getModuleLoader().lookupMissingImports(Typo->getName(),
  3528. TypoName.getLocStart());
  3529. }
  3530. CorrectionCandidateCallback &CCCRef = *CCC;
  3531. auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
  3532. *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
  3533. EnteringContext);
  3534. // Perform name lookup to find visible, similarly-named entities.
  3535. bool IsUnqualifiedLookup = false;
  3536. DeclContext *QualifiedDC = MemberContext;
  3537. if (MemberContext) {
  3538. LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
  3539. // Look in qualified interfaces.
  3540. if (OPT) {
  3541. for (auto *I : OPT->quals())
  3542. LookupVisibleDecls(I, LookupKind, *Consumer);
  3543. }
  3544. } else if (SS && SS->isSet()) {
  3545. QualifiedDC = computeDeclContext(*SS, EnteringContext);
  3546. if (!QualifiedDC)
  3547. return nullptr;
  3548. LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
  3549. } else {
  3550. IsUnqualifiedLookup = true;
  3551. }
  3552. // Determine whether we are going to search in the various namespaces for
  3553. // corrections.
  3554. bool SearchNamespaces
  3555. = getLangOpts().CPlusPlus &&
  3556. (IsUnqualifiedLookup || (SS && SS->isSet()));
  3557. if (IsUnqualifiedLookup || SearchNamespaces) {
  3558. // For unqualified lookup, look through all of the names that we have
  3559. // seen in this translation unit.
  3560. // FIXME: Re-add the ability to skip very unlikely potential corrections.
  3561. for (const auto &I : Context.Idents)
  3562. Consumer->FoundName(I.getKey());
  3563. // Walk through identifiers in external identifier sources.
  3564. // FIXME: Re-add the ability to skip very unlikely potential corrections.
  3565. if (IdentifierInfoLookup *External
  3566. = Context.Idents.getExternalIdentifierLookup()) {
  3567. std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
  3568. do {
  3569. StringRef Name = Iter->Next();
  3570. if (Name.empty())
  3571. break;
  3572. Consumer->FoundName(Name);
  3573. } while (true);
  3574. }
  3575. }
  3576. AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
  3577. // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
  3578. // to search those namespaces.
  3579. if (SearchNamespaces) {
  3580. // Load any externally-known namespaces.
  3581. if (ExternalSource && !LoadedExternalKnownNamespaces) {
  3582. SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
  3583. LoadedExternalKnownNamespaces = true;
  3584. ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
  3585. for (auto *N : ExternalKnownNamespaces)
  3586. KnownNamespaces[N] = true;
  3587. }
  3588. Consumer->addNamespaces(KnownNamespaces);
  3589. }
  3590. return Consumer;
  3591. }
  3592. /// \brief Try to "correct" a typo in the source code by finding
  3593. /// visible declarations whose names are similar to the name that was
  3594. /// present in the source code.
  3595. ///
  3596. /// \param TypoName the \c DeclarationNameInfo structure that contains
  3597. /// the name that was present in the source code along with its location.
  3598. ///
  3599. /// \param LookupKind the name-lookup criteria used to search for the name.
  3600. ///
  3601. /// \param S the scope in which name lookup occurs.
  3602. ///
  3603. /// \param SS the nested-name-specifier that precedes the name we're
  3604. /// looking for, if present.
  3605. ///
  3606. /// \param CCC A CorrectionCandidateCallback object that provides further
  3607. /// validation of typo correction candidates. It also provides flags for
  3608. /// determining the set of keywords permitted.
  3609. ///
  3610. /// \param MemberContext if non-NULL, the context in which to look for
  3611. /// a member access expression.
  3612. ///
  3613. /// \param EnteringContext whether we're entering the context described by
  3614. /// the nested-name-specifier SS.
  3615. ///
  3616. /// \param OPT when non-NULL, the search for visible declarations will
  3617. /// also walk the protocols in the qualified interfaces of \p OPT.
  3618. ///
  3619. /// \returns a \c TypoCorrection containing the corrected name if the typo
  3620. /// along with information such as the \c NamedDecl where the corrected name
  3621. /// was declared, and any additional \c NestedNameSpecifier needed to access
  3622. /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
  3623. TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
  3624. Sema::LookupNameKind LookupKind,
  3625. Scope *S, CXXScopeSpec *SS,
  3626. std::unique_ptr<CorrectionCandidateCallback> CCC,
  3627. CorrectTypoKind Mode,
  3628. DeclContext *MemberContext,
  3629. bool EnteringContext,
  3630. const ObjCObjectPointerType *OPT,
  3631. bool RecordFailure) {
  3632. assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback");
  3633. // Always let the ExternalSource have the first chance at correction, even
  3634. // if we would otherwise have given up.
  3635. if (ExternalSource) {
  3636. if (TypoCorrection Correction = ExternalSource->CorrectTypo(
  3637. TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
  3638. return Correction;
  3639. }
  3640. // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
  3641. // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
  3642. // some instances of CTC_Unknown, while WantRemainingKeywords is true
  3643. // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
  3644. bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
  3645. IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
  3646. auto Consumer = makeTypoCorrectionConsumer(
  3647. TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
  3648. EnteringContext, OPT, Mode == CTK_ErrorRecovery);
  3649. if (!Consumer)
  3650. return TypoCorrection();
  3651. // If we haven't found anything, we're done.
  3652. if (Consumer->empty())
  3653. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  3654. // Make sure the best edit distance (prior to adding any namespace qualifiers)
  3655. // is not more that about a third of the length of the typo's identifier.
  3656. unsigned ED = Consumer->getBestEditDistance(true);
  3657. unsigned TypoLen = Typo->getName().size();
  3658. if (ED > 0 && TypoLen / ED < 3)
  3659. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  3660. TypoCorrection BestTC = Consumer->getNextCorrection();
  3661. TypoCorrection SecondBestTC = Consumer->getNextCorrection();
  3662. if (!BestTC)
  3663. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  3664. ED = BestTC.getEditDistance();
  3665. if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
  3666. // If this was an unqualified lookup and we believe the callback
  3667. // object wouldn't have filtered out possible corrections, note
  3668. // that no correction was found.
  3669. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  3670. }
  3671. // If only a single name remains, return that result.
  3672. if (!SecondBestTC ||
  3673. SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
  3674. const TypoCorrection &Result = BestTC;
  3675. // Don't correct to a keyword that's the same as the typo; the keyword
  3676. // wasn't actually in scope.
  3677. if (ED == 0 && Result.isKeyword())
  3678. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  3679. TypoCorrection TC = Result;
  3680. TC.setCorrectionRange(SS, TypoName);
  3681. checkCorrectionVisibility(*this, TC);
  3682. return TC;
  3683. } else if (SecondBestTC && ObjCMessageReceiver) {
  3684. // Prefer 'super' when we're completing in a message-receiver
  3685. // context.
  3686. if (BestTC.getCorrection().getAsString() != "super") {
  3687. if (SecondBestTC.getCorrection().getAsString() == "super")
  3688. BestTC = SecondBestTC;
  3689. else if ((*Consumer)["super"].front().isKeyword())
  3690. BestTC = (*Consumer)["super"].front();
  3691. }
  3692. // Don't correct to a keyword that's the same as the typo; the keyword
  3693. // wasn't actually in scope.
  3694. if (BestTC.getEditDistance() == 0 ||
  3695. BestTC.getCorrection().getAsString() != "super")
  3696. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
  3697. BestTC.setCorrectionRange(SS, TypoName);
  3698. return BestTC;
  3699. }
  3700. // Record the failure's location if needed and return an empty correction. If
  3701. // this was an unqualified lookup and we believe the callback object did not
  3702. // filter out possible corrections, also cache the failure for the typo.
  3703. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
  3704. }
  3705. /// \brief Try to "correct" a typo in the source code by finding
  3706. /// visible declarations whose names are similar to the name that was
  3707. /// present in the source code.
  3708. ///
  3709. /// \param TypoName the \c DeclarationNameInfo structure that contains
  3710. /// the name that was present in the source code along with its location.
  3711. ///
  3712. /// \param LookupKind the name-lookup criteria used to search for the name.
  3713. ///
  3714. /// \param S the scope in which name lookup occurs.
  3715. ///
  3716. /// \param SS the nested-name-specifier that precedes the name we're
  3717. /// looking for, if present.
  3718. ///
  3719. /// \param CCC A CorrectionCandidateCallback object that provides further
  3720. /// validation of typo correction candidates. It also provides flags for
  3721. /// determining the set of keywords permitted.
  3722. ///
  3723. /// \param TDG A TypoDiagnosticGenerator functor that will be used to print
  3724. /// diagnostics when the actual typo correction is attempted.
  3725. ///
  3726. /// \param TRC A TypoRecoveryCallback functor that will be used to build an
  3727. /// Expr from a typo correction candidate.
  3728. ///
  3729. /// \param MemberContext if non-NULL, the context in which to look for
  3730. /// a member access expression.
  3731. ///
  3732. /// \param EnteringContext whether we're entering the context described by
  3733. /// the nested-name-specifier SS.
  3734. ///
  3735. /// \param OPT when non-NULL, the search for visible declarations will
  3736. /// also walk the protocols in the qualified interfaces of \p OPT.
  3737. ///
  3738. /// \returns a new \c TypoExpr that will later be replaced in the AST with an
  3739. /// Expr representing the result of performing typo correction, or nullptr if
  3740. /// typo correction is not possible. If nullptr is returned, no diagnostics will
  3741. /// be emitted and it is the responsibility of the caller to emit any that are
  3742. /// needed.
  3743. TypoExpr *Sema::CorrectTypoDelayed(
  3744. const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
  3745. Scope *S, CXXScopeSpec *SS,
  3746. std::unique_ptr<CorrectionCandidateCallback> CCC,
  3747. TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
  3748. DeclContext *MemberContext, bool EnteringContext,
  3749. const ObjCObjectPointerType *OPT) {
  3750. assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback");
  3751. TypoCorrection Empty;
  3752. auto Consumer = makeTypoCorrectionConsumer(
  3753. TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
  3754. EnteringContext, OPT, Mode == CTK_ErrorRecovery);
  3755. if (!Consumer || Consumer->empty())
  3756. return nullptr;
  3757. // Make sure the best edit distance (prior to adding any namespace qualifiers)
  3758. // is not more that about a third of the length of the typo's identifier.
  3759. unsigned ED = Consumer->getBestEditDistance(true);
  3760. IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
  3761. if (ED > 0 && Typo->getName().size() / ED < 3)
  3762. return nullptr;
  3763. ExprEvalContexts.back().NumTypos++;
  3764. return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
  3765. }
  3766. void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
  3767. if (!CDecl) return;
  3768. if (isKeyword())
  3769. CorrectionDecls.clear();
  3770. CorrectionDecls.push_back(CDecl->getUnderlyingDecl());
  3771. if (!CorrectionName)
  3772. CorrectionName = CDecl->getDeclName();
  3773. }
  3774. std::string TypoCorrection::getAsString(const LangOptions &LO) const {
  3775. if (CorrectionNameSpec) {
  3776. std::string tmpBuffer;
  3777. llvm::raw_string_ostream PrefixOStream(tmpBuffer);
  3778. CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
  3779. PrefixOStream << CorrectionName;
  3780. return PrefixOStream.str();
  3781. }
  3782. return CorrectionName.getAsString();
  3783. }
  3784. bool CorrectionCandidateCallback::ValidateCandidate(
  3785. const TypoCorrection &candidate) {
  3786. if (!candidate.isResolved())
  3787. return true;
  3788. if (candidate.isKeyword())
  3789. return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
  3790. WantRemainingKeywords || WantObjCSuper;
  3791. bool HasNonType = false;
  3792. bool HasStaticMethod = false;
  3793. bool HasNonStaticMethod = false;
  3794. for (Decl *D : candidate) {
  3795. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
  3796. D = FTD->getTemplatedDecl();
  3797. if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
  3798. if (Method->isStatic())
  3799. HasStaticMethod = true;
  3800. else
  3801. HasNonStaticMethod = true;
  3802. }
  3803. if (!isa<TypeDecl>(D))
  3804. HasNonType = true;
  3805. }
  3806. if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
  3807. !candidate.getCorrectionSpecifier())
  3808. return false;
  3809. return WantTypeSpecifiers || HasNonType;
  3810. }
  3811. FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
  3812. bool HasExplicitTemplateArgs,
  3813. MemberExpr *ME)
  3814. : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
  3815. CurContext(SemaRef.CurContext), MemberFn(ME) {
  3816. WantTypeSpecifiers = false;
  3817. WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
  3818. WantRemainingKeywords = false;
  3819. }
  3820. bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
  3821. if (!candidate.getCorrectionDecl())
  3822. return candidate.isKeyword();
  3823. for (auto *C : candidate) {
  3824. FunctionDecl *FD = nullptr;
  3825. NamedDecl *ND = C->getUnderlyingDecl();
  3826. if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
  3827. FD = FTD->getTemplatedDecl();
  3828. if (!HasExplicitTemplateArgs && !FD) {
  3829. if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
  3830. // If the Decl is neither a function nor a template function,
  3831. // determine if it is a pointer or reference to a function. If so,
  3832. // check against the number of arguments expected for the pointee.
  3833. QualType ValType = cast<ValueDecl>(ND)->getType();
  3834. if (ValType->isAnyPointerType() || ValType->isReferenceType())
  3835. ValType = ValType->getPointeeType();
  3836. if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
  3837. if (FPT->getNumParams() == NumArgs)
  3838. return true;
  3839. }
  3840. }
  3841. // Skip the current candidate if it is not a FunctionDecl or does not accept
  3842. // the current number of arguments.
  3843. if (!FD || !(FD->getNumParams() >= NumArgs &&
  3844. FD->getMinRequiredArguments() <= NumArgs))
  3845. continue;
  3846. // If the current candidate is a non-static C++ method, skip the candidate
  3847. // unless the method being corrected--or the current DeclContext, if the
  3848. // function being corrected is not a method--is a method in the same class
  3849. // or a descendent class of the candidate's parent class.
  3850. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  3851. if (MemberFn || !MD->isStatic()) {
  3852. CXXMethodDecl *CurMD =
  3853. MemberFn
  3854. ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
  3855. : dyn_cast_or_null<CXXMethodDecl>(CurContext);
  3856. CXXRecordDecl *CurRD =
  3857. CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
  3858. CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
  3859. if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
  3860. continue;
  3861. }
  3862. }
  3863. return true;
  3864. }
  3865. return false;
  3866. }
  3867. void Sema::diagnoseTypo(const TypoCorrection &Correction,
  3868. const PartialDiagnostic &TypoDiag,
  3869. bool ErrorRecovery) {
  3870. diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
  3871. ErrorRecovery);
  3872. }
  3873. /// Find which declaration we should import to provide the definition of
  3874. /// the given declaration.
  3875. static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
  3876. if (const VarDecl *VD = dyn_cast<VarDecl>(D))
  3877. return VD->getDefinition();
  3878. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  3879. return FD->isDefined(FD) ? FD : nullptr;
  3880. if (const TagDecl *TD = dyn_cast<TagDecl>(D))
  3881. return TD->getDefinition();
  3882. if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
  3883. return ID->getDefinition();
  3884. if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
  3885. return PD->getDefinition();
  3886. if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
  3887. return getDefinitionToImport(TD->getTemplatedDecl());
  3888. return nullptr;
  3889. }
  3890. /// \brief Diagnose a successfully-corrected typo. Separated from the correction
  3891. /// itself to allow external validation of the result, etc.
  3892. ///
  3893. /// \param Correction The result of performing typo correction.
  3894. /// \param TypoDiag The diagnostic to produce. This will have the corrected
  3895. /// string added to it (and usually also a fixit).
  3896. /// \param PrevNote A note to use when indicating the location of the entity to
  3897. /// which we are correcting. Will have the correction string added to it.
  3898. /// \param ErrorRecovery If \c true (the default), the caller is going to
  3899. /// recover from the typo as if the corrected string had been typed.
  3900. /// In this case, \c PDiag must be an error, and we will attach a fixit
  3901. /// to it.
  3902. void Sema::diagnoseTypo(const TypoCorrection &Correction,
  3903. const PartialDiagnostic &TypoDiag,
  3904. const PartialDiagnostic &PrevNote,
  3905. bool ErrorRecovery) {
  3906. std::string CorrectedStr = Correction.getAsString(getLangOpts());
  3907. std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
  3908. FixItHint FixTypo = FixItHint::CreateReplacement(
  3909. Correction.getCorrectionRange(), CorrectedStr);
  3910. // Maybe we're just missing a module import.
  3911. if (Correction.requiresImport()) {
  3912. NamedDecl *Decl = Correction.getCorrectionDecl();
  3913. assert(Decl && "import required but no declaration to import");
  3914. // Suggest importing a module providing the definition of this entity, if
  3915. // possible.
  3916. const NamedDecl *Def = getDefinitionToImport(Decl);
  3917. if (!Def)
  3918. Def = Decl;
  3919. Module *Owner = Def->getOwningModule();
  3920. assert(Owner && "definition of hidden declaration is not in a module");
  3921. Diag(Correction.getCorrectionRange().getBegin(),
  3922. diag::err_module_private_declaration)
  3923. << Def << Owner->getFullModuleName();
  3924. Diag(Def->getLocation(), diag::note_previous_declaration);
  3925. // Recover by implicitly importing this module.
  3926. if (ErrorRecovery)
  3927. createImplicitModuleImportForErrorRecovery(
  3928. Correction.getCorrectionRange().getBegin(), Owner);
  3929. return;
  3930. }
  3931. Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
  3932. << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
  3933. NamedDecl *ChosenDecl =
  3934. Correction.isKeyword() ? nullptr : Correction.getCorrectionDecl();
  3935. if (PrevNote.getDiagID() && ChosenDecl)
  3936. Diag(ChosenDecl->getLocation(), PrevNote)
  3937. << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
  3938. }
  3939. TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
  3940. TypoDiagnosticGenerator TDG,
  3941. TypoRecoveryCallback TRC) {
  3942. assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
  3943. auto TE = new (Context) TypoExpr(Context.DependentTy);
  3944. auto &State = DelayedTypos[TE];
  3945. State.Consumer = std::move(TCC);
  3946. State.DiagHandler = std::move(TDG);
  3947. State.RecoveryHandler = std::move(TRC);
  3948. return TE;
  3949. }
  3950. const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
  3951. auto Entry = DelayedTypos.find(TE);
  3952. assert(Entry != DelayedTypos.end() &&
  3953. "Failed to get the state for a TypoExpr!");
  3954. return Entry->second;
  3955. }
  3956. void Sema::clearDelayedTypo(TypoExpr *TE) {
  3957. DelayedTypos.erase(TE);
  3958. }