SemaLookup.cpp 197 KB

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