SemaCodeComplete.cpp 314 KB

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