SemaCodeComplete.cpp 308 KB

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