SemaCodeComplete.cpp 275 KB

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