SemaCodeComplete.cpp 308 KB

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