SemaCodeComplete.cpp 327 KB

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