SemaCodeComplete.cpp 307 KB

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