SemaCodeComplete.cpp 283 KB

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