SemaCodeComplete.cpp 282 KB

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