SemaCodeComplete.cpp 310 KB

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