SemaCodeComplete.cpp 308 KB

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