SemaCodeComplete.cpp 322 KB

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