SemaCodeComplete.cpp 329 KB

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