SemaCodeComplete.cpp 335 KB

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