SemaCodeComplete.cpp 335 KB

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