SemaCodeComplete.cpp 320 KB

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