SemaCodeComplete.cpp 317 KB

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