SemaCodeComplete.cpp 303 KB

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