SemaCodeComplete.cpp 278 KB

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