SemaCodeComplete.cpp 323 KB

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