SemaCodeComplete.cpp 330 KB

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