SemaCodeComplete.cpp 327 KB

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