SemaCodeComplete.cpp 329 KB

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