SemaCodeComplete.cpp 278 KB

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