SemaCodeComplete.cpp 282 KB

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