SemaCodeComplete.cpp 283 KB

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