SemaCodeComplete.cpp 278 KB

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