SemaCodeComplete.cpp 262 KB

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