SemaCodeComplete.cpp 322 KB

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