SemaCodeComplete.cpp 386 KB

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