SemaCodeComplete.cpp 318 KB

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