SemaCodeComplete.cpp 314 KB

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