SemaCodeComplete.cpp 266 KB

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