SemaCodeComplete.cpp 263 KB

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