SemaCodeComplete.cpp 278 KB

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