SemaLookup.cpp 177 KB

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