SemaCodeComplete.cpp 317 KB

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