SemaCodeComplete.cpp 321 KB

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