SemaCodeComplete.cpp 289 KB

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