SemaCodeComplete.cpp 268 KB

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