SemaCodeComplete.cpp 282 KB

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