SemaCodeComplete.cpp 306 KB

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