SemaCodeComplete.cpp 267 KB

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