SemaCodeComplete.cpp 278 KB

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