SemaCodeComplete.cpp 306 KB

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