SemaCodeComplete.cpp 317 KB

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