ASTImporterTest.cpp 193 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658
  1. //===- unittest/AST/ASTImporterTest.cpp - AST node import test ------------===//
  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. // Tests for the correct import of AST nodes from one AST context to another.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/StringMap.h"
  13. #include "clang/AST/DeclContextInternals.h"
  14. #include "ASTImporterFixtures.h"
  15. #include "MatchVerifier.h"
  16. namespace clang {
  17. namespace ast_matchers {
  18. using internal::Matcher;
  19. using internal::BindableMatcher;
  20. using llvm::StringMap;
  21. // Base class for those tests which use the family of `testImport` functions.
  22. class TestImportBase : public CompilerOptionSpecificTest,
  23. public ::testing::WithParamInterface<ArgVector> {
  24. template <typename NodeType>
  25. llvm::Expected<NodeType> importNode(ASTUnit *From, ASTUnit *To,
  26. ASTImporter &Importer, NodeType Node) {
  27. ASTContext &ToCtx = To->getASTContext();
  28. // Add 'From' file to virtual file system so importer can 'find' it
  29. // while importing SourceLocations. It is safe to add same file multiple
  30. // times - it just isn't replaced.
  31. StringRef FromFileName = From->getMainFileName();
  32. createVirtualFileIfNeeded(To, FromFileName,
  33. From->getBufferForFile(FromFileName));
  34. auto Imported = Importer.Import(Node);
  35. if (Imported) {
  36. // This should dump source locations and assert if some source locations
  37. // were not imported.
  38. SmallString<1024> ImportChecker;
  39. llvm::raw_svector_ostream ToNothing(ImportChecker);
  40. ToCtx.getTranslationUnitDecl()->print(ToNothing);
  41. // This traverses the AST to catch certain bugs like poorly or not
  42. // implemented subtrees.
  43. (*Imported)->dump(ToNothing);
  44. }
  45. return Imported;
  46. }
  47. template <typename NodeType>
  48. testing::AssertionResult
  49. testImport(const std::string &FromCode, const ArgVector &FromArgs,
  50. const std::string &ToCode, const ArgVector &ToArgs,
  51. MatchVerifier<NodeType> &Verifier,
  52. const BindableMatcher<NodeType> &SearchMatcher,
  53. const BindableMatcher<NodeType> &VerificationMatcher) {
  54. const char *const InputFileName = "input.cc";
  55. const char *const OutputFileName = "output.cc";
  56. std::unique_ptr<ASTUnit> FromAST = tooling::buildASTFromCodeWithArgs(
  57. FromCode, FromArgs, InputFileName),
  58. ToAST = tooling::buildASTFromCodeWithArgs(
  59. ToCode, ToArgs, OutputFileName);
  60. ASTContext &FromCtx = FromAST->getASTContext(),
  61. &ToCtx = ToAST->getASTContext();
  62. ASTImporter Importer(ToCtx, ToAST->getFileManager(), FromCtx,
  63. FromAST->getFileManager(), false);
  64. auto FoundNodes = match(SearchMatcher, FromCtx);
  65. if (FoundNodes.size() != 1)
  66. return testing::AssertionFailure()
  67. << "Multiple potential nodes were found!";
  68. auto ToImport = selectFirst<NodeType>(DeclToImportID, FoundNodes);
  69. if (!ToImport)
  70. return testing::AssertionFailure() << "Node type mismatch!";
  71. // Sanity check: the node being imported should match in the same way as
  72. // the result node.
  73. BindableMatcher<NodeType> WrapperMatcher(VerificationMatcher);
  74. EXPECT_TRUE(Verifier.match(ToImport, WrapperMatcher));
  75. auto Imported = importNode(FromAST.get(), ToAST.get(), Importer, ToImport);
  76. if (!Imported) {
  77. std::string ErrorText;
  78. handleAllErrors(
  79. Imported.takeError(),
  80. [&ErrorText](const ImportError &Err) { ErrorText = Err.message(); });
  81. return testing::AssertionFailure()
  82. << "Import failed, error: \"" << ErrorText << "\"!";
  83. }
  84. return Verifier.match(*Imported, WrapperMatcher);
  85. }
  86. template <typename NodeType>
  87. testing::AssertionResult
  88. testImport(const std::string &FromCode, const ArgVector &FromArgs,
  89. const std::string &ToCode, const ArgVector &ToArgs,
  90. MatchVerifier<NodeType> &Verifier,
  91. const BindableMatcher<NodeType> &VerificationMatcher) {
  92. return testImport(
  93. FromCode, FromArgs, ToCode, ToArgs, Verifier,
  94. translationUnitDecl(
  95. has(namedDecl(hasName(DeclToImportID)).bind(DeclToImportID))),
  96. VerificationMatcher);
  97. }
  98. protected:
  99. ArgVector getExtraArgs() const override { return GetParam(); }
  100. public:
  101. /// Test how AST node named "declToImport" located in the translation unit
  102. /// of "FromCode" virtual file is imported to "ToCode" virtual file.
  103. /// The verification is done by running AMatcher over the imported node.
  104. template <typename NodeType, typename MatcherType>
  105. void testImport(const std::string &FromCode, Language FromLang,
  106. const std::string &ToCode, Language ToLang,
  107. MatchVerifier<NodeType> &Verifier,
  108. const MatcherType &AMatcher) {
  109. ArgVector FromArgs = getArgVectorForLanguage(FromLang),
  110. ToArgs = getArgVectorForLanguage(ToLang);
  111. EXPECT_TRUE(
  112. testImport(FromCode, FromArgs, ToCode, ToArgs, Verifier, AMatcher));
  113. }
  114. struct ImportAction {
  115. StringRef FromFilename;
  116. StringRef ToFilename;
  117. // FIXME: Generalize this to support other node kinds.
  118. BindableMatcher<Decl> ImportPredicate;
  119. ImportAction(StringRef FromFilename, StringRef ToFilename,
  120. DeclarationMatcher ImportPredicate)
  121. : FromFilename(FromFilename), ToFilename(ToFilename),
  122. ImportPredicate(ImportPredicate) {}
  123. ImportAction(StringRef FromFilename, StringRef ToFilename,
  124. const std::string &DeclName)
  125. : FromFilename(FromFilename), ToFilename(ToFilename),
  126. ImportPredicate(namedDecl(hasName(DeclName))) {}
  127. };
  128. using SingleASTUnit = std::unique_ptr<ASTUnit>;
  129. using AllASTUnits = StringMap<SingleASTUnit>;
  130. struct CodeEntry {
  131. std::string CodeSample;
  132. Language Lang;
  133. };
  134. using CodeFiles = StringMap<CodeEntry>;
  135. /// Builds an ASTUnit for one potential compile options set.
  136. SingleASTUnit createASTUnit(StringRef FileName, const CodeEntry &CE) const {
  137. ArgVector Args = getArgVectorForLanguage(CE.Lang);
  138. auto AST = tooling::buildASTFromCodeWithArgs(CE.CodeSample, Args, FileName);
  139. EXPECT_TRUE(AST.get());
  140. return AST;
  141. }
  142. /// Test an arbitrary sequence of imports for a set of given in-memory files.
  143. /// The verification is done by running VerificationMatcher against a
  144. /// specified AST node inside of one of given files.
  145. /// \param CodeSamples Map whose key is the file name and the value is the
  146. /// file content.
  147. /// \param ImportActions Sequence of imports. Each import in sequence
  148. /// specifies "from file" and "to file" and a matcher that is used for
  149. /// searching a declaration for import in "from file".
  150. /// \param FileForFinalCheck Name of virtual file for which the final check is
  151. /// applied.
  152. /// \param FinalSelectPredicate Matcher that specifies the AST node in the
  153. /// FileForFinalCheck for which the verification will be done.
  154. /// \param VerificationMatcher Matcher that will be used for verification
  155. /// after all imports in sequence are done.
  156. void testImportSequence(const CodeFiles &CodeSamples,
  157. const std::vector<ImportAction> &ImportActions,
  158. StringRef FileForFinalCheck,
  159. BindableMatcher<Decl> FinalSelectPredicate,
  160. BindableMatcher<Decl> VerificationMatcher) {
  161. AllASTUnits AllASTs;
  162. using ImporterKey = std::pair<const ASTUnit *, const ASTUnit *>;
  163. llvm::DenseMap<ImporterKey, std::unique_ptr<ASTImporter>> Importers;
  164. auto GenASTsIfNeeded = [this, &AllASTs, &CodeSamples](StringRef Filename) {
  165. if (!AllASTs.count(Filename)) {
  166. auto Found = CodeSamples.find(Filename);
  167. assert(Found != CodeSamples.end() && "Wrong file for import!");
  168. AllASTs[Filename] = createASTUnit(Filename, Found->getValue());
  169. }
  170. };
  171. for (const ImportAction &Action : ImportActions) {
  172. StringRef FromFile = Action.FromFilename, ToFile = Action.ToFilename;
  173. GenASTsIfNeeded(FromFile);
  174. GenASTsIfNeeded(ToFile);
  175. ASTUnit *From = AllASTs[FromFile].get();
  176. ASTUnit *To = AllASTs[ToFile].get();
  177. // Create a new importer if needed.
  178. std::unique_ptr<ASTImporter> &ImporterRef = Importers[{From, To}];
  179. if (!ImporterRef)
  180. ImporterRef.reset(new ASTImporter(
  181. To->getASTContext(), To->getFileManager(), From->getASTContext(),
  182. From->getFileManager(), false));
  183. // Find the declaration and import it.
  184. auto FoundDecl = match(Action.ImportPredicate.bind(DeclToImportID),
  185. From->getASTContext());
  186. EXPECT_TRUE(FoundDecl.size() == 1);
  187. const Decl *ToImport = selectFirst<Decl>(DeclToImportID, FoundDecl);
  188. auto Imported = importNode(From, To, *ImporterRef, ToImport);
  189. EXPECT_TRUE(static_cast<bool>(Imported));
  190. if (!Imported)
  191. llvm::consumeError(Imported.takeError());
  192. }
  193. // Find the declaration and import it.
  194. auto FoundDecl = match(FinalSelectPredicate.bind(DeclToVerifyID),
  195. AllASTs[FileForFinalCheck]->getASTContext());
  196. EXPECT_TRUE(FoundDecl.size() == 1);
  197. const Decl *ToVerify = selectFirst<Decl>(DeclToVerifyID, FoundDecl);
  198. MatchVerifier<Decl> Verifier;
  199. EXPECT_TRUE(
  200. Verifier.match(ToVerify, BindableMatcher<Decl>(VerificationMatcher)));
  201. }
  202. };
  203. template <typename T> RecordDecl *getRecordDecl(T *D) {
  204. auto *ET = cast<ElaboratedType>(D->getType().getTypePtr());
  205. return cast<RecordType>(ET->getNamedType().getTypePtr())->getDecl();
  206. }
  207. struct ImportExpr : TestImportBase {};
  208. struct ImportType : TestImportBase {};
  209. struct ImportDecl : TestImportBase {};
  210. struct CanonicalRedeclChain : ASTImporterOptionSpecificTestBase {};
  211. TEST_P(CanonicalRedeclChain, ShouldBeConsequentWithMatchers) {
  212. Decl *FromTU = getTuDecl("void f();", Lang_CXX);
  213. auto Pattern = functionDecl(hasName("f"));
  214. auto *D0 = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  215. auto Redecls = getCanonicalForwardRedeclChain(D0);
  216. ASSERT_EQ(Redecls.size(), 1u);
  217. EXPECT_EQ(D0, Redecls[0]);
  218. }
  219. TEST_P(CanonicalRedeclChain, ShouldBeConsequentWithMatchers2) {
  220. Decl *FromTU = getTuDecl("void f(); void f(); void f();", Lang_CXX);
  221. auto Pattern = functionDecl(hasName("f"));
  222. auto *D0 = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  223. auto *D2 = LastDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  224. FunctionDecl *D1 = D2->getPreviousDecl();
  225. auto Redecls = getCanonicalForwardRedeclChain(D0);
  226. ASSERT_EQ(Redecls.size(), 3u);
  227. EXPECT_EQ(D0, Redecls[0]);
  228. EXPECT_EQ(D1, Redecls[1]);
  229. EXPECT_EQ(D2, Redecls[2]);
  230. }
  231. TEST_P(CanonicalRedeclChain, ShouldBeSameForAllDeclInTheChain) {
  232. Decl *FromTU = getTuDecl("void f(); void f(); void f();", Lang_CXX);
  233. auto Pattern = functionDecl(hasName("f"));
  234. auto *D0 = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  235. auto *D2 = LastDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  236. FunctionDecl *D1 = D2->getPreviousDecl();
  237. auto RedeclsD0 = getCanonicalForwardRedeclChain(D0);
  238. auto RedeclsD1 = getCanonicalForwardRedeclChain(D1);
  239. auto RedeclsD2 = getCanonicalForwardRedeclChain(D2);
  240. EXPECT_THAT(RedeclsD0, ::testing::ContainerEq(RedeclsD1));
  241. EXPECT_THAT(RedeclsD1, ::testing::ContainerEq(RedeclsD2));
  242. }
  243. namespace {
  244. struct RedirectingImporter : public ASTImporter {
  245. using ASTImporter::ASTImporter;
  246. protected:
  247. llvm::Expected<Decl *> ImportImpl(Decl *FromD) override {
  248. auto *ND = dyn_cast<NamedDecl>(FromD);
  249. if (!ND || ND->getName() != "shouldNotBeImported")
  250. return ASTImporter::ImportImpl(FromD);
  251. for (Decl *D : getToContext().getTranslationUnitDecl()->decls()) {
  252. if (auto *ND = dyn_cast<NamedDecl>(D))
  253. if (ND->getName() == "realDecl") {
  254. RegisterImportedDecl(FromD, ND);
  255. return ND;
  256. }
  257. }
  258. return ASTImporter::ImportImpl(FromD);
  259. }
  260. };
  261. } // namespace
  262. struct RedirectingImporterTest : ASTImporterOptionSpecificTestBase {
  263. RedirectingImporterTest() {
  264. Creator = [](ASTContext &ToContext, FileManager &ToFileManager,
  265. ASTContext &FromContext, FileManager &FromFileManager,
  266. bool MinimalImport,
  267. const std::shared_ptr<ASTImporterSharedState> &SharedState) {
  268. return new RedirectingImporter(ToContext, ToFileManager, FromContext,
  269. FromFileManager, MinimalImport,
  270. SharedState);
  271. };
  272. }
  273. };
  274. // Test that an ASTImporter subclass can intercept an import call.
  275. TEST_P(RedirectingImporterTest, InterceptImport) {
  276. Decl *From, *To;
  277. std::tie(From, To) =
  278. getImportedDecl("class shouldNotBeImported {};", Lang_CXX,
  279. "class realDecl {};", Lang_CXX, "shouldNotBeImported");
  280. auto *Imported = cast<CXXRecordDecl>(To);
  281. EXPECT_EQ(Imported->getQualifiedNameAsString(), "realDecl");
  282. // Make sure our importer prevented the importing of the decl.
  283. auto *ToTU = Imported->getTranslationUnitDecl();
  284. auto Pattern = functionDecl(hasName("shouldNotBeImported"));
  285. unsigned count =
  286. DeclCounterWithPredicate<CXXRecordDecl>().match(ToTU, Pattern);
  287. EXPECT_EQ(0U, count);
  288. }
  289. // Test that when we indirectly import a declaration the custom ASTImporter
  290. // is still intercepting the import.
  291. TEST_P(RedirectingImporterTest, InterceptIndirectImport) {
  292. Decl *From, *To;
  293. std::tie(From, To) =
  294. getImportedDecl("class shouldNotBeImported {};"
  295. "class F { shouldNotBeImported f; };",
  296. Lang_CXX, "class realDecl {};", Lang_CXX, "F");
  297. // Make sure our ASTImporter prevented the importing of the decl.
  298. auto *ToTU = To->getTranslationUnitDecl();
  299. auto Pattern = functionDecl(hasName("shouldNotBeImported"));
  300. unsigned count =
  301. DeclCounterWithPredicate<CXXRecordDecl>().match(ToTU, Pattern);
  302. EXPECT_EQ(0U, count);
  303. }
  304. struct ImportPath : ASTImporterOptionSpecificTestBase {
  305. Decl *FromTU;
  306. FunctionDecl *D0, *D1, *D2;
  307. ImportPath() {
  308. FromTU = getTuDecl("void f(); void f(); void f();", Lang_CXX);
  309. auto Pattern = functionDecl(hasName("f"));
  310. D0 = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  311. D2 = LastDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  312. D1 = D2->getPreviousDecl();
  313. }
  314. };
  315. TEST_P(ImportPath, Push) {
  316. ASTImporter::ImportPathTy path;
  317. path.push(D0);
  318. EXPECT_FALSE(path.hasCycleAtBack());
  319. }
  320. TEST_P(ImportPath, SmallCycle) {
  321. ASTImporter::ImportPathTy path;
  322. path.push(D0);
  323. path.push(D0);
  324. EXPECT_TRUE(path.hasCycleAtBack());
  325. path.pop();
  326. EXPECT_FALSE(path.hasCycleAtBack());
  327. path.push(D0);
  328. EXPECT_TRUE(path.hasCycleAtBack());
  329. }
  330. TEST_P(ImportPath, GetSmallCycle) {
  331. ASTImporter::ImportPathTy path;
  332. path.push(D0);
  333. path.push(D0);
  334. EXPECT_TRUE(path.hasCycleAtBack());
  335. std::array<Decl* ,2> Res;
  336. int i = 0;
  337. for (Decl *Di : path.getCycleAtBack()) {
  338. Res[i++] = Di;
  339. }
  340. ASSERT_EQ(i, 2);
  341. EXPECT_EQ(Res[0], D0);
  342. EXPECT_EQ(Res[1], D0);
  343. }
  344. TEST_P(ImportPath, GetCycle) {
  345. ASTImporter::ImportPathTy path;
  346. path.push(D0);
  347. path.push(D1);
  348. path.push(D2);
  349. path.push(D0);
  350. EXPECT_TRUE(path.hasCycleAtBack());
  351. std::array<Decl* ,4> Res;
  352. int i = 0;
  353. for (Decl *Di : path.getCycleAtBack()) {
  354. Res[i++] = Di;
  355. }
  356. ASSERT_EQ(i, 4);
  357. EXPECT_EQ(Res[0], D0);
  358. EXPECT_EQ(Res[1], D2);
  359. EXPECT_EQ(Res[2], D1);
  360. EXPECT_EQ(Res[3], D0);
  361. }
  362. TEST_P(ImportPath, CycleAfterCycle) {
  363. ASTImporter::ImportPathTy path;
  364. path.push(D0);
  365. path.push(D1);
  366. path.push(D0);
  367. path.push(D1);
  368. path.push(D2);
  369. path.push(D0);
  370. EXPECT_TRUE(path.hasCycleAtBack());
  371. std::array<Decl* ,4> Res;
  372. int i = 0;
  373. for (Decl *Di : path.getCycleAtBack()) {
  374. Res[i++] = Di;
  375. }
  376. ASSERT_EQ(i, 4);
  377. EXPECT_EQ(Res[0], D0);
  378. EXPECT_EQ(Res[1], D2);
  379. EXPECT_EQ(Res[2], D1);
  380. EXPECT_EQ(Res[3], D0);
  381. path.pop();
  382. path.pop();
  383. path.pop();
  384. EXPECT_TRUE(path.hasCycleAtBack());
  385. i = 0;
  386. for (Decl *Di : path.getCycleAtBack()) {
  387. Res[i++] = Di;
  388. }
  389. ASSERT_EQ(i, 3);
  390. EXPECT_EQ(Res[0], D0);
  391. EXPECT_EQ(Res[1], D1);
  392. EXPECT_EQ(Res[2], D0);
  393. path.pop();
  394. EXPECT_FALSE(path.hasCycleAtBack());
  395. }
  396. TEST_P(ImportExpr, ImportStringLiteral) {
  397. MatchVerifier<Decl> Verifier;
  398. testImport(
  399. "void declToImport() { (void)\"foo\"; }",
  400. Lang_CXX, "", Lang_CXX, Verifier,
  401. functionDecl(hasDescendant(
  402. stringLiteral(hasType(asString("const char [4]"))))));
  403. testImport(
  404. "void declToImport() { (void)L\"foo\"; }",
  405. Lang_CXX, "", Lang_CXX, Verifier,
  406. functionDecl(hasDescendant(
  407. stringLiteral(hasType(asString("const wchar_t [4]"))))));
  408. testImport(
  409. "void declToImport() { (void) \"foo\" \"bar\"; }",
  410. Lang_CXX, "", Lang_CXX, Verifier,
  411. functionDecl(hasDescendant(
  412. stringLiteral(hasType(asString("const char [7]"))))));
  413. }
  414. TEST_P(ImportExpr, ImportChooseExpr) {
  415. MatchVerifier<Decl> Verifier;
  416. // This case tests C code that is not condition-dependent and has a true
  417. // condition.
  418. testImport(
  419. "void declToImport() { (void)__builtin_choose_expr(1, 2, 3); }",
  420. Lang_C, "", Lang_C, Verifier,
  421. functionDecl(hasDescendant(chooseExpr())));
  422. }
  423. TEST_P(ImportExpr, ImportGNUNullExpr) {
  424. MatchVerifier<Decl> Verifier;
  425. testImport(
  426. "void declToImport() { (void)__null; }",
  427. Lang_CXX, "", Lang_CXX, Verifier,
  428. functionDecl(hasDescendant(gnuNullExpr(hasType(isInteger())))));
  429. }
  430. TEST_P(ImportExpr, ImportCXXNullPtrLiteralExpr) {
  431. MatchVerifier<Decl> Verifier;
  432. testImport(
  433. "void declToImport() { (void)nullptr; }",
  434. Lang_CXX11, "", Lang_CXX11, Verifier,
  435. functionDecl(hasDescendant(cxxNullPtrLiteralExpr())));
  436. }
  437. TEST_P(ImportExpr, ImportFloatinglLiteralExpr) {
  438. MatchVerifier<Decl> Verifier;
  439. testImport(
  440. "void declToImport() { (void)1.0; }",
  441. Lang_C, "", Lang_C, Verifier,
  442. functionDecl(hasDescendant(
  443. floatLiteral(equals(1.0), hasType(asString("double"))))));
  444. testImport(
  445. "void declToImport() { (void)1.0e-5f; }",
  446. Lang_C, "", Lang_C, Verifier,
  447. functionDecl(hasDescendant(
  448. floatLiteral(equals(1.0e-5f), hasType(asString("float"))))));
  449. }
  450. TEST_P(ImportExpr, ImportImaginaryLiteralExpr) {
  451. MatchVerifier<Decl> Verifier;
  452. testImport(
  453. "void declToImport() { (void)1.0i; }",
  454. Lang_CXX14, "", Lang_CXX14, Verifier,
  455. functionDecl(hasDescendant(imaginaryLiteral())));
  456. }
  457. TEST_P(ImportExpr, ImportCompoundLiteralExpr) {
  458. MatchVerifier<Decl> Verifier;
  459. testImport(
  460. "void declToImport() {"
  461. " struct s { int x; long y; unsigned z; }; "
  462. " (void)(struct s){ 42, 0L, 1U }; }",
  463. Lang_CXX, "", Lang_CXX, Verifier,
  464. functionDecl(hasDescendant(
  465. compoundLiteralExpr(
  466. hasType(asString("struct s")),
  467. has(initListExpr(
  468. hasType(asString("struct s")),
  469. has(integerLiteral(
  470. equals(42), hasType(asString("int")))),
  471. has(integerLiteral(
  472. equals(0), hasType(asString("long")))),
  473. has(integerLiteral(
  474. equals(1), hasType(asString("unsigned int"))))))))));
  475. }
  476. TEST_P(ImportExpr, ImportCXXThisExpr) {
  477. MatchVerifier<Decl> Verifier;
  478. testImport(
  479. "class declToImport { void f() { (void)this; } };",
  480. Lang_CXX, "", Lang_CXX, Verifier,
  481. cxxRecordDecl(
  482. hasMethod(
  483. hasDescendant(
  484. cxxThisExpr(
  485. hasType(
  486. asString("class declToImport *")))))));
  487. }
  488. TEST_P(ImportExpr, ImportAtomicExpr) {
  489. MatchVerifier<Decl> Verifier;
  490. testImport(
  491. "void declToImport() { int *ptr; __atomic_load_n(ptr, 1); }",
  492. Lang_C, "", Lang_C, Verifier,
  493. functionDecl(hasDescendant(
  494. atomicExpr(
  495. has(ignoringParenImpCasts(
  496. declRefExpr(hasDeclaration(varDecl(hasName("ptr"))),
  497. hasType(asString("int *"))))),
  498. has(integerLiteral(equals(1), hasType(asString("int"))))))));
  499. }
  500. TEST_P(ImportExpr, ImportLabelDeclAndAddrLabelExpr) {
  501. MatchVerifier<Decl> Verifier;
  502. testImport(
  503. "void declToImport() { loop: goto loop; (void)&&loop; }",
  504. Lang_C, "", Lang_C, Verifier,
  505. functionDecl(
  506. hasDescendant(
  507. labelStmt(hasDeclaration(labelDecl(hasName("loop"))))),
  508. hasDescendant(
  509. addrLabelExpr(hasDeclaration(labelDecl(hasName("loop")))))));
  510. }
  511. AST_MATCHER_P(TemplateDecl, hasTemplateDecl,
  512. internal::Matcher<NamedDecl>, InnerMatcher) {
  513. const NamedDecl *Template = Node.getTemplatedDecl();
  514. return Template && InnerMatcher.matches(*Template, Finder, Builder);
  515. }
  516. TEST_P(ImportExpr, ImportParenListExpr) {
  517. MatchVerifier<Decl> Verifier;
  518. testImport(
  519. "template<typename T> class dummy { void f() { dummy X(*this); } };"
  520. "typedef dummy<int> declToImport;"
  521. "template class dummy<int>;",
  522. Lang_CXX, "", Lang_CXX, Verifier,
  523. typedefDecl(hasType(templateSpecializationType(
  524. hasDeclaration(classTemplateSpecializationDecl(hasSpecializedTemplate(
  525. classTemplateDecl(hasTemplateDecl(cxxRecordDecl(hasMethod(allOf(
  526. hasName("f"),
  527. hasBody(compoundStmt(has(declStmt(hasSingleDecl(
  528. varDecl(hasInitializer(parenListExpr(has(unaryOperator(
  529. hasOperatorName("*"),
  530. hasUnaryOperand(cxxThisExpr())))))))))))))))))))))));
  531. }
  532. TEST_P(ImportExpr, ImportSwitch) {
  533. MatchVerifier<Decl> Verifier;
  534. testImport(
  535. "void declToImport() { int b; switch (b) { case 1: break; } }",
  536. Lang_C, "", Lang_C, Verifier,
  537. functionDecl(hasDescendant(
  538. switchStmt(has(compoundStmt(has(caseStmt())))))));
  539. }
  540. TEST_P(ImportExpr, ImportStmtExpr) {
  541. MatchVerifier<Decl> Verifier;
  542. testImport(
  543. "void declToImport() { int b; int a = b ?: 1; int C = ({int X=4; X;}); }",
  544. Lang_C, "", Lang_C, Verifier,
  545. functionDecl(hasDescendant(
  546. varDecl(
  547. hasName("C"),
  548. hasType(asString("int")),
  549. hasInitializer(
  550. stmtExpr(
  551. hasAnySubstatement(declStmt(hasSingleDecl(
  552. varDecl(
  553. hasName("X"),
  554. hasType(asString("int")),
  555. hasInitializer(
  556. integerLiteral(equals(4))))))),
  557. hasDescendant(
  558. implicitCastExpr())))))));
  559. }
  560. TEST_P(ImportExpr, ImportConditionalOperator) {
  561. MatchVerifier<Decl> Verifier;
  562. testImport(
  563. "void declToImport() { (void)(true ? 1 : -5); }",
  564. Lang_CXX, "", Lang_CXX, Verifier,
  565. functionDecl(hasDescendant(
  566. conditionalOperator(
  567. hasCondition(cxxBoolLiteral(equals(true))),
  568. hasTrueExpression(integerLiteral(equals(1))),
  569. hasFalseExpression(
  570. unaryOperator(hasUnaryOperand(integerLiteral(equals(5))))))
  571. )));
  572. }
  573. TEST_P(ImportExpr, ImportBinaryConditionalOperator) {
  574. MatchVerifier<Decl> Verifier;
  575. testImport(
  576. "void declToImport() { (void)(1 ?: -5); }",
  577. Lang_CXX, "", Lang_CXX, Verifier,
  578. functionDecl(hasDescendant(
  579. binaryConditionalOperator(
  580. hasCondition(
  581. implicitCastExpr(
  582. hasSourceExpression(opaqueValueExpr(
  583. hasSourceExpression(integerLiteral(equals(1))))),
  584. hasType(booleanType()))),
  585. hasTrueExpression(
  586. opaqueValueExpr(
  587. hasSourceExpression(integerLiteral(equals(1))))),
  588. hasFalseExpression(
  589. unaryOperator(
  590. hasOperatorName("-"),
  591. hasUnaryOperand(integerLiteral(equals(5)))))))));
  592. }
  593. TEST_P(ImportExpr, ImportDesignatedInitExpr) {
  594. MatchVerifier<Decl> Verifier;
  595. testImport(
  596. "void declToImport() {"
  597. " struct point { double x; double y; };"
  598. " struct point ptarray[10] = "
  599. "{ [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; }",
  600. Lang_C, "", Lang_C, Verifier,
  601. functionDecl(hasDescendant(
  602. initListExpr(
  603. has(designatedInitExpr(
  604. designatorCountIs(2),
  605. hasDescendant(floatLiteral(equals(1.0))),
  606. hasDescendant(integerLiteral(equals(2))))),
  607. has(designatedInitExpr(
  608. designatorCountIs(2),
  609. hasDescendant(floatLiteral(equals(2.0))),
  610. hasDescendant(integerLiteral(equals(2))))),
  611. has(designatedInitExpr(
  612. designatorCountIs(2),
  613. hasDescendant(floatLiteral(equals(1.0))),
  614. hasDescendant(integerLiteral(equals(0)))))))));
  615. }
  616. TEST_P(ImportExpr, ImportPredefinedExpr) {
  617. MatchVerifier<Decl> Verifier;
  618. // __func__ expands as StringLiteral("declToImport")
  619. testImport(
  620. "void declToImport() { (void)__func__; }",
  621. Lang_CXX, "", Lang_CXX, Verifier,
  622. functionDecl(hasDescendant(
  623. predefinedExpr(
  624. hasType(
  625. asString("const char [13]")),
  626. has(stringLiteral(hasType(
  627. asString("const char [13]"))))))));
  628. }
  629. TEST_P(ImportExpr, ImportInitListExpr) {
  630. MatchVerifier<Decl> Verifier;
  631. testImport(
  632. "void declToImport() {"
  633. " struct point { double x; double y; };"
  634. " point ptarray[10] = { [2].y = 1.0, [2].x = 2.0,"
  635. " [0].x = 1.0 }; }",
  636. Lang_CXX, "", Lang_CXX, Verifier,
  637. functionDecl(hasDescendant(
  638. initListExpr(
  639. has(
  640. cxxConstructExpr(
  641. requiresZeroInitialization())),
  642. has(
  643. initListExpr(
  644. hasType(asString("struct point")),
  645. has(floatLiteral(equals(1.0))),
  646. has(implicitValueInitExpr(
  647. hasType(asString("double")))))),
  648. has(
  649. initListExpr(
  650. hasType(asString("struct point")),
  651. has(floatLiteral(equals(2.0))),
  652. has(floatLiteral(equals(1.0)))))))));
  653. }
  654. const internal::VariadicDynCastAllOfMatcher<Expr, VAArgExpr> vaArgExpr;
  655. TEST_P(ImportExpr, ImportVAArgExpr) {
  656. MatchVerifier<Decl> Verifier;
  657. testImport(
  658. "void declToImport(__builtin_va_list list, ...) {"
  659. " (void)__builtin_va_arg(list, int); }",
  660. Lang_CXX, "", Lang_CXX, Verifier,
  661. functionDecl(hasDescendant(
  662. cStyleCastExpr(hasSourceExpression(vaArgExpr())))));
  663. }
  664. TEST_P(ImportExpr, CXXTemporaryObjectExpr) {
  665. MatchVerifier<Decl> Verifier;
  666. testImport(
  667. "struct C {};"
  668. "void declToImport() { C c = C(); }",
  669. Lang_CXX, "", Lang_CXX, Verifier,
  670. functionDecl(hasDescendant(
  671. exprWithCleanups(has(cxxConstructExpr(
  672. has(materializeTemporaryExpr(has(implicitCastExpr(
  673. has(cxxTemporaryObjectExpr())))))))))));
  674. }
  675. TEST_P(ImportType, ImportAtomicType) {
  676. MatchVerifier<Decl> Verifier;
  677. testImport(
  678. "void declToImport() { typedef _Atomic(int) a_int; }",
  679. Lang_CXX11, "", Lang_CXX11, Verifier,
  680. functionDecl(hasDescendant(typedefDecl(has(atomicType())))));
  681. }
  682. TEST_P(ImportDecl, ImportFunctionTemplateDecl) {
  683. MatchVerifier<Decl> Verifier;
  684. testImport(
  685. "template <typename T> void declToImport() { };",
  686. Lang_CXX, "", Lang_CXX, Verifier,
  687. functionTemplateDecl());
  688. }
  689. TEST_P(ImportExpr, ImportCXXDependentScopeMemberExpr) {
  690. MatchVerifier<Decl> Verifier;
  691. testImport(
  692. "template <typename T> struct C { T t; };"
  693. "template <typename T> void declToImport() {"
  694. " C<T> d;"
  695. " (void)d.t;"
  696. "}"
  697. "void instantiate() { declToImport<int>(); }",
  698. Lang_CXX, "", Lang_CXX, Verifier,
  699. functionTemplateDecl(hasDescendant(
  700. cStyleCastExpr(has(cxxDependentScopeMemberExpr())))));
  701. testImport(
  702. "template <typename T> struct C { T t; };"
  703. "template <typename T> void declToImport() {"
  704. " C<T> d;"
  705. " (void)(&d)->t;"
  706. "}"
  707. "void instantiate() { declToImport<int>(); }",
  708. Lang_CXX, "", Lang_CXX, Verifier,
  709. functionTemplateDecl(hasDescendant(
  710. cStyleCastExpr(has(cxxDependentScopeMemberExpr())))));
  711. }
  712. TEST_P(ImportType, ImportTypeAliasTemplate) {
  713. MatchVerifier<Decl> Verifier;
  714. testImport(
  715. "template <int K>"
  716. "struct dummy { static const int i = K; };"
  717. "template <int K> using dummy2 = dummy<K>;"
  718. "int declToImport() { return dummy2<3>::i; }",
  719. Lang_CXX11, "", Lang_CXX11, Verifier,
  720. functionDecl(
  721. hasDescendant(implicitCastExpr(has(declRefExpr()))),
  722. unless(hasAncestor(translationUnitDecl(has(typeAliasDecl()))))));
  723. }
  724. const internal::VariadicDynCastAllOfMatcher<Decl, VarTemplateSpecializationDecl>
  725. varTemplateSpecializationDecl;
  726. TEST_P(ImportDecl, ImportVarTemplate) {
  727. MatchVerifier<Decl> Verifier;
  728. testImport(
  729. "template <typename T>"
  730. "T pi = T(3.1415926535897932385L);"
  731. "void declToImport() { (void)pi<int>; }",
  732. Lang_CXX14, "", Lang_CXX14, Verifier,
  733. functionDecl(
  734. hasDescendant(declRefExpr(to(varTemplateSpecializationDecl()))),
  735. unless(hasAncestor(translationUnitDecl(has(varDecl(
  736. hasName("pi"), unless(varTemplateSpecializationDecl()))))))));
  737. }
  738. TEST_P(ImportType, ImportPackExpansion) {
  739. MatchVerifier<Decl> Verifier;
  740. testImport(
  741. "template <typename... Args>"
  742. "struct dummy {"
  743. " dummy(Args... args) {}"
  744. " static const int i = 4;"
  745. "};"
  746. "int declToImport() { return dummy<int>::i; }",
  747. Lang_CXX11, "", Lang_CXX11, Verifier,
  748. functionDecl(hasDescendant(
  749. returnStmt(has(implicitCastExpr(has(declRefExpr())))))));
  750. }
  751. const internal::VariadicDynCastAllOfMatcher<Type,
  752. DependentTemplateSpecializationType>
  753. dependentTemplateSpecializationType;
  754. TEST_P(ImportType, ImportDependentTemplateSpecialization) {
  755. MatchVerifier<Decl> Verifier;
  756. testImport(
  757. "template<typename T>"
  758. "struct A;"
  759. "template<typename T>"
  760. "struct declToImport {"
  761. " typename A<T>::template B<T> a;"
  762. "};",
  763. Lang_CXX, "", Lang_CXX, Verifier,
  764. classTemplateDecl(has(cxxRecordDecl(has(
  765. fieldDecl(hasType(dependentTemplateSpecializationType())))))));
  766. }
  767. const internal::VariadicDynCastAllOfMatcher<Stmt, SizeOfPackExpr>
  768. sizeOfPackExpr;
  769. TEST_P(ImportExpr, ImportSizeOfPackExpr) {
  770. MatchVerifier<Decl> Verifier;
  771. testImport(
  772. "template <typename... Ts>"
  773. "void declToImport() {"
  774. " const int i = sizeof...(Ts);"
  775. "};"
  776. "void g() { declToImport<int>(); }",
  777. Lang_CXX11, "", Lang_CXX11, Verifier,
  778. functionTemplateDecl(hasDescendant(sizeOfPackExpr())));
  779. testImport(
  780. "template <typename... Ts>"
  781. "using X = int[sizeof...(Ts)];"
  782. "template <typename... Us>"
  783. "struct Y {"
  784. " X<Us..., int, double, int, Us...> f;"
  785. "};"
  786. "Y<float, int> declToImport;",
  787. Lang_CXX11, "", Lang_CXX11, Verifier,
  788. varDecl(hasType(classTemplateSpecializationDecl(has(fieldDecl(hasType(
  789. hasUnqualifiedDesugaredType(constantArrayType(hasSize(7))))))))));
  790. }
  791. /// \brief Matches __builtin_types_compatible_p:
  792. /// GNU extension to check equivalent types
  793. /// Given
  794. /// \code
  795. /// __builtin_types_compatible_p(int, int)
  796. /// \endcode
  797. // will generate TypeTraitExpr <...> 'int'
  798. const internal::VariadicDynCastAllOfMatcher<Stmt, TypeTraitExpr> typeTraitExpr;
  799. TEST_P(ImportExpr, ImportTypeTraitExpr) {
  800. MatchVerifier<Decl> Verifier;
  801. testImport(
  802. "void declToImport() { "
  803. " (void)__builtin_types_compatible_p(int, int);"
  804. "}",
  805. Lang_C, "", Lang_C, Verifier,
  806. functionDecl(hasDescendant(typeTraitExpr(hasType(asString("int"))))));
  807. }
  808. const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTypeidExpr> cxxTypeidExpr;
  809. TEST_P(ImportExpr, ImportCXXTypeidExpr) {
  810. MatchVerifier<Decl> Verifier;
  811. testImport(
  812. "namespace std { class type_info {}; }"
  813. "void declToImport() {"
  814. " int x;"
  815. " auto a = typeid(int); auto b = typeid(x);"
  816. "}",
  817. Lang_CXX11, "", Lang_CXX11, Verifier,
  818. functionDecl(
  819. hasDescendant(varDecl(
  820. hasName("a"), hasInitializer(hasDescendant(cxxTypeidExpr())))),
  821. hasDescendant(varDecl(
  822. hasName("b"), hasInitializer(hasDescendant(cxxTypeidExpr()))))));
  823. }
  824. TEST_P(ImportExpr, ImportTypeTraitExprValDep) {
  825. MatchVerifier<Decl> Verifier;
  826. testImport(
  827. "template<typename T> struct declToImport {"
  828. " void m() { (void)__is_pod(T); }"
  829. "};"
  830. "void f() { declToImport<int>().m(); }",
  831. Lang_CXX11, "", Lang_CXX11, Verifier,
  832. classTemplateDecl(has(cxxRecordDecl(has(
  833. functionDecl(hasDescendant(
  834. typeTraitExpr(hasType(booleanType())))))))));
  835. }
  836. TEST_P(ImportDecl, ImportRecordDeclInFunc) {
  837. MatchVerifier<Decl> Verifier;
  838. testImport("int declToImport() { "
  839. " struct data_t {int a;int b;};"
  840. " struct data_t d;"
  841. " return 0;"
  842. "}",
  843. Lang_C, "", Lang_C, Verifier,
  844. functionDecl(hasBody(compoundStmt(
  845. has(declStmt(hasSingleDecl(varDecl(hasName("d")))))))));
  846. }
  847. TEST_P(ASTImporterOptionSpecificTestBase, ImportRecordTypeInFunc) {
  848. Decl *FromTU = getTuDecl("int declToImport() { "
  849. " struct data_t {int a;int b;};"
  850. " struct data_t d;"
  851. " return 0;"
  852. "}",
  853. Lang_C, "input.c");
  854. auto *FromVar =
  855. FirstDeclMatcher<VarDecl>().match(FromTU, varDecl(hasName("d")));
  856. ASSERT_TRUE(FromVar);
  857. auto ToType =
  858. ImportType(FromVar->getType().getCanonicalType(), FromVar, Lang_C);
  859. EXPECT_FALSE(ToType.isNull());
  860. }
  861. TEST_P(ASTImporterOptionSpecificTestBase, ImportRecordDeclInFuncParams) {
  862. // This construct is not supported by ASTImporter.
  863. Decl *FromTU = getTuDecl(
  864. "int declToImport(struct data_t{int a;int b;} ***d){ return 0; }",
  865. Lang_C, "input.c");
  866. auto *From = FirstDeclMatcher<FunctionDecl>().match(
  867. FromTU, functionDecl(hasName("declToImport")));
  868. ASSERT_TRUE(From);
  869. auto *To = Import(From, Lang_C);
  870. EXPECT_EQ(To, nullptr);
  871. }
  872. TEST_P(ASTImporterOptionSpecificTestBase, ImportRecordDeclInFuncFromMacro) {
  873. Decl *FromTU = getTuDecl(
  874. "#define NONAME_SIZEOF(type) sizeof(struct{type *dummy;}) \n"
  875. "int declToImport(){ return NONAME_SIZEOF(int); }",
  876. Lang_C, "input.c");
  877. auto *From = FirstDeclMatcher<FunctionDecl>().match(
  878. FromTU, functionDecl(hasName("declToImport")));
  879. ASSERT_TRUE(From);
  880. auto *To = Import(From, Lang_C);
  881. ASSERT_TRUE(To);
  882. EXPECT_TRUE(MatchVerifier<FunctionDecl>().match(
  883. To, functionDecl(hasName("declToImport"),
  884. hasDescendant(unaryExprOrTypeTraitExpr()))));
  885. }
  886. TEST_P(ASTImporterOptionSpecificTestBase,
  887. ImportRecordDeclInFuncParamsFromMacro) {
  888. // This construct is not supported by ASTImporter.
  889. Decl *FromTU = getTuDecl(
  890. "#define PAIR_STRUCT(type) struct data_t{type a;type b;} \n"
  891. "int declToImport(PAIR_STRUCT(int) ***d){ return 0; }",
  892. Lang_C, "input.c");
  893. auto *From = FirstDeclMatcher<FunctionDecl>().match(
  894. FromTU, functionDecl(hasName("declToImport")));
  895. ASSERT_TRUE(From);
  896. auto *To = Import(From, Lang_C);
  897. EXPECT_EQ(To, nullptr);
  898. }
  899. const internal::VariadicDynCastAllOfMatcher<Expr, CXXPseudoDestructorExpr>
  900. cxxPseudoDestructorExpr;
  901. TEST_P(ImportExpr, ImportCXXPseudoDestructorExpr) {
  902. MatchVerifier<Decl> Verifier;
  903. testImport(
  904. "typedef int T;"
  905. "void declToImport(int *p) {"
  906. " T t;"
  907. " p->T::~T();"
  908. "}",
  909. Lang_CXX, "", Lang_CXX, Verifier,
  910. functionDecl(hasDescendant(
  911. callExpr(has(cxxPseudoDestructorExpr())))));
  912. }
  913. TEST_P(ImportDecl, ImportUsingDecl) {
  914. MatchVerifier<Decl> Verifier;
  915. testImport(
  916. "namespace foo { int bar; }"
  917. "void declToImport() { using foo::bar; }",
  918. Lang_CXX, "", Lang_CXX, Verifier,
  919. functionDecl(hasDescendant(usingDecl())));
  920. }
  921. /// \brief Matches shadow declarations introduced into a scope by a
  922. /// (resolved) using declaration.
  923. ///
  924. /// Given
  925. /// \code
  926. /// namespace n { int f; }
  927. /// namespace declToImport { using n::f; }
  928. /// \endcode
  929. /// usingShadowDecl()
  930. /// matches \code f \endcode
  931. const internal::VariadicDynCastAllOfMatcher<Decl,
  932. UsingShadowDecl> usingShadowDecl;
  933. TEST_P(ImportDecl, ImportUsingShadowDecl) {
  934. MatchVerifier<Decl> Verifier;
  935. testImport(
  936. "namespace foo { int bar; }"
  937. "namespace declToImport { using foo::bar; }",
  938. Lang_CXX, "", Lang_CXX, Verifier,
  939. namespaceDecl(has(usingShadowDecl())));
  940. }
  941. TEST_P(ImportExpr, ImportUnresolvedLookupExpr) {
  942. MatchVerifier<Decl> Verifier;
  943. testImport(
  944. "template<typename T> int foo();"
  945. "template <typename T> void declToImport() {"
  946. " (void)::foo<T>;"
  947. " (void)::template foo<T>;"
  948. "}"
  949. "void instantiate() { declToImport<int>(); }",
  950. Lang_CXX, "", Lang_CXX, Verifier,
  951. functionTemplateDecl(hasDescendant(unresolvedLookupExpr())));
  952. }
  953. TEST_P(ImportExpr, ImportCXXUnresolvedConstructExpr) {
  954. MatchVerifier<Decl> Verifier;
  955. testImport(
  956. "template <typename T> struct C { T t; };"
  957. "template <typename T> void declToImport() {"
  958. " C<T> d;"
  959. " d.t = T();"
  960. "}"
  961. "void instantiate() { declToImport<int>(); }",
  962. Lang_CXX, "", Lang_CXX, Verifier,
  963. functionTemplateDecl(hasDescendant(
  964. binaryOperator(has(cxxUnresolvedConstructExpr())))));
  965. testImport(
  966. "template <typename T> struct C { T t; };"
  967. "template <typename T> void declToImport() {"
  968. " C<T> d;"
  969. " (&d)->t = T();"
  970. "}"
  971. "void instantiate() { declToImport<int>(); }",
  972. Lang_CXX, "", Lang_CXX, Verifier,
  973. functionTemplateDecl(hasDescendant(
  974. binaryOperator(has(cxxUnresolvedConstructExpr())))));
  975. }
  976. /// Check that function "declToImport()" (which is the templated function
  977. /// for corresponding FunctionTemplateDecl) is not added into DeclContext.
  978. /// Same for class template declarations.
  979. TEST_P(ImportDecl, ImportTemplatedDeclForTemplate) {
  980. MatchVerifier<Decl> Verifier;
  981. testImport(
  982. "template <typename T> void declToImport() { T a = 1; }"
  983. "void instantiate() { declToImport<int>(); }",
  984. Lang_CXX, "", Lang_CXX, Verifier,
  985. functionTemplateDecl(hasAncestor(translationUnitDecl(
  986. unless(has(functionDecl(hasName("declToImport"))))))));
  987. testImport(
  988. "template <typename T> struct declToImport { T t; };"
  989. "void instantiate() { declToImport<int>(); }",
  990. Lang_CXX, "", Lang_CXX, Verifier,
  991. classTemplateDecl(hasAncestor(translationUnitDecl(
  992. unless(has(cxxRecordDecl(hasName("declToImport"))))))));
  993. }
  994. TEST_P(ImportDecl, ImportClassTemplatePartialSpecialization) {
  995. MatchVerifier<Decl> Verifier;
  996. auto Code =
  997. R"s(
  998. struct declToImport {
  999. template <typename T0> struct X;
  1000. template <typename T0> struct X<T0 *> {};
  1001. };
  1002. )s";
  1003. testImport(Code, Lang_CXX, "", Lang_CXX, Verifier,
  1004. recordDecl(has(classTemplateDecl()),
  1005. has(classTemplateSpecializationDecl())));
  1006. }
  1007. TEST_P(ImportExpr, CXXOperatorCallExpr) {
  1008. MatchVerifier<Decl> Verifier;
  1009. testImport(
  1010. "class declToImport {"
  1011. " void f() { *this = declToImport(); }"
  1012. "};",
  1013. Lang_CXX, "", Lang_CXX, Verifier,
  1014. cxxRecordDecl(has(cxxMethodDecl(hasDescendant(
  1015. cxxOperatorCallExpr())))));
  1016. }
  1017. TEST_P(ImportExpr, DependentSizedArrayType) {
  1018. MatchVerifier<Decl> Verifier;
  1019. testImport(
  1020. "template<typename T, int Size> class declToImport {"
  1021. " T data[Size];"
  1022. "};",
  1023. Lang_CXX, "", Lang_CXX, Verifier,
  1024. classTemplateDecl(has(cxxRecordDecl(
  1025. has(fieldDecl(hasType(dependentSizedArrayType())))))));
  1026. }
  1027. TEST_P(ASTImporterOptionSpecificTestBase, ImportBeginLocOfDeclRefExpr) {
  1028. Decl *FromTU = getTuDecl(
  1029. "class A { public: static int X; }; void f() { (void)A::X; }", Lang_CXX);
  1030. auto From = FirstDeclMatcher<FunctionDecl>().match(
  1031. FromTU, functionDecl(hasName("f")));
  1032. ASSERT_TRUE(From);
  1033. ASSERT_TRUE(
  1034. cast<CStyleCastExpr>(cast<CompoundStmt>(From->getBody())->body_front())
  1035. ->getSubExpr()
  1036. ->getBeginLoc()
  1037. .isValid());
  1038. FunctionDecl *To = Import(From, Lang_CXX);
  1039. ASSERT_TRUE(To);
  1040. ASSERT_TRUE(
  1041. cast<CStyleCastExpr>(cast<CompoundStmt>(To->getBody())->body_front())
  1042. ->getSubExpr()
  1043. ->getBeginLoc()
  1044. .isValid());
  1045. }
  1046. TEST_P(ASTImporterOptionSpecificTestBase,
  1047. ImportOfTemplatedDeclOfClassTemplateDecl) {
  1048. Decl *FromTU = getTuDecl("template<class X> struct S{};", Lang_CXX);
  1049. auto From =
  1050. FirstDeclMatcher<ClassTemplateDecl>().match(FromTU, classTemplateDecl());
  1051. ASSERT_TRUE(From);
  1052. auto To = cast<ClassTemplateDecl>(Import(From, Lang_CXX));
  1053. ASSERT_TRUE(To);
  1054. Decl *ToTemplated = To->getTemplatedDecl();
  1055. Decl *ToTemplated1 = Import(From->getTemplatedDecl(), Lang_CXX);
  1056. EXPECT_TRUE(ToTemplated1);
  1057. EXPECT_EQ(ToTemplated1, ToTemplated);
  1058. }
  1059. TEST_P(ASTImporterOptionSpecificTestBase,
  1060. ImportOfTemplatedDeclOfFunctionTemplateDecl) {
  1061. Decl *FromTU = getTuDecl("template<class X> void f(){}", Lang_CXX);
  1062. auto From = FirstDeclMatcher<FunctionTemplateDecl>().match(
  1063. FromTU, functionTemplateDecl());
  1064. ASSERT_TRUE(From);
  1065. auto To = cast<FunctionTemplateDecl>(Import(From, Lang_CXX));
  1066. ASSERT_TRUE(To);
  1067. Decl *ToTemplated = To->getTemplatedDecl();
  1068. Decl *ToTemplated1 = Import(From->getTemplatedDecl(), Lang_CXX);
  1069. EXPECT_TRUE(ToTemplated1);
  1070. EXPECT_EQ(ToTemplated1, ToTemplated);
  1071. }
  1072. TEST_P(ASTImporterOptionSpecificTestBase,
  1073. ImportOfTemplatedDeclShouldImportTheClassTemplateDecl) {
  1074. Decl *FromTU = getTuDecl("template<class X> struct S{};", Lang_CXX);
  1075. auto FromFT =
  1076. FirstDeclMatcher<ClassTemplateDecl>().match(FromTU, classTemplateDecl());
  1077. ASSERT_TRUE(FromFT);
  1078. auto ToTemplated =
  1079. cast<CXXRecordDecl>(Import(FromFT->getTemplatedDecl(), Lang_CXX));
  1080. EXPECT_TRUE(ToTemplated);
  1081. auto ToTU = ToTemplated->getTranslationUnitDecl();
  1082. auto ToFT =
  1083. FirstDeclMatcher<ClassTemplateDecl>().match(ToTU, classTemplateDecl());
  1084. EXPECT_TRUE(ToFT);
  1085. }
  1086. TEST_P(ASTImporterOptionSpecificTestBase,
  1087. ImportOfTemplatedDeclShouldImportTheFunctionTemplateDecl) {
  1088. Decl *FromTU = getTuDecl("template<class X> void f(){}", Lang_CXX);
  1089. auto FromFT = FirstDeclMatcher<FunctionTemplateDecl>().match(
  1090. FromTU, functionTemplateDecl());
  1091. ASSERT_TRUE(FromFT);
  1092. auto ToTemplated =
  1093. cast<FunctionDecl>(Import(FromFT->getTemplatedDecl(), Lang_CXX));
  1094. EXPECT_TRUE(ToTemplated);
  1095. auto ToTU = ToTemplated->getTranslationUnitDecl();
  1096. auto ToFT = FirstDeclMatcher<FunctionTemplateDecl>().match(
  1097. ToTU, functionTemplateDecl());
  1098. EXPECT_TRUE(ToFT);
  1099. }
  1100. TEST_P(ASTImporterOptionSpecificTestBase, ImportCorrectTemplatedDecl) {
  1101. auto Code =
  1102. R"(
  1103. namespace x {
  1104. template<class X> struct S1{};
  1105. template<class X> struct S2{};
  1106. template<class X> struct S3{};
  1107. }
  1108. )";
  1109. Decl *FromTU = getTuDecl(Code, Lang_CXX);
  1110. auto FromNs =
  1111. FirstDeclMatcher<NamespaceDecl>().match(FromTU, namespaceDecl());
  1112. auto ToNs = cast<NamespaceDecl>(Import(FromNs, Lang_CXX));
  1113. ASSERT_TRUE(ToNs);
  1114. auto From =
  1115. FirstDeclMatcher<ClassTemplateDecl>().match(FromTU,
  1116. classTemplateDecl(
  1117. hasName("S2")));
  1118. auto To =
  1119. FirstDeclMatcher<ClassTemplateDecl>().match(ToNs,
  1120. classTemplateDecl(
  1121. hasName("S2")));
  1122. ASSERT_TRUE(From);
  1123. ASSERT_TRUE(To);
  1124. auto ToTemplated = To->getTemplatedDecl();
  1125. auto ToTemplated1 =
  1126. cast<CXXRecordDecl>(Import(From->getTemplatedDecl(), Lang_CXX));
  1127. EXPECT_TRUE(ToTemplated1);
  1128. ASSERT_EQ(ToTemplated1, ToTemplated);
  1129. }
  1130. TEST_P(ASTImporterOptionSpecificTestBase, ImportChooseExpr) {
  1131. // This tests the import of isConditionTrue directly to make sure the importer
  1132. // gets it right.
  1133. Decl *From, *To;
  1134. std::tie(From, To) = getImportedDecl(
  1135. "void declToImport() { (void)__builtin_choose_expr(1, 0, 1); }",
  1136. Lang_C, "", Lang_C);
  1137. auto ToResults = match(chooseExpr().bind("choose"), To->getASTContext());
  1138. auto FromResults = match(chooseExpr().bind("choose"), From->getASTContext());
  1139. const ChooseExpr *FromChooseExpr =
  1140. selectFirst<ChooseExpr>("choose", FromResults);
  1141. ASSERT_TRUE(FromChooseExpr);
  1142. const ChooseExpr *ToChooseExpr = selectFirst<ChooseExpr>("choose", ToResults);
  1143. ASSERT_TRUE(ToChooseExpr);
  1144. EXPECT_EQ(FromChooseExpr->isConditionTrue(), ToChooseExpr->isConditionTrue());
  1145. EXPECT_EQ(FromChooseExpr->isConditionDependent(),
  1146. ToChooseExpr->isConditionDependent());
  1147. }
  1148. TEST_P(ASTImporterOptionSpecificTestBase,
  1149. ImportFunctionWithBackReferringParameter) {
  1150. Decl *From, *To;
  1151. std::tie(From, To) = getImportedDecl(
  1152. R"(
  1153. template <typename T> struct X {};
  1154. void declToImport(int y, X<int> &x) {}
  1155. template <> struct X<int> {
  1156. void g() {
  1157. X<int> x;
  1158. declToImport(0, x);
  1159. }
  1160. };
  1161. )",
  1162. Lang_CXX, "", Lang_CXX);
  1163. MatchVerifier<Decl> Verifier;
  1164. auto Matcher = functionDecl(hasName("declToImport"),
  1165. parameterCountIs(2),
  1166. hasParameter(0, hasName("y")),
  1167. hasParameter(1, hasName("x")),
  1168. hasParameter(1, hasType(asString("X<int> &"))));
  1169. ASSERT_TRUE(Verifier.match(From, Matcher));
  1170. EXPECT_TRUE(Verifier.match(To, Matcher));
  1171. }
  1172. TEST_P(ASTImporterOptionSpecificTestBase,
  1173. TUshouldNotContainTemplatedDeclOfFunctionTemplates) {
  1174. Decl *From, *To;
  1175. std::tie(From, To) =
  1176. getImportedDecl("template <typename T> void declToImport() { T a = 1; }"
  1177. "void instantiate() { declToImport<int>(); }",
  1178. Lang_CXX, "", Lang_CXX);
  1179. auto Check = [](Decl *D) -> bool {
  1180. auto TU = D->getTranslationUnitDecl();
  1181. for (auto Child : TU->decls()) {
  1182. if (auto *FD = dyn_cast<FunctionDecl>(Child)) {
  1183. if (FD->getNameAsString() == "declToImport") {
  1184. GTEST_NONFATAL_FAILURE_(
  1185. "TU should not contain any FunctionDecl with name declToImport");
  1186. return false;
  1187. }
  1188. }
  1189. }
  1190. return true;
  1191. };
  1192. ASSERT_TRUE(Check(From));
  1193. EXPECT_TRUE(Check(To));
  1194. }
  1195. TEST_P(ASTImporterOptionSpecificTestBase,
  1196. TUshouldNotContainTemplatedDeclOfClassTemplates) {
  1197. Decl *From, *To;
  1198. std::tie(From, To) =
  1199. getImportedDecl("template <typename T> struct declToImport { T t; };"
  1200. "void instantiate() { declToImport<int>(); }",
  1201. Lang_CXX, "", Lang_CXX);
  1202. auto Check = [](Decl *D) -> bool {
  1203. auto TU = D->getTranslationUnitDecl();
  1204. for (auto Child : TU->decls()) {
  1205. if (auto *RD = dyn_cast<CXXRecordDecl>(Child)) {
  1206. if (RD->getNameAsString() == "declToImport") {
  1207. GTEST_NONFATAL_FAILURE_(
  1208. "TU should not contain any CXXRecordDecl with name declToImport");
  1209. return false;
  1210. }
  1211. }
  1212. }
  1213. return true;
  1214. };
  1215. ASSERT_TRUE(Check(From));
  1216. EXPECT_TRUE(Check(To));
  1217. }
  1218. TEST_P(ASTImporterOptionSpecificTestBase,
  1219. TUshouldNotContainTemplatedDeclOfTypeAlias) {
  1220. Decl *From, *To;
  1221. std::tie(From, To) =
  1222. getImportedDecl(
  1223. "template <typename T> struct X {};"
  1224. "template <typename T> using declToImport = X<T>;"
  1225. "void instantiate() { declToImport<int> a; }",
  1226. Lang_CXX11, "", Lang_CXX11);
  1227. auto Check = [](Decl *D) -> bool {
  1228. auto TU = D->getTranslationUnitDecl();
  1229. for (auto Child : TU->decls()) {
  1230. if (auto *AD = dyn_cast<TypeAliasDecl>(Child)) {
  1231. if (AD->getNameAsString() == "declToImport") {
  1232. GTEST_NONFATAL_FAILURE_(
  1233. "TU should not contain any TypeAliasDecl with name declToImport");
  1234. return false;
  1235. }
  1236. }
  1237. }
  1238. return true;
  1239. };
  1240. ASSERT_TRUE(Check(From));
  1241. EXPECT_TRUE(Check(To));
  1242. }
  1243. TEST_P(ASTImporterOptionSpecificTestBase,
  1244. TUshouldNotContainClassTemplateSpecializationOfImplicitInstantiation) {
  1245. Decl *From, *To;
  1246. std::tie(From, To) = getImportedDecl(
  1247. R"(
  1248. template<class T>
  1249. class Base {};
  1250. class declToImport : public Base<declToImport> {};
  1251. )",
  1252. Lang_CXX, "", Lang_CXX);
  1253. // Check that the ClassTemplateSpecializationDecl is NOT the child of the TU.
  1254. auto Pattern =
  1255. translationUnitDecl(unless(has(classTemplateSpecializationDecl())));
  1256. ASSERT_TRUE(
  1257. MatchVerifier<Decl>{}.match(From->getTranslationUnitDecl(), Pattern));
  1258. EXPECT_TRUE(
  1259. MatchVerifier<Decl>{}.match(To->getTranslationUnitDecl(), Pattern));
  1260. // Check that the ClassTemplateSpecializationDecl is the child of the
  1261. // ClassTemplateDecl.
  1262. Pattern = translationUnitDecl(has(classTemplateDecl(
  1263. hasName("Base"), has(classTemplateSpecializationDecl()))));
  1264. ASSERT_TRUE(
  1265. MatchVerifier<Decl>{}.match(From->getTranslationUnitDecl(), Pattern));
  1266. EXPECT_TRUE(
  1267. MatchVerifier<Decl>{}.match(To->getTranslationUnitDecl(), Pattern));
  1268. }
  1269. AST_MATCHER_P(RecordDecl, hasFieldOrder, std::vector<StringRef>, Order) {
  1270. size_t Index = 0;
  1271. for (Decl *D : Node.decls()) {
  1272. if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) {
  1273. auto *ND = cast<NamedDecl>(D);
  1274. if (Index == Order.size())
  1275. return false;
  1276. if (ND->getName() != Order[Index])
  1277. return false;
  1278. ++Index;
  1279. }
  1280. }
  1281. return Index == Order.size();
  1282. }
  1283. TEST_P(ASTImporterOptionSpecificTestBase,
  1284. TUshouldContainClassTemplateSpecializationOfExplicitInstantiation) {
  1285. Decl *From, *To;
  1286. std::tie(From, To) = getImportedDecl(
  1287. R"(
  1288. namespace NS {
  1289. template<class T>
  1290. class X {};
  1291. template class X<int>;
  1292. }
  1293. )",
  1294. Lang_CXX, "", Lang_CXX, "NS");
  1295. // Check that the ClassTemplateSpecializationDecl is NOT the child of the
  1296. // ClassTemplateDecl.
  1297. auto Pattern = namespaceDecl(has(classTemplateDecl(
  1298. hasName("X"), unless(has(classTemplateSpecializationDecl())))));
  1299. ASSERT_TRUE(MatchVerifier<Decl>{}.match(From, Pattern));
  1300. EXPECT_TRUE(MatchVerifier<Decl>{}.match(To, Pattern));
  1301. // Check that the ClassTemplateSpecializationDecl is the child of the
  1302. // NamespaceDecl.
  1303. Pattern = namespaceDecl(has(classTemplateSpecializationDecl(hasName("X"))));
  1304. ASSERT_TRUE(MatchVerifier<Decl>{}.match(From, Pattern));
  1305. EXPECT_TRUE(MatchVerifier<Decl>{}.match(To, Pattern));
  1306. }
  1307. TEST_P(ASTImporterOptionSpecificTestBase,
  1308. CXXRecordDeclFieldsShouldBeInCorrectOrder) {
  1309. Decl *From, *To;
  1310. std::tie(From, To) =
  1311. getImportedDecl(
  1312. "struct declToImport { int a; int b; };",
  1313. Lang_CXX11, "", Lang_CXX11);
  1314. MatchVerifier<Decl> Verifier;
  1315. ASSERT_TRUE(Verifier.match(From, cxxRecordDecl(hasFieldOrder({"a", "b"}))));
  1316. EXPECT_TRUE(Verifier.match(To, cxxRecordDecl(hasFieldOrder({"a", "b"}))));
  1317. }
  1318. TEST_P(ASTImporterOptionSpecificTestBase,
  1319. CXXRecordDeclFieldOrderShouldNotDependOnImportOrder) {
  1320. Decl *From, *To;
  1321. std::tie(From, To) = getImportedDecl(
  1322. // The original recursive algorithm of ASTImporter first imports 'c' then
  1323. // 'b' and lastly 'a'. Therefore we must restore the order somehow.
  1324. R"s(
  1325. struct declToImport {
  1326. int a = c + b;
  1327. int b = 1;
  1328. int c = 2;
  1329. };
  1330. )s",
  1331. Lang_CXX11, "", Lang_CXX11);
  1332. MatchVerifier<Decl> Verifier;
  1333. ASSERT_TRUE(
  1334. Verifier.match(From, cxxRecordDecl(hasFieldOrder({"a", "b", "c"}))));
  1335. EXPECT_TRUE(
  1336. Verifier.match(To, cxxRecordDecl(hasFieldOrder({"a", "b", "c"}))));
  1337. }
  1338. TEST_P(ASTImporterOptionSpecificTestBase,
  1339. CXXRecordDeclFieldAndIndirectFieldOrder) {
  1340. Decl *From, *To;
  1341. std::tie(From, To) = getImportedDecl(
  1342. // First field is "a", then the field for unnamed union, then "b" and "c"
  1343. // from it (indirect fields), then "d".
  1344. R"s(
  1345. struct declToImport {
  1346. int a = d;
  1347. union {
  1348. int b;
  1349. int c;
  1350. };
  1351. int d;
  1352. };
  1353. )s",
  1354. Lang_CXX11, "", Lang_CXX11);
  1355. MatchVerifier<Decl> Verifier;
  1356. ASSERT_TRUE(Verifier.match(
  1357. From, cxxRecordDecl(hasFieldOrder({"a", "", "b", "c", "d"}))));
  1358. EXPECT_TRUE(Verifier.match(
  1359. To, cxxRecordDecl(hasFieldOrder({"a", "", "b", "c", "d"}))));
  1360. }
  1361. TEST_P(ASTImporterOptionSpecificTestBase, ShouldImportImplicitCXXRecordDecl) {
  1362. Decl *From, *To;
  1363. std::tie(From, To) = getImportedDecl(
  1364. R"(
  1365. struct declToImport {
  1366. };
  1367. )",
  1368. Lang_CXX, "", Lang_CXX);
  1369. MatchVerifier<Decl> Verifier;
  1370. // Match the implicit Decl.
  1371. auto Matcher = cxxRecordDecl(has(cxxRecordDecl()));
  1372. ASSERT_TRUE(Verifier.match(From, Matcher));
  1373. EXPECT_TRUE(Verifier.match(To, Matcher));
  1374. }
  1375. TEST_P(ASTImporterOptionSpecificTestBase,
  1376. ShouldImportImplicitCXXRecordDeclOfClassTemplate) {
  1377. Decl *From, *To;
  1378. std::tie(From, To) = getImportedDecl(
  1379. R"(
  1380. template <typename U>
  1381. struct declToImport {
  1382. };
  1383. )",
  1384. Lang_CXX, "", Lang_CXX);
  1385. MatchVerifier<Decl> Verifier;
  1386. // Match the implicit Decl.
  1387. auto Matcher = classTemplateDecl(has(cxxRecordDecl(has(cxxRecordDecl()))));
  1388. ASSERT_TRUE(Verifier.match(From, Matcher));
  1389. EXPECT_TRUE(Verifier.match(To, Matcher));
  1390. }
  1391. TEST_P(ASTImporterOptionSpecificTestBase,
  1392. ShouldImportImplicitCXXRecordDeclOfClassTemplateSpecializationDecl) {
  1393. Decl *From, *To;
  1394. std::tie(From, To) = getImportedDecl(
  1395. R"(
  1396. template<class T>
  1397. class Base {};
  1398. class declToImport : public Base<declToImport> {};
  1399. )",
  1400. Lang_CXX, "", Lang_CXX);
  1401. auto hasImplicitClass = has(cxxRecordDecl());
  1402. auto Pattern = translationUnitDecl(has(classTemplateDecl(
  1403. hasName("Base"),
  1404. has(classTemplateSpecializationDecl(hasImplicitClass)))));
  1405. ASSERT_TRUE(
  1406. MatchVerifier<Decl>{}.match(From->getTranslationUnitDecl(), Pattern));
  1407. EXPECT_TRUE(
  1408. MatchVerifier<Decl>{}.match(To->getTranslationUnitDecl(), Pattern));
  1409. }
  1410. TEST_P(ASTImporterOptionSpecificTestBase, IDNSOrdinary) {
  1411. Decl *From, *To;
  1412. std::tie(From, To) =
  1413. getImportedDecl("void declToImport() {}", Lang_CXX, "", Lang_CXX);
  1414. MatchVerifier<Decl> Verifier;
  1415. auto Matcher = functionDecl();
  1416. ASSERT_TRUE(Verifier.match(From, Matcher));
  1417. EXPECT_TRUE(Verifier.match(To, Matcher));
  1418. EXPECT_EQ(From->getIdentifierNamespace(), To->getIdentifierNamespace());
  1419. }
  1420. TEST_P(ASTImporterOptionSpecificTestBase, IDNSOfNonmemberOperator) {
  1421. Decl *FromTU = getTuDecl(
  1422. R"(
  1423. struct X {};
  1424. void operator<<(int, X);
  1425. )",
  1426. Lang_CXX);
  1427. Decl *From = LastDeclMatcher<Decl>{}.match(FromTU, functionDecl());
  1428. const Decl *To = Import(From, Lang_CXX);
  1429. EXPECT_EQ(From->getIdentifierNamespace(), To->getIdentifierNamespace());
  1430. }
  1431. TEST_P(ASTImporterOptionSpecificTestBase,
  1432. ShouldImportMembersOfClassTemplateSpecializationDecl) {
  1433. Decl *From, *To;
  1434. std::tie(From, To) = getImportedDecl(
  1435. R"(
  1436. template<class T>
  1437. class Base { int a; };
  1438. class declToImport : Base<declToImport> {};
  1439. )",
  1440. Lang_CXX, "", Lang_CXX);
  1441. auto Pattern = translationUnitDecl(has(classTemplateDecl(
  1442. hasName("Base"),
  1443. has(classTemplateSpecializationDecl(has(fieldDecl(hasName("a"))))))));
  1444. ASSERT_TRUE(
  1445. MatchVerifier<Decl>{}.match(From->getTranslationUnitDecl(), Pattern));
  1446. EXPECT_TRUE(
  1447. MatchVerifier<Decl>{}.match(To->getTranslationUnitDecl(), Pattern));
  1448. }
  1449. TEST_P(ASTImporterOptionSpecificTestBase,
  1450. ImportDefinitionOfClassTemplateAfterFwdDecl) {
  1451. {
  1452. Decl *FromTU = getTuDecl(
  1453. R"(
  1454. template <typename T>
  1455. struct B;
  1456. )",
  1457. Lang_CXX, "input0.cc");
  1458. auto *FromD = FirstDeclMatcher<ClassTemplateDecl>().match(
  1459. FromTU, classTemplateDecl(hasName("B")));
  1460. Import(FromD, Lang_CXX);
  1461. }
  1462. {
  1463. Decl *FromTU = getTuDecl(
  1464. R"(
  1465. template <typename T>
  1466. struct B {
  1467. void f();
  1468. };
  1469. )",
  1470. Lang_CXX, "input1.cc");
  1471. FunctionDecl *FromD = FirstDeclMatcher<FunctionDecl>().match(
  1472. FromTU, functionDecl(hasName("f")));
  1473. Import(FromD, Lang_CXX);
  1474. auto *FromCTD = FirstDeclMatcher<ClassTemplateDecl>().match(
  1475. FromTU, classTemplateDecl(hasName("B")));
  1476. auto *ToCTD = cast<ClassTemplateDecl>(Import(FromCTD, Lang_CXX));
  1477. EXPECT_TRUE(ToCTD->isThisDeclarationADefinition());
  1478. }
  1479. }
  1480. TEST_P(ASTImporterOptionSpecificTestBase,
  1481. ImportDefinitionOfClassTemplateIfThereIsAnExistingFwdDeclAndDefinition) {
  1482. Decl *ToTU = getToTuDecl(
  1483. R"(
  1484. template <typename T>
  1485. struct B {
  1486. void f();
  1487. };
  1488. template <typename T>
  1489. struct B;
  1490. )",
  1491. Lang_CXX);
  1492. ASSERT_EQ(1u, DeclCounterWithPredicate<ClassTemplateDecl>(
  1493. [](const ClassTemplateDecl *T) {
  1494. return T->isThisDeclarationADefinition();
  1495. })
  1496. .match(ToTU, classTemplateDecl()));
  1497. Decl *FromTU = getTuDecl(
  1498. R"(
  1499. template <typename T>
  1500. struct B {
  1501. void f();
  1502. };
  1503. )",
  1504. Lang_CXX, "input1.cc");
  1505. ClassTemplateDecl *FromD = FirstDeclMatcher<ClassTemplateDecl>().match(
  1506. FromTU, classTemplateDecl(hasName("B")));
  1507. Import(FromD, Lang_CXX);
  1508. // We should have only one definition.
  1509. EXPECT_EQ(1u, DeclCounterWithPredicate<ClassTemplateDecl>(
  1510. [](const ClassTemplateDecl *T) {
  1511. return T->isThisDeclarationADefinition();
  1512. })
  1513. .match(ToTU, classTemplateDecl()));
  1514. }
  1515. TEST_P(ASTImporterOptionSpecificTestBase,
  1516. ImportDefinitionOfClassIfThereIsAnExistingFwdDeclAndDefinition) {
  1517. Decl *ToTU = getToTuDecl(
  1518. R"(
  1519. struct B {
  1520. void f();
  1521. };
  1522. struct B;
  1523. )",
  1524. Lang_CXX);
  1525. ASSERT_EQ(2u, DeclCounter<CXXRecordDecl>().match(
  1526. ToTU, cxxRecordDecl(unless(isImplicit()))));
  1527. Decl *FromTU = getTuDecl(
  1528. R"(
  1529. struct B {
  1530. void f();
  1531. };
  1532. )",
  1533. Lang_CXX, "input1.cc");
  1534. auto *FromD = FirstDeclMatcher<CXXRecordDecl>().match(
  1535. FromTU, cxxRecordDecl(hasName("B")));
  1536. Import(FromD, Lang_CXX);
  1537. EXPECT_EQ(2u, DeclCounter<CXXRecordDecl>().match(
  1538. ToTU, cxxRecordDecl(unless(isImplicit()))));
  1539. }
  1540. static void CompareSourceLocs(FullSourceLoc Loc1, FullSourceLoc Loc2) {
  1541. EXPECT_EQ(Loc1.getExpansionLineNumber(), Loc2.getExpansionLineNumber());
  1542. EXPECT_EQ(Loc1.getExpansionColumnNumber(), Loc2.getExpansionColumnNumber());
  1543. EXPECT_EQ(Loc1.getSpellingLineNumber(), Loc2.getSpellingLineNumber());
  1544. EXPECT_EQ(Loc1.getSpellingColumnNumber(), Loc2.getSpellingColumnNumber());
  1545. }
  1546. static void CompareSourceRanges(SourceRange Range1, SourceRange Range2,
  1547. SourceManager &SM1, SourceManager &SM2) {
  1548. CompareSourceLocs(FullSourceLoc{ Range1.getBegin(), SM1 },
  1549. FullSourceLoc{ Range2.getBegin(), SM2 });
  1550. CompareSourceLocs(FullSourceLoc{ Range1.getEnd(), SM1 },
  1551. FullSourceLoc{ Range2.getEnd(), SM2 });
  1552. }
  1553. TEST_P(ASTImporterOptionSpecificTestBase, ImportSourceLocs) {
  1554. Decl *FromTU = getTuDecl(
  1555. R"(
  1556. #define MFOO(arg) arg = arg + 1
  1557. void foo() {
  1558. int a = 5;
  1559. MFOO(a);
  1560. }
  1561. )",
  1562. Lang_CXX);
  1563. auto FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, functionDecl());
  1564. auto ToD = Import(FromD, Lang_CXX);
  1565. auto ToLHS = LastDeclMatcher<DeclRefExpr>().match(ToD, declRefExpr());
  1566. auto FromLHS = LastDeclMatcher<DeclRefExpr>().match(FromTU, declRefExpr());
  1567. auto ToRHS = LastDeclMatcher<IntegerLiteral>().match(ToD, integerLiteral());
  1568. auto FromRHS =
  1569. LastDeclMatcher<IntegerLiteral>().match(FromTU, integerLiteral());
  1570. SourceManager &ToSM = ToAST->getASTContext().getSourceManager();
  1571. SourceManager &FromSM = FromD->getASTContext().getSourceManager();
  1572. CompareSourceRanges(ToD->getSourceRange(), FromD->getSourceRange(), ToSM,
  1573. FromSM);
  1574. CompareSourceRanges(ToLHS->getSourceRange(), FromLHS->getSourceRange(), ToSM,
  1575. FromSM);
  1576. CompareSourceRanges(ToRHS->getSourceRange(), FromRHS->getSourceRange(), ToSM,
  1577. FromSM);
  1578. }
  1579. TEST_P(ASTImporterOptionSpecificTestBase, ImportNestedMacro) {
  1580. Decl *FromTU = getTuDecl(
  1581. R"(
  1582. #define FUNC_INT void declToImport
  1583. #define FUNC FUNC_INT
  1584. FUNC(int a);
  1585. )",
  1586. Lang_CXX);
  1587. auto FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, functionDecl());
  1588. auto ToD = Import(FromD, Lang_CXX);
  1589. SourceManager &ToSM = ToAST->getASTContext().getSourceManager();
  1590. SourceManager &FromSM = FromD->getASTContext().getSourceManager();
  1591. CompareSourceRanges(ToD->getSourceRange(), FromD->getSourceRange(), ToSM,
  1592. FromSM);
  1593. }
  1594. TEST_P(
  1595. ASTImporterOptionSpecificTestBase,
  1596. ImportDefinitionOfClassTemplateSpecIfThereIsAnExistingFwdDeclAndDefinition) {
  1597. Decl *ToTU = getToTuDecl(
  1598. R"(
  1599. template <typename T>
  1600. struct B;
  1601. template <>
  1602. struct B<int> {};
  1603. template <>
  1604. struct B<int>;
  1605. )",
  1606. Lang_CXX);
  1607. // We should have only one definition.
  1608. ASSERT_EQ(1u, DeclCounterWithPredicate<ClassTemplateSpecializationDecl>(
  1609. [](const ClassTemplateSpecializationDecl *T) {
  1610. return T->isThisDeclarationADefinition();
  1611. })
  1612. .match(ToTU, classTemplateSpecializationDecl()));
  1613. Decl *FromTU = getTuDecl(
  1614. R"(
  1615. template <typename T>
  1616. struct B;
  1617. template <>
  1618. struct B<int> {};
  1619. )",
  1620. Lang_CXX, "input1.cc");
  1621. auto *FromD = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  1622. FromTU, classTemplateSpecializationDecl(hasName("B")));
  1623. Import(FromD, Lang_CXX);
  1624. // We should have only one definition.
  1625. EXPECT_EQ(1u, DeclCounterWithPredicate<ClassTemplateSpecializationDecl>(
  1626. [](const ClassTemplateSpecializationDecl *T) {
  1627. return T->isThisDeclarationADefinition();
  1628. })
  1629. .match(ToTU, classTemplateSpecializationDecl()));
  1630. }
  1631. TEST_P(ASTImporterOptionSpecificTestBase, ObjectsWithUnnamedStructType) {
  1632. Decl *FromTU = getTuDecl(
  1633. R"(
  1634. struct { int a; int b; } object0 = { 2, 3 };
  1635. struct { int x; int y; int z; } object1;
  1636. )",
  1637. Lang_CXX, "input0.cc");
  1638. auto *Obj0 =
  1639. FirstDeclMatcher<VarDecl>().match(FromTU, varDecl(hasName("object0")));
  1640. auto *From0 = getRecordDecl(Obj0);
  1641. auto *Obj1 =
  1642. FirstDeclMatcher<VarDecl>().match(FromTU, varDecl(hasName("object1")));
  1643. auto *From1 = getRecordDecl(Obj1);
  1644. auto *To0 = Import(From0, Lang_CXX);
  1645. auto *To1 = Import(From1, Lang_CXX);
  1646. EXPECT_TRUE(To0);
  1647. EXPECT_TRUE(To1);
  1648. EXPECT_NE(To0, To1);
  1649. EXPECT_NE(To0->getCanonicalDecl(), To1->getCanonicalDecl());
  1650. }
  1651. TEST_P(ASTImporterOptionSpecificTestBase, AnonymousRecords) {
  1652. auto *Code =
  1653. R"(
  1654. struct X {
  1655. struct { int a; };
  1656. struct { int b; };
  1657. };
  1658. )";
  1659. Decl *FromTU0 = getTuDecl(Code, Lang_C, "input0.c");
  1660. Decl *FromTU1 = getTuDecl(Code, Lang_C, "input1.c");
  1661. auto *X0 =
  1662. FirstDeclMatcher<RecordDecl>().match(FromTU0, recordDecl(hasName("X")));
  1663. auto *X1 =
  1664. FirstDeclMatcher<RecordDecl>().match(FromTU1, recordDecl(hasName("X")));
  1665. Import(X0, Lang_C);
  1666. Import(X1, Lang_C);
  1667. auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  1668. // We expect no (ODR) warning during the import.
  1669. EXPECT_EQ(0u, ToTU->getASTContext().getDiagnostics().getNumWarnings());
  1670. EXPECT_EQ(1u,
  1671. DeclCounter<RecordDecl>().match(ToTU, recordDecl(hasName("X"))));
  1672. }
  1673. TEST_P(ASTImporterOptionSpecificTestBase, AnonymousRecordsReversed) {
  1674. Decl *FromTU0 = getTuDecl(
  1675. R"(
  1676. struct X {
  1677. struct { int a; };
  1678. struct { int b; };
  1679. };
  1680. )",
  1681. Lang_C, "input0.c");
  1682. Decl *FromTU1 = getTuDecl(
  1683. R"(
  1684. struct X { // reversed order
  1685. struct { int b; };
  1686. struct { int a; };
  1687. };
  1688. )",
  1689. Lang_C, "input1.c");
  1690. auto *X0 =
  1691. FirstDeclMatcher<RecordDecl>().match(FromTU0, recordDecl(hasName("X")));
  1692. auto *X1 =
  1693. FirstDeclMatcher<RecordDecl>().match(FromTU1, recordDecl(hasName("X")));
  1694. Import(X0, Lang_C);
  1695. Import(X1, Lang_C);
  1696. auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  1697. // We expect one (ODR) warning during the import.
  1698. EXPECT_EQ(1u, ToTU->getASTContext().getDiagnostics().getNumWarnings());
  1699. EXPECT_EQ(1u,
  1700. DeclCounter<RecordDecl>().match(ToTU, recordDecl(hasName("X"))));
  1701. }
  1702. TEST_P(ASTImporterOptionSpecificTestBase, ImportDoesUpdateUsedFlag) {
  1703. auto Pattern = varDecl(hasName("x"));
  1704. VarDecl *Imported1;
  1705. {
  1706. Decl *FromTU = getTuDecl("extern int x;", Lang_CXX, "input0.cc");
  1707. auto *FromD = FirstDeclMatcher<VarDecl>().match(FromTU, Pattern);
  1708. Imported1 = cast<VarDecl>(Import(FromD, Lang_CXX));
  1709. }
  1710. VarDecl *Imported2;
  1711. {
  1712. Decl *FromTU = getTuDecl("int x;", Lang_CXX, "input1.cc");
  1713. auto *FromD = FirstDeclMatcher<VarDecl>().match(FromTU, Pattern);
  1714. Imported2 = cast<VarDecl>(Import(FromD, Lang_CXX));
  1715. }
  1716. EXPECT_EQ(Imported1->getCanonicalDecl(), Imported2->getCanonicalDecl());
  1717. EXPECT_FALSE(Imported2->isUsed(false));
  1718. {
  1719. Decl *FromTU =
  1720. getTuDecl("extern int x; int f() { return x; }", Lang_CXX, "input2.cc");
  1721. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(
  1722. FromTU, functionDecl(hasName("f")));
  1723. Import(FromD, Lang_CXX);
  1724. }
  1725. EXPECT_TRUE(Imported2->isUsed(false));
  1726. }
  1727. TEST_P(ASTImporterOptionSpecificTestBase, ImportDoesUpdateUsedFlag2) {
  1728. auto Pattern = varDecl(hasName("x"));
  1729. VarDecl *ExistingD;
  1730. {
  1731. Decl *ToTU = getToTuDecl("int x = 1;", Lang_CXX);
  1732. ExistingD = FirstDeclMatcher<VarDecl>().match(ToTU, Pattern);
  1733. }
  1734. EXPECT_FALSE(ExistingD->isUsed(false));
  1735. {
  1736. Decl *FromTU = getTuDecl(
  1737. "int x = 1; int f() { return x; }", Lang_CXX, "input1.cc");
  1738. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(
  1739. FromTU, functionDecl(hasName("f")));
  1740. Import(FromD, Lang_CXX);
  1741. }
  1742. EXPECT_TRUE(ExistingD->isUsed(false));
  1743. }
  1744. TEST_P(ASTImporterOptionSpecificTestBase, ImportDoesUpdateUsedFlag3) {
  1745. auto Pattern = varDecl(hasName("a"));
  1746. VarDecl *ExistingD;
  1747. {
  1748. Decl *ToTU = getToTuDecl(
  1749. R"(
  1750. struct A {
  1751. static const int a = 1;
  1752. };
  1753. )", Lang_CXX);
  1754. ExistingD = FirstDeclMatcher<VarDecl>().match(ToTU, Pattern);
  1755. }
  1756. EXPECT_FALSE(ExistingD->isUsed(false));
  1757. {
  1758. Decl *FromTU = getTuDecl(
  1759. R"(
  1760. struct A {
  1761. static const int a = 1;
  1762. };
  1763. const int *f() { return &A::a; } // requires storage,
  1764. // thus used flag will be set
  1765. )", Lang_CXX, "input1.cc");
  1766. auto *FromFunD = FirstDeclMatcher<FunctionDecl>().match(
  1767. FromTU, functionDecl(hasName("f")));
  1768. auto *FromD = FirstDeclMatcher<VarDecl>().match(FromTU, Pattern);
  1769. ASSERT_TRUE(FromD->isUsed(false));
  1770. Import(FromFunD, Lang_CXX);
  1771. }
  1772. EXPECT_TRUE(ExistingD->isUsed(false));
  1773. }
  1774. TEST_P(ASTImporterOptionSpecificTestBase, ReimportWithUsedFlag) {
  1775. auto Pattern = varDecl(hasName("x"));
  1776. Decl *FromTU = getTuDecl("int x;", Lang_CXX, "input0.cc");
  1777. auto *FromD = FirstDeclMatcher<VarDecl>().match(FromTU, Pattern);
  1778. auto *Imported1 = cast<VarDecl>(Import(FromD, Lang_CXX));
  1779. ASSERT_FALSE(Imported1->isUsed(false));
  1780. FromD->setIsUsed();
  1781. auto *Imported2 = cast<VarDecl>(Import(FromD, Lang_CXX));
  1782. EXPECT_EQ(Imported1, Imported2);
  1783. EXPECT_TRUE(Imported2->isUsed(false));
  1784. }
  1785. struct ImportFunctions : ASTImporterOptionSpecificTestBase {};
  1786. TEST_P(ImportFunctions, ImportPrototypeOfRecursiveFunction) {
  1787. Decl *FromTU = getTuDecl("void f(); void f() { f(); }", Lang_CXX);
  1788. auto Pattern = functionDecl(hasName("f"));
  1789. auto *From =
  1790. FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern); // Proto
  1791. Decl *ImportedD = Import(From, Lang_CXX);
  1792. Decl *ToTU = ImportedD->getTranslationUnitDecl();
  1793. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u);
  1794. auto *To0 = FirstDeclMatcher<FunctionDecl>().match(ToTU, Pattern);
  1795. auto *To1 = LastDeclMatcher<FunctionDecl>().match(ToTU, Pattern);
  1796. EXPECT_TRUE(ImportedD == To0);
  1797. EXPECT_FALSE(To0->doesThisDeclarationHaveABody());
  1798. EXPECT_TRUE(To1->doesThisDeclarationHaveABody());
  1799. EXPECT_EQ(To1->getPreviousDecl(), To0);
  1800. }
  1801. TEST_P(ImportFunctions, ImportDefinitionOfRecursiveFunction) {
  1802. Decl *FromTU = getTuDecl("void f(); void f() { f(); }", Lang_CXX);
  1803. auto Pattern = functionDecl(hasName("f"));
  1804. auto *From =
  1805. LastDeclMatcher<FunctionDecl>().match(FromTU, Pattern); // Def
  1806. Decl *ImportedD = Import(From, Lang_CXX);
  1807. Decl *ToTU = ImportedD->getTranslationUnitDecl();
  1808. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u);
  1809. auto *To0 = FirstDeclMatcher<FunctionDecl>().match(ToTU, Pattern);
  1810. auto *To1 = LastDeclMatcher<FunctionDecl>().match(ToTU, Pattern);
  1811. EXPECT_TRUE(ImportedD == To1);
  1812. EXPECT_FALSE(To0->doesThisDeclarationHaveABody());
  1813. EXPECT_TRUE(To1->doesThisDeclarationHaveABody());
  1814. EXPECT_EQ(To1->getPreviousDecl(), To0);
  1815. }
  1816. TEST_P(ImportFunctions, OverriddenMethodsShouldBeImported) {
  1817. auto Code =
  1818. R"(
  1819. struct B { virtual void f(); };
  1820. void B::f() {}
  1821. struct D : B { void f(); };
  1822. )";
  1823. auto Pattern =
  1824. cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("D"))));
  1825. Decl *FromTU = getTuDecl(Code, Lang_CXX);
  1826. CXXMethodDecl *Proto =
  1827. FirstDeclMatcher<CXXMethodDecl>().match(FromTU, Pattern);
  1828. ASSERT_EQ(Proto->size_overridden_methods(), 1u);
  1829. CXXMethodDecl *To = cast<CXXMethodDecl>(Import(Proto, Lang_CXX));
  1830. EXPECT_EQ(To->size_overridden_methods(), 1u);
  1831. }
  1832. TEST_P(ImportFunctions, VirtualFlagShouldBePreservedWhenImportingPrototype) {
  1833. auto Code =
  1834. R"(
  1835. struct B { virtual void f(); };
  1836. void B::f() {}
  1837. )";
  1838. auto Pattern =
  1839. cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("B"))));
  1840. Decl *FromTU = getTuDecl(Code, Lang_CXX);
  1841. CXXMethodDecl *Proto =
  1842. FirstDeclMatcher<CXXMethodDecl>().match(FromTU, Pattern);
  1843. CXXMethodDecl *Def = LastDeclMatcher<CXXMethodDecl>().match(FromTU, Pattern);
  1844. ASSERT_TRUE(Proto->isVirtual());
  1845. ASSERT_TRUE(Def->isVirtual());
  1846. CXXMethodDecl *To = cast<CXXMethodDecl>(Import(Proto, Lang_CXX));
  1847. EXPECT_TRUE(To->isVirtual());
  1848. }
  1849. TEST_P(ImportFunctions,
  1850. ImportDefinitionIfThereIsAnExistingDefinitionAndFwdDecl) {
  1851. Decl *ToTU = getToTuDecl(
  1852. R"(
  1853. void f() {}
  1854. void f();
  1855. )",
  1856. Lang_CXX);
  1857. ASSERT_EQ(1u,
  1858. DeclCounterWithPredicate<FunctionDecl>([](const FunctionDecl *FD) {
  1859. return FD->doesThisDeclarationHaveABody();
  1860. }).match(ToTU, functionDecl()));
  1861. Decl *FromTU = getTuDecl("void f() {}", Lang_CXX, "input0.cc");
  1862. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, functionDecl());
  1863. Import(FromD, Lang_CXX);
  1864. EXPECT_EQ(1u,
  1865. DeclCounterWithPredicate<FunctionDecl>([](const FunctionDecl *FD) {
  1866. return FD->doesThisDeclarationHaveABody();
  1867. }).match(ToTU, functionDecl()));
  1868. }
  1869. TEST_P(ImportFunctions, ImportOverriddenMethodTwice) {
  1870. auto Code =
  1871. R"(
  1872. struct B { virtual void f(); };
  1873. struct D:B { void f(); };
  1874. )";
  1875. auto BFP =
  1876. cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("B"))));
  1877. auto DFP =
  1878. cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("D"))));
  1879. Decl *FromTU0 = getTuDecl(Code, Lang_CXX);
  1880. auto *DF = FirstDeclMatcher<CXXMethodDecl>().match(FromTU0, DFP);
  1881. Import(DF, Lang_CXX);
  1882. Decl *FromTU1 = getTuDecl(Code, Lang_CXX, "input1.cc");
  1883. auto *BF = FirstDeclMatcher<CXXMethodDecl>().match(FromTU1, BFP);
  1884. Import(BF, Lang_CXX);
  1885. auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  1886. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFP), 1u);
  1887. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, DFP), 1u);
  1888. }
  1889. TEST_P(ImportFunctions, ImportOverriddenMethodTwiceDefinitionFirst) {
  1890. auto CodeWithoutDef =
  1891. R"(
  1892. struct B { virtual void f(); };
  1893. struct D:B { void f(); };
  1894. )";
  1895. auto CodeWithDef =
  1896. R"(
  1897. struct B { virtual void f(){}; };
  1898. struct D:B { void f(){}; };
  1899. )";
  1900. auto BFP =
  1901. cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("B"))));
  1902. auto DFP =
  1903. cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("D"))));
  1904. auto BFDefP = cxxMethodDecl(
  1905. hasName("f"), hasParent(cxxRecordDecl(hasName("B"))), isDefinition());
  1906. auto DFDefP = cxxMethodDecl(
  1907. hasName("f"), hasParent(cxxRecordDecl(hasName("D"))), isDefinition());
  1908. auto FDefAllP = cxxMethodDecl(hasName("f"), isDefinition());
  1909. {
  1910. Decl *FromTU = getTuDecl(CodeWithDef, Lang_CXX, "input0.cc");
  1911. auto *FromD = FirstDeclMatcher<CXXMethodDecl>().match(FromTU, DFP);
  1912. Import(FromD, Lang_CXX);
  1913. }
  1914. {
  1915. Decl *FromTU = getTuDecl(CodeWithoutDef, Lang_CXX, "input1.cc");
  1916. auto *FromB = FirstDeclMatcher<CXXMethodDecl>().match(FromTU, BFP);
  1917. Import(FromB, Lang_CXX);
  1918. }
  1919. auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  1920. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFP), 1u);
  1921. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, DFP), 1u);
  1922. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFDefP), 1u);
  1923. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, DFDefP), 1u);
  1924. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, FDefAllP), 2u);
  1925. }
  1926. TEST_P(ImportFunctions, ImportOverriddenMethodTwiceOutOfClassDef) {
  1927. auto Code =
  1928. R"(
  1929. struct B { virtual void f(); };
  1930. struct D:B { void f(); };
  1931. void B::f(){};
  1932. )";
  1933. auto BFP =
  1934. cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("B"))));
  1935. auto BFDefP = cxxMethodDecl(
  1936. hasName("f"), hasParent(cxxRecordDecl(hasName("B"))), isDefinition());
  1937. auto DFP = cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("D"))),
  1938. unless(isDefinition()));
  1939. Decl *FromTU0 = getTuDecl(Code, Lang_CXX);
  1940. auto *D = FirstDeclMatcher<CXXMethodDecl>().match(FromTU0, DFP);
  1941. Import(D, Lang_CXX);
  1942. Decl *FromTU1 = getTuDecl(Code, Lang_CXX, "input1.cc");
  1943. auto *B = FirstDeclMatcher<CXXMethodDecl>().match(FromTU1, BFP);
  1944. Import(B, Lang_CXX);
  1945. auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  1946. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFP), 1u);
  1947. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFDefP), 0u);
  1948. auto *ToB = FirstDeclMatcher<CXXRecordDecl>().match(
  1949. ToTU, cxxRecordDecl(hasName("B")));
  1950. auto *ToBFInClass = FirstDeclMatcher<CXXMethodDecl>().match(ToTU, BFP);
  1951. auto *ToBFOutOfClass = FirstDeclMatcher<CXXMethodDecl>().match(
  1952. ToTU, cxxMethodDecl(hasName("f"), isDefinition()));
  1953. // The definition should be out-of-class.
  1954. EXPECT_NE(ToBFInClass, ToBFOutOfClass);
  1955. EXPECT_NE(ToBFInClass->getLexicalDeclContext(),
  1956. ToBFOutOfClass->getLexicalDeclContext());
  1957. EXPECT_EQ(ToBFOutOfClass->getDeclContext(), ToB);
  1958. EXPECT_EQ(ToBFOutOfClass->getLexicalDeclContext(), ToTU);
  1959. // Check that the redecl chain is intact.
  1960. EXPECT_EQ(ToBFOutOfClass->getPreviousDecl(), ToBFInClass);
  1961. }
  1962. TEST_P(ImportFunctions,
  1963. ImportOverriddenMethodTwiceOutOfClassDefInSeparateCode) {
  1964. auto CodeTU0 =
  1965. R"(
  1966. struct B { virtual void f(); };
  1967. struct D:B { void f(); };
  1968. )";
  1969. auto CodeTU1 =
  1970. R"(
  1971. struct B { virtual void f(); };
  1972. struct D:B { void f(); };
  1973. void B::f(){}
  1974. void D::f(){}
  1975. void foo(B &b, D &d) { b.f(); d.f(); }
  1976. )";
  1977. auto BFP =
  1978. cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("B"))));
  1979. auto BFDefP = cxxMethodDecl(
  1980. hasName("f"), hasParent(cxxRecordDecl(hasName("B"))), isDefinition());
  1981. auto DFP =
  1982. cxxMethodDecl(hasName("f"), hasParent(cxxRecordDecl(hasName("D"))));
  1983. auto DFDefP = cxxMethodDecl(
  1984. hasName("f"), hasParent(cxxRecordDecl(hasName("D"))), isDefinition());
  1985. auto FooDef = functionDecl(hasName("foo"));
  1986. {
  1987. Decl *FromTU0 = getTuDecl(CodeTU0, Lang_CXX, "input0.cc");
  1988. auto *D = FirstDeclMatcher<CXXMethodDecl>().match(FromTU0, DFP);
  1989. Import(D, Lang_CXX);
  1990. }
  1991. {
  1992. Decl *FromTU1 = getTuDecl(CodeTU1, Lang_CXX, "input1.cc");
  1993. auto *Foo = FirstDeclMatcher<FunctionDecl>().match(FromTU1, FooDef);
  1994. Import(Foo, Lang_CXX);
  1995. }
  1996. auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  1997. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFP), 1u);
  1998. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, DFP), 1u);
  1999. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, BFDefP), 0u);
  2000. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, DFDefP), 0u);
  2001. auto *ToB = FirstDeclMatcher<CXXRecordDecl>().match(
  2002. ToTU, cxxRecordDecl(hasName("B")));
  2003. auto *ToD = FirstDeclMatcher<CXXRecordDecl>().match(
  2004. ToTU, cxxRecordDecl(hasName("D")));
  2005. auto *ToBFInClass = FirstDeclMatcher<CXXMethodDecl>().match(ToTU, BFP);
  2006. auto *ToBFOutOfClass = FirstDeclMatcher<CXXMethodDecl>().match(
  2007. ToTU, cxxMethodDecl(hasName("f"), isDefinition()));
  2008. auto *ToDFInClass = FirstDeclMatcher<CXXMethodDecl>().match(ToTU, DFP);
  2009. auto *ToDFOutOfClass = LastDeclMatcher<CXXMethodDecl>().match(
  2010. ToTU, cxxMethodDecl(hasName("f"), isDefinition()));
  2011. // The definition should be out-of-class.
  2012. EXPECT_NE(ToBFInClass, ToBFOutOfClass);
  2013. EXPECT_NE(ToBFInClass->getLexicalDeclContext(),
  2014. ToBFOutOfClass->getLexicalDeclContext());
  2015. EXPECT_EQ(ToBFOutOfClass->getDeclContext(), ToB);
  2016. EXPECT_EQ(ToBFOutOfClass->getLexicalDeclContext(), ToTU);
  2017. EXPECT_NE(ToDFInClass, ToDFOutOfClass);
  2018. EXPECT_NE(ToDFInClass->getLexicalDeclContext(),
  2019. ToDFOutOfClass->getLexicalDeclContext());
  2020. EXPECT_EQ(ToDFOutOfClass->getDeclContext(), ToD);
  2021. EXPECT_EQ(ToDFOutOfClass->getLexicalDeclContext(), ToTU);
  2022. // Check that the redecl chain is intact.
  2023. EXPECT_EQ(ToBFOutOfClass->getPreviousDecl(), ToBFInClass);
  2024. EXPECT_EQ(ToDFOutOfClass->getPreviousDecl(), ToDFInClass);
  2025. }
  2026. TEST_P(ASTImporterOptionSpecificTestBase, ImportVariableChainInC) {
  2027. std::string Code = "static int v; static int v = 0;";
  2028. auto Pattern = varDecl(hasName("v"));
  2029. TranslationUnitDecl *FromTu = getTuDecl(Code, Lang_C, "input0.c");
  2030. auto *From0 = FirstDeclMatcher<VarDecl>().match(FromTu, Pattern);
  2031. auto *From1 = LastDeclMatcher<VarDecl>().match(FromTu, Pattern);
  2032. auto *To0 = Import(From0, Lang_C);
  2033. auto *To1 = Import(From1, Lang_C);
  2034. EXPECT_TRUE(To0);
  2035. ASSERT_TRUE(To1);
  2036. EXPECT_NE(To0, To1);
  2037. EXPECT_EQ(To1->getPreviousDecl(), To0);
  2038. }
  2039. TEST_P(ImportFunctions, ImportFromDifferentScopedAnonNamespace) {
  2040. TranslationUnitDecl *FromTu = getTuDecl(
  2041. "namespace NS0 { namespace { void f(); } }"
  2042. "namespace NS1 { namespace { void f(); } }",
  2043. Lang_CXX, "input0.cc");
  2044. auto Pattern = functionDecl(hasName("f"));
  2045. auto *FromF0 = FirstDeclMatcher<FunctionDecl>().match(FromTu, Pattern);
  2046. auto *FromF1 = LastDeclMatcher<FunctionDecl>().match(FromTu, Pattern);
  2047. auto *ToF0 = Import(FromF0, Lang_CXX);
  2048. auto *ToF1 = Import(FromF1, Lang_CXX);
  2049. EXPECT_TRUE(ToF0);
  2050. ASSERT_TRUE(ToF1);
  2051. EXPECT_NE(ToF0, ToF1);
  2052. EXPECT_FALSE(ToF1->getPreviousDecl());
  2053. }
  2054. TEST_P(ImportFunctions, ImportFunctionFromUnnamedNamespace) {
  2055. {
  2056. Decl *FromTU = getTuDecl("namespace { void f() {} } void g0() { f(); }",
  2057. Lang_CXX, "input0.cc");
  2058. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(
  2059. FromTU, functionDecl(hasName("g0")));
  2060. Import(FromD, Lang_CXX);
  2061. }
  2062. {
  2063. Decl *FromTU =
  2064. getTuDecl("namespace { void f() { int a; } } void g1() { f(); }",
  2065. Lang_CXX, "input1.cc");
  2066. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(
  2067. FromTU, functionDecl(hasName("g1")));
  2068. Import(FromD, Lang_CXX);
  2069. }
  2070. Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2071. ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, functionDecl(hasName("f"))),
  2072. 2u);
  2073. }
  2074. TEST_P(ImportFunctions, ImportImplicitFunctionsInLambda) {
  2075. Decl *FromTU = getTuDecl(
  2076. R"(
  2077. void foo() {
  2078. (void)[]() { ; };
  2079. }
  2080. )",
  2081. Lang_CXX11);
  2082. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(
  2083. FromTU, functionDecl(hasName("foo")));
  2084. auto *ToD = Import(FromD, Lang_CXX);
  2085. EXPECT_TRUE(ToD);
  2086. CXXRecordDecl *LambdaRec =
  2087. cast<LambdaExpr>(cast<CStyleCastExpr>(
  2088. *cast<CompoundStmt>(ToD->getBody())->body_begin())
  2089. ->getSubExpr())
  2090. ->getLambdaClass();
  2091. EXPECT_TRUE(LambdaRec->getDestructor());
  2092. }
  2093. TEST_P(ImportFunctions,
  2094. CallExprOfMemberFunctionTemplateWithExplicitTemplateArgs) {
  2095. Decl *FromTU = getTuDecl(
  2096. R"(
  2097. struct X {
  2098. template <typename T>
  2099. void foo(){}
  2100. };
  2101. void f() {
  2102. X x;
  2103. x.foo<int>();
  2104. }
  2105. )",
  2106. Lang_CXX);
  2107. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(
  2108. FromTU, functionDecl(hasName("f")));
  2109. auto *ToD = Import(FromD, Lang_CXX);
  2110. EXPECT_TRUE(ToD);
  2111. EXPECT_TRUE(MatchVerifier<FunctionDecl>().match(
  2112. ToD, functionDecl(hasName("f"), hasDescendant(declRefExpr()))));
  2113. }
  2114. TEST_P(ImportFunctions,
  2115. DependentCallExprOfMemberFunctionTemplateWithExplicitTemplateArgs) {
  2116. Decl *FromTU = getTuDecl(
  2117. R"(
  2118. struct X {
  2119. template <typename T>
  2120. void foo(){}
  2121. };
  2122. template <typename T>
  2123. void f() {
  2124. X x;
  2125. x.foo<T>();
  2126. }
  2127. void g() {
  2128. f<int>();
  2129. }
  2130. )",
  2131. Lang_CXX);
  2132. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(
  2133. FromTU, functionDecl(hasName("g")));
  2134. auto *ToD = Import(FromD, Lang_CXX);
  2135. EXPECT_TRUE(ToD);
  2136. Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2137. EXPECT_TRUE(MatchVerifier<TranslationUnitDecl>().match(
  2138. ToTU, translationUnitDecl(hasDescendant(
  2139. functionDecl(hasName("f"), hasDescendant(declRefExpr()))))));
  2140. }
  2141. struct ImportFunctionTemplates : ASTImporterOptionSpecificTestBase {};
  2142. TEST_P(ImportFunctionTemplates, ImportFunctionTemplateInRecordDeclTwice) {
  2143. auto Code =
  2144. R"(
  2145. class X {
  2146. template <class T>
  2147. void f(T t);
  2148. };
  2149. )";
  2150. Decl *FromTU1 = getTuDecl(Code, Lang_CXX, "input1.cc");
  2151. auto *FromD1 = FirstDeclMatcher<FunctionTemplateDecl>().match(
  2152. FromTU1, functionTemplateDecl(hasName("f")));
  2153. auto *ToD1 = Import(FromD1, Lang_CXX);
  2154. Decl *FromTU2 = getTuDecl(Code, Lang_CXX, "input2.cc");
  2155. auto *FromD2 = FirstDeclMatcher<FunctionTemplateDecl>().match(
  2156. FromTU2, functionTemplateDecl(hasName("f")));
  2157. auto *ToD2 = Import(FromD2, Lang_CXX);
  2158. EXPECT_EQ(ToD1, ToD2);
  2159. }
  2160. TEST_P(ImportFunctionTemplates,
  2161. ImportFunctionTemplateWithDefInRecordDeclTwice) {
  2162. auto Code =
  2163. R"(
  2164. class X {
  2165. template <class T>
  2166. void f(T t);
  2167. };
  2168. template <class T>
  2169. void X::f(T t) {};
  2170. )";
  2171. Decl *FromTU1 = getTuDecl(Code, Lang_CXX, "input1.cc");
  2172. auto *FromD1 = FirstDeclMatcher<FunctionTemplateDecl>().match(
  2173. FromTU1, functionTemplateDecl(hasName("f")));
  2174. auto *ToD1 = Import(FromD1, Lang_CXX);
  2175. Decl *FromTU2 = getTuDecl(Code, Lang_CXX, "input2.cc");
  2176. auto *FromD2 = FirstDeclMatcher<FunctionTemplateDecl>().match(
  2177. FromTU2, functionTemplateDecl(hasName("f")));
  2178. auto *ToD2 = Import(FromD2, Lang_CXX);
  2179. EXPECT_EQ(ToD1, ToD2);
  2180. }
  2181. TEST_P(ImportFunctionTemplates,
  2182. ImportFunctionWhenThereIsAFunTemplateWithSameName) {
  2183. getToTuDecl(
  2184. R"(
  2185. template <typename T>
  2186. void foo(T) {}
  2187. void foo();
  2188. )",
  2189. Lang_CXX);
  2190. Decl *FromTU = getTuDecl("void foo();", Lang_CXX);
  2191. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(
  2192. FromTU, functionDecl(hasName("foo")));
  2193. auto *ImportedD = Import(FromD, Lang_CXX);
  2194. EXPECT_TRUE(ImportedD);
  2195. }
  2196. TEST_P(ImportFunctionTemplates,
  2197. ImportConstructorWhenThereIsAFunTemplateWithSameName) {
  2198. auto Code =
  2199. R"(
  2200. struct Foo {
  2201. template <typename T>
  2202. Foo(T) {}
  2203. Foo();
  2204. };
  2205. )";
  2206. getToTuDecl(Code, Lang_CXX);
  2207. Decl *FromTU = getTuDecl(Code, Lang_CXX);
  2208. auto *FromD =
  2209. LastDeclMatcher<CXXConstructorDecl>().match(FromTU, cxxConstructorDecl());
  2210. auto *ImportedD = Import(FromD, Lang_CXX);
  2211. EXPECT_TRUE(ImportedD);
  2212. }
  2213. TEST_P(ImportFunctionTemplates,
  2214. ImportOperatorWhenThereIsAFunTemplateWithSameName) {
  2215. getToTuDecl(
  2216. R"(
  2217. template <typename T>
  2218. void operator<(T,T) {}
  2219. struct X{};
  2220. void operator<(X, X);
  2221. )",
  2222. Lang_CXX);
  2223. Decl *FromTU = getTuDecl(
  2224. R"(
  2225. struct X{};
  2226. void operator<(X, X);
  2227. )",
  2228. Lang_CXX);
  2229. auto *FromD = LastDeclMatcher<FunctionDecl>().match(
  2230. FromTU, functionDecl(hasOverloadedOperatorName("<")));
  2231. auto *ImportedD = Import(FromD, Lang_CXX);
  2232. EXPECT_TRUE(ImportedD);
  2233. }
  2234. struct ImportFriendFunctions : ImportFunctions {};
  2235. TEST_P(ImportFriendFunctions, ImportFriendFunctionRedeclChainProto) {
  2236. auto Pattern = functionDecl(hasName("f"));
  2237. Decl *FromTU = getTuDecl("struct X { friend void f(); };"
  2238. "void f();",
  2239. Lang_CXX,
  2240. "input0.cc");
  2241. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  2242. auto *ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX));
  2243. Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2244. ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u);
  2245. EXPECT_FALSE(ImportedD->doesThisDeclarationHaveABody());
  2246. auto *ToFD = LastDeclMatcher<FunctionDecl>().match(ToTU, Pattern);
  2247. EXPECT_FALSE(ToFD->doesThisDeclarationHaveABody());
  2248. EXPECT_EQ(ToFD->getPreviousDecl(), ImportedD);
  2249. }
  2250. TEST_P(ImportFriendFunctions,
  2251. ImportFriendFunctionRedeclChainProto_OutOfClassProtoFirst) {
  2252. auto Pattern = functionDecl(hasName("f"));
  2253. Decl *FromTU = getTuDecl("void f();"
  2254. "struct X { friend void f(); };",
  2255. Lang_CXX, "input0.cc");
  2256. auto FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  2257. auto *ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX));
  2258. Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2259. ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u);
  2260. EXPECT_FALSE(ImportedD->doesThisDeclarationHaveABody());
  2261. auto *ToFD = LastDeclMatcher<FunctionDecl>().match(ToTU, Pattern);
  2262. EXPECT_FALSE(ToFD->doesThisDeclarationHaveABody());
  2263. EXPECT_EQ(ToFD->getPreviousDecl(), ImportedD);
  2264. }
  2265. TEST_P(ImportFriendFunctions, ImportFriendFunctionRedeclChainDef) {
  2266. auto Pattern = functionDecl(hasName("f"));
  2267. Decl *FromTU = getTuDecl("struct X { friend void f(){} };"
  2268. "void f();",
  2269. Lang_CXX,
  2270. "input0.cc");
  2271. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  2272. auto *ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX));
  2273. Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2274. ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u);
  2275. EXPECT_TRUE(ImportedD->doesThisDeclarationHaveABody());
  2276. auto *ToFD = LastDeclMatcher<FunctionDecl>().match(ToTU, Pattern);
  2277. EXPECT_FALSE(ToFD->doesThisDeclarationHaveABody());
  2278. EXPECT_EQ(ToFD->getPreviousDecl(), ImportedD);
  2279. }
  2280. TEST_P(ImportFriendFunctions,
  2281. ImportFriendFunctionRedeclChainDef_OutOfClassDef) {
  2282. auto Pattern = functionDecl(hasName("f"));
  2283. Decl *FromTU = getTuDecl("struct X { friend void f(); };"
  2284. "void f(){}",
  2285. Lang_CXX, "input0.cc");
  2286. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  2287. auto *ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX));
  2288. Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2289. ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u);
  2290. EXPECT_FALSE(ImportedD->doesThisDeclarationHaveABody());
  2291. auto *ToFD = LastDeclMatcher<FunctionDecl>().match(ToTU, Pattern);
  2292. EXPECT_TRUE(ToFD->doesThisDeclarationHaveABody());
  2293. EXPECT_EQ(ToFD->getPreviousDecl(), ImportedD);
  2294. }
  2295. TEST_P(ImportFriendFunctions, ImportFriendFunctionRedeclChainDefWithClass) {
  2296. auto Pattern = functionDecl(hasName("f"));
  2297. Decl *FromTU = getTuDecl(
  2298. R"(
  2299. class X;
  2300. void f(X *x){}
  2301. class X{
  2302. friend void f(X *x);
  2303. };
  2304. )",
  2305. Lang_CXX, "input0.cc");
  2306. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  2307. auto *ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX));
  2308. Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2309. ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u);
  2310. EXPECT_TRUE(ImportedD->doesThisDeclarationHaveABody());
  2311. auto *InClassFD = cast<FunctionDecl>(FirstDeclMatcher<FriendDecl>()
  2312. .match(ToTU, friendDecl())
  2313. ->getFriendDecl());
  2314. EXPECT_FALSE(InClassFD->doesThisDeclarationHaveABody());
  2315. EXPECT_EQ(InClassFD->getPreviousDecl(), ImportedD);
  2316. // The parameters must refer the same type
  2317. EXPECT_EQ((*InClassFD->param_begin())->getOriginalType(),
  2318. (*ImportedD->param_begin())->getOriginalType());
  2319. }
  2320. TEST_P(ImportFriendFunctions,
  2321. ImportFriendFunctionRedeclChainDefWithClass_ImportTheProto) {
  2322. auto Pattern = functionDecl(hasName("f"));
  2323. Decl *FromTU = getTuDecl(
  2324. R"(
  2325. class X;
  2326. void f(X *x){}
  2327. class X{
  2328. friend void f(X *x);
  2329. };
  2330. )",
  2331. Lang_CXX, "input0.cc");
  2332. auto *FromD = LastDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  2333. auto *ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX));
  2334. Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2335. ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u);
  2336. EXPECT_FALSE(ImportedD->doesThisDeclarationHaveABody());
  2337. auto *OutOfClassFD = FirstDeclMatcher<FunctionDecl>().match(
  2338. ToTU, functionDecl(unless(hasParent(friendDecl()))));
  2339. EXPECT_TRUE(OutOfClassFD->doesThisDeclarationHaveABody());
  2340. EXPECT_EQ(ImportedD->getPreviousDecl(), OutOfClassFD);
  2341. // The parameters must refer the same type
  2342. EXPECT_EQ((*OutOfClassFD->param_begin())->getOriginalType(),
  2343. (*ImportedD->param_begin())->getOriginalType());
  2344. }
  2345. TEST_P(ImportFriendFunctions, ImportFriendFunctionFromMultipleTU) {
  2346. auto Pattern = functionDecl(hasName("f"));
  2347. FunctionDecl *ImportedD;
  2348. {
  2349. Decl *FromTU =
  2350. getTuDecl("struct X { friend void f(){} };", Lang_CXX, "input0.cc");
  2351. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  2352. ImportedD = cast<FunctionDecl>(Import(FromD, Lang_CXX));
  2353. }
  2354. FunctionDecl *ImportedD1;
  2355. {
  2356. Decl *FromTU = getTuDecl("void f();", Lang_CXX, "input1.cc");
  2357. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, Pattern);
  2358. ImportedD1 = cast<FunctionDecl>(Import(FromD, Lang_CXX));
  2359. }
  2360. Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2361. ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u);
  2362. EXPECT_TRUE(ImportedD->doesThisDeclarationHaveABody());
  2363. EXPECT_FALSE(ImportedD1->doesThisDeclarationHaveABody());
  2364. EXPECT_EQ(ImportedD1->getPreviousDecl(), ImportedD);
  2365. }
  2366. TEST_P(ImportFriendFunctions, Lookup) {
  2367. auto FunctionPattern = functionDecl(hasName("f"));
  2368. auto ClassPattern = cxxRecordDecl(hasName("X"));
  2369. TranslationUnitDecl *FromTU =
  2370. getTuDecl("struct X { friend void f(); };", Lang_CXX, "input0.cc");
  2371. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU, FunctionPattern);
  2372. ASSERT_TRUE(FromD->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2373. ASSERT_FALSE(FromD->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2374. {
  2375. auto FromName = FromD->getDeclName();
  2376. auto *Class = FirstDeclMatcher<CXXRecordDecl>().match(FromTU, ClassPattern);
  2377. auto LookupRes = Class->noload_lookup(FromName);
  2378. ASSERT_EQ(LookupRes.size(), 0u);
  2379. LookupRes = FromTU->noload_lookup(FromName);
  2380. ASSERT_EQ(LookupRes.size(), 1u);
  2381. }
  2382. auto *ToD = cast<FunctionDecl>(Import(FromD, Lang_CXX));
  2383. auto ToName = ToD->getDeclName();
  2384. TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2385. auto *Class = FirstDeclMatcher<CXXRecordDecl>().match(ToTU, ClassPattern);
  2386. auto LookupRes = Class->noload_lookup(ToName);
  2387. EXPECT_EQ(LookupRes.size(), 0u);
  2388. LookupRes = ToTU->noload_lookup(ToName);
  2389. EXPECT_EQ(LookupRes.size(), 1u);
  2390. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, FunctionPattern), 1u);
  2391. auto *To0 = FirstDeclMatcher<FunctionDecl>().match(ToTU, FunctionPattern);
  2392. EXPECT_TRUE(To0->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2393. EXPECT_FALSE(To0->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2394. }
  2395. TEST_P(ImportFriendFunctions, DISABLED_LookupWithProtoAfter) {
  2396. auto FunctionPattern = functionDecl(hasName("f"));
  2397. auto ClassPattern = cxxRecordDecl(hasName("X"));
  2398. TranslationUnitDecl *FromTU = getTuDecl(
  2399. "struct X { friend void f(); };"
  2400. // This proto decl makes f available to normal
  2401. // lookup, otherwise it is hidden.
  2402. // Normal C++ lookup (implemented in
  2403. // `clang::Sema::CppLookupName()` and in `LookupDirect()`)
  2404. // returns the found `NamedDecl` only if the set IDNS is matched
  2405. "void f();",
  2406. Lang_CXX, "input0.cc");
  2407. auto *FromFriend =
  2408. FirstDeclMatcher<FunctionDecl>().match(FromTU, FunctionPattern);
  2409. auto *FromNormal =
  2410. LastDeclMatcher<FunctionDecl>().match(FromTU, FunctionPattern);
  2411. ASSERT_TRUE(FromFriend->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2412. ASSERT_FALSE(FromFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2413. ASSERT_FALSE(FromNormal->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2414. ASSERT_TRUE(FromNormal->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2415. auto FromName = FromFriend->getDeclName();
  2416. auto *FromClass =
  2417. FirstDeclMatcher<CXXRecordDecl>().match(FromTU, ClassPattern);
  2418. auto LookupRes = FromClass->noload_lookup(FromName);
  2419. ASSERT_EQ(LookupRes.size(), 0u);
  2420. LookupRes = FromTU->noload_lookup(FromName);
  2421. ASSERT_EQ(LookupRes.size(), 1u);
  2422. auto *ToFriend = cast<FunctionDecl>(Import(FromFriend, Lang_CXX));
  2423. auto ToName = ToFriend->getDeclName();
  2424. TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2425. auto *ToClass = FirstDeclMatcher<CXXRecordDecl>().match(ToTU, ClassPattern);
  2426. LookupRes = ToClass->noload_lookup(ToName);
  2427. EXPECT_EQ(LookupRes.size(), 0u);
  2428. LookupRes = ToTU->noload_lookup(ToName);
  2429. // Test is disabled because this result is 2.
  2430. EXPECT_EQ(LookupRes.size(), 1u);
  2431. ASSERT_EQ(DeclCounter<FunctionDecl>().match(ToTU, FunctionPattern), 2u);
  2432. ToFriend = FirstDeclMatcher<FunctionDecl>().match(ToTU, FunctionPattern);
  2433. auto *ToNormal = LastDeclMatcher<FunctionDecl>().match(ToTU, FunctionPattern);
  2434. EXPECT_TRUE(ToFriend->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2435. EXPECT_FALSE(ToFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2436. EXPECT_FALSE(ToNormal->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2437. EXPECT_TRUE(ToNormal->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2438. }
  2439. TEST_P(ImportFriendFunctions, LookupWithProtoBefore) {
  2440. auto FunctionPattern = functionDecl(hasName("f"));
  2441. auto ClassPattern = cxxRecordDecl(hasName("X"));
  2442. TranslationUnitDecl *FromTU = getTuDecl(
  2443. "void f();"
  2444. "struct X { friend void f(); };",
  2445. Lang_CXX, "input0.cc");
  2446. auto *FromNormal =
  2447. FirstDeclMatcher<FunctionDecl>().match(FromTU, FunctionPattern);
  2448. auto *FromFriend =
  2449. LastDeclMatcher<FunctionDecl>().match(FromTU, FunctionPattern);
  2450. ASSERT_FALSE(FromNormal->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2451. ASSERT_TRUE(FromNormal->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2452. ASSERT_TRUE(FromFriend->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2453. ASSERT_TRUE(FromFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2454. auto FromName = FromNormal->getDeclName();
  2455. auto *FromClass =
  2456. FirstDeclMatcher<CXXRecordDecl>().match(FromTU, ClassPattern);
  2457. auto LookupRes = FromClass->noload_lookup(FromName);
  2458. ASSERT_EQ(LookupRes.size(), 0u);
  2459. LookupRes = FromTU->noload_lookup(FromName);
  2460. ASSERT_EQ(LookupRes.size(), 1u);
  2461. auto *ToNormal = cast<FunctionDecl>(Import(FromNormal, Lang_CXX));
  2462. auto ToName = ToNormal->getDeclName();
  2463. TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2464. auto *ToClass = FirstDeclMatcher<CXXRecordDecl>().match(ToTU, ClassPattern);
  2465. LookupRes = ToClass->noload_lookup(ToName);
  2466. EXPECT_EQ(LookupRes.size(), 0u);
  2467. LookupRes = ToTU->noload_lookup(ToName);
  2468. EXPECT_EQ(LookupRes.size(), 1u);
  2469. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, FunctionPattern), 2u);
  2470. ToNormal = FirstDeclMatcher<FunctionDecl>().match(ToTU, FunctionPattern);
  2471. auto *ToFriend = LastDeclMatcher<FunctionDecl>().match(ToTU, FunctionPattern);
  2472. EXPECT_FALSE(ToNormal->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2473. EXPECT_TRUE(ToNormal->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2474. EXPECT_TRUE(ToFriend->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2475. EXPECT_TRUE(ToFriend->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2476. }
  2477. TEST_P(ImportFriendFunctions, ImportFriendChangesLookup) {
  2478. auto Pattern = functionDecl(hasName("f"));
  2479. TranslationUnitDecl *FromNormalTU =
  2480. getTuDecl("void f();", Lang_CXX, "input0.cc");
  2481. auto *FromNormalF =
  2482. FirstDeclMatcher<FunctionDecl>().match(FromNormalTU, Pattern);
  2483. TranslationUnitDecl *FromFriendTU =
  2484. getTuDecl("class X { friend void f(); };", Lang_CXX, "input1.cc");
  2485. auto *FromFriendF =
  2486. FirstDeclMatcher<FunctionDecl>().match(FromFriendTU, Pattern);
  2487. auto FromNormalName = FromNormalF->getDeclName();
  2488. auto FromFriendName = FromFriendF->getDeclName();
  2489. ASSERT_TRUE(FromNormalF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2490. ASSERT_FALSE(FromNormalF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2491. ASSERT_FALSE(FromFriendF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2492. ASSERT_TRUE(FromFriendF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2493. auto LookupRes = FromNormalTU->noload_lookup(FromNormalName);
  2494. ASSERT_EQ(LookupRes.size(), 1u);
  2495. LookupRes = FromFriendTU->noload_lookup(FromFriendName);
  2496. ASSERT_EQ(LookupRes.size(), 1u);
  2497. auto *ToNormalF = cast<FunctionDecl>(Import(FromNormalF, Lang_CXX));
  2498. TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2499. auto ToName = ToNormalF->getDeclName();
  2500. EXPECT_TRUE(ToNormalF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2501. EXPECT_FALSE(ToNormalF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2502. LookupRes = ToTU->noload_lookup(ToName);
  2503. EXPECT_EQ(LookupRes.size(), 1u);
  2504. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 1u);
  2505. auto *ToFriendF = cast<FunctionDecl>(Import(FromFriendF, Lang_CXX));
  2506. LookupRes = ToTU->noload_lookup(ToName);
  2507. EXPECT_EQ(LookupRes.size(), 1u);
  2508. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, Pattern), 2u);
  2509. EXPECT_TRUE(ToNormalF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2510. EXPECT_FALSE(ToNormalF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2511. EXPECT_TRUE(ToFriendF->isInIdentifierNamespace(Decl::IDNS_Ordinary));
  2512. EXPECT_TRUE(ToFriendF->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend));
  2513. }
  2514. TEST_P(ImportFriendFunctions, ImportFriendList) {
  2515. TranslationUnitDecl *FromTU = getTuDecl(
  2516. "struct X { friend void f(); };"
  2517. "void f();",
  2518. Lang_CXX, "input0.cc");
  2519. auto *FromFriendF = FirstDeclMatcher<FunctionDecl>().match(
  2520. FromTU, functionDecl(hasName("f")));
  2521. auto *FromClass = FirstDeclMatcher<CXXRecordDecl>().match(
  2522. FromTU, cxxRecordDecl(hasName("X")));
  2523. auto *FromFriend = FirstDeclMatcher<FriendDecl>().match(FromTU, friendDecl());
  2524. auto FromFriends = FromClass->friends();
  2525. unsigned int FrN = 0;
  2526. for (auto Fr : FromFriends) {
  2527. ASSERT_EQ(Fr, FromFriend);
  2528. ++FrN;
  2529. }
  2530. ASSERT_EQ(FrN, 1u);
  2531. Import(FromFriendF, Lang_CXX);
  2532. TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2533. auto *ToClass = FirstDeclMatcher<CXXRecordDecl>().match(
  2534. ToTU, cxxRecordDecl(hasName("X")));
  2535. auto *ToFriend = FirstDeclMatcher<FriendDecl>().match(ToTU, friendDecl());
  2536. auto ToFriends = ToClass->friends();
  2537. FrN = 0;
  2538. for (auto Fr : ToFriends) {
  2539. EXPECT_EQ(Fr, ToFriend);
  2540. ++FrN;
  2541. }
  2542. EXPECT_EQ(FrN, 1u);
  2543. }
  2544. AST_MATCHER_P(TagDecl, hasTypedefForAnonDecl, Matcher<TypedefNameDecl>,
  2545. InnerMatcher) {
  2546. if (auto *Typedef = Node.getTypedefNameForAnonDecl())
  2547. return InnerMatcher.matches(*Typedef, Finder, Builder);
  2548. return false;
  2549. }
  2550. TEST_P(ImportDecl, ImportEnumSequential) {
  2551. CodeFiles Samples{{"main.c",
  2552. {"void foo();"
  2553. "void moo();"
  2554. "int main() { foo(); moo(); }",
  2555. Lang_C}},
  2556. {"foo.c",
  2557. {"typedef enum { THING_VALUE } thing_t;"
  2558. "void conflict(thing_t type);"
  2559. "void foo() { (void)THING_VALUE; }"
  2560. "void conflict(thing_t type) {}",
  2561. Lang_C}},
  2562. {"moo.c",
  2563. {"typedef enum { THING_VALUE } thing_t;"
  2564. "void conflict(thing_t type);"
  2565. "void moo() { conflict(THING_VALUE); }",
  2566. Lang_C}}};
  2567. auto VerificationMatcher =
  2568. enumDecl(has(enumConstantDecl(hasName("THING_VALUE"))),
  2569. hasTypedefForAnonDecl(hasName("thing_t")));
  2570. ImportAction ImportFoo{"foo.c", "main.c", functionDecl(hasName("foo"))},
  2571. ImportMoo{"moo.c", "main.c", functionDecl(hasName("moo"))};
  2572. testImportSequence(
  2573. Samples, {ImportFoo, ImportMoo}, // "foo", them "moo".
  2574. // Just check that there is only one enum decl in the result AST.
  2575. "main.c", enumDecl(), VerificationMatcher);
  2576. // For different import order, result should be the same.
  2577. testImportSequence(
  2578. Samples, {ImportMoo, ImportFoo}, // "moo", them "foo".
  2579. // Check that there is only one enum decl in the result AST.
  2580. "main.c", enumDecl(), VerificationMatcher);
  2581. }
  2582. TEST_P(ImportDecl, ImportFieldOrder) {
  2583. MatchVerifier<Decl> Verifier;
  2584. testImport("struct declToImport {"
  2585. " int b = a + 2;"
  2586. " int a = 5;"
  2587. "};",
  2588. Lang_CXX11, "", Lang_CXX11, Verifier,
  2589. recordDecl(hasFieldOrder({"b", "a"})));
  2590. }
  2591. const internal::VariadicDynCastAllOfMatcher<Expr, DependentScopeDeclRefExpr>
  2592. dependentScopeDeclRefExpr;
  2593. TEST_P(ImportExpr, DependentScopeDeclRefExpr) {
  2594. MatchVerifier<Decl> Verifier;
  2595. testImport("template <typename T> struct S { static T foo; };"
  2596. "template <typename T> void declToImport() {"
  2597. " (void) S<T>::foo;"
  2598. "}"
  2599. "void instantiate() { declToImport<int>(); }"
  2600. "template <typename T> T S<T>::foo;",
  2601. Lang_CXX11, "", Lang_CXX11, Verifier,
  2602. functionTemplateDecl(has(functionDecl(has(compoundStmt(
  2603. has(cStyleCastExpr(has(dependentScopeDeclRefExpr())))))))));
  2604. testImport("template <typename T> struct S {"
  2605. "template<typename S> static void foo(){};"
  2606. "};"
  2607. "template <typename T> void declToImport() {"
  2608. " S<T>::template foo<T>();"
  2609. "}"
  2610. "void instantiate() { declToImport<int>(); }",
  2611. Lang_CXX11, "", Lang_CXX11, Verifier,
  2612. functionTemplateDecl(has(functionDecl(has(compoundStmt(
  2613. has(callExpr(has(dependentScopeDeclRefExpr())))))))));
  2614. }
  2615. const internal::VariadicDynCastAllOfMatcher<Type, DependentNameType>
  2616. dependentNameType;
  2617. TEST_P(ImportExpr, DependentNameType) {
  2618. MatchVerifier<Decl> Verifier;
  2619. testImport("template <typename T> struct declToImport {"
  2620. " typedef typename T::type dependent_name;"
  2621. "};",
  2622. Lang_CXX11, "", Lang_CXX11, Verifier,
  2623. classTemplateDecl(has(
  2624. cxxRecordDecl(has(typedefDecl(has(dependentNameType())))))));
  2625. }
  2626. TEST_P(ImportExpr, UnresolvedMemberExpr) {
  2627. MatchVerifier<Decl> Verifier;
  2628. testImport("struct S { template <typename T> void mem(); };"
  2629. "template <typename U> void declToImport() {"
  2630. " S s;"
  2631. " s.mem<U>();"
  2632. "}"
  2633. "void instantiate() { declToImport<int>(); }",
  2634. Lang_CXX11, "", Lang_CXX11, Verifier,
  2635. functionTemplateDecl(has(functionDecl(has(
  2636. compoundStmt(has(callExpr(has(unresolvedMemberExpr())))))))));
  2637. }
  2638. class ImportImplicitMethods : public ASTImporterOptionSpecificTestBase {
  2639. public:
  2640. static constexpr auto DefaultCode = R"(
  2641. struct A { int x; };
  2642. void f() {
  2643. A a;
  2644. A a1(a);
  2645. A a2(A{});
  2646. a = a1;
  2647. a = A{};
  2648. a.~A();
  2649. })";
  2650. template <typename MatcherType>
  2651. void testImportOf(
  2652. const MatcherType &MethodMatcher, const char *Code = DefaultCode) {
  2653. test(MethodMatcher, Code, /*ExpectedCount=*/1u);
  2654. }
  2655. template <typename MatcherType>
  2656. void testNoImportOf(
  2657. const MatcherType &MethodMatcher, const char *Code = DefaultCode) {
  2658. test(MethodMatcher, Code, /*ExpectedCount=*/0u);
  2659. }
  2660. private:
  2661. template <typename MatcherType>
  2662. void test(const MatcherType &MethodMatcher,
  2663. const char *Code, unsigned int ExpectedCount) {
  2664. auto ClassMatcher = cxxRecordDecl(unless(isImplicit()));
  2665. Decl *ToTU = getToTuDecl(Code, Lang_CXX11);
  2666. auto *ToClass = FirstDeclMatcher<CXXRecordDecl>().match(
  2667. ToTU, ClassMatcher);
  2668. ASSERT_EQ(DeclCounter<CXXMethodDecl>().match(ToClass, MethodMatcher), 1u);
  2669. {
  2670. CXXMethodDecl *Method =
  2671. FirstDeclMatcher<CXXMethodDecl>().match(ToClass, MethodMatcher);
  2672. ToClass->removeDecl(Method);
  2673. SharedStatePtr->getLookupTable()->remove(Method);
  2674. }
  2675. ASSERT_EQ(DeclCounter<CXXMethodDecl>().match(ToClass, MethodMatcher), 0u);
  2676. Decl *ImportedClass = nullptr;
  2677. {
  2678. Decl *FromTU = getTuDecl(Code, Lang_CXX11, "input1.cc");
  2679. auto *FromClass = FirstDeclMatcher<CXXRecordDecl>().match(
  2680. FromTU, ClassMatcher);
  2681. ImportedClass = Import(FromClass, Lang_CXX11);
  2682. }
  2683. EXPECT_EQ(ToClass, ImportedClass);
  2684. EXPECT_EQ(DeclCounter<CXXMethodDecl>().match(ToClass, MethodMatcher),
  2685. ExpectedCount);
  2686. }
  2687. };
  2688. TEST_P(ImportImplicitMethods, DefaultConstructor) {
  2689. testImportOf(cxxConstructorDecl(isDefaultConstructor()));
  2690. }
  2691. TEST_P(ImportImplicitMethods, CopyConstructor) {
  2692. testImportOf(cxxConstructorDecl(isCopyConstructor()));
  2693. }
  2694. TEST_P(ImportImplicitMethods, MoveConstructor) {
  2695. testImportOf(cxxConstructorDecl(isMoveConstructor()));
  2696. }
  2697. TEST_P(ImportImplicitMethods, Destructor) {
  2698. testImportOf(cxxDestructorDecl());
  2699. }
  2700. TEST_P(ImportImplicitMethods, CopyAssignment) {
  2701. testImportOf(cxxMethodDecl(isCopyAssignmentOperator()));
  2702. }
  2703. TEST_P(ImportImplicitMethods, MoveAssignment) {
  2704. testImportOf(cxxMethodDecl(isMoveAssignmentOperator()));
  2705. }
  2706. TEST_P(ImportImplicitMethods, DoNotImportUserProvided) {
  2707. auto Code = R"(
  2708. struct A { A() { int x; } };
  2709. )";
  2710. testNoImportOf(cxxConstructorDecl(isDefaultConstructor()), Code);
  2711. }
  2712. TEST_P(ImportImplicitMethods, DoNotImportDefault) {
  2713. auto Code = R"(
  2714. struct A { A() = default; };
  2715. )";
  2716. testNoImportOf(cxxConstructorDecl(isDefaultConstructor()), Code);
  2717. }
  2718. TEST_P(ImportImplicitMethods, DoNotImportDeleted) {
  2719. auto Code = R"(
  2720. struct A { A() = delete; };
  2721. )";
  2722. testNoImportOf(cxxConstructorDecl(isDefaultConstructor()), Code);
  2723. }
  2724. TEST_P(ImportImplicitMethods, DoNotImportOtherMethod) {
  2725. auto Code = R"(
  2726. struct A { void f() { } };
  2727. )";
  2728. testNoImportOf(cxxMethodDecl(hasName("f")), Code);
  2729. }
  2730. TEST_P(ASTImporterOptionSpecificTestBase, ImportOfEquivalentRecord) {
  2731. Decl *ToR1;
  2732. {
  2733. Decl *FromTU = getTuDecl(
  2734. "struct A { };", Lang_CXX, "input0.cc");
  2735. auto *FromR = FirstDeclMatcher<CXXRecordDecl>().match(
  2736. FromTU, cxxRecordDecl(hasName("A")));
  2737. ToR1 = Import(FromR, Lang_CXX);
  2738. }
  2739. Decl *ToR2;
  2740. {
  2741. Decl *FromTU = getTuDecl(
  2742. "struct A { };", Lang_CXX, "input1.cc");
  2743. auto *FromR = FirstDeclMatcher<CXXRecordDecl>().match(
  2744. FromTU, cxxRecordDecl(hasName("A")));
  2745. ToR2 = Import(FromR, Lang_CXX);
  2746. }
  2747. EXPECT_EQ(ToR1, ToR2);
  2748. }
  2749. TEST_P(ASTImporterOptionSpecificTestBase, ImportOfNonEquivalentRecord) {
  2750. Decl *ToR1;
  2751. {
  2752. Decl *FromTU = getTuDecl(
  2753. "struct A { int x; };", Lang_CXX, "input0.cc");
  2754. auto *FromR = FirstDeclMatcher<CXXRecordDecl>().match(
  2755. FromTU, cxxRecordDecl(hasName("A")));
  2756. ToR1 = Import(FromR, Lang_CXX);
  2757. }
  2758. Decl *ToR2;
  2759. {
  2760. Decl *FromTU = getTuDecl(
  2761. "struct A { unsigned x; };", Lang_CXX, "input1.cc");
  2762. auto *FromR = FirstDeclMatcher<CXXRecordDecl>().match(
  2763. FromTU, cxxRecordDecl(hasName("A")));
  2764. ToR2 = Import(FromR, Lang_CXX);
  2765. }
  2766. EXPECT_NE(ToR1, ToR2);
  2767. }
  2768. TEST_P(ASTImporterOptionSpecificTestBase, ImportOfEquivalentField) {
  2769. Decl *ToF1;
  2770. {
  2771. Decl *FromTU = getTuDecl(
  2772. "struct A { int x; };", Lang_CXX, "input0.cc");
  2773. auto *FromF = FirstDeclMatcher<FieldDecl>().match(
  2774. FromTU, fieldDecl(hasName("x")));
  2775. ToF1 = Import(FromF, Lang_CXX);
  2776. }
  2777. Decl *ToF2;
  2778. {
  2779. Decl *FromTU = getTuDecl(
  2780. "struct A { int x; };", Lang_CXX, "input1.cc");
  2781. auto *FromF = FirstDeclMatcher<FieldDecl>().match(
  2782. FromTU, fieldDecl(hasName("x")));
  2783. ToF2 = Import(FromF, Lang_CXX);
  2784. }
  2785. EXPECT_EQ(ToF1, ToF2);
  2786. }
  2787. TEST_P(ASTImporterOptionSpecificTestBase, ImportOfNonEquivalentField) {
  2788. Decl *ToF1;
  2789. {
  2790. Decl *FromTU = getTuDecl(
  2791. "struct A { int x; };", Lang_CXX, "input0.cc");
  2792. auto *FromF = FirstDeclMatcher<FieldDecl>().match(
  2793. FromTU, fieldDecl(hasName("x")));
  2794. ToF1 = Import(FromF, Lang_CXX);
  2795. }
  2796. Decl *ToF2;
  2797. {
  2798. Decl *FromTU = getTuDecl(
  2799. "struct A { unsigned x; };", Lang_CXX, "input1.cc");
  2800. auto *FromF = FirstDeclMatcher<FieldDecl>().match(
  2801. FromTU, fieldDecl(hasName("x")));
  2802. ToF2 = Import(FromF, Lang_CXX);
  2803. }
  2804. EXPECT_NE(ToF1, ToF2);
  2805. }
  2806. TEST_P(ASTImporterOptionSpecificTestBase, ImportOfEquivalentMethod) {
  2807. Decl *ToM1;
  2808. {
  2809. Decl *FromTU = getTuDecl(
  2810. "struct A { void x(); }; void A::x() { }", Lang_CXX, "input0.cc");
  2811. auto *FromM = FirstDeclMatcher<FunctionDecl>().match(
  2812. FromTU, functionDecl(hasName("x"), isDefinition()));
  2813. ToM1 = Import(FromM, Lang_CXX);
  2814. }
  2815. Decl *ToM2;
  2816. {
  2817. Decl *FromTU = getTuDecl(
  2818. "struct A { void x(); }; void A::x() { }", Lang_CXX, "input1.cc");
  2819. auto *FromM = FirstDeclMatcher<FunctionDecl>().match(
  2820. FromTU, functionDecl(hasName("x"), isDefinition()));
  2821. ToM2 = Import(FromM, Lang_CXX);
  2822. }
  2823. EXPECT_EQ(ToM1, ToM2);
  2824. }
  2825. TEST_P(ASTImporterOptionSpecificTestBase, ImportOfNonEquivalentMethod) {
  2826. Decl *ToM1;
  2827. {
  2828. Decl *FromTU = getTuDecl(
  2829. "struct A { void x(); }; void A::x() { }",
  2830. Lang_CXX, "input0.cc");
  2831. auto *FromM = FirstDeclMatcher<FunctionDecl>().match(
  2832. FromTU, functionDecl(hasName("x"), isDefinition()));
  2833. ToM1 = Import(FromM, Lang_CXX);
  2834. }
  2835. Decl *ToM2;
  2836. {
  2837. Decl *FromTU = getTuDecl(
  2838. "struct A { void x() const; }; void A::x() const { }",
  2839. Lang_CXX, "input1.cc");
  2840. auto *FromM = FirstDeclMatcher<FunctionDecl>().match(
  2841. FromTU, functionDecl(hasName("x"), isDefinition()));
  2842. ToM2 = Import(FromM, Lang_CXX);
  2843. }
  2844. EXPECT_NE(ToM1, ToM2);
  2845. }
  2846. TEST_P(ASTImporterOptionSpecificTestBase,
  2847. ImportUnnamedStructsWithRecursingField) {
  2848. Decl *FromTU = getTuDecl(
  2849. R"(
  2850. struct A {
  2851. struct {
  2852. struct A *next;
  2853. } entry0;
  2854. struct {
  2855. struct A *next;
  2856. } entry1;
  2857. };
  2858. )",
  2859. Lang_C, "input0.cc");
  2860. auto *From =
  2861. FirstDeclMatcher<RecordDecl>().match(FromTU, recordDecl(hasName("A")));
  2862. Import(From, Lang_C);
  2863. auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  2864. auto *Entry0 =
  2865. FirstDeclMatcher<FieldDecl>().match(ToTU, fieldDecl(hasName("entry0")));
  2866. auto *Entry1 =
  2867. FirstDeclMatcher<FieldDecl>().match(ToTU, fieldDecl(hasName("entry1")));
  2868. auto *R0 = getRecordDecl(Entry0);
  2869. auto *R1 = getRecordDecl(Entry1);
  2870. EXPECT_NE(R0, R1);
  2871. EXPECT_TRUE(MatchVerifier<RecordDecl>().match(
  2872. R0, recordDecl(has(fieldDecl(hasName("next"))))));
  2873. EXPECT_TRUE(MatchVerifier<RecordDecl>().match(
  2874. R1, recordDecl(has(fieldDecl(hasName("next"))))));
  2875. }
  2876. TEST_P(ASTImporterOptionSpecificTestBase, ImportUnnamedFieldsInCorrectOrder) {
  2877. Decl *FromTU = getTuDecl(
  2878. R"(
  2879. void f(int X, int Y, bool Z) {
  2880. (void)[X, Y, Z] { (void)Z; };
  2881. }
  2882. )",
  2883. Lang_CXX11, "input0.cc");
  2884. auto *FromF = FirstDeclMatcher<FunctionDecl>().match(
  2885. FromTU, functionDecl(hasName("f")));
  2886. auto *ToF = cast_or_null<FunctionDecl>(Import(FromF, Lang_CXX11));
  2887. EXPECT_TRUE(ToF);
  2888. CXXRecordDecl *FromLambda =
  2889. cast<LambdaExpr>(cast<CStyleCastExpr>(cast<CompoundStmt>(
  2890. FromF->getBody())->body_front())->getSubExpr())->getLambdaClass();
  2891. auto *ToLambda = cast_or_null<CXXRecordDecl>(Import(FromLambda, Lang_CXX11));
  2892. EXPECT_TRUE(ToLambda);
  2893. // Check if the fields of the lambda class are imported in correct order.
  2894. unsigned FromIndex = 0u;
  2895. for (auto *FromField : FromLambda->fields()) {
  2896. ASSERT_FALSE(FromField->getDeclName());
  2897. auto *ToField = cast_or_null<FieldDecl>(Import(FromField, Lang_CXX11));
  2898. EXPECT_TRUE(ToField);
  2899. Optional<unsigned> ToIndex = ASTImporter::getFieldIndex(ToField);
  2900. EXPECT_TRUE(ToIndex);
  2901. EXPECT_EQ(*ToIndex, FromIndex);
  2902. ++FromIndex;
  2903. }
  2904. EXPECT_EQ(FromIndex, 3u);
  2905. }
  2906. TEST_P(ASTImporterOptionSpecificTestBase,
  2907. MergeFieldDeclsOfClassTemplateSpecialization) {
  2908. std::string ClassTemplate =
  2909. R"(
  2910. template <typename T>
  2911. struct X {
  2912. int a{0}; // FieldDecl with InitListExpr
  2913. X(char) : a(3) {} // (1)
  2914. X(int) {} // (2)
  2915. };
  2916. )";
  2917. Decl *ToTU = getToTuDecl(ClassTemplate +
  2918. R"(
  2919. void foo() {
  2920. // ClassTemplateSpec with ctor (1): FieldDecl without InitlistExpr
  2921. X<char> xc('c');
  2922. }
  2923. )", Lang_CXX11);
  2924. auto *ToSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  2925. ToTU, classTemplateSpecializationDecl(hasName("X")));
  2926. // FieldDecl without InitlistExpr:
  2927. auto *ToField = *ToSpec->field_begin();
  2928. ASSERT_TRUE(ToField);
  2929. ASSERT_FALSE(ToField->getInClassInitializer());
  2930. Decl *FromTU = getTuDecl(ClassTemplate +
  2931. R"(
  2932. void bar() {
  2933. // ClassTemplateSpec with ctor (2): FieldDecl WITH InitlistExpr
  2934. X<char> xc(1);
  2935. }
  2936. )", Lang_CXX11);
  2937. auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  2938. FromTU, classTemplateSpecializationDecl(hasName("X")));
  2939. // FieldDecl with InitlistExpr:
  2940. auto *FromField = *FromSpec->field_begin();
  2941. ASSERT_TRUE(FromField);
  2942. ASSERT_TRUE(FromField->getInClassInitializer());
  2943. auto *ImportedSpec = Import(FromSpec, Lang_CXX11);
  2944. ASSERT_TRUE(ImportedSpec);
  2945. EXPECT_EQ(ImportedSpec, ToSpec);
  2946. // After the import, the FieldDecl has to be merged, thus it should have the
  2947. // InitListExpr.
  2948. EXPECT_TRUE(ToField->getInClassInitializer());
  2949. }
  2950. TEST_P(ASTImporterOptionSpecificTestBase,
  2951. MergeFunctionOfClassTemplateSpecialization) {
  2952. std::string ClassTemplate =
  2953. R"(
  2954. template <typename T>
  2955. struct X {
  2956. void f() {}
  2957. void g() {}
  2958. };
  2959. )";
  2960. Decl *ToTU = getToTuDecl(ClassTemplate +
  2961. R"(
  2962. void foo() {
  2963. X<char> x;
  2964. x.f();
  2965. }
  2966. )", Lang_CXX11);
  2967. Decl *FromTU = getTuDecl(ClassTemplate +
  2968. R"(
  2969. void bar() {
  2970. X<char> x;
  2971. x.g();
  2972. }
  2973. )", Lang_CXX11);
  2974. auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  2975. FromTU, classTemplateSpecializationDecl(hasName("X")));
  2976. auto FunPattern = functionDecl(hasName("g"),
  2977. hasParent(classTemplateSpecializationDecl()));
  2978. auto *FromFun =
  2979. FirstDeclMatcher<FunctionDecl>().match(FromTU, FunPattern);
  2980. auto *ToFun =
  2981. FirstDeclMatcher<FunctionDecl>().match(ToTU, FunPattern);
  2982. ASSERT_TRUE(FromFun->hasBody());
  2983. ASSERT_FALSE(ToFun->hasBody());
  2984. auto *ImportedSpec = Import(FromSpec, Lang_CXX11);
  2985. ASSERT_TRUE(ImportedSpec);
  2986. auto *ToSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  2987. ToTU, classTemplateSpecializationDecl(hasName("X")));
  2988. EXPECT_EQ(ImportedSpec, ToSpec);
  2989. EXPECT_TRUE(ToFun->hasBody());
  2990. }
  2991. TEST_P(ASTImporterOptionSpecificTestBase,
  2992. ODRViolationOfClassTemplateSpecializationsShouldBeReported) {
  2993. std::string ClassTemplate =
  2994. R"(
  2995. template <typename T>
  2996. struct X {};
  2997. )";
  2998. Decl *ToTU = getToTuDecl(ClassTemplate +
  2999. R"(
  3000. template <>
  3001. struct X<char> {
  3002. int a;
  3003. };
  3004. void foo() {
  3005. X<char> x;
  3006. }
  3007. )",
  3008. Lang_CXX11);
  3009. Decl *FromTU = getTuDecl(ClassTemplate +
  3010. R"(
  3011. template <>
  3012. struct X<char> {
  3013. int b;
  3014. };
  3015. void foo() {
  3016. X<char> x;
  3017. }
  3018. )",
  3019. Lang_CXX11);
  3020. auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  3021. FromTU, classTemplateSpecializationDecl(hasName("X")));
  3022. auto *ImportedSpec = Import(FromSpec, Lang_CXX11);
  3023. // We expect one (ODR) warning during the import.
  3024. EXPECT_EQ(1u, ToTU->getASTContext().getDiagnostics().getNumWarnings());
  3025. // The second specialization is different from the first, thus it violates
  3026. // ODR, consequently we expect to keep the first specialization only, which is
  3027. // already in the "To" context.
  3028. EXPECT_FALSE(ImportedSpec);
  3029. EXPECT_EQ(1u,
  3030. DeclCounter<ClassTemplateSpecializationDecl>().match(
  3031. ToTU, classTemplateSpecializationDecl(hasName("X"))));
  3032. }
  3033. TEST_P(ASTImporterOptionSpecificTestBase,
  3034. MergeCtorOfClassTemplateSpecialization) {
  3035. std::string ClassTemplate =
  3036. R"(
  3037. template <typename T>
  3038. struct X {
  3039. X(char) {}
  3040. X(int) {}
  3041. };
  3042. )";
  3043. Decl *ToTU = getToTuDecl(ClassTemplate +
  3044. R"(
  3045. void foo() {
  3046. X<char> x('c');
  3047. }
  3048. )", Lang_CXX11);
  3049. Decl *FromTU = getTuDecl(ClassTemplate +
  3050. R"(
  3051. void bar() {
  3052. X<char> x(1);
  3053. }
  3054. )", Lang_CXX11);
  3055. auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  3056. FromTU, classTemplateSpecializationDecl(hasName("X")));
  3057. // Match the void(int) ctor.
  3058. auto CtorPattern =
  3059. cxxConstructorDecl(hasParameter(0, varDecl(hasType(asString("int")))),
  3060. hasParent(classTemplateSpecializationDecl()));
  3061. auto *FromCtor =
  3062. FirstDeclMatcher<CXXConstructorDecl>().match(FromTU, CtorPattern);
  3063. auto *ToCtor =
  3064. FirstDeclMatcher<CXXConstructorDecl>().match(ToTU, CtorPattern);
  3065. ASSERT_TRUE(FromCtor->hasBody());
  3066. ASSERT_FALSE(ToCtor->hasBody());
  3067. auto *ImportedSpec = Import(FromSpec, Lang_CXX11);
  3068. ASSERT_TRUE(ImportedSpec);
  3069. auto *ToSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  3070. ToTU, classTemplateSpecializationDecl(hasName("X")));
  3071. EXPECT_EQ(ImportedSpec, ToSpec);
  3072. EXPECT_TRUE(ToCtor->hasBody());
  3073. }
  3074. TEST_P(ASTImporterOptionSpecificTestBase,
  3075. ClassTemplatePartialSpecializationsShouldNotBeDuplicated) {
  3076. auto Code =
  3077. R"(
  3078. // primary template
  3079. template<class T1, class T2, int I>
  3080. class A {};
  3081. // partial specialization
  3082. template<class T, int I>
  3083. class A<T, T*, I> {};
  3084. )";
  3085. Decl *ToTU = getToTuDecl(Code, Lang_CXX11);
  3086. Decl *FromTU = getTuDecl(Code, Lang_CXX11);
  3087. auto *FromSpec =
  3088. FirstDeclMatcher<ClassTemplatePartialSpecializationDecl>().match(
  3089. FromTU, classTemplatePartialSpecializationDecl());
  3090. auto *ToSpec =
  3091. FirstDeclMatcher<ClassTemplatePartialSpecializationDecl>().match(
  3092. ToTU, classTemplatePartialSpecializationDecl());
  3093. auto *ImportedSpec = Import(FromSpec, Lang_CXX11);
  3094. EXPECT_EQ(ImportedSpec, ToSpec);
  3095. EXPECT_EQ(1u, DeclCounter<ClassTemplatePartialSpecializationDecl>().match(
  3096. ToTU, classTemplatePartialSpecializationDecl()));
  3097. }
  3098. TEST_P(ASTImporterOptionSpecificTestBase,
  3099. ClassTemplateSpecializationsShouldNotBeDuplicated) {
  3100. auto Code =
  3101. R"(
  3102. // primary template
  3103. template<class T1, class T2, int I>
  3104. class A {};
  3105. // full specialization
  3106. template<>
  3107. class A<int, int, 1> {};
  3108. )";
  3109. Decl *ToTU = getToTuDecl(Code, Lang_CXX11);
  3110. Decl *FromTU = getTuDecl(Code, Lang_CXX11);
  3111. auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  3112. FromTU, classTemplateSpecializationDecl());
  3113. auto *ToSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  3114. ToTU, classTemplateSpecializationDecl());
  3115. auto *ImportedSpec = Import(FromSpec, Lang_CXX11);
  3116. EXPECT_EQ(ImportedSpec, ToSpec);
  3117. EXPECT_EQ(1u, DeclCounter<ClassTemplateSpecializationDecl>().match(
  3118. ToTU, classTemplateSpecializationDecl()));
  3119. }
  3120. TEST_P(ASTImporterOptionSpecificTestBase,
  3121. ClassTemplateFullAndPartialSpecsShouldNotBeMixed) {
  3122. std::string PrimaryTemplate =
  3123. R"(
  3124. template<class T1, class T2, int I>
  3125. class A {};
  3126. )";
  3127. auto PartialSpec =
  3128. R"(
  3129. template<class T, int I>
  3130. class A<T, T*, I> {};
  3131. )";
  3132. auto FullSpec =
  3133. R"(
  3134. template<>
  3135. class A<int, int, 1> {};
  3136. )";
  3137. Decl *ToTU = getToTuDecl(PrimaryTemplate + FullSpec, Lang_CXX11);
  3138. Decl *FromTU = getTuDecl(PrimaryTemplate + PartialSpec, Lang_CXX11);
  3139. auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  3140. FromTU, classTemplateSpecializationDecl());
  3141. auto *ImportedSpec = Import(FromSpec, Lang_CXX11);
  3142. EXPECT_TRUE(ImportedSpec);
  3143. // Check the number of partial specializations.
  3144. EXPECT_EQ(1u, DeclCounter<ClassTemplatePartialSpecializationDecl>().match(
  3145. ToTU, classTemplatePartialSpecializationDecl()));
  3146. // Check the number of full specializations.
  3147. EXPECT_EQ(1u, DeclCounter<ClassTemplateSpecializationDecl>().match(
  3148. ToTU, classTemplateSpecializationDecl(
  3149. unless(classTemplatePartialSpecializationDecl()))));
  3150. }
  3151. TEST_P(ASTImporterOptionSpecificTestBase,
  3152. InitListExprValueKindShouldBeImported) {
  3153. Decl *TU = getTuDecl(
  3154. R"(
  3155. const int &init();
  3156. void foo() { const int &a{init()}; }
  3157. )", Lang_CXX11, "input0.cc");
  3158. auto *FromD = FirstDeclMatcher<VarDecl>().match(TU, varDecl(hasName("a")));
  3159. ASSERT_TRUE(FromD->getAnyInitializer());
  3160. auto *InitExpr = FromD->getAnyInitializer();
  3161. ASSERT_TRUE(InitExpr);
  3162. ASSERT_TRUE(InitExpr->isGLValue());
  3163. auto *ToD = Import(FromD, Lang_CXX11);
  3164. EXPECT_TRUE(ToD);
  3165. auto *ToInitExpr = cast<VarDecl>(ToD)->getAnyInitializer();
  3166. EXPECT_TRUE(ToInitExpr);
  3167. EXPECT_TRUE(ToInitExpr->isGLValue());
  3168. }
  3169. struct ImportVariables : ASTImporterOptionSpecificTestBase {};
  3170. TEST_P(ImportVariables, ImportOfOneDeclBringsInTheWholeChain) {
  3171. Decl *FromTU = getTuDecl(
  3172. R"(
  3173. struct A {
  3174. static const int a = 1 + 2;
  3175. };
  3176. const int A::a;
  3177. )", Lang_CXX, "input1.cc");
  3178. auto *FromDWithInit = FirstDeclMatcher<VarDecl>().match(
  3179. FromTU, varDecl(hasName("a"))); // Decl with init
  3180. auto *FromDWithDef = LastDeclMatcher<VarDecl>().match(
  3181. FromTU, varDecl(hasName("a"))); // Decl with definition
  3182. ASSERT_NE(FromDWithInit, FromDWithDef);
  3183. ASSERT_EQ(FromDWithDef->getPreviousDecl(), FromDWithInit);
  3184. auto *ToD0 = cast<VarDecl>(Import(FromDWithInit, Lang_CXX11));
  3185. auto *ToD1 = cast<VarDecl>(Import(FromDWithDef, Lang_CXX11));
  3186. ASSERT_TRUE(ToD0);
  3187. ASSERT_TRUE(ToD1);
  3188. EXPECT_NE(ToD0, ToD1);
  3189. EXPECT_EQ(ToD1->getPreviousDecl(), ToD0);
  3190. }
  3191. TEST_P(ImportVariables, InitAndDefinitionAreInDifferentTUs) {
  3192. auto StructA =
  3193. R"(
  3194. struct A {
  3195. static const int a = 1 + 2;
  3196. };
  3197. )";
  3198. Decl *ToTU = getToTuDecl(StructA, Lang_CXX);
  3199. Decl *FromTU = getTuDecl(std::string(StructA) + "const int A::a;", Lang_CXX,
  3200. "input1.cc");
  3201. auto *FromDWithInit = FirstDeclMatcher<VarDecl>().match(
  3202. FromTU, varDecl(hasName("a"))); // Decl with init
  3203. auto *FromDWithDef = LastDeclMatcher<VarDecl>().match(
  3204. FromTU, varDecl(hasName("a"))); // Decl with definition
  3205. ASSERT_EQ(FromDWithInit, FromDWithDef->getPreviousDecl());
  3206. ASSERT_TRUE(FromDWithInit->getInit());
  3207. ASSERT_FALSE(FromDWithInit->isThisDeclarationADefinition());
  3208. ASSERT_TRUE(FromDWithDef->isThisDeclarationADefinition());
  3209. ASSERT_FALSE(FromDWithDef->getInit());
  3210. auto *ToD = FirstDeclMatcher<VarDecl>().match(
  3211. ToTU, varDecl(hasName("a"))); // Decl with init
  3212. ASSERT_TRUE(ToD->getInit());
  3213. ASSERT_FALSE(ToD->getDefinition());
  3214. auto *ImportedD = cast<VarDecl>(Import(FromDWithDef, Lang_CXX11));
  3215. EXPECT_TRUE(ImportedD->getAnyInitializer());
  3216. EXPECT_TRUE(ImportedD->getDefinition());
  3217. }
  3218. TEST_P(ImportVariables, InitAndDefinitionAreInTheFromContext) {
  3219. auto StructA =
  3220. R"(
  3221. struct A {
  3222. static const int a;
  3223. };
  3224. )";
  3225. Decl *ToTU = getToTuDecl(StructA, Lang_CXX);
  3226. Decl *FromTU = getTuDecl(std::string(StructA) + "const int A::a = 1 + 2;",
  3227. Lang_CXX, "input1.cc");
  3228. auto *FromDDeclarationOnly = FirstDeclMatcher<VarDecl>().match(
  3229. FromTU, varDecl(hasName("a")));
  3230. auto *FromDWithDef = LastDeclMatcher<VarDecl>().match(
  3231. FromTU, varDecl(hasName("a"))); // Decl with definition and with init.
  3232. ASSERT_EQ(FromDDeclarationOnly, FromDWithDef->getPreviousDecl());
  3233. ASSERT_FALSE(FromDDeclarationOnly->getInit());
  3234. ASSERT_FALSE(FromDDeclarationOnly->isThisDeclarationADefinition());
  3235. ASSERT_TRUE(FromDWithDef->isThisDeclarationADefinition());
  3236. ASSERT_TRUE(FromDWithDef->getInit());
  3237. auto *ToD = FirstDeclMatcher<VarDecl>().match(
  3238. ToTU, varDecl(hasName("a")));
  3239. ASSERT_FALSE(ToD->getInit());
  3240. ASSERT_FALSE(ToD->getDefinition());
  3241. auto *ImportedD = cast<VarDecl>(Import(FromDWithDef, Lang_CXX11));
  3242. EXPECT_TRUE(ImportedD->getAnyInitializer());
  3243. EXPECT_TRUE(ImportedD->getDefinition());
  3244. }
  3245. struct ImportClasses : ASTImporterOptionSpecificTestBase {};
  3246. TEST_P(ImportClasses, ImportDefinitionWhenProtoIsInNestedToContext) {
  3247. Decl *ToTU = getToTuDecl("struct A { struct X *Xp; };", Lang_C);
  3248. Decl *FromTU1 = getTuDecl("struct X {};", Lang_C, "input1.cc");
  3249. auto Pattern = recordDecl(hasName("X"), unless(isImplicit()));
  3250. auto ToProto = FirstDeclMatcher<RecordDecl>().match(ToTU, Pattern);
  3251. auto FromDef = FirstDeclMatcher<RecordDecl>().match(FromTU1, Pattern);
  3252. Decl *ImportedDef = Import(FromDef, Lang_C);
  3253. EXPECT_NE(ImportedDef, ToProto);
  3254. EXPECT_EQ(DeclCounter<RecordDecl>().match(ToTU, Pattern), 2u);
  3255. auto ToDef = LastDeclMatcher<RecordDecl>().match(ToTU, Pattern);
  3256. EXPECT_TRUE(ImportedDef == ToDef);
  3257. EXPECT_TRUE(ToDef->isThisDeclarationADefinition());
  3258. EXPECT_FALSE(ToProto->isThisDeclarationADefinition());
  3259. EXPECT_EQ(ToDef->getPreviousDecl(), ToProto);
  3260. }
  3261. TEST_P(ImportClasses, ImportDefinitionWhenProtoIsInNestedToContextCXX) {
  3262. Decl *ToTU = getToTuDecl("struct A { struct X *Xp; };", Lang_CXX);
  3263. Decl *FromTU1 = getTuDecl("struct X {};", Lang_CXX, "input1.cc");
  3264. auto Pattern = recordDecl(hasName("X"), unless(isImplicit()));
  3265. auto ToProto = FirstDeclMatcher<RecordDecl>().match(ToTU, Pattern);
  3266. auto FromDef = FirstDeclMatcher<RecordDecl>().match(FromTU1, Pattern);
  3267. Decl *ImportedDef = Import(FromDef, Lang_CXX);
  3268. EXPECT_NE(ImportedDef, ToProto);
  3269. EXPECT_EQ(DeclCounter<RecordDecl>().match(ToTU, Pattern), 2u);
  3270. auto ToDef = LastDeclMatcher<RecordDecl>().match(ToTU, Pattern);
  3271. EXPECT_TRUE(ImportedDef == ToDef);
  3272. EXPECT_TRUE(ToDef->isThisDeclarationADefinition());
  3273. EXPECT_FALSE(ToProto->isThisDeclarationADefinition());
  3274. EXPECT_EQ(ToDef->getPreviousDecl(), ToProto);
  3275. }
  3276. TEST_P(ImportClasses, ImportNestedPrototypeThenDefinition) {
  3277. Decl *FromTU0 = getTuDecl("struct A { struct X *Xp; };", Lang_C, "input0.cc");
  3278. Decl *FromTU1 = getTuDecl("struct X {};", Lang_C, "input1.cc");
  3279. auto Pattern = recordDecl(hasName("X"), unless(isImplicit()));
  3280. auto FromProto = FirstDeclMatcher<RecordDecl>().match(FromTU0, Pattern);
  3281. auto FromDef = FirstDeclMatcher<RecordDecl>().match(FromTU1, Pattern);
  3282. Decl *ImportedProto = Import(FromProto, Lang_C);
  3283. Decl *ImportedDef = Import(FromDef, Lang_C);
  3284. Decl *ToTU = ImportedDef->getTranslationUnitDecl();
  3285. EXPECT_NE(ImportedDef, ImportedProto);
  3286. EXPECT_EQ(DeclCounter<RecordDecl>().match(ToTU, Pattern), 2u);
  3287. auto ToProto = FirstDeclMatcher<RecordDecl>().match(ToTU, Pattern);
  3288. auto ToDef = LastDeclMatcher<RecordDecl>().match(ToTU, Pattern);
  3289. EXPECT_TRUE(ImportedDef == ToDef);
  3290. EXPECT_TRUE(ImportedProto == ToProto);
  3291. EXPECT_TRUE(ToDef->isThisDeclarationADefinition());
  3292. EXPECT_FALSE(ToProto->isThisDeclarationADefinition());
  3293. EXPECT_EQ(ToDef->getPreviousDecl(), ToProto);
  3294. }
  3295. struct ImportFriendClasses : ASTImporterOptionSpecificTestBase {};
  3296. TEST_P(ImportFriendClasses, ImportOfFriendRecordDoesNotMergeDefinition) {
  3297. Decl *FromTU = getTuDecl(
  3298. R"(
  3299. class A {
  3300. template <int I> class F {};
  3301. class X {
  3302. template <int I> friend class F;
  3303. };
  3304. };
  3305. )",
  3306. Lang_CXX, "input0.cc");
  3307. auto *FromClass = FirstDeclMatcher<CXXRecordDecl>().match(
  3308. FromTU, cxxRecordDecl(hasName("F"), isDefinition()));
  3309. auto *FromFriendClass = LastDeclMatcher<CXXRecordDecl>().match(
  3310. FromTU, cxxRecordDecl(hasName("F")));
  3311. ASSERT_TRUE(FromClass);
  3312. ASSERT_TRUE(FromFriendClass);
  3313. ASSERT_NE(FromClass, FromFriendClass);
  3314. ASSERT_EQ(FromFriendClass->getDefinition(), FromClass);
  3315. ASSERT_EQ(FromFriendClass->getPreviousDecl(), FromClass);
  3316. ASSERT_EQ(FromFriendClass->getDescribedClassTemplate()->getPreviousDecl(),
  3317. FromClass->getDescribedClassTemplate());
  3318. auto *ToClass = cast<CXXRecordDecl>(Import(FromClass, Lang_CXX));
  3319. auto *ToFriendClass = cast<CXXRecordDecl>(Import(FromFriendClass, Lang_CXX));
  3320. EXPECT_TRUE(ToClass);
  3321. EXPECT_TRUE(ToFriendClass);
  3322. EXPECT_NE(ToClass, ToFriendClass);
  3323. EXPECT_EQ(ToFriendClass->getDefinition(), ToClass);
  3324. EXPECT_EQ(ToFriendClass->getPreviousDecl(), ToClass);
  3325. EXPECT_EQ(ToFriendClass->getDescribedClassTemplate()->getPreviousDecl(),
  3326. ToClass->getDescribedClassTemplate());
  3327. }
  3328. TEST_P(ImportFriendClasses, ImportOfRecursiveFriendClass) {
  3329. Decl *FromTu = getTuDecl(
  3330. R"(
  3331. class declToImport {
  3332. friend class declToImport;
  3333. };
  3334. )",
  3335. Lang_CXX, "input.cc");
  3336. auto *FromD = FirstDeclMatcher<CXXRecordDecl>().match(
  3337. FromTu, cxxRecordDecl(hasName("declToImport")));
  3338. auto *ToD = Import(FromD, Lang_CXX);
  3339. auto Pattern = cxxRecordDecl(has(friendDecl()));
  3340. ASSERT_TRUE(MatchVerifier<Decl>{}.match(FromD, Pattern));
  3341. EXPECT_TRUE(MatchVerifier<Decl>{}.match(ToD, Pattern));
  3342. }
  3343. TEST_P(ImportFriendClasses, ImportOfRecursiveFriendClassTemplate) {
  3344. Decl *FromTu = getTuDecl(
  3345. R"(
  3346. template<class A> class declToImport {
  3347. template<class A1> friend class declToImport;
  3348. };
  3349. )",
  3350. Lang_CXX, "input.cc");
  3351. auto *FromD =
  3352. FirstDeclMatcher<ClassTemplateDecl>().match(FromTu, classTemplateDecl());
  3353. auto *ToD = Import(FromD, Lang_CXX);
  3354. auto Pattern = classTemplateDecl(
  3355. has(cxxRecordDecl(has(friendDecl(has(classTemplateDecl()))))));
  3356. ASSERT_TRUE(MatchVerifier<Decl>{}.match(FromD, Pattern));
  3357. EXPECT_TRUE(MatchVerifier<Decl>{}.match(ToD, Pattern));
  3358. auto *Class =
  3359. FirstDeclMatcher<ClassTemplateDecl>().match(ToD, classTemplateDecl());
  3360. auto *Friend = FirstDeclMatcher<FriendDecl>().match(ToD, friendDecl());
  3361. EXPECT_NE(Friend->getFriendDecl(), Class);
  3362. EXPECT_EQ(Friend->getFriendDecl()->getPreviousDecl(), Class);
  3363. }
  3364. TEST_P(ImportFriendClasses, ProperPrevDeclForClassTemplateDecls) {
  3365. auto Pattern = classTemplateSpecializationDecl(hasName("X"));
  3366. ClassTemplateSpecializationDecl *Imported1;
  3367. {
  3368. Decl *FromTU = getTuDecl("template<class T> class X;"
  3369. "struct Y { friend class X<int>; };",
  3370. Lang_CXX, "input0.cc");
  3371. auto *FromD = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  3372. FromTU, Pattern);
  3373. Imported1 = cast<ClassTemplateSpecializationDecl>(Import(FromD, Lang_CXX));
  3374. }
  3375. ClassTemplateSpecializationDecl *Imported2;
  3376. {
  3377. Decl *FromTU = getTuDecl("template<class T> class X;"
  3378. "template<> class X<int>{};"
  3379. "struct Z { friend class X<int>; };",
  3380. Lang_CXX, "input1.cc");
  3381. auto *FromD = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  3382. FromTU, Pattern);
  3383. Imported2 = cast<ClassTemplateSpecializationDecl>(Import(FromD, Lang_CXX));
  3384. }
  3385. Decl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  3386. EXPECT_EQ(DeclCounter<ClassTemplateSpecializationDecl>().match(ToTU, Pattern),
  3387. 2u);
  3388. ASSERT_TRUE(Imported2->getPreviousDecl());
  3389. EXPECT_EQ(Imported2->getPreviousDecl(), Imported1);
  3390. }
  3391. TEST_P(ImportFriendClasses, TypeForDeclShouldBeSetInTemplated) {
  3392. Decl *FromTU0 = getTuDecl(
  3393. R"(
  3394. class X {
  3395. class Y;
  3396. };
  3397. class X::Y {
  3398. template <typename T>
  3399. friend class F; // The decl context of F is the global namespace.
  3400. };
  3401. )",
  3402. Lang_CXX, "input0.cc");
  3403. auto *Fwd = FirstDeclMatcher<ClassTemplateDecl>().match(
  3404. FromTU0, classTemplateDecl(hasName("F")));
  3405. auto *Imported0 = cast<ClassTemplateDecl>(Import(Fwd, Lang_CXX));
  3406. Decl *FromTU1 = getTuDecl(
  3407. R"(
  3408. template <typename T>
  3409. class F {};
  3410. )",
  3411. Lang_CXX, "input1.cc");
  3412. auto *Definition = FirstDeclMatcher<ClassTemplateDecl>().match(
  3413. FromTU1, classTemplateDecl(hasName("F")));
  3414. auto *Imported1 = cast<ClassTemplateDecl>(Import(Definition, Lang_CXX));
  3415. EXPECT_EQ(Imported0->getTemplatedDecl()->getTypeForDecl(),
  3416. Imported1->getTemplatedDecl()->getTypeForDecl());
  3417. }
  3418. TEST_P(ImportFriendClasses, DeclsFromFriendsShouldBeInRedeclChains) {
  3419. Decl *From, *To;
  3420. std::tie(From, To) =
  3421. getImportedDecl("class declToImport {};", Lang_CXX,
  3422. "class Y { friend class declToImport; };", Lang_CXX);
  3423. auto *Imported = cast<CXXRecordDecl>(To);
  3424. EXPECT_TRUE(Imported->getPreviousDecl());
  3425. }
  3426. TEST_P(ImportFriendClasses,
  3427. ImportOfClassTemplateDefinitionShouldConnectToFwdFriend) {
  3428. Decl *ToTU = getToTuDecl(
  3429. R"(
  3430. class X {
  3431. class Y;
  3432. };
  3433. class X::Y {
  3434. template <typename T>
  3435. friend class F; // The decl context of F is the global namespace.
  3436. };
  3437. )",
  3438. Lang_CXX);
  3439. auto *ToDecl = FirstDeclMatcher<ClassTemplateDecl>().match(
  3440. ToTU, classTemplateDecl(hasName("F")));
  3441. Decl *FromTU = getTuDecl(
  3442. R"(
  3443. template <typename T>
  3444. class F {};
  3445. )",
  3446. Lang_CXX, "input0.cc");
  3447. auto *Definition = FirstDeclMatcher<ClassTemplateDecl>().match(
  3448. FromTU, classTemplateDecl(hasName("F")));
  3449. auto *ImportedDef = cast<ClassTemplateDecl>(Import(Definition, Lang_CXX));
  3450. EXPECT_TRUE(ImportedDef->getPreviousDecl());
  3451. EXPECT_EQ(ToDecl, ImportedDef->getPreviousDecl());
  3452. EXPECT_EQ(ToDecl->getTemplatedDecl(),
  3453. ImportedDef->getTemplatedDecl()->getPreviousDecl());
  3454. }
  3455. TEST_P(ImportFriendClasses,
  3456. ImportOfClassTemplateDefinitionAndFwdFriendShouldBeLinked) {
  3457. Decl *FromTU0 = getTuDecl(
  3458. R"(
  3459. class X {
  3460. class Y;
  3461. };
  3462. class X::Y {
  3463. template <typename T>
  3464. friend class F; // The decl context of F is the global namespace.
  3465. };
  3466. )",
  3467. Lang_CXX, "input0.cc");
  3468. auto *Fwd = FirstDeclMatcher<ClassTemplateDecl>().match(
  3469. FromTU0, classTemplateDecl(hasName("F")));
  3470. auto *ImportedFwd = cast<ClassTemplateDecl>(Import(Fwd, Lang_CXX));
  3471. Decl *FromTU1 = getTuDecl(
  3472. R"(
  3473. template <typename T>
  3474. class F {};
  3475. )",
  3476. Lang_CXX, "input1.cc");
  3477. auto *Definition = FirstDeclMatcher<ClassTemplateDecl>().match(
  3478. FromTU1, classTemplateDecl(hasName("F")));
  3479. auto *ImportedDef = cast<ClassTemplateDecl>(Import(Definition, Lang_CXX));
  3480. EXPECT_TRUE(ImportedDef->getPreviousDecl());
  3481. EXPECT_EQ(ImportedFwd, ImportedDef->getPreviousDecl());
  3482. EXPECT_EQ(ImportedFwd->getTemplatedDecl(),
  3483. ImportedDef->getTemplatedDecl()->getPreviousDecl());
  3484. }
  3485. TEST_P(ImportFriendClasses, ImportOfClassDefinitionAndFwdFriendShouldBeLinked) {
  3486. Decl *FromTU0 = getTuDecl(
  3487. R"(
  3488. class X {
  3489. class Y;
  3490. };
  3491. class X::Y {
  3492. friend class F; // The decl context of F is the global namespace.
  3493. };
  3494. )",
  3495. Lang_CXX, "input0.cc");
  3496. auto *Friend = FirstDeclMatcher<FriendDecl>().match(FromTU0, friendDecl());
  3497. QualType FT = Friend->getFriendType()->getType();
  3498. FT = FromTU0->getASTContext().getCanonicalType(FT);
  3499. auto *Fwd = cast<TagType>(FT)->getDecl();
  3500. auto *ImportedFwd = Import(Fwd, Lang_CXX);
  3501. Decl *FromTU1 = getTuDecl(
  3502. R"(
  3503. class F {};
  3504. )",
  3505. Lang_CXX, "input1.cc");
  3506. auto *Definition = FirstDeclMatcher<CXXRecordDecl>().match(
  3507. FromTU1, cxxRecordDecl(hasName("F")));
  3508. auto *ImportedDef = Import(Definition, Lang_CXX);
  3509. EXPECT_TRUE(ImportedDef->getPreviousDecl());
  3510. EXPECT_EQ(ImportedFwd, ImportedDef->getPreviousDecl());
  3511. }
  3512. TEST_P(ASTImporterOptionSpecificTestBase, FriendFunInClassTemplate) {
  3513. auto *Code = R"(
  3514. template <class T>
  3515. struct X {
  3516. friend void foo(){}
  3517. };
  3518. )";
  3519. TranslationUnitDecl *ToTU = getToTuDecl(Code, Lang_CXX);
  3520. auto *ToFoo = FirstDeclMatcher<FunctionDecl>().match(
  3521. ToTU, functionDecl(hasName("foo")));
  3522. TranslationUnitDecl *FromTU = getTuDecl(Code, Lang_CXX, "input.cc");
  3523. auto *FromFoo = FirstDeclMatcher<FunctionDecl>().match(
  3524. FromTU, functionDecl(hasName("foo")));
  3525. auto *ImportedFoo = Import(FromFoo, Lang_CXX);
  3526. EXPECT_EQ(ImportedFoo, ToFoo);
  3527. }
  3528. struct DeclContextTest : ASTImporterOptionSpecificTestBase {};
  3529. TEST_P(DeclContextTest, removeDeclOfClassTemplateSpecialization) {
  3530. Decl *TU = getTuDecl(
  3531. R"(
  3532. namespace NS {
  3533. template <typename T>
  3534. struct S {};
  3535. template struct S<int>;
  3536. inline namespace INS {
  3537. template <typename T>
  3538. struct S {};
  3539. template struct S<int>;
  3540. }
  3541. }
  3542. )", Lang_CXX11, "input0.cc");
  3543. auto *NS = FirstDeclMatcher<NamespaceDecl>().match(
  3544. TU, namespaceDecl());
  3545. auto *Spec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  3546. TU, classTemplateSpecializationDecl());
  3547. ASSERT_TRUE(NS->containsDecl(Spec));
  3548. NS->removeDecl(Spec);
  3549. EXPECT_FALSE(NS->containsDecl(Spec));
  3550. }
  3551. TEST_P(DeclContextTest,
  3552. removeDeclShouldNotFailEvenIfWeHaveExternalVisibleStorage) {
  3553. Decl *TU = getTuDecl("extern int A; int A;", Lang_CXX);
  3554. auto *A0 = FirstDeclMatcher<VarDecl>().match(TU, varDecl(hasName("A")));
  3555. auto *A1 = LastDeclMatcher<VarDecl>().match(TU, varDecl(hasName("A")));
  3556. // Investigate the list.
  3557. auto *DC = A0->getDeclContext();
  3558. ASSERT_TRUE(DC->containsDecl(A0));
  3559. ASSERT_TRUE(DC->containsDecl(A1));
  3560. // Investigate the lookup table.
  3561. auto *Map = DC->getLookupPtr();
  3562. ASSERT_TRUE(Map);
  3563. auto I = Map->find(A0->getDeclName());
  3564. ASSERT_NE(I, Map->end());
  3565. StoredDeclsList &L = I->second;
  3566. // The lookup table contains the most recent decl of A.
  3567. ASSERT_NE(L.getAsDecl(), A0);
  3568. ASSERT_EQ(L.getAsDecl(), A1);
  3569. ASSERT_TRUE(L.getAsDecl());
  3570. // Simulate the private function DeclContext::reconcileExternalVisibleStorage.
  3571. // The point here is to have a Vec with only one element, which is not the
  3572. // one we are going to delete from the DC later.
  3573. L.setHasExternalDecls();
  3574. ASSERT_TRUE(L.getAsVector());
  3575. ASSERT_EQ(1u, L.getAsVector()->size());
  3576. // This asserts in the old implementation.
  3577. DC->removeDecl(A0);
  3578. EXPECT_FALSE(DC->containsDecl(A0));
  3579. }
  3580. struct ImportFunctionTemplateSpecializations
  3581. : ASTImporterOptionSpecificTestBase {};
  3582. TEST_P(ImportFunctionTemplateSpecializations,
  3583. TUshouldNotContainFunctionTemplateImplicitInstantiation) {
  3584. Decl *FromTU = getTuDecl(
  3585. R"(
  3586. template<class T>
  3587. int f() { return 0; }
  3588. void foo() { f<int>(); }
  3589. )",
  3590. Lang_CXX, "input0.cc");
  3591. // Check that the function template instantiation is NOT the child of the TU.
  3592. auto Pattern = translationUnitDecl(
  3593. unless(has(functionDecl(hasName("f"), isTemplateInstantiation()))));
  3594. ASSERT_TRUE(MatchVerifier<Decl>{}.match(FromTU, Pattern));
  3595. auto *Foo = FirstDeclMatcher<FunctionDecl>().match(
  3596. FromTU, functionDecl(hasName("foo")));
  3597. ASSERT_TRUE(Import(Foo, Lang_CXX));
  3598. auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  3599. EXPECT_TRUE(MatchVerifier<Decl>{}.match(ToTU, Pattern));
  3600. }
  3601. TEST_P(ImportFunctionTemplateSpecializations,
  3602. TUshouldNotContainFunctionTemplateExplicitInstantiation) {
  3603. Decl *FromTU = getTuDecl(
  3604. R"(
  3605. template<class T>
  3606. int f() { return 0; }
  3607. template int f<int>();
  3608. )",
  3609. Lang_CXX, "input0.cc");
  3610. // Check that the function template instantiation is NOT the child of the TU.
  3611. auto Instantiation = functionDecl(hasName("f"), isTemplateInstantiation());
  3612. auto Pattern = translationUnitDecl(unless(has(Instantiation)));
  3613. ASSERT_TRUE(MatchVerifier<Decl>{}.match(FromTU, Pattern));
  3614. ASSERT_TRUE(
  3615. Import(FirstDeclMatcher<Decl>().match(FromTU, Instantiation), Lang_CXX));
  3616. auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  3617. EXPECT_TRUE(MatchVerifier<Decl>{}.match(ToTU, Pattern));
  3618. }
  3619. TEST_P(ImportFunctionTemplateSpecializations,
  3620. TUshouldContainFunctionTemplateSpecialization) {
  3621. Decl *FromTU = getTuDecl(
  3622. R"(
  3623. template<class T>
  3624. int f() { return 0; }
  3625. template <> int f<int>() { return 4; }
  3626. )",
  3627. Lang_CXX, "input0.cc");
  3628. // Check that the function template specialization is the child of the TU.
  3629. auto Specialization =
  3630. functionDecl(hasName("f"), isExplicitTemplateSpecialization());
  3631. auto Pattern = translationUnitDecl(has(Specialization));
  3632. ASSERT_TRUE(MatchVerifier<Decl>{}.match(FromTU, Pattern));
  3633. ASSERT_TRUE(
  3634. Import(FirstDeclMatcher<Decl>().match(FromTU, Specialization), Lang_CXX));
  3635. auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  3636. EXPECT_TRUE(MatchVerifier<Decl>{}.match(ToTU, Pattern));
  3637. }
  3638. TEST_P(ImportFunctionTemplateSpecializations,
  3639. FunctionTemplateSpecializationRedeclChain) {
  3640. Decl *FromTU = getTuDecl(
  3641. R"(
  3642. template<class T>
  3643. int f() { return 0; }
  3644. template <> int f<int>() { return 4; }
  3645. )",
  3646. Lang_CXX, "input0.cc");
  3647. auto Spec = functionDecl(hasName("f"), isExplicitTemplateSpecialization(),
  3648. hasParent(translationUnitDecl()));
  3649. auto *FromSpecD = FirstDeclMatcher<Decl>().match(FromTU, Spec);
  3650. {
  3651. auto *TU = FromTU;
  3652. auto *SpecD = FromSpecD;
  3653. auto *TemplateD = FirstDeclMatcher<FunctionTemplateDecl>().match(
  3654. TU, functionTemplateDecl());
  3655. auto *FirstSpecD = *(TemplateD->spec_begin());
  3656. ASSERT_EQ(SpecD, FirstSpecD);
  3657. ASSERT_TRUE(SpecD->getPreviousDecl());
  3658. ASSERT_FALSE(cast<FunctionDecl>(SpecD->getPreviousDecl())
  3659. ->doesThisDeclarationHaveABody());
  3660. }
  3661. ASSERT_TRUE(Import(FromSpecD, Lang_CXX));
  3662. {
  3663. auto *TU = ToAST->getASTContext().getTranslationUnitDecl();
  3664. auto *SpecD = FirstDeclMatcher<Decl>().match(TU, Spec);
  3665. auto *TemplateD = FirstDeclMatcher<FunctionTemplateDecl>().match(
  3666. TU, functionTemplateDecl());
  3667. auto *FirstSpecD = *(TemplateD->spec_begin());
  3668. EXPECT_EQ(SpecD, FirstSpecD);
  3669. ASSERT_TRUE(SpecD->getPreviousDecl());
  3670. EXPECT_FALSE(cast<FunctionDecl>(SpecD->getPreviousDecl())
  3671. ->doesThisDeclarationHaveABody());
  3672. }
  3673. }
  3674. TEST_P(ImportFunctionTemplateSpecializations,
  3675. MatchNumberOfFunctionTemplateSpecializations) {
  3676. Decl *FromTU = getTuDecl(
  3677. R"(
  3678. template <typename T> constexpr int f() { return 0; }
  3679. template <> constexpr int f<int>() { return 4; }
  3680. void foo() {
  3681. static_assert(f<char>() == 0, "");
  3682. static_assert(f<int>() == 4, "");
  3683. }
  3684. )",
  3685. Lang_CXX11, "input0.cc");
  3686. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(
  3687. FromTU, functionDecl(hasName("foo")));
  3688. Import(FromD, Lang_CXX11);
  3689. auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  3690. EXPECT_EQ(
  3691. DeclCounter<FunctionDecl>().match(FromTU, functionDecl(hasName("f"))),
  3692. DeclCounter<FunctionDecl>().match(ToTU, functionDecl(hasName("f"))));
  3693. }
  3694. TEST_P(ASTImporterOptionSpecificTestBase,
  3695. ImportShouldNotReportFalseODRErrorWhenRecordIsBeingDefined) {
  3696. {
  3697. Decl *FromTU = getTuDecl(
  3698. R"(
  3699. template <typename T>
  3700. struct B;
  3701. )",
  3702. Lang_CXX, "input0.cc");
  3703. auto *FromD = FirstDeclMatcher<ClassTemplateDecl>().match(
  3704. FromTU, classTemplateDecl(hasName("B")));
  3705. Import(FromD, Lang_CXX);
  3706. }
  3707. {
  3708. Decl *FromTU = getTuDecl(
  3709. R"(
  3710. template <typename T>
  3711. struct B {
  3712. void f();
  3713. B* b;
  3714. };
  3715. )",
  3716. Lang_CXX, "input1.cc");
  3717. FunctionDecl *FromD = FirstDeclMatcher<FunctionDecl>().match(
  3718. FromTU, functionDecl(hasName("f")));
  3719. Import(FromD, Lang_CXX);
  3720. auto *FromCTD = FirstDeclMatcher<ClassTemplateDecl>().match(
  3721. FromTU, classTemplateDecl(hasName("B")));
  3722. auto *ToCTD = cast<ClassTemplateDecl>(Import(FromCTD, Lang_CXX));
  3723. EXPECT_TRUE(ToCTD->isThisDeclarationADefinition());
  3724. // We expect no (ODR) warning during the import.
  3725. auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  3726. EXPECT_EQ(0u, ToTU->getASTContext().getDiagnostics().getNumWarnings());
  3727. }
  3728. }
  3729. TEST_P(ASTImporterOptionSpecificTestBase,
  3730. ImportingTypedefShouldImportTheCompleteType) {
  3731. // We already have an incomplete underlying type in the "To" context.
  3732. auto Code =
  3733. R"(
  3734. template <typename T>
  3735. struct S {
  3736. void foo();
  3737. };
  3738. using U = S<int>;
  3739. )";
  3740. Decl *ToTU = getToTuDecl(Code, Lang_CXX11);
  3741. auto *ToD = FirstDeclMatcher<TypedefNameDecl>().match(ToTU,
  3742. typedefNameDecl(hasName("U")));
  3743. ASSERT_TRUE(ToD->getUnderlyingType()->isIncompleteType());
  3744. // The "From" context has the same typedef, but the underlying type is
  3745. // complete this time.
  3746. Decl *FromTU = getTuDecl(std::string(Code) +
  3747. R"(
  3748. void foo(U* u) {
  3749. u->foo();
  3750. }
  3751. )", Lang_CXX11);
  3752. auto *FromD = FirstDeclMatcher<TypedefNameDecl>().match(FromTU,
  3753. typedefNameDecl(hasName("U")));
  3754. ASSERT_FALSE(FromD->getUnderlyingType()->isIncompleteType());
  3755. // The imported type should be complete.
  3756. auto *ImportedD = cast<TypedefNameDecl>(Import(FromD, Lang_CXX11));
  3757. EXPECT_FALSE(ImportedD->getUnderlyingType()->isIncompleteType());
  3758. }
  3759. TEST_P(ASTImporterOptionSpecificTestBase, ImportTemplateParameterLists) {
  3760. auto Code =
  3761. R"(
  3762. template<class T>
  3763. int f() { return 0; }
  3764. template <> int f<int>() { return 4; }
  3765. )";
  3766. Decl *FromTU = getTuDecl(Code, Lang_CXX);
  3767. auto *FromD = FirstDeclMatcher<FunctionDecl>().match(FromTU,
  3768. functionDecl(hasName("f"), isExplicitTemplateSpecialization()));
  3769. ASSERT_EQ(FromD->getNumTemplateParameterLists(), 1u);
  3770. auto *ToD = Import(FromD, Lang_CXX);
  3771. // The template parameter list should exist.
  3772. EXPECT_EQ(ToD->getNumTemplateParameterLists(), 1u);
  3773. }
  3774. struct ASTImporterLookupTableTest : ASTImporterOptionSpecificTestBase {};
  3775. TEST_P(ASTImporterLookupTableTest, OneDecl) {
  3776. auto *ToTU = getToTuDecl("int a;", Lang_CXX);
  3777. auto *D = FirstDeclMatcher<VarDecl>().match(ToTU, varDecl(hasName("a")));
  3778. ASTImporterLookupTable LT(*ToTU);
  3779. auto Res = LT.lookup(ToTU, D->getDeclName());
  3780. ASSERT_EQ(Res.size(), 1u);
  3781. EXPECT_EQ(*Res.begin(), D);
  3782. }
  3783. static Decl *findInDeclListOfDC(DeclContext *DC, DeclarationName Name) {
  3784. for (Decl *D : DC->decls()) {
  3785. if (auto *ND = dyn_cast<NamedDecl>(D))
  3786. if (ND->getDeclName() == Name)
  3787. return ND;
  3788. }
  3789. return nullptr;
  3790. }
  3791. TEST_P(ASTImporterLookupTableTest,
  3792. FriendWhichIsnotFoundByNormalLookupShouldBeFoundByImporterSpecificLookup) {
  3793. auto *Code = R"(
  3794. template <class T>
  3795. struct X {
  3796. friend void foo(){}
  3797. };
  3798. )";
  3799. TranslationUnitDecl *ToTU = getToTuDecl(Code, Lang_CXX);
  3800. auto *X = FirstDeclMatcher<ClassTemplateDecl>().match(
  3801. ToTU, classTemplateDecl(hasName("X")));
  3802. auto *Foo = FirstDeclMatcher<FunctionDecl>().match(
  3803. ToTU, functionDecl(hasName("foo")));
  3804. DeclContext *FooDC = Foo->getDeclContext();
  3805. DeclContext *FooLexicalDC = Foo->getLexicalDeclContext();
  3806. ASSERT_EQ(cast<Decl>(FooLexicalDC), X->getTemplatedDecl());
  3807. ASSERT_EQ(cast<Decl>(FooDC), ToTU);
  3808. DeclarationName FooName = Foo->getDeclName();
  3809. // Cannot find in the LookupTable of its DC (TUDecl)
  3810. SmallVector<NamedDecl *, 2> FoundDecls;
  3811. FooDC->getRedeclContext()->localUncachedLookup(FooName, FoundDecls);
  3812. EXPECT_EQ(FoundDecls.size(), 0u);
  3813. // Cannot find in the LookupTable of its LexicalDC (X)
  3814. FooLexicalDC->getRedeclContext()->localUncachedLookup(FooName, FoundDecls);
  3815. EXPECT_EQ(FoundDecls.size(), 0u);
  3816. // Can't find in the list of Decls of the DC.
  3817. EXPECT_EQ(findInDeclListOfDC(FooDC, FooName), nullptr);
  3818. // Can't find in the list of Decls of the LexicalDC
  3819. EXPECT_EQ(findInDeclListOfDC(FooLexicalDC, FooName), nullptr);
  3820. // ASTImporter specific lookup finds it.
  3821. ASTImporterLookupTable LT(*ToTU);
  3822. auto Res = LT.lookup(FooDC, Foo->getDeclName());
  3823. ASSERT_EQ(Res.size(), 1u);
  3824. EXPECT_EQ(*Res.begin(), Foo);
  3825. }
  3826. TEST_P(ASTImporterLookupTableTest,
  3827. FwdDeclStructShouldBeFoundByImporterSpecificLookup) {
  3828. TranslationUnitDecl *ToTU =
  3829. getToTuDecl("struct A { struct Foo *p; };", Lang_C);
  3830. auto *Foo =
  3831. FirstDeclMatcher<RecordDecl>().match(ToTU, recordDecl(hasName("Foo")));
  3832. auto *A =
  3833. FirstDeclMatcher<RecordDecl>().match(ToTU, recordDecl(hasName("A")));
  3834. DeclContext *FooDC = Foo->getDeclContext();
  3835. DeclContext *FooLexicalDC = Foo->getLexicalDeclContext();
  3836. ASSERT_EQ(cast<Decl>(FooLexicalDC), A);
  3837. ASSERT_EQ(cast<Decl>(FooDC), ToTU);
  3838. DeclarationName FooName = Foo->getDeclName();
  3839. // Cannot find in the LookupTable of its DC (TUDecl).
  3840. SmallVector<NamedDecl *, 2> FoundDecls;
  3841. FooDC->getRedeclContext()->localUncachedLookup(FooName, FoundDecls);
  3842. EXPECT_EQ(FoundDecls.size(), 0u);
  3843. // Cannot find in the LookupTable of its LexicalDC (A).
  3844. FooLexicalDC->getRedeclContext()->localUncachedLookup(FooName, FoundDecls);
  3845. EXPECT_EQ(FoundDecls.size(), 0u);
  3846. // Can't find in the list of Decls of the DC.
  3847. EXPECT_EQ(findInDeclListOfDC(FooDC, FooName), nullptr);
  3848. // Can find in the list of Decls of the LexicalDC.
  3849. EXPECT_EQ(findInDeclListOfDC(FooLexicalDC, FooName), Foo);
  3850. // ASTImporter specific lookup finds it.
  3851. ASTImporterLookupTable LT(*ToTU);
  3852. auto Res = LT.lookup(FooDC, Foo->getDeclName());
  3853. ASSERT_EQ(Res.size(), 1u);
  3854. EXPECT_EQ(*Res.begin(), Foo);
  3855. }
  3856. TEST_P(ASTImporterLookupTableTest, LookupFindsNamesInDifferentDC) {
  3857. TranslationUnitDecl *ToTU =
  3858. getToTuDecl("int V; struct A { int V; }; struct B { int V; };", Lang_C);
  3859. DeclarationName VName = FirstDeclMatcher<VarDecl>()
  3860. .match(ToTU, varDecl(hasName("V")))
  3861. ->getDeclName();
  3862. auto *A =
  3863. FirstDeclMatcher<RecordDecl>().match(ToTU, recordDecl(hasName("A")));
  3864. auto *B =
  3865. FirstDeclMatcher<RecordDecl>().match(ToTU, recordDecl(hasName("B")));
  3866. ASTImporterLookupTable LT(*ToTU);
  3867. auto Res = LT.lookup(cast<DeclContext>(A), VName);
  3868. ASSERT_EQ(Res.size(), 1u);
  3869. EXPECT_EQ(*Res.begin(), FirstDeclMatcher<FieldDecl>().match(
  3870. ToTU, fieldDecl(hasName("V"),
  3871. hasParent(recordDecl(hasName("A"))))));
  3872. Res = LT.lookup(cast<DeclContext>(B), VName);
  3873. ASSERT_EQ(Res.size(), 1u);
  3874. EXPECT_EQ(*Res.begin(), FirstDeclMatcher<FieldDecl>().match(
  3875. ToTU, fieldDecl(hasName("V"),
  3876. hasParent(recordDecl(hasName("B"))))));
  3877. Res = LT.lookup(ToTU, VName);
  3878. ASSERT_EQ(Res.size(), 1u);
  3879. EXPECT_EQ(*Res.begin(), FirstDeclMatcher<VarDecl>().match(
  3880. ToTU, varDecl(hasName("V"),
  3881. hasParent(translationUnitDecl()))));
  3882. }
  3883. TEST_P(ASTImporterLookupTableTest, LookupFindsOverloadedNames) {
  3884. TranslationUnitDecl *ToTU = getToTuDecl(
  3885. R"(
  3886. void foo();
  3887. void foo(int);
  3888. void foo(int, int);
  3889. )",
  3890. Lang_CXX);
  3891. ASTImporterLookupTable LT(*ToTU);
  3892. auto *F0 = FirstDeclMatcher<FunctionDecl>().match(ToTU, functionDecl());
  3893. auto *F2 = LastDeclMatcher<FunctionDecl>().match(ToTU, functionDecl());
  3894. DeclarationName Name = F0->getDeclName();
  3895. auto Res = LT.lookup(ToTU, Name);
  3896. EXPECT_EQ(Res.size(), 3u);
  3897. EXPECT_EQ(Res.count(F0), 1u);
  3898. EXPECT_EQ(Res.count(F2), 1u);
  3899. }
  3900. TEST_P(ASTImporterLookupTableTest,
  3901. DifferentOperatorsShouldHaveDifferentResultSet) {
  3902. TranslationUnitDecl *ToTU = getToTuDecl(
  3903. R"(
  3904. struct X{};
  3905. void operator+(X, X);
  3906. void operator-(X, X);
  3907. )",
  3908. Lang_CXX);
  3909. ASTImporterLookupTable LT(*ToTU);
  3910. auto *FPlus = FirstDeclMatcher<FunctionDecl>().match(
  3911. ToTU, functionDecl(hasOverloadedOperatorName("+")));
  3912. auto *FMinus = FirstDeclMatcher<FunctionDecl>().match(
  3913. ToTU, functionDecl(hasOverloadedOperatorName("-")));
  3914. DeclarationName NamePlus = FPlus->getDeclName();
  3915. auto ResPlus = LT.lookup(ToTU, NamePlus);
  3916. EXPECT_EQ(ResPlus.size(), 1u);
  3917. EXPECT_EQ(ResPlus.count(FPlus), 1u);
  3918. EXPECT_EQ(ResPlus.count(FMinus), 0u);
  3919. DeclarationName NameMinus = FMinus->getDeclName();
  3920. auto ResMinus = LT.lookup(ToTU, NameMinus);
  3921. EXPECT_EQ(ResMinus.size(), 1u);
  3922. EXPECT_EQ(ResMinus.count(FMinus), 1u);
  3923. EXPECT_EQ(ResMinus.count(FPlus), 0u);
  3924. EXPECT_NE(*ResMinus.begin(), *ResPlus.begin());
  3925. }
  3926. TEST_P(ASTImporterLookupTableTest, LookupDeclNamesFromDifferentTUs) {
  3927. TranslationUnitDecl *ToTU = getToTuDecl(
  3928. R"(
  3929. struct X {};
  3930. void operator+(X, X);
  3931. )",
  3932. Lang_CXX);
  3933. auto *ToPlus = FirstDeclMatcher<FunctionDecl>().match(
  3934. ToTU, functionDecl(hasOverloadedOperatorName("+")));
  3935. Decl *FromTU = getTuDecl(
  3936. R"(
  3937. struct X {};
  3938. void operator+(X, X);
  3939. )",
  3940. Lang_CXX);
  3941. auto *FromPlus = FirstDeclMatcher<FunctionDecl>().match(
  3942. FromTU, functionDecl(hasOverloadedOperatorName("+")));
  3943. // FromPlus have a different TU, thus its DeclarationName is different too.
  3944. ASSERT_NE(ToPlus->getDeclName(), FromPlus->getDeclName());
  3945. ASTImporterLookupTable LT(*ToTU);
  3946. auto Res = LT.lookup(ToTU, ToPlus->getDeclName());
  3947. ASSERT_EQ(Res.size(), 1u);
  3948. EXPECT_EQ(*Res.begin(), ToPlus);
  3949. // FromPlus have a different TU, thus its DeclarationName is different too.
  3950. Res = LT.lookup(ToTU, FromPlus->getDeclName());
  3951. ASSERT_EQ(Res.size(), 0u);
  3952. }
  3953. static const RecordDecl *getRecordDeclOfFriend(FriendDecl *FD) {
  3954. QualType Ty = FD->getFriendType()->getType().getCanonicalType();
  3955. return cast<RecordType>(Ty)->getDecl();
  3956. }
  3957. TEST_P(ASTImporterLookupTableTest,
  3958. LookupFindsFwdFriendClassDeclWithElaboratedType) {
  3959. TranslationUnitDecl *ToTU = getToTuDecl(
  3960. R"(
  3961. class Y { friend class F; };
  3962. )",
  3963. Lang_CXX);
  3964. // In this case, the CXXRecordDecl is hidden, the FriendDecl is not a parent.
  3965. // So we must dig up the underlying CXXRecordDecl.
  3966. ASTImporterLookupTable LT(*ToTU);
  3967. auto *FriendD = FirstDeclMatcher<FriendDecl>().match(ToTU, friendDecl());
  3968. const RecordDecl *RD = getRecordDeclOfFriend(FriendD);
  3969. auto *Y = FirstDeclMatcher<CXXRecordDecl>().match(
  3970. ToTU, cxxRecordDecl(hasName("Y")));
  3971. DeclarationName Name = RD->getDeclName();
  3972. auto Res = LT.lookup(ToTU, Name);
  3973. EXPECT_EQ(Res.size(), 1u);
  3974. EXPECT_EQ(*Res.begin(), RD);
  3975. Res = LT.lookup(Y, Name);
  3976. EXPECT_EQ(Res.size(), 0u);
  3977. }
  3978. TEST_P(ASTImporterLookupTableTest,
  3979. LookupFindsFwdFriendClassDeclWithUnelaboratedType) {
  3980. TranslationUnitDecl *ToTU = getToTuDecl(
  3981. R"(
  3982. class F;
  3983. class Y { friend F; };
  3984. )",
  3985. Lang_CXX11);
  3986. // In this case, the CXXRecordDecl is hidden, the FriendDecl is not a parent.
  3987. // So we must dig up the underlying CXXRecordDecl.
  3988. ASTImporterLookupTable LT(*ToTU);
  3989. auto *FriendD = FirstDeclMatcher<FriendDecl>().match(ToTU, friendDecl());
  3990. const RecordDecl *RD = getRecordDeclOfFriend(FriendD);
  3991. auto *Y = FirstDeclMatcher<CXXRecordDecl>().match(ToTU, cxxRecordDecl(hasName("Y")));
  3992. DeclarationName Name = RD->getDeclName();
  3993. auto Res = LT.lookup(ToTU, Name);
  3994. EXPECT_EQ(Res.size(), 1u);
  3995. EXPECT_EQ(*Res.begin(), RD);
  3996. Res = LT.lookup(Y, Name);
  3997. EXPECT_EQ(Res.size(), 0u);
  3998. }
  3999. TEST_P(ASTImporterLookupTableTest,
  4000. LookupFindsFriendClassDeclWithTypeAliasDoesNotAssert) {
  4001. TranslationUnitDecl *ToTU = getToTuDecl(
  4002. R"(
  4003. class F;
  4004. using alias_of_f = F;
  4005. class Y { friend alias_of_f; };
  4006. )",
  4007. Lang_CXX11);
  4008. // ASTImporterLookupTable constructor handles using declarations correctly,
  4009. // no assert is expected.
  4010. ASTImporterLookupTable LT(*ToTU);
  4011. auto *Alias = FirstDeclMatcher<TypeAliasDecl>().match(
  4012. ToTU, typeAliasDecl(hasName("alias_of_f")));
  4013. DeclarationName Name = Alias->getDeclName();
  4014. auto Res = LT.lookup(ToTU, Name);
  4015. EXPECT_EQ(Res.count(Alias), 1u);
  4016. }
  4017. TEST_P(ASTImporterLookupTableTest, LookupFindsFwdFriendClassTemplateDecl) {
  4018. TranslationUnitDecl *ToTU = getToTuDecl(
  4019. R"(
  4020. class Y { template <class T> friend class F; };
  4021. )",
  4022. Lang_CXX);
  4023. ASTImporterLookupTable LT(*ToTU);
  4024. auto *F = FirstDeclMatcher<ClassTemplateDecl>().match(
  4025. ToTU, classTemplateDecl(hasName("F")));
  4026. DeclarationName Name = F->getDeclName();
  4027. auto Res = LT.lookup(ToTU, Name);
  4028. EXPECT_EQ(Res.size(), 2u);
  4029. EXPECT_EQ(Res.count(F), 1u);
  4030. EXPECT_EQ(Res.count(F->getTemplatedDecl()), 1u);
  4031. }
  4032. TEST_P(ASTImporterLookupTableTest, DependentFriendClass) {
  4033. TranslationUnitDecl *ToTU = getToTuDecl(
  4034. R"(
  4035. template <typename T>
  4036. class F;
  4037. template <typename T>
  4038. class Y {
  4039. friend class F<T>;
  4040. };
  4041. )",
  4042. Lang_CXX);
  4043. ASTImporterLookupTable LT(*ToTU);
  4044. auto *F = FirstDeclMatcher<ClassTemplateDecl>().match(
  4045. ToTU, classTemplateDecl(hasName("F")));
  4046. DeclarationName Name = F->getDeclName();
  4047. auto Res = LT.lookup(ToTU, Name);
  4048. EXPECT_EQ(Res.size(), 2u);
  4049. EXPECT_EQ(Res.count(F), 1u);
  4050. EXPECT_EQ(Res.count(F->getTemplatedDecl()), 1u);
  4051. }
  4052. TEST_P(ASTImporterLookupTableTest, FriendClassTemplateSpecialization) {
  4053. TranslationUnitDecl *ToTU = getToTuDecl(
  4054. R"(
  4055. template <typename T>
  4056. class F;
  4057. class Y {
  4058. friend class F<int>;
  4059. };
  4060. )",
  4061. Lang_CXX);
  4062. ASTImporterLookupTable LT(*ToTU);
  4063. auto *F = FirstDeclMatcher<ClassTemplateDecl>().match(
  4064. ToTU, classTemplateDecl(hasName("F")));
  4065. DeclarationName Name = F->getDeclName();
  4066. auto Res = LT.lookup(ToTU, Name);
  4067. ASSERT_EQ(Res.size(), 3u);
  4068. EXPECT_EQ(Res.count(F), 1u);
  4069. EXPECT_EQ(Res.count(F->getTemplatedDecl()), 1u);
  4070. EXPECT_EQ(Res.count(*F->spec_begin()), 1u);
  4071. }
  4072. TEST_P(ASTImporterLookupTableTest, LookupFindsFwdFriendFunctionDecl) {
  4073. TranslationUnitDecl *ToTU = getToTuDecl(
  4074. R"(
  4075. class Y { friend void F(); };
  4076. )",
  4077. Lang_CXX);
  4078. ASTImporterLookupTable LT(*ToTU);
  4079. auto *F =
  4080. FirstDeclMatcher<FunctionDecl>().match(ToTU, functionDecl(hasName("F")));
  4081. DeclarationName Name = F->getDeclName();
  4082. auto Res = LT.lookup(ToTU, Name);
  4083. EXPECT_EQ(Res.size(), 1u);
  4084. EXPECT_EQ(*Res.begin(), F);
  4085. }
  4086. TEST_P(ASTImporterLookupTableTest,
  4087. LookupFindsDeclsInClassTemplateSpecialization) {
  4088. TranslationUnitDecl *ToTU = getToTuDecl(
  4089. R"(
  4090. template <typename T>
  4091. struct X {
  4092. int F;
  4093. };
  4094. void foo() {
  4095. X<char> xc;
  4096. }
  4097. )",
  4098. Lang_CXX);
  4099. ASTImporterLookupTable LT(*ToTU);
  4100. auto *Template = FirstDeclMatcher<ClassTemplateDecl>().match(
  4101. ToTU, classTemplateDecl(hasName("X")));
  4102. auto *FieldInTemplate = FirstDeclMatcher<FieldDecl>().match(
  4103. ToTU,
  4104. fieldDecl(hasParent(cxxRecordDecl(hasParent(classTemplateDecl())))));
  4105. auto *Spec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  4106. ToTU, classTemplateSpecializationDecl(hasName("X")));
  4107. FieldDecl *FieldInSpec = *Spec->field_begin();
  4108. ASSERT_TRUE(FieldInSpec);
  4109. DeclarationName Name = FieldInSpec->getDeclName();
  4110. auto TemplateDC = cast<DeclContext>(Template->getTemplatedDecl());
  4111. SmallVector<NamedDecl *, 2> FoundDecls;
  4112. TemplateDC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
  4113. EXPECT_EQ(FoundDecls.size(), 1u);
  4114. EXPECT_EQ(FoundDecls[0], FieldInTemplate);
  4115. auto Res = LT.lookup(TemplateDC, Name);
  4116. ASSERT_EQ(Res.size(), 1u);
  4117. EXPECT_EQ(*Res.begin(), FieldInTemplate);
  4118. cast<DeclContext>(Spec)->getRedeclContext()->localUncachedLookup(Name,
  4119. FoundDecls);
  4120. EXPECT_EQ(FoundDecls.size(), 1u);
  4121. EXPECT_EQ(FoundDecls[0], FieldInSpec);
  4122. Res = LT.lookup(cast<DeclContext>(Spec), Name);
  4123. ASSERT_EQ(Res.size(), 1u);
  4124. EXPECT_EQ(*Res.begin(), FieldInSpec);
  4125. }
  4126. TEST_P(ASTImporterLookupTableTest, LookupFindsFwdFriendFunctionTemplateDecl) {
  4127. TranslationUnitDecl *ToTU = getToTuDecl(
  4128. R"(
  4129. class Y { template <class T> friend void F(); };
  4130. )",
  4131. Lang_CXX);
  4132. ASTImporterLookupTable LT(*ToTU);
  4133. auto *F = FirstDeclMatcher<FunctionTemplateDecl>().match(
  4134. ToTU, functionTemplateDecl(hasName("F")));
  4135. DeclarationName Name = F->getDeclName();
  4136. auto Res = LT.lookup(ToTU, Name);
  4137. EXPECT_EQ(Res.size(), 2u);
  4138. EXPECT_EQ(Res.count(F), 1u);
  4139. EXPECT_EQ(Res.count(F->getTemplatedDecl()), 1u);
  4140. }
  4141. TEST_P(ASTImporterLookupTableTest, MultipleBefriendingClasses) {
  4142. TranslationUnitDecl *ToTU = getToTuDecl(
  4143. R"(
  4144. struct X;
  4145. struct A {
  4146. friend struct X;
  4147. };
  4148. struct B {
  4149. friend struct X;
  4150. };
  4151. )",
  4152. Lang_CXX);
  4153. ASTImporterLookupTable LT(*ToTU);
  4154. auto *X = FirstDeclMatcher<CXXRecordDecl>().match(
  4155. ToTU, cxxRecordDecl(hasName("X")));
  4156. auto *FriendD0 = FirstDeclMatcher<FriendDecl>().match(ToTU, friendDecl());
  4157. auto *FriendD1 = LastDeclMatcher<FriendDecl>().match(ToTU, friendDecl());
  4158. const RecordDecl *RD0 = getRecordDeclOfFriend(FriendD0);
  4159. const RecordDecl *RD1 = getRecordDeclOfFriend(FriendD1);
  4160. ASSERT_EQ(RD0, RD1);
  4161. ASSERT_EQ(RD1, X);
  4162. DeclarationName Name = X->getDeclName();
  4163. auto Res = LT.lookup(ToTU, Name);
  4164. EXPECT_EQ(Res.size(), 1u);
  4165. EXPECT_EQ(*Res.begin(), X);
  4166. }
  4167. TEST_P(ASTImporterLookupTableTest, EnumConstantDecl) {
  4168. TranslationUnitDecl *ToTU = getToTuDecl(
  4169. R"(
  4170. enum E {
  4171. A,
  4172. B
  4173. };
  4174. )",
  4175. Lang_C);
  4176. ASTImporterLookupTable LT(*ToTU);
  4177. auto *E = FirstDeclMatcher<EnumDecl>().match(ToTU, enumDecl(hasName("E")));
  4178. auto *A = FirstDeclMatcher<EnumConstantDecl>().match(
  4179. ToTU, enumConstantDecl(hasName("A")));
  4180. DeclarationName Name = A->getDeclName();
  4181. // Redecl context is the TU.
  4182. ASSERT_EQ(E->getRedeclContext(), ToTU);
  4183. SmallVector<NamedDecl *, 2> FoundDecls;
  4184. // Normal lookup finds in the DC.
  4185. E->localUncachedLookup(Name, FoundDecls);
  4186. EXPECT_EQ(FoundDecls.size(), 1u);
  4187. // Normal lookup finds in the Redecl context.
  4188. ToTU->localUncachedLookup(Name, FoundDecls);
  4189. EXPECT_EQ(FoundDecls.size(), 1u);
  4190. // Import specific lookup finds in the DC.
  4191. auto Res = LT.lookup(E, Name);
  4192. ASSERT_EQ(Res.size(), 1u);
  4193. EXPECT_EQ(*Res.begin(), A);
  4194. // Import specific lookup finds in the Redecl context.
  4195. Res = LT.lookup(ToTU, Name);
  4196. ASSERT_EQ(Res.size(), 1u);
  4197. EXPECT_EQ(*Res.begin(), A);
  4198. }
  4199. TEST_P(ASTImporterLookupTableTest, LookupSearchesInTheWholeRedeclChain) {
  4200. TranslationUnitDecl *ToTU = getToTuDecl(
  4201. R"(
  4202. namespace N {
  4203. int A;
  4204. }
  4205. namespace N {
  4206. }
  4207. )",
  4208. Lang_CXX);
  4209. auto *N1 =
  4210. LastDeclMatcher<NamespaceDecl>().match(ToTU, namespaceDecl(hasName("N")));
  4211. auto *A = FirstDeclMatcher<VarDecl>().match(ToTU, varDecl(hasName("A")));
  4212. DeclarationName Name = A->getDeclName();
  4213. ASTImporterLookupTable LT(*ToTU);
  4214. auto Res = LT.lookup(N1, Name);
  4215. ASSERT_EQ(Res.size(), 1u);
  4216. EXPECT_EQ(*Res.begin(), A);
  4217. }
  4218. TEST_P(ASTImporterOptionSpecificTestBase,
  4219. RedeclChainShouldBeCorrectAmongstNamespaces) {
  4220. Decl *FromTU = getTuDecl(
  4221. R"(
  4222. namespace NS {
  4223. struct X;
  4224. struct Y {
  4225. static const int I = 3;
  4226. };
  4227. }
  4228. namespace NS {
  4229. struct X { // <--- To be imported
  4230. void method(int i = Y::I) {}
  4231. int f;
  4232. };
  4233. }
  4234. )",
  4235. Lang_CXX);
  4236. auto *FromFwd = FirstDeclMatcher<CXXRecordDecl>().match(
  4237. FromTU, cxxRecordDecl(hasName("X"), unless(isImplicit())));
  4238. auto *FromDef = LastDeclMatcher<CXXRecordDecl>().match(
  4239. FromTU,
  4240. cxxRecordDecl(hasName("X"), isDefinition(), unless(isImplicit())));
  4241. ASSERT_NE(FromFwd, FromDef);
  4242. ASSERT_FALSE(FromFwd->isThisDeclarationADefinition());
  4243. ASSERT_TRUE(FromDef->isThisDeclarationADefinition());
  4244. ASSERT_EQ(FromFwd->getCanonicalDecl(), FromDef->getCanonicalDecl());
  4245. auto *ToDef = cast_or_null<CXXRecordDecl>(Import(FromDef, Lang_CXX));
  4246. auto *ToFwd = cast_or_null<CXXRecordDecl>(Import(FromFwd, Lang_CXX));
  4247. EXPECT_NE(ToFwd, ToDef);
  4248. EXPECT_FALSE(ToFwd->isThisDeclarationADefinition());
  4249. EXPECT_TRUE(ToDef->isThisDeclarationADefinition());
  4250. EXPECT_EQ(ToFwd->getCanonicalDecl(), ToDef->getCanonicalDecl());
  4251. auto *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  4252. // We expect no (ODR) warning during the import.
  4253. EXPECT_EQ(0u, ToTU->getASTContext().getDiagnostics().getNumWarnings());
  4254. }
  4255. struct ImportFriendFunctionTemplates : ASTImporterOptionSpecificTestBase {};
  4256. TEST_P(ImportFriendFunctionTemplates, LookupShouldFindPreviousFriend) {
  4257. Decl *ToTU = getToTuDecl(
  4258. R"(
  4259. class X {
  4260. template <typename T> friend void foo();
  4261. };
  4262. )",
  4263. Lang_CXX);
  4264. auto *Friend = FirstDeclMatcher<FunctionTemplateDecl>().match(
  4265. ToTU, functionTemplateDecl(hasName("foo")));
  4266. Decl *FromTU = getTuDecl(
  4267. R"(
  4268. template <typename T> void foo();
  4269. )",
  4270. Lang_CXX);
  4271. auto *FromFoo = FirstDeclMatcher<FunctionTemplateDecl>().match(
  4272. FromTU, functionTemplateDecl(hasName("foo")));
  4273. auto *Imported = Import(FromFoo, Lang_CXX);
  4274. EXPECT_EQ(Imported->getPreviousDecl(), Friend);
  4275. }
  4276. struct ASTImporterWithFakeErrors : ASTImporter {
  4277. using ASTImporter::ASTImporter;
  4278. bool returnWithErrorInTest() override { return true; }
  4279. };
  4280. struct ErrorHandlingTest : ASTImporterOptionSpecificTestBase {
  4281. ErrorHandlingTest() {
  4282. Creator = [](ASTContext &ToContext, FileManager &ToFileManager,
  4283. ASTContext &FromContext, FileManager &FromFileManager,
  4284. bool MinimalImport,
  4285. const std::shared_ptr<ASTImporterSharedState> &SharedState) {
  4286. return new ASTImporterWithFakeErrors(ToContext, ToFileManager,
  4287. FromContext, FromFileManager,
  4288. MinimalImport, SharedState);
  4289. };
  4290. }
  4291. // In this test we purposely report an error (UnsupportedConstruct) when
  4292. // importing the below stmt.
  4293. static constexpr auto* ErroneousStmt = R"( asm(""); )";
  4294. };
  4295. // Check a case when no new AST node is created in the AST before encountering
  4296. // the error.
  4297. TEST_P(ErrorHandlingTest, ErrorHappensBeforeCreatingANewNode) {
  4298. TranslationUnitDecl *ToTU = getToTuDecl(
  4299. R"(
  4300. template <typename T>
  4301. class X {};
  4302. template <>
  4303. class X<int> { int a; };
  4304. )",
  4305. Lang_CXX);
  4306. TranslationUnitDecl *FromTU = getTuDecl(
  4307. R"(
  4308. template <typename T>
  4309. class X {};
  4310. template <>
  4311. class X<int> { double b; };
  4312. )",
  4313. Lang_CXX);
  4314. auto *FromSpec = FirstDeclMatcher<ClassTemplateSpecializationDecl>().match(
  4315. FromTU, classTemplateSpecializationDecl(hasName("X")));
  4316. ClassTemplateSpecializationDecl *ImportedSpec = Import(FromSpec, Lang_CXX);
  4317. EXPECT_FALSE(ImportedSpec);
  4318. // The original Decl is kept, no new decl is created.
  4319. EXPECT_EQ(DeclCounter<ClassTemplateSpecializationDecl>().match(
  4320. ToTU, classTemplateSpecializationDecl(hasName("X"))),
  4321. 1u);
  4322. // But an error is set to the counterpart in the "from" context.
  4323. ASTImporter *Importer = findFromTU(FromSpec)->Importer.get();
  4324. Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromSpec);
  4325. ASSERT_TRUE(OptErr);
  4326. EXPECT_EQ(OptErr->Error, ImportError::NameConflict);
  4327. }
  4328. // Check a case when a new AST node is created but not linked to the AST before
  4329. // encountering the error.
  4330. TEST_P(ErrorHandlingTest,
  4331. ErrorHappensAfterCreatingTheNodeButBeforeLinkingThatToTheAST) {
  4332. TranslationUnitDecl *FromTU = getTuDecl(
  4333. std::string("void foo() { ") + ErroneousStmt + " }",
  4334. Lang_CXX);
  4335. auto *FromFoo = FirstDeclMatcher<FunctionDecl>().match(
  4336. FromTU, functionDecl(hasName("foo")));
  4337. FunctionDecl *ImportedFoo = Import(FromFoo, Lang_CXX);
  4338. EXPECT_FALSE(ImportedFoo);
  4339. TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  4340. // Created, but not linked.
  4341. EXPECT_EQ(
  4342. DeclCounter<FunctionDecl>().match(ToTU, functionDecl(hasName("foo"))),
  4343. 0u);
  4344. ASTImporter *Importer = findFromTU(FromFoo)->Importer.get();
  4345. Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromFoo);
  4346. ASSERT_TRUE(OptErr);
  4347. EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct);
  4348. }
  4349. // Check a case when a new AST node is created and linked to the AST before
  4350. // encountering the error. The error is set for the counterpart of the nodes in
  4351. // the "from" context.
  4352. TEST_P(ErrorHandlingTest, ErrorHappensAfterNodeIsCreatedAndLinked) {
  4353. TranslationUnitDecl *FromTU = getTuDecl(
  4354. std::string(R"(
  4355. void f();
  4356. void f() { )") + ErroneousStmt + R"( }
  4357. )",
  4358. Lang_CXX);
  4359. auto *FromProto = FirstDeclMatcher<FunctionDecl>().match(
  4360. FromTU, functionDecl(hasName("f")));
  4361. auto *FromDef =
  4362. LastDeclMatcher<FunctionDecl>().match(FromTU, functionDecl(hasName("f")));
  4363. FunctionDecl *ImportedProto = Import(FromProto, Lang_CXX);
  4364. EXPECT_FALSE(ImportedProto); // Could not import.
  4365. // However, we created two nodes in the AST. 1) the fwd decl 2) the
  4366. // definition. The definition is not added to its DC, but the fwd decl is
  4367. // there.
  4368. TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  4369. EXPECT_EQ(DeclCounter<FunctionDecl>().match(ToTU, functionDecl(hasName("f"))),
  4370. 1u);
  4371. // Match the fwd decl.
  4372. auto *ToProto =
  4373. FirstDeclMatcher<FunctionDecl>().match(ToTU, functionDecl(hasName("f")));
  4374. EXPECT_TRUE(ToProto);
  4375. // An error is set to the counterpart in the "from" context both for the fwd
  4376. // decl and the definition.
  4377. ASTImporter *Importer = findFromTU(FromProto)->Importer.get();
  4378. Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromProto);
  4379. ASSERT_TRUE(OptErr);
  4380. EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct);
  4381. OptErr = Importer->getImportDeclErrorIfAny(FromDef);
  4382. ASSERT_TRUE(OptErr);
  4383. EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct);
  4384. }
  4385. // An error should be set for a class if we cannot import one member.
  4386. TEST_P(ErrorHandlingTest, ErrorIsPropagatedFromMemberToClass) {
  4387. TranslationUnitDecl *FromTU = getTuDecl(
  4388. std::string(R"(
  4389. class X {
  4390. void f() { )") + ErroneousStmt + R"( } // This member has the error
  4391. // during import.
  4392. void ok(); // The error should not prevent importing this.
  4393. }; // An error will be set for X too.
  4394. )",
  4395. Lang_CXX);
  4396. auto *FromX = FirstDeclMatcher<CXXRecordDecl>().match(
  4397. FromTU, cxxRecordDecl(hasName("X")));
  4398. CXXRecordDecl *ImportedX = Import(FromX, Lang_CXX);
  4399. // An error is set for X.
  4400. EXPECT_FALSE(ImportedX);
  4401. ASTImporter *Importer = findFromTU(FromX)->Importer.get();
  4402. Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromX);
  4403. ASSERT_TRUE(OptErr);
  4404. EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct);
  4405. // An error is set for f().
  4406. auto *FromF = FirstDeclMatcher<CXXMethodDecl>().match(
  4407. FromTU, cxxMethodDecl(hasName("f")));
  4408. OptErr = Importer->getImportDeclErrorIfAny(FromF);
  4409. ASSERT_TRUE(OptErr);
  4410. EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct);
  4411. // And any subsequent import should fail.
  4412. CXXMethodDecl *ImportedF = Import(FromF, Lang_CXX);
  4413. EXPECT_FALSE(ImportedF);
  4414. // There is an error set for the other member too.
  4415. auto *FromOK = FirstDeclMatcher<CXXMethodDecl>().match(
  4416. FromTU, cxxMethodDecl(hasName("ok")));
  4417. OptErr = Importer->getImportDeclErrorIfAny(FromOK);
  4418. EXPECT_TRUE(OptErr);
  4419. // Cannot import the other member.
  4420. CXXMethodDecl *ImportedOK = Import(FromOK, Lang_CXX);
  4421. EXPECT_FALSE(ImportedOK);
  4422. }
  4423. // Check that an error propagates to the dependent AST nodes.
  4424. // In the below code it means that an error in X should propagate to A.
  4425. // And even to F since the containing A is erroneous.
  4426. // And to all AST nodes which we visit during the import process which finally
  4427. // ends up in a failure (in the error() function).
  4428. TEST_P(ErrorHandlingTest, ErrorPropagatesThroughImportCycles) {
  4429. Decl *FromTU = getTuDecl(
  4430. std::string(R"(
  4431. namespace NS {
  4432. class A {
  4433. template <int I> class F {};
  4434. class X {
  4435. template <int I> friend class F;
  4436. void error() { )") + ErroneousStmt + R"( }
  4437. };
  4438. };
  4439. class B {};
  4440. } // NS
  4441. )",
  4442. Lang_CXX, "input0.cc");
  4443. auto *FromFRD = FirstDeclMatcher<CXXRecordDecl>().match(
  4444. FromTU, cxxRecordDecl(hasName("F"), isDefinition()));
  4445. auto *FromA = FirstDeclMatcher<CXXRecordDecl>().match(
  4446. FromTU, cxxRecordDecl(hasName("A"), isDefinition()));
  4447. auto *FromB = FirstDeclMatcher<CXXRecordDecl>().match(
  4448. FromTU, cxxRecordDecl(hasName("B"), isDefinition()));
  4449. auto *FromNS = FirstDeclMatcher<NamespaceDecl>().match(
  4450. FromTU, namespaceDecl(hasName("NS")));
  4451. // Start by importing the templated CXXRecordDecl of F.
  4452. // Import fails for that.
  4453. EXPECT_FALSE(Import(FromFRD, Lang_CXX));
  4454. // Import fails for A.
  4455. EXPECT_FALSE(Import(FromA, Lang_CXX));
  4456. // But we should be able to import the independent B.
  4457. EXPECT_TRUE(Import(FromB, Lang_CXX));
  4458. // And the namespace.
  4459. EXPECT_TRUE(Import(FromNS, Lang_CXX));
  4460. // An error is set to the templated CXXRecordDecl of F.
  4461. ASTImporter *Importer = findFromTU(FromFRD)->Importer.get();
  4462. Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromFRD);
  4463. EXPECT_TRUE(OptErr);
  4464. // An error is set to A.
  4465. OptErr = Importer->getImportDeclErrorIfAny(FromA);
  4466. EXPECT_TRUE(OptErr);
  4467. // There is no error set to B.
  4468. OptErr = Importer->getImportDeclErrorIfAny(FromB);
  4469. EXPECT_FALSE(OptErr);
  4470. // There is no error set to NS.
  4471. OptErr = Importer->getImportDeclErrorIfAny(FromNS);
  4472. EXPECT_FALSE(OptErr);
  4473. // Check some of those decls whose ancestor is X, they all should have an
  4474. // error set if we visited them during an import process which finally failed.
  4475. // These decls are part of a cycle in an ImportPath.
  4476. // There would not be any error set for these decls if we hadn't follow the
  4477. // ImportPaths and the cycles.
  4478. OptErr = Importer->getImportDeclErrorIfAny(
  4479. FirstDeclMatcher<ClassTemplateDecl>().match(
  4480. FromTU, classTemplateDecl(hasName("F"))));
  4481. // An error is set to the 'F' ClassTemplateDecl.
  4482. EXPECT_TRUE(OptErr);
  4483. // An error is set to the FriendDecl.
  4484. OptErr = Importer->getImportDeclErrorIfAny(
  4485. FirstDeclMatcher<FriendDecl>().match(
  4486. FromTU, friendDecl()));
  4487. EXPECT_TRUE(OptErr);
  4488. // An error is set to the implicit class of A.
  4489. OptErr =
  4490. Importer->getImportDeclErrorIfAny(FirstDeclMatcher<CXXRecordDecl>().match(
  4491. FromTU, cxxRecordDecl(hasName("A"), isImplicit())));
  4492. EXPECT_TRUE(OptErr);
  4493. // An error is set to the implicit class of X.
  4494. OptErr =
  4495. Importer->getImportDeclErrorIfAny(FirstDeclMatcher<CXXRecordDecl>().match(
  4496. FromTU, cxxRecordDecl(hasName("X"), isImplicit())));
  4497. EXPECT_TRUE(OptErr);
  4498. }
  4499. TEST_P(ErrorHandlingTest, ErrorIsNotPropagatedFromMemberToNamespace) {
  4500. TranslationUnitDecl *FromTU = getTuDecl(
  4501. std::string(R"(
  4502. namespace X {
  4503. void f() { )") + ErroneousStmt + R"( } // This member has the error
  4504. // during import.
  4505. void ok(); // The error should not prevent importing this.
  4506. }; // An error will be set for X too.
  4507. )",
  4508. Lang_CXX);
  4509. auto *FromX = FirstDeclMatcher<NamespaceDecl>().match(
  4510. FromTU, namespaceDecl(hasName("X")));
  4511. NamespaceDecl *ImportedX = Import(FromX, Lang_CXX);
  4512. // There is no error set for X.
  4513. EXPECT_TRUE(ImportedX);
  4514. ASTImporter *Importer = findFromTU(FromX)->Importer.get();
  4515. Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromX);
  4516. ASSERT_FALSE(OptErr);
  4517. // An error is set for f().
  4518. auto *FromF = FirstDeclMatcher<FunctionDecl>().match(
  4519. FromTU, functionDecl(hasName("f")));
  4520. OptErr = Importer->getImportDeclErrorIfAny(FromF);
  4521. ASSERT_TRUE(OptErr);
  4522. EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct);
  4523. // And any subsequent import should fail.
  4524. FunctionDecl *ImportedF = Import(FromF, Lang_CXX);
  4525. EXPECT_FALSE(ImportedF);
  4526. // There is no error set for ok().
  4527. auto *FromOK = FirstDeclMatcher<FunctionDecl>().match(
  4528. FromTU, functionDecl(hasName("ok")));
  4529. OptErr = Importer->getImportDeclErrorIfAny(FromOK);
  4530. EXPECT_FALSE(OptErr);
  4531. // And we should be able to import.
  4532. FunctionDecl *ImportedOK = Import(FromOK, Lang_CXX);
  4533. EXPECT_TRUE(ImportedOK);
  4534. }
  4535. // An error should be set for a class if it had a previous import with an error
  4536. // from another TU.
  4537. TEST_P(ErrorHandlingTest,
  4538. ImportedDeclWithErrorShouldFailTheImportOfDeclWhichMapToIt) {
  4539. // We already have a fwd decl.
  4540. TranslationUnitDecl *ToTU = getToTuDecl(
  4541. "class X;", Lang_CXX);
  4542. // Then we import a definition.
  4543. {
  4544. TranslationUnitDecl *FromTU = getTuDecl(std::string(R"(
  4545. class X {
  4546. void f() { )") + ErroneousStmt + R"( }
  4547. void ok();
  4548. };
  4549. )",
  4550. Lang_CXX);
  4551. auto *FromX = FirstDeclMatcher<CXXRecordDecl>().match(
  4552. FromTU, cxxRecordDecl(hasName("X")));
  4553. CXXRecordDecl *ImportedX = Import(FromX, Lang_CXX);
  4554. // An error is set for X ...
  4555. EXPECT_FALSE(ImportedX);
  4556. ASTImporter *Importer = findFromTU(FromX)->Importer.get();
  4557. Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromX);
  4558. ASSERT_TRUE(OptErr);
  4559. EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct);
  4560. }
  4561. // ... but the node had been created.
  4562. auto *ToXDef = FirstDeclMatcher<CXXRecordDecl>().match(
  4563. ToTU, cxxRecordDecl(hasName("X"), isDefinition()));
  4564. // An error is set for "ToXDef" in the shared state.
  4565. Optional<ImportError> OptErr =
  4566. SharedStatePtr->getImportDeclErrorIfAny(ToXDef);
  4567. ASSERT_TRUE(OptErr);
  4568. EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct);
  4569. auto *ToXFwd = FirstDeclMatcher<CXXRecordDecl>().match(
  4570. ToTU, cxxRecordDecl(hasName("X"), unless(isDefinition())));
  4571. // An error is NOT set for the fwd Decl of X in the shared state.
  4572. OptErr = SharedStatePtr->getImportDeclErrorIfAny(ToXFwd);
  4573. ASSERT_FALSE(OptErr);
  4574. // Try to import X again but from another TU.
  4575. {
  4576. TranslationUnitDecl *FromTU = getTuDecl(std::string(R"(
  4577. class X {
  4578. void f() { )") + ErroneousStmt + R"( }
  4579. void ok();
  4580. };
  4581. )",
  4582. Lang_CXX, "input1.cc");
  4583. auto *FromX = FirstDeclMatcher<CXXRecordDecl>().match(
  4584. FromTU, cxxRecordDecl(hasName("X")));
  4585. CXXRecordDecl *ImportedX = Import(FromX, Lang_CXX);
  4586. // If we did not save the errors for the "to" context then the below checks
  4587. // would fail, because the lookup finds the fwd Decl of the existing
  4588. // definition in the "to" context. We can reach the existing definition via
  4589. // the found fwd Decl. That existing definition is structurally equivalent
  4590. // (we check only the fields) with this one we want to import, so we return
  4591. // with the existing definition, which is erroneous (one method is missing).
  4592. // The import should fail.
  4593. EXPECT_FALSE(ImportedX);
  4594. ASTImporter *Importer = findFromTU(FromX)->Importer.get();
  4595. Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromX);
  4596. // And an error is set for this new X in the "from" ctx.
  4597. ASSERT_TRUE(OptErr);
  4598. EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct);
  4599. }
  4600. }
  4601. TEST_P(ErrorHandlingTest, ImportOfOverriddenMethods) {
  4602. auto MatchFooA =
  4603. functionDecl(hasName("foo"), hasAncestor(cxxRecordDecl(hasName("A"))));
  4604. auto MatchFooB =
  4605. functionDecl(hasName("foo"), hasAncestor(cxxRecordDecl(hasName("B"))));
  4606. auto MatchFooC =
  4607. functionDecl(hasName("foo"), hasAncestor(cxxRecordDecl(hasName("C"))));
  4608. // Provoke import of a method that has overridden methods with import error.
  4609. TranslationUnitDecl *FromTU = getTuDecl(std::string(R"(
  4610. struct C;
  4611. struct A {
  4612. virtual void foo();
  4613. void f1(C *);
  4614. };
  4615. void A::foo() {
  4616. )") + ErroneousStmt + R"(
  4617. }
  4618. struct B : public A {
  4619. void foo() override;
  4620. };
  4621. struct C : public B {
  4622. void foo() override;
  4623. };
  4624. )",
  4625. Lang_CXX11);
  4626. auto *FromFooA = FirstDeclMatcher<FunctionDecl>().match(FromTU, MatchFooA);
  4627. auto *FromFooB = FirstDeclMatcher<FunctionDecl>().match(FromTU, MatchFooB);
  4628. auto *FromFooC = FirstDeclMatcher<FunctionDecl>().match(FromTU, MatchFooC);
  4629. EXPECT_FALSE(Import(FromFooA, Lang_CXX11));
  4630. ASTImporter *Importer = findFromTU(FromFooA)->Importer.get();
  4631. auto CheckError = [&Importer](Decl *FromD) {
  4632. Optional<ImportError> OptErr = Importer->getImportDeclErrorIfAny(FromD);
  4633. ASSERT_TRUE(OptErr);
  4634. EXPECT_EQ(OptErr->Error, ImportError::UnsupportedConstruct);
  4635. };
  4636. CheckError(FromFooA);
  4637. EXPECT_FALSE(Import(FromFooB, Lang_CXX11));
  4638. CheckError(FromFooB);
  4639. EXPECT_FALSE(Import(FromFooC, Lang_CXX11));
  4640. CheckError(FromFooC);
  4641. }
  4642. TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionBody) {
  4643. Decl *FromTU = getTuDecl(
  4644. R"(
  4645. void f() {
  4646. auto L = [](){};
  4647. }
  4648. )",
  4649. Lang_CXX11, "input0.cc");
  4650. auto Pattern = lambdaExpr();
  4651. CXXRecordDecl *FromL =
  4652. FirstDeclMatcher<LambdaExpr>().match(FromTU, Pattern)->getLambdaClass();
  4653. auto ToL = Import(FromL, Lang_CXX11);
  4654. unsigned ToLSize = std::distance(ToL->decls().begin(), ToL->decls().end());
  4655. unsigned FromLSize =
  4656. std::distance(FromL->decls().begin(), FromL->decls().end());
  4657. EXPECT_NE(ToLSize, 0u);
  4658. EXPECT_EQ(ToLSize, FromLSize);
  4659. }
  4660. TEST_P(ASTImporterOptionSpecificTestBase, LambdaInFunctionParam) {
  4661. Decl *FromTU = getTuDecl(
  4662. R"(
  4663. template <typename F>
  4664. void f(F L = [](){}) {}
  4665. )",
  4666. Lang_CXX11, "input0.cc");
  4667. auto Pattern = lambdaExpr();
  4668. CXXRecordDecl *FromL =
  4669. FirstDeclMatcher<LambdaExpr>().match(FromTU, Pattern)->getLambdaClass();
  4670. auto ToL = Import(FromL, Lang_CXX11);
  4671. unsigned ToLSize = std::distance(ToL->decls().begin(), ToL->decls().end());
  4672. unsigned FromLSize =
  4673. std::distance(FromL->decls().begin(), FromL->decls().end());
  4674. EXPECT_NE(ToLSize, 0u);
  4675. EXPECT_EQ(ToLSize, FromLSize);
  4676. }
  4677. TEST_P(ASTImporterOptionSpecificTestBase, LambdaInGlobalScope) {
  4678. Decl *FromTU = getTuDecl(
  4679. R"(
  4680. auto l1 = [](unsigned lp) { return 1; };
  4681. auto l2 = [](int lp) { return 2; };
  4682. int f(int p) {
  4683. return l1(p) + l2(p);
  4684. }
  4685. )",
  4686. Lang_CXX11, "input0.cc");
  4687. FunctionDecl *FromF = FirstDeclMatcher<FunctionDecl>().match(
  4688. FromTU, functionDecl(hasName("f")));
  4689. FunctionDecl *ToF = Import(FromF, Lang_CXX11);
  4690. EXPECT_TRUE(ToF);
  4691. }
  4692. TEST_P(ASTImporterOptionSpecificTestBase,
  4693. ImportExistingFriendClassTemplateDef) {
  4694. auto Code =
  4695. R"(
  4696. template <class T1, class T2>
  4697. struct Base {
  4698. template <class U1, class U2>
  4699. friend struct Class;
  4700. };
  4701. template <class T1, class T2>
  4702. struct Class { };
  4703. )";
  4704. TranslationUnitDecl *ToTU = getToTuDecl(Code, Lang_CXX);
  4705. TranslationUnitDecl *FromTU = getTuDecl(Code, Lang_CXX, "input.cc");
  4706. auto *ToClassProto = FirstDeclMatcher<ClassTemplateDecl>().match(
  4707. ToTU, classTemplateDecl(hasName("Class")));
  4708. auto *ToClassDef = LastDeclMatcher<ClassTemplateDecl>().match(
  4709. ToTU, classTemplateDecl(hasName("Class")));
  4710. ASSERT_FALSE(ToClassProto->isThisDeclarationADefinition());
  4711. ASSERT_TRUE(ToClassDef->isThisDeclarationADefinition());
  4712. // Previous friend decl is not linked to it!
  4713. ASSERT_FALSE(ToClassDef->getPreviousDecl());
  4714. ASSERT_EQ(ToClassDef->getMostRecentDecl(), ToClassDef);
  4715. ASSERT_EQ(ToClassProto->getMostRecentDecl(), ToClassProto);
  4716. auto *FromClassProto = FirstDeclMatcher<ClassTemplateDecl>().match(
  4717. FromTU, classTemplateDecl(hasName("Class")));
  4718. auto *FromClassDef = LastDeclMatcher<ClassTemplateDecl>().match(
  4719. FromTU, classTemplateDecl(hasName("Class")));
  4720. ASSERT_FALSE(FromClassProto->isThisDeclarationADefinition());
  4721. ASSERT_TRUE(FromClassDef->isThisDeclarationADefinition());
  4722. ASSERT_FALSE(FromClassDef->getPreviousDecl());
  4723. ASSERT_EQ(FromClassDef->getMostRecentDecl(), FromClassDef);
  4724. ASSERT_EQ(FromClassProto->getMostRecentDecl(), FromClassProto);
  4725. auto *ImportedDef = Import(FromClassDef, Lang_CXX);
  4726. // At import we should find the definition for 'Class' even if the
  4727. // prototype (inside 'friend') for it comes first in the AST and is not
  4728. // linked to the definition.
  4729. EXPECT_EQ(ImportedDef, ToClassDef);
  4730. }
  4731. struct LLDBLookupTest : ASTImporterOptionSpecificTestBase {
  4732. LLDBLookupTest() {
  4733. Creator = [](ASTContext &ToContext, FileManager &ToFileManager,
  4734. ASTContext &FromContext, FileManager &FromFileManager,
  4735. bool MinimalImport,
  4736. const std::shared_ptr<ASTImporterSharedState> &SharedState) {
  4737. return new ASTImporter(ToContext, ToFileManager, FromContext,
  4738. FromFileManager, MinimalImport,
  4739. // We use the regular lookup.
  4740. /*SharedState=*/nullptr);
  4741. };
  4742. }
  4743. };
  4744. TEST_P(LLDBLookupTest, ImporterShouldFindInTransparentContext) {
  4745. TranslationUnitDecl *ToTU = getToTuDecl(
  4746. R"(
  4747. extern "C" {
  4748. class X{};
  4749. };
  4750. )",
  4751. Lang_CXX);
  4752. auto *ToX = FirstDeclMatcher<CXXRecordDecl>().match(
  4753. ToTU, cxxRecordDecl(hasName("X")));
  4754. // Set up a stub external storage.
  4755. ToTU->setHasExternalLexicalStorage(true);
  4756. // Set up DeclContextBits.HasLazyExternalLexicalLookups to true.
  4757. ToTU->setMustBuildLookupTable();
  4758. struct TestExternalASTSource : ExternalASTSource {};
  4759. ToTU->getASTContext().setExternalSource(new TestExternalASTSource());
  4760. Decl *FromTU = getTuDecl(
  4761. R"(
  4762. class X;
  4763. )",
  4764. Lang_CXX);
  4765. auto *FromX = FirstDeclMatcher<CXXRecordDecl>().match(
  4766. FromTU, cxxRecordDecl(hasName("X")));
  4767. auto *ImportedX = Import(FromX, Lang_CXX);
  4768. // The lookup must find the existing class definition in the LinkageSpecDecl.
  4769. // Then the importer renders the existing and the new decl into one chain.
  4770. EXPECT_EQ(ImportedX->getCanonicalDecl(), ToX->getCanonicalDecl());
  4771. }
  4772. struct SVEBuiltins : ASTImporterOptionSpecificTestBase {};
  4773. TEST_P(SVEBuiltins, ImportTypes) {
  4774. static const char *const TypeNames[] = {
  4775. "__SVInt8_t",
  4776. "__SVInt16_t",
  4777. "__SVInt32_t",
  4778. "__SVInt64_t",
  4779. "__SVUint8_t",
  4780. "__SVUint16_t",
  4781. "__SVUint32_t",
  4782. "__SVUint64_t",
  4783. "__SVFloat16_t",
  4784. "__SVFloat32_t",
  4785. "__SVFloat64_t",
  4786. "__SVBool_t"
  4787. };
  4788. TranslationUnitDecl *ToTU = getToTuDecl("", Lang_CXX);
  4789. TranslationUnitDecl *FromTU = getTuDecl("", Lang_CXX, "input.cc");
  4790. for (auto *TypeName : TypeNames) {
  4791. auto *ToTypedef = FirstDeclMatcher<TypedefDecl>().match(
  4792. ToTU, typedefDecl(hasName(TypeName)));
  4793. QualType ToType = ToTypedef->getUnderlyingType();
  4794. auto *FromTypedef = FirstDeclMatcher<TypedefDecl>().match(
  4795. FromTU, typedefDecl(hasName(TypeName)));
  4796. QualType FromType = FromTypedef->getUnderlyingType();
  4797. QualType ImportedType = ImportType(FromType, FromTypedef, Lang_CXX);
  4798. EXPECT_EQ(ImportedType, ToType);
  4799. }
  4800. }
  4801. TEST_P(ASTImporterOptionSpecificTestBase, ImportOfDefaultImplicitFunctions) {
  4802. // Test that import of implicit functions works and the functions
  4803. // are merged into one chain.
  4804. auto GetDeclToImport = [this](StringRef File) {
  4805. Decl *FromTU = getTuDecl(
  4806. R"(
  4807. struct X { };
  4808. // Force generating some implicit operator definitions for X.
  4809. void f() { X x1, x2; x1 = x2; X *x3 = new X; delete x3; }
  4810. )",
  4811. Lang_CXX11, File);
  4812. auto *FromD = FirstDeclMatcher<CXXRecordDecl>().match(
  4813. FromTU, cxxRecordDecl(hasName("X"), unless(isImplicit())));
  4814. // Destructor is picked as one example of implicit function.
  4815. return FromD->getDestructor();
  4816. };
  4817. auto *ToD1 = Import(GetDeclToImport("input1.cc"), Lang_CXX11);
  4818. ASSERT_TRUE(ToD1);
  4819. auto *ToD2 = Import(GetDeclToImport("input2.cc"), Lang_CXX11);
  4820. ASSERT_TRUE(ToD2);
  4821. EXPECT_EQ(ToD1->getCanonicalDecl(), ToD2->getCanonicalDecl());
  4822. }
  4823. TEST_P(ASTImporterOptionSpecificTestBase,
  4824. ImportOfExplicitlyDefaultedOrDeleted) {
  4825. Decl *FromTU = getTuDecl(
  4826. R"(
  4827. struct X { X() = default; X(const X&) = delete; };
  4828. )",
  4829. Lang_CXX11);
  4830. auto *FromX = FirstDeclMatcher<CXXRecordDecl>().match(
  4831. FromTU, cxxRecordDecl(hasName("X")));
  4832. auto *ImportedX = Import(FromX, Lang_CXX11);
  4833. auto *Constr1 = FirstDeclMatcher<CXXConstructorDecl>().match(
  4834. ImportedX, cxxConstructorDecl(hasName("X"), unless(isImplicit())));
  4835. auto *Constr2 = LastDeclMatcher<CXXConstructorDecl>().match(
  4836. ImportedX, cxxConstructorDecl(hasName("X"), unless(isImplicit())));
  4837. ASSERT_TRUE(ImportedX);
  4838. EXPECT_TRUE(Constr1->isDefaulted());
  4839. EXPECT_TRUE(Constr1->isExplicitlyDefaulted());
  4840. EXPECT_TRUE(Constr2->isDeletedAsWritten());
  4841. EXPECT_EQ(ImportedX->isAggregate(), FromX->isAggregate());
  4842. }
  4843. INSTANTIATE_TEST_CASE_P(ParameterizedTests, SVEBuiltins,
  4844. ::testing::Values(ArgVector{"-target",
  4845. "aarch64-linux-gnu"}), );
  4846. INSTANTIATE_TEST_CASE_P(ParameterizedTests, DeclContextTest,
  4847. ::testing::Values(ArgVector()), );
  4848. INSTANTIATE_TEST_CASE_P(ParameterizedTests, CanonicalRedeclChain,
  4849. ::testing::Values(ArgVector()), );
  4850. TEST_P(ASTImporterOptionSpecificTestBase, LambdasAreDifferentiated) {
  4851. Decl *FromTU = getTuDecl(
  4852. R"(
  4853. void f() {
  4854. auto L0 = [](){};
  4855. auto L1 = [](){};
  4856. }
  4857. )",
  4858. Lang_CXX11, "input0.cc");
  4859. auto Pattern = lambdaExpr();
  4860. CXXRecordDecl *FromL0 =
  4861. FirstDeclMatcher<LambdaExpr>().match(FromTU, Pattern)->getLambdaClass();
  4862. CXXRecordDecl *FromL1 =
  4863. LastDeclMatcher<LambdaExpr>().match(FromTU, Pattern)->getLambdaClass();
  4864. ASSERT_NE(FromL0, FromL1);
  4865. CXXRecordDecl *ToL0 = Import(FromL0, Lang_CXX11);
  4866. CXXRecordDecl *ToL1 = Import(FromL1, Lang_CXX11);
  4867. EXPECT_NE(ToL0, ToL1);
  4868. }
  4869. TEST_P(ASTImporterOptionSpecificTestBase,
  4870. LambdasInFunctionParamsAreDifferentiated) {
  4871. Decl *FromTU = getTuDecl(
  4872. R"(
  4873. template <typename F0, typename F1>
  4874. void f(F0 L0 = [](){}, F1 L1 = [](){}) {}
  4875. )",
  4876. Lang_CXX11, "input0.cc");
  4877. auto Pattern = cxxRecordDecl(isLambda());
  4878. CXXRecordDecl *FromL0 =
  4879. FirstDeclMatcher<CXXRecordDecl>().match(FromTU, Pattern);
  4880. CXXRecordDecl *FromL1 =
  4881. LastDeclMatcher<CXXRecordDecl>().match(FromTU, Pattern);
  4882. ASSERT_NE(FromL0, FromL1);
  4883. CXXRecordDecl *ToL0 = Import(FromL0, Lang_CXX11);
  4884. CXXRecordDecl *ToL1 = Import(FromL1, Lang_CXX11);
  4885. ASSERT_NE(ToL0, ToL1);
  4886. }
  4887. TEST_P(ASTImporterOptionSpecificTestBase,
  4888. LambdasInFunctionParamsAreDifferentiatedWhenMacroIsUsed) {
  4889. Decl *FromTU = getTuDecl(
  4890. R"(
  4891. #define LAMBDA [](){}
  4892. template <typename F0, typename F1>
  4893. void f(F0 L0 = LAMBDA, F1 L1 = LAMBDA) {}
  4894. )",
  4895. Lang_CXX11, "input0.cc");
  4896. auto Pattern = cxxRecordDecl(isLambda());
  4897. CXXRecordDecl *FromL0 =
  4898. FirstDeclMatcher<CXXRecordDecl>().match(FromTU, Pattern);
  4899. CXXRecordDecl *FromL1 =
  4900. LastDeclMatcher<CXXRecordDecl>().match(FromTU, Pattern);
  4901. ASSERT_NE(FromL0, FromL1);
  4902. Import(FromL0, Lang_CXX11);
  4903. Import(FromL1, Lang_CXX11);
  4904. CXXRecordDecl *ToL0 = Import(FromL0, Lang_CXX11);
  4905. CXXRecordDecl *ToL1 = Import(FromL1, Lang_CXX11);
  4906. ASSERT_NE(ToL0, ToL1);
  4907. }
  4908. TEST_P(ASTImporterOptionSpecificTestBase, ImportAssignedLambda) {
  4909. Decl *FromTU = getTuDecl(
  4910. R"(
  4911. void f() {
  4912. auto x = []{} = {}; auto x2 = x;
  4913. }
  4914. )",
  4915. Lang_CXX2a, "input0.cc");
  4916. auto FromF = FirstDeclMatcher<FunctionDecl>().match(
  4917. FromTU, functionDecl(hasName("f")));
  4918. // We have only one lambda class.
  4919. ASSERT_EQ(
  4920. DeclCounter<CXXRecordDecl>().match(FromTU, cxxRecordDecl(isLambda())),
  4921. 1u);
  4922. FunctionDecl *ToF = Import(FromF, Lang_CXX2a);
  4923. EXPECT_TRUE(ToF);
  4924. TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  4925. // We have only one lambda class after the import.
  4926. EXPECT_EQ(DeclCounter<CXXRecordDecl>().match(ToTU, cxxRecordDecl(isLambda())),
  4927. 1u);
  4928. }
  4929. TEST_P(ASTImporterOptionSpecificTestBase, ImportDefaultConstructibleLambdas) {
  4930. Decl *FromTU = getTuDecl(
  4931. R"(
  4932. void f() {
  4933. auto x = []{} = {};
  4934. auto xb = []{} = {};
  4935. }
  4936. )",
  4937. Lang_CXX2a, "input0.cc");
  4938. auto FromF = FirstDeclMatcher<FunctionDecl>().match(
  4939. FromTU, functionDecl(hasName("f")));
  4940. // We have two lambda classes.
  4941. ASSERT_EQ(
  4942. DeclCounter<CXXRecordDecl>().match(FromTU, cxxRecordDecl(isLambda())),
  4943. 2u);
  4944. FunctionDecl *ToF = Import(FromF, Lang_CXX2a);
  4945. EXPECT_TRUE(ToF);
  4946. TranslationUnitDecl *ToTU = ToAST->getASTContext().getTranslationUnitDecl();
  4947. // We have two lambda classes after the import.
  4948. EXPECT_EQ(DeclCounter<CXXRecordDecl>().match(ToTU, cxxRecordDecl(isLambda())),
  4949. 2u);
  4950. }
  4951. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ASTImporterLookupTableTest,
  4952. DefaultTestValuesForRunOptions, );
  4953. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportPath,
  4954. ::testing::Values(ArgVector()), );
  4955. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportExpr,
  4956. DefaultTestValuesForRunOptions, );
  4957. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportType,
  4958. DefaultTestValuesForRunOptions, );
  4959. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportDecl,
  4960. DefaultTestValuesForRunOptions, );
  4961. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ASTImporterOptionSpecificTestBase,
  4962. DefaultTestValuesForRunOptions, );
  4963. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ErrorHandlingTest,
  4964. DefaultTestValuesForRunOptions, );
  4965. INSTANTIATE_TEST_CASE_P(ParameterizedTests, RedirectingImporterTest,
  4966. DefaultTestValuesForRunOptions, );
  4967. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportFunctions,
  4968. DefaultTestValuesForRunOptions, );
  4969. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportFunctionTemplates,
  4970. DefaultTestValuesForRunOptions, );
  4971. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportFriendFunctionTemplates,
  4972. DefaultTestValuesForRunOptions, );
  4973. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportClasses,
  4974. DefaultTestValuesForRunOptions, );
  4975. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportFriendFunctions,
  4976. DefaultTestValuesForRunOptions, );
  4977. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportFriendClasses,
  4978. DefaultTestValuesForRunOptions, );
  4979. INSTANTIATE_TEST_CASE_P(ParameterizedTests,
  4980. ImportFunctionTemplateSpecializations,
  4981. DefaultTestValuesForRunOptions, );
  4982. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportImplicitMethods,
  4983. DefaultTestValuesForRunOptions, );
  4984. INSTANTIATE_TEST_CASE_P(ParameterizedTests, ImportVariables,
  4985. DefaultTestValuesForRunOptions, );
  4986. INSTANTIATE_TEST_CASE_P(ParameterizedTests, LLDBLookupTest,
  4987. DefaultTestValuesForRunOptions, );
  4988. } // end namespace ast_matchers
  4989. } // end namespace clang