SemaCodeComplete.cpp 314 KB

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