SemaCodeComplete.cpp 383 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035
  1. //===---------------- SemaCodeComplete.cpp - Code Completion ----*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the code-completion semantic actions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ASTConcept.h"
  13. #include "clang/AST/Decl.h"
  14. #include "clang/AST/DeclBase.h"
  15. #include "clang/AST/DeclCXX.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/DeclTemplate.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/ExprConcepts.h"
  21. #include "clang/AST/ExprObjC.h"
  22. #include "clang/AST/NestedNameSpecifier.h"
  23. #include "clang/AST/QualTypeNames.h"
  24. #include "clang/AST/RecursiveASTVisitor.h"
  25. #include "clang/AST/Type.h"
  26. #include "clang/Basic/AttributeCommonInfo.h"
  27. #include "clang/Basic/CharInfo.h"
  28. #include "clang/Basic/OperatorKinds.h"
  29. #include "clang/Basic/Specifiers.h"
  30. #include "clang/Lex/HeaderSearch.h"
  31. #include "clang/Lex/MacroInfo.h"
  32. #include "clang/Lex/Preprocessor.h"
  33. #include "clang/Sema/CodeCompleteConsumer.h"
  34. #include "clang/Sema/DeclSpec.h"
  35. #include "clang/Sema/Designator.h"
  36. #include "clang/Sema/Lookup.h"
  37. #include "clang/Sema/Overload.h"
  38. #include "clang/Sema/ParsedAttr.h"
  39. #include "clang/Sema/ParsedTemplate.h"
  40. #include "clang/Sema/Scope.h"
  41. #include "clang/Sema/ScopeInfo.h"
  42. #include "clang/Sema/Sema.h"
  43. #include "clang/Sema/SemaInternal.h"
  44. #include "llvm/ADT/ArrayRef.h"
  45. #include "llvm/ADT/DenseSet.h"
  46. #include "llvm/ADT/SmallBitVector.h"
  47. #include "llvm/ADT/SmallPtrSet.h"
  48. #include "llvm/ADT/SmallString.h"
  49. #include "llvm/ADT/StringExtras.h"
  50. #include "llvm/ADT/StringSwitch.h"
  51. #include "llvm/ADT/Twine.h"
  52. #include "llvm/ADT/iterator_range.h"
  53. #include "llvm/Support/Casting.h"
  54. #include "llvm/Support/Path.h"
  55. #include "llvm/Support/raw_ostream.h"
  56. #include <list>
  57. #include <map>
  58. #include <string>
  59. #include <vector>
  60. using namespace clang;
  61. using namespace sema;
  62. namespace {
  63. /// A container of code-completion results.
  64. class ResultBuilder {
  65. public:
  66. /// The type of a name-lookup filter, which can be provided to the
  67. /// name-lookup routines to specify which declarations should be included in
  68. /// the result set (when it returns true) and which declarations should be
  69. /// filtered out (returns false).
  70. typedef bool (ResultBuilder::*LookupFilter)(const NamedDecl *) const;
  71. typedef CodeCompletionResult Result;
  72. private:
  73. /// The actual results we have found.
  74. std::vector<Result> Results;
  75. /// A record of all of the declarations we have found and placed
  76. /// into the result set, used to ensure that no declaration ever gets into
  77. /// the result set twice.
  78. llvm::SmallPtrSet<const Decl *, 16> AllDeclsFound;
  79. typedef std::pair<const NamedDecl *, unsigned> DeclIndexPair;
  80. /// An entry in the shadow map, which is optimized to store
  81. /// a single (declaration, index) mapping (the common case) but
  82. /// can also store a list of (declaration, index) mappings.
  83. class ShadowMapEntry {
  84. typedef SmallVector<DeclIndexPair, 4> DeclIndexPairVector;
  85. /// Contains either the solitary NamedDecl * or a vector
  86. /// of (declaration, index) pairs.
  87. llvm::PointerUnion<const NamedDecl *, DeclIndexPairVector *> DeclOrVector;
  88. /// When the entry contains a single declaration, this is
  89. /// the index associated with that entry.
  90. unsigned SingleDeclIndex;
  91. public:
  92. ShadowMapEntry() : SingleDeclIndex(0) {}
  93. ShadowMapEntry(const ShadowMapEntry &) = delete;
  94. ShadowMapEntry(ShadowMapEntry &&Move) { *this = std::move(Move); }
  95. ShadowMapEntry &operator=(const ShadowMapEntry &) = delete;
  96. ShadowMapEntry &operator=(ShadowMapEntry &&Move) {
  97. SingleDeclIndex = Move.SingleDeclIndex;
  98. DeclOrVector = Move.DeclOrVector;
  99. Move.DeclOrVector = nullptr;
  100. return *this;
  101. }
  102. void Add(const NamedDecl *ND, unsigned Index) {
  103. if (DeclOrVector.isNull()) {
  104. // 0 - > 1 elements: just set the single element information.
  105. DeclOrVector = ND;
  106. SingleDeclIndex = Index;
  107. return;
  108. }
  109. if (const NamedDecl *PrevND =
  110. DeclOrVector.dyn_cast<const NamedDecl *>()) {
  111. // 1 -> 2 elements: create the vector of results and push in the
  112. // existing declaration.
  113. DeclIndexPairVector *Vec = new DeclIndexPairVector;
  114. Vec->push_back(DeclIndexPair(PrevND, SingleDeclIndex));
  115. DeclOrVector = Vec;
  116. }
  117. // Add the new element to the end of the vector.
  118. DeclOrVector.get<DeclIndexPairVector *>()->push_back(
  119. DeclIndexPair(ND, Index));
  120. }
  121. ~ShadowMapEntry() {
  122. if (DeclIndexPairVector *Vec =
  123. DeclOrVector.dyn_cast<DeclIndexPairVector *>()) {
  124. delete Vec;
  125. DeclOrVector = ((NamedDecl *)nullptr);
  126. }
  127. }
  128. // Iteration.
  129. class iterator;
  130. iterator begin() const;
  131. iterator end() const;
  132. };
  133. /// A mapping from declaration names to the declarations that have
  134. /// this name within a particular scope and their index within the list of
  135. /// results.
  136. typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
  137. /// The semantic analysis object for which results are being
  138. /// produced.
  139. Sema &SemaRef;
  140. /// The allocator used to allocate new code-completion strings.
  141. CodeCompletionAllocator &Allocator;
  142. CodeCompletionTUInfo &CCTUInfo;
  143. /// If non-NULL, a filter function used to remove any code-completion
  144. /// results that are not desirable.
  145. LookupFilter Filter;
  146. /// Whether we should allow declarations as
  147. /// nested-name-specifiers that would otherwise be filtered out.
  148. bool AllowNestedNameSpecifiers;
  149. /// If set, the type that we would prefer our resulting value
  150. /// declarations to have.
  151. ///
  152. /// Closely matching the preferred type gives a boost to a result's
  153. /// priority.
  154. CanQualType PreferredType;
  155. /// A list of shadow maps, which is used to model name hiding at
  156. /// different levels of, e.g., the inheritance hierarchy.
  157. std::list<ShadowMap> ShadowMaps;
  158. /// Overloaded C++ member functions found by SemaLookup.
  159. /// Used to determine when one overload is dominated by another.
  160. llvm::DenseMap<std::pair<DeclContext *, /*Name*/uintptr_t>, ShadowMapEntry>
  161. OverloadMap;
  162. /// If we're potentially referring to a C++ member function, the set
  163. /// of qualifiers applied to the object type.
  164. Qualifiers ObjectTypeQualifiers;
  165. /// The kind of the object expression, for rvalue/lvalue overloads.
  166. ExprValueKind ObjectKind;
  167. /// Whether the \p ObjectTypeQualifiers field is active.
  168. bool HasObjectTypeQualifiers;
  169. /// The selector that we prefer.
  170. Selector PreferredSelector;
  171. /// The completion context in which we are gathering results.
  172. CodeCompletionContext CompletionContext;
  173. /// If we are in an instance method definition, the \@implementation
  174. /// object.
  175. ObjCImplementationDecl *ObjCImplementation;
  176. void AdjustResultPriorityForDecl(Result &R);
  177. void MaybeAddConstructorResults(Result R);
  178. public:
  179. explicit ResultBuilder(Sema &SemaRef, CodeCompletionAllocator &Allocator,
  180. CodeCompletionTUInfo &CCTUInfo,
  181. const CodeCompletionContext &CompletionContext,
  182. LookupFilter Filter = nullptr)
  183. : SemaRef(SemaRef), Allocator(Allocator), CCTUInfo(CCTUInfo),
  184. Filter(Filter), AllowNestedNameSpecifiers(false),
  185. HasObjectTypeQualifiers(false), CompletionContext(CompletionContext),
  186. ObjCImplementation(nullptr) {
  187. // If this is an Objective-C instance method definition, dig out the
  188. // corresponding implementation.
  189. switch (CompletionContext.getKind()) {
  190. case CodeCompletionContext::CCC_Expression:
  191. case CodeCompletionContext::CCC_ObjCMessageReceiver:
  192. case CodeCompletionContext::CCC_ParenthesizedExpression:
  193. case CodeCompletionContext::CCC_Statement:
  194. case CodeCompletionContext::CCC_Recovery:
  195. if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl())
  196. if (Method->isInstanceMethod())
  197. if (ObjCInterfaceDecl *Interface = Method->getClassInterface())
  198. ObjCImplementation = Interface->getImplementation();
  199. break;
  200. default:
  201. break;
  202. }
  203. }
  204. /// Determine the priority for a reference to the given declaration.
  205. unsigned getBasePriority(const NamedDecl *D);
  206. /// Whether we should include code patterns in the completion
  207. /// results.
  208. bool includeCodePatterns() const {
  209. return SemaRef.CodeCompleter &&
  210. SemaRef.CodeCompleter->includeCodePatterns();
  211. }
  212. /// Set the filter used for code-completion results.
  213. void setFilter(LookupFilter Filter) { this->Filter = Filter; }
  214. Result *data() { return Results.empty() ? nullptr : &Results.front(); }
  215. unsigned size() const { return Results.size(); }
  216. bool empty() const { return Results.empty(); }
  217. /// Specify the preferred type.
  218. void setPreferredType(QualType T) {
  219. PreferredType = SemaRef.Context.getCanonicalType(T);
  220. }
  221. /// Set the cv-qualifiers on the object type, for us in filtering
  222. /// calls to member functions.
  223. ///
  224. /// When there are qualifiers in this set, they will be used to filter
  225. /// out member functions that aren't available (because there will be a
  226. /// cv-qualifier mismatch) or prefer functions with an exact qualifier
  227. /// match.
  228. void setObjectTypeQualifiers(Qualifiers Quals, ExprValueKind Kind) {
  229. ObjectTypeQualifiers = Quals;
  230. ObjectKind = Kind;
  231. HasObjectTypeQualifiers = true;
  232. }
  233. /// Set the preferred selector.
  234. ///
  235. /// When an Objective-C method declaration result is added, and that
  236. /// method's selector matches this preferred selector, we give that method
  237. /// a slight priority boost.
  238. void setPreferredSelector(Selector Sel) { PreferredSelector = Sel; }
  239. /// Retrieve the code-completion context for which results are
  240. /// being collected.
  241. const CodeCompletionContext &getCompletionContext() const {
  242. return CompletionContext;
  243. }
  244. /// Specify whether nested-name-specifiers are allowed.
  245. void allowNestedNameSpecifiers(bool Allow = true) {
  246. AllowNestedNameSpecifiers = Allow;
  247. }
  248. /// Return the semantic analysis object for which we are collecting
  249. /// code completion results.
  250. Sema &getSema() const { return SemaRef; }
  251. /// Retrieve the allocator used to allocate code completion strings.
  252. CodeCompletionAllocator &getAllocator() const { return Allocator; }
  253. CodeCompletionTUInfo &getCodeCompletionTUInfo() const { return CCTUInfo; }
  254. /// Determine whether the given declaration is at all interesting
  255. /// as a code-completion result.
  256. ///
  257. /// \param ND the declaration that we are inspecting.
  258. ///
  259. /// \param AsNestedNameSpecifier will be set true if this declaration is
  260. /// only interesting when it is a nested-name-specifier.
  261. bool isInterestingDecl(const NamedDecl *ND,
  262. bool &AsNestedNameSpecifier) const;
  263. /// Check whether the result is hidden by the Hiding declaration.
  264. ///
  265. /// \returns true if the result is hidden and cannot be found, false if
  266. /// the hidden result could still be found. When false, \p R may be
  267. /// modified to describe how the result can be found (e.g., via extra
  268. /// qualification).
  269. bool CheckHiddenResult(Result &R, DeclContext *CurContext,
  270. const NamedDecl *Hiding);
  271. /// Add a new result to this result set (if it isn't already in one
  272. /// of the shadow maps), or replace an existing result (for, e.g., a
  273. /// redeclaration).
  274. ///
  275. /// \param R the result to add (if it is unique).
  276. ///
  277. /// \param CurContext the context in which this result will be named.
  278. void MaybeAddResult(Result R, DeclContext *CurContext = nullptr);
  279. /// Add a new result to this result set, where we already know
  280. /// the hiding declaration (if any).
  281. ///
  282. /// \param R the result to add (if it is unique).
  283. ///
  284. /// \param CurContext the context in which this result will be named.
  285. ///
  286. /// \param Hiding the declaration that hides the result.
  287. ///
  288. /// \param InBaseClass whether the result was found in a base
  289. /// class of the searched context.
  290. void AddResult(Result R, DeclContext *CurContext, NamedDecl *Hiding,
  291. bool InBaseClass);
  292. /// Add a new non-declaration result to this result set.
  293. void AddResult(Result R);
  294. /// Enter into a new scope.
  295. void EnterNewScope();
  296. /// Exit from the current scope.
  297. void ExitScope();
  298. /// Ignore this declaration, if it is seen again.
  299. void Ignore(const Decl *D) { AllDeclsFound.insert(D->getCanonicalDecl()); }
  300. /// Add a visited context.
  301. void addVisitedContext(DeclContext *Ctx) {
  302. CompletionContext.addVisitedContext(Ctx);
  303. }
  304. /// \name Name lookup predicates
  305. ///
  306. /// These predicates can be passed to the name lookup functions to filter the
  307. /// results of name lookup. All of the predicates have the same type, so that
  308. ///
  309. //@{
  310. bool IsOrdinaryName(const NamedDecl *ND) const;
  311. bool IsOrdinaryNonTypeName(const NamedDecl *ND) const;
  312. bool IsIntegralConstantValue(const NamedDecl *ND) const;
  313. bool IsOrdinaryNonValueName(const NamedDecl *ND) const;
  314. bool IsNestedNameSpecifier(const NamedDecl *ND) const;
  315. bool IsEnum(const NamedDecl *ND) const;
  316. bool IsClassOrStruct(const NamedDecl *ND) const;
  317. bool IsUnion(const NamedDecl *ND) const;
  318. bool IsNamespace(const NamedDecl *ND) const;
  319. bool IsNamespaceOrAlias(const NamedDecl *ND) const;
  320. bool IsType(const NamedDecl *ND) const;
  321. bool IsMember(const NamedDecl *ND) const;
  322. bool IsObjCIvar(const NamedDecl *ND) const;
  323. bool IsObjCMessageReceiver(const NamedDecl *ND) const;
  324. bool IsObjCMessageReceiverOrLambdaCapture(const NamedDecl *ND) const;
  325. bool IsObjCCollection(const NamedDecl *ND) const;
  326. bool IsImpossibleToSatisfy(const NamedDecl *ND) const;
  327. //@}
  328. };
  329. } // namespace
  330. void PreferredTypeBuilder::enterReturn(Sema &S, SourceLocation Tok) {
  331. if (!Enabled)
  332. return;
  333. if (isa<BlockDecl>(S.CurContext)) {
  334. if (sema::BlockScopeInfo *BSI = S.getCurBlock()) {
  335. ComputeType = nullptr;
  336. Type = BSI->ReturnType;
  337. ExpectedLoc = Tok;
  338. }
  339. } else if (const auto *Function = dyn_cast<FunctionDecl>(S.CurContext)) {
  340. ComputeType = nullptr;
  341. Type = Function->getReturnType();
  342. ExpectedLoc = Tok;
  343. } else if (const auto *Method = dyn_cast<ObjCMethodDecl>(S.CurContext)) {
  344. ComputeType = nullptr;
  345. Type = Method->getReturnType();
  346. ExpectedLoc = Tok;
  347. }
  348. }
  349. void PreferredTypeBuilder::enterVariableInit(SourceLocation Tok, Decl *D) {
  350. if (!Enabled)
  351. return;
  352. auto *VD = llvm::dyn_cast_or_null<ValueDecl>(D);
  353. ComputeType = nullptr;
  354. Type = VD ? VD->getType() : QualType();
  355. ExpectedLoc = Tok;
  356. }
  357. static QualType getDesignatedType(QualType BaseType, const Designation &Desig);
  358. void PreferredTypeBuilder::enterDesignatedInitializer(SourceLocation Tok,
  359. QualType BaseType,
  360. const Designation &D) {
  361. if (!Enabled)
  362. return;
  363. ComputeType = nullptr;
  364. Type = getDesignatedType(BaseType, D);
  365. ExpectedLoc = Tok;
  366. }
  367. void PreferredTypeBuilder::enterFunctionArgument(
  368. SourceLocation Tok, llvm::function_ref<QualType()> ComputeType) {
  369. if (!Enabled)
  370. return;
  371. this->ComputeType = ComputeType;
  372. Type = QualType();
  373. ExpectedLoc = Tok;
  374. }
  375. void PreferredTypeBuilder::enterParenExpr(SourceLocation Tok,
  376. SourceLocation LParLoc) {
  377. if (!Enabled)
  378. return;
  379. // expected type for parenthesized expression does not change.
  380. if (ExpectedLoc == LParLoc)
  381. ExpectedLoc = Tok;
  382. }
  383. static QualType getPreferredTypeOfBinaryRHS(Sema &S, Expr *LHS,
  384. tok::TokenKind Op) {
  385. if (!LHS)
  386. return QualType();
  387. QualType LHSType = LHS->getType();
  388. if (LHSType->isPointerType()) {
  389. if (Op == tok::plus || Op == tok::plusequal || Op == tok::minusequal)
  390. return S.getASTContext().getPointerDiffType();
  391. // Pointer difference is more common than subtracting an int from a pointer.
  392. if (Op == tok::minus)
  393. return LHSType;
  394. }
  395. switch (Op) {
  396. // No way to infer the type of RHS from LHS.
  397. case tok::comma:
  398. return QualType();
  399. // Prefer the type of the left operand for all of these.
  400. // Arithmetic operations.
  401. case tok::plus:
  402. case tok::plusequal:
  403. case tok::minus:
  404. case tok::minusequal:
  405. case tok::percent:
  406. case tok::percentequal:
  407. case tok::slash:
  408. case tok::slashequal:
  409. case tok::star:
  410. case tok::starequal:
  411. // Assignment.
  412. case tok::equal:
  413. // Comparison operators.
  414. case tok::equalequal:
  415. case tok::exclaimequal:
  416. case tok::less:
  417. case tok::lessequal:
  418. case tok::greater:
  419. case tok::greaterequal:
  420. case tok::spaceship:
  421. return LHS->getType();
  422. // Binary shifts are often overloaded, so don't try to guess those.
  423. case tok::greatergreater:
  424. case tok::greatergreaterequal:
  425. case tok::lessless:
  426. case tok::lesslessequal:
  427. if (LHSType->isIntegralOrEnumerationType())
  428. return S.getASTContext().IntTy;
  429. return QualType();
  430. // Logical operators, assume we want bool.
  431. case tok::ampamp:
  432. case tok::pipepipe:
  433. case tok::caretcaret:
  434. return S.getASTContext().BoolTy;
  435. // Operators often used for bit manipulation are typically used with the type
  436. // of the left argument.
  437. case tok::pipe:
  438. case tok::pipeequal:
  439. case tok::caret:
  440. case tok::caretequal:
  441. case tok::amp:
  442. case tok::ampequal:
  443. if (LHSType->isIntegralOrEnumerationType())
  444. return LHSType;
  445. return QualType();
  446. // RHS should be a pointer to a member of the 'LHS' type, but we can't give
  447. // any particular type here.
  448. case tok::periodstar:
  449. case tok::arrowstar:
  450. return QualType();
  451. default:
  452. // FIXME(ibiryukov): handle the missing op, re-add the assertion.
  453. // assert(false && "unhandled binary op");
  454. return QualType();
  455. }
  456. }
  457. /// Get preferred type for an argument of an unary expression. \p ContextType is
  458. /// preferred type of the whole unary expression.
  459. static QualType getPreferredTypeOfUnaryArg(Sema &S, QualType ContextType,
  460. tok::TokenKind Op) {
  461. switch (Op) {
  462. case tok::exclaim:
  463. return S.getASTContext().BoolTy;
  464. case tok::amp:
  465. if (!ContextType.isNull() && ContextType->isPointerType())
  466. return ContextType->getPointeeType();
  467. return QualType();
  468. case tok::star:
  469. if (ContextType.isNull())
  470. return QualType();
  471. return S.getASTContext().getPointerType(ContextType.getNonReferenceType());
  472. case tok::plus:
  473. case tok::minus:
  474. case tok::tilde:
  475. case tok::minusminus:
  476. case tok::plusplus:
  477. if (ContextType.isNull())
  478. return S.getASTContext().IntTy;
  479. // leave as is, these operators typically return the same type.
  480. return ContextType;
  481. case tok::kw___real:
  482. case tok::kw___imag:
  483. return QualType();
  484. default:
  485. assert(false && "unhandled unary op");
  486. return QualType();
  487. }
  488. }
  489. void PreferredTypeBuilder::enterBinary(Sema &S, SourceLocation Tok, Expr *LHS,
  490. tok::TokenKind Op) {
  491. if (!Enabled)
  492. return;
  493. ComputeType = nullptr;
  494. Type = getPreferredTypeOfBinaryRHS(S, LHS, Op);
  495. ExpectedLoc = Tok;
  496. }
  497. void PreferredTypeBuilder::enterMemAccess(Sema &S, SourceLocation Tok,
  498. Expr *Base) {
  499. if (!Enabled || !Base)
  500. return;
  501. // Do we have expected type for Base?
  502. if (ExpectedLoc != Base->getBeginLoc())
  503. return;
  504. // Keep the expected type, only update the location.
  505. ExpectedLoc = Tok;
  506. }
  507. void PreferredTypeBuilder::enterUnary(Sema &S, SourceLocation Tok,
  508. tok::TokenKind OpKind,
  509. SourceLocation OpLoc) {
  510. if (!Enabled)
  511. return;
  512. ComputeType = nullptr;
  513. Type = getPreferredTypeOfUnaryArg(S, this->get(OpLoc), OpKind);
  514. ExpectedLoc = Tok;
  515. }
  516. void PreferredTypeBuilder::enterSubscript(Sema &S, SourceLocation Tok,
  517. Expr *LHS) {
  518. if (!Enabled)
  519. return;
  520. ComputeType = nullptr;
  521. Type = S.getASTContext().IntTy;
  522. ExpectedLoc = Tok;
  523. }
  524. void PreferredTypeBuilder::enterTypeCast(SourceLocation Tok,
  525. QualType CastType) {
  526. if (!Enabled)
  527. return;
  528. ComputeType = nullptr;
  529. Type = !CastType.isNull() ? CastType.getCanonicalType() : QualType();
  530. ExpectedLoc = Tok;
  531. }
  532. void PreferredTypeBuilder::enterCondition(Sema &S, SourceLocation Tok) {
  533. if (!Enabled)
  534. return;
  535. ComputeType = nullptr;
  536. Type = S.getASTContext().BoolTy;
  537. ExpectedLoc = Tok;
  538. }
  539. class ResultBuilder::ShadowMapEntry::iterator {
  540. llvm::PointerUnion<const NamedDecl *, const DeclIndexPair *> DeclOrIterator;
  541. unsigned SingleDeclIndex;
  542. public:
  543. typedef DeclIndexPair value_type;
  544. typedef value_type reference;
  545. typedef std::ptrdiff_t difference_type;
  546. typedef std::input_iterator_tag iterator_category;
  547. class pointer {
  548. DeclIndexPair Value;
  549. public:
  550. pointer(const DeclIndexPair &Value) : Value(Value) {}
  551. const DeclIndexPair *operator->() const { return &Value; }
  552. };
  553. iterator() : DeclOrIterator((NamedDecl *)nullptr), SingleDeclIndex(0) {}
  554. iterator(const NamedDecl *SingleDecl, unsigned Index)
  555. : DeclOrIterator(SingleDecl), SingleDeclIndex(Index) {}
  556. iterator(const DeclIndexPair *Iterator)
  557. : DeclOrIterator(Iterator), SingleDeclIndex(0) {}
  558. iterator &operator++() {
  559. if (DeclOrIterator.is<const NamedDecl *>()) {
  560. DeclOrIterator = (NamedDecl *)nullptr;
  561. SingleDeclIndex = 0;
  562. return *this;
  563. }
  564. const DeclIndexPair *I = DeclOrIterator.get<const DeclIndexPair *>();
  565. ++I;
  566. DeclOrIterator = I;
  567. return *this;
  568. }
  569. /*iterator operator++(int) {
  570. iterator tmp(*this);
  571. ++(*this);
  572. return tmp;
  573. }*/
  574. reference operator*() const {
  575. if (const NamedDecl *ND = DeclOrIterator.dyn_cast<const NamedDecl *>())
  576. return reference(ND, SingleDeclIndex);
  577. return *DeclOrIterator.get<const DeclIndexPair *>();
  578. }
  579. pointer operator->() const { return pointer(**this); }
  580. friend bool operator==(const iterator &X, const iterator &Y) {
  581. return X.DeclOrIterator.getOpaqueValue() ==
  582. Y.DeclOrIterator.getOpaqueValue() &&
  583. X.SingleDeclIndex == Y.SingleDeclIndex;
  584. }
  585. friend bool operator!=(const iterator &X, const iterator &Y) {
  586. return !(X == Y);
  587. }
  588. };
  589. ResultBuilder::ShadowMapEntry::iterator
  590. ResultBuilder::ShadowMapEntry::begin() const {
  591. if (DeclOrVector.isNull())
  592. return iterator();
  593. if (const NamedDecl *ND = DeclOrVector.dyn_cast<const NamedDecl *>())
  594. return iterator(ND, SingleDeclIndex);
  595. return iterator(DeclOrVector.get<DeclIndexPairVector *>()->begin());
  596. }
  597. ResultBuilder::ShadowMapEntry::iterator
  598. ResultBuilder::ShadowMapEntry::end() const {
  599. if (DeclOrVector.is<const NamedDecl *>() || DeclOrVector.isNull())
  600. return iterator();
  601. return iterator(DeclOrVector.get<DeclIndexPairVector *>()->end());
  602. }
  603. /// Compute the qualification required to get from the current context
  604. /// (\p CurContext) to the target context (\p TargetContext).
  605. ///
  606. /// \param Context the AST context in which the qualification will be used.
  607. ///
  608. /// \param CurContext the context where an entity is being named, which is
  609. /// typically based on the current scope.
  610. ///
  611. /// \param TargetContext the context in which the named entity actually
  612. /// resides.
  613. ///
  614. /// \returns a nested name specifier that refers into the target context, or
  615. /// NULL if no qualification is needed.
  616. static NestedNameSpecifier *
  617. getRequiredQualification(ASTContext &Context, const DeclContext *CurContext,
  618. const DeclContext *TargetContext) {
  619. SmallVector<const DeclContext *, 4> TargetParents;
  620. for (const DeclContext *CommonAncestor = TargetContext;
  621. CommonAncestor && !CommonAncestor->Encloses(CurContext);
  622. CommonAncestor = CommonAncestor->getLookupParent()) {
  623. if (CommonAncestor->isTransparentContext() ||
  624. CommonAncestor->isFunctionOrMethod())
  625. continue;
  626. TargetParents.push_back(CommonAncestor);
  627. }
  628. NestedNameSpecifier *Result = nullptr;
  629. while (!TargetParents.empty()) {
  630. const DeclContext *Parent = TargetParents.pop_back_val();
  631. if (const auto *Namespace = dyn_cast<NamespaceDecl>(Parent)) {
  632. if (!Namespace->getIdentifier())
  633. continue;
  634. Result = NestedNameSpecifier::Create(Context, Result, Namespace);
  635. } else if (const auto *TD = dyn_cast<TagDecl>(Parent))
  636. Result = NestedNameSpecifier::Create(
  637. Context, Result, false, Context.getTypeDeclType(TD).getTypePtr());
  638. }
  639. return Result;
  640. }
  641. // Some declarations have reserved names that we don't want to ever show.
  642. // Filter out names reserved for the implementation if they come from a
  643. // system header.
  644. static bool shouldIgnoreDueToReservedName(const NamedDecl *ND, Sema &SemaRef) {
  645. ReservedIdentifierStatus Status = ND->isReserved(SemaRef.getLangOpts());
  646. // Ignore reserved names for compiler provided decls.
  647. if (isReservedInAllContexts(Status) && ND->getLocation().isInvalid())
  648. return true;
  649. // For system headers ignore only double-underscore names.
  650. // This allows for system headers providing private symbols with a single
  651. // underscore.
  652. if (Status == ReservedIdentifierStatus::StartsWithDoubleUnderscore &&
  653. SemaRef.SourceMgr.isInSystemHeader(
  654. SemaRef.SourceMgr.getSpellingLoc(ND->getLocation())))
  655. return true;
  656. return false;
  657. }
  658. bool ResultBuilder::isInterestingDecl(const NamedDecl *ND,
  659. bool &AsNestedNameSpecifier) const {
  660. AsNestedNameSpecifier = false;
  661. auto *Named = ND;
  662. ND = ND->getUnderlyingDecl();
  663. // Skip unnamed entities.
  664. if (!ND->getDeclName())
  665. return false;
  666. // Friend declarations and declarations introduced due to friends are never
  667. // added as results.
  668. if (ND->getFriendObjectKind() == Decl::FOK_Undeclared)
  669. return false;
  670. // Class template (partial) specializations are never added as results.
  671. if (isa<ClassTemplateSpecializationDecl>(ND) ||
  672. isa<ClassTemplatePartialSpecializationDecl>(ND))
  673. return false;
  674. // Using declarations themselves are never added as results.
  675. if (isa<UsingDecl>(ND))
  676. return false;
  677. if (shouldIgnoreDueToReservedName(ND, SemaRef))
  678. return false;
  679. if (Filter == &ResultBuilder::IsNestedNameSpecifier ||
  680. (isa<NamespaceDecl>(ND) && Filter != &ResultBuilder::IsNamespace &&
  681. Filter != &ResultBuilder::IsNamespaceOrAlias && Filter != nullptr))
  682. AsNestedNameSpecifier = true;
  683. // Filter out any unwanted results.
  684. if (Filter && !(this->*Filter)(Named)) {
  685. // Check whether it is interesting as a nested-name-specifier.
  686. if (AllowNestedNameSpecifiers && SemaRef.getLangOpts().CPlusPlus &&
  687. IsNestedNameSpecifier(ND) &&
  688. (Filter != &ResultBuilder::IsMember ||
  689. (isa<CXXRecordDecl>(ND) &&
  690. cast<CXXRecordDecl>(ND)->isInjectedClassName()))) {
  691. AsNestedNameSpecifier = true;
  692. return true;
  693. }
  694. return false;
  695. }
  696. // ... then it must be interesting!
  697. return true;
  698. }
  699. bool ResultBuilder::CheckHiddenResult(Result &R, DeclContext *CurContext,
  700. const NamedDecl *Hiding) {
  701. // In C, there is no way to refer to a hidden name.
  702. // FIXME: This isn't true; we can find a tag name hidden by an ordinary
  703. // name if we introduce the tag type.
  704. if (!SemaRef.getLangOpts().CPlusPlus)
  705. return true;
  706. const DeclContext *HiddenCtx =
  707. R.Declaration->getDeclContext()->getRedeclContext();
  708. // There is no way to qualify a name declared in a function or method.
  709. if (HiddenCtx->isFunctionOrMethod())
  710. return true;
  711. if (HiddenCtx == Hiding->getDeclContext()->getRedeclContext())
  712. return true;
  713. // We can refer to the result with the appropriate qualification. Do it.
  714. R.Hidden = true;
  715. R.QualifierIsInformative = false;
  716. if (!R.Qualifier)
  717. R.Qualifier = getRequiredQualification(SemaRef.Context, CurContext,
  718. R.Declaration->getDeclContext());
  719. return false;
  720. }
  721. /// A simplified classification of types used to determine whether two
  722. /// types are "similar enough" when adjusting priorities.
  723. SimplifiedTypeClass clang::getSimplifiedTypeClass(CanQualType T) {
  724. switch (T->getTypeClass()) {
  725. case Type::Builtin:
  726. switch (cast<BuiltinType>(T)->getKind()) {
  727. case BuiltinType::Void:
  728. return STC_Void;
  729. case BuiltinType::NullPtr:
  730. return STC_Pointer;
  731. case BuiltinType::Overload:
  732. case BuiltinType::Dependent:
  733. return STC_Other;
  734. case BuiltinType::ObjCId:
  735. case BuiltinType::ObjCClass:
  736. case BuiltinType::ObjCSel:
  737. return STC_ObjectiveC;
  738. default:
  739. return STC_Arithmetic;
  740. }
  741. case Type::Complex:
  742. return STC_Arithmetic;
  743. case Type::Pointer:
  744. return STC_Pointer;
  745. case Type::BlockPointer:
  746. return STC_Block;
  747. case Type::LValueReference:
  748. case Type::RValueReference:
  749. return getSimplifiedTypeClass(T->getAs<ReferenceType>()->getPointeeType());
  750. case Type::ConstantArray:
  751. case Type::IncompleteArray:
  752. case Type::VariableArray:
  753. case Type::DependentSizedArray:
  754. return STC_Array;
  755. case Type::DependentSizedExtVector:
  756. case Type::Vector:
  757. case Type::ExtVector:
  758. return STC_Arithmetic;
  759. case Type::FunctionProto:
  760. case Type::FunctionNoProto:
  761. return STC_Function;
  762. case Type::Record:
  763. return STC_Record;
  764. case Type::Enum:
  765. return STC_Arithmetic;
  766. case Type::ObjCObject:
  767. case Type::ObjCInterface:
  768. case Type::ObjCObjectPointer:
  769. return STC_ObjectiveC;
  770. default:
  771. return STC_Other;
  772. }
  773. }
  774. /// Get the type that a given expression will have if this declaration
  775. /// is used as an expression in its "typical" code-completion form.
  776. QualType clang::getDeclUsageType(ASTContext &C, const NamedDecl *ND) {
  777. ND = ND->getUnderlyingDecl();
  778. if (const auto *Type = dyn_cast<TypeDecl>(ND))
  779. return C.getTypeDeclType(Type);
  780. if (const auto *Iface = dyn_cast<ObjCInterfaceDecl>(ND))
  781. return C.getObjCInterfaceType(Iface);
  782. QualType T;
  783. if (const FunctionDecl *Function = ND->getAsFunction())
  784. T = Function->getCallResultType();
  785. else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND))
  786. T = Method->getSendResultType();
  787. else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND))
  788. T = C.getTypeDeclType(cast<EnumDecl>(Enumerator->getDeclContext()));
  789. else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND))
  790. T = Property->getType();
  791. else if (const auto *Value = dyn_cast<ValueDecl>(ND))
  792. T = Value->getType();
  793. if (T.isNull())
  794. return QualType();
  795. // Dig through references, function pointers, and block pointers to
  796. // get down to the likely type of an expression when the entity is
  797. // used.
  798. do {
  799. if (const auto *Ref = T->getAs<ReferenceType>()) {
  800. T = Ref->getPointeeType();
  801. continue;
  802. }
  803. if (const auto *Pointer = T->getAs<PointerType>()) {
  804. if (Pointer->getPointeeType()->isFunctionType()) {
  805. T = Pointer->getPointeeType();
  806. continue;
  807. }
  808. break;
  809. }
  810. if (const auto *Block = T->getAs<BlockPointerType>()) {
  811. T = Block->getPointeeType();
  812. continue;
  813. }
  814. if (const auto *Function = T->getAs<FunctionType>()) {
  815. T = Function->getReturnType();
  816. continue;
  817. }
  818. break;
  819. } while (true);
  820. return T;
  821. }
  822. unsigned ResultBuilder::getBasePriority(const NamedDecl *ND) {
  823. if (!ND)
  824. return CCP_Unlikely;
  825. // Context-based decisions.
  826. const DeclContext *LexicalDC = ND->getLexicalDeclContext();
  827. if (LexicalDC->isFunctionOrMethod()) {
  828. // _cmd is relatively rare
  829. if (const auto *ImplicitParam = dyn_cast<ImplicitParamDecl>(ND))
  830. if (ImplicitParam->getIdentifier() &&
  831. ImplicitParam->getIdentifier()->isStr("_cmd"))
  832. return CCP_ObjC_cmd;
  833. return CCP_LocalDeclaration;
  834. }
  835. const DeclContext *DC = ND->getDeclContext()->getRedeclContext();
  836. if (DC->isRecord() || isa<ObjCContainerDecl>(DC)) {
  837. // Explicit destructor calls are very rare.
  838. if (isa<CXXDestructorDecl>(ND))
  839. return CCP_Unlikely;
  840. // Explicit operator and conversion function calls are also very rare.
  841. auto DeclNameKind = ND->getDeclName().getNameKind();
  842. if (DeclNameKind == DeclarationName::CXXOperatorName ||
  843. DeclNameKind == DeclarationName::CXXLiteralOperatorName ||
  844. DeclNameKind == DeclarationName::CXXConversionFunctionName)
  845. return CCP_Unlikely;
  846. return CCP_MemberDeclaration;
  847. }
  848. // Content-based decisions.
  849. if (isa<EnumConstantDecl>(ND))
  850. return CCP_Constant;
  851. // Use CCP_Type for type declarations unless we're in a statement, Objective-C
  852. // message receiver, or parenthesized expression context. There, it's as
  853. // likely that the user will want to write a type as other declarations.
  854. if ((isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) &&
  855. !(CompletionContext.getKind() == CodeCompletionContext::CCC_Statement ||
  856. CompletionContext.getKind() ==
  857. CodeCompletionContext::CCC_ObjCMessageReceiver ||
  858. CompletionContext.getKind() ==
  859. CodeCompletionContext::CCC_ParenthesizedExpression))
  860. return CCP_Type;
  861. return CCP_Declaration;
  862. }
  863. void ResultBuilder::AdjustResultPriorityForDecl(Result &R) {
  864. // If this is an Objective-C method declaration whose selector matches our
  865. // preferred selector, give it a priority boost.
  866. if (!PreferredSelector.isNull())
  867. if (const auto *Method = dyn_cast<ObjCMethodDecl>(R.Declaration))
  868. if (PreferredSelector == Method->getSelector())
  869. R.Priority += CCD_SelectorMatch;
  870. // If we have a preferred type, adjust the priority for results with exactly-
  871. // matching or nearly-matching types.
  872. if (!PreferredType.isNull()) {
  873. QualType T = getDeclUsageType(SemaRef.Context, R.Declaration);
  874. if (!T.isNull()) {
  875. CanQualType TC = SemaRef.Context.getCanonicalType(T);
  876. // Check for exactly-matching types (modulo qualifiers).
  877. if (SemaRef.Context.hasSameUnqualifiedType(PreferredType, TC))
  878. R.Priority /= CCF_ExactTypeMatch;
  879. // Check for nearly-matching types, based on classification of each.
  880. else if ((getSimplifiedTypeClass(PreferredType) ==
  881. getSimplifiedTypeClass(TC)) &&
  882. !(PreferredType->isEnumeralType() && TC->isEnumeralType()))
  883. R.Priority /= CCF_SimilarTypeMatch;
  884. }
  885. }
  886. }
  887. static DeclContext::lookup_result getConstructors(ASTContext &Context,
  888. const CXXRecordDecl *Record) {
  889. QualType RecordTy = Context.getTypeDeclType(Record);
  890. DeclarationName ConstructorName =
  891. Context.DeclarationNames.getCXXConstructorName(
  892. Context.getCanonicalType(RecordTy));
  893. return Record->lookup(ConstructorName);
  894. }
  895. void ResultBuilder::MaybeAddConstructorResults(Result R) {
  896. if (!SemaRef.getLangOpts().CPlusPlus || !R.Declaration ||
  897. !CompletionContext.wantConstructorResults())
  898. return;
  899. const NamedDecl *D = R.Declaration;
  900. const CXXRecordDecl *Record = nullptr;
  901. if (const ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D))
  902. Record = ClassTemplate->getTemplatedDecl();
  903. else if ((Record = dyn_cast<CXXRecordDecl>(D))) {
  904. // Skip specializations and partial specializations.
  905. if (isa<ClassTemplateSpecializationDecl>(Record))
  906. return;
  907. } else {
  908. // There are no constructors here.
  909. return;
  910. }
  911. Record = Record->getDefinition();
  912. if (!Record)
  913. return;
  914. for (NamedDecl *Ctor : getConstructors(SemaRef.Context, Record)) {
  915. R.Declaration = Ctor;
  916. R.CursorKind = getCursorKindForDecl(R.Declaration);
  917. Results.push_back(R);
  918. }
  919. }
  920. static bool isConstructor(const Decl *ND) {
  921. if (const auto *Tmpl = dyn_cast<FunctionTemplateDecl>(ND))
  922. ND = Tmpl->getTemplatedDecl();
  923. return isa<CXXConstructorDecl>(ND);
  924. }
  925. void ResultBuilder::MaybeAddResult(Result R, DeclContext *CurContext) {
  926. assert(!ShadowMaps.empty() && "Must enter into a results scope");
  927. if (R.Kind != Result::RK_Declaration) {
  928. // For non-declaration results, just add the result.
  929. Results.push_back(R);
  930. return;
  931. }
  932. // Look through using declarations.
  933. if (const UsingShadowDecl *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
  934. CodeCompletionResult Result(Using->getTargetDecl(),
  935. getBasePriority(Using->getTargetDecl()),
  936. R.Qualifier);
  937. Result.ShadowDecl = Using;
  938. MaybeAddResult(Result, CurContext);
  939. return;
  940. }
  941. const Decl *CanonDecl = R.Declaration->getCanonicalDecl();
  942. unsigned IDNS = CanonDecl->getIdentifierNamespace();
  943. bool AsNestedNameSpecifier = false;
  944. if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
  945. return;
  946. // C++ constructors are never found by name lookup.
  947. if (isConstructor(R.Declaration))
  948. return;
  949. ShadowMap &SMap = ShadowMaps.back();
  950. ShadowMapEntry::iterator I, IEnd;
  951. ShadowMap::iterator NamePos = SMap.find(R.Declaration->getDeclName());
  952. if (NamePos != SMap.end()) {
  953. I = NamePos->second.begin();
  954. IEnd = NamePos->second.end();
  955. }
  956. for (; I != IEnd; ++I) {
  957. const NamedDecl *ND = I->first;
  958. unsigned Index = I->second;
  959. if (ND->getCanonicalDecl() == CanonDecl) {
  960. // This is a redeclaration. Always pick the newer declaration.
  961. Results[Index].Declaration = R.Declaration;
  962. // We're done.
  963. return;
  964. }
  965. }
  966. // This is a new declaration in this scope. However, check whether this
  967. // declaration name is hidden by a similarly-named declaration in an outer
  968. // scope.
  969. std::list<ShadowMap>::iterator SM, SMEnd = ShadowMaps.end();
  970. --SMEnd;
  971. for (SM = ShadowMaps.begin(); SM != SMEnd; ++SM) {
  972. ShadowMapEntry::iterator I, IEnd;
  973. ShadowMap::iterator NamePos = SM->find(R.Declaration->getDeclName());
  974. if (NamePos != SM->end()) {
  975. I = NamePos->second.begin();
  976. IEnd = NamePos->second.end();
  977. }
  978. for (; I != IEnd; ++I) {
  979. // A tag declaration does not hide a non-tag declaration.
  980. if (I->first->hasTagIdentifierNamespace() &&
  981. (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
  982. Decl::IDNS_LocalExtern | Decl::IDNS_ObjCProtocol)))
  983. continue;
  984. // Protocols are in distinct namespaces from everything else.
  985. if (((I->first->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) ||
  986. (IDNS & Decl::IDNS_ObjCProtocol)) &&
  987. I->first->getIdentifierNamespace() != IDNS)
  988. continue;
  989. // The newly-added result is hidden by an entry in the shadow map.
  990. if (CheckHiddenResult(R, CurContext, I->first))
  991. return;
  992. break;
  993. }
  994. }
  995. // Make sure that any given declaration only shows up in the result set once.
  996. if (!AllDeclsFound.insert(CanonDecl).second)
  997. return;
  998. // If the filter is for nested-name-specifiers, then this result starts a
  999. // nested-name-specifier.
  1000. if (AsNestedNameSpecifier) {
  1001. R.StartsNestedNameSpecifier = true;
  1002. R.Priority = CCP_NestedNameSpecifier;
  1003. } else
  1004. AdjustResultPriorityForDecl(R);
  1005. // If this result is supposed to have an informative qualifier, add one.
  1006. if (R.QualifierIsInformative && !R.Qualifier &&
  1007. !R.StartsNestedNameSpecifier) {
  1008. const DeclContext *Ctx = R.Declaration->getDeclContext();
  1009. if (const NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(Ctx))
  1010. R.Qualifier =
  1011. NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
  1012. else if (const TagDecl *Tag = dyn_cast<TagDecl>(Ctx))
  1013. R.Qualifier = NestedNameSpecifier::Create(
  1014. SemaRef.Context, nullptr, false,
  1015. SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
  1016. else
  1017. R.QualifierIsInformative = false;
  1018. }
  1019. // Insert this result into the set of results and into the current shadow
  1020. // map.
  1021. SMap[R.Declaration->getDeclName()].Add(R.Declaration, Results.size());
  1022. Results.push_back(R);
  1023. if (!AsNestedNameSpecifier)
  1024. MaybeAddConstructorResults(R);
  1025. }
  1026. static void setInBaseClass(ResultBuilder::Result &R) {
  1027. R.Priority += CCD_InBaseClass;
  1028. R.InBaseClass = true;
  1029. }
  1030. enum class OverloadCompare { BothViable, Dominates, Dominated };
  1031. // Will Candidate ever be called on the object, when overloaded with Incumbent?
  1032. // Returns Dominates if Candidate is always called, Dominated if Incumbent is
  1033. // always called, BothViable if either may be called dependending on arguments.
  1034. // Precondition: must actually be overloads!
  1035. static OverloadCompare compareOverloads(const CXXMethodDecl &Candidate,
  1036. const CXXMethodDecl &Incumbent,
  1037. const Qualifiers &ObjectQuals,
  1038. ExprValueKind ObjectKind) {
  1039. // Base/derived shadowing is handled elsewhere.
  1040. if (Candidate.getDeclContext() != Incumbent.getDeclContext())
  1041. return OverloadCompare::BothViable;
  1042. if (Candidate.isVariadic() != Incumbent.isVariadic() ||
  1043. Candidate.getNumParams() != Incumbent.getNumParams() ||
  1044. Candidate.getMinRequiredArguments() !=
  1045. Incumbent.getMinRequiredArguments())
  1046. return OverloadCompare::BothViable;
  1047. for (unsigned I = 0, E = Candidate.getNumParams(); I != E; ++I)
  1048. if (Candidate.parameters()[I]->getType().getCanonicalType() !=
  1049. Incumbent.parameters()[I]->getType().getCanonicalType())
  1050. return OverloadCompare::BothViable;
  1051. if (!llvm::empty(Candidate.specific_attrs<EnableIfAttr>()) ||
  1052. !llvm::empty(Incumbent.specific_attrs<EnableIfAttr>()))
  1053. return OverloadCompare::BothViable;
  1054. // At this point, we know calls can't pick one or the other based on
  1055. // arguments, so one of the two must win. (Or both fail, handled elsewhere).
  1056. RefQualifierKind CandidateRef = Candidate.getRefQualifier();
  1057. RefQualifierKind IncumbentRef = Incumbent.getRefQualifier();
  1058. if (CandidateRef != IncumbentRef) {
  1059. // If the object kind is LValue/RValue, there's one acceptable ref-qualifier
  1060. // and it can't be mixed with ref-unqualified overloads (in valid code).
  1061. // For xvalue objects, we prefer the rvalue overload even if we have to
  1062. // add qualifiers (which is rare, because const&& is rare).
  1063. if (ObjectKind == clang::VK_XValue)
  1064. return CandidateRef == RQ_RValue ? OverloadCompare::Dominates
  1065. : OverloadCompare::Dominated;
  1066. }
  1067. // Now the ref qualifiers are the same (or we're in some invalid state).
  1068. // So make some decision based on the qualifiers.
  1069. Qualifiers CandidateQual = Candidate.getMethodQualifiers();
  1070. Qualifiers IncumbentQual = Incumbent.getMethodQualifiers();
  1071. bool CandidateSuperset = CandidateQual.compatiblyIncludes(IncumbentQual);
  1072. bool IncumbentSuperset = IncumbentQual.compatiblyIncludes(CandidateQual);
  1073. if (CandidateSuperset == IncumbentSuperset)
  1074. return OverloadCompare::BothViable;
  1075. return IncumbentSuperset ? OverloadCompare::Dominates
  1076. : OverloadCompare::Dominated;
  1077. }
  1078. void ResultBuilder::AddResult(Result R, DeclContext *CurContext,
  1079. NamedDecl *Hiding, bool InBaseClass = false) {
  1080. if (R.Kind != Result::RK_Declaration) {
  1081. // For non-declaration results, just add the result.
  1082. Results.push_back(R);
  1083. return;
  1084. }
  1085. // Look through using declarations.
  1086. if (const auto *Using = dyn_cast<UsingShadowDecl>(R.Declaration)) {
  1087. CodeCompletionResult Result(Using->getTargetDecl(),
  1088. getBasePriority(Using->getTargetDecl()),
  1089. R.Qualifier);
  1090. Result.ShadowDecl = Using;
  1091. AddResult(Result, CurContext, Hiding);
  1092. return;
  1093. }
  1094. bool AsNestedNameSpecifier = false;
  1095. if (!isInterestingDecl(R.Declaration, AsNestedNameSpecifier))
  1096. return;
  1097. // C++ constructors are never found by name lookup.
  1098. if (isConstructor(R.Declaration))
  1099. return;
  1100. if (Hiding && CheckHiddenResult(R, CurContext, Hiding))
  1101. return;
  1102. // Make sure that any given declaration only shows up in the result set once.
  1103. if (!AllDeclsFound.insert(R.Declaration->getCanonicalDecl()).second)
  1104. return;
  1105. // If the filter is for nested-name-specifiers, then this result starts a
  1106. // nested-name-specifier.
  1107. if (AsNestedNameSpecifier) {
  1108. R.StartsNestedNameSpecifier = true;
  1109. R.Priority = CCP_NestedNameSpecifier;
  1110. } else if (Filter == &ResultBuilder::IsMember && !R.Qualifier &&
  1111. InBaseClass &&
  1112. isa<CXXRecordDecl>(
  1113. R.Declaration->getDeclContext()->getRedeclContext()))
  1114. R.QualifierIsInformative = true;
  1115. // If this result is supposed to have an informative qualifier, add one.
  1116. if (R.QualifierIsInformative && !R.Qualifier &&
  1117. !R.StartsNestedNameSpecifier) {
  1118. const DeclContext *Ctx = R.Declaration->getDeclContext();
  1119. if (const auto *Namespace = dyn_cast<NamespaceDecl>(Ctx))
  1120. R.Qualifier =
  1121. NestedNameSpecifier::Create(SemaRef.Context, nullptr, Namespace);
  1122. else if (const auto *Tag = dyn_cast<TagDecl>(Ctx))
  1123. R.Qualifier = NestedNameSpecifier::Create(
  1124. SemaRef.Context, nullptr, false,
  1125. SemaRef.Context.getTypeDeclType(Tag).getTypePtr());
  1126. else
  1127. R.QualifierIsInformative = false;
  1128. }
  1129. // Adjust the priority if this result comes from a base class.
  1130. if (InBaseClass)
  1131. setInBaseClass(R);
  1132. AdjustResultPriorityForDecl(R);
  1133. if (HasObjectTypeQualifiers)
  1134. if (const auto *Method = dyn_cast<CXXMethodDecl>(R.Declaration))
  1135. if (Method->isInstance()) {
  1136. Qualifiers MethodQuals = Method->getMethodQualifiers();
  1137. if (ObjectTypeQualifiers == MethodQuals)
  1138. R.Priority += CCD_ObjectQualifierMatch;
  1139. else if (ObjectTypeQualifiers - MethodQuals) {
  1140. // The method cannot be invoked, because doing so would drop
  1141. // qualifiers.
  1142. return;
  1143. }
  1144. // Detect cases where a ref-qualified method cannot be invoked.
  1145. switch (Method->getRefQualifier()) {
  1146. case RQ_LValue:
  1147. if (ObjectKind != VK_LValue && !MethodQuals.hasConst())
  1148. return;
  1149. break;
  1150. case RQ_RValue:
  1151. if (ObjectKind == VK_LValue)
  1152. return;
  1153. break;
  1154. case RQ_None:
  1155. break;
  1156. }
  1157. /// Check whether this dominates another overloaded method, which should
  1158. /// be suppressed (or vice versa).
  1159. /// Motivating case is const_iterator begin() const vs iterator begin().
  1160. auto &OverloadSet = OverloadMap[std::make_pair(
  1161. CurContext, Method->getDeclName().getAsOpaqueInteger())];
  1162. for (const DeclIndexPair Entry : OverloadSet) {
  1163. Result &Incumbent = Results[Entry.second];
  1164. switch (compareOverloads(*Method,
  1165. *cast<CXXMethodDecl>(Incumbent.Declaration),
  1166. ObjectTypeQualifiers, ObjectKind)) {
  1167. case OverloadCompare::Dominates:
  1168. // Replace the dominated overload with this one.
  1169. // FIXME: if the overload dominates multiple incumbents then we
  1170. // should remove all. But two overloads is by far the common case.
  1171. Incumbent = std::move(R);
  1172. return;
  1173. case OverloadCompare::Dominated:
  1174. // This overload can't be called, drop it.
  1175. return;
  1176. case OverloadCompare::BothViable:
  1177. break;
  1178. }
  1179. }
  1180. OverloadSet.Add(Method, Results.size());
  1181. }
  1182. // Insert this result into the set of results.
  1183. Results.push_back(R);
  1184. if (!AsNestedNameSpecifier)
  1185. MaybeAddConstructorResults(R);
  1186. }
  1187. void ResultBuilder::AddResult(Result R) {
  1188. assert(R.Kind != Result::RK_Declaration &&
  1189. "Declaration results need more context");
  1190. Results.push_back(R);
  1191. }
  1192. /// Enter into a new scope.
  1193. void ResultBuilder::EnterNewScope() { ShadowMaps.emplace_back(); }
  1194. /// Exit from the current scope.
  1195. void ResultBuilder::ExitScope() {
  1196. ShadowMaps.pop_back();
  1197. }
  1198. /// Determines whether this given declaration will be found by
  1199. /// ordinary name lookup.
  1200. bool ResultBuilder::IsOrdinaryName(const NamedDecl *ND) const {
  1201. ND = ND->getUnderlyingDecl();
  1202. // If name lookup finds a local extern declaration, then we are in a
  1203. // context where it behaves like an ordinary name.
  1204. unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
  1205. if (SemaRef.getLangOpts().CPlusPlus)
  1206. IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
  1207. else if (SemaRef.getLangOpts().ObjC) {
  1208. if (isa<ObjCIvarDecl>(ND))
  1209. return true;
  1210. }
  1211. return ND->getIdentifierNamespace() & IDNS;
  1212. }
  1213. /// Determines whether this given declaration will be found by
  1214. /// ordinary name lookup but is not a type name.
  1215. bool ResultBuilder::IsOrdinaryNonTypeName(const NamedDecl *ND) const {
  1216. ND = ND->getUnderlyingDecl();
  1217. if (isa<TypeDecl>(ND))
  1218. return false;
  1219. // Objective-C interfaces names are not filtered by this method because they
  1220. // can be used in a class property expression. We can still filter out
  1221. // @class declarations though.
  1222. if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(ND)) {
  1223. if (!ID->getDefinition())
  1224. return false;
  1225. }
  1226. unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
  1227. if (SemaRef.getLangOpts().CPlusPlus)
  1228. IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace | Decl::IDNS_Member;
  1229. else if (SemaRef.getLangOpts().ObjC) {
  1230. if (isa<ObjCIvarDecl>(ND))
  1231. return true;
  1232. }
  1233. return ND->getIdentifierNamespace() & IDNS;
  1234. }
  1235. bool ResultBuilder::IsIntegralConstantValue(const NamedDecl *ND) const {
  1236. if (!IsOrdinaryNonTypeName(ND))
  1237. return false;
  1238. if (const auto *VD = dyn_cast<ValueDecl>(ND->getUnderlyingDecl()))
  1239. if (VD->getType()->isIntegralOrEnumerationType())
  1240. return true;
  1241. return false;
  1242. }
  1243. /// Determines whether this given declaration will be found by
  1244. /// ordinary name lookup.
  1245. bool ResultBuilder::IsOrdinaryNonValueName(const NamedDecl *ND) const {
  1246. ND = ND->getUnderlyingDecl();
  1247. unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_LocalExtern;
  1248. if (SemaRef.getLangOpts().CPlusPlus)
  1249. IDNS |= Decl::IDNS_Tag | Decl::IDNS_Namespace;
  1250. return (ND->getIdentifierNamespace() & IDNS) && !isa<ValueDecl>(ND) &&
  1251. !isa<FunctionTemplateDecl>(ND) && !isa<ObjCPropertyDecl>(ND);
  1252. }
  1253. /// Determines whether the given declaration is suitable as the
  1254. /// start of a C++ nested-name-specifier, e.g., a class or namespace.
  1255. bool ResultBuilder::IsNestedNameSpecifier(const NamedDecl *ND) const {
  1256. // Allow us to find class templates, too.
  1257. if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
  1258. ND = ClassTemplate->getTemplatedDecl();
  1259. return SemaRef.isAcceptableNestedNameSpecifier(ND);
  1260. }
  1261. /// Determines whether the given declaration is an enumeration.
  1262. bool ResultBuilder::IsEnum(const NamedDecl *ND) const {
  1263. return isa<EnumDecl>(ND);
  1264. }
  1265. /// Determines whether the given declaration is a class or struct.
  1266. bool ResultBuilder::IsClassOrStruct(const NamedDecl *ND) const {
  1267. // Allow us to find class templates, too.
  1268. if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
  1269. ND = ClassTemplate->getTemplatedDecl();
  1270. // For purposes of this check, interfaces match too.
  1271. if (const auto *RD = dyn_cast<RecordDecl>(ND))
  1272. return RD->getTagKind() == TTK_Class || RD->getTagKind() == TTK_Struct ||
  1273. RD->getTagKind() == TTK_Interface;
  1274. return false;
  1275. }
  1276. /// Determines whether the given declaration is a union.
  1277. bool ResultBuilder::IsUnion(const NamedDecl *ND) const {
  1278. // Allow us to find class templates, too.
  1279. if (const auto *ClassTemplate = dyn_cast<ClassTemplateDecl>(ND))
  1280. ND = ClassTemplate->getTemplatedDecl();
  1281. if (const auto *RD = dyn_cast<RecordDecl>(ND))
  1282. return RD->getTagKind() == TTK_Union;
  1283. return false;
  1284. }
  1285. /// Determines whether the given declaration is a namespace.
  1286. bool ResultBuilder::IsNamespace(const NamedDecl *ND) const {
  1287. return isa<NamespaceDecl>(ND);
  1288. }
  1289. /// Determines whether the given declaration is a namespace or
  1290. /// namespace alias.
  1291. bool ResultBuilder::IsNamespaceOrAlias(const NamedDecl *ND) const {
  1292. return isa<NamespaceDecl>(ND->getUnderlyingDecl());
  1293. }
  1294. /// Determines whether the given declaration is a type.
  1295. bool ResultBuilder::IsType(const NamedDecl *ND) const {
  1296. ND = ND->getUnderlyingDecl();
  1297. return isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
  1298. }
  1299. /// Determines which members of a class should be visible via
  1300. /// "." or "->". Only value declarations, nested name specifiers, and
  1301. /// using declarations thereof should show up.
  1302. bool ResultBuilder::IsMember(const NamedDecl *ND) const {
  1303. ND = ND->getUnderlyingDecl();
  1304. return isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
  1305. isa<ObjCPropertyDecl>(ND);
  1306. }
  1307. static bool isObjCReceiverType(ASTContext &C, QualType T) {
  1308. T = C.getCanonicalType(T);
  1309. switch (T->getTypeClass()) {
  1310. case Type::ObjCObject:
  1311. case Type::ObjCInterface:
  1312. case Type::ObjCObjectPointer:
  1313. return true;
  1314. case Type::Builtin:
  1315. switch (cast<BuiltinType>(T)->getKind()) {
  1316. case BuiltinType::ObjCId:
  1317. case BuiltinType::ObjCClass:
  1318. case BuiltinType::ObjCSel:
  1319. return true;
  1320. default:
  1321. break;
  1322. }
  1323. return false;
  1324. default:
  1325. break;
  1326. }
  1327. if (!C.getLangOpts().CPlusPlus)
  1328. return false;
  1329. // FIXME: We could perform more analysis here to determine whether a
  1330. // particular class type has any conversions to Objective-C types. For now,
  1331. // just accept all class types.
  1332. return T->isDependentType() || T->isRecordType();
  1333. }
  1334. bool ResultBuilder::IsObjCMessageReceiver(const NamedDecl *ND) const {
  1335. QualType T = getDeclUsageType(SemaRef.Context, ND);
  1336. if (T.isNull())
  1337. return false;
  1338. T = SemaRef.Context.getBaseElementType(T);
  1339. return isObjCReceiverType(SemaRef.Context, T);
  1340. }
  1341. bool ResultBuilder::IsObjCMessageReceiverOrLambdaCapture(
  1342. const NamedDecl *ND) const {
  1343. if (IsObjCMessageReceiver(ND))
  1344. return true;
  1345. const auto *Var = dyn_cast<VarDecl>(ND);
  1346. if (!Var)
  1347. return false;
  1348. return Var->hasLocalStorage() && !Var->hasAttr<BlocksAttr>();
  1349. }
  1350. bool ResultBuilder::IsObjCCollection(const NamedDecl *ND) const {
  1351. if ((SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryName(ND)) ||
  1352. (!SemaRef.getLangOpts().CPlusPlus && !IsOrdinaryNonTypeName(ND)))
  1353. return false;
  1354. QualType T = getDeclUsageType(SemaRef.Context, ND);
  1355. if (T.isNull())
  1356. return false;
  1357. T = SemaRef.Context.getBaseElementType(T);
  1358. return T->isObjCObjectType() || T->isObjCObjectPointerType() ||
  1359. T->isObjCIdType() ||
  1360. (SemaRef.getLangOpts().CPlusPlus && T->isRecordType());
  1361. }
  1362. bool ResultBuilder::IsImpossibleToSatisfy(const NamedDecl *ND) const {
  1363. return false;
  1364. }
  1365. /// Determines whether the given declaration is an Objective-C
  1366. /// instance variable.
  1367. bool ResultBuilder::IsObjCIvar(const NamedDecl *ND) const {
  1368. return isa<ObjCIvarDecl>(ND);
  1369. }
  1370. namespace {
  1371. /// Visible declaration consumer that adds a code-completion result
  1372. /// for each visible declaration.
  1373. class CodeCompletionDeclConsumer : public VisibleDeclConsumer {
  1374. ResultBuilder &Results;
  1375. DeclContext *InitialLookupCtx;
  1376. // NamingClass and BaseType are used for access-checking. See
  1377. // Sema::IsSimplyAccessible for details.
  1378. CXXRecordDecl *NamingClass;
  1379. QualType BaseType;
  1380. std::vector<FixItHint> FixIts;
  1381. public:
  1382. CodeCompletionDeclConsumer(
  1383. ResultBuilder &Results, DeclContext *InitialLookupCtx,
  1384. QualType BaseType = QualType(),
  1385. std::vector<FixItHint> FixIts = std::vector<FixItHint>())
  1386. : Results(Results), InitialLookupCtx(InitialLookupCtx),
  1387. FixIts(std::move(FixIts)) {
  1388. NamingClass = llvm::dyn_cast<CXXRecordDecl>(InitialLookupCtx);
  1389. // If BaseType was not provided explicitly, emulate implicit 'this->'.
  1390. if (BaseType.isNull()) {
  1391. auto ThisType = Results.getSema().getCurrentThisType();
  1392. if (!ThisType.isNull()) {
  1393. assert(ThisType->isPointerType());
  1394. BaseType = ThisType->getPointeeType();
  1395. if (!NamingClass)
  1396. NamingClass = BaseType->getAsCXXRecordDecl();
  1397. }
  1398. }
  1399. this->BaseType = BaseType;
  1400. }
  1401. void FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx,
  1402. bool InBaseClass) override {
  1403. ResultBuilder::Result Result(ND, Results.getBasePriority(ND), nullptr,
  1404. false, IsAccessible(ND, Ctx), FixIts);
  1405. Results.AddResult(Result, InitialLookupCtx, Hiding, InBaseClass);
  1406. }
  1407. void EnteredContext(DeclContext *Ctx) override {
  1408. Results.addVisitedContext(Ctx);
  1409. }
  1410. private:
  1411. bool IsAccessible(NamedDecl *ND, DeclContext *Ctx) {
  1412. // Naming class to use for access check. In most cases it was provided
  1413. // explicitly (e.g. member access (lhs.foo) or qualified lookup (X::)),
  1414. // for unqualified lookup we fallback to the \p Ctx in which we found the
  1415. // member.
  1416. auto *NamingClass = this->NamingClass;
  1417. QualType BaseType = this->BaseType;
  1418. if (auto *Cls = llvm::dyn_cast_or_null<CXXRecordDecl>(Ctx)) {
  1419. if (!NamingClass)
  1420. NamingClass = Cls;
  1421. // When we emulate implicit 'this->' in an unqualified lookup, we might
  1422. // end up with an invalid naming class. In that case, we avoid emulating
  1423. // 'this->' qualifier to satisfy preconditions of the access checking.
  1424. if (NamingClass->getCanonicalDecl() != Cls->getCanonicalDecl() &&
  1425. !NamingClass->isDerivedFrom(Cls)) {
  1426. NamingClass = Cls;
  1427. BaseType = QualType();
  1428. }
  1429. } else {
  1430. // The decl was found outside the C++ class, so only ObjC access checks
  1431. // apply. Those do not rely on NamingClass and BaseType, so we clear them
  1432. // out.
  1433. NamingClass = nullptr;
  1434. BaseType = QualType();
  1435. }
  1436. return Results.getSema().IsSimplyAccessible(ND, NamingClass, BaseType);
  1437. }
  1438. };
  1439. } // namespace
  1440. /// Add type specifiers for the current language as keyword results.
  1441. static void AddTypeSpecifierResults(const LangOptions &LangOpts,
  1442. ResultBuilder &Results) {
  1443. typedef CodeCompletionResult Result;
  1444. Results.AddResult(Result("short", CCP_Type));
  1445. Results.AddResult(Result("long", CCP_Type));
  1446. Results.AddResult(Result("signed", CCP_Type));
  1447. Results.AddResult(Result("unsigned", CCP_Type));
  1448. Results.AddResult(Result("void", CCP_Type));
  1449. Results.AddResult(Result("char", CCP_Type));
  1450. Results.AddResult(Result("int", CCP_Type));
  1451. Results.AddResult(Result("float", CCP_Type));
  1452. Results.AddResult(Result("double", CCP_Type));
  1453. Results.AddResult(Result("enum", CCP_Type));
  1454. Results.AddResult(Result("struct", CCP_Type));
  1455. Results.AddResult(Result("union", CCP_Type));
  1456. Results.AddResult(Result("const", CCP_Type));
  1457. Results.AddResult(Result("volatile", CCP_Type));
  1458. if (LangOpts.C99) {
  1459. // C99-specific
  1460. Results.AddResult(Result("_Complex", CCP_Type));
  1461. Results.AddResult(Result("_Imaginary", CCP_Type));
  1462. Results.AddResult(Result("_Bool", CCP_Type));
  1463. Results.AddResult(Result("restrict", CCP_Type));
  1464. }
  1465. CodeCompletionBuilder Builder(Results.getAllocator(),
  1466. Results.getCodeCompletionTUInfo());
  1467. if (LangOpts.CPlusPlus) {
  1468. // C++-specific
  1469. Results.AddResult(
  1470. Result("bool", CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0)));
  1471. Results.AddResult(Result("class", CCP_Type));
  1472. Results.AddResult(Result("wchar_t", CCP_Type));
  1473. // typename name
  1474. Builder.AddTypedTextChunk("typename");
  1475. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1476. Builder.AddPlaceholderChunk("name");
  1477. Results.AddResult(Result(Builder.TakeString()));
  1478. if (LangOpts.CPlusPlus11) {
  1479. Results.AddResult(Result("auto", CCP_Type));
  1480. Results.AddResult(Result("char16_t", CCP_Type));
  1481. Results.AddResult(Result("char32_t", CCP_Type));
  1482. Builder.AddTypedTextChunk("decltype");
  1483. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  1484. Builder.AddPlaceholderChunk("expression");
  1485. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  1486. Results.AddResult(Result(Builder.TakeString()));
  1487. }
  1488. } else
  1489. Results.AddResult(Result("__auto_type", CCP_Type));
  1490. // GNU keywords
  1491. if (LangOpts.GNUKeywords) {
  1492. // FIXME: Enable when we actually support decimal floating point.
  1493. // Results.AddResult(Result("_Decimal32"));
  1494. // Results.AddResult(Result("_Decimal64"));
  1495. // Results.AddResult(Result("_Decimal128"));
  1496. Builder.AddTypedTextChunk("typeof");
  1497. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1498. Builder.AddPlaceholderChunk("expression");
  1499. Results.AddResult(Result(Builder.TakeString()));
  1500. Builder.AddTypedTextChunk("typeof");
  1501. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  1502. Builder.AddPlaceholderChunk("type");
  1503. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  1504. Results.AddResult(Result(Builder.TakeString()));
  1505. }
  1506. // Nullability
  1507. Results.AddResult(Result("_Nonnull", CCP_Type));
  1508. Results.AddResult(Result("_Null_unspecified", CCP_Type));
  1509. Results.AddResult(Result("_Nullable", CCP_Type));
  1510. }
  1511. static void AddStorageSpecifiers(Sema::ParserCompletionContext CCC,
  1512. const LangOptions &LangOpts,
  1513. ResultBuilder &Results) {
  1514. typedef CodeCompletionResult Result;
  1515. // Note: we don't suggest either "auto" or "register", because both
  1516. // are pointless as storage specifiers. Elsewhere, we suggest "auto"
  1517. // in C++0x as a type specifier.
  1518. Results.AddResult(Result("extern"));
  1519. Results.AddResult(Result("static"));
  1520. if (LangOpts.CPlusPlus11) {
  1521. CodeCompletionAllocator &Allocator = Results.getAllocator();
  1522. CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
  1523. // alignas
  1524. Builder.AddTypedTextChunk("alignas");
  1525. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  1526. Builder.AddPlaceholderChunk("expression");
  1527. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  1528. Results.AddResult(Result(Builder.TakeString()));
  1529. Results.AddResult(Result("constexpr"));
  1530. Results.AddResult(Result("thread_local"));
  1531. }
  1532. }
  1533. static void AddFunctionSpecifiers(Sema::ParserCompletionContext CCC,
  1534. const LangOptions &LangOpts,
  1535. ResultBuilder &Results) {
  1536. typedef CodeCompletionResult Result;
  1537. switch (CCC) {
  1538. case Sema::PCC_Class:
  1539. case Sema::PCC_MemberTemplate:
  1540. if (LangOpts.CPlusPlus) {
  1541. Results.AddResult(Result("explicit"));
  1542. Results.AddResult(Result("friend"));
  1543. Results.AddResult(Result("mutable"));
  1544. Results.AddResult(Result("virtual"));
  1545. }
  1546. LLVM_FALLTHROUGH;
  1547. case Sema::PCC_ObjCInterface:
  1548. case Sema::PCC_ObjCImplementation:
  1549. case Sema::PCC_Namespace:
  1550. case Sema::PCC_Template:
  1551. if (LangOpts.CPlusPlus || LangOpts.C99)
  1552. Results.AddResult(Result("inline"));
  1553. break;
  1554. case Sema::PCC_ObjCInstanceVariableList:
  1555. case Sema::PCC_Expression:
  1556. case Sema::PCC_Statement:
  1557. case Sema::PCC_ForInit:
  1558. case Sema::PCC_Condition:
  1559. case Sema::PCC_RecoveryInFunction:
  1560. case Sema::PCC_Type:
  1561. case Sema::PCC_ParenthesizedExpression:
  1562. case Sema::PCC_LocalDeclarationSpecifiers:
  1563. break;
  1564. }
  1565. }
  1566. static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt);
  1567. static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt);
  1568. static void AddObjCVisibilityResults(const LangOptions &LangOpts,
  1569. ResultBuilder &Results, bool NeedAt);
  1570. static void AddObjCImplementationResults(const LangOptions &LangOpts,
  1571. ResultBuilder &Results, bool NeedAt);
  1572. static void AddObjCInterfaceResults(const LangOptions &LangOpts,
  1573. ResultBuilder &Results, bool NeedAt);
  1574. static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt);
  1575. static void AddTypedefResult(ResultBuilder &Results) {
  1576. CodeCompletionBuilder Builder(Results.getAllocator(),
  1577. Results.getCodeCompletionTUInfo());
  1578. Builder.AddTypedTextChunk("typedef");
  1579. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1580. Builder.AddPlaceholderChunk("type");
  1581. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1582. Builder.AddPlaceholderChunk("name");
  1583. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  1584. Results.AddResult(CodeCompletionResult(Builder.TakeString()));
  1585. }
  1586. // using name = type
  1587. static void AddUsingAliasResult(CodeCompletionBuilder &Builder,
  1588. ResultBuilder &Results) {
  1589. Builder.AddTypedTextChunk("using");
  1590. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1591. Builder.AddPlaceholderChunk("name");
  1592. Builder.AddChunk(CodeCompletionString::CK_Equal);
  1593. Builder.AddPlaceholderChunk("type");
  1594. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  1595. Results.AddResult(CodeCompletionResult(Builder.TakeString()));
  1596. }
  1597. static bool WantTypesInContext(Sema::ParserCompletionContext CCC,
  1598. const LangOptions &LangOpts) {
  1599. switch (CCC) {
  1600. case Sema::PCC_Namespace:
  1601. case Sema::PCC_Class:
  1602. case Sema::PCC_ObjCInstanceVariableList:
  1603. case Sema::PCC_Template:
  1604. case Sema::PCC_MemberTemplate:
  1605. case Sema::PCC_Statement:
  1606. case Sema::PCC_RecoveryInFunction:
  1607. case Sema::PCC_Type:
  1608. case Sema::PCC_ParenthesizedExpression:
  1609. case Sema::PCC_LocalDeclarationSpecifiers:
  1610. return true;
  1611. case Sema::PCC_Expression:
  1612. case Sema::PCC_Condition:
  1613. return LangOpts.CPlusPlus;
  1614. case Sema::PCC_ObjCInterface:
  1615. case Sema::PCC_ObjCImplementation:
  1616. return false;
  1617. case Sema::PCC_ForInit:
  1618. return LangOpts.CPlusPlus || LangOpts.ObjC || LangOpts.C99;
  1619. }
  1620. llvm_unreachable("Invalid ParserCompletionContext!");
  1621. }
  1622. static PrintingPolicy getCompletionPrintingPolicy(const ASTContext &Context,
  1623. const Preprocessor &PP) {
  1624. PrintingPolicy Policy = Sema::getPrintingPolicy(Context, PP);
  1625. Policy.AnonymousTagLocations = false;
  1626. Policy.SuppressStrongLifetime = true;
  1627. Policy.SuppressUnwrittenScope = true;
  1628. Policy.SuppressScope = true;
  1629. Policy.CleanUglifiedParameters = true;
  1630. return Policy;
  1631. }
  1632. /// Retrieve a printing policy suitable for code completion.
  1633. static PrintingPolicy getCompletionPrintingPolicy(Sema &S) {
  1634. return getCompletionPrintingPolicy(S.Context, S.PP);
  1635. }
  1636. /// Retrieve the string representation of the given type as a string
  1637. /// that has the appropriate lifetime for code completion.
  1638. ///
  1639. /// This routine provides a fast path where we provide constant strings for
  1640. /// common type names.
  1641. static const char *GetCompletionTypeString(QualType T, ASTContext &Context,
  1642. const PrintingPolicy &Policy,
  1643. CodeCompletionAllocator &Allocator) {
  1644. if (!T.getLocalQualifiers()) {
  1645. // Built-in type names are constant strings.
  1646. if (const BuiltinType *BT = dyn_cast<BuiltinType>(T))
  1647. return BT->getNameAsCString(Policy);
  1648. // Anonymous tag types are constant strings.
  1649. if (const TagType *TagT = dyn_cast<TagType>(T))
  1650. if (TagDecl *Tag = TagT->getDecl())
  1651. if (!Tag->hasNameForLinkage()) {
  1652. switch (Tag->getTagKind()) {
  1653. case TTK_Struct:
  1654. return "struct <anonymous>";
  1655. case TTK_Interface:
  1656. return "__interface <anonymous>";
  1657. case TTK_Class:
  1658. return "class <anonymous>";
  1659. case TTK_Union:
  1660. return "union <anonymous>";
  1661. case TTK_Enum:
  1662. return "enum <anonymous>";
  1663. }
  1664. }
  1665. }
  1666. // Slow path: format the type as a string.
  1667. std::string Result;
  1668. T.getAsStringInternal(Result, Policy);
  1669. return Allocator.CopyString(Result);
  1670. }
  1671. /// Add a completion for "this", if we're in a member function.
  1672. static void addThisCompletion(Sema &S, ResultBuilder &Results) {
  1673. QualType ThisTy = S.getCurrentThisType();
  1674. if (ThisTy.isNull())
  1675. return;
  1676. CodeCompletionAllocator &Allocator = Results.getAllocator();
  1677. CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
  1678. PrintingPolicy Policy = getCompletionPrintingPolicy(S);
  1679. Builder.AddResultTypeChunk(
  1680. GetCompletionTypeString(ThisTy, S.Context, Policy, Allocator));
  1681. Builder.AddTypedTextChunk("this");
  1682. Results.AddResult(CodeCompletionResult(Builder.TakeString()));
  1683. }
  1684. static void AddStaticAssertResult(CodeCompletionBuilder &Builder,
  1685. ResultBuilder &Results,
  1686. const LangOptions &LangOpts) {
  1687. if (!LangOpts.CPlusPlus11)
  1688. return;
  1689. Builder.AddTypedTextChunk("static_assert");
  1690. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  1691. Builder.AddPlaceholderChunk("expression");
  1692. Builder.AddChunk(CodeCompletionString::CK_Comma);
  1693. Builder.AddPlaceholderChunk("message");
  1694. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  1695. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  1696. Results.AddResult(CodeCompletionResult(Builder.TakeString()));
  1697. }
  1698. static void AddOverrideResults(ResultBuilder &Results,
  1699. const CodeCompletionContext &CCContext,
  1700. CodeCompletionBuilder &Builder) {
  1701. Sema &S = Results.getSema();
  1702. const auto *CR = llvm::dyn_cast<CXXRecordDecl>(S.CurContext);
  1703. // If not inside a class/struct/union return empty.
  1704. if (!CR)
  1705. return;
  1706. // First store overrides within current class.
  1707. // These are stored by name to make querying fast in the later step.
  1708. llvm::StringMap<std::vector<FunctionDecl *>> Overrides;
  1709. for (auto *Method : CR->methods()) {
  1710. if (!Method->isVirtual() || !Method->getIdentifier())
  1711. continue;
  1712. Overrides[Method->getName()].push_back(Method);
  1713. }
  1714. for (const auto &Base : CR->bases()) {
  1715. const auto *BR = Base.getType().getTypePtr()->getAsCXXRecordDecl();
  1716. if (!BR)
  1717. continue;
  1718. for (auto *Method : BR->methods()) {
  1719. if (!Method->isVirtual() || !Method->getIdentifier())
  1720. continue;
  1721. const auto it = Overrides.find(Method->getName());
  1722. bool IsOverriden = false;
  1723. if (it != Overrides.end()) {
  1724. for (auto *MD : it->second) {
  1725. // If the method in current body is not an overload of this virtual
  1726. // function, then it overrides this one.
  1727. if (!S.IsOverload(MD, Method, false)) {
  1728. IsOverriden = true;
  1729. break;
  1730. }
  1731. }
  1732. }
  1733. if (!IsOverriden) {
  1734. // Generates a new CodeCompletionResult by taking this function and
  1735. // converting it into an override declaration with only one chunk in the
  1736. // final CodeCompletionString as a TypedTextChunk.
  1737. std::string OverrideSignature;
  1738. llvm::raw_string_ostream OS(OverrideSignature);
  1739. CodeCompletionResult CCR(Method, 0);
  1740. PrintingPolicy Policy =
  1741. getCompletionPrintingPolicy(S.getASTContext(), S.getPreprocessor());
  1742. auto *CCS = CCR.createCodeCompletionStringForOverride(
  1743. S.getPreprocessor(), S.getASTContext(), Builder,
  1744. /*IncludeBriefComments=*/false, CCContext, Policy);
  1745. Results.AddResult(CodeCompletionResult(CCS, Method, CCP_CodePattern));
  1746. }
  1747. }
  1748. }
  1749. }
  1750. /// Add language constructs that show up for "ordinary" names.
  1751. static void AddOrdinaryNameResults(Sema::ParserCompletionContext CCC, Scope *S,
  1752. Sema &SemaRef, ResultBuilder &Results) {
  1753. CodeCompletionAllocator &Allocator = Results.getAllocator();
  1754. CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
  1755. typedef CodeCompletionResult Result;
  1756. switch (CCC) {
  1757. case Sema::PCC_Namespace:
  1758. if (SemaRef.getLangOpts().CPlusPlus) {
  1759. if (Results.includeCodePatterns()) {
  1760. // namespace <identifier> { declarations }
  1761. Builder.AddTypedTextChunk("namespace");
  1762. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1763. Builder.AddPlaceholderChunk("identifier");
  1764. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1765. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  1766. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1767. Builder.AddPlaceholderChunk("declarations");
  1768. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1769. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  1770. Results.AddResult(Result(Builder.TakeString()));
  1771. }
  1772. // namespace identifier = identifier ;
  1773. Builder.AddTypedTextChunk("namespace");
  1774. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1775. Builder.AddPlaceholderChunk("name");
  1776. Builder.AddChunk(CodeCompletionString::CK_Equal);
  1777. Builder.AddPlaceholderChunk("namespace");
  1778. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  1779. Results.AddResult(Result(Builder.TakeString()));
  1780. // Using directives
  1781. Builder.AddTypedTextChunk("using namespace");
  1782. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1783. Builder.AddPlaceholderChunk("identifier");
  1784. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  1785. Results.AddResult(Result(Builder.TakeString()));
  1786. // asm(string-literal)
  1787. Builder.AddTypedTextChunk("asm");
  1788. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  1789. Builder.AddPlaceholderChunk("string-literal");
  1790. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  1791. Results.AddResult(Result(Builder.TakeString()));
  1792. if (Results.includeCodePatterns()) {
  1793. // Explicit template instantiation
  1794. Builder.AddTypedTextChunk("template");
  1795. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1796. Builder.AddPlaceholderChunk("declaration");
  1797. Results.AddResult(Result(Builder.TakeString()));
  1798. } else {
  1799. Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
  1800. }
  1801. }
  1802. if (SemaRef.getLangOpts().ObjC)
  1803. AddObjCTopLevelResults(Results, true);
  1804. AddTypedefResult(Results);
  1805. LLVM_FALLTHROUGH;
  1806. case Sema::PCC_Class:
  1807. if (SemaRef.getLangOpts().CPlusPlus) {
  1808. // Using declaration
  1809. Builder.AddTypedTextChunk("using");
  1810. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1811. Builder.AddPlaceholderChunk("qualifier");
  1812. Builder.AddTextChunk("::");
  1813. Builder.AddPlaceholderChunk("name");
  1814. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  1815. Results.AddResult(Result(Builder.TakeString()));
  1816. if (SemaRef.getLangOpts().CPlusPlus11)
  1817. AddUsingAliasResult(Builder, Results);
  1818. // using typename qualifier::name (only in a dependent context)
  1819. if (SemaRef.CurContext->isDependentContext()) {
  1820. Builder.AddTypedTextChunk("using typename");
  1821. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1822. Builder.AddPlaceholderChunk("qualifier");
  1823. Builder.AddTextChunk("::");
  1824. Builder.AddPlaceholderChunk("name");
  1825. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  1826. Results.AddResult(Result(Builder.TakeString()));
  1827. }
  1828. AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
  1829. if (CCC == Sema::PCC_Class) {
  1830. AddTypedefResult(Results);
  1831. bool IsNotInheritanceScope =
  1832. !(S->getFlags() & Scope::ClassInheritanceScope);
  1833. // public:
  1834. Builder.AddTypedTextChunk("public");
  1835. if (IsNotInheritanceScope && Results.includeCodePatterns())
  1836. Builder.AddChunk(CodeCompletionString::CK_Colon);
  1837. Results.AddResult(Result(Builder.TakeString()));
  1838. // protected:
  1839. Builder.AddTypedTextChunk("protected");
  1840. if (IsNotInheritanceScope && Results.includeCodePatterns())
  1841. Builder.AddChunk(CodeCompletionString::CK_Colon);
  1842. Results.AddResult(Result(Builder.TakeString()));
  1843. // private:
  1844. Builder.AddTypedTextChunk("private");
  1845. if (IsNotInheritanceScope && Results.includeCodePatterns())
  1846. Builder.AddChunk(CodeCompletionString::CK_Colon);
  1847. Results.AddResult(Result(Builder.TakeString()));
  1848. // FIXME: This adds override results only if we are at the first word of
  1849. // the declaration/definition. Also call this from other sides to have
  1850. // more use-cases.
  1851. AddOverrideResults(Results, CodeCompletionContext::CCC_ClassStructUnion,
  1852. Builder);
  1853. }
  1854. }
  1855. LLVM_FALLTHROUGH;
  1856. case Sema::PCC_Template:
  1857. case Sema::PCC_MemberTemplate:
  1858. if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns()) {
  1859. // template < parameters >
  1860. Builder.AddTypedTextChunk("template");
  1861. Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
  1862. Builder.AddPlaceholderChunk("parameters");
  1863. Builder.AddChunk(CodeCompletionString::CK_RightAngle);
  1864. Results.AddResult(Result(Builder.TakeString()));
  1865. } else {
  1866. Results.AddResult(Result("template", CodeCompletionResult::RK_Keyword));
  1867. }
  1868. AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
  1869. AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
  1870. break;
  1871. case Sema::PCC_ObjCInterface:
  1872. AddObjCInterfaceResults(SemaRef.getLangOpts(), Results, true);
  1873. AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
  1874. AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
  1875. break;
  1876. case Sema::PCC_ObjCImplementation:
  1877. AddObjCImplementationResults(SemaRef.getLangOpts(), Results, true);
  1878. AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
  1879. AddFunctionSpecifiers(CCC, SemaRef.getLangOpts(), Results);
  1880. break;
  1881. case Sema::PCC_ObjCInstanceVariableList:
  1882. AddObjCVisibilityResults(SemaRef.getLangOpts(), Results, true);
  1883. break;
  1884. case Sema::PCC_RecoveryInFunction:
  1885. case Sema::PCC_Statement: {
  1886. if (SemaRef.getLangOpts().CPlusPlus11)
  1887. AddUsingAliasResult(Builder, Results);
  1888. AddTypedefResult(Results);
  1889. if (SemaRef.getLangOpts().CPlusPlus && Results.includeCodePatterns() &&
  1890. SemaRef.getLangOpts().CXXExceptions) {
  1891. Builder.AddTypedTextChunk("try");
  1892. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1893. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  1894. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1895. Builder.AddPlaceholderChunk("statements");
  1896. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1897. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  1898. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1899. Builder.AddTextChunk("catch");
  1900. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1901. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  1902. Builder.AddPlaceholderChunk("declaration");
  1903. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  1904. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1905. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  1906. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1907. Builder.AddPlaceholderChunk("statements");
  1908. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1909. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  1910. Results.AddResult(Result(Builder.TakeString()));
  1911. }
  1912. if (SemaRef.getLangOpts().ObjC)
  1913. AddObjCStatementResults(Results, true);
  1914. if (Results.includeCodePatterns()) {
  1915. // if (condition) { statements }
  1916. Builder.AddTypedTextChunk("if");
  1917. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1918. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  1919. if (SemaRef.getLangOpts().CPlusPlus)
  1920. Builder.AddPlaceholderChunk("condition");
  1921. else
  1922. Builder.AddPlaceholderChunk("expression");
  1923. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  1924. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1925. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  1926. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1927. Builder.AddPlaceholderChunk("statements");
  1928. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1929. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  1930. Results.AddResult(Result(Builder.TakeString()));
  1931. // switch (condition) { }
  1932. Builder.AddTypedTextChunk("switch");
  1933. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1934. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  1935. if (SemaRef.getLangOpts().CPlusPlus)
  1936. Builder.AddPlaceholderChunk("condition");
  1937. else
  1938. Builder.AddPlaceholderChunk("expression");
  1939. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  1940. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1941. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  1942. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1943. Builder.AddPlaceholderChunk("cases");
  1944. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1945. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  1946. Results.AddResult(Result(Builder.TakeString()));
  1947. }
  1948. // Switch-specific statements.
  1949. if (SemaRef.getCurFunction() &&
  1950. !SemaRef.getCurFunction()->SwitchStack.empty()) {
  1951. // case expression:
  1952. Builder.AddTypedTextChunk("case");
  1953. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1954. Builder.AddPlaceholderChunk("expression");
  1955. Builder.AddChunk(CodeCompletionString::CK_Colon);
  1956. Results.AddResult(Result(Builder.TakeString()));
  1957. // default:
  1958. Builder.AddTypedTextChunk("default");
  1959. Builder.AddChunk(CodeCompletionString::CK_Colon);
  1960. Results.AddResult(Result(Builder.TakeString()));
  1961. }
  1962. if (Results.includeCodePatterns()) {
  1963. /// while (condition) { statements }
  1964. Builder.AddTypedTextChunk("while");
  1965. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1966. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  1967. if (SemaRef.getLangOpts().CPlusPlus)
  1968. Builder.AddPlaceholderChunk("condition");
  1969. else
  1970. Builder.AddPlaceholderChunk("expression");
  1971. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  1972. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1973. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  1974. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1975. Builder.AddPlaceholderChunk("statements");
  1976. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1977. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  1978. Results.AddResult(Result(Builder.TakeString()));
  1979. // do { statements } while ( expression );
  1980. Builder.AddTypedTextChunk("do");
  1981. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1982. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  1983. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1984. Builder.AddPlaceholderChunk("statements");
  1985. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  1986. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  1987. Builder.AddTextChunk("while");
  1988. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1989. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  1990. Builder.AddPlaceholderChunk("expression");
  1991. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  1992. Results.AddResult(Result(Builder.TakeString()));
  1993. // for ( for-init-statement ; condition ; expression ) { statements }
  1994. Builder.AddTypedTextChunk("for");
  1995. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  1996. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  1997. if (SemaRef.getLangOpts().CPlusPlus || SemaRef.getLangOpts().C99)
  1998. Builder.AddPlaceholderChunk("init-statement");
  1999. else
  2000. Builder.AddPlaceholderChunk("init-expression");
  2001. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  2002. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2003. Builder.AddPlaceholderChunk("condition");
  2004. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  2005. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2006. Builder.AddPlaceholderChunk("inc-expression");
  2007. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2008. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2009. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  2010. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  2011. Builder.AddPlaceholderChunk("statements");
  2012. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  2013. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  2014. Results.AddResult(Result(Builder.TakeString()));
  2015. if (SemaRef.getLangOpts().CPlusPlus11 || SemaRef.getLangOpts().ObjC) {
  2016. // for ( range_declaration (:|in) range_expression ) { statements }
  2017. Builder.AddTypedTextChunk("for");
  2018. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2019. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  2020. Builder.AddPlaceholderChunk("range-declaration");
  2021. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2022. if (SemaRef.getLangOpts().ObjC)
  2023. Builder.AddTextChunk("in");
  2024. else
  2025. Builder.AddChunk(CodeCompletionString::CK_Colon);
  2026. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2027. Builder.AddPlaceholderChunk("range-expression");
  2028. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2029. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2030. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  2031. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  2032. Builder.AddPlaceholderChunk("statements");
  2033. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  2034. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  2035. Results.AddResult(Result(Builder.TakeString()));
  2036. }
  2037. }
  2038. if (S->getContinueParent()) {
  2039. // continue ;
  2040. Builder.AddTypedTextChunk("continue");
  2041. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  2042. Results.AddResult(Result(Builder.TakeString()));
  2043. }
  2044. if (S->getBreakParent()) {
  2045. // break ;
  2046. Builder.AddTypedTextChunk("break");
  2047. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  2048. Results.AddResult(Result(Builder.TakeString()));
  2049. }
  2050. // "return expression ;" or "return ;", depending on the return type.
  2051. QualType ReturnType;
  2052. if (const auto *Function = dyn_cast<FunctionDecl>(SemaRef.CurContext))
  2053. ReturnType = Function->getReturnType();
  2054. else if (const auto *Method = dyn_cast<ObjCMethodDecl>(SemaRef.CurContext))
  2055. ReturnType = Method->getReturnType();
  2056. else if (SemaRef.getCurBlock() &&
  2057. !SemaRef.getCurBlock()->ReturnType.isNull())
  2058. ReturnType = SemaRef.getCurBlock()->ReturnType;;
  2059. if (ReturnType.isNull() || ReturnType->isVoidType()) {
  2060. Builder.AddTypedTextChunk("return");
  2061. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  2062. Results.AddResult(Result(Builder.TakeString()));
  2063. } else {
  2064. assert(!ReturnType.isNull());
  2065. // "return expression ;"
  2066. Builder.AddTypedTextChunk("return");
  2067. Builder.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
  2068. Builder.AddPlaceholderChunk("expression");
  2069. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  2070. Results.AddResult(Result(Builder.TakeString()));
  2071. // When boolean, also add 'return true;' and 'return false;'.
  2072. if (ReturnType->isBooleanType()) {
  2073. Builder.AddTypedTextChunk("return true");
  2074. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  2075. Results.AddResult(Result(Builder.TakeString()));
  2076. Builder.AddTypedTextChunk("return false");
  2077. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  2078. Results.AddResult(Result(Builder.TakeString()));
  2079. }
  2080. // For pointers, suggest 'return nullptr' in C++.
  2081. if (SemaRef.getLangOpts().CPlusPlus11 &&
  2082. (ReturnType->isPointerType() || ReturnType->isMemberPointerType())) {
  2083. Builder.AddTypedTextChunk("return nullptr");
  2084. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  2085. Results.AddResult(Result(Builder.TakeString()));
  2086. }
  2087. }
  2088. // goto identifier ;
  2089. Builder.AddTypedTextChunk("goto");
  2090. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2091. Builder.AddPlaceholderChunk("label");
  2092. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  2093. Results.AddResult(Result(Builder.TakeString()));
  2094. // Using directives
  2095. Builder.AddTypedTextChunk("using namespace");
  2096. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2097. Builder.AddPlaceholderChunk("identifier");
  2098. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  2099. Results.AddResult(Result(Builder.TakeString()));
  2100. AddStaticAssertResult(Builder, Results, SemaRef.getLangOpts());
  2101. }
  2102. LLVM_FALLTHROUGH;
  2103. // Fall through (for statement expressions).
  2104. case Sema::PCC_ForInit:
  2105. case Sema::PCC_Condition:
  2106. AddStorageSpecifiers(CCC, SemaRef.getLangOpts(), Results);
  2107. // Fall through: conditions and statements can have expressions.
  2108. LLVM_FALLTHROUGH;
  2109. case Sema::PCC_ParenthesizedExpression:
  2110. if (SemaRef.getLangOpts().ObjCAutoRefCount &&
  2111. CCC == Sema::PCC_ParenthesizedExpression) {
  2112. // (__bridge <type>)<expression>
  2113. Builder.AddTypedTextChunk("__bridge");
  2114. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2115. Builder.AddPlaceholderChunk("type");
  2116. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2117. Builder.AddPlaceholderChunk("expression");
  2118. Results.AddResult(Result(Builder.TakeString()));
  2119. // (__bridge_transfer <Objective-C type>)<expression>
  2120. Builder.AddTypedTextChunk("__bridge_transfer");
  2121. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2122. Builder.AddPlaceholderChunk("Objective-C type");
  2123. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2124. Builder.AddPlaceholderChunk("expression");
  2125. Results.AddResult(Result(Builder.TakeString()));
  2126. // (__bridge_retained <CF type>)<expression>
  2127. Builder.AddTypedTextChunk("__bridge_retained");
  2128. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2129. Builder.AddPlaceholderChunk("CF type");
  2130. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2131. Builder.AddPlaceholderChunk("expression");
  2132. Results.AddResult(Result(Builder.TakeString()));
  2133. }
  2134. // Fall through
  2135. LLVM_FALLTHROUGH;
  2136. case Sema::PCC_Expression: {
  2137. if (SemaRef.getLangOpts().CPlusPlus) {
  2138. // 'this', if we're in a non-static member function.
  2139. addThisCompletion(SemaRef, Results);
  2140. // true
  2141. Builder.AddResultTypeChunk("bool");
  2142. Builder.AddTypedTextChunk("true");
  2143. Results.AddResult(Result(Builder.TakeString()));
  2144. // false
  2145. Builder.AddResultTypeChunk("bool");
  2146. Builder.AddTypedTextChunk("false");
  2147. Results.AddResult(Result(Builder.TakeString()));
  2148. if (SemaRef.getLangOpts().RTTI) {
  2149. // dynamic_cast < type-id > ( expression )
  2150. Builder.AddTypedTextChunk("dynamic_cast");
  2151. Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
  2152. Builder.AddPlaceholderChunk("type");
  2153. Builder.AddChunk(CodeCompletionString::CK_RightAngle);
  2154. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  2155. Builder.AddPlaceholderChunk("expression");
  2156. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2157. Results.AddResult(Result(Builder.TakeString()));
  2158. }
  2159. // static_cast < type-id > ( expression )
  2160. Builder.AddTypedTextChunk("static_cast");
  2161. Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
  2162. Builder.AddPlaceholderChunk("type");
  2163. Builder.AddChunk(CodeCompletionString::CK_RightAngle);
  2164. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  2165. Builder.AddPlaceholderChunk("expression");
  2166. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2167. Results.AddResult(Result(Builder.TakeString()));
  2168. // reinterpret_cast < type-id > ( expression )
  2169. Builder.AddTypedTextChunk("reinterpret_cast");
  2170. Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
  2171. Builder.AddPlaceholderChunk("type");
  2172. Builder.AddChunk(CodeCompletionString::CK_RightAngle);
  2173. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  2174. Builder.AddPlaceholderChunk("expression");
  2175. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2176. Results.AddResult(Result(Builder.TakeString()));
  2177. // const_cast < type-id > ( expression )
  2178. Builder.AddTypedTextChunk("const_cast");
  2179. Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
  2180. Builder.AddPlaceholderChunk("type");
  2181. Builder.AddChunk(CodeCompletionString::CK_RightAngle);
  2182. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  2183. Builder.AddPlaceholderChunk("expression");
  2184. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2185. Results.AddResult(Result(Builder.TakeString()));
  2186. if (SemaRef.getLangOpts().RTTI) {
  2187. // typeid ( expression-or-type )
  2188. Builder.AddResultTypeChunk("std::type_info");
  2189. Builder.AddTypedTextChunk("typeid");
  2190. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  2191. Builder.AddPlaceholderChunk("expression-or-type");
  2192. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2193. Results.AddResult(Result(Builder.TakeString()));
  2194. }
  2195. // new T ( ... )
  2196. Builder.AddTypedTextChunk("new");
  2197. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2198. Builder.AddPlaceholderChunk("type");
  2199. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  2200. Builder.AddPlaceholderChunk("expressions");
  2201. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2202. Results.AddResult(Result(Builder.TakeString()));
  2203. // new T [ ] ( ... )
  2204. Builder.AddTypedTextChunk("new");
  2205. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2206. Builder.AddPlaceholderChunk("type");
  2207. Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
  2208. Builder.AddPlaceholderChunk("size");
  2209. Builder.AddChunk(CodeCompletionString::CK_RightBracket);
  2210. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  2211. Builder.AddPlaceholderChunk("expressions");
  2212. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2213. Results.AddResult(Result(Builder.TakeString()));
  2214. // delete expression
  2215. Builder.AddResultTypeChunk("void");
  2216. Builder.AddTypedTextChunk("delete");
  2217. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2218. Builder.AddPlaceholderChunk("expression");
  2219. Results.AddResult(Result(Builder.TakeString()));
  2220. // delete [] expression
  2221. Builder.AddResultTypeChunk("void");
  2222. Builder.AddTypedTextChunk("delete");
  2223. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2224. Builder.AddChunk(CodeCompletionString::CK_LeftBracket);
  2225. Builder.AddChunk(CodeCompletionString::CK_RightBracket);
  2226. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2227. Builder.AddPlaceholderChunk("expression");
  2228. Results.AddResult(Result(Builder.TakeString()));
  2229. if (SemaRef.getLangOpts().CXXExceptions) {
  2230. // throw expression
  2231. Builder.AddResultTypeChunk("void");
  2232. Builder.AddTypedTextChunk("throw");
  2233. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2234. Builder.AddPlaceholderChunk("expression");
  2235. Results.AddResult(Result(Builder.TakeString()));
  2236. }
  2237. // FIXME: Rethrow?
  2238. if (SemaRef.getLangOpts().CPlusPlus11) {
  2239. // nullptr
  2240. Builder.AddResultTypeChunk("std::nullptr_t");
  2241. Builder.AddTypedTextChunk("nullptr");
  2242. Results.AddResult(Result(Builder.TakeString()));
  2243. // alignof
  2244. Builder.AddResultTypeChunk("size_t");
  2245. Builder.AddTypedTextChunk("alignof");
  2246. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  2247. Builder.AddPlaceholderChunk("type");
  2248. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2249. Results.AddResult(Result(Builder.TakeString()));
  2250. // noexcept
  2251. Builder.AddResultTypeChunk("bool");
  2252. Builder.AddTypedTextChunk("noexcept");
  2253. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  2254. Builder.AddPlaceholderChunk("expression");
  2255. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2256. Results.AddResult(Result(Builder.TakeString()));
  2257. // sizeof... expression
  2258. Builder.AddResultTypeChunk("size_t");
  2259. Builder.AddTypedTextChunk("sizeof...");
  2260. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  2261. Builder.AddPlaceholderChunk("parameter-pack");
  2262. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2263. Results.AddResult(Result(Builder.TakeString()));
  2264. }
  2265. }
  2266. if (SemaRef.getLangOpts().ObjC) {
  2267. // Add "super", if we're in an Objective-C class with a superclass.
  2268. if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
  2269. // The interface can be NULL.
  2270. if (ObjCInterfaceDecl *ID = Method->getClassInterface())
  2271. if (ID->getSuperClass()) {
  2272. std::string SuperType;
  2273. SuperType = ID->getSuperClass()->getNameAsString();
  2274. if (Method->isInstanceMethod())
  2275. SuperType += " *";
  2276. Builder.AddResultTypeChunk(Allocator.CopyString(SuperType));
  2277. Builder.AddTypedTextChunk("super");
  2278. Results.AddResult(Result(Builder.TakeString()));
  2279. }
  2280. }
  2281. AddObjCExpressionResults(Results, true);
  2282. }
  2283. if (SemaRef.getLangOpts().C11) {
  2284. // _Alignof
  2285. Builder.AddResultTypeChunk("size_t");
  2286. if (SemaRef.PP.isMacroDefined("alignof"))
  2287. Builder.AddTypedTextChunk("alignof");
  2288. else
  2289. Builder.AddTypedTextChunk("_Alignof");
  2290. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  2291. Builder.AddPlaceholderChunk("type");
  2292. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2293. Results.AddResult(Result(Builder.TakeString()));
  2294. }
  2295. // sizeof expression
  2296. Builder.AddResultTypeChunk("size_t");
  2297. Builder.AddTypedTextChunk("sizeof");
  2298. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  2299. Builder.AddPlaceholderChunk("expression-or-type");
  2300. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  2301. Results.AddResult(Result(Builder.TakeString()));
  2302. break;
  2303. }
  2304. case Sema::PCC_Type:
  2305. case Sema::PCC_LocalDeclarationSpecifiers:
  2306. break;
  2307. }
  2308. if (WantTypesInContext(CCC, SemaRef.getLangOpts()))
  2309. AddTypeSpecifierResults(SemaRef.getLangOpts(), Results);
  2310. if (SemaRef.getLangOpts().CPlusPlus && CCC != Sema::PCC_Type)
  2311. Results.AddResult(Result("operator"));
  2312. }
  2313. /// If the given declaration has an associated type, add it as a result
  2314. /// type chunk.
  2315. static void AddResultTypeChunk(ASTContext &Context,
  2316. const PrintingPolicy &Policy,
  2317. const NamedDecl *ND, QualType BaseType,
  2318. CodeCompletionBuilder &Result) {
  2319. if (!ND)
  2320. return;
  2321. // Skip constructors and conversion functions, which have their return types
  2322. // built into their names.
  2323. if (isConstructor(ND) || isa<CXXConversionDecl>(ND))
  2324. return;
  2325. // Determine the type of the declaration (if it has a type).
  2326. QualType T;
  2327. if (const FunctionDecl *Function = ND->getAsFunction())
  2328. T = Function->getReturnType();
  2329. else if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
  2330. if (!BaseType.isNull())
  2331. T = Method->getSendResultType(BaseType);
  2332. else
  2333. T = Method->getReturnType();
  2334. } else if (const auto *Enumerator = dyn_cast<EnumConstantDecl>(ND)) {
  2335. T = Context.getTypeDeclType(cast<TypeDecl>(Enumerator->getDeclContext()));
  2336. T = clang::TypeName::getFullyQualifiedType(T, Context);
  2337. } else if (isa<UnresolvedUsingValueDecl>(ND)) {
  2338. /* Do nothing: ignore unresolved using declarations*/
  2339. } else if (const auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
  2340. if (!BaseType.isNull())
  2341. T = Ivar->getUsageType(BaseType);
  2342. else
  2343. T = Ivar->getType();
  2344. } else if (const auto *Value = dyn_cast<ValueDecl>(ND)) {
  2345. T = Value->getType();
  2346. } else if (const auto *Property = dyn_cast<ObjCPropertyDecl>(ND)) {
  2347. if (!BaseType.isNull())
  2348. T = Property->getUsageType(BaseType);
  2349. else
  2350. T = Property->getType();
  2351. }
  2352. if (T.isNull() || Context.hasSameType(T, Context.DependentTy))
  2353. return;
  2354. Result.AddResultTypeChunk(
  2355. GetCompletionTypeString(T, Context, Policy, Result.getAllocator()));
  2356. }
  2357. static void MaybeAddSentinel(Preprocessor &PP,
  2358. const NamedDecl *FunctionOrMethod,
  2359. CodeCompletionBuilder &Result) {
  2360. if (SentinelAttr *Sentinel = FunctionOrMethod->getAttr<SentinelAttr>())
  2361. if (Sentinel->getSentinel() == 0) {
  2362. if (PP.getLangOpts().ObjC && PP.isMacroDefined("nil"))
  2363. Result.AddTextChunk(", nil");
  2364. else if (PP.isMacroDefined("NULL"))
  2365. Result.AddTextChunk(", NULL");
  2366. else
  2367. Result.AddTextChunk(", (void*)0");
  2368. }
  2369. }
  2370. static std::string formatObjCParamQualifiers(unsigned ObjCQuals,
  2371. QualType &Type) {
  2372. std::string Result;
  2373. if (ObjCQuals & Decl::OBJC_TQ_In)
  2374. Result += "in ";
  2375. else if (ObjCQuals & Decl::OBJC_TQ_Inout)
  2376. Result += "inout ";
  2377. else if (ObjCQuals & Decl::OBJC_TQ_Out)
  2378. Result += "out ";
  2379. if (ObjCQuals & Decl::OBJC_TQ_Bycopy)
  2380. Result += "bycopy ";
  2381. else if (ObjCQuals & Decl::OBJC_TQ_Byref)
  2382. Result += "byref ";
  2383. if (ObjCQuals & Decl::OBJC_TQ_Oneway)
  2384. Result += "oneway ";
  2385. if (ObjCQuals & Decl::OBJC_TQ_CSNullability) {
  2386. if (auto nullability = AttributedType::stripOuterNullability(Type)) {
  2387. switch (*nullability) {
  2388. case NullabilityKind::NonNull:
  2389. Result += "nonnull ";
  2390. break;
  2391. case NullabilityKind::Nullable:
  2392. Result += "nullable ";
  2393. break;
  2394. case NullabilityKind::Unspecified:
  2395. Result += "null_unspecified ";
  2396. break;
  2397. case NullabilityKind::NullableResult:
  2398. llvm_unreachable("Not supported as a context-sensitive keyword!");
  2399. break;
  2400. }
  2401. }
  2402. }
  2403. return Result;
  2404. }
  2405. /// Tries to find the most appropriate type location for an Objective-C
  2406. /// block placeholder.
  2407. ///
  2408. /// This function ignores things like typedefs and qualifiers in order to
  2409. /// present the most relevant and accurate block placeholders in code completion
  2410. /// results.
  2411. static void findTypeLocationForBlockDecl(const TypeSourceInfo *TSInfo,
  2412. FunctionTypeLoc &Block,
  2413. FunctionProtoTypeLoc &BlockProto,
  2414. bool SuppressBlock = false) {
  2415. if (!TSInfo)
  2416. return;
  2417. TypeLoc TL = TSInfo->getTypeLoc().getUnqualifiedLoc();
  2418. while (true) {
  2419. // Look through typedefs.
  2420. if (!SuppressBlock) {
  2421. if (TypedefTypeLoc TypedefTL = TL.getAs<TypedefTypeLoc>()) {
  2422. if (TypeSourceInfo *InnerTSInfo =
  2423. TypedefTL.getTypedefNameDecl()->getTypeSourceInfo()) {
  2424. TL = InnerTSInfo->getTypeLoc().getUnqualifiedLoc();
  2425. continue;
  2426. }
  2427. }
  2428. // Look through qualified types
  2429. if (QualifiedTypeLoc QualifiedTL = TL.getAs<QualifiedTypeLoc>()) {
  2430. TL = QualifiedTL.getUnqualifiedLoc();
  2431. continue;
  2432. }
  2433. if (AttributedTypeLoc AttrTL = TL.getAs<AttributedTypeLoc>()) {
  2434. TL = AttrTL.getModifiedLoc();
  2435. continue;
  2436. }
  2437. }
  2438. // Try to get the function prototype behind the block pointer type,
  2439. // then we're done.
  2440. if (BlockPointerTypeLoc BlockPtr = TL.getAs<BlockPointerTypeLoc>()) {
  2441. TL = BlockPtr.getPointeeLoc().IgnoreParens();
  2442. Block = TL.getAs<FunctionTypeLoc>();
  2443. BlockProto = TL.getAs<FunctionProtoTypeLoc>();
  2444. }
  2445. break;
  2446. }
  2447. }
  2448. static std::string
  2449. formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
  2450. FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
  2451. bool SuppressBlockName = false,
  2452. bool SuppressBlock = false,
  2453. Optional<ArrayRef<QualType>> ObjCSubsts = None);
  2454. static std::string
  2455. FormatFunctionParameter(const PrintingPolicy &Policy,
  2456. const DeclaratorDecl *Param, bool SuppressName = false,
  2457. bool SuppressBlock = false,
  2458. Optional<ArrayRef<QualType>> ObjCSubsts = None) {
  2459. // Params are unavailable in FunctionTypeLoc if the FunctionType is invalid.
  2460. // It would be better to pass in the param Type, which is usually available.
  2461. // But this case is rare, so just pretend we fell back to int as elsewhere.
  2462. if (!Param)
  2463. return "int";
  2464. Decl::ObjCDeclQualifier ObjCQual = Decl::OBJC_TQ_None;
  2465. if (const auto *PVD = dyn_cast<ParmVarDecl>(Param))
  2466. ObjCQual = PVD->getObjCDeclQualifier();
  2467. bool ObjCMethodParam = isa<ObjCMethodDecl>(Param->getDeclContext());
  2468. if (Param->getType()->isDependentType() ||
  2469. !Param->getType()->isBlockPointerType()) {
  2470. // The argument for a dependent or non-block parameter is a placeholder
  2471. // containing that parameter's type.
  2472. std::string Result;
  2473. if (Param->getIdentifier() && !ObjCMethodParam && !SuppressName)
  2474. Result = std::string(Param->getIdentifier()->deuglifiedName());
  2475. QualType Type = Param->getType();
  2476. if (ObjCSubsts)
  2477. Type = Type.substObjCTypeArgs(Param->getASTContext(), *ObjCSubsts,
  2478. ObjCSubstitutionContext::Parameter);
  2479. if (ObjCMethodParam) {
  2480. Result = "(" + formatObjCParamQualifiers(ObjCQual, Type);
  2481. Result += Type.getAsString(Policy) + ")";
  2482. if (Param->getIdentifier() && !SuppressName)
  2483. Result += Param->getIdentifier()->deuglifiedName();
  2484. } else {
  2485. Type.getAsStringInternal(Result, Policy);
  2486. }
  2487. return Result;
  2488. }
  2489. // The argument for a block pointer parameter is a block literal with
  2490. // the appropriate type.
  2491. FunctionTypeLoc Block;
  2492. FunctionProtoTypeLoc BlockProto;
  2493. findTypeLocationForBlockDecl(Param->getTypeSourceInfo(), Block, BlockProto,
  2494. SuppressBlock);
  2495. // Try to retrieve the block type information from the property if this is a
  2496. // parameter in a setter.
  2497. if (!Block && ObjCMethodParam &&
  2498. cast<ObjCMethodDecl>(Param->getDeclContext())->isPropertyAccessor()) {
  2499. if (const auto *PD = cast<ObjCMethodDecl>(Param->getDeclContext())
  2500. ->findPropertyDecl(/*CheckOverrides=*/false))
  2501. findTypeLocationForBlockDecl(PD->getTypeSourceInfo(), Block, BlockProto,
  2502. SuppressBlock);
  2503. }
  2504. if (!Block) {
  2505. // We were unable to find a FunctionProtoTypeLoc with parameter names
  2506. // for the block; just use the parameter type as a placeholder.
  2507. std::string Result;
  2508. if (!ObjCMethodParam && Param->getIdentifier())
  2509. Result = std::string(Param->getIdentifier()->deuglifiedName());
  2510. QualType Type = Param->getType().getUnqualifiedType();
  2511. if (ObjCMethodParam) {
  2512. Result = Type.getAsString(Policy);
  2513. std::string Quals = formatObjCParamQualifiers(ObjCQual, Type);
  2514. if (!Quals.empty())
  2515. Result = "(" + Quals + " " + Result + ")";
  2516. if (Result.back() != ')')
  2517. Result += " ";
  2518. if (Param->getIdentifier())
  2519. Result += Param->getIdentifier()->deuglifiedName();
  2520. } else {
  2521. Type.getAsStringInternal(Result, Policy);
  2522. }
  2523. return Result;
  2524. }
  2525. // We have the function prototype behind the block pointer type, as it was
  2526. // written in the source.
  2527. return formatBlockPlaceholder(Policy, Param, Block, BlockProto,
  2528. /*SuppressBlockName=*/false, SuppressBlock,
  2529. ObjCSubsts);
  2530. }
  2531. /// Returns a placeholder string that corresponds to an Objective-C block
  2532. /// declaration.
  2533. ///
  2534. /// \param BlockDecl A declaration with an Objective-C block type.
  2535. ///
  2536. /// \param Block The most relevant type location for that block type.
  2537. ///
  2538. /// \param SuppressBlockName Determines whether or not the name of the block
  2539. /// declaration is included in the resulting string.
  2540. static std::string
  2541. formatBlockPlaceholder(const PrintingPolicy &Policy, const NamedDecl *BlockDecl,
  2542. FunctionTypeLoc &Block, FunctionProtoTypeLoc &BlockProto,
  2543. bool SuppressBlockName, bool SuppressBlock,
  2544. Optional<ArrayRef<QualType>> ObjCSubsts) {
  2545. std::string Result;
  2546. QualType ResultType = Block.getTypePtr()->getReturnType();
  2547. if (ObjCSubsts)
  2548. ResultType =
  2549. ResultType.substObjCTypeArgs(BlockDecl->getASTContext(), *ObjCSubsts,
  2550. ObjCSubstitutionContext::Result);
  2551. if (!ResultType->isVoidType() || SuppressBlock)
  2552. ResultType.getAsStringInternal(Result, Policy);
  2553. // Format the parameter list.
  2554. std::string Params;
  2555. if (!BlockProto || Block.getNumParams() == 0) {
  2556. if (BlockProto && BlockProto.getTypePtr()->isVariadic())
  2557. Params = "(...)";
  2558. else
  2559. Params = "(void)";
  2560. } else {
  2561. Params += "(";
  2562. for (unsigned I = 0, N = Block.getNumParams(); I != N; ++I) {
  2563. if (I)
  2564. Params += ", ";
  2565. Params += FormatFunctionParameter(Policy, Block.getParam(I),
  2566. /*SuppressName=*/false,
  2567. /*SuppressBlock=*/true, ObjCSubsts);
  2568. if (I == N - 1 && BlockProto.getTypePtr()->isVariadic())
  2569. Params += ", ...";
  2570. }
  2571. Params += ")";
  2572. }
  2573. if (SuppressBlock) {
  2574. // Format as a parameter.
  2575. Result = Result + " (^";
  2576. if (!SuppressBlockName && BlockDecl->getIdentifier())
  2577. Result += BlockDecl->getIdentifier()->getName();
  2578. Result += ")";
  2579. Result += Params;
  2580. } else {
  2581. // Format as a block literal argument.
  2582. Result = '^' + Result;
  2583. Result += Params;
  2584. if (!SuppressBlockName && BlockDecl->getIdentifier())
  2585. Result += BlockDecl->getIdentifier()->getName();
  2586. }
  2587. return Result;
  2588. }
  2589. static std::string GetDefaultValueString(const ParmVarDecl *Param,
  2590. const SourceManager &SM,
  2591. const LangOptions &LangOpts) {
  2592. const SourceRange SrcRange = Param->getDefaultArgRange();
  2593. CharSourceRange CharSrcRange = CharSourceRange::getTokenRange(SrcRange);
  2594. bool Invalid = CharSrcRange.isInvalid();
  2595. if (Invalid)
  2596. return "";
  2597. StringRef srcText =
  2598. Lexer::getSourceText(CharSrcRange, SM, LangOpts, &Invalid);
  2599. if (Invalid)
  2600. return "";
  2601. if (srcText.empty() || srcText == "=") {
  2602. // Lexer can't determine the value.
  2603. // This happens if the code is incorrect (for example class is forward
  2604. // declared).
  2605. return "";
  2606. }
  2607. std::string DefValue(srcText.str());
  2608. // FIXME: remove this check if the Lexer::getSourceText value is fixed and
  2609. // this value always has (or always does not have) '=' in front of it
  2610. if (DefValue.at(0) != '=') {
  2611. // If we don't have '=' in front of value.
  2612. // Lexer returns built-in types values without '=' and user-defined types
  2613. // values with it.
  2614. return " = " + DefValue;
  2615. }
  2616. return " " + DefValue;
  2617. }
  2618. /// Add function parameter chunks to the given code completion string.
  2619. static void AddFunctionParameterChunks(Preprocessor &PP,
  2620. const PrintingPolicy &Policy,
  2621. const FunctionDecl *Function,
  2622. CodeCompletionBuilder &Result,
  2623. unsigned Start = 0,
  2624. bool InOptional = false) {
  2625. bool FirstParameter = true;
  2626. for (unsigned P = Start, N = Function->getNumParams(); P != N; ++P) {
  2627. const ParmVarDecl *Param = Function->getParamDecl(P);
  2628. if (Param->hasDefaultArg() && !InOptional) {
  2629. // When we see an optional default argument, put that argument and
  2630. // the remaining default arguments into a new, optional string.
  2631. CodeCompletionBuilder Opt(Result.getAllocator(),
  2632. Result.getCodeCompletionTUInfo());
  2633. if (!FirstParameter)
  2634. Opt.AddChunk(CodeCompletionString::CK_Comma);
  2635. AddFunctionParameterChunks(PP, Policy, Function, Opt, P, true);
  2636. Result.AddOptionalChunk(Opt.TakeString());
  2637. break;
  2638. }
  2639. if (FirstParameter)
  2640. FirstParameter = false;
  2641. else
  2642. Result.AddChunk(CodeCompletionString::CK_Comma);
  2643. InOptional = false;
  2644. // Format the placeholder string.
  2645. std::string PlaceholderStr = FormatFunctionParameter(Policy, Param);
  2646. if (Param->hasDefaultArg())
  2647. PlaceholderStr +=
  2648. GetDefaultValueString(Param, PP.getSourceManager(), PP.getLangOpts());
  2649. if (Function->isVariadic() && P == N - 1)
  2650. PlaceholderStr += ", ...";
  2651. // Add the placeholder string.
  2652. Result.AddPlaceholderChunk(
  2653. Result.getAllocator().CopyString(PlaceholderStr));
  2654. }
  2655. if (const auto *Proto = Function->getType()->getAs<FunctionProtoType>())
  2656. if (Proto->isVariadic()) {
  2657. if (Proto->getNumParams() == 0)
  2658. Result.AddPlaceholderChunk("...");
  2659. MaybeAddSentinel(PP, Function, Result);
  2660. }
  2661. }
  2662. /// Add template parameter chunks to the given code completion string.
  2663. static void AddTemplateParameterChunks(
  2664. ASTContext &Context, const PrintingPolicy &Policy,
  2665. const TemplateDecl *Template, CodeCompletionBuilder &Result,
  2666. unsigned MaxParameters = 0, unsigned Start = 0, bool InDefaultArg = false) {
  2667. bool FirstParameter = true;
  2668. // Prefer to take the template parameter names from the first declaration of
  2669. // the template.
  2670. Template = cast<TemplateDecl>(Template->getCanonicalDecl());
  2671. TemplateParameterList *Params = Template->getTemplateParameters();
  2672. TemplateParameterList::iterator PEnd = Params->end();
  2673. if (MaxParameters)
  2674. PEnd = Params->begin() + MaxParameters;
  2675. for (TemplateParameterList::iterator P = Params->begin() + Start; P != PEnd;
  2676. ++P) {
  2677. bool HasDefaultArg = false;
  2678. std::string PlaceholderStr;
  2679. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
  2680. if (TTP->wasDeclaredWithTypename())
  2681. PlaceholderStr = "typename";
  2682. else if (const auto *TC = TTP->getTypeConstraint()) {
  2683. llvm::raw_string_ostream OS(PlaceholderStr);
  2684. TC->print(OS, Policy);
  2685. OS.flush();
  2686. } else
  2687. PlaceholderStr = "class";
  2688. if (TTP->getIdentifier()) {
  2689. PlaceholderStr += ' ';
  2690. PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
  2691. }
  2692. HasDefaultArg = TTP->hasDefaultArgument();
  2693. } else if (NonTypeTemplateParmDecl *NTTP =
  2694. dyn_cast<NonTypeTemplateParmDecl>(*P)) {
  2695. if (NTTP->getIdentifier())
  2696. PlaceholderStr = std::string(NTTP->getIdentifier()->deuglifiedName());
  2697. NTTP->getType().getAsStringInternal(PlaceholderStr, Policy);
  2698. HasDefaultArg = NTTP->hasDefaultArgument();
  2699. } else {
  2700. assert(isa<TemplateTemplateParmDecl>(*P));
  2701. TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
  2702. // Since putting the template argument list into the placeholder would
  2703. // be very, very long, we just use an abbreviation.
  2704. PlaceholderStr = "template<...> class";
  2705. if (TTP->getIdentifier()) {
  2706. PlaceholderStr += ' ';
  2707. PlaceholderStr += TTP->getIdentifier()->deuglifiedName();
  2708. }
  2709. HasDefaultArg = TTP->hasDefaultArgument();
  2710. }
  2711. if (HasDefaultArg && !InDefaultArg) {
  2712. // When we see an optional default argument, put that argument and
  2713. // the remaining default arguments into a new, optional string.
  2714. CodeCompletionBuilder Opt(Result.getAllocator(),
  2715. Result.getCodeCompletionTUInfo());
  2716. if (!FirstParameter)
  2717. Opt.AddChunk(CodeCompletionString::CK_Comma);
  2718. AddTemplateParameterChunks(Context, Policy, Template, Opt, MaxParameters,
  2719. P - Params->begin(), true);
  2720. Result.AddOptionalChunk(Opt.TakeString());
  2721. break;
  2722. }
  2723. InDefaultArg = false;
  2724. if (FirstParameter)
  2725. FirstParameter = false;
  2726. else
  2727. Result.AddChunk(CodeCompletionString::CK_Comma);
  2728. // Add the placeholder string.
  2729. Result.AddPlaceholderChunk(
  2730. Result.getAllocator().CopyString(PlaceholderStr));
  2731. }
  2732. }
  2733. /// Add a qualifier to the given code-completion string, if the
  2734. /// provided nested-name-specifier is non-NULL.
  2735. static void AddQualifierToCompletionString(CodeCompletionBuilder &Result,
  2736. NestedNameSpecifier *Qualifier,
  2737. bool QualifierIsInformative,
  2738. ASTContext &Context,
  2739. const PrintingPolicy &Policy) {
  2740. if (!Qualifier)
  2741. return;
  2742. std::string PrintedNNS;
  2743. {
  2744. llvm::raw_string_ostream OS(PrintedNNS);
  2745. Qualifier->print(OS, Policy);
  2746. }
  2747. if (QualifierIsInformative)
  2748. Result.AddInformativeChunk(Result.getAllocator().CopyString(PrintedNNS));
  2749. else
  2750. Result.AddTextChunk(Result.getAllocator().CopyString(PrintedNNS));
  2751. }
  2752. static void
  2753. AddFunctionTypeQualsToCompletionString(CodeCompletionBuilder &Result,
  2754. const FunctionDecl *Function) {
  2755. const auto *Proto = Function->getType()->getAs<FunctionProtoType>();
  2756. if (!Proto || !Proto->getMethodQuals())
  2757. return;
  2758. // FIXME: Add ref-qualifier!
  2759. // Handle single qualifiers without copying
  2760. if (Proto->getMethodQuals().hasOnlyConst()) {
  2761. Result.AddInformativeChunk(" const");
  2762. return;
  2763. }
  2764. if (Proto->getMethodQuals().hasOnlyVolatile()) {
  2765. Result.AddInformativeChunk(" volatile");
  2766. return;
  2767. }
  2768. if (Proto->getMethodQuals().hasOnlyRestrict()) {
  2769. Result.AddInformativeChunk(" restrict");
  2770. return;
  2771. }
  2772. // Handle multiple qualifiers.
  2773. std::string QualsStr;
  2774. if (Proto->isConst())
  2775. QualsStr += " const";
  2776. if (Proto->isVolatile())
  2777. QualsStr += " volatile";
  2778. if (Proto->isRestrict())
  2779. QualsStr += " restrict";
  2780. Result.AddInformativeChunk(Result.getAllocator().CopyString(QualsStr));
  2781. }
  2782. /// Add the name of the given declaration
  2783. static void AddTypedNameChunk(ASTContext &Context, const PrintingPolicy &Policy,
  2784. const NamedDecl *ND,
  2785. CodeCompletionBuilder &Result) {
  2786. DeclarationName Name = ND->getDeclName();
  2787. if (!Name)
  2788. return;
  2789. switch (Name.getNameKind()) {
  2790. case DeclarationName::CXXOperatorName: {
  2791. const char *OperatorName = nullptr;
  2792. switch (Name.getCXXOverloadedOperator()) {
  2793. case OO_None:
  2794. case OO_Conditional:
  2795. case NUM_OVERLOADED_OPERATORS:
  2796. OperatorName = "operator";
  2797. break;
  2798. #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
  2799. case OO_##Name: \
  2800. OperatorName = "operator" Spelling; \
  2801. break;
  2802. #define OVERLOADED_OPERATOR_MULTI(Name, Spelling, Unary, Binary, MemberOnly)
  2803. #include "clang/Basic/OperatorKinds.def"
  2804. case OO_New:
  2805. OperatorName = "operator new";
  2806. break;
  2807. case OO_Delete:
  2808. OperatorName = "operator delete";
  2809. break;
  2810. case OO_Array_New:
  2811. OperatorName = "operator new[]";
  2812. break;
  2813. case OO_Array_Delete:
  2814. OperatorName = "operator delete[]";
  2815. break;
  2816. case OO_Call:
  2817. OperatorName = "operator()";
  2818. break;
  2819. case OO_Subscript:
  2820. OperatorName = "operator[]";
  2821. break;
  2822. }
  2823. Result.AddTypedTextChunk(OperatorName);
  2824. break;
  2825. }
  2826. case DeclarationName::Identifier:
  2827. case DeclarationName::CXXConversionFunctionName:
  2828. case DeclarationName::CXXDestructorName:
  2829. case DeclarationName::CXXLiteralOperatorName:
  2830. Result.AddTypedTextChunk(
  2831. Result.getAllocator().CopyString(ND->getNameAsString()));
  2832. break;
  2833. case DeclarationName::CXXDeductionGuideName:
  2834. case DeclarationName::CXXUsingDirective:
  2835. case DeclarationName::ObjCZeroArgSelector:
  2836. case DeclarationName::ObjCOneArgSelector:
  2837. case DeclarationName::ObjCMultiArgSelector:
  2838. break;
  2839. case DeclarationName::CXXConstructorName: {
  2840. CXXRecordDecl *Record = nullptr;
  2841. QualType Ty = Name.getCXXNameType();
  2842. if (const auto *RecordTy = Ty->getAs<RecordType>())
  2843. Record = cast<CXXRecordDecl>(RecordTy->getDecl());
  2844. else if (const auto *InjectedTy = Ty->getAs<InjectedClassNameType>())
  2845. Record = InjectedTy->getDecl();
  2846. else {
  2847. Result.AddTypedTextChunk(
  2848. Result.getAllocator().CopyString(ND->getNameAsString()));
  2849. break;
  2850. }
  2851. Result.AddTypedTextChunk(
  2852. Result.getAllocator().CopyString(Record->getNameAsString()));
  2853. if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) {
  2854. Result.AddChunk(CodeCompletionString::CK_LeftAngle);
  2855. AddTemplateParameterChunks(Context, Policy, Template, Result);
  2856. Result.AddChunk(CodeCompletionString::CK_RightAngle);
  2857. }
  2858. break;
  2859. }
  2860. }
  2861. }
  2862. CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
  2863. Sema &S, const CodeCompletionContext &CCContext,
  2864. CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
  2865. bool IncludeBriefComments) {
  2866. return CreateCodeCompletionString(S.Context, S.PP, CCContext, Allocator,
  2867. CCTUInfo, IncludeBriefComments);
  2868. }
  2869. CodeCompletionString *CodeCompletionResult::CreateCodeCompletionStringForMacro(
  2870. Preprocessor &PP, CodeCompletionAllocator &Allocator,
  2871. CodeCompletionTUInfo &CCTUInfo) {
  2872. assert(Kind == RK_Macro);
  2873. CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
  2874. const MacroInfo *MI = PP.getMacroInfo(Macro);
  2875. Result.AddTypedTextChunk(Result.getAllocator().CopyString(Macro->getName()));
  2876. if (!MI || !MI->isFunctionLike())
  2877. return Result.TakeString();
  2878. // Format a function-like macro with placeholders for the arguments.
  2879. Result.AddChunk(CodeCompletionString::CK_LeftParen);
  2880. MacroInfo::param_iterator A = MI->param_begin(), AEnd = MI->param_end();
  2881. // C99 variadic macros add __VA_ARGS__ at the end. Skip it.
  2882. if (MI->isC99Varargs()) {
  2883. --AEnd;
  2884. if (A == AEnd) {
  2885. Result.AddPlaceholderChunk("...");
  2886. }
  2887. }
  2888. for (MacroInfo::param_iterator A = MI->param_begin(); A != AEnd; ++A) {
  2889. if (A != MI->param_begin())
  2890. Result.AddChunk(CodeCompletionString::CK_Comma);
  2891. if (MI->isVariadic() && (A + 1) == AEnd) {
  2892. SmallString<32> Arg = (*A)->getName();
  2893. if (MI->isC99Varargs())
  2894. Arg += ", ...";
  2895. else
  2896. Arg += "...";
  2897. Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
  2898. break;
  2899. }
  2900. // Non-variadic macros are simple.
  2901. Result.AddPlaceholderChunk(
  2902. Result.getAllocator().CopyString((*A)->getName()));
  2903. }
  2904. Result.AddChunk(CodeCompletionString::CK_RightParen);
  2905. return Result.TakeString();
  2906. }
  2907. /// If possible, create a new code completion string for the given
  2908. /// result.
  2909. ///
  2910. /// \returns Either a new, heap-allocated code completion string describing
  2911. /// how to use this result, or NULL to indicate that the string or name of the
  2912. /// result is all that is needed.
  2913. CodeCompletionString *CodeCompletionResult::CreateCodeCompletionString(
  2914. ASTContext &Ctx, Preprocessor &PP, const CodeCompletionContext &CCContext,
  2915. CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
  2916. bool IncludeBriefComments) {
  2917. if (Kind == RK_Macro)
  2918. return CreateCodeCompletionStringForMacro(PP, Allocator, CCTUInfo);
  2919. CodeCompletionBuilder Result(Allocator, CCTUInfo, Priority, Availability);
  2920. PrintingPolicy Policy = getCompletionPrintingPolicy(Ctx, PP);
  2921. if (Kind == RK_Pattern) {
  2922. Pattern->Priority = Priority;
  2923. Pattern->Availability = Availability;
  2924. if (Declaration) {
  2925. Result.addParentContext(Declaration->getDeclContext());
  2926. Pattern->ParentName = Result.getParentName();
  2927. if (const RawComment *RC =
  2928. getPatternCompletionComment(Ctx, Declaration)) {
  2929. Result.addBriefComment(RC->getBriefText(Ctx));
  2930. Pattern->BriefComment = Result.getBriefComment();
  2931. }
  2932. }
  2933. return Pattern;
  2934. }
  2935. if (Kind == RK_Keyword) {
  2936. Result.AddTypedTextChunk(Keyword);
  2937. return Result.TakeString();
  2938. }
  2939. assert(Kind == RK_Declaration && "Missed a result kind?");
  2940. return createCodeCompletionStringForDecl(
  2941. PP, Ctx, Result, IncludeBriefComments, CCContext, Policy);
  2942. }
  2943. static void printOverrideString(const CodeCompletionString &CCS,
  2944. std::string &BeforeName,
  2945. std::string &NameAndSignature) {
  2946. bool SeenTypedChunk = false;
  2947. for (auto &Chunk : CCS) {
  2948. if (Chunk.Kind == CodeCompletionString::CK_Optional) {
  2949. assert(SeenTypedChunk && "optional parameter before name");
  2950. // Note that we put all chunks inside into NameAndSignature.
  2951. printOverrideString(*Chunk.Optional, NameAndSignature, NameAndSignature);
  2952. continue;
  2953. }
  2954. SeenTypedChunk |= Chunk.Kind == CodeCompletionString::CK_TypedText;
  2955. if (SeenTypedChunk)
  2956. NameAndSignature += Chunk.Text;
  2957. else
  2958. BeforeName += Chunk.Text;
  2959. }
  2960. }
  2961. CodeCompletionString *
  2962. CodeCompletionResult::createCodeCompletionStringForOverride(
  2963. Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
  2964. bool IncludeBriefComments, const CodeCompletionContext &CCContext,
  2965. PrintingPolicy &Policy) {
  2966. auto *CCS = createCodeCompletionStringForDecl(PP, Ctx, Result,
  2967. /*IncludeBriefComments=*/false,
  2968. CCContext, Policy);
  2969. std::string BeforeName;
  2970. std::string NameAndSignature;
  2971. // For overrides all chunks go into the result, none are informative.
  2972. printOverrideString(*CCS, BeforeName, NameAndSignature);
  2973. NameAndSignature += " override";
  2974. Result.AddTextChunk(Result.getAllocator().CopyString(BeforeName));
  2975. Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  2976. Result.AddTypedTextChunk(Result.getAllocator().CopyString(NameAndSignature));
  2977. return Result.TakeString();
  2978. }
  2979. // FIXME: Right now this works well with lambdas. Add support for other functor
  2980. // types like std::function.
  2981. static const NamedDecl *extractFunctorCallOperator(const NamedDecl *ND) {
  2982. const auto *VD = dyn_cast<VarDecl>(ND);
  2983. if (!VD)
  2984. return nullptr;
  2985. const auto *RecordDecl = VD->getType()->getAsCXXRecordDecl();
  2986. if (!RecordDecl || !RecordDecl->isLambda())
  2987. return nullptr;
  2988. return RecordDecl->getLambdaCallOperator();
  2989. }
  2990. CodeCompletionString *CodeCompletionResult::createCodeCompletionStringForDecl(
  2991. Preprocessor &PP, ASTContext &Ctx, CodeCompletionBuilder &Result,
  2992. bool IncludeBriefComments, const CodeCompletionContext &CCContext,
  2993. PrintingPolicy &Policy) {
  2994. const NamedDecl *ND = Declaration;
  2995. Result.addParentContext(ND->getDeclContext());
  2996. if (IncludeBriefComments) {
  2997. // Add documentation comment, if it exists.
  2998. if (const RawComment *RC = getCompletionComment(Ctx, Declaration)) {
  2999. Result.addBriefComment(RC->getBriefText(Ctx));
  3000. }
  3001. }
  3002. if (StartsNestedNameSpecifier) {
  3003. Result.AddTypedTextChunk(
  3004. Result.getAllocator().CopyString(ND->getNameAsString()));
  3005. Result.AddTextChunk("::");
  3006. return Result.TakeString();
  3007. }
  3008. for (const auto *I : ND->specific_attrs<AnnotateAttr>())
  3009. Result.AddAnnotation(Result.getAllocator().CopyString(I->getAnnotation()));
  3010. auto AddFunctionTypeAndResult = [&](const FunctionDecl *Function) {
  3011. AddResultTypeChunk(Ctx, Policy, Function, CCContext.getBaseType(), Result);
  3012. AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
  3013. Ctx, Policy);
  3014. AddTypedNameChunk(Ctx, Policy, ND, Result);
  3015. Result.AddChunk(CodeCompletionString::CK_LeftParen);
  3016. AddFunctionParameterChunks(PP, Policy, Function, Result);
  3017. Result.AddChunk(CodeCompletionString::CK_RightParen);
  3018. AddFunctionTypeQualsToCompletionString(Result, Function);
  3019. };
  3020. if (const auto *Function = dyn_cast<FunctionDecl>(ND)) {
  3021. AddFunctionTypeAndResult(Function);
  3022. return Result.TakeString();
  3023. }
  3024. if (const auto *CallOperator =
  3025. dyn_cast_or_null<FunctionDecl>(extractFunctorCallOperator(ND))) {
  3026. AddFunctionTypeAndResult(CallOperator);
  3027. return Result.TakeString();
  3028. }
  3029. AddResultTypeChunk(Ctx, Policy, ND, CCContext.getBaseType(), Result);
  3030. if (const FunctionTemplateDecl *FunTmpl =
  3031. dyn_cast<FunctionTemplateDecl>(ND)) {
  3032. AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
  3033. Ctx, Policy);
  3034. FunctionDecl *Function = FunTmpl->getTemplatedDecl();
  3035. AddTypedNameChunk(Ctx, Policy, Function, Result);
  3036. // Figure out which template parameters are deduced (or have default
  3037. // arguments).
  3038. llvm::SmallBitVector Deduced;
  3039. Sema::MarkDeducedTemplateParameters(Ctx, FunTmpl, Deduced);
  3040. unsigned LastDeducibleArgument;
  3041. for (LastDeducibleArgument = Deduced.size(); LastDeducibleArgument > 0;
  3042. --LastDeducibleArgument) {
  3043. if (!Deduced[LastDeducibleArgument - 1]) {
  3044. // C++0x: Figure out if the template argument has a default. If so,
  3045. // the user doesn't need to type this argument.
  3046. // FIXME: We need to abstract template parameters better!
  3047. bool HasDefaultArg = false;
  3048. NamedDecl *Param = FunTmpl->getTemplateParameters()->getParam(
  3049. LastDeducibleArgument - 1);
  3050. if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
  3051. HasDefaultArg = TTP->hasDefaultArgument();
  3052. else if (NonTypeTemplateParmDecl *NTTP =
  3053. dyn_cast<NonTypeTemplateParmDecl>(Param))
  3054. HasDefaultArg = NTTP->hasDefaultArgument();
  3055. else {
  3056. assert(isa<TemplateTemplateParmDecl>(Param));
  3057. HasDefaultArg =
  3058. cast<TemplateTemplateParmDecl>(Param)->hasDefaultArgument();
  3059. }
  3060. if (!HasDefaultArg)
  3061. break;
  3062. }
  3063. }
  3064. if (LastDeducibleArgument) {
  3065. // Some of the function template arguments cannot be deduced from a
  3066. // function call, so we introduce an explicit template argument list
  3067. // containing all of the arguments up to the first deducible argument.
  3068. Result.AddChunk(CodeCompletionString::CK_LeftAngle);
  3069. AddTemplateParameterChunks(Ctx, Policy, FunTmpl, Result,
  3070. LastDeducibleArgument);
  3071. Result.AddChunk(CodeCompletionString::CK_RightAngle);
  3072. }
  3073. // Add the function parameters
  3074. Result.AddChunk(CodeCompletionString::CK_LeftParen);
  3075. AddFunctionParameterChunks(PP, Policy, Function, Result);
  3076. Result.AddChunk(CodeCompletionString::CK_RightParen);
  3077. AddFunctionTypeQualsToCompletionString(Result, Function);
  3078. return Result.TakeString();
  3079. }
  3080. if (const auto *Template = dyn_cast<TemplateDecl>(ND)) {
  3081. AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
  3082. Ctx, Policy);
  3083. Result.AddTypedTextChunk(
  3084. Result.getAllocator().CopyString(Template->getNameAsString()));
  3085. Result.AddChunk(CodeCompletionString::CK_LeftAngle);
  3086. AddTemplateParameterChunks(Ctx, Policy, Template, Result);
  3087. Result.AddChunk(CodeCompletionString::CK_RightAngle);
  3088. return Result.TakeString();
  3089. }
  3090. if (const auto *Method = dyn_cast<ObjCMethodDecl>(ND)) {
  3091. Selector Sel = Method->getSelector();
  3092. if (Sel.isUnarySelector()) {
  3093. Result.AddTypedTextChunk(
  3094. Result.getAllocator().CopyString(Sel.getNameForSlot(0)));
  3095. return Result.TakeString();
  3096. }
  3097. std::string SelName = Sel.getNameForSlot(0).str();
  3098. SelName += ':';
  3099. if (StartParameter == 0)
  3100. Result.AddTypedTextChunk(Result.getAllocator().CopyString(SelName));
  3101. else {
  3102. Result.AddInformativeChunk(Result.getAllocator().CopyString(SelName));
  3103. // If there is only one parameter, and we're past it, add an empty
  3104. // typed-text chunk since there is nothing to type.
  3105. if (Method->param_size() == 1)
  3106. Result.AddTypedTextChunk("");
  3107. }
  3108. unsigned Idx = 0;
  3109. // The extra Idx < Sel.getNumArgs() check is needed due to legacy C-style
  3110. // method parameters.
  3111. for (ObjCMethodDecl::param_const_iterator P = Method->param_begin(),
  3112. PEnd = Method->param_end();
  3113. P != PEnd && Idx < Sel.getNumArgs(); (void)++P, ++Idx) {
  3114. if (Idx > 0) {
  3115. std::string Keyword;
  3116. if (Idx > StartParameter)
  3117. Result.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  3118. if (IdentifierInfo *II = Sel.getIdentifierInfoForSlot(Idx))
  3119. Keyword += II->getName();
  3120. Keyword += ":";
  3121. if (Idx < StartParameter || AllParametersAreInformative)
  3122. Result.AddInformativeChunk(Result.getAllocator().CopyString(Keyword));
  3123. else
  3124. Result.AddTypedTextChunk(Result.getAllocator().CopyString(Keyword));
  3125. }
  3126. // If we're before the starting parameter, skip the placeholder.
  3127. if (Idx < StartParameter)
  3128. continue;
  3129. std::string Arg;
  3130. QualType ParamType = (*P)->getType();
  3131. Optional<ArrayRef<QualType>> ObjCSubsts;
  3132. if (!CCContext.getBaseType().isNull())
  3133. ObjCSubsts = CCContext.getBaseType()->getObjCSubstitutions(Method);
  3134. if (ParamType->isBlockPointerType() && !DeclaringEntity)
  3135. Arg = FormatFunctionParameter(Policy, *P, true,
  3136. /*SuppressBlock=*/false, ObjCSubsts);
  3137. else {
  3138. if (ObjCSubsts)
  3139. ParamType = ParamType.substObjCTypeArgs(
  3140. Ctx, *ObjCSubsts, ObjCSubstitutionContext::Parameter);
  3141. Arg = "(" + formatObjCParamQualifiers((*P)->getObjCDeclQualifier(),
  3142. ParamType);
  3143. Arg += ParamType.getAsString(Policy) + ")";
  3144. if (IdentifierInfo *II = (*P)->getIdentifier())
  3145. if (DeclaringEntity || AllParametersAreInformative)
  3146. Arg += II->getName();
  3147. }
  3148. if (Method->isVariadic() && (P + 1) == PEnd)
  3149. Arg += ", ...";
  3150. if (DeclaringEntity)
  3151. Result.AddTextChunk(Result.getAllocator().CopyString(Arg));
  3152. else if (AllParametersAreInformative)
  3153. Result.AddInformativeChunk(Result.getAllocator().CopyString(Arg));
  3154. else
  3155. Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Arg));
  3156. }
  3157. if (Method->isVariadic()) {
  3158. if (Method->param_size() == 0) {
  3159. if (DeclaringEntity)
  3160. Result.AddTextChunk(", ...");
  3161. else if (AllParametersAreInformative)
  3162. Result.AddInformativeChunk(", ...");
  3163. else
  3164. Result.AddPlaceholderChunk(", ...");
  3165. }
  3166. MaybeAddSentinel(PP, Method, Result);
  3167. }
  3168. return Result.TakeString();
  3169. }
  3170. if (Qualifier)
  3171. AddQualifierToCompletionString(Result, Qualifier, QualifierIsInformative,
  3172. Ctx, Policy);
  3173. Result.AddTypedTextChunk(
  3174. Result.getAllocator().CopyString(ND->getNameAsString()));
  3175. return Result.TakeString();
  3176. }
  3177. const RawComment *clang::getCompletionComment(const ASTContext &Ctx,
  3178. const NamedDecl *ND) {
  3179. if (!ND)
  3180. return nullptr;
  3181. if (auto *RC = Ctx.getRawCommentForAnyRedecl(ND))
  3182. return RC;
  3183. // Try to find comment from a property for ObjC methods.
  3184. const auto *M = dyn_cast<ObjCMethodDecl>(ND);
  3185. if (!M)
  3186. return nullptr;
  3187. const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
  3188. if (!PDecl)
  3189. return nullptr;
  3190. return Ctx.getRawCommentForAnyRedecl(PDecl);
  3191. }
  3192. const RawComment *clang::getPatternCompletionComment(const ASTContext &Ctx,
  3193. const NamedDecl *ND) {
  3194. const auto *M = dyn_cast_or_null<ObjCMethodDecl>(ND);
  3195. if (!M || !M->isPropertyAccessor())
  3196. return nullptr;
  3197. // Provide code completion comment for self.GetterName where
  3198. // GetterName is the getter method for a property with name
  3199. // different from the property name (declared via a property
  3200. // getter attribute.
  3201. const ObjCPropertyDecl *PDecl = M->findPropertyDecl();
  3202. if (!PDecl)
  3203. return nullptr;
  3204. if (PDecl->getGetterName() == M->getSelector() &&
  3205. PDecl->getIdentifier() != M->getIdentifier()) {
  3206. if (auto *RC = Ctx.getRawCommentForAnyRedecl(M))
  3207. return RC;
  3208. if (auto *RC = Ctx.getRawCommentForAnyRedecl(PDecl))
  3209. return RC;
  3210. }
  3211. return nullptr;
  3212. }
  3213. const RawComment *clang::getParameterComment(
  3214. const ASTContext &Ctx,
  3215. const CodeCompleteConsumer::OverloadCandidate &Result, unsigned ArgIndex) {
  3216. auto FDecl = Result.getFunction();
  3217. if (!FDecl)
  3218. return nullptr;
  3219. if (ArgIndex < FDecl->getNumParams())
  3220. return Ctx.getRawCommentForAnyRedecl(FDecl->getParamDecl(ArgIndex));
  3221. return nullptr;
  3222. }
  3223. static void AddOverloadAggregateChunks(const RecordDecl *RD,
  3224. const PrintingPolicy &Policy,
  3225. CodeCompletionBuilder &Result,
  3226. unsigned CurrentArg) {
  3227. unsigned ChunkIndex = 0;
  3228. auto AddChunk = [&](llvm::StringRef Placeholder) {
  3229. if (ChunkIndex > 0)
  3230. Result.AddChunk(CodeCompletionString::CK_Comma);
  3231. const char *Copy = Result.getAllocator().CopyString(Placeholder);
  3232. if (ChunkIndex == CurrentArg)
  3233. Result.AddCurrentParameterChunk(Copy);
  3234. else
  3235. Result.AddPlaceholderChunk(Copy);
  3236. ++ChunkIndex;
  3237. };
  3238. // Aggregate initialization has all bases followed by all fields.
  3239. // (Bases are not legal in C++11 but in that case we never get here).
  3240. if (auto *CRD = llvm::dyn_cast<CXXRecordDecl>(RD)) {
  3241. for (const auto &Base : CRD->bases())
  3242. AddChunk(Base.getType().getAsString(Policy));
  3243. }
  3244. for (const auto &Field : RD->fields())
  3245. AddChunk(FormatFunctionParameter(Policy, Field));
  3246. }
  3247. /// Add function overload parameter chunks to the given code completion
  3248. /// string.
  3249. static void AddOverloadParameterChunks(ASTContext &Context,
  3250. const PrintingPolicy &Policy,
  3251. const FunctionDecl *Function,
  3252. const FunctionProtoType *Prototype,
  3253. CodeCompletionBuilder &Result,
  3254. unsigned CurrentArg, unsigned Start = 0,
  3255. bool InOptional = false) {
  3256. if (!Function && !Prototype) {
  3257. Result.AddChunk(CodeCompletionString::CK_CurrentParameter, "...");
  3258. return;
  3259. }
  3260. bool FirstParameter = true;
  3261. unsigned NumParams =
  3262. Function ? Function->getNumParams() : Prototype->getNumParams();
  3263. for (unsigned P = Start; P != NumParams; ++P) {
  3264. if (Function && Function->getParamDecl(P)->hasDefaultArg() && !InOptional) {
  3265. // When we see an optional default argument, put that argument and
  3266. // the remaining default arguments into a new, optional string.
  3267. CodeCompletionBuilder Opt(Result.getAllocator(),
  3268. Result.getCodeCompletionTUInfo());
  3269. if (!FirstParameter)
  3270. Opt.AddChunk(CodeCompletionString::CK_Comma);
  3271. // Optional sections are nested.
  3272. AddOverloadParameterChunks(Context, Policy, Function, Prototype, Opt,
  3273. CurrentArg, P, /*InOptional=*/true);
  3274. Result.AddOptionalChunk(Opt.TakeString());
  3275. return;
  3276. }
  3277. if (FirstParameter)
  3278. FirstParameter = false;
  3279. else
  3280. Result.AddChunk(CodeCompletionString::CK_Comma);
  3281. InOptional = false;
  3282. // Format the placeholder string.
  3283. std::string Placeholder;
  3284. if (Function) {
  3285. const ParmVarDecl *Param = Function->getParamDecl(P);
  3286. Placeholder = FormatFunctionParameter(Policy, Param);
  3287. if (Param->hasDefaultArg())
  3288. Placeholder += GetDefaultValueString(Param, Context.getSourceManager(),
  3289. Context.getLangOpts());
  3290. } else {
  3291. Placeholder = Prototype->getParamType(P).getAsString(Policy);
  3292. }
  3293. if (P == CurrentArg)
  3294. Result.AddCurrentParameterChunk(
  3295. Result.getAllocator().CopyString(Placeholder));
  3296. else
  3297. Result.AddPlaceholderChunk(Result.getAllocator().CopyString(Placeholder));
  3298. }
  3299. if (Prototype && Prototype->isVariadic()) {
  3300. CodeCompletionBuilder Opt(Result.getAllocator(),
  3301. Result.getCodeCompletionTUInfo());
  3302. if (!FirstParameter)
  3303. Opt.AddChunk(CodeCompletionString::CK_Comma);
  3304. if (CurrentArg < NumParams)
  3305. Opt.AddPlaceholderChunk("...");
  3306. else
  3307. Opt.AddCurrentParameterChunk("...");
  3308. Result.AddOptionalChunk(Opt.TakeString());
  3309. }
  3310. }
  3311. static std::string
  3312. formatTemplateParameterPlaceholder(const NamedDecl *Param, bool &Optional,
  3313. const PrintingPolicy &Policy) {
  3314. if (const auto *Type = dyn_cast<TemplateTypeParmDecl>(Param)) {
  3315. Optional = Type->hasDefaultArgument();
  3316. } else if (const auto *NonType = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
  3317. Optional = NonType->hasDefaultArgument();
  3318. } else if (const auto *Template = dyn_cast<TemplateTemplateParmDecl>(Param)) {
  3319. Optional = Template->hasDefaultArgument();
  3320. }
  3321. std::string Result;
  3322. llvm::raw_string_ostream OS(Result);
  3323. Param->print(OS, Policy);
  3324. return Result;
  3325. }
  3326. static std::string templateResultType(const TemplateDecl *TD,
  3327. const PrintingPolicy &Policy) {
  3328. if (const auto *CTD = dyn_cast<ClassTemplateDecl>(TD))
  3329. return CTD->getTemplatedDecl()->getKindName().str();
  3330. if (const auto *VTD = dyn_cast<VarTemplateDecl>(TD))
  3331. return VTD->getTemplatedDecl()->getType().getAsString(Policy);
  3332. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(TD))
  3333. return FTD->getTemplatedDecl()->getReturnType().getAsString(Policy);
  3334. if (isa<TypeAliasTemplateDecl>(TD))
  3335. return "type";
  3336. if (isa<TemplateTemplateParmDecl>(TD))
  3337. return "class";
  3338. if (isa<ConceptDecl>(TD))
  3339. return "concept";
  3340. return "";
  3341. }
  3342. static CodeCompletionString *createTemplateSignatureString(
  3343. const TemplateDecl *TD, CodeCompletionBuilder &Builder, unsigned CurrentArg,
  3344. const PrintingPolicy &Policy) {
  3345. llvm::ArrayRef<NamedDecl *> Params = TD->getTemplateParameters()->asArray();
  3346. CodeCompletionBuilder OptionalBuilder(Builder.getAllocator(),
  3347. Builder.getCodeCompletionTUInfo());
  3348. std::string ResultType = templateResultType(TD, Policy);
  3349. if (!ResultType.empty())
  3350. Builder.AddResultTypeChunk(Builder.getAllocator().CopyString(ResultType));
  3351. Builder.AddTextChunk(
  3352. Builder.getAllocator().CopyString(TD->getNameAsString()));
  3353. Builder.AddChunk(CodeCompletionString::CK_LeftAngle);
  3354. // Initially we're writing into the main string. Once we see an optional arg
  3355. // (with default), we're writing into the nested optional chunk.
  3356. CodeCompletionBuilder *Current = &Builder;
  3357. for (unsigned I = 0; I < Params.size(); ++I) {
  3358. bool Optional = false;
  3359. std::string Placeholder =
  3360. formatTemplateParameterPlaceholder(Params[I], Optional, Policy);
  3361. if (Optional)
  3362. Current = &OptionalBuilder;
  3363. if (I > 0)
  3364. Current->AddChunk(CodeCompletionString::CK_Comma);
  3365. Current->AddChunk(I == CurrentArg
  3366. ? CodeCompletionString::CK_CurrentParameter
  3367. : CodeCompletionString::CK_Placeholder,
  3368. Current->getAllocator().CopyString(Placeholder));
  3369. }
  3370. // Add the optional chunk to the main string if we ever used it.
  3371. if (Current == &OptionalBuilder)
  3372. Builder.AddOptionalChunk(OptionalBuilder.TakeString());
  3373. Builder.AddChunk(CodeCompletionString::CK_RightAngle);
  3374. // For function templates, ResultType was the function's return type.
  3375. // Give some clue this is a function. (Don't show the possibly-bulky params).
  3376. if (isa<FunctionTemplateDecl>(TD))
  3377. Builder.AddInformativeChunk("()");
  3378. return Builder.TakeString();
  3379. }
  3380. CodeCompletionString *
  3381. CodeCompleteConsumer::OverloadCandidate::CreateSignatureString(
  3382. unsigned CurrentArg, Sema &S, CodeCompletionAllocator &Allocator,
  3383. CodeCompletionTUInfo &CCTUInfo, bool IncludeBriefComments,
  3384. bool Braced) const {
  3385. PrintingPolicy Policy = getCompletionPrintingPolicy(S);
  3386. // Show signatures of constructors as they are declared:
  3387. // vector(int n) rather than vector<string>(int n)
  3388. // This is less noisy without being less clear, and avoids tricky cases.
  3389. Policy.SuppressTemplateArgsInCXXConstructors = true;
  3390. // FIXME: Set priority, availability appropriately.
  3391. CodeCompletionBuilder Result(Allocator, CCTUInfo, 1,
  3392. CXAvailability_Available);
  3393. if (getKind() == CK_Template)
  3394. return createTemplateSignatureString(getTemplate(), Result, CurrentArg,
  3395. Policy);
  3396. FunctionDecl *FDecl = getFunction();
  3397. const FunctionProtoType *Proto =
  3398. dyn_cast_or_null<FunctionProtoType>(getFunctionType());
  3399. // First, the name/type of the callee.
  3400. if (getKind() == CK_Aggregate) {
  3401. Result.AddTextChunk(
  3402. Result.getAllocator().CopyString(getAggregate()->getName()));
  3403. } else if (FDecl) {
  3404. if (IncludeBriefComments) {
  3405. if (auto RC = getParameterComment(S.getASTContext(), *this, CurrentArg))
  3406. Result.addBriefComment(RC->getBriefText(S.getASTContext()));
  3407. }
  3408. AddResultTypeChunk(S.Context, Policy, FDecl, QualType(), Result);
  3409. std::string Name;
  3410. llvm::raw_string_ostream OS(Name);
  3411. FDecl->getDeclName().print(OS, Policy);
  3412. Result.AddTextChunk(Result.getAllocator().CopyString(OS.str()));
  3413. } else {
  3414. // Function without a declaration. Just give the return type.
  3415. Result.AddResultTypeChunk(Result.getAllocator().CopyString(
  3416. getFunctionType()->getReturnType().getAsString(Policy)));
  3417. }
  3418. // Next, the brackets and parameters.
  3419. Result.AddChunk(Braced ? CodeCompletionString::CK_LeftBrace
  3420. : CodeCompletionString::CK_LeftParen);
  3421. if (getKind() == CK_Aggregate)
  3422. AddOverloadAggregateChunks(getAggregate(), Policy, Result, CurrentArg);
  3423. else
  3424. AddOverloadParameterChunks(S.getASTContext(), Policy, FDecl, Proto, Result,
  3425. CurrentArg);
  3426. Result.AddChunk(Braced ? CodeCompletionString::CK_RightBrace
  3427. : CodeCompletionString::CK_RightParen);
  3428. return Result.TakeString();
  3429. }
  3430. unsigned clang::getMacroUsagePriority(StringRef MacroName,
  3431. const LangOptions &LangOpts,
  3432. bool PreferredTypeIsPointer) {
  3433. unsigned Priority = CCP_Macro;
  3434. // Treat the "nil", "Nil" and "NULL" macros as null pointer constants.
  3435. if (MacroName.equals("nil") || MacroName.equals("NULL") ||
  3436. MacroName.equals("Nil")) {
  3437. Priority = CCP_Constant;
  3438. if (PreferredTypeIsPointer)
  3439. Priority = Priority / CCF_SimilarTypeMatch;
  3440. }
  3441. // Treat "YES", "NO", "true", and "false" as constants.
  3442. else if (MacroName.equals("YES") || MacroName.equals("NO") ||
  3443. MacroName.equals("true") || MacroName.equals("false"))
  3444. Priority = CCP_Constant;
  3445. // Treat "bool" as a type.
  3446. else if (MacroName.equals("bool"))
  3447. Priority = CCP_Type + (LangOpts.ObjC ? CCD_bool_in_ObjC : 0);
  3448. return Priority;
  3449. }
  3450. CXCursorKind clang::getCursorKindForDecl(const Decl *D) {
  3451. if (!D)
  3452. return CXCursor_UnexposedDecl;
  3453. switch (D->getKind()) {
  3454. case Decl::Enum:
  3455. return CXCursor_EnumDecl;
  3456. case Decl::EnumConstant:
  3457. return CXCursor_EnumConstantDecl;
  3458. case Decl::Field:
  3459. return CXCursor_FieldDecl;
  3460. case Decl::Function:
  3461. return CXCursor_FunctionDecl;
  3462. case Decl::ObjCCategory:
  3463. return CXCursor_ObjCCategoryDecl;
  3464. case Decl::ObjCCategoryImpl:
  3465. return CXCursor_ObjCCategoryImplDecl;
  3466. case Decl::ObjCImplementation:
  3467. return CXCursor_ObjCImplementationDecl;
  3468. case Decl::ObjCInterface:
  3469. return CXCursor_ObjCInterfaceDecl;
  3470. case Decl::ObjCIvar:
  3471. return CXCursor_ObjCIvarDecl;
  3472. case Decl::ObjCMethod:
  3473. return cast<ObjCMethodDecl>(D)->isInstanceMethod()
  3474. ? CXCursor_ObjCInstanceMethodDecl
  3475. : CXCursor_ObjCClassMethodDecl;
  3476. case Decl::CXXMethod:
  3477. return CXCursor_CXXMethod;
  3478. case Decl::CXXConstructor:
  3479. return CXCursor_Constructor;
  3480. case Decl::CXXDestructor:
  3481. return CXCursor_Destructor;
  3482. case Decl::CXXConversion:
  3483. return CXCursor_ConversionFunction;
  3484. case Decl::ObjCProperty:
  3485. return CXCursor_ObjCPropertyDecl;
  3486. case Decl::ObjCProtocol:
  3487. return CXCursor_ObjCProtocolDecl;
  3488. case Decl::ParmVar:
  3489. return CXCursor_ParmDecl;
  3490. case Decl::Typedef:
  3491. return CXCursor_TypedefDecl;
  3492. case Decl::TypeAlias:
  3493. return CXCursor_TypeAliasDecl;
  3494. case Decl::TypeAliasTemplate:
  3495. return CXCursor_TypeAliasTemplateDecl;
  3496. case Decl::Var:
  3497. return CXCursor_VarDecl;
  3498. case Decl::Namespace:
  3499. return CXCursor_Namespace;
  3500. case Decl::NamespaceAlias:
  3501. return CXCursor_NamespaceAlias;
  3502. case Decl::TemplateTypeParm:
  3503. return CXCursor_TemplateTypeParameter;
  3504. case Decl::NonTypeTemplateParm:
  3505. return CXCursor_NonTypeTemplateParameter;
  3506. case Decl::TemplateTemplateParm:
  3507. return CXCursor_TemplateTemplateParameter;
  3508. case Decl::FunctionTemplate:
  3509. return CXCursor_FunctionTemplate;
  3510. case Decl::ClassTemplate:
  3511. return CXCursor_ClassTemplate;
  3512. case Decl::AccessSpec:
  3513. return CXCursor_CXXAccessSpecifier;
  3514. case Decl::ClassTemplatePartialSpecialization:
  3515. return CXCursor_ClassTemplatePartialSpecialization;
  3516. case Decl::UsingDirective:
  3517. return CXCursor_UsingDirective;
  3518. case Decl::StaticAssert:
  3519. return CXCursor_StaticAssert;
  3520. case Decl::Friend:
  3521. return CXCursor_FriendDecl;
  3522. case Decl::TranslationUnit:
  3523. return CXCursor_TranslationUnit;
  3524. case Decl::Using:
  3525. case Decl::UnresolvedUsingValue:
  3526. case Decl::UnresolvedUsingTypename:
  3527. return CXCursor_UsingDeclaration;
  3528. case Decl::UsingEnum:
  3529. return CXCursor_EnumDecl;
  3530. case Decl::ObjCPropertyImpl:
  3531. switch (cast<ObjCPropertyImplDecl>(D)->getPropertyImplementation()) {
  3532. case ObjCPropertyImplDecl::Dynamic:
  3533. return CXCursor_ObjCDynamicDecl;
  3534. case ObjCPropertyImplDecl::Synthesize:
  3535. return CXCursor_ObjCSynthesizeDecl;
  3536. }
  3537. llvm_unreachable("Unexpected Kind!");
  3538. case Decl::Import:
  3539. return CXCursor_ModuleImportDecl;
  3540. case Decl::ObjCTypeParam:
  3541. return CXCursor_TemplateTypeParameter;
  3542. default:
  3543. if (const auto *TD = dyn_cast<TagDecl>(D)) {
  3544. switch (TD->getTagKind()) {
  3545. case TTK_Interface: // fall through
  3546. case TTK_Struct:
  3547. return CXCursor_StructDecl;
  3548. case TTK_Class:
  3549. return CXCursor_ClassDecl;
  3550. case TTK_Union:
  3551. return CXCursor_UnionDecl;
  3552. case TTK_Enum:
  3553. return CXCursor_EnumDecl;
  3554. }
  3555. }
  3556. }
  3557. return CXCursor_UnexposedDecl;
  3558. }
  3559. static void AddMacroResults(Preprocessor &PP, ResultBuilder &Results,
  3560. bool LoadExternal, bool IncludeUndefined,
  3561. bool TargetTypeIsPointer = false) {
  3562. typedef CodeCompletionResult Result;
  3563. Results.EnterNewScope();
  3564. for (Preprocessor::macro_iterator M = PP.macro_begin(LoadExternal),
  3565. MEnd = PP.macro_end(LoadExternal);
  3566. M != MEnd; ++M) {
  3567. auto MD = PP.getMacroDefinition(M->first);
  3568. if (IncludeUndefined || MD) {
  3569. MacroInfo *MI = MD.getMacroInfo();
  3570. if (MI && MI->isUsedForHeaderGuard())
  3571. continue;
  3572. Results.AddResult(
  3573. Result(M->first, MI,
  3574. getMacroUsagePriority(M->first->getName(), PP.getLangOpts(),
  3575. TargetTypeIsPointer)));
  3576. }
  3577. }
  3578. Results.ExitScope();
  3579. }
  3580. static void AddPrettyFunctionResults(const LangOptions &LangOpts,
  3581. ResultBuilder &Results) {
  3582. typedef CodeCompletionResult Result;
  3583. Results.EnterNewScope();
  3584. Results.AddResult(Result("__PRETTY_FUNCTION__", CCP_Constant));
  3585. Results.AddResult(Result("__FUNCTION__", CCP_Constant));
  3586. if (LangOpts.C99 || LangOpts.CPlusPlus11)
  3587. Results.AddResult(Result("__func__", CCP_Constant));
  3588. Results.ExitScope();
  3589. }
  3590. static void HandleCodeCompleteResults(Sema *S,
  3591. CodeCompleteConsumer *CodeCompleter,
  3592. CodeCompletionContext Context,
  3593. CodeCompletionResult *Results,
  3594. unsigned NumResults) {
  3595. if (CodeCompleter)
  3596. CodeCompleter->ProcessCodeCompleteResults(*S, Context, Results, NumResults);
  3597. }
  3598. static CodeCompletionContext
  3599. mapCodeCompletionContext(Sema &S, Sema::ParserCompletionContext PCC) {
  3600. switch (PCC) {
  3601. case Sema::PCC_Namespace:
  3602. return CodeCompletionContext::CCC_TopLevel;
  3603. case Sema::PCC_Class:
  3604. return CodeCompletionContext::CCC_ClassStructUnion;
  3605. case Sema::PCC_ObjCInterface:
  3606. return CodeCompletionContext::CCC_ObjCInterface;
  3607. case Sema::PCC_ObjCImplementation:
  3608. return CodeCompletionContext::CCC_ObjCImplementation;
  3609. case Sema::PCC_ObjCInstanceVariableList:
  3610. return CodeCompletionContext::CCC_ObjCIvarList;
  3611. case Sema::PCC_Template:
  3612. case Sema::PCC_MemberTemplate:
  3613. if (S.CurContext->isFileContext())
  3614. return CodeCompletionContext::CCC_TopLevel;
  3615. if (S.CurContext->isRecord())
  3616. return CodeCompletionContext::CCC_ClassStructUnion;
  3617. return CodeCompletionContext::CCC_Other;
  3618. case Sema::PCC_RecoveryInFunction:
  3619. return CodeCompletionContext::CCC_Recovery;
  3620. case Sema::PCC_ForInit:
  3621. if (S.getLangOpts().CPlusPlus || S.getLangOpts().C99 ||
  3622. S.getLangOpts().ObjC)
  3623. return CodeCompletionContext::CCC_ParenthesizedExpression;
  3624. else
  3625. return CodeCompletionContext::CCC_Expression;
  3626. case Sema::PCC_Expression:
  3627. return CodeCompletionContext::CCC_Expression;
  3628. case Sema::PCC_Condition:
  3629. return CodeCompletionContext(CodeCompletionContext::CCC_Expression,
  3630. S.getASTContext().BoolTy);
  3631. case Sema::PCC_Statement:
  3632. return CodeCompletionContext::CCC_Statement;
  3633. case Sema::PCC_Type:
  3634. return CodeCompletionContext::CCC_Type;
  3635. case Sema::PCC_ParenthesizedExpression:
  3636. return CodeCompletionContext::CCC_ParenthesizedExpression;
  3637. case Sema::PCC_LocalDeclarationSpecifiers:
  3638. return CodeCompletionContext::CCC_Type;
  3639. }
  3640. llvm_unreachable("Invalid ParserCompletionContext!");
  3641. }
  3642. /// If we're in a C++ virtual member function, add completion results
  3643. /// that invoke the functions we override, since it's common to invoke the
  3644. /// overridden function as well as adding new functionality.
  3645. ///
  3646. /// \param S The semantic analysis object for which we are generating results.
  3647. ///
  3648. /// \param InContext This context in which the nested-name-specifier preceding
  3649. /// the code-completion point
  3650. static void MaybeAddOverrideCalls(Sema &S, DeclContext *InContext,
  3651. ResultBuilder &Results) {
  3652. // Look through blocks.
  3653. DeclContext *CurContext = S.CurContext;
  3654. while (isa<BlockDecl>(CurContext))
  3655. CurContext = CurContext->getParent();
  3656. CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(CurContext);
  3657. if (!Method || !Method->isVirtual())
  3658. return;
  3659. // We need to have names for all of the parameters, if we're going to
  3660. // generate a forwarding call.
  3661. for (auto P : Method->parameters())
  3662. if (!P->getDeclName())
  3663. return;
  3664. PrintingPolicy Policy = getCompletionPrintingPolicy(S);
  3665. for (const CXXMethodDecl *Overridden : Method->overridden_methods()) {
  3666. CodeCompletionBuilder Builder(Results.getAllocator(),
  3667. Results.getCodeCompletionTUInfo());
  3668. if (Overridden->getCanonicalDecl() == Method->getCanonicalDecl())
  3669. continue;
  3670. // If we need a nested-name-specifier, add one now.
  3671. if (!InContext) {
  3672. NestedNameSpecifier *NNS = getRequiredQualification(
  3673. S.Context, CurContext, Overridden->getDeclContext());
  3674. if (NNS) {
  3675. std::string Str;
  3676. llvm::raw_string_ostream OS(Str);
  3677. NNS->print(OS, Policy);
  3678. Builder.AddTextChunk(Results.getAllocator().CopyString(OS.str()));
  3679. }
  3680. } else if (!InContext->Equals(Overridden->getDeclContext()))
  3681. continue;
  3682. Builder.AddTypedTextChunk(
  3683. Results.getAllocator().CopyString(Overridden->getNameAsString()));
  3684. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  3685. bool FirstParam = true;
  3686. for (auto P : Method->parameters()) {
  3687. if (FirstParam)
  3688. FirstParam = false;
  3689. else
  3690. Builder.AddChunk(CodeCompletionString::CK_Comma);
  3691. Builder.AddPlaceholderChunk(
  3692. Results.getAllocator().CopyString(P->getIdentifier()->getName()));
  3693. }
  3694. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  3695. Results.AddResult(CodeCompletionResult(
  3696. Builder.TakeString(), CCP_SuperCompletion, CXCursor_CXXMethod,
  3697. CXAvailability_Available, Overridden));
  3698. Results.Ignore(Overridden);
  3699. }
  3700. }
  3701. void Sema::CodeCompleteModuleImport(SourceLocation ImportLoc,
  3702. ModuleIdPath Path) {
  3703. typedef CodeCompletionResult Result;
  3704. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  3705. CodeCompleter->getCodeCompletionTUInfo(),
  3706. CodeCompletionContext::CCC_Other);
  3707. Results.EnterNewScope();
  3708. CodeCompletionAllocator &Allocator = Results.getAllocator();
  3709. CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
  3710. typedef CodeCompletionResult Result;
  3711. if (Path.empty()) {
  3712. // Enumerate all top-level modules.
  3713. SmallVector<Module *, 8> Modules;
  3714. PP.getHeaderSearchInfo().collectAllModules(Modules);
  3715. for (unsigned I = 0, N = Modules.size(); I != N; ++I) {
  3716. Builder.AddTypedTextChunk(
  3717. Builder.getAllocator().CopyString(Modules[I]->Name));
  3718. Results.AddResult(Result(
  3719. Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
  3720. Modules[I]->isAvailable() ? CXAvailability_Available
  3721. : CXAvailability_NotAvailable));
  3722. }
  3723. } else if (getLangOpts().Modules) {
  3724. // Load the named module.
  3725. Module *Mod =
  3726. PP.getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
  3727. /*IsInclusionDirective=*/false);
  3728. // Enumerate submodules.
  3729. if (Mod) {
  3730. for (Module::submodule_iterator Sub = Mod->submodule_begin(),
  3731. SubEnd = Mod->submodule_end();
  3732. Sub != SubEnd; ++Sub) {
  3733. Builder.AddTypedTextChunk(
  3734. Builder.getAllocator().CopyString((*Sub)->Name));
  3735. Results.AddResult(Result(
  3736. Builder.TakeString(), CCP_Declaration, CXCursor_ModuleImportDecl,
  3737. (*Sub)->isAvailable() ? CXAvailability_Available
  3738. : CXAvailability_NotAvailable));
  3739. }
  3740. }
  3741. }
  3742. Results.ExitScope();
  3743. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  3744. Results.data(), Results.size());
  3745. }
  3746. void Sema::CodeCompleteOrdinaryName(Scope *S,
  3747. ParserCompletionContext CompletionContext) {
  3748. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  3749. CodeCompleter->getCodeCompletionTUInfo(),
  3750. mapCodeCompletionContext(*this, CompletionContext));
  3751. Results.EnterNewScope();
  3752. // Determine how to filter results, e.g., so that the names of
  3753. // values (functions, enumerators, function templates, etc.) are
  3754. // only allowed where we can have an expression.
  3755. switch (CompletionContext) {
  3756. case PCC_Namespace:
  3757. case PCC_Class:
  3758. case PCC_ObjCInterface:
  3759. case PCC_ObjCImplementation:
  3760. case PCC_ObjCInstanceVariableList:
  3761. case PCC_Template:
  3762. case PCC_MemberTemplate:
  3763. case PCC_Type:
  3764. case PCC_LocalDeclarationSpecifiers:
  3765. Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
  3766. break;
  3767. case PCC_Statement:
  3768. case PCC_ParenthesizedExpression:
  3769. case PCC_Expression:
  3770. case PCC_ForInit:
  3771. case PCC_Condition:
  3772. if (WantTypesInContext(CompletionContext, getLangOpts()))
  3773. Results.setFilter(&ResultBuilder::IsOrdinaryName);
  3774. else
  3775. Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
  3776. if (getLangOpts().CPlusPlus)
  3777. MaybeAddOverrideCalls(*this, /*InContext=*/nullptr, Results);
  3778. break;
  3779. case PCC_RecoveryInFunction:
  3780. // Unfiltered
  3781. break;
  3782. }
  3783. // If we are in a C++ non-static member function, check the qualifiers on
  3784. // the member function to filter/prioritize the results list.
  3785. auto ThisType = getCurrentThisType();
  3786. if (!ThisType.isNull())
  3787. Results.setObjectTypeQualifiers(ThisType->getPointeeType().getQualifiers(),
  3788. VK_LValue);
  3789. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  3790. LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
  3791. CodeCompleter->includeGlobals(),
  3792. CodeCompleter->loadExternal());
  3793. AddOrdinaryNameResults(CompletionContext, S, *this, Results);
  3794. Results.ExitScope();
  3795. switch (CompletionContext) {
  3796. case PCC_ParenthesizedExpression:
  3797. case PCC_Expression:
  3798. case PCC_Statement:
  3799. case PCC_RecoveryInFunction:
  3800. if (S->getFnParent())
  3801. AddPrettyFunctionResults(getLangOpts(), Results);
  3802. break;
  3803. case PCC_Namespace:
  3804. case PCC_Class:
  3805. case PCC_ObjCInterface:
  3806. case PCC_ObjCImplementation:
  3807. case PCC_ObjCInstanceVariableList:
  3808. case PCC_Template:
  3809. case PCC_MemberTemplate:
  3810. case PCC_ForInit:
  3811. case PCC_Condition:
  3812. case PCC_Type:
  3813. case PCC_LocalDeclarationSpecifiers:
  3814. break;
  3815. }
  3816. if (CodeCompleter->includeMacros())
  3817. AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
  3818. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  3819. Results.data(), Results.size());
  3820. }
  3821. static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
  3822. ParsedType Receiver,
  3823. ArrayRef<IdentifierInfo *> SelIdents,
  3824. bool AtArgumentExpression, bool IsSuper,
  3825. ResultBuilder &Results);
  3826. void Sema::CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
  3827. bool AllowNonIdentifiers,
  3828. bool AllowNestedNameSpecifiers) {
  3829. typedef CodeCompletionResult Result;
  3830. ResultBuilder Results(
  3831. *this, CodeCompleter->getAllocator(),
  3832. CodeCompleter->getCodeCompletionTUInfo(),
  3833. AllowNestedNameSpecifiers
  3834. // FIXME: Try to separate codepath leading here to deduce whether we
  3835. // need an existing symbol or a new one.
  3836. ? CodeCompletionContext::CCC_SymbolOrNewName
  3837. : CodeCompletionContext::CCC_NewName);
  3838. Results.EnterNewScope();
  3839. // Type qualifiers can come after names.
  3840. Results.AddResult(Result("const"));
  3841. Results.AddResult(Result("volatile"));
  3842. if (getLangOpts().C99)
  3843. Results.AddResult(Result("restrict"));
  3844. if (getLangOpts().CPlusPlus) {
  3845. if (getLangOpts().CPlusPlus11 &&
  3846. (DS.getTypeSpecType() == DeclSpec::TST_class ||
  3847. DS.getTypeSpecType() == DeclSpec::TST_struct))
  3848. Results.AddResult("final");
  3849. if (AllowNonIdentifiers) {
  3850. Results.AddResult(Result("operator"));
  3851. }
  3852. // Add nested-name-specifiers.
  3853. if (AllowNestedNameSpecifiers) {
  3854. Results.allowNestedNameSpecifiers();
  3855. Results.setFilter(&ResultBuilder::IsImpossibleToSatisfy);
  3856. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  3857. LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
  3858. CodeCompleter->includeGlobals(),
  3859. CodeCompleter->loadExternal());
  3860. Results.setFilter(nullptr);
  3861. }
  3862. }
  3863. Results.ExitScope();
  3864. // If we're in a context where we might have an expression (rather than a
  3865. // declaration), and what we've seen so far is an Objective-C type that could
  3866. // be a receiver of a class message, this may be a class message send with
  3867. // the initial opening bracket '[' missing. Add appropriate completions.
  3868. if (AllowNonIdentifiers && !AllowNestedNameSpecifiers &&
  3869. DS.getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
  3870. DS.getTypeSpecType() == DeclSpec::TST_typename &&
  3871. DS.getTypeSpecComplex() == DeclSpec::TSC_unspecified &&
  3872. DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
  3873. !DS.isTypeAltiVecVector() && S &&
  3874. (S->getFlags() & Scope::DeclScope) != 0 &&
  3875. (S->getFlags() & (Scope::ClassScope | Scope::TemplateParamScope |
  3876. Scope::FunctionPrototypeScope | Scope::AtCatchScope)) ==
  3877. 0) {
  3878. ParsedType T = DS.getRepAsType();
  3879. if (!T.get().isNull() && T.get()->isObjCObjectOrInterfaceType())
  3880. AddClassMessageCompletions(*this, S, T, None, false, false, Results);
  3881. }
  3882. // Note that we intentionally suppress macro results here, since we do not
  3883. // encourage using macros to produce the names of entities.
  3884. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  3885. Results.data(), Results.size());
  3886. }
  3887. static const char *underscoreAttrScope(llvm::StringRef Scope) {
  3888. if (Scope == "clang")
  3889. return "_Clang";
  3890. if (Scope == "gnu")
  3891. return "__gnu__";
  3892. return nullptr;
  3893. }
  3894. static const char *noUnderscoreAttrScope(llvm::StringRef Scope) {
  3895. if (Scope == "_Clang")
  3896. return "clang";
  3897. if (Scope == "__gnu__")
  3898. return "gnu";
  3899. return nullptr;
  3900. }
  3901. void Sema::CodeCompleteAttribute(AttributeCommonInfo::Syntax Syntax,
  3902. AttributeCompletion Completion,
  3903. const IdentifierInfo *InScope) {
  3904. if (Completion == AttributeCompletion::None)
  3905. return;
  3906. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  3907. CodeCompleter->getCodeCompletionTUInfo(),
  3908. CodeCompletionContext::CCC_Attribute);
  3909. // We're going to iterate over the normalized spellings of the attribute.
  3910. // These don't include "underscore guarding": the normalized spelling is
  3911. // clang::foo but you can also write _Clang::__foo__.
  3912. //
  3913. // (Clang supports a mix like clang::__foo__ but we won't suggest it: either
  3914. // you care about clashing with macros or you don't).
  3915. //
  3916. // So if we're already in a scope, we determine its canonical spellings
  3917. // (for comparison with normalized attr spelling) and remember whether it was
  3918. // underscore-guarded (so we know how to spell contained attributes).
  3919. llvm::StringRef InScopeName;
  3920. bool InScopeUnderscore = false;
  3921. if (InScope) {
  3922. InScopeName = InScope->getName();
  3923. if (const char *NoUnderscore = noUnderscoreAttrScope(InScopeName)) {
  3924. InScopeName = NoUnderscore;
  3925. InScopeUnderscore = true;
  3926. }
  3927. }
  3928. bool SyntaxSupportsGuards = Syntax == AttributeCommonInfo::AS_GNU ||
  3929. Syntax == AttributeCommonInfo::AS_CXX11 ||
  3930. Syntax == AttributeCommonInfo::AS_C2x;
  3931. llvm::DenseSet<llvm::StringRef> FoundScopes;
  3932. auto AddCompletions = [&](const ParsedAttrInfo &A) {
  3933. if (A.IsTargetSpecific && !A.existsInTarget(Context.getTargetInfo()))
  3934. return;
  3935. if (!A.acceptsLangOpts(getLangOpts()))
  3936. return;
  3937. for (const auto &S : A.Spellings) {
  3938. if (S.Syntax != Syntax)
  3939. continue;
  3940. llvm::StringRef Name = S.NormalizedFullName;
  3941. llvm::StringRef Scope;
  3942. if ((Syntax == AttributeCommonInfo::AS_CXX11 ||
  3943. Syntax == AttributeCommonInfo::AS_C2x)) {
  3944. std::tie(Scope, Name) = Name.split("::");
  3945. if (Name.empty()) // oops, unscoped
  3946. std::swap(Name, Scope);
  3947. }
  3948. // Do we just want a list of scopes rather than attributes?
  3949. if (Completion == AttributeCompletion::Scope) {
  3950. // Make sure to emit each scope only once.
  3951. if (!Scope.empty() && FoundScopes.insert(Scope).second) {
  3952. Results.AddResult(
  3953. CodeCompletionResult(Results.getAllocator().CopyString(Scope)));
  3954. // Include alternate form (__gnu__ instead of gnu).
  3955. if (const char *Scope2 = underscoreAttrScope(Scope))
  3956. Results.AddResult(CodeCompletionResult(Scope2));
  3957. }
  3958. continue;
  3959. }
  3960. // If a scope was specified, it must match but we don't need to print it.
  3961. if (!InScopeName.empty()) {
  3962. if (Scope != InScopeName)
  3963. continue;
  3964. Scope = "";
  3965. }
  3966. auto Add = [&](llvm::StringRef Scope, llvm::StringRef Name,
  3967. bool Underscores) {
  3968. CodeCompletionBuilder Builder(Results.getAllocator(),
  3969. Results.getCodeCompletionTUInfo());
  3970. llvm::SmallString<32> Text;
  3971. if (!Scope.empty()) {
  3972. Text.append(Scope);
  3973. Text.append("::");
  3974. }
  3975. if (Underscores)
  3976. Text.append("__");
  3977. Text.append(Name);
  3978. if (Underscores)
  3979. Text.append("__");
  3980. Builder.AddTypedTextChunk(Results.getAllocator().CopyString(Text));
  3981. if (!A.ArgNames.empty()) {
  3982. Builder.AddChunk(CodeCompletionString::CK_LeftParen, "(");
  3983. bool First = true;
  3984. for (const char *Arg : A.ArgNames) {
  3985. if (!First)
  3986. Builder.AddChunk(CodeCompletionString::CK_Comma, ", ");
  3987. First = false;
  3988. Builder.AddPlaceholderChunk(Arg);
  3989. }
  3990. Builder.AddChunk(CodeCompletionString::CK_RightParen, ")");
  3991. }
  3992. Results.AddResult(Builder.TakeString());
  3993. };
  3994. // Generate the non-underscore-guarded result.
  3995. // Note this is (a suffix of) the NormalizedFullName, no need to copy.
  3996. // If an underscore-guarded scope was specified, only the
  3997. // underscore-guarded attribute name is relevant.
  3998. if (!InScopeUnderscore)
  3999. Add(Scope, Name, /*Underscores=*/false);
  4000. // Generate the underscore-guarded version, for syntaxes that support it.
  4001. // We skip this if the scope was already spelled and not guarded, or
  4002. // we must spell it and can't guard it.
  4003. if (!(InScope && !InScopeUnderscore) && SyntaxSupportsGuards) {
  4004. llvm::SmallString<32> Guarded;
  4005. if (Scope.empty()) {
  4006. Add(Scope, Name, /*Underscores=*/true);
  4007. } else {
  4008. const char *GuardedScope = underscoreAttrScope(Scope);
  4009. if (!GuardedScope)
  4010. continue;
  4011. Add(GuardedScope, Name, /*Underscores=*/true);
  4012. }
  4013. }
  4014. // It may be nice to include the Kind so we can look up the docs later.
  4015. }
  4016. };
  4017. for (const auto *A : ParsedAttrInfo::getAllBuiltin())
  4018. AddCompletions(*A);
  4019. for (const auto &Entry : ParsedAttrInfoRegistry::entries())
  4020. AddCompletions(*Entry.instantiate());
  4021. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  4022. Results.data(), Results.size());
  4023. }
  4024. struct Sema::CodeCompleteExpressionData {
  4025. CodeCompleteExpressionData(QualType PreferredType = QualType(),
  4026. bool IsParenthesized = false)
  4027. : PreferredType(PreferredType), IntegralConstantExpression(false),
  4028. ObjCCollection(false), IsParenthesized(IsParenthesized) {}
  4029. QualType PreferredType;
  4030. bool IntegralConstantExpression;
  4031. bool ObjCCollection;
  4032. bool IsParenthesized;
  4033. SmallVector<Decl *, 4> IgnoreDecls;
  4034. };
  4035. namespace {
  4036. /// Information that allows to avoid completing redundant enumerators.
  4037. struct CoveredEnumerators {
  4038. llvm::SmallPtrSet<EnumConstantDecl *, 8> Seen;
  4039. NestedNameSpecifier *SuggestedQualifier = nullptr;
  4040. };
  4041. } // namespace
  4042. static void AddEnumerators(ResultBuilder &Results, ASTContext &Context,
  4043. EnumDecl *Enum, DeclContext *CurContext,
  4044. const CoveredEnumerators &Enumerators) {
  4045. NestedNameSpecifier *Qualifier = Enumerators.SuggestedQualifier;
  4046. if (Context.getLangOpts().CPlusPlus && !Qualifier && Enumerators.Seen.empty()) {
  4047. // If there are no prior enumerators in C++, check whether we have to
  4048. // qualify the names of the enumerators that we suggest, because they
  4049. // may not be visible in this scope.
  4050. Qualifier = getRequiredQualification(Context, CurContext, Enum);
  4051. }
  4052. Results.EnterNewScope();
  4053. for (auto *E : Enum->enumerators()) {
  4054. if (Enumerators.Seen.count(E))
  4055. continue;
  4056. CodeCompletionResult R(E, CCP_EnumInCase, Qualifier);
  4057. Results.AddResult(R, CurContext, nullptr, false);
  4058. }
  4059. Results.ExitScope();
  4060. }
  4061. /// Try to find a corresponding FunctionProtoType for function-like types (e.g.
  4062. /// function pointers, std::function, etc).
  4063. static const FunctionProtoType *TryDeconstructFunctionLike(QualType T) {
  4064. assert(!T.isNull());
  4065. // Try to extract first template argument from std::function<> and similar.
  4066. // Note we only handle the sugared types, they closely match what users wrote.
  4067. // We explicitly choose to not handle ClassTemplateSpecializationDecl.
  4068. if (auto *Specialization = T->getAs<TemplateSpecializationType>()) {
  4069. if (Specialization->getNumArgs() != 1)
  4070. return nullptr;
  4071. const TemplateArgument &Argument = Specialization->getArg(0);
  4072. if (Argument.getKind() != TemplateArgument::Type)
  4073. return nullptr;
  4074. return Argument.getAsType()->getAs<FunctionProtoType>();
  4075. }
  4076. // Handle other cases.
  4077. if (T->isPointerType())
  4078. T = T->getPointeeType();
  4079. return T->getAs<FunctionProtoType>();
  4080. }
  4081. /// Adds a pattern completion for a lambda expression with the specified
  4082. /// parameter types and placeholders for parameter names.
  4083. static void AddLambdaCompletion(ResultBuilder &Results,
  4084. llvm::ArrayRef<QualType> Parameters,
  4085. const LangOptions &LangOpts) {
  4086. if (!Results.includeCodePatterns())
  4087. return;
  4088. CodeCompletionBuilder Completion(Results.getAllocator(),
  4089. Results.getCodeCompletionTUInfo());
  4090. // [](<parameters>) {}
  4091. Completion.AddChunk(CodeCompletionString::CK_LeftBracket);
  4092. Completion.AddPlaceholderChunk("=");
  4093. Completion.AddChunk(CodeCompletionString::CK_RightBracket);
  4094. if (!Parameters.empty()) {
  4095. Completion.AddChunk(CodeCompletionString::CK_LeftParen);
  4096. bool First = true;
  4097. for (auto Parameter : Parameters) {
  4098. if (!First)
  4099. Completion.AddChunk(CodeCompletionString::ChunkKind::CK_Comma);
  4100. else
  4101. First = false;
  4102. constexpr llvm::StringLiteral NamePlaceholder = "!#!NAME_GOES_HERE!#!";
  4103. std::string Type = std::string(NamePlaceholder);
  4104. Parameter.getAsStringInternal(Type, PrintingPolicy(LangOpts));
  4105. llvm::StringRef Prefix, Suffix;
  4106. std::tie(Prefix, Suffix) = llvm::StringRef(Type).split(NamePlaceholder);
  4107. Prefix = Prefix.rtrim();
  4108. Suffix = Suffix.ltrim();
  4109. Completion.AddTextChunk(Completion.getAllocator().CopyString(Prefix));
  4110. Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  4111. Completion.AddPlaceholderChunk("parameter");
  4112. Completion.AddTextChunk(Completion.getAllocator().CopyString(Suffix));
  4113. };
  4114. Completion.AddChunk(CodeCompletionString::CK_RightParen);
  4115. }
  4116. Completion.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
  4117. Completion.AddChunk(CodeCompletionString::CK_LeftBrace);
  4118. Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  4119. Completion.AddPlaceholderChunk("body");
  4120. Completion.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  4121. Completion.AddChunk(CodeCompletionString::CK_RightBrace);
  4122. Results.AddResult(Completion.TakeString());
  4123. }
  4124. /// Perform code-completion in an expression context when we know what
  4125. /// type we're looking for.
  4126. void Sema::CodeCompleteExpression(Scope *S,
  4127. const CodeCompleteExpressionData &Data) {
  4128. ResultBuilder Results(
  4129. *this, CodeCompleter->getAllocator(),
  4130. CodeCompleter->getCodeCompletionTUInfo(),
  4131. CodeCompletionContext(
  4132. Data.IsParenthesized
  4133. ? CodeCompletionContext::CCC_ParenthesizedExpression
  4134. : CodeCompletionContext::CCC_Expression,
  4135. Data.PreferredType));
  4136. auto PCC =
  4137. Data.IsParenthesized ? PCC_ParenthesizedExpression : PCC_Expression;
  4138. if (Data.ObjCCollection)
  4139. Results.setFilter(&ResultBuilder::IsObjCCollection);
  4140. else if (Data.IntegralConstantExpression)
  4141. Results.setFilter(&ResultBuilder::IsIntegralConstantValue);
  4142. else if (WantTypesInContext(PCC, getLangOpts()))
  4143. Results.setFilter(&ResultBuilder::IsOrdinaryName);
  4144. else
  4145. Results.setFilter(&ResultBuilder::IsOrdinaryNonTypeName);
  4146. if (!Data.PreferredType.isNull())
  4147. Results.setPreferredType(Data.PreferredType.getNonReferenceType());
  4148. // Ignore any declarations that we were told that we don't care about.
  4149. for (unsigned I = 0, N = Data.IgnoreDecls.size(); I != N; ++I)
  4150. Results.Ignore(Data.IgnoreDecls[I]);
  4151. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  4152. LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
  4153. CodeCompleter->includeGlobals(),
  4154. CodeCompleter->loadExternal());
  4155. Results.EnterNewScope();
  4156. AddOrdinaryNameResults(PCC, S, *this, Results);
  4157. Results.ExitScope();
  4158. bool PreferredTypeIsPointer = false;
  4159. if (!Data.PreferredType.isNull()) {
  4160. PreferredTypeIsPointer = Data.PreferredType->isAnyPointerType() ||
  4161. Data.PreferredType->isMemberPointerType() ||
  4162. Data.PreferredType->isBlockPointerType();
  4163. if (Data.PreferredType->isEnumeralType()) {
  4164. EnumDecl *Enum = Data.PreferredType->castAs<EnumType>()->getDecl();
  4165. if (auto *Def = Enum->getDefinition())
  4166. Enum = Def;
  4167. // FIXME: collect covered enumerators in cases like:
  4168. // if (x == my_enum::one) { ... } else if (x == ^) {}
  4169. AddEnumerators(Results, Context, Enum, CurContext, CoveredEnumerators());
  4170. }
  4171. }
  4172. if (S->getFnParent() && !Data.ObjCCollection &&
  4173. !Data.IntegralConstantExpression)
  4174. AddPrettyFunctionResults(getLangOpts(), Results);
  4175. if (CodeCompleter->includeMacros())
  4176. AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false,
  4177. PreferredTypeIsPointer);
  4178. // Complete a lambda expression when preferred type is a function.
  4179. if (!Data.PreferredType.isNull() && getLangOpts().CPlusPlus11) {
  4180. if (const FunctionProtoType *F =
  4181. TryDeconstructFunctionLike(Data.PreferredType))
  4182. AddLambdaCompletion(Results, F->getParamTypes(), getLangOpts());
  4183. }
  4184. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  4185. Results.data(), Results.size());
  4186. }
  4187. void Sema::CodeCompleteExpression(Scope *S, QualType PreferredType,
  4188. bool IsParenthesized) {
  4189. return CodeCompleteExpression(
  4190. S, CodeCompleteExpressionData(PreferredType, IsParenthesized));
  4191. }
  4192. void Sema::CodeCompletePostfixExpression(Scope *S, ExprResult E,
  4193. QualType PreferredType) {
  4194. if (E.isInvalid())
  4195. CodeCompleteExpression(S, PreferredType);
  4196. else if (getLangOpts().ObjC)
  4197. CodeCompleteObjCInstanceMessage(S, E.get(), None, false);
  4198. }
  4199. /// The set of properties that have already been added, referenced by
  4200. /// property name.
  4201. typedef llvm::SmallPtrSet<IdentifierInfo *, 16> AddedPropertiesSet;
  4202. /// Retrieve the container definition, if any?
  4203. static ObjCContainerDecl *getContainerDef(ObjCContainerDecl *Container) {
  4204. if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
  4205. if (Interface->hasDefinition())
  4206. return Interface->getDefinition();
  4207. return Interface;
  4208. }
  4209. if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
  4210. if (Protocol->hasDefinition())
  4211. return Protocol->getDefinition();
  4212. return Protocol;
  4213. }
  4214. return Container;
  4215. }
  4216. /// Adds a block invocation code completion result for the given block
  4217. /// declaration \p BD.
  4218. static void AddObjCBlockCall(ASTContext &Context, const PrintingPolicy &Policy,
  4219. CodeCompletionBuilder &Builder,
  4220. const NamedDecl *BD,
  4221. const FunctionTypeLoc &BlockLoc,
  4222. const FunctionProtoTypeLoc &BlockProtoLoc) {
  4223. Builder.AddResultTypeChunk(
  4224. GetCompletionTypeString(BlockLoc.getReturnLoc().getType(), Context,
  4225. Policy, Builder.getAllocator()));
  4226. AddTypedNameChunk(Context, Policy, BD, Builder);
  4227. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  4228. if (BlockProtoLoc && BlockProtoLoc.getTypePtr()->isVariadic()) {
  4229. Builder.AddPlaceholderChunk("...");
  4230. } else {
  4231. for (unsigned I = 0, N = BlockLoc.getNumParams(); I != N; ++I) {
  4232. if (I)
  4233. Builder.AddChunk(CodeCompletionString::CK_Comma);
  4234. // Format the placeholder string.
  4235. std::string PlaceholderStr =
  4236. FormatFunctionParameter(Policy, BlockLoc.getParam(I));
  4237. if (I == N - 1 && BlockProtoLoc &&
  4238. BlockProtoLoc.getTypePtr()->isVariadic())
  4239. PlaceholderStr += ", ...";
  4240. // Add the placeholder string.
  4241. Builder.AddPlaceholderChunk(
  4242. Builder.getAllocator().CopyString(PlaceholderStr));
  4243. }
  4244. }
  4245. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  4246. }
  4247. static void
  4248. AddObjCProperties(const CodeCompletionContext &CCContext,
  4249. ObjCContainerDecl *Container, bool AllowCategories,
  4250. bool AllowNullaryMethods, DeclContext *CurContext,
  4251. AddedPropertiesSet &AddedProperties, ResultBuilder &Results,
  4252. bool IsBaseExprStatement = false,
  4253. bool IsClassProperty = false, bool InOriginalClass = true) {
  4254. typedef CodeCompletionResult Result;
  4255. // Retrieve the definition.
  4256. Container = getContainerDef(Container);
  4257. // Add properties in this container.
  4258. const auto AddProperty = [&](const ObjCPropertyDecl *P) {
  4259. if (!AddedProperties.insert(P->getIdentifier()).second)
  4260. return;
  4261. // FIXME: Provide block invocation completion for non-statement
  4262. // expressions.
  4263. if (!P->getType().getTypePtr()->isBlockPointerType() ||
  4264. !IsBaseExprStatement) {
  4265. Result R = Result(P, Results.getBasePriority(P), nullptr);
  4266. if (!InOriginalClass)
  4267. setInBaseClass(R);
  4268. Results.MaybeAddResult(R, CurContext);
  4269. return;
  4270. }
  4271. // Block setter and invocation completion is provided only when we are able
  4272. // to find the FunctionProtoTypeLoc with parameter names for the block.
  4273. FunctionTypeLoc BlockLoc;
  4274. FunctionProtoTypeLoc BlockProtoLoc;
  4275. findTypeLocationForBlockDecl(P->getTypeSourceInfo(), BlockLoc,
  4276. BlockProtoLoc);
  4277. if (!BlockLoc) {
  4278. Result R = Result(P, Results.getBasePriority(P), nullptr);
  4279. if (!InOriginalClass)
  4280. setInBaseClass(R);
  4281. Results.MaybeAddResult(R, CurContext);
  4282. return;
  4283. }
  4284. // The default completion result for block properties should be the block
  4285. // invocation completion when the base expression is a statement.
  4286. CodeCompletionBuilder Builder(Results.getAllocator(),
  4287. Results.getCodeCompletionTUInfo());
  4288. AddObjCBlockCall(Container->getASTContext(),
  4289. getCompletionPrintingPolicy(Results.getSema()), Builder, P,
  4290. BlockLoc, BlockProtoLoc);
  4291. Result R = Result(Builder.TakeString(), P, Results.getBasePriority(P));
  4292. if (!InOriginalClass)
  4293. setInBaseClass(R);
  4294. Results.MaybeAddResult(R, CurContext);
  4295. // Provide additional block setter completion iff the base expression is a
  4296. // statement and the block property is mutable.
  4297. if (!P->isReadOnly()) {
  4298. CodeCompletionBuilder Builder(Results.getAllocator(),
  4299. Results.getCodeCompletionTUInfo());
  4300. AddResultTypeChunk(Container->getASTContext(),
  4301. getCompletionPrintingPolicy(Results.getSema()), P,
  4302. CCContext.getBaseType(), Builder);
  4303. Builder.AddTypedTextChunk(
  4304. Results.getAllocator().CopyString(P->getName()));
  4305. Builder.AddChunk(CodeCompletionString::CK_Equal);
  4306. std::string PlaceholderStr = formatBlockPlaceholder(
  4307. getCompletionPrintingPolicy(Results.getSema()), P, BlockLoc,
  4308. BlockProtoLoc, /*SuppressBlockName=*/true);
  4309. // Add the placeholder string.
  4310. Builder.AddPlaceholderChunk(
  4311. Builder.getAllocator().CopyString(PlaceholderStr));
  4312. // When completing blocks properties that return void the default
  4313. // property completion result should show up before the setter,
  4314. // otherwise the setter completion should show up before the default
  4315. // property completion, as we normally want to use the result of the
  4316. // call.
  4317. Result R =
  4318. Result(Builder.TakeString(), P,
  4319. Results.getBasePriority(P) +
  4320. (BlockLoc.getTypePtr()->getReturnType()->isVoidType()
  4321. ? CCD_BlockPropertySetter
  4322. : -CCD_BlockPropertySetter));
  4323. if (!InOriginalClass)
  4324. setInBaseClass(R);
  4325. Results.MaybeAddResult(R, CurContext);
  4326. }
  4327. };
  4328. if (IsClassProperty) {
  4329. for (const auto *P : Container->class_properties())
  4330. AddProperty(P);
  4331. } else {
  4332. for (const auto *P : Container->instance_properties())
  4333. AddProperty(P);
  4334. }
  4335. // Add nullary methods or implicit class properties
  4336. if (AllowNullaryMethods) {
  4337. ASTContext &Context = Container->getASTContext();
  4338. PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
  4339. // Adds a method result
  4340. const auto AddMethod = [&](const ObjCMethodDecl *M) {
  4341. IdentifierInfo *Name = M->getSelector().getIdentifierInfoForSlot(0);
  4342. if (!Name)
  4343. return;
  4344. if (!AddedProperties.insert(Name).second)
  4345. return;
  4346. CodeCompletionBuilder Builder(Results.getAllocator(),
  4347. Results.getCodeCompletionTUInfo());
  4348. AddResultTypeChunk(Context, Policy, M, CCContext.getBaseType(), Builder);
  4349. Builder.AddTypedTextChunk(
  4350. Results.getAllocator().CopyString(Name->getName()));
  4351. Result R = Result(Builder.TakeString(), M,
  4352. CCP_MemberDeclaration + CCD_MethodAsProperty);
  4353. if (!InOriginalClass)
  4354. setInBaseClass(R);
  4355. Results.MaybeAddResult(R, CurContext);
  4356. };
  4357. if (IsClassProperty) {
  4358. for (const auto *M : Container->methods()) {
  4359. // Gather the class method that can be used as implicit property
  4360. // getters. Methods with arguments or methods that return void aren't
  4361. // added to the results as they can't be used as a getter.
  4362. if (!M->getSelector().isUnarySelector() ||
  4363. M->getReturnType()->isVoidType() || M->isInstanceMethod())
  4364. continue;
  4365. AddMethod(M);
  4366. }
  4367. } else {
  4368. for (auto *M : Container->methods()) {
  4369. if (M->getSelector().isUnarySelector())
  4370. AddMethod(M);
  4371. }
  4372. }
  4373. }
  4374. // Add properties in referenced protocols.
  4375. if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
  4376. for (auto *P : Protocol->protocols())
  4377. AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
  4378. CurContext, AddedProperties, Results,
  4379. IsBaseExprStatement, IsClassProperty,
  4380. /*InOriginalClass*/ false);
  4381. } else if (ObjCInterfaceDecl *IFace =
  4382. dyn_cast<ObjCInterfaceDecl>(Container)) {
  4383. if (AllowCategories) {
  4384. // Look through categories.
  4385. for (auto *Cat : IFace->known_categories())
  4386. AddObjCProperties(CCContext, Cat, AllowCategories, AllowNullaryMethods,
  4387. CurContext, AddedProperties, Results,
  4388. IsBaseExprStatement, IsClassProperty,
  4389. InOriginalClass);
  4390. }
  4391. // Look through protocols.
  4392. for (auto *I : IFace->all_referenced_protocols())
  4393. AddObjCProperties(CCContext, I, AllowCategories, AllowNullaryMethods,
  4394. CurContext, AddedProperties, Results,
  4395. IsBaseExprStatement, IsClassProperty,
  4396. /*InOriginalClass*/ false);
  4397. // Look in the superclass.
  4398. if (IFace->getSuperClass())
  4399. AddObjCProperties(CCContext, IFace->getSuperClass(), AllowCategories,
  4400. AllowNullaryMethods, CurContext, AddedProperties,
  4401. Results, IsBaseExprStatement, IsClassProperty,
  4402. /*InOriginalClass*/ false);
  4403. } else if (const auto *Category =
  4404. dyn_cast<ObjCCategoryDecl>(Container)) {
  4405. // Look through protocols.
  4406. for (auto *P : Category->protocols())
  4407. AddObjCProperties(CCContext, P, AllowCategories, AllowNullaryMethods,
  4408. CurContext, AddedProperties, Results,
  4409. IsBaseExprStatement, IsClassProperty,
  4410. /*InOriginalClass*/ false);
  4411. }
  4412. }
  4413. static void AddRecordMembersCompletionResults(
  4414. Sema &SemaRef, ResultBuilder &Results, Scope *S, QualType BaseType,
  4415. ExprValueKind BaseKind, RecordDecl *RD, Optional<FixItHint> AccessOpFixIt) {
  4416. // Indicate that we are performing a member access, and the cv-qualifiers
  4417. // for the base object type.
  4418. Results.setObjectTypeQualifiers(BaseType.getQualifiers(), BaseKind);
  4419. // Access to a C/C++ class, struct, or union.
  4420. Results.allowNestedNameSpecifiers();
  4421. std::vector<FixItHint> FixIts;
  4422. if (AccessOpFixIt)
  4423. FixIts.emplace_back(AccessOpFixIt.getValue());
  4424. CodeCompletionDeclConsumer Consumer(Results, RD, BaseType, std::move(FixIts));
  4425. SemaRef.LookupVisibleDecls(RD, Sema::LookupMemberName, Consumer,
  4426. SemaRef.CodeCompleter->includeGlobals(),
  4427. /*IncludeDependentBases=*/true,
  4428. SemaRef.CodeCompleter->loadExternal());
  4429. if (SemaRef.getLangOpts().CPlusPlus) {
  4430. if (!Results.empty()) {
  4431. // The "template" keyword can follow "->" or "." in the grammar.
  4432. // However, we only want to suggest the template keyword if something
  4433. // is dependent.
  4434. bool IsDependent = BaseType->isDependentType();
  4435. if (!IsDependent) {
  4436. for (Scope *DepScope = S; DepScope; DepScope = DepScope->getParent())
  4437. if (DeclContext *Ctx = DepScope->getEntity()) {
  4438. IsDependent = Ctx->isDependentContext();
  4439. break;
  4440. }
  4441. }
  4442. if (IsDependent)
  4443. Results.AddResult(CodeCompletionResult("template"));
  4444. }
  4445. }
  4446. }
  4447. // Returns the RecordDecl inside the BaseType, falling back to primary template
  4448. // in case of specializations. Since we might not have a decl for the
  4449. // instantiation/specialization yet, e.g. dependent code.
  4450. static RecordDecl *getAsRecordDecl(const QualType BaseType) {
  4451. if (auto *RD = BaseType->getAsRecordDecl()) {
  4452. if (const auto *CTSD =
  4453. llvm::dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
  4454. // Template might not be instantiated yet, fall back to primary template
  4455. // in such cases.
  4456. if (CTSD->getTemplateSpecializationKind() == TSK_Undeclared)
  4457. RD = CTSD->getSpecializedTemplate()->getTemplatedDecl();
  4458. }
  4459. return RD;
  4460. }
  4461. if (const auto *TST = BaseType->getAs<TemplateSpecializationType>()) {
  4462. if (const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(
  4463. TST->getTemplateName().getAsTemplateDecl())) {
  4464. return TD->getTemplatedDecl();
  4465. }
  4466. }
  4467. return nullptr;
  4468. }
  4469. namespace {
  4470. // Collects completion-relevant information about a concept-constrainted type T.
  4471. // In particular, examines the constraint expressions to find members of T.
  4472. //
  4473. // The design is very simple: we walk down each constraint looking for
  4474. // expressions of the form T.foo().
  4475. // If we're extra lucky, the return type is specified.
  4476. // We don't do any clever handling of && or || in constraint expressions, we
  4477. // take members from both branches.
  4478. //
  4479. // For example, given:
  4480. // template <class T> concept X = requires (T t, string& s) { t.print(s); };
  4481. // template <X U> void foo(U u) { u.^ }
  4482. // We want to suggest the inferred member function 'print(string)'.
  4483. // We see that u has type U, so X<U> holds.
  4484. // X<U> requires t.print(s) to be valid, where t has type U (substituted for T).
  4485. // By looking at the CallExpr we find the signature of print().
  4486. //
  4487. // While we tend to know in advance which kind of members (access via . -> ::)
  4488. // we want, it's simpler just to gather them all and post-filter.
  4489. //
  4490. // FIXME: some of this machinery could be used for non-concept type-parms too,
  4491. // enabling completion for type parameters based on other uses of that param.
  4492. //
  4493. // FIXME: there are other cases where a type can be constrained by a concept,
  4494. // e.g. inside `if constexpr(ConceptSpecializationExpr) { ... }`
  4495. class ConceptInfo {
  4496. public:
  4497. // Describes a likely member of a type, inferred by concept constraints.
  4498. // Offered as a code completion for T. T-> and T:: contexts.
  4499. struct Member {
  4500. // Always non-null: we only handle members with ordinary identifier names.
  4501. const IdentifierInfo *Name = nullptr;
  4502. // Set for functions we've seen called.
  4503. // We don't have the declared parameter types, only the actual types of
  4504. // arguments we've seen. These are still valuable, as it's hard to render
  4505. // a useful function completion with neither parameter types nor names!
  4506. llvm::Optional<SmallVector<QualType, 1>> ArgTypes;
  4507. // Whether this is accessed as T.member, T->member, or T::member.
  4508. enum AccessOperator {
  4509. Colons,
  4510. Arrow,
  4511. Dot,
  4512. } Operator = Dot;
  4513. // What's known about the type of a variable or return type of a function.
  4514. const TypeConstraint *ResultType = nullptr;
  4515. // FIXME: also track:
  4516. // - kind of entity (function/variable/type), to expose structured results
  4517. // - template args kinds/types, as a proxy for template params
  4518. // For now we simply return these results as "pattern" strings.
  4519. CodeCompletionString *render(Sema &S, CodeCompletionAllocator &Alloc,
  4520. CodeCompletionTUInfo &Info) const {
  4521. CodeCompletionBuilder B(Alloc, Info);
  4522. // Result type
  4523. if (ResultType) {
  4524. std::string AsString;
  4525. {
  4526. llvm::raw_string_ostream OS(AsString);
  4527. QualType ExactType = deduceType(*ResultType);
  4528. if (!ExactType.isNull())
  4529. ExactType.print(OS, getCompletionPrintingPolicy(S));
  4530. else
  4531. ResultType->print(OS, getCompletionPrintingPolicy(S));
  4532. }
  4533. B.AddResultTypeChunk(Alloc.CopyString(AsString));
  4534. }
  4535. // Member name
  4536. B.AddTypedTextChunk(Alloc.CopyString(Name->getName()));
  4537. // Function argument list
  4538. if (ArgTypes) {
  4539. B.AddChunk(clang::CodeCompletionString::CK_LeftParen);
  4540. bool First = true;
  4541. for (QualType Arg : *ArgTypes) {
  4542. if (First)
  4543. First = false;
  4544. else {
  4545. B.AddChunk(clang::CodeCompletionString::CK_Comma);
  4546. B.AddChunk(clang::CodeCompletionString::CK_HorizontalSpace);
  4547. }
  4548. B.AddPlaceholderChunk(Alloc.CopyString(
  4549. Arg.getAsString(getCompletionPrintingPolicy(S))));
  4550. }
  4551. B.AddChunk(clang::CodeCompletionString::CK_RightParen);
  4552. }
  4553. return B.TakeString();
  4554. }
  4555. };
  4556. // BaseType is the type parameter T to infer members from.
  4557. // T must be accessible within S, as we use it to find the template entity
  4558. // that T is attached to in order to gather the relevant constraints.
  4559. ConceptInfo(const TemplateTypeParmType &BaseType, Scope *S) {
  4560. auto *TemplatedEntity = getTemplatedEntity(BaseType.getDecl(), S);
  4561. for (const Expr *E : constraintsForTemplatedEntity(TemplatedEntity))
  4562. believe(E, &BaseType);
  4563. }
  4564. std::vector<Member> members() {
  4565. std::vector<Member> Results;
  4566. for (const auto &E : this->Results)
  4567. Results.push_back(E.second);
  4568. llvm::sort(Results, [](const Member &L, const Member &R) {
  4569. return L.Name->getName() < R.Name->getName();
  4570. });
  4571. return Results;
  4572. }
  4573. private:
  4574. // Infer members of T, given that the expression E (dependent on T) is true.
  4575. void believe(const Expr *E, const TemplateTypeParmType *T) {
  4576. if (!E || !T)
  4577. return;
  4578. if (auto *CSE = dyn_cast<ConceptSpecializationExpr>(E)) {
  4579. // If the concept is
  4580. // template <class A, class B> concept CD = f<A, B>();
  4581. // And the concept specialization is
  4582. // CD<int, T>
  4583. // Then we're substituting T for B, so we want to make f<A, B>() true
  4584. // by adding members to B - i.e. believe(f<A, B>(), B);
  4585. //
  4586. // For simplicity:
  4587. // - we don't attempt to substitute int for A
  4588. // - when T is used in other ways (like CD<T*>) we ignore it
  4589. ConceptDecl *CD = CSE->getNamedConcept();
  4590. TemplateParameterList *Params = CD->getTemplateParameters();
  4591. unsigned Index = 0;
  4592. for (const auto &Arg : CSE->getTemplateArguments()) {
  4593. if (Index >= Params->size())
  4594. break; // Won't happen in valid code.
  4595. if (isApprox(Arg, T)) {
  4596. auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Params->getParam(Index));
  4597. if (!TTPD)
  4598. continue;
  4599. // T was used as an argument, and bound to the parameter TT.
  4600. auto *TT = cast<TemplateTypeParmType>(TTPD->getTypeForDecl());
  4601. // So now we know the constraint as a function of TT is true.
  4602. believe(CD->getConstraintExpr(), TT);
  4603. // (concepts themselves have no associated constraints to require)
  4604. }
  4605. ++Index;
  4606. }
  4607. } else if (auto *BO = dyn_cast<BinaryOperator>(E)) {
  4608. // For A && B, we can infer members from both branches.
  4609. // For A || B, the union is still more useful than the intersection.
  4610. if (BO->getOpcode() == BO_LAnd || BO->getOpcode() == BO_LOr) {
  4611. believe(BO->getLHS(), T);
  4612. believe(BO->getRHS(), T);
  4613. }
  4614. } else if (auto *RE = dyn_cast<RequiresExpr>(E)) {
  4615. // A requires(){...} lets us infer members from each requirement.
  4616. for (const concepts::Requirement *Req : RE->getRequirements()) {
  4617. if (!Req->isDependent())
  4618. continue; // Can't tell us anything about T.
  4619. // Now Req cannot a substitution-error: those aren't dependent.
  4620. if (auto *TR = dyn_cast<concepts::TypeRequirement>(Req)) {
  4621. // Do a full traversal so we get `foo` from `typename T::foo::bar`.
  4622. QualType AssertedType = TR->getType()->getType();
  4623. ValidVisitor(this, T).TraverseType(AssertedType);
  4624. } else if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
  4625. ValidVisitor Visitor(this, T);
  4626. // If we have a type constraint on the value of the expression,
  4627. // AND the whole outer expression describes a member, then we'll
  4628. // be able to use the constraint to provide the return type.
  4629. if (ER->getReturnTypeRequirement().isTypeConstraint()) {
  4630. Visitor.OuterType =
  4631. ER->getReturnTypeRequirement().getTypeConstraint();
  4632. Visitor.OuterExpr = ER->getExpr();
  4633. }
  4634. Visitor.TraverseStmt(ER->getExpr());
  4635. } else if (auto *NR = dyn_cast<concepts::NestedRequirement>(Req)) {
  4636. believe(NR->getConstraintExpr(), T);
  4637. }
  4638. }
  4639. }
  4640. }
  4641. // This visitor infers members of T based on traversing expressions/types
  4642. // that involve T. It is invoked with code known to be valid for T.
  4643. class ValidVisitor : public RecursiveASTVisitor<ValidVisitor> {
  4644. ConceptInfo *Outer;
  4645. const TemplateTypeParmType *T;
  4646. CallExpr *Caller = nullptr;
  4647. Expr *Callee = nullptr;
  4648. public:
  4649. // If set, OuterExpr is constrained by OuterType.
  4650. Expr *OuterExpr = nullptr;
  4651. const TypeConstraint *OuterType = nullptr;
  4652. ValidVisitor(ConceptInfo *Outer, const TemplateTypeParmType *T)
  4653. : Outer(Outer), T(T) {
  4654. assert(T);
  4655. }
  4656. // In T.foo or T->foo, `foo` is a member function/variable.
  4657. bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E) {
  4658. const Type *Base = E->getBaseType().getTypePtr();
  4659. bool IsArrow = E->isArrow();
  4660. if (Base->isPointerType() && IsArrow) {
  4661. IsArrow = false;
  4662. Base = Base->getPointeeType().getTypePtr();
  4663. }
  4664. if (isApprox(Base, T))
  4665. addValue(E, E->getMember(), IsArrow ? Member::Arrow : Member::Dot);
  4666. return true;
  4667. }
  4668. // In T::foo, `foo` is a static member function/variable.
  4669. bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
  4670. if (E->getQualifier() && isApprox(E->getQualifier()->getAsType(), T))
  4671. addValue(E, E->getDeclName(), Member::Colons);
  4672. return true;
  4673. }
  4674. // In T::typename foo, `foo` is a type.
  4675. bool VisitDependentNameType(DependentNameType *DNT) {
  4676. const auto *Q = DNT->getQualifier();
  4677. if (Q && isApprox(Q->getAsType(), T))
  4678. addType(DNT->getIdentifier());
  4679. return true;
  4680. }
  4681. // In T::foo::bar, `foo` must be a type.
  4682. // VisitNNS() doesn't exist, and TraverseNNS isn't always called :-(
  4683. bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNSL) {
  4684. if (NNSL) {
  4685. NestedNameSpecifier *NNS = NNSL.getNestedNameSpecifier();
  4686. const auto *Q = NNS->getPrefix();
  4687. if (Q && isApprox(Q->getAsType(), T))
  4688. addType(NNS->getAsIdentifier());
  4689. }
  4690. // FIXME: also handle T::foo<X>::bar
  4691. return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(NNSL);
  4692. }
  4693. // FIXME also handle T::foo<X>
  4694. // Track the innermost caller/callee relationship so we can tell if a
  4695. // nested expr is being called as a function.
  4696. bool VisitCallExpr(CallExpr *CE) {
  4697. Caller = CE;
  4698. Callee = CE->getCallee();
  4699. return true;
  4700. }
  4701. private:
  4702. void addResult(Member &&M) {
  4703. auto R = Outer->Results.try_emplace(M.Name);
  4704. Member &O = R.first->second;
  4705. // Overwrite existing if the new member has more info.
  4706. // The preference of . vs :: vs -> is fairly arbitrary.
  4707. if (/*Inserted*/ R.second ||
  4708. std::make_tuple(M.ArgTypes.hasValue(), M.ResultType != nullptr,
  4709. M.Operator) > std::make_tuple(O.ArgTypes.hasValue(),
  4710. O.ResultType != nullptr,
  4711. O.Operator))
  4712. O = std::move(M);
  4713. }
  4714. void addType(const IdentifierInfo *Name) {
  4715. if (!Name)
  4716. return;
  4717. Member M;
  4718. M.Name = Name;
  4719. M.Operator = Member::Colons;
  4720. addResult(std::move(M));
  4721. }
  4722. void addValue(Expr *E, DeclarationName Name,
  4723. Member::AccessOperator Operator) {
  4724. if (!Name.isIdentifier())
  4725. return;
  4726. Member Result;
  4727. Result.Name = Name.getAsIdentifierInfo();
  4728. Result.Operator = Operator;
  4729. // If this is the callee of an immediately-enclosing CallExpr, then
  4730. // treat it as a method, otherwise it's a variable.
  4731. if (Caller != nullptr && Callee == E) {
  4732. Result.ArgTypes.emplace();
  4733. for (const auto *Arg : Caller->arguments())
  4734. Result.ArgTypes->push_back(Arg->getType());
  4735. if (Caller == OuterExpr) {
  4736. Result.ResultType = OuterType;
  4737. }
  4738. } else {
  4739. if (E == OuterExpr)
  4740. Result.ResultType = OuterType;
  4741. }
  4742. addResult(std::move(Result));
  4743. }
  4744. };
  4745. static bool isApprox(const TemplateArgument &Arg, const Type *T) {
  4746. return Arg.getKind() == TemplateArgument::Type &&
  4747. isApprox(Arg.getAsType().getTypePtr(), T);
  4748. }
  4749. static bool isApprox(const Type *T1, const Type *T2) {
  4750. return T1 && T2 &&
  4751. T1->getCanonicalTypeUnqualified() ==
  4752. T2->getCanonicalTypeUnqualified();
  4753. }
  4754. // Returns the DeclContext immediately enclosed by the template parameter
  4755. // scope. For primary templates, this is the templated (e.g.) CXXRecordDecl.
  4756. // For specializations, this is e.g. ClassTemplatePartialSpecializationDecl.
  4757. static DeclContext *getTemplatedEntity(const TemplateTypeParmDecl *D,
  4758. Scope *S) {
  4759. if (D == nullptr)
  4760. return nullptr;
  4761. Scope *Inner = nullptr;
  4762. while (S) {
  4763. if (S->isTemplateParamScope() && S->isDeclScope(D))
  4764. return Inner ? Inner->getEntity() : nullptr;
  4765. Inner = S;
  4766. S = S->getParent();
  4767. }
  4768. return nullptr;
  4769. }
  4770. // Gets all the type constraint expressions that might apply to the type
  4771. // variables associated with DC (as returned by getTemplatedEntity()).
  4772. static SmallVector<const Expr *, 1>
  4773. constraintsForTemplatedEntity(DeclContext *DC) {
  4774. SmallVector<const Expr *, 1> Result;
  4775. if (DC == nullptr)
  4776. return Result;
  4777. // Primary templates can have constraints.
  4778. if (const auto *TD = cast<Decl>(DC)->getDescribedTemplate())
  4779. TD->getAssociatedConstraints(Result);
  4780. // Partial specializations may have constraints.
  4781. if (const auto *CTPSD =
  4782. dyn_cast<ClassTemplatePartialSpecializationDecl>(DC))
  4783. CTPSD->getAssociatedConstraints(Result);
  4784. if (const auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(DC))
  4785. VTPSD->getAssociatedConstraints(Result);
  4786. return Result;
  4787. }
  4788. // Attempt to find the unique type satisfying a constraint.
  4789. // This lets us show e.g. `int` instead of `std::same_as<int>`.
  4790. static QualType deduceType(const TypeConstraint &T) {
  4791. // Assume a same_as<T> return type constraint is std::same_as or equivalent.
  4792. // In this case the return type is T.
  4793. DeclarationName DN = T.getNamedConcept()->getDeclName();
  4794. if (DN.isIdentifier() && DN.getAsIdentifierInfo()->isStr("same_as"))
  4795. if (const auto *Args = T.getTemplateArgsAsWritten())
  4796. if (Args->getNumTemplateArgs() == 1) {
  4797. const auto &Arg = Args->arguments().front().getArgument();
  4798. if (Arg.getKind() == TemplateArgument::Type)
  4799. return Arg.getAsType();
  4800. }
  4801. return {};
  4802. }
  4803. llvm::DenseMap<const IdentifierInfo *, Member> Results;
  4804. };
  4805. // Returns a type for E that yields acceptable member completions.
  4806. // In particular, when E->getType() is DependentTy, try to guess a likely type.
  4807. // We accept some lossiness (like dropping parameters).
  4808. // We only try to handle common expressions on the LHS of MemberExpr.
  4809. QualType getApproximateType(const Expr *E) {
  4810. QualType Unresolved = E->getType();
  4811. if (Unresolved.isNull() ||
  4812. !Unresolved->isSpecificBuiltinType(BuiltinType::Dependent))
  4813. return Unresolved;
  4814. E = E->IgnoreParens();
  4815. // A call: approximate-resolve callee to a function type, get its return type
  4816. if (const CallExpr *CE = llvm::dyn_cast<CallExpr>(E)) {
  4817. QualType Callee = getApproximateType(CE->getCallee());
  4818. if (Callee.isNull() ||
  4819. Callee->isSpecificPlaceholderType(BuiltinType::BoundMember))
  4820. Callee = Expr::findBoundMemberType(CE->getCallee());
  4821. if (Callee.isNull())
  4822. return Unresolved;
  4823. if (const auto *FnTypePtr = Callee->getAs<PointerType>()) {
  4824. Callee = FnTypePtr->getPointeeType();
  4825. } else if (const auto *BPT = Callee->getAs<BlockPointerType>()) {
  4826. Callee = BPT->getPointeeType();
  4827. }
  4828. if (const FunctionType *FnType = Callee->getAs<FunctionType>())
  4829. return FnType->getReturnType().getNonReferenceType();
  4830. // Unresolved call: try to guess the return type.
  4831. if (const auto *OE = llvm::dyn_cast<OverloadExpr>(CE->getCallee())) {
  4832. // If all candidates have the same approximate return type, use it.
  4833. // Discard references and const to allow more to be "the same".
  4834. // (In particular, if there's one candidate + ADL, resolve it).
  4835. const Type *Common = nullptr;
  4836. for (const auto *D : OE->decls()) {
  4837. QualType ReturnType;
  4838. if (const auto *FD = llvm::dyn_cast<FunctionDecl>(D))
  4839. ReturnType = FD->getReturnType();
  4840. else if (const auto *FTD = llvm::dyn_cast<FunctionTemplateDecl>(D))
  4841. ReturnType = FTD->getTemplatedDecl()->getReturnType();
  4842. if (ReturnType.isNull())
  4843. continue;
  4844. const Type *Candidate =
  4845. ReturnType.getNonReferenceType().getCanonicalType().getTypePtr();
  4846. if (Common && Common != Candidate)
  4847. return Unresolved; // Multiple candidates.
  4848. Common = Candidate;
  4849. }
  4850. if (Common != nullptr)
  4851. return QualType(Common, 0);
  4852. }
  4853. }
  4854. // A dependent member: approximate-resolve the base, then lookup.
  4855. if (const auto *CDSME = llvm::dyn_cast<CXXDependentScopeMemberExpr>(E)) {
  4856. QualType Base = CDSME->isImplicitAccess()
  4857. ? CDSME->getBaseType()
  4858. : getApproximateType(CDSME->getBase());
  4859. if (CDSME->isArrow() && !Base.isNull())
  4860. Base = Base->getPointeeType(); // could handle unique_ptr etc here?
  4861. auto *RD =
  4862. Base.isNull()
  4863. ? nullptr
  4864. : llvm::dyn_cast_or_null<CXXRecordDecl>(getAsRecordDecl(Base));
  4865. if (RD && RD->isCompleteDefinition()) {
  4866. // Look up member heuristically, including in bases.
  4867. for (const auto *Member : RD->lookupDependentName(
  4868. CDSME->getMember(), [](const NamedDecl *Member) {
  4869. return llvm::isa<ValueDecl>(Member);
  4870. })) {
  4871. return llvm::cast<ValueDecl>(Member)->getType().getNonReferenceType();
  4872. }
  4873. }
  4874. }
  4875. return Unresolved;
  4876. }
  4877. // If \p Base is ParenListExpr, assume a chain of comma operators and pick the
  4878. // last expr. We expect other ParenListExprs to be resolved to e.g. constructor
  4879. // calls before here. (So the ParenListExpr should be nonempty, but check just
  4880. // in case)
  4881. Expr *unwrapParenList(Expr *Base) {
  4882. if (auto *PLE = llvm::dyn_cast_or_null<ParenListExpr>(Base)) {
  4883. if (PLE->getNumExprs() == 0)
  4884. return nullptr;
  4885. Base = PLE->getExpr(PLE->getNumExprs() - 1);
  4886. }
  4887. return Base;
  4888. }
  4889. } // namespace
  4890. void Sema::CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base,
  4891. Expr *OtherOpBase,
  4892. SourceLocation OpLoc, bool IsArrow,
  4893. bool IsBaseExprStatement,
  4894. QualType PreferredType) {
  4895. Base = unwrapParenList(Base);
  4896. OtherOpBase = unwrapParenList(OtherOpBase);
  4897. if (!Base || !CodeCompleter)
  4898. return;
  4899. ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
  4900. if (ConvertedBase.isInvalid())
  4901. return;
  4902. QualType ConvertedBaseType = getApproximateType(ConvertedBase.get());
  4903. enum CodeCompletionContext::Kind contextKind;
  4904. if (IsArrow) {
  4905. if (const auto *Ptr = ConvertedBaseType->getAs<PointerType>())
  4906. ConvertedBaseType = Ptr->getPointeeType();
  4907. }
  4908. if (IsArrow) {
  4909. contextKind = CodeCompletionContext::CCC_ArrowMemberAccess;
  4910. } else {
  4911. if (ConvertedBaseType->isObjCObjectPointerType() ||
  4912. ConvertedBaseType->isObjCObjectOrInterfaceType()) {
  4913. contextKind = CodeCompletionContext::CCC_ObjCPropertyAccess;
  4914. } else {
  4915. contextKind = CodeCompletionContext::CCC_DotMemberAccess;
  4916. }
  4917. }
  4918. CodeCompletionContext CCContext(contextKind, ConvertedBaseType);
  4919. CCContext.setPreferredType(PreferredType);
  4920. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  4921. CodeCompleter->getCodeCompletionTUInfo(), CCContext,
  4922. &ResultBuilder::IsMember);
  4923. auto DoCompletion = [&](Expr *Base, bool IsArrow,
  4924. Optional<FixItHint> AccessOpFixIt) -> bool {
  4925. if (!Base)
  4926. return false;
  4927. ExprResult ConvertedBase = PerformMemberExprBaseConversion(Base, IsArrow);
  4928. if (ConvertedBase.isInvalid())
  4929. return false;
  4930. Base = ConvertedBase.get();
  4931. QualType BaseType = getApproximateType(Base);
  4932. if (BaseType.isNull())
  4933. return false;
  4934. ExprValueKind BaseKind = Base->getValueKind();
  4935. if (IsArrow) {
  4936. if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
  4937. BaseType = Ptr->getPointeeType();
  4938. BaseKind = VK_LValue;
  4939. } else if (BaseType->isObjCObjectPointerType() ||
  4940. BaseType->isTemplateTypeParmType()) {
  4941. // Both cases (dot/arrow) handled below.
  4942. } else {
  4943. return false;
  4944. }
  4945. }
  4946. if (RecordDecl *RD = getAsRecordDecl(BaseType)) {
  4947. AddRecordMembersCompletionResults(*this, Results, S, BaseType, BaseKind,
  4948. RD, std::move(AccessOpFixIt));
  4949. } else if (const auto *TTPT =
  4950. dyn_cast<TemplateTypeParmType>(BaseType.getTypePtr())) {
  4951. auto Operator =
  4952. IsArrow ? ConceptInfo::Member::Arrow : ConceptInfo::Member::Dot;
  4953. for (const auto &R : ConceptInfo(*TTPT, S).members()) {
  4954. if (R.Operator != Operator)
  4955. continue;
  4956. CodeCompletionResult Result(
  4957. R.render(*this, CodeCompleter->getAllocator(),
  4958. CodeCompleter->getCodeCompletionTUInfo()));
  4959. if (AccessOpFixIt)
  4960. Result.FixIts.push_back(*AccessOpFixIt);
  4961. Results.AddResult(std::move(Result));
  4962. }
  4963. } else if (!IsArrow && BaseType->isObjCObjectPointerType()) {
  4964. // Objective-C property reference. Bail if we're performing fix-it code
  4965. // completion since Objective-C properties are normally backed by ivars,
  4966. // most Objective-C fix-its here would have little value.
  4967. if (AccessOpFixIt.hasValue()) {
  4968. return false;
  4969. }
  4970. AddedPropertiesSet AddedProperties;
  4971. if (const ObjCObjectPointerType *ObjCPtr =
  4972. BaseType->getAsObjCInterfacePointerType()) {
  4973. // Add property results based on our interface.
  4974. assert(ObjCPtr && "Non-NULL pointer guaranteed above!");
  4975. AddObjCProperties(CCContext, ObjCPtr->getInterfaceDecl(), true,
  4976. /*AllowNullaryMethods=*/true, CurContext,
  4977. AddedProperties, Results, IsBaseExprStatement);
  4978. }
  4979. // Add properties from the protocols in a qualified interface.
  4980. for (auto *I : BaseType->castAs<ObjCObjectPointerType>()->quals())
  4981. AddObjCProperties(CCContext, I, true, /*AllowNullaryMethods=*/true,
  4982. CurContext, AddedProperties, Results,
  4983. IsBaseExprStatement, /*IsClassProperty*/ false,
  4984. /*InOriginalClass*/ false);
  4985. } else if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
  4986. (!IsArrow && BaseType->isObjCObjectType())) {
  4987. // Objective-C instance variable access. Bail if we're performing fix-it
  4988. // code completion since Objective-C properties are normally backed by
  4989. // ivars, most Objective-C fix-its here would have little value.
  4990. if (AccessOpFixIt.hasValue()) {
  4991. return false;
  4992. }
  4993. ObjCInterfaceDecl *Class = nullptr;
  4994. if (const ObjCObjectPointerType *ObjCPtr =
  4995. BaseType->getAs<ObjCObjectPointerType>())
  4996. Class = ObjCPtr->getInterfaceDecl();
  4997. else
  4998. Class = BaseType->castAs<ObjCObjectType>()->getInterface();
  4999. // Add all ivars from this class and its superclasses.
  5000. if (Class) {
  5001. CodeCompletionDeclConsumer Consumer(Results, Class, BaseType);
  5002. Results.setFilter(&ResultBuilder::IsObjCIvar);
  5003. LookupVisibleDecls(
  5004. Class, LookupMemberName, Consumer, CodeCompleter->includeGlobals(),
  5005. /*IncludeDependentBases=*/false, CodeCompleter->loadExternal());
  5006. }
  5007. }
  5008. // FIXME: How do we cope with isa?
  5009. return true;
  5010. };
  5011. Results.EnterNewScope();
  5012. bool CompletionSucceded = DoCompletion(Base, IsArrow, None);
  5013. if (CodeCompleter->includeFixIts()) {
  5014. const CharSourceRange OpRange =
  5015. CharSourceRange::getTokenRange(OpLoc, OpLoc);
  5016. CompletionSucceded |= DoCompletion(
  5017. OtherOpBase, !IsArrow,
  5018. FixItHint::CreateReplacement(OpRange, IsArrow ? "." : "->"));
  5019. }
  5020. Results.ExitScope();
  5021. if (!CompletionSucceded)
  5022. return;
  5023. // Hand off the results found for code completion.
  5024. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5025. Results.data(), Results.size());
  5026. }
  5027. void Sema::CodeCompleteObjCClassPropertyRefExpr(Scope *S,
  5028. IdentifierInfo &ClassName,
  5029. SourceLocation ClassNameLoc,
  5030. bool IsBaseExprStatement) {
  5031. IdentifierInfo *ClassNamePtr = &ClassName;
  5032. ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(ClassNamePtr, ClassNameLoc);
  5033. if (!IFace)
  5034. return;
  5035. CodeCompletionContext CCContext(
  5036. CodeCompletionContext::CCC_ObjCPropertyAccess);
  5037. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5038. CodeCompleter->getCodeCompletionTUInfo(), CCContext,
  5039. &ResultBuilder::IsMember);
  5040. Results.EnterNewScope();
  5041. AddedPropertiesSet AddedProperties;
  5042. AddObjCProperties(CCContext, IFace, true,
  5043. /*AllowNullaryMethods=*/true, CurContext, AddedProperties,
  5044. Results, IsBaseExprStatement,
  5045. /*IsClassProperty=*/true);
  5046. Results.ExitScope();
  5047. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5048. Results.data(), Results.size());
  5049. }
  5050. void Sema::CodeCompleteTag(Scope *S, unsigned TagSpec) {
  5051. if (!CodeCompleter)
  5052. return;
  5053. ResultBuilder::LookupFilter Filter = nullptr;
  5054. enum CodeCompletionContext::Kind ContextKind =
  5055. CodeCompletionContext::CCC_Other;
  5056. switch ((DeclSpec::TST)TagSpec) {
  5057. case DeclSpec::TST_enum:
  5058. Filter = &ResultBuilder::IsEnum;
  5059. ContextKind = CodeCompletionContext::CCC_EnumTag;
  5060. break;
  5061. case DeclSpec::TST_union:
  5062. Filter = &ResultBuilder::IsUnion;
  5063. ContextKind = CodeCompletionContext::CCC_UnionTag;
  5064. break;
  5065. case DeclSpec::TST_struct:
  5066. case DeclSpec::TST_class:
  5067. case DeclSpec::TST_interface:
  5068. Filter = &ResultBuilder::IsClassOrStruct;
  5069. ContextKind = CodeCompletionContext::CCC_ClassOrStructTag;
  5070. break;
  5071. default:
  5072. llvm_unreachable("Unknown type specifier kind in CodeCompleteTag");
  5073. }
  5074. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5075. CodeCompleter->getCodeCompletionTUInfo(), ContextKind);
  5076. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  5077. // First pass: look for tags.
  5078. Results.setFilter(Filter);
  5079. LookupVisibleDecls(S, LookupTagName, Consumer,
  5080. CodeCompleter->includeGlobals(),
  5081. CodeCompleter->loadExternal());
  5082. if (CodeCompleter->includeGlobals()) {
  5083. // Second pass: look for nested name specifiers.
  5084. Results.setFilter(&ResultBuilder::IsNestedNameSpecifier);
  5085. LookupVisibleDecls(S, LookupNestedNameSpecifierName, Consumer,
  5086. CodeCompleter->includeGlobals(),
  5087. CodeCompleter->loadExternal());
  5088. }
  5089. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5090. Results.data(), Results.size());
  5091. }
  5092. static void AddTypeQualifierResults(DeclSpec &DS, ResultBuilder &Results,
  5093. const LangOptions &LangOpts) {
  5094. if (!(DS.getTypeQualifiers() & DeclSpec::TQ_const))
  5095. Results.AddResult("const");
  5096. if (!(DS.getTypeQualifiers() & DeclSpec::TQ_volatile))
  5097. Results.AddResult("volatile");
  5098. if (LangOpts.C99 && !(DS.getTypeQualifiers() & DeclSpec::TQ_restrict))
  5099. Results.AddResult("restrict");
  5100. if (LangOpts.C11 && !(DS.getTypeQualifiers() & DeclSpec::TQ_atomic))
  5101. Results.AddResult("_Atomic");
  5102. if (LangOpts.MSVCCompat && !(DS.getTypeQualifiers() & DeclSpec::TQ_unaligned))
  5103. Results.AddResult("__unaligned");
  5104. }
  5105. void Sema::CodeCompleteTypeQualifiers(DeclSpec &DS) {
  5106. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5107. CodeCompleter->getCodeCompletionTUInfo(),
  5108. CodeCompletionContext::CCC_TypeQualifiers);
  5109. Results.EnterNewScope();
  5110. AddTypeQualifierResults(DS, Results, LangOpts);
  5111. Results.ExitScope();
  5112. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5113. Results.data(), Results.size());
  5114. }
  5115. void Sema::CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
  5116. const VirtSpecifiers *VS) {
  5117. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5118. CodeCompleter->getCodeCompletionTUInfo(),
  5119. CodeCompletionContext::CCC_TypeQualifiers);
  5120. Results.EnterNewScope();
  5121. AddTypeQualifierResults(DS, Results, LangOpts);
  5122. if (LangOpts.CPlusPlus11) {
  5123. Results.AddResult("noexcept");
  5124. if (D.getContext() == DeclaratorContext::Member && !D.isCtorOrDtor() &&
  5125. !D.isStaticMember()) {
  5126. if (!VS || !VS->isFinalSpecified())
  5127. Results.AddResult("final");
  5128. if (!VS || !VS->isOverrideSpecified())
  5129. Results.AddResult("override");
  5130. }
  5131. }
  5132. Results.ExitScope();
  5133. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5134. Results.data(), Results.size());
  5135. }
  5136. void Sema::CodeCompleteBracketDeclarator(Scope *S) {
  5137. CodeCompleteExpression(S, QualType(getASTContext().getSizeType()));
  5138. }
  5139. void Sema::CodeCompleteCase(Scope *S) {
  5140. if (getCurFunction()->SwitchStack.empty() || !CodeCompleter)
  5141. return;
  5142. SwitchStmt *Switch = getCurFunction()->SwitchStack.back().getPointer();
  5143. // Condition expression might be invalid, do not continue in this case.
  5144. if (!Switch->getCond())
  5145. return;
  5146. QualType type = Switch->getCond()->IgnoreImplicit()->getType();
  5147. if (!type->isEnumeralType()) {
  5148. CodeCompleteExpressionData Data(type);
  5149. Data.IntegralConstantExpression = true;
  5150. CodeCompleteExpression(S, Data);
  5151. return;
  5152. }
  5153. // Code-complete the cases of a switch statement over an enumeration type
  5154. // by providing the list of
  5155. EnumDecl *Enum = type->castAs<EnumType>()->getDecl();
  5156. if (EnumDecl *Def = Enum->getDefinition())
  5157. Enum = Def;
  5158. // Determine which enumerators we have already seen in the switch statement.
  5159. // FIXME: Ideally, we would also be able to look *past* the code-completion
  5160. // token, in case we are code-completing in the middle of the switch and not
  5161. // at the end. However, we aren't able to do so at the moment.
  5162. CoveredEnumerators Enumerators;
  5163. for (SwitchCase *SC = Switch->getSwitchCaseList(); SC;
  5164. SC = SC->getNextSwitchCase()) {
  5165. CaseStmt *Case = dyn_cast<CaseStmt>(SC);
  5166. if (!Case)
  5167. continue;
  5168. Expr *CaseVal = Case->getLHS()->IgnoreParenCasts();
  5169. if (auto *DRE = dyn_cast<DeclRefExpr>(CaseVal))
  5170. if (auto *Enumerator =
  5171. dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
  5172. // We look into the AST of the case statement to determine which
  5173. // enumerator was named. Alternatively, we could compute the value of
  5174. // the integral constant expression, then compare it against the
  5175. // values of each enumerator. However, value-based approach would not
  5176. // work as well with C++ templates where enumerators declared within a
  5177. // template are type- and value-dependent.
  5178. Enumerators.Seen.insert(Enumerator);
  5179. // If this is a qualified-id, keep track of the nested-name-specifier
  5180. // so that we can reproduce it as part of code completion, e.g.,
  5181. //
  5182. // switch (TagD.getKind()) {
  5183. // case TagDecl::TK_enum:
  5184. // break;
  5185. // case XXX
  5186. //
  5187. // At the XXX, our completions are TagDecl::TK_union,
  5188. // TagDecl::TK_struct, and TagDecl::TK_class, rather than TK_union,
  5189. // TK_struct, and TK_class.
  5190. Enumerators.SuggestedQualifier = DRE->getQualifier();
  5191. }
  5192. }
  5193. // Add any enumerators that have not yet been mentioned.
  5194. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5195. CodeCompleter->getCodeCompletionTUInfo(),
  5196. CodeCompletionContext::CCC_Expression);
  5197. AddEnumerators(Results, Context, Enum, CurContext, Enumerators);
  5198. if (CodeCompleter->includeMacros()) {
  5199. AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
  5200. }
  5201. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5202. Results.data(), Results.size());
  5203. }
  5204. static bool anyNullArguments(ArrayRef<Expr *> Args) {
  5205. if (Args.size() && !Args.data())
  5206. return true;
  5207. for (unsigned I = 0; I != Args.size(); ++I)
  5208. if (!Args[I])
  5209. return true;
  5210. return false;
  5211. }
  5212. typedef CodeCompleteConsumer::OverloadCandidate ResultCandidate;
  5213. static void mergeCandidatesWithResults(
  5214. Sema &SemaRef, SmallVectorImpl<ResultCandidate> &Results,
  5215. OverloadCandidateSet &CandidateSet, SourceLocation Loc, size_t ArgSize) {
  5216. // Sort the overload candidate set by placing the best overloads first.
  5217. llvm::stable_sort(CandidateSet, [&](const OverloadCandidate &X,
  5218. const OverloadCandidate &Y) {
  5219. return isBetterOverloadCandidate(SemaRef, X, Y, Loc,
  5220. CandidateSet.getKind());
  5221. });
  5222. // Add the remaining viable overload candidates as code-completion results.
  5223. for (OverloadCandidate &Candidate : CandidateSet) {
  5224. if (Candidate.Function) {
  5225. if (Candidate.Function->isDeleted())
  5226. continue;
  5227. if (shouldEnforceArgLimit(/*PartialOverloading=*/true,
  5228. Candidate.Function) &&
  5229. Candidate.Function->getNumParams() <= ArgSize &&
  5230. // Having zero args is annoying, normally we don't surface a function
  5231. // with 2 params, if you already have 2 params, because you are
  5232. // inserting the 3rd now. But with zero, it helps the user to figure
  5233. // out there are no overloads that take any arguments. Hence we are
  5234. // keeping the overload.
  5235. ArgSize > 0)
  5236. continue;
  5237. }
  5238. if (Candidate.Viable)
  5239. Results.push_back(ResultCandidate(Candidate.Function));
  5240. }
  5241. }
  5242. /// Get the type of the Nth parameter from a given set of overload
  5243. /// candidates.
  5244. static QualType getParamType(Sema &SemaRef,
  5245. ArrayRef<ResultCandidate> Candidates, unsigned N) {
  5246. // Given the overloads 'Candidates' for a function call matching all arguments
  5247. // up to N, return the type of the Nth parameter if it is the same for all
  5248. // overload candidates.
  5249. QualType ParamType;
  5250. for (auto &Candidate : Candidates) {
  5251. QualType CandidateParamType = Candidate.getParamType(N);
  5252. if (CandidateParamType.isNull())
  5253. continue;
  5254. if (ParamType.isNull()) {
  5255. ParamType = CandidateParamType;
  5256. continue;
  5257. }
  5258. if (!SemaRef.Context.hasSameUnqualifiedType(
  5259. ParamType.getNonReferenceType(),
  5260. CandidateParamType.getNonReferenceType()))
  5261. // Two conflicting types, give up.
  5262. return QualType();
  5263. }
  5264. return ParamType;
  5265. }
  5266. static QualType
  5267. ProduceSignatureHelp(Sema &SemaRef, MutableArrayRef<ResultCandidate> Candidates,
  5268. unsigned CurrentArg, SourceLocation OpenParLoc,
  5269. bool Braced) {
  5270. if (Candidates.empty())
  5271. return QualType();
  5272. if (SemaRef.getPreprocessor().isCodeCompletionReached())
  5273. SemaRef.CodeCompleter->ProcessOverloadCandidates(
  5274. SemaRef, CurrentArg, Candidates.data(), Candidates.size(), OpenParLoc,
  5275. Braced);
  5276. return getParamType(SemaRef, Candidates, CurrentArg);
  5277. }
  5278. QualType Sema::ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args,
  5279. SourceLocation OpenParLoc) {
  5280. Fn = unwrapParenList(Fn);
  5281. if (!CodeCompleter || !Fn)
  5282. return QualType();
  5283. // FIXME: Provide support for variadic template functions.
  5284. // Ignore type-dependent call expressions entirely.
  5285. if (Fn->isTypeDependent() || anyNullArguments(Args))
  5286. return QualType();
  5287. // In presence of dependent args we surface all possible signatures using the
  5288. // non-dependent args in the prefix. Afterwards we do a post filtering to make
  5289. // sure provided candidates satisfy parameter count restrictions.
  5290. auto ArgsWithoutDependentTypes =
  5291. Args.take_while([](Expr *Arg) { return !Arg->isTypeDependent(); });
  5292. SmallVector<ResultCandidate, 8> Results;
  5293. Expr *NakedFn = Fn->IgnoreParenCasts();
  5294. // Build an overload candidate set based on the functions we find.
  5295. SourceLocation Loc = Fn->getExprLoc();
  5296. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5297. if (auto ULE = dyn_cast<UnresolvedLookupExpr>(NakedFn)) {
  5298. AddOverloadedCallCandidates(ULE, ArgsWithoutDependentTypes, CandidateSet,
  5299. /*PartialOverloading=*/true);
  5300. } else if (auto UME = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
  5301. TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
  5302. if (UME->hasExplicitTemplateArgs()) {
  5303. UME->copyTemplateArgumentsInto(TemplateArgsBuffer);
  5304. TemplateArgs = &TemplateArgsBuffer;
  5305. }
  5306. // Add the base as first argument (use a nullptr if the base is implicit).
  5307. SmallVector<Expr *, 12> ArgExprs(
  5308. 1, UME->isImplicitAccess() ? nullptr : UME->getBase());
  5309. ArgExprs.append(ArgsWithoutDependentTypes.begin(),
  5310. ArgsWithoutDependentTypes.end());
  5311. UnresolvedSet<8> Decls;
  5312. Decls.append(UME->decls_begin(), UME->decls_end());
  5313. const bool FirstArgumentIsBase = !UME->isImplicitAccess() && UME->getBase();
  5314. AddFunctionCandidates(Decls, ArgExprs, CandidateSet, TemplateArgs,
  5315. /*SuppressUserConversions=*/false,
  5316. /*PartialOverloading=*/true, FirstArgumentIsBase);
  5317. } else {
  5318. FunctionDecl *FD = nullptr;
  5319. if (auto *MCE = dyn_cast<MemberExpr>(NakedFn))
  5320. FD = dyn_cast<FunctionDecl>(MCE->getMemberDecl());
  5321. else if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn))
  5322. FD = dyn_cast<FunctionDecl>(DRE->getDecl());
  5323. if (FD) { // We check whether it's a resolved function declaration.
  5324. if (!getLangOpts().CPlusPlus ||
  5325. !FD->getType()->getAs<FunctionProtoType>())
  5326. Results.push_back(ResultCandidate(FD));
  5327. else
  5328. AddOverloadCandidate(FD, DeclAccessPair::make(FD, FD->getAccess()),
  5329. ArgsWithoutDependentTypes, CandidateSet,
  5330. /*SuppressUserConversions=*/false,
  5331. /*PartialOverloading=*/true);
  5332. } else if (auto DC = NakedFn->getType()->getAsCXXRecordDecl()) {
  5333. // If expression's type is CXXRecordDecl, it may overload the function
  5334. // call operator, so we check if it does and add them as candidates.
  5335. // A complete type is needed to lookup for member function call operators.
  5336. if (isCompleteType(Loc, NakedFn->getType())) {
  5337. DeclarationName OpName =
  5338. Context.DeclarationNames.getCXXOperatorName(OO_Call);
  5339. LookupResult R(*this, OpName, Loc, LookupOrdinaryName);
  5340. LookupQualifiedName(R, DC);
  5341. R.suppressDiagnostics();
  5342. SmallVector<Expr *, 12> ArgExprs(1, NakedFn);
  5343. ArgExprs.append(ArgsWithoutDependentTypes.begin(),
  5344. ArgsWithoutDependentTypes.end());
  5345. AddFunctionCandidates(R.asUnresolvedSet(), ArgExprs, CandidateSet,
  5346. /*ExplicitArgs=*/nullptr,
  5347. /*SuppressUserConversions=*/false,
  5348. /*PartialOverloading=*/true);
  5349. }
  5350. } else {
  5351. // Lastly we check whether expression's type is function pointer or
  5352. // function.
  5353. QualType T = NakedFn->getType();
  5354. if (!T->getPointeeType().isNull())
  5355. T = T->getPointeeType();
  5356. if (auto FP = T->getAs<FunctionProtoType>()) {
  5357. if (!TooManyArguments(FP->getNumParams(),
  5358. ArgsWithoutDependentTypes.size(),
  5359. /*PartialOverloading=*/true) ||
  5360. FP->isVariadic())
  5361. Results.push_back(ResultCandidate(FP));
  5362. } else if (auto FT = T->getAs<FunctionType>())
  5363. // No prototype and declaration, it may be a K & R style function.
  5364. Results.push_back(ResultCandidate(FT));
  5365. }
  5366. }
  5367. mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size());
  5368. QualType ParamType = ProduceSignatureHelp(*this, Results, Args.size(),
  5369. OpenParLoc, /*Braced=*/false);
  5370. return !CandidateSet.empty() ? ParamType : QualType();
  5371. }
  5372. // Determine which param to continue aggregate initialization from after
  5373. // a designated initializer.
  5374. //
  5375. // Given struct S { int a,b,c,d,e; }:
  5376. // after `S{.b=1,` we want to suggest c to continue
  5377. // after `S{.b=1, 2,` we continue with d (this is legal C and ext in C++)
  5378. // after `S{.b=1, .a=2,` we continue with b (this is legal C and ext in C++)
  5379. //
  5380. // Possible outcomes:
  5381. // - we saw a designator for a field, and continue from the returned index.
  5382. // Only aggregate initialization is allowed.
  5383. // - we saw a designator, but it was complex or we couldn't find the field.
  5384. // Only aggregate initialization is possible, but we can't assist with it.
  5385. // Returns an out-of-range index.
  5386. // - we saw no designators, just positional arguments.
  5387. // Returns None.
  5388. static llvm::Optional<unsigned>
  5389. getNextAggregateIndexAfterDesignatedInit(const ResultCandidate &Aggregate,
  5390. ArrayRef<Expr *> Args) {
  5391. static constexpr unsigned Invalid = std::numeric_limits<unsigned>::max();
  5392. assert(Aggregate.getKind() == ResultCandidate::CK_Aggregate);
  5393. // Look for designated initializers.
  5394. // They're in their syntactic form, not yet resolved to fields.
  5395. IdentifierInfo *DesignatedFieldName = nullptr;
  5396. unsigned ArgsAfterDesignator = 0;
  5397. for (const Expr *Arg : Args) {
  5398. if (const auto *DIE = dyn_cast<DesignatedInitExpr>(Arg)) {
  5399. if (DIE->size() == 1 && DIE->getDesignator(0)->isFieldDesignator()) {
  5400. DesignatedFieldName = DIE->getDesignator(0)->getFieldName();
  5401. ArgsAfterDesignator = 0;
  5402. } else {
  5403. return Invalid; // Complicated designator.
  5404. }
  5405. } else if (isa<DesignatedInitUpdateExpr>(Arg)) {
  5406. return Invalid; // Unsupported.
  5407. } else {
  5408. ++ArgsAfterDesignator;
  5409. }
  5410. }
  5411. if (!DesignatedFieldName)
  5412. return llvm::None;
  5413. // Find the index within the class's fields.
  5414. // (Probing getParamDecl() directly would be quadratic in number of fields).
  5415. unsigned DesignatedIndex = 0;
  5416. const FieldDecl *DesignatedField = nullptr;
  5417. for (const auto *Field : Aggregate.getAggregate()->fields()) {
  5418. if (Field->getIdentifier() == DesignatedFieldName) {
  5419. DesignatedField = Field;
  5420. break;
  5421. }
  5422. ++DesignatedIndex;
  5423. }
  5424. if (!DesignatedField)
  5425. return Invalid; // Designator referred to a missing field, give up.
  5426. // Find the index within the aggregate (which may have leading bases).
  5427. unsigned AggregateSize = Aggregate.getNumParams();
  5428. while (DesignatedIndex < AggregateSize &&
  5429. Aggregate.getParamDecl(DesignatedIndex) != DesignatedField)
  5430. ++DesignatedIndex;
  5431. // Continue from the index after the last named field.
  5432. return DesignatedIndex + ArgsAfterDesignator + 1;
  5433. }
  5434. QualType Sema::ProduceConstructorSignatureHelp(QualType Type,
  5435. SourceLocation Loc,
  5436. ArrayRef<Expr *> Args,
  5437. SourceLocation OpenParLoc,
  5438. bool Braced) {
  5439. if (!CodeCompleter)
  5440. return QualType();
  5441. SmallVector<ResultCandidate, 8> Results;
  5442. // A complete type is needed to lookup for constructors.
  5443. RecordDecl *RD =
  5444. isCompleteType(Loc, Type) ? Type->getAsRecordDecl() : nullptr;
  5445. if (!RD)
  5446. return Type;
  5447. CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD);
  5448. // Consider aggregate initialization.
  5449. // We don't check that types so far are correct.
  5450. // We also don't handle C99/C++17 brace-elision, we assume init-list elements
  5451. // are 1:1 with fields.
  5452. // FIXME: it would be nice to support "unwrapping" aggregates that contain
  5453. // a single subaggregate, like std::array<T, N> -> T __elements[N].
  5454. if (Braced && !RD->isUnion() &&
  5455. (!LangOpts.CPlusPlus || (CRD && CRD->isAggregate()))) {
  5456. ResultCandidate AggregateSig(RD);
  5457. unsigned AggregateSize = AggregateSig.getNumParams();
  5458. if (auto NextIndex =
  5459. getNextAggregateIndexAfterDesignatedInit(AggregateSig, Args)) {
  5460. // A designator was used, only aggregate init is possible.
  5461. if (*NextIndex >= AggregateSize)
  5462. return Type;
  5463. Results.push_back(AggregateSig);
  5464. return ProduceSignatureHelp(*this, Results, *NextIndex, OpenParLoc,
  5465. Braced);
  5466. }
  5467. // Describe aggregate initialization, but also constructors below.
  5468. if (Args.size() < AggregateSize)
  5469. Results.push_back(AggregateSig);
  5470. }
  5471. // FIXME: Provide support for member initializers.
  5472. // FIXME: Provide support for variadic template constructors.
  5473. if (CRD) {
  5474. OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
  5475. for (NamedDecl *C : LookupConstructors(CRD)) {
  5476. if (auto *FD = dyn_cast<FunctionDecl>(C)) {
  5477. // FIXME: we can't yet provide correct signature help for initializer
  5478. // list constructors, so skip them entirely.
  5479. if (Braced && LangOpts.CPlusPlus && isInitListConstructor(FD))
  5480. continue;
  5481. AddOverloadCandidate(FD, DeclAccessPair::make(FD, C->getAccess()), Args,
  5482. CandidateSet,
  5483. /*SuppressUserConversions=*/false,
  5484. /*PartialOverloading=*/true,
  5485. /*AllowExplicit*/ true);
  5486. } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(C)) {
  5487. if (Braced && LangOpts.CPlusPlus &&
  5488. isInitListConstructor(FTD->getTemplatedDecl()))
  5489. continue;
  5490. AddTemplateOverloadCandidate(
  5491. FTD, DeclAccessPair::make(FTD, C->getAccess()),
  5492. /*ExplicitTemplateArgs=*/nullptr, Args, CandidateSet,
  5493. /*SuppressUserConversions=*/false,
  5494. /*PartialOverloading=*/true);
  5495. }
  5496. }
  5497. mergeCandidatesWithResults(*this, Results, CandidateSet, Loc, Args.size());
  5498. }
  5499. return ProduceSignatureHelp(*this, Results, Args.size(), OpenParLoc, Braced);
  5500. }
  5501. QualType Sema::ProduceCtorInitMemberSignatureHelp(
  5502. Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
  5503. ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc,
  5504. bool Braced) {
  5505. if (!CodeCompleter)
  5506. return QualType();
  5507. CXXConstructorDecl *Constructor =
  5508. dyn_cast<CXXConstructorDecl>(ConstructorDecl);
  5509. if (!Constructor)
  5510. return QualType();
  5511. // FIXME: Add support for Base class constructors as well.
  5512. if (ValueDecl *MemberDecl = tryLookupCtorInitMemberDecl(
  5513. Constructor->getParent(), SS, TemplateTypeTy, II))
  5514. return ProduceConstructorSignatureHelp(MemberDecl->getType(),
  5515. MemberDecl->getLocation(), ArgExprs,
  5516. OpenParLoc, Braced);
  5517. return QualType();
  5518. }
  5519. static bool argMatchesTemplateParams(const ParsedTemplateArgument &Arg,
  5520. unsigned Index,
  5521. const TemplateParameterList &Params) {
  5522. const NamedDecl *Param;
  5523. if (Index < Params.size())
  5524. Param = Params.getParam(Index);
  5525. else if (Params.hasParameterPack())
  5526. Param = Params.asArray().back();
  5527. else
  5528. return false; // too many args
  5529. switch (Arg.getKind()) {
  5530. case ParsedTemplateArgument::Type:
  5531. return llvm::isa<TemplateTypeParmDecl>(Param); // constraints not checked
  5532. case ParsedTemplateArgument::NonType:
  5533. return llvm::isa<NonTypeTemplateParmDecl>(Param); // type not checked
  5534. case ParsedTemplateArgument::Template:
  5535. return llvm::isa<TemplateTemplateParmDecl>(Param); // signature not checked
  5536. }
  5537. llvm_unreachable("Unhandled switch case");
  5538. }
  5539. QualType Sema::ProduceTemplateArgumentSignatureHelp(
  5540. TemplateTy ParsedTemplate, ArrayRef<ParsedTemplateArgument> Args,
  5541. SourceLocation LAngleLoc) {
  5542. if (!CodeCompleter || !ParsedTemplate)
  5543. return QualType();
  5544. SmallVector<ResultCandidate, 8> Results;
  5545. auto Consider = [&](const TemplateDecl *TD) {
  5546. // Only add if the existing args are compatible with the template.
  5547. bool Matches = true;
  5548. for (unsigned I = 0; I < Args.size(); ++I) {
  5549. if (!argMatchesTemplateParams(Args[I], I, *TD->getTemplateParameters())) {
  5550. Matches = false;
  5551. break;
  5552. }
  5553. }
  5554. if (Matches)
  5555. Results.emplace_back(TD);
  5556. };
  5557. TemplateName Template = ParsedTemplate.get();
  5558. if (const auto *TD = Template.getAsTemplateDecl()) {
  5559. Consider(TD);
  5560. } else if (const auto *OTS = Template.getAsOverloadedTemplate()) {
  5561. for (const NamedDecl *ND : *OTS)
  5562. if (const auto *TD = llvm::dyn_cast<TemplateDecl>(ND))
  5563. Consider(TD);
  5564. }
  5565. return ProduceSignatureHelp(*this, Results, Args.size(), LAngleLoc,
  5566. /*Braced=*/false);
  5567. }
  5568. static QualType getDesignatedType(QualType BaseType, const Designation &Desig) {
  5569. for (unsigned I = 0; I < Desig.getNumDesignators(); ++I) {
  5570. if (BaseType.isNull())
  5571. break;
  5572. QualType NextType;
  5573. const auto &D = Desig.getDesignator(I);
  5574. if (D.isArrayDesignator() || D.isArrayRangeDesignator()) {
  5575. if (BaseType->isArrayType())
  5576. NextType = BaseType->getAsArrayTypeUnsafe()->getElementType();
  5577. } else {
  5578. assert(D.isFieldDesignator());
  5579. auto *RD = getAsRecordDecl(BaseType);
  5580. if (RD && RD->isCompleteDefinition()) {
  5581. for (const auto *Member : RD->lookup(D.getField()))
  5582. if (const FieldDecl *FD = llvm::dyn_cast<FieldDecl>(Member)) {
  5583. NextType = FD->getType();
  5584. break;
  5585. }
  5586. }
  5587. }
  5588. BaseType = NextType;
  5589. }
  5590. return BaseType;
  5591. }
  5592. void Sema::CodeCompleteDesignator(QualType BaseType,
  5593. llvm::ArrayRef<Expr *> InitExprs,
  5594. const Designation &D) {
  5595. BaseType = getDesignatedType(BaseType, D);
  5596. if (BaseType.isNull())
  5597. return;
  5598. const auto *RD = getAsRecordDecl(BaseType);
  5599. if (!RD || RD->fields().empty())
  5600. return;
  5601. CodeCompletionContext CCC(CodeCompletionContext::CCC_DotMemberAccess,
  5602. BaseType);
  5603. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5604. CodeCompleter->getCodeCompletionTUInfo(), CCC);
  5605. Results.EnterNewScope();
  5606. for (const Decl *D : RD->decls()) {
  5607. const FieldDecl *FD;
  5608. if (auto *IFD = dyn_cast<IndirectFieldDecl>(D))
  5609. FD = IFD->getAnonField();
  5610. else if (auto *DFD = dyn_cast<FieldDecl>(D))
  5611. FD = DFD;
  5612. else
  5613. continue;
  5614. // FIXME: Make use of previous designators to mark any fields before those
  5615. // inaccessible, and also compute the next initializer priority.
  5616. ResultBuilder::Result Result(FD, Results.getBasePriority(FD));
  5617. Results.AddResult(Result, CurContext, /*Hiding=*/nullptr);
  5618. }
  5619. Results.ExitScope();
  5620. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5621. Results.data(), Results.size());
  5622. }
  5623. void Sema::CodeCompleteInitializer(Scope *S, Decl *D) {
  5624. ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
  5625. if (!VD) {
  5626. CodeCompleteOrdinaryName(S, PCC_Expression);
  5627. return;
  5628. }
  5629. CodeCompleteExpressionData Data;
  5630. Data.PreferredType = VD->getType();
  5631. // Ignore VD to avoid completing the variable itself, e.g. in 'int foo = ^'.
  5632. Data.IgnoreDecls.push_back(VD);
  5633. CodeCompleteExpression(S, Data);
  5634. }
  5635. void Sema::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) {
  5636. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5637. CodeCompleter->getCodeCompletionTUInfo(),
  5638. mapCodeCompletionContext(*this, PCC_Statement));
  5639. Results.setFilter(&ResultBuilder::IsOrdinaryName);
  5640. Results.EnterNewScope();
  5641. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  5642. LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
  5643. CodeCompleter->includeGlobals(),
  5644. CodeCompleter->loadExternal());
  5645. AddOrdinaryNameResults(PCC_Statement, S, *this, Results);
  5646. // "else" block
  5647. CodeCompletionBuilder Builder(Results.getAllocator(),
  5648. Results.getCodeCompletionTUInfo());
  5649. auto AddElseBodyPattern = [&] {
  5650. if (IsBracedThen) {
  5651. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  5652. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  5653. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  5654. Builder.AddPlaceholderChunk("statements");
  5655. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  5656. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  5657. } else {
  5658. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  5659. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  5660. Builder.AddPlaceholderChunk("statement");
  5661. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  5662. }
  5663. };
  5664. Builder.AddTypedTextChunk("else");
  5665. if (Results.includeCodePatterns())
  5666. AddElseBodyPattern();
  5667. Results.AddResult(Builder.TakeString());
  5668. // "else if" block
  5669. Builder.AddTypedTextChunk("else if");
  5670. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  5671. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  5672. if (getLangOpts().CPlusPlus)
  5673. Builder.AddPlaceholderChunk("condition");
  5674. else
  5675. Builder.AddPlaceholderChunk("expression");
  5676. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  5677. if (Results.includeCodePatterns()) {
  5678. AddElseBodyPattern();
  5679. }
  5680. Results.AddResult(Builder.TakeString());
  5681. Results.ExitScope();
  5682. if (S->getFnParent())
  5683. AddPrettyFunctionResults(getLangOpts(), Results);
  5684. if (CodeCompleter->includeMacros())
  5685. AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
  5686. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5687. Results.data(), Results.size());
  5688. }
  5689. void Sema::CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS,
  5690. bool EnteringContext,
  5691. bool IsUsingDeclaration, QualType BaseType,
  5692. QualType PreferredType) {
  5693. if (SS.isEmpty() || !CodeCompleter)
  5694. return;
  5695. CodeCompletionContext CC(CodeCompletionContext::CCC_Symbol, PreferredType);
  5696. CC.setIsUsingDeclaration(IsUsingDeclaration);
  5697. CC.setCXXScopeSpecifier(SS);
  5698. // We want to keep the scope specifier even if it's invalid (e.g. the scope
  5699. // "a::b::" is not corresponding to any context/namespace in the AST), since
  5700. // it can be useful for global code completion which have information about
  5701. // contexts/symbols that are not in the AST.
  5702. if (SS.isInvalid()) {
  5703. // As SS is invalid, we try to collect accessible contexts from the current
  5704. // scope with a dummy lookup so that the completion consumer can try to
  5705. // guess what the specified scope is.
  5706. ResultBuilder DummyResults(*this, CodeCompleter->getAllocator(),
  5707. CodeCompleter->getCodeCompletionTUInfo(), CC);
  5708. if (!PreferredType.isNull())
  5709. DummyResults.setPreferredType(PreferredType);
  5710. if (S->getEntity()) {
  5711. CodeCompletionDeclConsumer Consumer(DummyResults, S->getEntity(),
  5712. BaseType);
  5713. LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
  5714. /*IncludeGlobalScope=*/false,
  5715. /*LoadExternal=*/false);
  5716. }
  5717. HandleCodeCompleteResults(this, CodeCompleter,
  5718. DummyResults.getCompletionContext(), nullptr, 0);
  5719. return;
  5720. }
  5721. // Always pretend to enter a context to ensure that a dependent type
  5722. // resolves to a dependent record.
  5723. DeclContext *Ctx = computeDeclContext(SS, /*EnteringContext=*/true);
  5724. // Try to instantiate any non-dependent declaration contexts before
  5725. // we look in them. Bail out if we fail.
  5726. NestedNameSpecifier *NNS = SS.getScopeRep();
  5727. if (NNS != nullptr && SS.isValid() && !NNS->isDependent()) {
  5728. if (Ctx == nullptr || RequireCompleteDeclContext(SS, Ctx))
  5729. return;
  5730. }
  5731. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5732. CodeCompleter->getCodeCompletionTUInfo(), CC);
  5733. if (!PreferredType.isNull())
  5734. Results.setPreferredType(PreferredType);
  5735. Results.EnterNewScope();
  5736. // The "template" keyword can follow "::" in the grammar, but only
  5737. // put it into the grammar if the nested-name-specifier is dependent.
  5738. // FIXME: results is always empty, this appears to be dead.
  5739. if (!Results.empty() && NNS->isDependent())
  5740. Results.AddResult("template");
  5741. // If the scope is a concept-constrained type parameter, infer nested
  5742. // members based on the constraints.
  5743. if (const auto *TTPT =
  5744. dyn_cast_or_null<TemplateTypeParmType>(NNS->getAsType())) {
  5745. for (const auto &R : ConceptInfo(*TTPT, S).members()) {
  5746. if (R.Operator != ConceptInfo::Member::Colons)
  5747. continue;
  5748. Results.AddResult(CodeCompletionResult(
  5749. R.render(*this, CodeCompleter->getAllocator(),
  5750. CodeCompleter->getCodeCompletionTUInfo())));
  5751. }
  5752. }
  5753. // Add calls to overridden virtual functions, if there are any.
  5754. //
  5755. // FIXME: This isn't wonderful, because we don't know whether we're actually
  5756. // in a context that permits expressions. This is a general issue with
  5757. // qualified-id completions.
  5758. if (Ctx && !EnteringContext)
  5759. MaybeAddOverrideCalls(*this, Ctx, Results);
  5760. Results.ExitScope();
  5761. if (Ctx &&
  5762. (CodeCompleter->includeNamespaceLevelDecls() || !Ctx->isFileContext())) {
  5763. CodeCompletionDeclConsumer Consumer(Results, Ctx, BaseType);
  5764. LookupVisibleDecls(Ctx, LookupOrdinaryName, Consumer,
  5765. /*IncludeGlobalScope=*/true,
  5766. /*IncludeDependentBases=*/true,
  5767. CodeCompleter->loadExternal());
  5768. }
  5769. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5770. Results.data(), Results.size());
  5771. }
  5772. void Sema::CodeCompleteUsing(Scope *S) {
  5773. if (!CodeCompleter)
  5774. return;
  5775. // This can be both a using alias or using declaration, in the former we
  5776. // expect a new name and a symbol in the latter case.
  5777. CodeCompletionContext Context(CodeCompletionContext::CCC_SymbolOrNewName);
  5778. Context.setIsUsingDeclaration(true);
  5779. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5780. CodeCompleter->getCodeCompletionTUInfo(), Context,
  5781. &ResultBuilder::IsNestedNameSpecifier);
  5782. Results.EnterNewScope();
  5783. // If we aren't in class scope, we could see the "namespace" keyword.
  5784. if (!S->isClassScope())
  5785. Results.AddResult(CodeCompletionResult("namespace"));
  5786. // After "using", we can see anything that would start a
  5787. // nested-name-specifier.
  5788. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  5789. LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
  5790. CodeCompleter->includeGlobals(),
  5791. CodeCompleter->loadExternal());
  5792. Results.ExitScope();
  5793. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5794. Results.data(), Results.size());
  5795. }
  5796. void Sema::CodeCompleteUsingDirective(Scope *S) {
  5797. if (!CodeCompleter)
  5798. return;
  5799. // After "using namespace", we expect to see a namespace name or namespace
  5800. // alias.
  5801. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5802. CodeCompleter->getCodeCompletionTUInfo(),
  5803. CodeCompletionContext::CCC_Namespace,
  5804. &ResultBuilder::IsNamespaceOrAlias);
  5805. Results.EnterNewScope();
  5806. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  5807. LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
  5808. CodeCompleter->includeGlobals(),
  5809. CodeCompleter->loadExternal());
  5810. Results.ExitScope();
  5811. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5812. Results.data(), Results.size());
  5813. }
  5814. void Sema::CodeCompleteNamespaceDecl(Scope *S) {
  5815. if (!CodeCompleter)
  5816. return;
  5817. DeclContext *Ctx = S->getEntity();
  5818. if (!S->getParent())
  5819. Ctx = Context.getTranslationUnitDecl();
  5820. bool SuppressedGlobalResults =
  5821. Ctx && !CodeCompleter->includeGlobals() && isa<TranslationUnitDecl>(Ctx);
  5822. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5823. CodeCompleter->getCodeCompletionTUInfo(),
  5824. SuppressedGlobalResults
  5825. ? CodeCompletionContext::CCC_Namespace
  5826. : CodeCompletionContext::CCC_Other,
  5827. &ResultBuilder::IsNamespace);
  5828. if (Ctx && Ctx->isFileContext() && !SuppressedGlobalResults) {
  5829. // We only want to see those namespaces that have already been defined
  5830. // within this scope, because its likely that the user is creating an
  5831. // extended namespace declaration. Keep track of the most recent
  5832. // definition of each namespace.
  5833. std::map<NamespaceDecl *, NamespaceDecl *> OrigToLatest;
  5834. for (DeclContext::specific_decl_iterator<NamespaceDecl>
  5835. NS(Ctx->decls_begin()),
  5836. NSEnd(Ctx->decls_end());
  5837. NS != NSEnd; ++NS)
  5838. OrigToLatest[NS->getOriginalNamespace()] = *NS;
  5839. // Add the most recent definition (or extended definition) of each
  5840. // namespace to the list of results.
  5841. Results.EnterNewScope();
  5842. for (std::map<NamespaceDecl *, NamespaceDecl *>::iterator
  5843. NS = OrigToLatest.begin(),
  5844. NSEnd = OrigToLatest.end();
  5845. NS != NSEnd; ++NS)
  5846. Results.AddResult(
  5847. CodeCompletionResult(NS->second, Results.getBasePriority(NS->second),
  5848. nullptr),
  5849. CurContext, nullptr, false);
  5850. Results.ExitScope();
  5851. }
  5852. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5853. Results.data(), Results.size());
  5854. }
  5855. void Sema::CodeCompleteNamespaceAliasDecl(Scope *S) {
  5856. if (!CodeCompleter)
  5857. return;
  5858. // After "namespace", we expect to see a namespace or alias.
  5859. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5860. CodeCompleter->getCodeCompletionTUInfo(),
  5861. CodeCompletionContext::CCC_Namespace,
  5862. &ResultBuilder::IsNamespaceOrAlias);
  5863. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  5864. LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
  5865. CodeCompleter->includeGlobals(),
  5866. CodeCompleter->loadExternal());
  5867. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5868. Results.data(), Results.size());
  5869. }
  5870. void Sema::CodeCompleteOperatorName(Scope *S) {
  5871. if (!CodeCompleter)
  5872. return;
  5873. typedef CodeCompletionResult Result;
  5874. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5875. CodeCompleter->getCodeCompletionTUInfo(),
  5876. CodeCompletionContext::CCC_Type,
  5877. &ResultBuilder::IsType);
  5878. Results.EnterNewScope();
  5879. // Add the names of overloadable operators. Note that OO_Conditional is not
  5880. // actually overloadable.
  5881. #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
  5882. if (OO_##Name != OO_Conditional) \
  5883. Results.AddResult(Result(Spelling));
  5884. #include "clang/Basic/OperatorKinds.def"
  5885. // Add any type names visible from the current scope
  5886. Results.allowNestedNameSpecifiers();
  5887. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  5888. LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
  5889. CodeCompleter->includeGlobals(),
  5890. CodeCompleter->loadExternal());
  5891. // Add any type specifiers
  5892. AddTypeSpecifierResults(getLangOpts(), Results);
  5893. Results.ExitScope();
  5894. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  5895. Results.data(), Results.size());
  5896. }
  5897. void Sema::CodeCompleteConstructorInitializer(
  5898. Decl *ConstructorD, ArrayRef<CXXCtorInitializer *> Initializers) {
  5899. if (!ConstructorD)
  5900. return;
  5901. AdjustDeclIfTemplate(ConstructorD);
  5902. auto *Constructor = dyn_cast<CXXConstructorDecl>(ConstructorD);
  5903. if (!Constructor)
  5904. return;
  5905. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  5906. CodeCompleter->getCodeCompletionTUInfo(),
  5907. CodeCompletionContext::CCC_Symbol);
  5908. Results.EnterNewScope();
  5909. // Fill in any already-initialized fields or base classes.
  5910. llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields;
  5911. llvm::SmallPtrSet<CanQualType, 4> InitializedBases;
  5912. for (unsigned I = 0, E = Initializers.size(); I != E; ++I) {
  5913. if (Initializers[I]->isBaseInitializer())
  5914. InitializedBases.insert(Context.getCanonicalType(
  5915. QualType(Initializers[I]->getBaseClass(), 0)));
  5916. else
  5917. InitializedFields.insert(
  5918. cast<FieldDecl>(Initializers[I]->getAnyMember()));
  5919. }
  5920. // Add completions for base classes.
  5921. PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
  5922. bool SawLastInitializer = Initializers.empty();
  5923. CXXRecordDecl *ClassDecl = Constructor->getParent();
  5924. auto GenerateCCS = [&](const NamedDecl *ND, const char *Name) {
  5925. CodeCompletionBuilder Builder(Results.getAllocator(),
  5926. Results.getCodeCompletionTUInfo());
  5927. Builder.AddTypedTextChunk(Name);
  5928. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  5929. if (const auto *Function = dyn_cast<FunctionDecl>(ND))
  5930. AddFunctionParameterChunks(PP, Policy, Function, Builder);
  5931. else if (const auto *FunTemplDecl = dyn_cast<FunctionTemplateDecl>(ND))
  5932. AddFunctionParameterChunks(PP, Policy, FunTemplDecl->getTemplatedDecl(),
  5933. Builder);
  5934. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  5935. return Builder.TakeString();
  5936. };
  5937. auto AddDefaultCtorInit = [&](const char *Name, const char *Type,
  5938. const NamedDecl *ND) {
  5939. CodeCompletionBuilder Builder(Results.getAllocator(),
  5940. Results.getCodeCompletionTUInfo());
  5941. Builder.AddTypedTextChunk(Name);
  5942. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  5943. Builder.AddPlaceholderChunk(Type);
  5944. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  5945. if (ND) {
  5946. auto CCR = CodeCompletionResult(
  5947. Builder.TakeString(), ND,
  5948. SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration);
  5949. if (isa<FieldDecl>(ND))
  5950. CCR.CursorKind = CXCursor_MemberRef;
  5951. return Results.AddResult(CCR);
  5952. }
  5953. return Results.AddResult(CodeCompletionResult(
  5954. Builder.TakeString(),
  5955. SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration));
  5956. };
  5957. auto AddCtorsWithName = [&](const CXXRecordDecl *RD, unsigned int Priority,
  5958. const char *Name, const FieldDecl *FD) {
  5959. if (!RD)
  5960. return AddDefaultCtorInit(Name,
  5961. FD ? Results.getAllocator().CopyString(
  5962. FD->getType().getAsString(Policy))
  5963. : Name,
  5964. FD);
  5965. auto Ctors = getConstructors(Context, RD);
  5966. if (Ctors.begin() == Ctors.end())
  5967. return AddDefaultCtorInit(Name, Name, RD);
  5968. for (const NamedDecl *Ctor : Ctors) {
  5969. auto CCR = CodeCompletionResult(GenerateCCS(Ctor, Name), RD, Priority);
  5970. CCR.CursorKind = getCursorKindForDecl(Ctor);
  5971. Results.AddResult(CCR);
  5972. }
  5973. };
  5974. auto AddBase = [&](const CXXBaseSpecifier &Base) {
  5975. const char *BaseName =
  5976. Results.getAllocator().CopyString(Base.getType().getAsString(Policy));
  5977. const auto *RD = Base.getType()->getAsCXXRecordDecl();
  5978. AddCtorsWithName(
  5979. RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
  5980. BaseName, nullptr);
  5981. };
  5982. auto AddField = [&](const FieldDecl *FD) {
  5983. const char *FieldName =
  5984. Results.getAllocator().CopyString(FD->getIdentifier()->getName());
  5985. const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
  5986. AddCtorsWithName(
  5987. RD, SawLastInitializer ? CCP_NextInitializer : CCP_MemberDeclaration,
  5988. FieldName, FD);
  5989. };
  5990. for (const auto &Base : ClassDecl->bases()) {
  5991. if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
  5992. .second) {
  5993. SawLastInitializer =
  5994. !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
  5995. Context.hasSameUnqualifiedType(
  5996. Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
  5997. continue;
  5998. }
  5999. AddBase(Base);
  6000. SawLastInitializer = false;
  6001. }
  6002. // Add completions for virtual base classes.
  6003. for (const auto &Base : ClassDecl->vbases()) {
  6004. if (!InitializedBases.insert(Context.getCanonicalType(Base.getType()))
  6005. .second) {
  6006. SawLastInitializer =
  6007. !Initializers.empty() && Initializers.back()->isBaseInitializer() &&
  6008. Context.hasSameUnqualifiedType(
  6009. Base.getType(), QualType(Initializers.back()->getBaseClass(), 0));
  6010. continue;
  6011. }
  6012. AddBase(Base);
  6013. SawLastInitializer = false;
  6014. }
  6015. // Add completions for members.
  6016. for (auto *Field : ClassDecl->fields()) {
  6017. if (!InitializedFields.insert(cast<FieldDecl>(Field->getCanonicalDecl()))
  6018. .second) {
  6019. SawLastInitializer = !Initializers.empty() &&
  6020. Initializers.back()->isAnyMemberInitializer() &&
  6021. Initializers.back()->getAnyMember() == Field;
  6022. continue;
  6023. }
  6024. if (!Field->getDeclName())
  6025. continue;
  6026. AddField(Field);
  6027. SawLastInitializer = false;
  6028. }
  6029. Results.ExitScope();
  6030. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  6031. Results.data(), Results.size());
  6032. }
  6033. /// Determine whether this scope denotes a namespace.
  6034. static bool isNamespaceScope(Scope *S) {
  6035. DeclContext *DC = S->getEntity();
  6036. if (!DC)
  6037. return false;
  6038. return DC->isFileContext();
  6039. }
  6040. void Sema::CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
  6041. bool AfterAmpersand) {
  6042. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  6043. CodeCompleter->getCodeCompletionTUInfo(),
  6044. CodeCompletionContext::CCC_Other);
  6045. Results.EnterNewScope();
  6046. // Note what has already been captured.
  6047. llvm::SmallPtrSet<IdentifierInfo *, 4> Known;
  6048. bool IncludedThis = false;
  6049. for (const auto &C : Intro.Captures) {
  6050. if (C.Kind == LCK_This) {
  6051. IncludedThis = true;
  6052. continue;
  6053. }
  6054. Known.insert(C.Id);
  6055. }
  6056. // Look for other capturable variables.
  6057. for (; S && !isNamespaceScope(S); S = S->getParent()) {
  6058. for (const auto *D : S->decls()) {
  6059. const auto *Var = dyn_cast<VarDecl>(D);
  6060. if (!Var || !Var->hasLocalStorage() || Var->hasAttr<BlocksAttr>())
  6061. continue;
  6062. if (Known.insert(Var->getIdentifier()).second)
  6063. Results.AddResult(CodeCompletionResult(Var, CCP_LocalDeclaration),
  6064. CurContext, nullptr, false);
  6065. }
  6066. }
  6067. // Add 'this', if it would be valid.
  6068. if (!IncludedThis && !AfterAmpersand && Intro.Default != LCD_ByCopy)
  6069. addThisCompletion(*this, Results);
  6070. Results.ExitScope();
  6071. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  6072. Results.data(), Results.size());
  6073. }
  6074. void Sema::CodeCompleteAfterFunctionEquals(Declarator &D) {
  6075. if (!LangOpts.CPlusPlus11)
  6076. return;
  6077. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  6078. CodeCompleter->getCodeCompletionTUInfo(),
  6079. CodeCompletionContext::CCC_Other);
  6080. auto ShouldAddDefault = [&D, this]() {
  6081. if (!D.isFunctionDeclarator())
  6082. return false;
  6083. auto &Id = D.getName();
  6084. if (Id.getKind() == UnqualifiedIdKind::IK_DestructorName)
  6085. return true;
  6086. // FIXME(liuhui): Ideally, we should check the constructor parameter list to
  6087. // verify that it is the default, copy or move constructor?
  6088. if (Id.getKind() == UnqualifiedIdKind::IK_ConstructorName &&
  6089. D.getFunctionTypeInfo().NumParams <= 1)
  6090. return true;
  6091. if (Id.getKind() == UnqualifiedIdKind::IK_OperatorFunctionId) {
  6092. auto Op = Id.OperatorFunctionId.Operator;
  6093. // FIXME(liuhui): Ideally, we should check the function parameter list to
  6094. // verify that it is the copy or move assignment?
  6095. if (Op == OverloadedOperatorKind::OO_Equal)
  6096. return true;
  6097. if (LangOpts.CPlusPlus20 &&
  6098. (Op == OverloadedOperatorKind::OO_EqualEqual ||
  6099. Op == OverloadedOperatorKind::OO_ExclaimEqual ||
  6100. Op == OverloadedOperatorKind::OO_Less ||
  6101. Op == OverloadedOperatorKind::OO_LessEqual ||
  6102. Op == OverloadedOperatorKind::OO_Greater ||
  6103. Op == OverloadedOperatorKind::OO_GreaterEqual ||
  6104. Op == OverloadedOperatorKind::OO_Spaceship))
  6105. return true;
  6106. }
  6107. return false;
  6108. };
  6109. Results.EnterNewScope();
  6110. if (ShouldAddDefault())
  6111. Results.AddResult("default");
  6112. // FIXME(liuhui): Ideally, we should only provide `delete` completion for the
  6113. // first function declaration.
  6114. Results.AddResult("delete");
  6115. Results.ExitScope();
  6116. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  6117. Results.data(), Results.size());
  6118. }
  6119. /// Macro that optionally prepends an "@" to the string literal passed in via
  6120. /// Keyword, depending on whether NeedAt is true or false.
  6121. #define OBJC_AT_KEYWORD_NAME(NeedAt, Keyword) ((NeedAt) ? "@" Keyword : Keyword)
  6122. static void AddObjCImplementationResults(const LangOptions &LangOpts,
  6123. ResultBuilder &Results, bool NeedAt) {
  6124. typedef CodeCompletionResult Result;
  6125. // Since we have an implementation, we can end it.
  6126. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
  6127. CodeCompletionBuilder Builder(Results.getAllocator(),
  6128. Results.getCodeCompletionTUInfo());
  6129. if (LangOpts.ObjC) {
  6130. // @dynamic
  6131. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "dynamic"));
  6132. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6133. Builder.AddPlaceholderChunk("property");
  6134. Results.AddResult(Result(Builder.TakeString()));
  6135. // @synthesize
  6136. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synthesize"));
  6137. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6138. Builder.AddPlaceholderChunk("property");
  6139. Results.AddResult(Result(Builder.TakeString()));
  6140. }
  6141. }
  6142. static void AddObjCInterfaceResults(const LangOptions &LangOpts,
  6143. ResultBuilder &Results, bool NeedAt) {
  6144. typedef CodeCompletionResult Result;
  6145. // Since we have an interface or protocol, we can end it.
  6146. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "end")));
  6147. if (LangOpts.ObjC) {
  6148. // @property
  6149. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "property")));
  6150. // @required
  6151. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "required")));
  6152. // @optional
  6153. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "optional")));
  6154. }
  6155. }
  6156. static void AddObjCTopLevelResults(ResultBuilder &Results, bool NeedAt) {
  6157. typedef CodeCompletionResult Result;
  6158. CodeCompletionBuilder Builder(Results.getAllocator(),
  6159. Results.getCodeCompletionTUInfo());
  6160. // @class name ;
  6161. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "class"));
  6162. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6163. Builder.AddPlaceholderChunk("name");
  6164. Results.AddResult(Result(Builder.TakeString()));
  6165. if (Results.includeCodePatterns()) {
  6166. // @interface name
  6167. // FIXME: Could introduce the whole pattern, including superclasses and
  6168. // such.
  6169. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "interface"));
  6170. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6171. Builder.AddPlaceholderChunk("class");
  6172. Results.AddResult(Result(Builder.TakeString()));
  6173. // @protocol name
  6174. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
  6175. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6176. Builder.AddPlaceholderChunk("protocol");
  6177. Results.AddResult(Result(Builder.TakeString()));
  6178. // @implementation name
  6179. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "implementation"));
  6180. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6181. Builder.AddPlaceholderChunk("class");
  6182. Results.AddResult(Result(Builder.TakeString()));
  6183. }
  6184. // @compatibility_alias name
  6185. Builder.AddTypedTextChunk(
  6186. OBJC_AT_KEYWORD_NAME(NeedAt, "compatibility_alias"));
  6187. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6188. Builder.AddPlaceholderChunk("alias");
  6189. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6190. Builder.AddPlaceholderChunk("class");
  6191. Results.AddResult(Result(Builder.TakeString()));
  6192. if (Results.getSema().getLangOpts().Modules) {
  6193. // @import name
  6194. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "import"));
  6195. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6196. Builder.AddPlaceholderChunk("module");
  6197. Results.AddResult(Result(Builder.TakeString()));
  6198. }
  6199. }
  6200. void Sema::CodeCompleteObjCAtDirective(Scope *S) {
  6201. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  6202. CodeCompleter->getCodeCompletionTUInfo(),
  6203. CodeCompletionContext::CCC_Other);
  6204. Results.EnterNewScope();
  6205. if (isa<ObjCImplDecl>(CurContext))
  6206. AddObjCImplementationResults(getLangOpts(), Results, false);
  6207. else if (CurContext->isObjCContainer())
  6208. AddObjCInterfaceResults(getLangOpts(), Results, false);
  6209. else
  6210. AddObjCTopLevelResults(Results, false);
  6211. Results.ExitScope();
  6212. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  6213. Results.data(), Results.size());
  6214. }
  6215. static void AddObjCExpressionResults(ResultBuilder &Results, bool NeedAt) {
  6216. typedef CodeCompletionResult Result;
  6217. CodeCompletionBuilder Builder(Results.getAllocator(),
  6218. Results.getCodeCompletionTUInfo());
  6219. // @encode ( type-name )
  6220. const char *EncodeType = "char[]";
  6221. if (Results.getSema().getLangOpts().CPlusPlus ||
  6222. Results.getSema().getLangOpts().ConstStrings)
  6223. EncodeType = "const char[]";
  6224. Builder.AddResultTypeChunk(EncodeType);
  6225. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "encode"));
  6226. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  6227. Builder.AddPlaceholderChunk("type-name");
  6228. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  6229. Results.AddResult(Result(Builder.TakeString()));
  6230. // @protocol ( protocol-name )
  6231. Builder.AddResultTypeChunk("Protocol *");
  6232. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "protocol"));
  6233. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  6234. Builder.AddPlaceholderChunk("protocol-name");
  6235. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  6236. Results.AddResult(Result(Builder.TakeString()));
  6237. // @selector ( selector )
  6238. Builder.AddResultTypeChunk("SEL");
  6239. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "selector"));
  6240. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  6241. Builder.AddPlaceholderChunk("selector");
  6242. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  6243. Results.AddResult(Result(Builder.TakeString()));
  6244. // @"string"
  6245. Builder.AddResultTypeChunk("NSString *");
  6246. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "\""));
  6247. Builder.AddPlaceholderChunk("string");
  6248. Builder.AddTextChunk("\"");
  6249. Results.AddResult(Result(Builder.TakeString()));
  6250. // @[objects, ...]
  6251. Builder.AddResultTypeChunk("NSArray *");
  6252. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "["));
  6253. Builder.AddPlaceholderChunk("objects, ...");
  6254. Builder.AddChunk(CodeCompletionString::CK_RightBracket);
  6255. Results.AddResult(Result(Builder.TakeString()));
  6256. // @{key : object, ...}
  6257. Builder.AddResultTypeChunk("NSDictionary *");
  6258. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "{"));
  6259. Builder.AddPlaceholderChunk("key");
  6260. Builder.AddChunk(CodeCompletionString::CK_Colon);
  6261. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6262. Builder.AddPlaceholderChunk("object, ...");
  6263. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  6264. Results.AddResult(Result(Builder.TakeString()));
  6265. // @(expression)
  6266. Builder.AddResultTypeChunk("id");
  6267. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "("));
  6268. Builder.AddPlaceholderChunk("expression");
  6269. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  6270. Results.AddResult(Result(Builder.TakeString()));
  6271. }
  6272. static void AddObjCStatementResults(ResultBuilder &Results, bool NeedAt) {
  6273. typedef CodeCompletionResult Result;
  6274. CodeCompletionBuilder Builder(Results.getAllocator(),
  6275. Results.getCodeCompletionTUInfo());
  6276. if (Results.includeCodePatterns()) {
  6277. // @try { statements } @catch ( declaration ) { statements } @finally
  6278. // { statements }
  6279. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "try"));
  6280. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  6281. Builder.AddPlaceholderChunk("statements");
  6282. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  6283. Builder.AddTextChunk("@catch");
  6284. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  6285. Builder.AddPlaceholderChunk("parameter");
  6286. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  6287. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  6288. Builder.AddPlaceholderChunk("statements");
  6289. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  6290. Builder.AddTextChunk("@finally");
  6291. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  6292. Builder.AddPlaceholderChunk("statements");
  6293. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  6294. Results.AddResult(Result(Builder.TakeString()));
  6295. }
  6296. // @throw
  6297. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "throw"));
  6298. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6299. Builder.AddPlaceholderChunk("expression");
  6300. Results.AddResult(Result(Builder.TakeString()));
  6301. if (Results.includeCodePatterns()) {
  6302. // @synchronized ( expression ) { statements }
  6303. Builder.AddTypedTextChunk(OBJC_AT_KEYWORD_NAME(NeedAt, "synchronized"));
  6304. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6305. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  6306. Builder.AddPlaceholderChunk("expression");
  6307. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  6308. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  6309. Builder.AddPlaceholderChunk("statements");
  6310. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  6311. Results.AddResult(Result(Builder.TakeString()));
  6312. }
  6313. }
  6314. static void AddObjCVisibilityResults(const LangOptions &LangOpts,
  6315. ResultBuilder &Results, bool NeedAt) {
  6316. typedef CodeCompletionResult Result;
  6317. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "private")));
  6318. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "protected")));
  6319. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "public")));
  6320. if (LangOpts.ObjC)
  6321. Results.AddResult(Result(OBJC_AT_KEYWORD_NAME(NeedAt, "package")));
  6322. }
  6323. void Sema::CodeCompleteObjCAtVisibility(Scope *S) {
  6324. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  6325. CodeCompleter->getCodeCompletionTUInfo(),
  6326. CodeCompletionContext::CCC_Other);
  6327. Results.EnterNewScope();
  6328. AddObjCVisibilityResults(getLangOpts(), Results, false);
  6329. Results.ExitScope();
  6330. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  6331. Results.data(), Results.size());
  6332. }
  6333. void Sema::CodeCompleteObjCAtStatement(Scope *S) {
  6334. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  6335. CodeCompleter->getCodeCompletionTUInfo(),
  6336. CodeCompletionContext::CCC_Other);
  6337. Results.EnterNewScope();
  6338. AddObjCStatementResults(Results, false);
  6339. AddObjCExpressionResults(Results, false);
  6340. Results.ExitScope();
  6341. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  6342. Results.data(), Results.size());
  6343. }
  6344. void Sema::CodeCompleteObjCAtExpression(Scope *S) {
  6345. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  6346. CodeCompleter->getCodeCompletionTUInfo(),
  6347. CodeCompletionContext::CCC_Other);
  6348. Results.EnterNewScope();
  6349. AddObjCExpressionResults(Results, false);
  6350. Results.ExitScope();
  6351. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  6352. Results.data(), Results.size());
  6353. }
  6354. /// Determine whether the addition of the given flag to an Objective-C
  6355. /// property's attributes will cause a conflict.
  6356. static bool ObjCPropertyFlagConflicts(unsigned Attributes, unsigned NewFlag) {
  6357. // Check if we've already added this flag.
  6358. if (Attributes & NewFlag)
  6359. return true;
  6360. Attributes |= NewFlag;
  6361. // Check for collisions with "readonly".
  6362. if ((Attributes & ObjCPropertyAttribute::kind_readonly) &&
  6363. (Attributes & ObjCPropertyAttribute::kind_readwrite))
  6364. return true;
  6365. // Check for more than one of { assign, copy, retain, strong, weak }.
  6366. unsigned AssignCopyRetMask =
  6367. Attributes &
  6368. (ObjCPropertyAttribute::kind_assign |
  6369. ObjCPropertyAttribute::kind_unsafe_unretained |
  6370. ObjCPropertyAttribute::kind_copy | ObjCPropertyAttribute::kind_retain |
  6371. ObjCPropertyAttribute::kind_strong | ObjCPropertyAttribute::kind_weak);
  6372. if (AssignCopyRetMask &&
  6373. AssignCopyRetMask != ObjCPropertyAttribute::kind_assign &&
  6374. AssignCopyRetMask != ObjCPropertyAttribute::kind_unsafe_unretained &&
  6375. AssignCopyRetMask != ObjCPropertyAttribute::kind_copy &&
  6376. AssignCopyRetMask != ObjCPropertyAttribute::kind_retain &&
  6377. AssignCopyRetMask != ObjCPropertyAttribute::kind_strong &&
  6378. AssignCopyRetMask != ObjCPropertyAttribute::kind_weak)
  6379. return true;
  6380. return false;
  6381. }
  6382. void Sema::CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS) {
  6383. if (!CodeCompleter)
  6384. return;
  6385. unsigned Attributes = ODS.getPropertyAttributes();
  6386. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  6387. CodeCompleter->getCodeCompletionTUInfo(),
  6388. CodeCompletionContext::CCC_Other);
  6389. Results.EnterNewScope();
  6390. if (!ObjCPropertyFlagConflicts(Attributes,
  6391. ObjCPropertyAttribute::kind_readonly))
  6392. Results.AddResult(CodeCompletionResult("readonly"));
  6393. if (!ObjCPropertyFlagConflicts(Attributes,
  6394. ObjCPropertyAttribute::kind_assign))
  6395. Results.AddResult(CodeCompletionResult("assign"));
  6396. if (!ObjCPropertyFlagConflicts(Attributes,
  6397. ObjCPropertyAttribute::kind_unsafe_unretained))
  6398. Results.AddResult(CodeCompletionResult("unsafe_unretained"));
  6399. if (!ObjCPropertyFlagConflicts(Attributes,
  6400. ObjCPropertyAttribute::kind_readwrite))
  6401. Results.AddResult(CodeCompletionResult("readwrite"));
  6402. if (!ObjCPropertyFlagConflicts(Attributes,
  6403. ObjCPropertyAttribute::kind_retain))
  6404. Results.AddResult(CodeCompletionResult("retain"));
  6405. if (!ObjCPropertyFlagConflicts(Attributes,
  6406. ObjCPropertyAttribute::kind_strong))
  6407. Results.AddResult(CodeCompletionResult("strong"));
  6408. if (!ObjCPropertyFlagConflicts(Attributes, ObjCPropertyAttribute::kind_copy))
  6409. Results.AddResult(CodeCompletionResult("copy"));
  6410. if (!ObjCPropertyFlagConflicts(Attributes,
  6411. ObjCPropertyAttribute::kind_nonatomic))
  6412. Results.AddResult(CodeCompletionResult("nonatomic"));
  6413. if (!ObjCPropertyFlagConflicts(Attributes,
  6414. ObjCPropertyAttribute::kind_atomic))
  6415. Results.AddResult(CodeCompletionResult("atomic"));
  6416. // Only suggest "weak" if we're compiling for ARC-with-weak-references or GC.
  6417. if (getLangOpts().ObjCWeak || getLangOpts().getGC() != LangOptions::NonGC)
  6418. if (!ObjCPropertyFlagConflicts(Attributes,
  6419. ObjCPropertyAttribute::kind_weak))
  6420. Results.AddResult(CodeCompletionResult("weak"));
  6421. if (!ObjCPropertyFlagConflicts(Attributes,
  6422. ObjCPropertyAttribute::kind_setter)) {
  6423. CodeCompletionBuilder Setter(Results.getAllocator(),
  6424. Results.getCodeCompletionTUInfo());
  6425. Setter.AddTypedTextChunk("setter");
  6426. Setter.AddTextChunk("=");
  6427. Setter.AddPlaceholderChunk("method");
  6428. Results.AddResult(CodeCompletionResult(Setter.TakeString()));
  6429. }
  6430. if (!ObjCPropertyFlagConflicts(Attributes,
  6431. ObjCPropertyAttribute::kind_getter)) {
  6432. CodeCompletionBuilder Getter(Results.getAllocator(),
  6433. Results.getCodeCompletionTUInfo());
  6434. Getter.AddTypedTextChunk("getter");
  6435. Getter.AddTextChunk("=");
  6436. Getter.AddPlaceholderChunk("method");
  6437. Results.AddResult(CodeCompletionResult(Getter.TakeString()));
  6438. }
  6439. if (!ObjCPropertyFlagConflicts(Attributes,
  6440. ObjCPropertyAttribute::kind_nullability)) {
  6441. Results.AddResult(CodeCompletionResult("nonnull"));
  6442. Results.AddResult(CodeCompletionResult("nullable"));
  6443. Results.AddResult(CodeCompletionResult("null_unspecified"));
  6444. Results.AddResult(CodeCompletionResult("null_resettable"));
  6445. }
  6446. Results.ExitScope();
  6447. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  6448. Results.data(), Results.size());
  6449. }
  6450. /// Describes the kind of Objective-C method that we want to find
  6451. /// via code completion.
  6452. enum ObjCMethodKind {
  6453. MK_Any, ///< Any kind of method, provided it means other specified criteria.
  6454. MK_ZeroArgSelector, ///< Zero-argument (unary) selector.
  6455. MK_OneArgSelector ///< One-argument selector.
  6456. };
  6457. static bool isAcceptableObjCSelector(Selector Sel, ObjCMethodKind WantKind,
  6458. ArrayRef<IdentifierInfo *> SelIdents,
  6459. bool AllowSameLength = true) {
  6460. unsigned NumSelIdents = SelIdents.size();
  6461. if (NumSelIdents > Sel.getNumArgs())
  6462. return false;
  6463. switch (WantKind) {
  6464. case MK_Any:
  6465. break;
  6466. case MK_ZeroArgSelector:
  6467. return Sel.isUnarySelector();
  6468. case MK_OneArgSelector:
  6469. return Sel.getNumArgs() == 1;
  6470. }
  6471. if (!AllowSameLength && NumSelIdents && NumSelIdents == Sel.getNumArgs())
  6472. return false;
  6473. for (unsigned I = 0; I != NumSelIdents; ++I)
  6474. if (SelIdents[I] != Sel.getIdentifierInfoForSlot(I))
  6475. return false;
  6476. return true;
  6477. }
  6478. static bool isAcceptableObjCMethod(ObjCMethodDecl *Method,
  6479. ObjCMethodKind WantKind,
  6480. ArrayRef<IdentifierInfo *> SelIdents,
  6481. bool AllowSameLength = true) {
  6482. return isAcceptableObjCSelector(Method->getSelector(), WantKind, SelIdents,
  6483. AllowSameLength);
  6484. }
  6485. /// A set of selectors, which is used to avoid introducing multiple
  6486. /// completions with the same selector into the result set.
  6487. typedef llvm::SmallPtrSet<Selector, 16> VisitedSelectorSet;
  6488. /// Add all of the Objective-C methods in the given Objective-C
  6489. /// container to the set of results.
  6490. ///
  6491. /// The container will be a class, protocol, category, or implementation of
  6492. /// any of the above. This mether will recurse to include methods from
  6493. /// the superclasses of classes along with their categories, protocols, and
  6494. /// implementations.
  6495. ///
  6496. /// \param Container the container in which we'll look to find methods.
  6497. ///
  6498. /// \param WantInstanceMethods Whether to add instance methods (only); if
  6499. /// false, this routine will add factory methods (only).
  6500. ///
  6501. /// \param CurContext the context in which we're performing the lookup that
  6502. /// finds methods.
  6503. ///
  6504. /// \param AllowSameLength Whether we allow a method to be added to the list
  6505. /// when it has the same number of parameters as we have selector identifiers.
  6506. ///
  6507. /// \param Results the structure into which we'll add results.
  6508. static void AddObjCMethods(ObjCContainerDecl *Container,
  6509. bool WantInstanceMethods, ObjCMethodKind WantKind,
  6510. ArrayRef<IdentifierInfo *> SelIdents,
  6511. DeclContext *CurContext,
  6512. VisitedSelectorSet &Selectors, bool AllowSameLength,
  6513. ResultBuilder &Results, bool InOriginalClass = true,
  6514. bool IsRootClass = false) {
  6515. typedef CodeCompletionResult Result;
  6516. Container = getContainerDef(Container);
  6517. ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container);
  6518. IsRootClass = IsRootClass || (IFace && !IFace->getSuperClass());
  6519. for (ObjCMethodDecl *M : Container->methods()) {
  6520. // The instance methods on the root class can be messaged via the
  6521. // metaclass.
  6522. if (M->isInstanceMethod() == WantInstanceMethods ||
  6523. (IsRootClass && !WantInstanceMethods)) {
  6524. // Check whether the selector identifiers we've been given are a
  6525. // subset of the identifiers for this particular method.
  6526. if (!isAcceptableObjCMethod(M, WantKind, SelIdents, AllowSameLength))
  6527. continue;
  6528. if (!Selectors.insert(M->getSelector()).second)
  6529. continue;
  6530. Result R = Result(M, Results.getBasePriority(M), nullptr);
  6531. R.StartParameter = SelIdents.size();
  6532. R.AllParametersAreInformative = (WantKind != MK_Any);
  6533. if (!InOriginalClass)
  6534. setInBaseClass(R);
  6535. Results.MaybeAddResult(R, CurContext);
  6536. }
  6537. }
  6538. // Visit the protocols of protocols.
  6539. if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
  6540. if (Protocol->hasDefinition()) {
  6541. const ObjCList<ObjCProtocolDecl> &Protocols =
  6542. Protocol->getReferencedProtocols();
  6543. for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
  6544. E = Protocols.end();
  6545. I != E; ++I)
  6546. AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
  6547. Selectors, AllowSameLength, Results, false, IsRootClass);
  6548. }
  6549. }
  6550. if (!IFace || !IFace->hasDefinition())
  6551. return;
  6552. // Add methods in protocols.
  6553. for (ObjCProtocolDecl *I : IFace->protocols())
  6554. AddObjCMethods(I, WantInstanceMethods, WantKind, SelIdents, CurContext,
  6555. Selectors, AllowSameLength, Results, false, IsRootClass);
  6556. // Add methods in categories.
  6557. for (ObjCCategoryDecl *CatDecl : IFace->known_categories()) {
  6558. AddObjCMethods(CatDecl, WantInstanceMethods, WantKind, SelIdents,
  6559. CurContext, Selectors, AllowSameLength, Results,
  6560. InOriginalClass, IsRootClass);
  6561. // Add a categories protocol methods.
  6562. const ObjCList<ObjCProtocolDecl> &Protocols =
  6563. CatDecl->getReferencedProtocols();
  6564. for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
  6565. E = Protocols.end();
  6566. I != E; ++I)
  6567. AddObjCMethods(*I, WantInstanceMethods, WantKind, SelIdents, CurContext,
  6568. Selectors, AllowSameLength, Results, false, IsRootClass);
  6569. // Add methods in category implementations.
  6570. if (ObjCCategoryImplDecl *Impl = CatDecl->getImplementation())
  6571. AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
  6572. Selectors, AllowSameLength, Results, InOriginalClass,
  6573. IsRootClass);
  6574. }
  6575. // Add methods in superclass.
  6576. // Avoid passing in IsRootClass since root classes won't have super classes.
  6577. if (IFace->getSuperClass())
  6578. AddObjCMethods(IFace->getSuperClass(), WantInstanceMethods, WantKind,
  6579. SelIdents, CurContext, Selectors, AllowSameLength, Results,
  6580. /*IsRootClass=*/false);
  6581. // Add methods in our implementation, if any.
  6582. if (ObjCImplementationDecl *Impl = IFace->getImplementation())
  6583. AddObjCMethods(Impl, WantInstanceMethods, WantKind, SelIdents, CurContext,
  6584. Selectors, AllowSameLength, Results, InOriginalClass,
  6585. IsRootClass);
  6586. }
  6587. void Sema::CodeCompleteObjCPropertyGetter(Scope *S) {
  6588. // Try to find the interface where getters might live.
  6589. ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
  6590. if (!Class) {
  6591. if (ObjCCategoryDecl *Category =
  6592. dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
  6593. Class = Category->getClassInterface();
  6594. if (!Class)
  6595. return;
  6596. }
  6597. // Find all of the potential getters.
  6598. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  6599. CodeCompleter->getCodeCompletionTUInfo(),
  6600. CodeCompletionContext::CCC_Other);
  6601. Results.EnterNewScope();
  6602. VisitedSelectorSet Selectors;
  6603. AddObjCMethods(Class, true, MK_ZeroArgSelector, None, CurContext, Selectors,
  6604. /*AllowSameLength=*/true, Results);
  6605. Results.ExitScope();
  6606. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  6607. Results.data(), Results.size());
  6608. }
  6609. void Sema::CodeCompleteObjCPropertySetter(Scope *S) {
  6610. // Try to find the interface where setters might live.
  6611. ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurContext);
  6612. if (!Class) {
  6613. if (ObjCCategoryDecl *Category =
  6614. dyn_cast_or_null<ObjCCategoryDecl>(CurContext))
  6615. Class = Category->getClassInterface();
  6616. if (!Class)
  6617. return;
  6618. }
  6619. // Find all of the potential getters.
  6620. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  6621. CodeCompleter->getCodeCompletionTUInfo(),
  6622. CodeCompletionContext::CCC_Other);
  6623. Results.EnterNewScope();
  6624. VisitedSelectorSet Selectors;
  6625. AddObjCMethods(Class, true, MK_OneArgSelector, None, CurContext, Selectors,
  6626. /*AllowSameLength=*/true, Results);
  6627. Results.ExitScope();
  6628. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  6629. Results.data(), Results.size());
  6630. }
  6631. void Sema::CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
  6632. bool IsParameter) {
  6633. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  6634. CodeCompleter->getCodeCompletionTUInfo(),
  6635. CodeCompletionContext::CCC_Type);
  6636. Results.EnterNewScope();
  6637. // Add context-sensitive, Objective-C parameter-passing keywords.
  6638. bool AddedInOut = false;
  6639. if ((DS.getObjCDeclQualifier() &
  6640. (ObjCDeclSpec::DQ_In | ObjCDeclSpec::DQ_Inout)) == 0) {
  6641. Results.AddResult("in");
  6642. Results.AddResult("inout");
  6643. AddedInOut = true;
  6644. }
  6645. if ((DS.getObjCDeclQualifier() &
  6646. (ObjCDeclSpec::DQ_Out | ObjCDeclSpec::DQ_Inout)) == 0) {
  6647. Results.AddResult("out");
  6648. if (!AddedInOut)
  6649. Results.AddResult("inout");
  6650. }
  6651. if ((DS.getObjCDeclQualifier() &
  6652. (ObjCDeclSpec::DQ_Bycopy | ObjCDeclSpec::DQ_Byref |
  6653. ObjCDeclSpec::DQ_Oneway)) == 0) {
  6654. Results.AddResult("bycopy");
  6655. Results.AddResult("byref");
  6656. Results.AddResult("oneway");
  6657. }
  6658. if ((DS.getObjCDeclQualifier() & ObjCDeclSpec::DQ_CSNullability) == 0) {
  6659. Results.AddResult("nonnull");
  6660. Results.AddResult("nullable");
  6661. Results.AddResult("null_unspecified");
  6662. }
  6663. // If we're completing the return type of an Objective-C method and the
  6664. // identifier IBAction refers to a macro, provide a completion item for
  6665. // an action, e.g.,
  6666. // IBAction)<#selector#>:(id)sender
  6667. if (DS.getObjCDeclQualifier() == 0 && !IsParameter &&
  6668. PP.isMacroDefined("IBAction")) {
  6669. CodeCompletionBuilder Builder(Results.getAllocator(),
  6670. Results.getCodeCompletionTUInfo(),
  6671. CCP_CodePattern, CXAvailability_Available);
  6672. Builder.AddTypedTextChunk("IBAction");
  6673. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  6674. Builder.AddPlaceholderChunk("selector");
  6675. Builder.AddChunk(CodeCompletionString::CK_Colon);
  6676. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  6677. Builder.AddTextChunk("id");
  6678. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  6679. Builder.AddTextChunk("sender");
  6680. Results.AddResult(CodeCompletionResult(Builder.TakeString()));
  6681. }
  6682. // If we're completing the return type, provide 'instancetype'.
  6683. if (!IsParameter) {
  6684. Results.AddResult(CodeCompletionResult("instancetype"));
  6685. }
  6686. // Add various builtin type names and specifiers.
  6687. AddOrdinaryNameResults(PCC_Type, S, *this, Results);
  6688. Results.ExitScope();
  6689. // Add the various type names
  6690. Results.setFilter(&ResultBuilder::IsOrdinaryNonValueName);
  6691. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  6692. LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
  6693. CodeCompleter->includeGlobals(),
  6694. CodeCompleter->loadExternal());
  6695. if (CodeCompleter->includeMacros())
  6696. AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
  6697. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  6698. Results.data(), Results.size());
  6699. }
  6700. /// When we have an expression with type "id", we may assume
  6701. /// that it has some more-specific class type based on knowledge of
  6702. /// common uses of Objective-C. This routine returns that class type,
  6703. /// or NULL if no better result could be determined.
  6704. static ObjCInterfaceDecl *GetAssumedMessageSendExprType(Expr *E) {
  6705. auto *Msg = dyn_cast_or_null<ObjCMessageExpr>(E);
  6706. if (!Msg)
  6707. return nullptr;
  6708. Selector Sel = Msg->getSelector();
  6709. if (Sel.isNull())
  6710. return nullptr;
  6711. IdentifierInfo *Id = Sel.getIdentifierInfoForSlot(0);
  6712. if (!Id)
  6713. return nullptr;
  6714. ObjCMethodDecl *Method = Msg->getMethodDecl();
  6715. if (!Method)
  6716. return nullptr;
  6717. // Determine the class that we're sending the message to.
  6718. ObjCInterfaceDecl *IFace = nullptr;
  6719. switch (Msg->getReceiverKind()) {
  6720. case ObjCMessageExpr::Class:
  6721. if (const ObjCObjectType *ObjType =
  6722. Msg->getClassReceiver()->getAs<ObjCObjectType>())
  6723. IFace = ObjType->getInterface();
  6724. break;
  6725. case ObjCMessageExpr::Instance: {
  6726. QualType T = Msg->getInstanceReceiver()->getType();
  6727. if (const ObjCObjectPointerType *Ptr = T->getAs<ObjCObjectPointerType>())
  6728. IFace = Ptr->getInterfaceDecl();
  6729. break;
  6730. }
  6731. case ObjCMessageExpr::SuperInstance:
  6732. case ObjCMessageExpr::SuperClass:
  6733. break;
  6734. }
  6735. if (!IFace)
  6736. return nullptr;
  6737. ObjCInterfaceDecl *Super = IFace->getSuperClass();
  6738. if (Method->isInstanceMethod())
  6739. return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
  6740. .Case("retain", IFace)
  6741. .Case("strong", IFace)
  6742. .Case("autorelease", IFace)
  6743. .Case("copy", IFace)
  6744. .Case("copyWithZone", IFace)
  6745. .Case("mutableCopy", IFace)
  6746. .Case("mutableCopyWithZone", IFace)
  6747. .Case("awakeFromCoder", IFace)
  6748. .Case("replacementObjectFromCoder", IFace)
  6749. .Case("class", IFace)
  6750. .Case("classForCoder", IFace)
  6751. .Case("superclass", Super)
  6752. .Default(nullptr);
  6753. return llvm::StringSwitch<ObjCInterfaceDecl *>(Id->getName())
  6754. .Case("new", IFace)
  6755. .Case("alloc", IFace)
  6756. .Case("allocWithZone", IFace)
  6757. .Case("class", IFace)
  6758. .Case("superclass", Super)
  6759. .Default(nullptr);
  6760. }
  6761. // Add a special completion for a message send to "super", which fills in the
  6762. // most likely case of forwarding all of our arguments to the superclass
  6763. // function.
  6764. ///
  6765. /// \param S The semantic analysis object.
  6766. ///
  6767. /// \param NeedSuperKeyword Whether we need to prefix this completion with
  6768. /// the "super" keyword. Otherwise, we just need to provide the arguments.
  6769. ///
  6770. /// \param SelIdents The identifiers in the selector that have already been
  6771. /// provided as arguments for a send to "super".
  6772. ///
  6773. /// \param Results The set of results to augment.
  6774. ///
  6775. /// \returns the Objective-C method declaration that would be invoked by
  6776. /// this "super" completion. If NULL, no completion was added.
  6777. static ObjCMethodDecl *
  6778. AddSuperSendCompletion(Sema &S, bool NeedSuperKeyword,
  6779. ArrayRef<IdentifierInfo *> SelIdents,
  6780. ResultBuilder &Results) {
  6781. ObjCMethodDecl *CurMethod = S.getCurMethodDecl();
  6782. if (!CurMethod)
  6783. return nullptr;
  6784. ObjCInterfaceDecl *Class = CurMethod->getClassInterface();
  6785. if (!Class)
  6786. return nullptr;
  6787. // Try to find a superclass method with the same selector.
  6788. ObjCMethodDecl *SuperMethod = nullptr;
  6789. while ((Class = Class->getSuperClass()) && !SuperMethod) {
  6790. // Check in the class
  6791. SuperMethod = Class->getMethod(CurMethod->getSelector(),
  6792. CurMethod->isInstanceMethod());
  6793. // Check in categories or class extensions.
  6794. if (!SuperMethod) {
  6795. for (const auto *Cat : Class->known_categories()) {
  6796. if ((SuperMethod = Cat->getMethod(CurMethod->getSelector(),
  6797. CurMethod->isInstanceMethod())))
  6798. break;
  6799. }
  6800. }
  6801. }
  6802. if (!SuperMethod)
  6803. return nullptr;
  6804. // Check whether the superclass method has the same signature.
  6805. if (CurMethod->param_size() != SuperMethod->param_size() ||
  6806. CurMethod->isVariadic() != SuperMethod->isVariadic())
  6807. return nullptr;
  6808. for (ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin(),
  6809. CurPEnd = CurMethod->param_end(),
  6810. SuperP = SuperMethod->param_begin();
  6811. CurP != CurPEnd; ++CurP, ++SuperP) {
  6812. // Make sure the parameter types are compatible.
  6813. if (!S.Context.hasSameUnqualifiedType((*CurP)->getType(),
  6814. (*SuperP)->getType()))
  6815. return nullptr;
  6816. // Make sure we have a parameter name to forward!
  6817. if (!(*CurP)->getIdentifier())
  6818. return nullptr;
  6819. }
  6820. // We have a superclass method. Now, form the send-to-super completion.
  6821. CodeCompletionBuilder Builder(Results.getAllocator(),
  6822. Results.getCodeCompletionTUInfo());
  6823. // Give this completion a return type.
  6824. AddResultTypeChunk(S.Context, getCompletionPrintingPolicy(S), SuperMethod,
  6825. Results.getCompletionContext().getBaseType(), Builder);
  6826. // If we need the "super" keyword, add it (plus some spacing).
  6827. if (NeedSuperKeyword) {
  6828. Builder.AddTypedTextChunk("super");
  6829. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6830. }
  6831. Selector Sel = CurMethod->getSelector();
  6832. if (Sel.isUnarySelector()) {
  6833. if (NeedSuperKeyword)
  6834. Builder.AddTextChunk(
  6835. Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
  6836. else
  6837. Builder.AddTypedTextChunk(
  6838. Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
  6839. } else {
  6840. ObjCMethodDecl::param_iterator CurP = CurMethod->param_begin();
  6841. for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I, ++CurP) {
  6842. if (I > SelIdents.size())
  6843. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  6844. if (I < SelIdents.size())
  6845. Builder.AddInformativeChunk(
  6846. Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
  6847. else if (NeedSuperKeyword || I > SelIdents.size()) {
  6848. Builder.AddTextChunk(
  6849. Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
  6850. Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
  6851. (*CurP)->getIdentifier()->getName()));
  6852. } else {
  6853. Builder.AddTypedTextChunk(
  6854. Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
  6855. Builder.AddPlaceholderChunk(Builder.getAllocator().CopyString(
  6856. (*CurP)->getIdentifier()->getName()));
  6857. }
  6858. }
  6859. }
  6860. Results.AddResult(CodeCompletionResult(Builder.TakeString(), SuperMethod,
  6861. CCP_SuperCompletion));
  6862. return SuperMethod;
  6863. }
  6864. void Sema::CodeCompleteObjCMessageReceiver(Scope *S) {
  6865. typedef CodeCompletionResult Result;
  6866. ResultBuilder Results(
  6867. *this, CodeCompleter->getAllocator(),
  6868. CodeCompleter->getCodeCompletionTUInfo(),
  6869. CodeCompletionContext::CCC_ObjCMessageReceiver,
  6870. getLangOpts().CPlusPlus11
  6871. ? &ResultBuilder::IsObjCMessageReceiverOrLambdaCapture
  6872. : &ResultBuilder::IsObjCMessageReceiver);
  6873. CodeCompletionDeclConsumer Consumer(Results, CurContext);
  6874. Results.EnterNewScope();
  6875. LookupVisibleDecls(S, LookupOrdinaryName, Consumer,
  6876. CodeCompleter->includeGlobals(),
  6877. CodeCompleter->loadExternal());
  6878. // If we are in an Objective-C method inside a class that has a superclass,
  6879. // add "super" as an option.
  6880. if (ObjCMethodDecl *Method = getCurMethodDecl())
  6881. if (ObjCInterfaceDecl *Iface = Method->getClassInterface())
  6882. if (Iface->getSuperClass()) {
  6883. Results.AddResult(Result("super"));
  6884. AddSuperSendCompletion(*this, /*NeedSuperKeyword=*/true, None, Results);
  6885. }
  6886. if (getLangOpts().CPlusPlus11)
  6887. addThisCompletion(*this, Results);
  6888. Results.ExitScope();
  6889. if (CodeCompleter->includeMacros())
  6890. AddMacroResults(PP, Results, CodeCompleter->loadExternal(), false);
  6891. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  6892. Results.data(), Results.size());
  6893. }
  6894. void Sema::CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
  6895. ArrayRef<IdentifierInfo *> SelIdents,
  6896. bool AtArgumentExpression) {
  6897. ObjCInterfaceDecl *CDecl = nullptr;
  6898. if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
  6899. // Figure out which interface we're in.
  6900. CDecl = CurMethod->getClassInterface();
  6901. if (!CDecl)
  6902. return;
  6903. // Find the superclass of this class.
  6904. CDecl = CDecl->getSuperClass();
  6905. if (!CDecl)
  6906. return;
  6907. if (CurMethod->isInstanceMethod()) {
  6908. // We are inside an instance method, which means that the message
  6909. // send [super ...] is actually calling an instance method on the
  6910. // current object.
  6911. return CodeCompleteObjCInstanceMessage(S, nullptr, SelIdents,
  6912. AtArgumentExpression, CDecl);
  6913. }
  6914. // Fall through to send to the superclass in CDecl.
  6915. } else {
  6916. // "super" may be the name of a type or variable. Figure out which
  6917. // it is.
  6918. IdentifierInfo *Super = getSuperIdentifier();
  6919. NamedDecl *ND = LookupSingleName(S, Super, SuperLoc, LookupOrdinaryName);
  6920. if ((CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(ND))) {
  6921. // "super" names an interface. Use it.
  6922. } else if (TypeDecl *TD = dyn_cast_or_null<TypeDecl>(ND)) {
  6923. if (const ObjCObjectType *Iface =
  6924. Context.getTypeDeclType(TD)->getAs<ObjCObjectType>())
  6925. CDecl = Iface->getInterface();
  6926. } else if (ND && isa<UnresolvedUsingTypenameDecl>(ND)) {
  6927. // "super" names an unresolved type; we can't be more specific.
  6928. } else {
  6929. // Assume that "super" names some kind of value and parse that way.
  6930. CXXScopeSpec SS;
  6931. SourceLocation TemplateKWLoc;
  6932. UnqualifiedId id;
  6933. id.setIdentifier(Super, SuperLoc);
  6934. ExprResult SuperExpr = ActOnIdExpression(S, SS, TemplateKWLoc, id,
  6935. /*HasTrailingLParen=*/false,
  6936. /*IsAddressOfOperand=*/false);
  6937. return CodeCompleteObjCInstanceMessage(S, (Expr *)SuperExpr.get(),
  6938. SelIdents, AtArgumentExpression);
  6939. }
  6940. // Fall through
  6941. }
  6942. ParsedType Receiver;
  6943. if (CDecl)
  6944. Receiver = ParsedType::make(Context.getObjCInterfaceType(CDecl));
  6945. return CodeCompleteObjCClassMessage(S, Receiver, SelIdents,
  6946. AtArgumentExpression,
  6947. /*IsSuper=*/true);
  6948. }
  6949. /// Given a set of code-completion results for the argument of a message
  6950. /// send, determine the preferred type (if any) for that argument expression.
  6951. static QualType getPreferredArgumentTypeForMessageSend(ResultBuilder &Results,
  6952. unsigned NumSelIdents) {
  6953. typedef CodeCompletionResult Result;
  6954. ASTContext &Context = Results.getSema().Context;
  6955. QualType PreferredType;
  6956. unsigned BestPriority = CCP_Unlikely * 2;
  6957. Result *ResultsData = Results.data();
  6958. for (unsigned I = 0, N = Results.size(); I != N; ++I) {
  6959. Result &R = ResultsData[I];
  6960. if (R.Kind == Result::RK_Declaration &&
  6961. isa<ObjCMethodDecl>(R.Declaration)) {
  6962. if (R.Priority <= BestPriority) {
  6963. const ObjCMethodDecl *Method = cast<ObjCMethodDecl>(R.Declaration);
  6964. if (NumSelIdents <= Method->param_size()) {
  6965. QualType MyPreferredType =
  6966. Method->parameters()[NumSelIdents - 1]->getType();
  6967. if (R.Priority < BestPriority || PreferredType.isNull()) {
  6968. BestPriority = R.Priority;
  6969. PreferredType = MyPreferredType;
  6970. } else if (!Context.hasSameUnqualifiedType(PreferredType,
  6971. MyPreferredType)) {
  6972. PreferredType = QualType();
  6973. }
  6974. }
  6975. }
  6976. }
  6977. }
  6978. return PreferredType;
  6979. }
  6980. static void AddClassMessageCompletions(Sema &SemaRef, Scope *S,
  6981. ParsedType Receiver,
  6982. ArrayRef<IdentifierInfo *> SelIdents,
  6983. bool AtArgumentExpression, bool IsSuper,
  6984. ResultBuilder &Results) {
  6985. typedef CodeCompletionResult Result;
  6986. ObjCInterfaceDecl *CDecl = nullptr;
  6987. // If the given name refers to an interface type, retrieve the
  6988. // corresponding declaration.
  6989. if (Receiver) {
  6990. QualType T = SemaRef.GetTypeFromParser(Receiver, nullptr);
  6991. if (!T.isNull())
  6992. if (const ObjCObjectType *Interface = T->getAs<ObjCObjectType>())
  6993. CDecl = Interface->getInterface();
  6994. }
  6995. // Add all of the factory methods in this Objective-C class, its protocols,
  6996. // superclasses, categories, implementation, etc.
  6997. Results.EnterNewScope();
  6998. // If this is a send-to-super, try to add the special "super" send
  6999. // completion.
  7000. if (IsSuper) {
  7001. if (ObjCMethodDecl *SuperMethod =
  7002. AddSuperSendCompletion(SemaRef, false, SelIdents, Results))
  7003. Results.Ignore(SuperMethod);
  7004. }
  7005. // If we're inside an Objective-C method definition, prefer its selector to
  7006. // others.
  7007. if (ObjCMethodDecl *CurMethod = SemaRef.getCurMethodDecl())
  7008. Results.setPreferredSelector(CurMethod->getSelector());
  7009. VisitedSelectorSet Selectors;
  7010. if (CDecl)
  7011. AddObjCMethods(CDecl, false, MK_Any, SelIdents, SemaRef.CurContext,
  7012. Selectors, AtArgumentExpression, Results);
  7013. else {
  7014. // We're messaging "id" as a type; provide all class/factory methods.
  7015. // If we have an external source, load the entire class method
  7016. // pool from the AST file.
  7017. if (SemaRef.getExternalSource()) {
  7018. for (uint32_t I = 0,
  7019. N = SemaRef.getExternalSource()->GetNumExternalSelectors();
  7020. I != N; ++I) {
  7021. Selector Sel = SemaRef.getExternalSource()->GetExternalSelector(I);
  7022. if (Sel.isNull() || SemaRef.MethodPool.count(Sel))
  7023. continue;
  7024. SemaRef.ReadMethodPool(Sel);
  7025. }
  7026. }
  7027. for (Sema::GlobalMethodPool::iterator M = SemaRef.MethodPool.begin(),
  7028. MEnd = SemaRef.MethodPool.end();
  7029. M != MEnd; ++M) {
  7030. for (ObjCMethodList *MethList = &M->second.second;
  7031. MethList && MethList->getMethod(); MethList = MethList->getNext()) {
  7032. if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
  7033. continue;
  7034. Result R(MethList->getMethod(),
  7035. Results.getBasePriority(MethList->getMethod()), nullptr);
  7036. R.StartParameter = SelIdents.size();
  7037. R.AllParametersAreInformative = false;
  7038. Results.MaybeAddResult(R, SemaRef.CurContext);
  7039. }
  7040. }
  7041. }
  7042. Results.ExitScope();
  7043. }
  7044. void Sema::CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
  7045. ArrayRef<IdentifierInfo *> SelIdents,
  7046. bool AtArgumentExpression,
  7047. bool IsSuper) {
  7048. QualType T = this->GetTypeFromParser(Receiver);
  7049. ResultBuilder Results(
  7050. *this, CodeCompleter->getAllocator(),
  7051. CodeCompleter->getCodeCompletionTUInfo(),
  7052. CodeCompletionContext(CodeCompletionContext::CCC_ObjCClassMessage, T,
  7053. SelIdents));
  7054. AddClassMessageCompletions(*this, S, Receiver, SelIdents,
  7055. AtArgumentExpression, IsSuper, Results);
  7056. // If we're actually at the argument expression (rather than prior to the
  7057. // selector), we're actually performing code completion for an expression.
  7058. // Determine whether we have a single, best method. If so, we can
  7059. // code-complete the expression using the corresponding parameter type as
  7060. // our preferred type, improving completion results.
  7061. if (AtArgumentExpression) {
  7062. QualType PreferredType =
  7063. getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
  7064. if (PreferredType.isNull())
  7065. CodeCompleteOrdinaryName(S, PCC_Expression);
  7066. else
  7067. CodeCompleteExpression(S, PreferredType);
  7068. return;
  7069. }
  7070. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  7071. Results.data(), Results.size());
  7072. }
  7073. void Sema::CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
  7074. ArrayRef<IdentifierInfo *> SelIdents,
  7075. bool AtArgumentExpression,
  7076. ObjCInterfaceDecl *Super) {
  7077. typedef CodeCompletionResult Result;
  7078. Expr *RecExpr = static_cast<Expr *>(Receiver);
  7079. // If necessary, apply function/array conversion to the receiver.
  7080. // C99 6.7.5.3p[7,8].
  7081. if (RecExpr) {
  7082. ExprResult Conv = DefaultFunctionArrayLvalueConversion(RecExpr);
  7083. if (Conv.isInvalid()) // conversion failed. bail.
  7084. return;
  7085. RecExpr = Conv.get();
  7086. }
  7087. QualType ReceiverType = RecExpr
  7088. ? RecExpr->getType()
  7089. : Super ? Context.getObjCObjectPointerType(
  7090. Context.getObjCInterfaceType(Super))
  7091. : Context.getObjCIdType();
  7092. // If we're messaging an expression with type "id" or "Class", check
  7093. // whether we know something special about the receiver that allows
  7094. // us to assume a more-specific receiver type.
  7095. if (ReceiverType->isObjCIdType() || ReceiverType->isObjCClassType()) {
  7096. if (ObjCInterfaceDecl *IFace = GetAssumedMessageSendExprType(RecExpr)) {
  7097. if (ReceiverType->isObjCClassType())
  7098. return CodeCompleteObjCClassMessage(
  7099. S, ParsedType::make(Context.getObjCInterfaceType(IFace)), SelIdents,
  7100. AtArgumentExpression, Super);
  7101. ReceiverType =
  7102. Context.getObjCObjectPointerType(Context.getObjCInterfaceType(IFace));
  7103. }
  7104. } else if (RecExpr && getLangOpts().CPlusPlus) {
  7105. ExprResult Conv = PerformContextuallyConvertToObjCPointer(RecExpr);
  7106. if (Conv.isUsable()) {
  7107. RecExpr = Conv.get();
  7108. ReceiverType = RecExpr->getType();
  7109. }
  7110. }
  7111. // Build the set of methods we can see.
  7112. ResultBuilder Results(
  7113. *this, CodeCompleter->getAllocator(),
  7114. CodeCompleter->getCodeCompletionTUInfo(),
  7115. CodeCompletionContext(CodeCompletionContext::CCC_ObjCInstanceMessage,
  7116. ReceiverType, SelIdents));
  7117. Results.EnterNewScope();
  7118. // If this is a send-to-super, try to add the special "super" send
  7119. // completion.
  7120. if (Super) {
  7121. if (ObjCMethodDecl *SuperMethod =
  7122. AddSuperSendCompletion(*this, false, SelIdents, Results))
  7123. Results.Ignore(SuperMethod);
  7124. }
  7125. // If we're inside an Objective-C method definition, prefer its selector to
  7126. // others.
  7127. if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
  7128. Results.setPreferredSelector(CurMethod->getSelector());
  7129. // Keep track of the selectors we've already added.
  7130. VisitedSelectorSet Selectors;
  7131. // Handle messages to Class. This really isn't a message to an instance
  7132. // method, so we treat it the same way we would treat a message send to a
  7133. // class method.
  7134. if (ReceiverType->isObjCClassType() ||
  7135. ReceiverType->isObjCQualifiedClassType()) {
  7136. if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) {
  7137. if (ObjCInterfaceDecl *ClassDecl = CurMethod->getClassInterface())
  7138. AddObjCMethods(ClassDecl, false, MK_Any, SelIdents, CurContext,
  7139. Selectors, AtArgumentExpression, Results);
  7140. }
  7141. }
  7142. // Handle messages to a qualified ID ("id<foo>").
  7143. else if (const ObjCObjectPointerType *QualID =
  7144. ReceiverType->getAsObjCQualifiedIdType()) {
  7145. // Search protocols for instance methods.
  7146. for (auto *I : QualID->quals())
  7147. AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
  7148. AtArgumentExpression, Results);
  7149. }
  7150. // Handle messages to a pointer to interface type.
  7151. else if (const ObjCObjectPointerType *IFacePtr =
  7152. ReceiverType->getAsObjCInterfacePointerType()) {
  7153. // Search the class, its superclasses, etc., for instance methods.
  7154. AddObjCMethods(IFacePtr->getInterfaceDecl(), true, MK_Any, SelIdents,
  7155. CurContext, Selectors, AtArgumentExpression, Results);
  7156. // Search protocols for instance methods.
  7157. for (auto *I : IFacePtr->quals())
  7158. AddObjCMethods(I, true, MK_Any, SelIdents, CurContext, Selectors,
  7159. AtArgumentExpression, Results);
  7160. }
  7161. // Handle messages to "id".
  7162. else if (ReceiverType->isObjCIdType()) {
  7163. // We're messaging "id", so provide all instance methods we know
  7164. // about as code-completion results.
  7165. // If we have an external source, load the entire class method
  7166. // pool from the AST file.
  7167. if (ExternalSource) {
  7168. for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors();
  7169. I != N; ++I) {
  7170. Selector Sel = ExternalSource->GetExternalSelector(I);
  7171. if (Sel.isNull() || MethodPool.count(Sel))
  7172. continue;
  7173. ReadMethodPool(Sel);
  7174. }
  7175. }
  7176. for (GlobalMethodPool::iterator M = MethodPool.begin(),
  7177. MEnd = MethodPool.end();
  7178. M != MEnd; ++M) {
  7179. for (ObjCMethodList *MethList = &M->second.first;
  7180. MethList && MethList->getMethod(); MethList = MethList->getNext()) {
  7181. if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
  7182. continue;
  7183. if (!Selectors.insert(MethList->getMethod()->getSelector()).second)
  7184. continue;
  7185. Result R(MethList->getMethod(),
  7186. Results.getBasePriority(MethList->getMethod()), nullptr);
  7187. R.StartParameter = SelIdents.size();
  7188. R.AllParametersAreInformative = false;
  7189. Results.MaybeAddResult(R, CurContext);
  7190. }
  7191. }
  7192. }
  7193. Results.ExitScope();
  7194. // If we're actually at the argument expression (rather than prior to the
  7195. // selector), we're actually performing code completion for an expression.
  7196. // Determine whether we have a single, best method. If so, we can
  7197. // code-complete the expression using the corresponding parameter type as
  7198. // our preferred type, improving completion results.
  7199. if (AtArgumentExpression) {
  7200. QualType PreferredType =
  7201. getPreferredArgumentTypeForMessageSend(Results, SelIdents.size());
  7202. if (PreferredType.isNull())
  7203. CodeCompleteOrdinaryName(S, PCC_Expression);
  7204. else
  7205. CodeCompleteExpression(S, PreferredType);
  7206. return;
  7207. }
  7208. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  7209. Results.data(), Results.size());
  7210. }
  7211. void Sema::CodeCompleteObjCForCollection(Scope *S,
  7212. DeclGroupPtrTy IterationVar) {
  7213. CodeCompleteExpressionData Data;
  7214. Data.ObjCCollection = true;
  7215. if (IterationVar.getAsOpaquePtr()) {
  7216. DeclGroupRef DG = IterationVar.get();
  7217. for (DeclGroupRef::iterator I = DG.begin(), End = DG.end(); I != End; ++I) {
  7218. if (*I)
  7219. Data.IgnoreDecls.push_back(*I);
  7220. }
  7221. }
  7222. CodeCompleteExpression(S, Data);
  7223. }
  7224. void Sema::CodeCompleteObjCSelector(Scope *S,
  7225. ArrayRef<IdentifierInfo *> SelIdents) {
  7226. // If we have an external source, load the entire class method
  7227. // pool from the AST file.
  7228. if (ExternalSource) {
  7229. for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
  7230. ++I) {
  7231. Selector Sel = ExternalSource->GetExternalSelector(I);
  7232. if (Sel.isNull() || MethodPool.count(Sel))
  7233. continue;
  7234. ReadMethodPool(Sel);
  7235. }
  7236. }
  7237. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  7238. CodeCompleter->getCodeCompletionTUInfo(),
  7239. CodeCompletionContext::CCC_SelectorName);
  7240. Results.EnterNewScope();
  7241. for (GlobalMethodPool::iterator M = MethodPool.begin(),
  7242. MEnd = MethodPool.end();
  7243. M != MEnd; ++M) {
  7244. Selector Sel = M->first;
  7245. if (!isAcceptableObjCSelector(Sel, MK_Any, SelIdents))
  7246. continue;
  7247. CodeCompletionBuilder Builder(Results.getAllocator(),
  7248. Results.getCodeCompletionTUInfo());
  7249. if (Sel.isUnarySelector()) {
  7250. Builder.AddTypedTextChunk(
  7251. Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
  7252. Results.AddResult(Builder.TakeString());
  7253. continue;
  7254. }
  7255. std::string Accumulator;
  7256. for (unsigned I = 0, N = Sel.getNumArgs(); I != N; ++I) {
  7257. if (I == SelIdents.size()) {
  7258. if (!Accumulator.empty()) {
  7259. Builder.AddInformativeChunk(
  7260. Builder.getAllocator().CopyString(Accumulator));
  7261. Accumulator.clear();
  7262. }
  7263. }
  7264. Accumulator += Sel.getNameForSlot(I);
  7265. Accumulator += ':';
  7266. }
  7267. Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(Accumulator));
  7268. Results.AddResult(Builder.TakeString());
  7269. }
  7270. Results.ExitScope();
  7271. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  7272. Results.data(), Results.size());
  7273. }
  7274. /// Add all of the protocol declarations that we find in the given
  7275. /// (translation unit) context.
  7276. static void AddProtocolResults(DeclContext *Ctx, DeclContext *CurContext,
  7277. bool OnlyForwardDeclarations,
  7278. ResultBuilder &Results) {
  7279. typedef CodeCompletionResult Result;
  7280. for (const auto *D : Ctx->decls()) {
  7281. // Record any protocols we find.
  7282. if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(D))
  7283. if (!OnlyForwardDeclarations || !Proto->hasDefinition())
  7284. Results.AddResult(
  7285. Result(Proto, Results.getBasePriority(Proto), nullptr), CurContext,
  7286. nullptr, false);
  7287. }
  7288. }
  7289. void Sema::CodeCompleteObjCProtocolReferences(
  7290. ArrayRef<IdentifierLocPair> Protocols) {
  7291. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  7292. CodeCompleter->getCodeCompletionTUInfo(),
  7293. CodeCompletionContext::CCC_ObjCProtocolName);
  7294. if (CodeCompleter->includeGlobals()) {
  7295. Results.EnterNewScope();
  7296. // Tell the result set to ignore all of the protocols we have
  7297. // already seen.
  7298. // FIXME: This doesn't work when caching code-completion results.
  7299. for (const IdentifierLocPair &Pair : Protocols)
  7300. if (ObjCProtocolDecl *Protocol = LookupProtocol(Pair.first, Pair.second))
  7301. Results.Ignore(Protocol);
  7302. // Add all protocols.
  7303. AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, false,
  7304. Results);
  7305. Results.ExitScope();
  7306. }
  7307. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  7308. Results.data(), Results.size());
  7309. }
  7310. void Sema::CodeCompleteObjCProtocolDecl(Scope *) {
  7311. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  7312. CodeCompleter->getCodeCompletionTUInfo(),
  7313. CodeCompletionContext::CCC_ObjCProtocolName);
  7314. if (CodeCompleter->includeGlobals()) {
  7315. Results.EnterNewScope();
  7316. // Add all protocols.
  7317. AddProtocolResults(Context.getTranslationUnitDecl(), CurContext, true,
  7318. Results);
  7319. Results.ExitScope();
  7320. }
  7321. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  7322. Results.data(), Results.size());
  7323. }
  7324. /// Add all of the Objective-C interface declarations that we find in
  7325. /// the given (translation unit) context.
  7326. static void AddInterfaceResults(DeclContext *Ctx, DeclContext *CurContext,
  7327. bool OnlyForwardDeclarations,
  7328. bool OnlyUnimplemented,
  7329. ResultBuilder &Results) {
  7330. typedef CodeCompletionResult Result;
  7331. for (const auto *D : Ctx->decls()) {
  7332. // Record any interfaces we find.
  7333. if (const auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
  7334. if ((!OnlyForwardDeclarations || !Class->hasDefinition()) &&
  7335. (!OnlyUnimplemented || !Class->getImplementation()))
  7336. Results.AddResult(
  7337. Result(Class, Results.getBasePriority(Class), nullptr), CurContext,
  7338. nullptr, false);
  7339. }
  7340. }
  7341. void Sema::CodeCompleteObjCInterfaceDecl(Scope *S) {
  7342. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  7343. CodeCompleter->getCodeCompletionTUInfo(),
  7344. CodeCompletionContext::CCC_ObjCInterfaceName);
  7345. Results.EnterNewScope();
  7346. if (CodeCompleter->includeGlobals()) {
  7347. // Add all classes.
  7348. AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
  7349. false, Results);
  7350. }
  7351. Results.ExitScope();
  7352. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  7353. Results.data(), Results.size());
  7354. }
  7355. void Sema::CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName,
  7356. SourceLocation ClassNameLoc) {
  7357. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  7358. CodeCompleter->getCodeCompletionTUInfo(),
  7359. CodeCompletionContext::CCC_ObjCInterfaceName);
  7360. Results.EnterNewScope();
  7361. // Make sure that we ignore the class we're currently defining.
  7362. NamedDecl *CurClass =
  7363. LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
  7364. if (CurClass && isa<ObjCInterfaceDecl>(CurClass))
  7365. Results.Ignore(CurClass);
  7366. if (CodeCompleter->includeGlobals()) {
  7367. // Add all classes.
  7368. AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
  7369. false, Results);
  7370. }
  7371. Results.ExitScope();
  7372. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  7373. Results.data(), Results.size());
  7374. }
  7375. void Sema::CodeCompleteObjCImplementationDecl(Scope *S) {
  7376. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  7377. CodeCompleter->getCodeCompletionTUInfo(),
  7378. CodeCompletionContext::CCC_ObjCImplementation);
  7379. Results.EnterNewScope();
  7380. if (CodeCompleter->includeGlobals()) {
  7381. // Add all unimplemented classes.
  7382. AddInterfaceResults(Context.getTranslationUnitDecl(), CurContext, false,
  7383. true, Results);
  7384. }
  7385. Results.ExitScope();
  7386. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  7387. Results.data(), Results.size());
  7388. }
  7389. void Sema::CodeCompleteObjCInterfaceCategory(Scope *S,
  7390. IdentifierInfo *ClassName,
  7391. SourceLocation ClassNameLoc) {
  7392. typedef CodeCompletionResult Result;
  7393. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  7394. CodeCompleter->getCodeCompletionTUInfo(),
  7395. CodeCompletionContext::CCC_ObjCCategoryName);
  7396. // Ignore any categories we find that have already been implemented by this
  7397. // interface.
  7398. llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
  7399. NamedDecl *CurClass =
  7400. LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
  7401. if (ObjCInterfaceDecl *Class =
  7402. dyn_cast_or_null<ObjCInterfaceDecl>(CurClass)) {
  7403. for (const auto *Cat : Class->visible_categories())
  7404. CategoryNames.insert(Cat->getIdentifier());
  7405. }
  7406. // Add all of the categories we know about.
  7407. Results.EnterNewScope();
  7408. TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
  7409. for (const auto *D : TU->decls())
  7410. if (const auto *Category = dyn_cast<ObjCCategoryDecl>(D))
  7411. if (CategoryNames.insert(Category->getIdentifier()).second)
  7412. Results.AddResult(
  7413. Result(Category, Results.getBasePriority(Category), nullptr),
  7414. CurContext, nullptr, false);
  7415. Results.ExitScope();
  7416. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  7417. Results.data(), Results.size());
  7418. }
  7419. void Sema::CodeCompleteObjCImplementationCategory(Scope *S,
  7420. IdentifierInfo *ClassName,
  7421. SourceLocation ClassNameLoc) {
  7422. typedef CodeCompletionResult Result;
  7423. // Find the corresponding interface. If we couldn't find the interface, the
  7424. // program itself is ill-formed. However, we'll try to be helpful still by
  7425. // providing the list of all of the categories we know about.
  7426. NamedDecl *CurClass =
  7427. LookupSingleName(TUScope, ClassName, ClassNameLoc, LookupOrdinaryName);
  7428. ObjCInterfaceDecl *Class = dyn_cast_or_null<ObjCInterfaceDecl>(CurClass);
  7429. if (!Class)
  7430. return CodeCompleteObjCInterfaceCategory(S, ClassName, ClassNameLoc);
  7431. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  7432. CodeCompleter->getCodeCompletionTUInfo(),
  7433. CodeCompletionContext::CCC_ObjCCategoryName);
  7434. // Add all of the categories that have have corresponding interface
  7435. // declarations in this class and any of its superclasses, except for
  7436. // already-implemented categories in the class itself.
  7437. llvm::SmallPtrSet<IdentifierInfo *, 16> CategoryNames;
  7438. Results.EnterNewScope();
  7439. bool IgnoreImplemented = true;
  7440. while (Class) {
  7441. for (const auto *Cat : Class->visible_categories()) {
  7442. if ((!IgnoreImplemented || !Cat->getImplementation()) &&
  7443. CategoryNames.insert(Cat->getIdentifier()).second)
  7444. Results.AddResult(Result(Cat, Results.getBasePriority(Cat), nullptr),
  7445. CurContext, nullptr, false);
  7446. }
  7447. Class = Class->getSuperClass();
  7448. IgnoreImplemented = false;
  7449. }
  7450. Results.ExitScope();
  7451. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  7452. Results.data(), Results.size());
  7453. }
  7454. void Sema::CodeCompleteObjCPropertyDefinition(Scope *S) {
  7455. CodeCompletionContext CCContext(CodeCompletionContext::CCC_Other);
  7456. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  7457. CodeCompleter->getCodeCompletionTUInfo(), CCContext);
  7458. // Figure out where this @synthesize lives.
  7459. ObjCContainerDecl *Container =
  7460. dyn_cast_or_null<ObjCContainerDecl>(CurContext);
  7461. if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
  7462. !isa<ObjCCategoryImplDecl>(Container)))
  7463. return;
  7464. // Ignore any properties that have already been implemented.
  7465. Container = getContainerDef(Container);
  7466. for (const auto *D : Container->decls())
  7467. if (const auto *PropertyImpl = dyn_cast<ObjCPropertyImplDecl>(D))
  7468. Results.Ignore(PropertyImpl->getPropertyDecl());
  7469. // Add any properties that we find.
  7470. AddedPropertiesSet AddedProperties;
  7471. Results.EnterNewScope();
  7472. if (ObjCImplementationDecl *ClassImpl =
  7473. dyn_cast<ObjCImplementationDecl>(Container))
  7474. AddObjCProperties(CCContext, ClassImpl->getClassInterface(), false,
  7475. /*AllowNullaryMethods=*/false, CurContext,
  7476. AddedProperties, Results);
  7477. else
  7478. AddObjCProperties(CCContext,
  7479. cast<ObjCCategoryImplDecl>(Container)->getCategoryDecl(),
  7480. false, /*AllowNullaryMethods=*/false, CurContext,
  7481. AddedProperties, Results);
  7482. Results.ExitScope();
  7483. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  7484. Results.data(), Results.size());
  7485. }
  7486. void Sema::CodeCompleteObjCPropertySynthesizeIvar(
  7487. Scope *S, IdentifierInfo *PropertyName) {
  7488. typedef CodeCompletionResult Result;
  7489. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  7490. CodeCompleter->getCodeCompletionTUInfo(),
  7491. CodeCompletionContext::CCC_Other);
  7492. // Figure out where this @synthesize lives.
  7493. ObjCContainerDecl *Container =
  7494. dyn_cast_or_null<ObjCContainerDecl>(CurContext);
  7495. if (!Container || (!isa<ObjCImplementationDecl>(Container) &&
  7496. !isa<ObjCCategoryImplDecl>(Container)))
  7497. return;
  7498. // Figure out which interface we're looking into.
  7499. ObjCInterfaceDecl *Class = nullptr;
  7500. if (ObjCImplementationDecl *ClassImpl =
  7501. dyn_cast<ObjCImplementationDecl>(Container))
  7502. Class = ClassImpl->getClassInterface();
  7503. else
  7504. Class = cast<ObjCCategoryImplDecl>(Container)
  7505. ->getCategoryDecl()
  7506. ->getClassInterface();
  7507. // Determine the type of the property we're synthesizing.
  7508. QualType PropertyType = Context.getObjCIdType();
  7509. if (Class) {
  7510. if (ObjCPropertyDecl *Property = Class->FindPropertyDeclaration(
  7511. PropertyName, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
  7512. PropertyType =
  7513. Property->getType().getNonReferenceType().getUnqualifiedType();
  7514. // Give preference to ivars
  7515. Results.setPreferredType(PropertyType);
  7516. }
  7517. }
  7518. // Add all of the instance variables in this class and its superclasses.
  7519. Results.EnterNewScope();
  7520. bool SawSimilarlyNamedIvar = false;
  7521. std::string NameWithPrefix;
  7522. NameWithPrefix += '_';
  7523. NameWithPrefix += PropertyName->getName();
  7524. std::string NameWithSuffix = PropertyName->getName().str();
  7525. NameWithSuffix += '_';
  7526. for (; Class; Class = Class->getSuperClass()) {
  7527. for (ObjCIvarDecl *Ivar = Class->all_declared_ivar_begin(); Ivar;
  7528. Ivar = Ivar->getNextIvar()) {
  7529. Results.AddResult(Result(Ivar, Results.getBasePriority(Ivar), nullptr),
  7530. CurContext, nullptr, false);
  7531. // Determine whether we've seen an ivar with a name similar to the
  7532. // property.
  7533. if ((PropertyName == Ivar->getIdentifier() ||
  7534. NameWithPrefix == Ivar->getName() ||
  7535. NameWithSuffix == Ivar->getName())) {
  7536. SawSimilarlyNamedIvar = true;
  7537. // Reduce the priority of this result by one, to give it a slight
  7538. // advantage over other results whose names don't match so closely.
  7539. if (Results.size() &&
  7540. Results.data()[Results.size() - 1].Kind ==
  7541. CodeCompletionResult::RK_Declaration &&
  7542. Results.data()[Results.size() - 1].Declaration == Ivar)
  7543. Results.data()[Results.size() - 1].Priority--;
  7544. }
  7545. }
  7546. }
  7547. if (!SawSimilarlyNamedIvar) {
  7548. // Create ivar result _propName, that the user can use to synthesize
  7549. // an ivar of the appropriate type.
  7550. unsigned Priority = CCP_MemberDeclaration + 1;
  7551. typedef CodeCompletionResult Result;
  7552. CodeCompletionAllocator &Allocator = Results.getAllocator();
  7553. CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo(),
  7554. Priority, CXAvailability_Available);
  7555. PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
  7556. Builder.AddResultTypeChunk(
  7557. GetCompletionTypeString(PropertyType, Context, Policy, Allocator));
  7558. Builder.AddTypedTextChunk(Allocator.CopyString(NameWithPrefix));
  7559. Results.AddResult(
  7560. Result(Builder.TakeString(), Priority, CXCursor_ObjCIvarDecl));
  7561. }
  7562. Results.ExitScope();
  7563. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  7564. Results.data(), Results.size());
  7565. }
  7566. // Mapping from selectors to the methods that implement that selector, along
  7567. // with the "in original class" flag.
  7568. typedef llvm::DenseMap<Selector,
  7569. llvm::PointerIntPair<ObjCMethodDecl *, 1, bool>>
  7570. KnownMethodsMap;
  7571. /// Find all of the methods that reside in the given container
  7572. /// (and its superclasses, protocols, etc.) that meet the given
  7573. /// criteria. Insert those methods into the map of known methods,
  7574. /// indexed by selector so they can be easily found.
  7575. static void FindImplementableMethods(ASTContext &Context,
  7576. ObjCContainerDecl *Container,
  7577. Optional<bool> WantInstanceMethods,
  7578. QualType ReturnType,
  7579. KnownMethodsMap &KnownMethods,
  7580. bool InOriginalClass = true) {
  7581. if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Container)) {
  7582. // Make sure we have a definition; that's what we'll walk.
  7583. if (!IFace->hasDefinition())
  7584. return;
  7585. IFace = IFace->getDefinition();
  7586. Container = IFace;
  7587. const ObjCList<ObjCProtocolDecl> &Protocols =
  7588. IFace->getReferencedProtocols();
  7589. for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
  7590. E = Protocols.end();
  7591. I != E; ++I)
  7592. FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
  7593. KnownMethods, InOriginalClass);
  7594. // Add methods from any class extensions and categories.
  7595. for (auto *Cat : IFace->visible_categories()) {
  7596. FindImplementableMethods(Context, Cat, WantInstanceMethods, ReturnType,
  7597. KnownMethods, false);
  7598. }
  7599. // Visit the superclass.
  7600. if (IFace->getSuperClass())
  7601. FindImplementableMethods(Context, IFace->getSuperClass(),
  7602. WantInstanceMethods, ReturnType, KnownMethods,
  7603. false);
  7604. }
  7605. if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
  7606. // Recurse into protocols.
  7607. const ObjCList<ObjCProtocolDecl> &Protocols =
  7608. Category->getReferencedProtocols();
  7609. for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
  7610. E = Protocols.end();
  7611. I != E; ++I)
  7612. FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
  7613. KnownMethods, InOriginalClass);
  7614. // If this category is the original class, jump to the interface.
  7615. if (InOriginalClass && Category->getClassInterface())
  7616. FindImplementableMethods(Context, Category->getClassInterface(),
  7617. WantInstanceMethods, ReturnType, KnownMethods,
  7618. false);
  7619. }
  7620. if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
  7621. // Make sure we have a definition; that's what we'll walk.
  7622. if (!Protocol->hasDefinition())
  7623. return;
  7624. Protocol = Protocol->getDefinition();
  7625. Container = Protocol;
  7626. // Recurse into protocols.
  7627. const ObjCList<ObjCProtocolDecl> &Protocols =
  7628. Protocol->getReferencedProtocols();
  7629. for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
  7630. E = Protocols.end();
  7631. I != E; ++I)
  7632. FindImplementableMethods(Context, *I, WantInstanceMethods, ReturnType,
  7633. KnownMethods, false);
  7634. }
  7635. // Add methods in this container. This operation occurs last because
  7636. // we want the methods from this container to override any methods
  7637. // we've previously seen with the same selector.
  7638. for (auto *M : Container->methods()) {
  7639. if (!WantInstanceMethods || M->isInstanceMethod() == *WantInstanceMethods) {
  7640. if (!ReturnType.isNull() &&
  7641. !Context.hasSameUnqualifiedType(ReturnType, M->getReturnType()))
  7642. continue;
  7643. KnownMethods[M->getSelector()] =
  7644. KnownMethodsMap::mapped_type(M, InOriginalClass);
  7645. }
  7646. }
  7647. }
  7648. /// Add the parenthesized return or parameter type chunk to a code
  7649. /// completion string.
  7650. static void AddObjCPassingTypeChunk(QualType Type, unsigned ObjCDeclQuals,
  7651. ASTContext &Context,
  7652. const PrintingPolicy &Policy,
  7653. CodeCompletionBuilder &Builder) {
  7654. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7655. std::string Quals = formatObjCParamQualifiers(ObjCDeclQuals, Type);
  7656. if (!Quals.empty())
  7657. Builder.AddTextChunk(Builder.getAllocator().CopyString(Quals));
  7658. Builder.AddTextChunk(
  7659. GetCompletionTypeString(Type, Context, Policy, Builder.getAllocator()));
  7660. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7661. }
  7662. /// Determine whether the given class is or inherits from a class by
  7663. /// the given name.
  7664. static bool InheritsFromClassNamed(ObjCInterfaceDecl *Class, StringRef Name) {
  7665. if (!Class)
  7666. return false;
  7667. if (Class->getIdentifier() && Class->getIdentifier()->getName() == Name)
  7668. return true;
  7669. return InheritsFromClassNamed(Class->getSuperClass(), Name);
  7670. }
  7671. /// Add code completions for Objective-C Key-Value Coding (KVC) and
  7672. /// Key-Value Observing (KVO).
  7673. static void AddObjCKeyValueCompletions(ObjCPropertyDecl *Property,
  7674. bool IsInstanceMethod,
  7675. QualType ReturnType, ASTContext &Context,
  7676. VisitedSelectorSet &KnownSelectors,
  7677. ResultBuilder &Results) {
  7678. IdentifierInfo *PropName = Property->getIdentifier();
  7679. if (!PropName || PropName->getLength() == 0)
  7680. return;
  7681. PrintingPolicy Policy = getCompletionPrintingPolicy(Results.getSema());
  7682. // Builder that will create each code completion.
  7683. typedef CodeCompletionResult Result;
  7684. CodeCompletionAllocator &Allocator = Results.getAllocator();
  7685. CodeCompletionBuilder Builder(Allocator, Results.getCodeCompletionTUInfo());
  7686. // The selector table.
  7687. SelectorTable &Selectors = Context.Selectors;
  7688. // The property name, copied into the code completion allocation region
  7689. // on demand.
  7690. struct KeyHolder {
  7691. CodeCompletionAllocator &Allocator;
  7692. StringRef Key;
  7693. const char *CopiedKey;
  7694. KeyHolder(CodeCompletionAllocator &Allocator, StringRef Key)
  7695. : Allocator(Allocator), Key(Key), CopiedKey(nullptr) {}
  7696. operator const char *() {
  7697. if (CopiedKey)
  7698. return CopiedKey;
  7699. return CopiedKey = Allocator.CopyString(Key);
  7700. }
  7701. } Key(Allocator, PropName->getName());
  7702. // The uppercased name of the property name.
  7703. std::string UpperKey = std::string(PropName->getName());
  7704. if (!UpperKey.empty())
  7705. UpperKey[0] = toUppercase(UpperKey[0]);
  7706. bool ReturnTypeMatchesProperty =
  7707. ReturnType.isNull() ||
  7708. Context.hasSameUnqualifiedType(ReturnType.getNonReferenceType(),
  7709. Property->getType());
  7710. bool ReturnTypeMatchesVoid = ReturnType.isNull() || ReturnType->isVoidType();
  7711. // Add the normal accessor -(type)key.
  7712. if (IsInstanceMethod &&
  7713. KnownSelectors.insert(Selectors.getNullarySelector(PropName)).second &&
  7714. ReturnTypeMatchesProperty && !Property->getGetterMethodDecl()) {
  7715. if (ReturnType.isNull())
  7716. AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
  7717. Builder);
  7718. Builder.AddTypedTextChunk(Key);
  7719. Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
  7720. CXCursor_ObjCInstanceMethodDecl));
  7721. }
  7722. // If we have an integral or boolean property (or the user has provided
  7723. // an integral or boolean return type), add the accessor -(type)isKey.
  7724. if (IsInstanceMethod &&
  7725. ((!ReturnType.isNull() &&
  7726. (ReturnType->isIntegerType() || ReturnType->isBooleanType())) ||
  7727. (ReturnType.isNull() && (Property->getType()->isIntegerType() ||
  7728. Property->getType()->isBooleanType())))) {
  7729. std::string SelectorName = (Twine("is") + UpperKey).str();
  7730. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  7731. if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
  7732. .second) {
  7733. if (ReturnType.isNull()) {
  7734. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7735. Builder.AddTextChunk("BOOL");
  7736. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7737. }
  7738. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
  7739. Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
  7740. CXCursor_ObjCInstanceMethodDecl));
  7741. }
  7742. }
  7743. // Add the normal mutator.
  7744. if (IsInstanceMethod && ReturnTypeMatchesVoid &&
  7745. !Property->getSetterMethodDecl()) {
  7746. std::string SelectorName = (Twine("set") + UpperKey).str();
  7747. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  7748. if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
  7749. if (ReturnType.isNull()) {
  7750. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7751. Builder.AddTextChunk("void");
  7752. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7753. }
  7754. Builder.AddTypedTextChunk(
  7755. Allocator.CopyString(SelectorId->getName() + ":"));
  7756. AddObjCPassingTypeChunk(Property->getType(), /*Quals=*/0, Context, Policy,
  7757. Builder);
  7758. Builder.AddTextChunk(Key);
  7759. Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
  7760. CXCursor_ObjCInstanceMethodDecl));
  7761. }
  7762. }
  7763. // Indexed and unordered accessors
  7764. unsigned IndexedGetterPriority = CCP_CodePattern;
  7765. unsigned IndexedSetterPriority = CCP_CodePattern;
  7766. unsigned UnorderedGetterPriority = CCP_CodePattern;
  7767. unsigned UnorderedSetterPriority = CCP_CodePattern;
  7768. if (const auto *ObjCPointer =
  7769. Property->getType()->getAs<ObjCObjectPointerType>()) {
  7770. if (ObjCInterfaceDecl *IFace = ObjCPointer->getInterfaceDecl()) {
  7771. // If this interface type is not provably derived from a known
  7772. // collection, penalize the corresponding completions.
  7773. if (!InheritsFromClassNamed(IFace, "NSMutableArray")) {
  7774. IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
  7775. if (!InheritsFromClassNamed(IFace, "NSArray"))
  7776. IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
  7777. }
  7778. if (!InheritsFromClassNamed(IFace, "NSMutableSet")) {
  7779. UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
  7780. if (!InheritsFromClassNamed(IFace, "NSSet"))
  7781. UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
  7782. }
  7783. }
  7784. } else {
  7785. IndexedGetterPriority += CCD_ProbablyNotObjCCollection;
  7786. IndexedSetterPriority += CCD_ProbablyNotObjCCollection;
  7787. UnorderedGetterPriority += CCD_ProbablyNotObjCCollection;
  7788. UnorderedSetterPriority += CCD_ProbablyNotObjCCollection;
  7789. }
  7790. // Add -(NSUInteger)countOf<key>
  7791. if (IsInstanceMethod &&
  7792. (ReturnType.isNull() || ReturnType->isIntegerType())) {
  7793. std::string SelectorName = (Twine("countOf") + UpperKey).str();
  7794. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  7795. if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
  7796. .second) {
  7797. if (ReturnType.isNull()) {
  7798. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7799. Builder.AddTextChunk("NSUInteger");
  7800. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7801. }
  7802. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorId->getName()));
  7803. Results.AddResult(
  7804. Result(Builder.TakeString(),
  7805. std::min(IndexedGetterPriority, UnorderedGetterPriority),
  7806. CXCursor_ObjCInstanceMethodDecl));
  7807. }
  7808. }
  7809. // Indexed getters
  7810. // Add -(id)objectInKeyAtIndex:(NSUInteger)index
  7811. if (IsInstanceMethod &&
  7812. (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
  7813. std::string SelectorName = (Twine("objectIn") + UpperKey + "AtIndex").str();
  7814. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  7815. if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
  7816. if (ReturnType.isNull()) {
  7817. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7818. Builder.AddTextChunk("id");
  7819. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7820. }
  7821. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  7822. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7823. Builder.AddTextChunk("NSUInteger");
  7824. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7825. Builder.AddTextChunk("index");
  7826. Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
  7827. CXCursor_ObjCInstanceMethodDecl));
  7828. }
  7829. }
  7830. // Add -(NSArray *)keyAtIndexes:(NSIndexSet *)indexes
  7831. if (IsInstanceMethod &&
  7832. (ReturnType.isNull() ||
  7833. (ReturnType->isObjCObjectPointerType() &&
  7834. ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
  7835. ReturnType->castAs<ObjCObjectPointerType>()
  7836. ->getInterfaceDecl()
  7837. ->getName() == "NSArray"))) {
  7838. std::string SelectorName = (Twine(Property->getName()) + "AtIndexes").str();
  7839. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  7840. if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
  7841. if (ReturnType.isNull()) {
  7842. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7843. Builder.AddTextChunk("NSArray *");
  7844. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7845. }
  7846. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  7847. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7848. Builder.AddTextChunk("NSIndexSet *");
  7849. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7850. Builder.AddTextChunk("indexes");
  7851. Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
  7852. CXCursor_ObjCInstanceMethodDecl));
  7853. }
  7854. }
  7855. // Add -(void)getKey:(type **)buffer range:(NSRange)inRange
  7856. if (IsInstanceMethod && ReturnTypeMatchesVoid) {
  7857. std::string SelectorName = (Twine("get") + UpperKey).str();
  7858. IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
  7859. &Context.Idents.get("range")};
  7860. if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
  7861. if (ReturnType.isNull()) {
  7862. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7863. Builder.AddTextChunk("void");
  7864. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7865. }
  7866. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  7867. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7868. Builder.AddPlaceholderChunk("object-type");
  7869. Builder.AddTextChunk(" **");
  7870. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7871. Builder.AddTextChunk("buffer");
  7872. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  7873. Builder.AddTypedTextChunk("range:");
  7874. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7875. Builder.AddTextChunk("NSRange");
  7876. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7877. Builder.AddTextChunk("inRange");
  7878. Results.AddResult(Result(Builder.TakeString(), IndexedGetterPriority,
  7879. CXCursor_ObjCInstanceMethodDecl));
  7880. }
  7881. }
  7882. // Mutable indexed accessors
  7883. // - (void)insertObject:(type *)object inKeyAtIndex:(NSUInteger)index
  7884. if (IsInstanceMethod && ReturnTypeMatchesVoid) {
  7885. std::string SelectorName = (Twine("in") + UpperKey + "AtIndex").str();
  7886. IdentifierInfo *SelectorIds[2] = {&Context.Idents.get("insertObject"),
  7887. &Context.Idents.get(SelectorName)};
  7888. if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
  7889. if (ReturnType.isNull()) {
  7890. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7891. Builder.AddTextChunk("void");
  7892. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7893. }
  7894. Builder.AddTypedTextChunk("insertObject:");
  7895. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7896. Builder.AddPlaceholderChunk("object-type");
  7897. Builder.AddTextChunk(" *");
  7898. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7899. Builder.AddTextChunk("object");
  7900. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  7901. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  7902. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7903. Builder.AddPlaceholderChunk("NSUInteger");
  7904. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7905. Builder.AddTextChunk("index");
  7906. Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
  7907. CXCursor_ObjCInstanceMethodDecl));
  7908. }
  7909. }
  7910. // - (void)insertKey:(NSArray *)array atIndexes:(NSIndexSet *)indexes
  7911. if (IsInstanceMethod && ReturnTypeMatchesVoid) {
  7912. std::string SelectorName = (Twine("insert") + UpperKey).str();
  7913. IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
  7914. &Context.Idents.get("atIndexes")};
  7915. if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
  7916. if (ReturnType.isNull()) {
  7917. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7918. Builder.AddTextChunk("void");
  7919. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7920. }
  7921. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  7922. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7923. Builder.AddTextChunk("NSArray *");
  7924. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7925. Builder.AddTextChunk("array");
  7926. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  7927. Builder.AddTypedTextChunk("atIndexes:");
  7928. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7929. Builder.AddPlaceholderChunk("NSIndexSet *");
  7930. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7931. Builder.AddTextChunk("indexes");
  7932. Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
  7933. CXCursor_ObjCInstanceMethodDecl));
  7934. }
  7935. }
  7936. // -(void)removeObjectFromKeyAtIndex:(NSUInteger)index
  7937. if (IsInstanceMethod && ReturnTypeMatchesVoid) {
  7938. std::string SelectorName =
  7939. (Twine("removeObjectFrom") + UpperKey + "AtIndex").str();
  7940. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  7941. if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
  7942. if (ReturnType.isNull()) {
  7943. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7944. Builder.AddTextChunk("void");
  7945. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7946. }
  7947. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  7948. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7949. Builder.AddTextChunk("NSUInteger");
  7950. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7951. Builder.AddTextChunk("index");
  7952. Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
  7953. CXCursor_ObjCInstanceMethodDecl));
  7954. }
  7955. }
  7956. // -(void)removeKeyAtIndexes:(NSIndexSet *)indexes
  7957. if (IsInstanceMethod && ReturnTypeMatchesVoid) {
  7958. std::string SelectorName = (Twine("remove") + UpperKey + "AtIndexes").str();
  7959. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  7960. if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
  7961. if (ReturnType.isNull()) {
  7962. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7963. Builder.AddTextChunk("void");
  7964. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7965. }
  7966. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  7967. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7968. Builder.AddTextChunk("NSIndexSet *");
  7969. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7970. Builder.AddTextChunk("indexes");
  7971. Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
  7972. CXCursor_ObjCInstanceMethodDecl));
  7973. }
  7974. }
  7975. // - (void)replaceObjectInKeyAtIndex:(NSUInteger)index withObject:(id)object
  7976. if (IsInstanceMethod && ReturnTypeMatchesVoid) {
  7977. std::string SelectorName =
  7978. (Twine("replaceObjectIn") + UpperKey + "AtIndex").str();
  7979. IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName),
  7980. &Context.Idents.get("withObject")};
  7981. if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
  7982. if (ReturnType.isNull()) {
  7983. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7984. Builder.AddTextChunk("void");
  7985. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7986. }
  7987. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  7988. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7989. Builder.AddPlaceholderChunk("NSUInteger");
  7990. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7991. Builder.AddTextChunk("index");
  7992. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  7993. Builder.AddTypedTextChunk("withObject:");
  7994. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  7995. Builder.AddTextChunk("id");
  7996. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  7997. Builder.AddTextChunk("object");
  7998. Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
  7999. CXCursor_ObjCInstanceMethodDecl));
  8000. }
  8001. }
  8002. // - (void)replaceKeyAtIndexes:(NSIndexSet *)indexes withKey:(NSArray *)array
  8003. if (IsInstanceMethod && ReturnTypeMatchesVoid) {
  8004. std::string SelectorName1 =
  8005. (Twine("replace") + UpperKey + "AtIndexes").str();
  8006. std::string SelectorName2 = (Twine("with") + UpperKey).str();
  8007. IdentifierInfo *SelectorIds[2] = {&Context.Idents.get(SelectorName1),
  8008. &Context.Idents.get(SelectorName2)};
  8009. if (KnownSelectors.insert(Selectors.getSelector(2, SelectorIds)).second) {
  8010. if (ReturnType.isNull()) {
  8011. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8012. Builder.AddTextChunk("void");
  8013. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8014. }
  8015. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName1 + ":"));
  8016. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8017. Builder.AddPlaceholderChunk("NSIndexSet *");
  8018. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8019. Builder.AddTextChunk("indexes");
  8020. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8021. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName2 + ":"));
  8022. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8023. Builder.AddTextChunk("NSArray *");
  8024. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8025. Builder.AddTextChunk("array");
  8026. Results.AddResult(Result(Builder.TakeString(), IndexedSetterPriority,
  8027. CXCursor_ObjCInstanceMethodDecl));
  8028. }
  8029. }
  8030. // Unordered getters
  8031. // - (NSEnumerator *)enumeratorOfKey
  8032. if (IsInstanceMethod &&
  8033. (ReturnType.isNull() ||
  8034. (ReturnType->isObjCObjectPointerType() &&
  8035. ReturnType->getAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
  8036. ReturnType->getAs<ObjCObjectPointerType>()
  8037. ->getInterfaceDecl()
  8038. ->getName() == "NSEnumerator"))) {
  8039. std::string SelectorName = (Twine("enumeratorOf") + UpperKey).str();
  8040. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  8041. if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
  8042. .second) {
  8043. if (ReturnType.isNull()) {
  8044. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8045. Builder.AddTextChunk("NSEnumerator *");
  8046. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8047. }
  8048. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
  8049. Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
  8050. CXCursor_ObjCInstanceMethodDecl));
  8051. }
  8052. }
  8053. // - (type *)memberOfKey:(type *)object
  8054. if (IsInstanceMethod &&
  8055. (ReturnType.isNull() || ReturnType->isObjCObjectPointerType())) {
  8056. std::string SelectorName = (Twine("memberOf") + UpperKey).str();
  8057. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  8058. if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
  8059. if (ReturnType.isNull()) {
  8060. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8061. Builder.AddPlaceholderChunk("object-type");
  8062. Builder.AddTextChunk(" *");
  8063. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8064. }
  8065. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  8066. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8067. if (ReturnType.isNull()) {
  8068. Builder.AddPlaceholderChunk("object-type");
  8069. Builder.AddTextChunk(" *");
  8070. } else {
  8071. Builder.AddTextChunk(GetCompletionTypeString(
  8072. ReturnType, Context, Policy, Builder.getAllocator()));
  8073. }
  8074. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8075. Builder.AddTextChunk("object");
  8076. Results.AddResult(Result(Builder.TakeString(), UnorderedGetterPriority,
  8077. CXCursor_ObjCInstanceMethodDecl));
  8078. }
  8079. }
  8080. // Mutable unordered accessors
  8081. // - (void)addKeyObject:(type *)object
  8082. if (IsInstanceMethod && ReturnTypeMatchesVoid) {
  8083. std::string SelectorName =
  8084. (Twine("add") + UpperKey + Twine("Object")).str();
  8085. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  8086. if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
  8087. if (ReturnType.isNull()) {
  8088. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8089. Builder.AddTextChunk("void");
  8090. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8091. }
  8092. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  8093. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8094. Builder.AddPlaceholderChunk("object-type");
  8095. Builder.AddTextChunk(" *");
  8096. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8097. Builder.AddTextChunk("object");
  8098. Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
  8099. CXCursor_ObjCInstanceMethodDecl));
  8100. }
  8101. }
  8102. // - (void)addKey:(NSSet *)objects
  8103. if (IsInstanceMethod && ReturnTypeMatchesVoid) {
  8104. std::string SelectorName = (Twine("add") + UpperKey).str();
  8105. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  8106. if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
  8107. if (ReturnType.isNull()) {
  8108. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8109. Builder.AddTextChunk("void");
  8110. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8111. }
  8112. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  8113. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8114. Builder.AddTextChunk("NSSet *");
  8115. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8116. Builder.AddTextChunk("objects");
  8117. Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
  8118. CXCursor_ObjCInstanceMethodDecl));
  8119. }
  8120. }
  8121. // - (void)removeKeyObject:(type *)object
  8122. if (IsInstanceMethod && ReturnTypeMatchesVoid) {
  8123. std::string SelectorName =
  8124. (Twine("remove") + UpperKey + Twine("Object")).str();
  8125. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  8126. if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
  8127. if (ReturnType.isNull()) {
  8128. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8129. Builder.AddTextChunk("void");
  8130. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8131. }
  8132. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  8133. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8134. Builder.AddPlaceholderChunk("object-type");
  8135. Builder.AddTextChunk(" *");
  8136. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8137. Builder.AddTextChunk("object");
  8138. Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
  8139. CXCursor_ObjCInstanceMethodDecl));
  8140. }
  8141. }
  8142. // - (void)removeKey:(NSSet *)objects
  8143. if (IsInstanceMethod && ReturnTypeMatchesVoid) {
  8144. std::string SelectorName = (Twine("remove") + UpperKey).str();
  8145. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  8146. if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
  8147. if (ReturnType.isNull()) {
  8148. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8149. Builder.AddTextChunk("void");
  8150. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8151. }
  8152. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  8153. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8154. Builder.AddTextChunk("NSSet *");
  8155. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8156. Builder.AddTextChunk("objects");
  8157. Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
  8158. CXCursor_ObjCInstanceMethodDecl));
  8159. }
  8160. }
  8161. // - (void)intersectKey:(NSSet *)objects
  8162. if (IsInstanceMethod && ReturnTypeMatchesVoid) {
  8163. std::string SelectorName = (Twine("intersect") + UpperKey).str();
  8164. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  8165. if (KnownSelectors.insert(Selectors.getUnarySelector(SelectorId)).second) {
  8166. if (ReturnType.isNull()) {
  8167. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8168. Builder.AddTextChunk("void");
  8169. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8170. }
  8171. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName + ":"));
  8172. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8173. Builder.AddTextChunk("NSSet *");
  8174. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8175. Builder.AddTextChunk("objects");
  8176. Results.AddResult(Result(Builder.TakeString(), UnorderedSetterPriority,
  8177. CXCursor_ObjCInstanceMethodDecl));
  8178. }
  8179. }
  8180. // Key-Value Observing
  8181. // + (NSSet *)keyPathsForValuesAffectingKey
  8182. if (!IsInstanceMethod &&
  8183. (ReturnType.isNull() ||
  8184. (ReturnType->isObjCObjectPointerType() &&
  8185. ReturnType->castAs<ObjCObjectPointerType>()->getInterfaceDecl() &&
  8186. ReturnType->castAs<ObjCObjectPointerType>()
  8187. ->getInterfaceDecl()
  8188. ->getName() == "NSSet"))) {
  8189. std::string SelectorName =
  8190. (Twine("keyPathsForValuesAffecting") + UpperKey).str();
  8191. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  8192. if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
  8193. .second) {
  8194. if (ReturnType.isNull()) {
  8195. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8196. Builder.AddTextChunk("NSSet<NSString *> *");
  8197. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8198. }
  8199. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
  8200. Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
  8201. CXCursor_ObjCClassMethodDecl));
  8202. }
  8203. }
  8204. // + (BOOL)automaticallyNotifiesObserversForKey
  8205. if (!IsInstanceMethod &&
  8206. (ReturnType.isNull() || ReturnType->isIntegerType() ||
  8207. ReturnType->isBooleanType())) {
  8208. std::string SelectorName =
  8209. (Twine("automaticallyNotifiesObserversOf") + UpperKey).str();
  8210. IdentifierInfo *SelectorId = &Context.Idents.get(SelectorName);
  8211. if (KnownSelectors.insert(Selectors.getNullarySelector(SelectorId))
  8212. .second) {
  8213. if (ReturnType.isNull()) {
  8214. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8215. Builder.AddTextChunk("BOOL");
  8216. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8217. }
  8218. Builder.AddTypedTextChunk(Allocator.CopyString(SelectorName));
  8219. Results.AddResult(Result(Builder.TakeString(), CCP_CodePattern,
  8220. CXCursor_ObjCClassMethodDecl));
  8221. }
  8222. }
  8223. }
  8224. void Sema::CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
  8225. ParsedType ReturnTy) {
  8226. // Determine the return type of the method we're declaring, if
  8227. // provided.
  8228. QualType ReturnType = GetTypeFromParser(ReturnTy);
  8229. Decl *IDecl = nullptr;
  8230. if (CurContext->isObjCContainer()) {
  8231. ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
  8232. IDecl = OCD;
  8233. }
  8234. // Determine where we should start searching for methods.
  8235. ObjCContainerDecl *SearchDecl = nullptr;
  8236. bool IsInImplementation = false;
  8237. if (Decl *D = IDecl) {
  8238. if (ObjCImplementationDecl *Impl = dyn_cast<ObjCImplementationDecl>(D)) {
  8239. SearchDecl = Impl->getClassInterface();
  8240. IsInImplementation = true;
  8241. } else if (ObjCCategoryImplDecl *CatImpl =
  8242. dyn_cast<ObjCCategoryImplDecl>(D)) {
  8243. SearchDecl = CatImpl->getCategoryDecl();
  8244. IsInImplementation = true;
  8245. } else
  8246. SearchDecl = dyn_cast<ObjCContainerDecl>(D);
  8247. }
  8248. if (!SearchDecl && S) {
  8249. if (DeclContext *DC = S->getEntity())
  8250. SearchDecl = dyn_cast<ObjCContainerDecl>(DC);
  8251. }
  8252. if (!SearchDecl) {
  8253. HandleCodeCompleteResults(this, CodeCompleter,
  8254. CodeCompletionContext::CCC_Other, nullptr, 0);
  8255. return;
  8256. }
  8257. // Find all of the methods that we could declare/implement here.
  8258. KnownMethodsMap KnownMethods;
  8259. FindImplementableMethods(Context, SearchDecl, IsInstanceMethod, ReturnType,
  8260. KnownMethods);
  8261. // Add declarations or definitions for each of the known methods.
  8262. typedef CodeCompletionResult Result;
  8263. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  8264. CodeCompleter->getCodeCompletionTUInfo(),
  8265. CodeCompletionContext::CCC_Other);
  8266. Results.EnterNewScope();
  8267. PrintingPolicy Policy = getCompletionPrintingPolicy(*this);
  8268. for (KnownMethodsMap::iterator M = KnownMethods.begin(),
  8269. MEnd = KnownMethods.end();
  8270. M != MEnd; ++M) {
  8271. ObjCMethodDecl *Method = M->second.getPointer();
  8272. CodeCompletionBuilder Builder(Results.getAllocator(),
  8273. Results.getCodeCompletionTUInfo());
  8274. // Add the '-'/'+' prefix if it wasn't provided yet.
  8275. if (!IsInstanceMethod) {
  8276. Builder.AddTextChunk(Method->isInstanceMethod() ? "-" : "+");
  8277. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8278. }
  8279. // If the result type was not already provided, add it to the
  8280. // pattern as (type).
  8281. if (ReturnType.isNull()) {
  8282. QualType ResTy = Method->getSendResultType().stripObjCKindOfType(Context);
  8283. AttributedType::stripOuterNullability(ResTy);
  8284. AddObjCPassingTypeChunk(ResTy, Method->getObjCDeclQualifier(), Context,
  8285. Policy, Builder);
  8286. }
  8287. Selector Sel = Method->getSelector();
  8288. if (Sel.isUnarySelector()) {
  8289. // Unary selectors have no arguments.
  8290. Builder.AddTypedTextChunk(
  8291. Builder.getAllocator().CopyString(Sel.getNameForSlot(0)));
  8292. } else {
  8293. // Add all parameters to the pattern.
  8294. unsigned I = 0;
  8295. for (ObjCMethodDecl::param_iterator P = Method->param_begin(),
  8296. PEnd = Method->param_end();
  8297. P != PEnd; (void)++P, ++I) {
  8298. // Add the part of the selector name.
  8299. if (I == 0)
  8300. Builder.AddTypedTextChunk(
  8301. Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
  8302. else if (I < Sel.getNumArgs()) {
  8303. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8304. Builder.AddTypedTextChunk(
  8305. Builder.getAllocator().CopyString(Sel.getNameForSlot(I) + ":"));
  8306. } else
  8307. break;
  8308. // Add the parameter type.
  8309. QualType ParamType;
  8310. if ((*P)->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
  8311. ParamType = (*P)->getType();
  8312. else
  8313. ParamType = (*P)->getOriginalType();
  8314. ParamType = ParamType.substObjCTypeArgs(
  8315. Context, {}, ObjCSubstitutionContext::Parameter);
  8316. AttributedType::stripOuterNullability(ParamType);
  8317. AddObjCPassingTypeChunk(ParamType, (*P)->getObjCDeclQualifier(),
  8318. Context, Policy, Builder);
  8319. if (IdentifierInfo *Id = (*P)->getIdentifier())
  8320. Builder.AddTextChunk(
  8321. Builder.getAllocator().CopyString(Id->getName()));
  8322. }
  8323. }
  8324. if (Method->isVariadic()) {
  8325. if (Method->param_size() > 0)
  8326. Builder.AddChunk(CodeCompletionString::CK_Comma);
  8327. Builder.AddTextChunk("...");
  8328. }
  8329. if (IsInImplementation && Results.includeCodePatterns()) {
  8330. // We will be defining the method here, so add a compound statement.
  8331. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8332. Builder.AddChunk(CodeCompletionString::CK_LeftBrace);
  8333. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  8334. if (!Method->getReturnType()->isVoidType()) {
  8335. // If the result type is not void, add a return clause.
  8336. Builder.AddTextChunk("return");
  8337. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8338. Builder.AddPlaceholderChunk("expression");
  8339. Builder.AddChunk(CodeCompletionString::CK_SemiColon);
  8340. } else
  8341. Builder.AddPlaceholderChunk("statements");
  8342. Builder.AddChunk(CodeCompletionString::CK_VerticalSpace);
  8343. Builder.AddChunk(CodeCompletionString::CK_RightBrace);
  8344. }
  8345. unsigned Priority = CCP_CodePattern;
  8346. auto R = Result(Builder.TakeString(), Method, Priority);
  8347. if (!M->second.getInt())
  8348. setInBaseClass(R);
  8349. Results.AddResult(std::move(R));
  8350. }
  8351. // Add Key-Value-Coding and Key-Value-Observing accessor methods for all of
  8352. // the properties in this class and its categories.
  8353. if (Context.getLangOpts().ObjC) {
  8354. SmallVector<ObjCContainerDecl *, 4> Containers;
  8355. Containers.push_back(SearchDecl);
  8356. VisitedSelectorSet KnownSelectors;
  8357. for (KnownMethodsMap::iterator M = KnownMethods.begin(),
  8358. MEnd = KnownMethods.end();
  8359. M != MEnd; ++M)
  8360. KnownSelectors.insert(M->first);
  8361. ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(SearchDecl);
  8362. if (!IFace)
  8363. if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(SearchDecl))
  8364. IFace = Category->getClassInterface();
  8365. if (IFace)
  8366. for (auto *Cat : IFace->visible_categories())
  8367. Containers.push_back(Cat);
  8368. if (IsInstanceMethod) {
  8369. for (unsigned I = 0, N = Containers.size(); I != N; ++I)
  8370. for (auto *P : Containers[I]->instance_properties())
  8371. AddObjCKeyValueCompletions(P, *IsInstanceMethod, ReturnType, Context,
  8372. KnownSelectors, Results);
  8373. }
  8374. }
  8375. Results.ExitScope();
  8376. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  8377. Results.data(), Results.size());
  8378. }
  8379. void Sema::CodeCompleteObjCMethodDeclSelector(
  8380. Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnTy,
  8381. ArrayRef<IdentifierInfo *> SelIdents) {
  8382. // If we have an external source, load the entire class method
  8383. // pool from the AST file.
  8384. if (ExternalSource) {
  8385. for (uint32_t I = 0, N = ExternalSource->GetNumExternalSelectors(); I != N;
  8386. ++I) {
  8387. Selector Sel = ExternalSource->GetExternalSelector(I);
  8388. if (Sel.isNull() || MethodPool.count(Sel))
  8389. continue;
  8390. ReadMethodPool(Sel);
  8391. }
  8392. }
  8393. // Build the set of methods we can see.
  8394. typedef CodeCompletionResult Result;
  8395. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  8396. CodeCompleter->getCodeCompletionTUInfo(),
  8397. CodeCompletionContext::CCC_Other);
  8398. if (ReturnTy)
  8399. Results.setPreferredType(GetTypeFromParser(ReturnTy).getNonReferenceType());
  8400. Results.EnterNewScope();
  8401. for (GlobalMethodPool::iterator M = MethodPool.begin(),
  8402. MEnd = MethodPool.end();
  8403. M != MEnd; ++M) {
  8404. for (ObjCMethodList *MethList = IsInstanceMethod ? &M->second.first
  8405. : &M->second.second;
  8406. MethList && MethList->getMethod(); MethList = MethList->getNext()) {
  8407. if (!isAcceptableObjCMethod(MethList->getMethod(), MK_Any, SelIdents))
  8408. continue;
  8409. if (AtParameterName) {
  8410. // Suggest parameter names we've seen before.
  8411. unsigned NumSelIdents = SelIdents.size();
  8412. if (NumSelIdents &&
  8413. NumSelIdents <= MethList->getMethod()->param_size()) {
  8414. ParmVarDecl *Param =
  8415. MethList->getMethod()->parameters()[NumSelIdents - 1];
  8416. if (Param->getIdentifier()) {
  8417. CodeCompletionBuilder Builder(Results.getAllocator(),
  8418. Results.getCodeCompletionTUInfo());
  8419. Builder.AddTypedTextChunk(Builder.getAllocator().CopyString(
  8420. Param->getIdentifier()->getName()));
  8421. Results.AddResult(Builder.TakeString());
  8422. }
  8423. }
  8424. continue;
  8425. }
  8426. Result R(MethList->getMethod(),
  8427. Results.getBasePriority(MethList->getMethod()), nullptr);
  8428. R.StartParameter = SelIdents.size();
  8429. R.AllParametersAreInformative = false;
  8430. R.DeclaringEntity = true;
  8431. Results.MaybeAddResult(R, CurContext);
  8432. }
  8433. }
  8434. Results.ExitScope();
  8435. if (!AtParameterName && !SelIdents.empty() &&
  8436. SelIdents.front()->getName().startswith("init")) {
  8437. for (const auto &M : PP.macros()) {
  8438. if (M.first->getName() != "NS_DESIGNATED_INITIALIZER")
  8439. continue;
  8440. Results.EnterNewScope();
  8441. CodeCompletionBuilder Builder(Results.getAllocator(),
  8442. Results.getCodeCompletionTUInfo());
  8443. Builder.AddTypedTextChunk(
  8444. Builder.getAllocator().CopyString(M.first->getName()));
  8445. Results.AddResult(CodeCompletionResult(Builder.TakeString(), CCP_Macro,
  8446. CXCursor_MacroDefinition));
  8447. Results.ExitScope();
  8448. }
  8449. }
  8450. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  8451. Results.data(), Results.size());
  8452. }
  8453. void Sema::CodeCompletePreprocessorDirective(bool InConditional) {
  8454. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  8455. CodeCompleter->getCodeCompletionTUInfo(),
  8456. CodeCompletionContext::CCC_PreprocessorDirective);
  8457. Results.EnterNewScope();
  8458. // #if <condition>
  8459. CodeCompletionBuilder Builder(Results.getAllocator(),
  8460. Results.getCodeCompletionTUInfo());
  8461. Builder.AddTypedTextChunk("if");
  8462. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8463. Builder.AddPlaceholderChunk("condition");
  8464. Results.AddResult(Builder.TakeString());
  8465. // #ifdef <macro>
  8466. Builder.AddTypedTextChunk("ifdef");
  8467. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8468. Builder.AddPlaceholderChunk("macro");
  8469. Results.AddResult(Builder.TakeString());
  8470. // #ifndef <macro>
  8471. Builder.AddTypedTextChunk("ifndef");
  8472. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8473. Builder.AddPlaceholderChunk("macro");
  8474. Results.AddResult(Builder.TakeString());
  8475. if (InConditional) {
  8476. // #elif <condition>
  8477. Builder.AddTypedTextChunk("elif");
  8478. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8479. Builder.AddPlaceholderChunk("condition");
  8480. Results.AddResult(Builder.TakeString());
  8481. // #elifdef <macro>
  8482. Builder.AddTypedTextChunk("elifdef");
  8483. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8484. Builder.AddPlaceholderChunk("macro");
  8485. Results.AddResult(Builder.TakeString());
  8486. // #elifndef <macro>
  8487. Builder.AddTypedTextChunk("elifndef");
  8488. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8489. Builder.AddPlaceholderChunk("macro");
  8490. Results.AddResult(Builder.TakeString());
  8491. // #else
  8492. Builder.AddTypedTextChunk("else");
  8493. Results.AddResult(Builder.TakeString());
  8494. // #endif
  8495. Builder.AddTypedTextChunk("endif");
  8496. Results.AddResult(Builder.TakeString());
  8497. }
  8498. // #include "header"
  8499. Builder.AddTypedTextChunk("include");
  8500. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8501. Builder.AddTextChunk("\"");
  8502. Builder.AddPlaceholderChunk("header");
  8503. Builder.AddTextChunk("\"");
  8504. Results.AddResult(Builder.TakeString());
  8505. // #include <header>
  8506. Builder.AddTypedTextChunk("include");
  8507. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8508. Builder.AddTextChunk("<");
  8509. Builder.AddPlaceholderChunk("header");
  8510. Builder.AddTextChunk(">");
  8511. Results.AddResult(Builder.TakeString());
  8512. // #define <macro>
  8513. Builder.AddTypedTextChunk("define");
  8514. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8515. Builder.AddPlaceholderChunk("macro");
  8516. Results.AddResult(Builder.TakeString());
  8517. // #define <macro>(<args>)
  8518. Builder.AddTypedTextChunk("define");
  8519. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8520. Builder.AddPlaceholderChunk("macro");
  8521. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8522. Builder.AddPlaceholderChunk("args");
  8523. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8524. Results.AddResult(Builder.TakeString());
  8525. // #undef <macro>
  8526. Builder.AddTypedTextChunk("undef");
  8527. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8528. Builder.AddPlaceholderChunk("macro");
  8529. Results.AddResult(Builder.TakeString());
  8530. // #line <number>
  8531. Builder.AddTypedTextChunk("line");
  8532. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8533. Builder.AddPlaceholderChunk("number");
  8534. Results.AddResult(Builder.TakeString());
  8535. // #line <number> "filename"
  8536. Builder.AddTypedTextChunk("line");
  8537. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8538. Builder.AddPlaceholderChunk("number");
  8539. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8540. Builder.AddTextChunk("\"");
  8541. Builder.AddPlaceholderChunk("filename");
  8542. Builder.AddTextChunk("\"");
  8543. Results.AddResult(Builder.TakeString());
  8544. // #error <message>
  8545. Builder.AddTypedTextChunk("error");
  8546. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8547. Builder.AddPlaceholderChunk("message");
  8548. Results.AddResult(Builder.TakeString());
  8549. // #pragma <arguments>
  8550. Builder.AddTypedTextChunk("pragma");
  8551. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8552. Builder.AddPlaceholderChunk("arguments");
  8553. Results.AddResult(Builder.TakeString());
  8554. if (getLangOpts().ObjC) {
  8555. // #import "header"
  8556. Builder.AddTypedTextChunk("import");
  8557. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8558. Builder.AddTextChunk("\"");
  8559. Builder.AddPlaceholderChunk("header");
  8560. Builder.AddTextChunk("\"");
  8561. Results.AddResult(Builder.TakeString());
  8562. // #import <header>
  8563. Builder.AddTypedTextChunk("import");
  8564. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8565. Builder.AddTextChunk("<");
  8566. Builder.AddPlaceholderChunk("header");
  8567. Builder.AddTextChunk(">");
  8568. Results.AddResult(Builder.TakeString());
  8569. }
  8570. // #include_next "header"
  8571. Builder.AddTypedTextChunk("include_next");
  8572. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8573. Builder.AddTextChunk("\"");
  8574. Builder.AddPlaceholderChunk("header");
  8575. Builder.AddTextChunk("\"");
  8576. Results.AddResult(Builder.TakeString());
  8577. // #include_next <header>
  8578. Builder.AddTypedTextChunk("include_next");
  8579. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8580. Builder.AddTextChunk("<");
  8581. Builder.AddPlaceholderChunk("header");
  8582. Builder.AddTextChunk(">");
  8583. Results.AddResult(Builder.TakeString());
  8584. // #warning <message>
  8585. Builder.AddTypedTextChunk("warning");
  8586. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8587. Builder.AddPlaceholderChunk("message");
  8588. Results.AddResult(Builder.TakeString());
  8589. // Note: #ident and #sccs are such crazy anachronisms that we don't provide
  8590. // completions for them. And __include_macros is a Clang-internal extension
  8591. // that we don't want to encourage anyone to use.
  8592. // FIXME: we don't support #assert or #unassert, so don't suggest them.
  8593. Results.ExitScope();
  8594. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  8595. Results.data(), Results.size());
  8596. }
  8597. void Sema::CodeCompleteInPreprocessorConditionalExclusion(Scope *S) {
  8598. CodeCompleteOrdinaryName(S, S->getFnParent() ? Sema::PCC_RecoveryInFunction
  8599. : Sema::PCC_Namespace);
  8600. }
  8601. void Sema::CodeCompletePreprocessorMacroName(bool IsDefinition) {
  8602. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  8603. CodeCompleter->getCodeCompletionTUInfo(),
  8604. IsDefinition ? CodeCompletionContext::CCC_MacroName
  8605. : CodeCompletionContext::CCC_MacroNameUse);
  8606. if (!IsDefinition && (!CodeCompleter || CodeCompleter->includeMacros())) {
  8607. // Add just the names of macros, not their arguments.
  8608. CodeCompletionBuilder Builder(Results.getAllocator(),
  8609. Results.getCodeCompletionTUInfo());
  8610. Results.EnterNewScope();
  8611. for (Preprocessor::macro_iterator M = PP.macro_begin(),
  8612. MEnd = PP.macro_end();
  8613. M != MEnd; ++M) {
  8614. Builder.AddTypedTextChunk(
  8615. Builder.getAllocator().CopyString(M->first->getName()));
  8616. Results.AddResult(CodeCompletionResult(
  8617. Builder.TakeString(), CCP_CodePattern, CXCursor_MacroDefinition));
  8618. }
  8619. Results.ExitScope();
  8620. } else if (IsDefinition) {
  8621. // FIXME: Can we detect when the user just wrote an include guard above?
  8622. }
  8623. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  8624. Results.data(), Results.size());
  8625. }
  8626. void Sema::CodeCompletePreprocessorExpression() {
  8627. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  8628. CodeCompleter->getCodeCompletionTUInfo(),
  8629. CodeCompletionContext::CCC_PreprocessorExpression);
  8630. if (!CodeCompleter || CodeCompleter->includeMacros())
  8631. AddMacroResults(PP, Results,
  8632. !CodeCompleter || CodeCompleter->loadExternal(), true);
  8633. // defined (<macro>)
  8634. Results.EnterNewScope();
  8635. CodeCompletionBuilder Builder(Results.getAllocator(),
  8636. Results.getCodeCompletionTUInfo());
  8637. Builder.AddTypedTextChunk("defined");
  8638. Builder.AddChunk(CodeCompletionString::CK_HorizontalSpace);
  8639. Builder.AddChunk(CodeCompletionString::CK_LeftParen);
  8640. Builder.AddPlaceholderChunk("macro");
  8641. Builder.AddChunk(CodeCompletionString::CK_RightParen);
  8642. Results.AddResult(Builder.TakeString());
  8643. Results.ExitScope();
  8644. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  8645. Results.data(), Results.size());
  8646. }
  8647. void Sema::CodeCompletePreprocessorMacroArgument(Scope *S,
  8648. IdentifierInfo *Macro,
  8649. MacroInfo *MacroInfo,
  8650. unsigned Argument) {
  8651. // FIXME: In the future, we could provide "overload" results, much like we
  8652. // do for function calls.
  8653. // Now just ignore this. There will be another code-completion callback
  8654. // for the expanded tokens.
  8655. }
  8656. // This handles completion inside an #include filename, e.g. #include <foo/ba
  8657. // We look for the directory "foo" under each directory on the include path,
  8658. // list its files, and reassemble the appropriate #include.
  8659. void Sema::CodeCompleteIncludedFile(llvm::StringRef Dir, bool Angled) {
  8660. // RelDir should use /, but unescaped \ is possible on windows!
  8661. // Our completions will normalize to / for simplicity, this case is rare.
  8662. std::string RelDir = llvm::sys::path::convert_to_slash(Dir);
  8663. // We need the native slashes for the actual file system interactions.
  8664. SmallString<128> NativeRelDir = StringRef(RelDir);
  8665. llvm::sys::path::native(NativeRelDir);
  8666. llvm::vfs::FileSystem &FS =
  8667. getSourceManager().getFileManager().getVirtualFileSystem();
  8668. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  8669. CodeCompleter->getCodeCompletionTUInfo(),
  8670. CodeCompletionContext::CCC_IncludedFile);
  8671. llvm::DenseSet<StringRef> SeenResults; // To deduplicate results.
  8672. // Helper: adds one file or directory completion result.
  8673. auto AddCompletion = [&](StringRef Filename, bool IsDirectory) {
  8674. SmallString<64> TypedChunk = Filename;
  8675. // Directory completion is up to the slash, e.g. <sys/
  8676. TypedChunk.push_back(IsDirectory ? '/' : Angled ? '>' : '"');
  8677. auto R = SeenResults.insert(TypedChunk);
  8678. if (R.second) { // New completion
  8679. const char *InternedTyped = Results.getAllocator().CopyString(TypedChunk);
  8680. *R.first = InternedTyped; // Avoid dangling StringRef.
  8681. CodeCompletionBuilder Builder(CodeCompleter->getAllocator(),
  8682. CodeCompleter->getCodeCompletionTUInfo());
  8683. Builder.AddTypedTextChunk(InternedTyped);
  8684. // The result is a "Pattern", which is pretty opaque.
  8685. // We may want to include the real filename to allow smart ranking.
  8686. Results.AddResult(CodeCompletionResult(Builder.TakeString()));
  8687. }
  8688. };
  8689. // Helper: scans IncludeDir for nice files, and adds results for each.
  8690. auto AddFilesFromIncludeDir = [&](StringRef IncludeDir,
  8691. bool IsSystem,
  8692. DirectoryLookup::LookupType_t LookupType) {
  8693. llvm::SmallString<128> Dir = IncludeDir;
  8694. if (!NativeRelDir.empty()) {
  8695. if (LookupType == DirectoryLookup::LT_Framework) {
  8696. // For a framework dir, #include <Foo/Bar/> actually maps to
  8697. // a path of Foo.framework/Headers/Bar/.
  8698. auto Begin = llvm::sys::path::begin(NativeRelDir);
  8699. auto End = llvm::sys::path::end(NativeRelDir);
  8700. llvm::sys::path::append(Dir, *Begin + ".framework", "Headers");
  8701. llvm::sys::path::append(Dir, ++Begin, End);
  8702. } else {
  8703. llvm::sys::path::append(Dir, NativeRelDir);
  8704. }
  8705. }
  8706. const StringRef &Dirname = llvm::sys::path::filename(Dir);
  8707. const bool isQt = Dirname.startswith("Qt") || Dirname == "ActiveQt";
  8708. const bool ExtensionlessHeaders =
  8709. IsSystem || isQt || Dir.endswith(".framework/Headers");
  8710. std::error_code EC;
  8711. unsigned Count = 0;
  8712. for (auto It = FS.dir_begin(Dir, EC);
  8713. !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) {
  8714. if (++Count == 2500) // If we happen to hit a huge directory,
  8715. break; // bail out early so we're not too slow.
  8716. StringRef Filename = llvm::sys::path::filename(It->path());
  8717. // To know whether a symlink should be treated as file or a directory, we
  8718. // have to stat it. This should be cheap enough as there shouldn't be many
  8719. // symlinks.
  8720. llvm::sys::fs::file_type Type = It->type();
  8721. if (Type == llvm::sys::fs::file_type::symlink_file) {
  8722. if (auto FileStatus = FS.status(It->path()))
  8723. Type = FileStatus->getType();
  8724. }
  8725. switch (Type) {
  8726. case llvm::sys::fs::file_type::directory_file:
  8727. // All entries in a framework directory must have a ".framework" suffix,
  8728. // but the suffix does not appear in the source code's include/import.
  8729. if (LookupType == DirectoryLookup::LT_Framework &&
  8730. NativeRelDir.empty() && !Filename.consume_back(".framework"))
  8731. break;
  8732. AddCompletion(Filename, /*IsDirectory=*/true);
  8733. break;
  8734. case llvm::sys::fs::file_type::regular_file: {
  8735. // Only files that really look like headers. (Except in special dirs).
  8736. // Header extensions from Types.def, which we can't depend on here.
  8737. const bool IsHeader = Filename.endswith_insensitive(".h") ||
  8738. Filename.endswith_insensitive(".hh") ||
  8739. Filename.endswith_insensitive(".hpp") ||
  8740. Filename.endswith_insensitive(".inc") ||
  8741. (ExtensionlessHeaders && !Filename.contains('.'));
  8742. if (!IsHeader)
  8743. break;
  8744. AddCompletion(Filename, /*IsDirectory=*/false);
  8745. break;
  8746. }
  8747. default:
  8748. break;
  8749. }
  8750. }
  8751. };
  8752. // Helper: adds results relative to IncludeDir, if possible.
  8753. auto AddFilesFromDirLookup = [&](const DirectoryLookup &IncludeDir,
  8754. bool IsSystem) {
  8755. switch (IncludeDir.getLookupType()) {
  8756. case DirectoryLookup::LT_HeaderMap:
  8757. // header maps are not (currently) enumerable.
  8758. break;
  8759. case DirectoryLookup::LT_NormalDir:
  8760. AddFilesFromIncludeDir(IncludeDir.getDir()->getName(), IsSystem,
  8761. DirectoryLookup::LT_NormalDir);
  8762. break;
  8763. case DirectoryLookup::LT_Framework:
  8764. AddFilesFromIncludeDir(IncludeDir.getFrameworkDir()->getName(), IsSystem,
  8765. DirectoryLookup::LT_Framework);
  8766. break;
  8767. }
  8768. };
  8769. // Finally with all our helpers, we can scan the include path.
  8770. // Do this in standard order so deduplication keeps the right file.
  8771. // (In case we decide to add more details to the results later).
  8772. const auto &S = PP.getHeaderSearchInfo();
  8773. using llvm::make_range;
  8774. if (!Angled) {
  8775. // The current directory is on the include path for "quoted" includes.
  8776. auto *CurFile = PP.getCurrentFileLexer()->getFileEntry();
  8777. if (CurFile && CurFile->getDir())
  8778. AddFilesFromIncludeDir(CurFile->getDir()->getName(), false,
  8779. DirectoryLookup::LT_NormalDir);
  8780. for (const auto &D : make_range(S.quoted_dir_begin(), S.quoted_dir_end()))
  8781. AddFilesFromDirLookup(D, false);
  8782. }
  8783. for (const auto &D : make_range(S.angled_dir_begin(), S.angled_dir_end()))
  8784. AddFilesFromDirLookup(D, false);
  8785. for (const auto &D : make_range(S.system_dir_begin(), S.system_dir_end()))
  8786. AddFilesFromDirLookup(D, true);
  8787. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  8788. Results.data(), Results.size());
  8789. }
  8790. void Sema::CodeCompleteNaturalLanguage() {
  8791. HandleCodeCompleteResults(this, CodeCompleter,
  8792. CodeCompletionContext::CCC_NaturalLanguage, nullptr,
  8793. 0);
  8794. }
  8795. void Sema::CodeCompleteAvailabilityPlatformName() {
  8796. ResultBuilder Results(*this, CodeCompleter->getAllocator(),
  8797. CodeCompleter->getCodeCompletionTUInfo(),
  8798. CodeCompletionContext::CCC_Other);
  8799. Results.EnterNewScope();
  8800. static const char *Platforms[] = {"macOS", "iOS", "watchOS", "tvOS"};
  8801. for (const char *Platform : llvm::makeArrayRef(Platforms)) {
  8802. Results.AddResult(CodeCompletionResult(Platform));
  8803. Results.AddResult(CodeCompletionResult(Results.getAllocator().CopyString(
  8804. Twine(Platform) + "ApplicationExtension")));
  8805. }
  8806. Results.ExitScope();
  8807. HandleCodeCompleteResults(this, CodeCompleter, Results.getCompletionContext(),
  8808. Results.data(), Results.size());
  8809. }
  8810. void Sema::GatherGlobalCodeCompletions(
  8811. CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo,
  8812. SmallVectorImpl<CodeCompletionResult> &Results) {
  8813. ResultBuilder Builder(*this, Allocator, CCTUInfo,
  8814. CodeCompletionContext::CCC_Recovery);
  8815. if (!CodeCompleter || CodeCompleter->includeGlobals()) {
  8816. CodeCompletionDeclConsumer Consumer(Builder,
  8817. Context.getTranslationUnitDecl());
  8818. LookupVisibleDecls(Context.getTranslationUnitDecl(), LookupAnyName,
  8819. Consumer,
  8820. !CodeCompleter || CodeCompleter->loadExternal());
  8821. }
  8822. if (!CodeCompleter || CodeCompleter->includeMacros())
  8823. AddMacroResults(PP, Builder,
  8824. !CodeCompleter || CodeCompleter->loadExternal(), true);
  8825. Results.clear();
  8826. Results.insert(Results.end(), Builder.data(),
  8827. Builder.data() + Builder.size());
  8828. }