BfModuleTypeUtils.cpp 354 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696
  1. #include "BeefySysLib/util/AllocDebug.h"
  2. #include "BfCompiler.h"
  3. #include "BfSystem.h"
  4. #include "BfParser.h"
  5. #include "BfCodeGen.h"
  6. #include "BfExprEvaluator.h"
  7. #include <fcntl.h>
  8. #include "BfConstResolver.h"
  9. #include "BfMangler.h"
  10. #include "BeefySysLib/util/PerfTimer.h"
  11. #include "BeefySysLib/util/BeefPerf.h"
  12. #include "BfSourceClassifier.h"
  13. #include "BfAutoComplete.h"
  14. #include "BfDemangler.h"
  15. #include "BfResolvePass.h"
  16. #include "BfFixits.h"
  17. #include "BfIRCodeGen.h"
  18. #include "BfDefBuilder.h"
  19. //////////////////////////////////////////////////////////////////////////
  20. int32 GetNumLowZeroBits(int32 n)
  21. {
  22. if (n == 0)
  23. return 32;
  24. int i = 0;
  25. while ((n & 1) == 0)
  26. {
  27. n = (int32)((uint32)n >> 1);
  28. i++;
  29. }
  30. return i;
  31. }
  32. //////////////////////////////////////////////////////////////////////////
  33. USING_NS_BF;
  34. BfGenericExtensionEntry* BfModule::BuildGenericExtensionInfo(BfGenericTypeInstance* genericTypeInst, BfTypeDef* partialTypeDef)
  35. {
  36. if (!partialTypeDef->IsExtension())
  37. return NULL;
  38. if (partialTypeDef->mGenericParamDefs.size() != genericTypeInst->mTypeGenericArguments.size())
  39. {
  40. AssertErrorState();
  41. return NULL;
  42. }
  43. BfGenericExtensionInfo* genericExtensionInfo = genericTypeInst->mGenericExtensionInfo;
  44. if (genericExtensionInfo == NULL)
  45. {
  46. genericExtensionInfo = new BfGenericExtensionInfo();
  47. genericTypeInst->mGenericExtensionInfo = genericExtensionInfo;
  48. }
  49. BfTypeState typeState;
  50. typeState.mCurTypeDef = partialTypeDef;
  51. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  52. //auto genericExEntry = new BfGenericExtensionEntry();
  53. //auto insertPair = genericExtensionInfo->mExtensionMap.insert(std::make_pair(partialTypeDef, BfGenericExtensionEntry()));
  54. //auto genericExEntry = &insertPair.first->second;
  55. BfGenericExtensionEntry* genericExEntry;
  56. genericExtensionInfo->mExtensionMap.TryAdd(partialTypeDef, NULL, &genericExEntry);
  57. int startDefGenericParamIdx = (int)genericExEntry->mGenericParams.size();
  58. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mTypeGenericArguments.size(); paramIdx++)
  59. {
  60. auto genericParamInstance = new BfGenericTypeParamInstance(partialTypeDef, paramIdx);
  61. genericExEntry->mGenericParams.push_back(genericParamInstance);
  62. }
  63. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mTypeGenericArguments.size(); paramIdx++)
  64. {
  65. auto genericParamInstance = genericExEntry->mGenericParams[paramIdx];
  66. auto rootGenericParamInstance = genericTypeInst->mGenericParams[paramIdx];
  67. genericParamInstance->mTypeConstraint = rootGenericParamInstance->mTypeConstraint;
  68. genericParamInstance->mInterfaceConstraints = rootGenericParamInstance->mInterfaceConstraints;
  69. genericParamInstance->mGenericParamFlags |= rootGenericParamInstance->mGenericParamFlags;
  70. ResolveGenericParamConstraints(genericParamInstance, partialTypeDef->mGenericParamDefs, paramIdx);
  71. }
  72. for (auto genericParam : genericExEntry->mGenericParams)
  73. {
  74. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  75. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  76. if (genericParam->mTypeConstraint != NULL)
  77. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  78. }
  79. return genericExEntry;
  80. }
  81. bool BfModule::BuildGenericParams(BfType* resolvedTypeRef)
  82. {
  83. BfTypeState typeState;
  84. typeState.mBuildingGenericParams = true;
  85. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  86. BF_ASSERT(mCurMethodInstance == NULL);
  87. auto genericTypeInst = (BfGenericTypeInstance*)resolvedTypeRef;
  88. if (genericTypeInst->mTypeGenericArguments[0]->IsGenericParam())
  89. {
  90. BF_ASSERT(genericTypeInst->mIsUnspecialized);
  91. }
  92. auto typeDef = genericTypeInst->mTypeDef;
  93. int startDefGenericParamIdx = (int)genericTypeInst->mGenericParams.size();
  94. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mTypeGenericArguments.size(); paramIdx++)
  95. {
  96. auto genericParamInstance = new BfGenericTypeParamInstance(typeDef, paramIdx);
  97. genericTypeInst->mGenericParams.push_back(genericParamInstance);
  98. }
  99. if (!typeDef->mPartials.empty())
  100. {
  101. for (auto partialTypeDef : typeDef->mPartials)
  102. {
  103. if (!partialTypeDef->IsExtension())
  104. {
  105. typeState.mCurTypeDef = partialTypeDef;
  106. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mTypeGenericArguments.size(); paramIdx++)
  107. {
  108. auto genericParamDef = typeDef->mGenericParamDefs[paramIdx];
  109. auto genericParamInstance = genericTypeInst->mGenericParams[paramIdx];
  110. ResolveGenericParamConstraints(genericParamInstance, typeDef->mGenericParamDefs, paramIdx);
  111. for (auto nameNode : genericParamDef->mNameNodes)
  112. {
  113. HandleTypeGenericParamRef(nameNode, typeDef, paramIdx);
  114. }
  115. }
  116. }
  117. else
  118. {
  119. auto genericExEntry = BuildGenericExtensionInfo(genericTypeInst, partialTypeDef);
  120. if (genericExEntry == NULL)
  121. continue;
  122. if (!genericTypeInst->IsUnspecializedType())
  123. {
  124. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  125. for (int paramIdx = 0; paramIdx < genericExEntry->mGenericParams.size(); paramIdx++)
  126. {
  127. auto genericParamInstance = genericExEntry->mGenericParams[paramIdx];
  128. BfGenericParamSource genericParamSource;
  129. genericParamSource.mCheckAccessibility = false;
  130. genericParamSource.mTypeInstance = genericTypeInst;
  131. BfError* error = NULL;
  132. if (!CheckGenericConstraints(genericParamSource, genericTypeInst->mTypeGenericArguments[paramIdx], NULL, genericParamInstance, NULL, &error))
  133. {
  134. genericExEntry->mConstraintsPassed = false;
  135. }
  136. }
  137. }
  138. }
  139. }
  140. }
  141. else
  142. {
  143. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mTypeGenericArguments.size(); paramIdx++)
  144. {
  145. auto genericParamInstance = genericTypeInst->mGenericParams[paramIdx];
  146. ResolveGenericParamConstraints(genericParamInstance, typeDef->mGenericParamDefs, paramIdx);
  147. auto genericParamDef = typeDef->mGenericParamDefs[paramIdx];
  148. for (auto nameNode : genericParamDef->mNameNodes)
  149. {
  150. HandleTypeGenericParamRef(nameNode, typeDef, paramIdx);
  151. }
  152. }
  153. }
  154. for (auto genericParam : genericTypeInst->mGenericParams)
  155. {
  156. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  157. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  158. if (genericParam->mTypeConstraint != NULL)
  159. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  160. }
  161. return true;
  162. }
  163. bool BfModule::ValidateGenericConstraints(BfTypeReference* typeRef, BfGenericTypeInstance* genericTypeInst, bool ignoreErrors)
  164. {
  165. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsTypeAlias()))
  166. {
  167. // Don't validate constraints during the population of a concrete generic type alias instance, we want to
  168. // throw those errors at the usage sites
  169. return true;
  170. }
  171. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, mIgnoreErrors || ignoreErrors);
  172. genericTypeInst->mValidatedGenericConstraints = true;
  173. if (genericTypeInst->IsTypeAlias())
  174. {
  175. auto underlyingType = genericTypeInst->GetUnderlyingType();
  176. if ((underlyingType != NULL) && (underlyingType->IsGenericTypeInstance()))
  177. return ValidateGenericConstraints(typeRef, (BfGenericTypeInstance*)underlyingType, ignoreErrors);
  178. return true;
  179. }
  180. auto typeDef = genericTypeInst->mTypeDef;
  181. for (int paramIdx = 0; paramIdx < (int)genericTypeInst->mTypeGenericArguments.size(); paramIdx++)
  182. {
  183. auto genericParamInstance = genericTypeInst->mGenericParams[paramIdx];
  184. // Why did we remove this line? This breaks determining compatibility of one unspecialized type to another unspecialized type, called from ResolveTypeResult
  185. //if (!genericTypeInst->mIsUnspecialized)
  186. {
  187. BfError* error = NULL;
  188. if (!CheckGenericConstraints(BfGenericParamSource(genericTypeInst), genericTypeInst->mTypeGenericArguments[paramIdx], typeRef, genericParamInstance, NULL, &error))
  189. {
  190. genericTypeInst->mHadValidateErrors = true;
  191. return false;
  192. }
  193. }
  194. }
  195. return true;
  196. }
  197. bool BfModule::AreConstraintsSubset(BfGenericParamInstance* checkInner, BfGenericParamInstance* checkOuter)
  198. {
  199. // Added new flags?
  200. if ((checkInner->mGenericParamFlags | checkOuter->mGenericParamFlags) != checkOuter->mGenericParamFlags)
  201. {
  202. // If the outer had a type flag and the inner has a specific type constraint, then see if those are compatible
  203. auto outerFlags = checkOuter->mGenericParamFlags;
  204. if (checkOuter->mTypeConstraint != NULL)
  205. {
  206. if (checkOuter->mTypeConstraint->IsStruct())
  207. outerFlags |= BfGenericParamFlag_Struct;
  208. else if (checkOuter->mTypeConstraint->IsStructOrStructPtr())
  209. outerFlags |= BfGenericParamFlag_StructPtr;
  210. else if (checkOuter->mTypeConstraint->IsObject())
  211. outerFlags |= BfGenericParamFlag_Class;
  212. }
  213. if ((checkInner->mGenericParamFlags | outerFlags) != outerFlags)
  214. return false;
  215. }
  216. if (checkInner->mTypeConstraint != NULL)
  217. {
  218. if (checkOuter->mTypeConstraint == NULL)
  219. return false;
  220. if (!TypeIsSubTypeOf(checkInner->mTypeConstraint->ToTypeInstance(), checkOuter->mTypeConstraint->ToTypeInstance()))
  221. return false;
  222. }
  223. for (auto& innerIFace : checkInner->mInterfaceConstraints)
  224. {
  225. if (!checkOuter->mInterfaceConstraints.Contains(innerIFace))
  226. return false;
  227. }
  228. return true;
  229. }
  230. bool BfModule::ShouldAllowMultipleDefinitions(BfTypeInstance* typeInst, BfTypeDef* firstDeclaringTypeDef, BfTypeDef* secondDeclaringTypeDef)
  231. {
  232. if (firstDeclaringTypeDef == secondDeclaringTypeDef)
  233. return false;
  234. // Since we will use shared debugging info, we won't be able to differentiate between these two fields.
  235. // If we created per-target debug info then we could "fix" this.
  236. // Can these projects even see each other?
  237. if ((!firstDeclaringTypeDef->mProject->ContainsReference(secondDeclaringTypeDef->mProject)) &&
  238. (!secondDeclaringTypeDef->mProject->ContainsReference(firstDeclaringTypeDef->mProject)))
  239. return true;
  240. if (typeInst->IsUnspecializedType())
  241. {
  242. bool alwaysCoincide = true;
  243. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  244. if (genericTypeInst->mGenericExtensionInfo != NULL)
  245. {
  246. auto firstConstraints = genericTypeInst->GetGenericParamsVector(firstDeclaringTypeDef);
  247. auto secondConstraints = genericTypeInst->GetGenericParamsVector(secondDeclaringTypeDef);
  248. for (int genericIdx = 0; genericIdx < (int)firstConstraints->size(); genericIdx++)
  249. {
  250. auto firstConstraint = (*firstConstraints)[genericIdx];
  251. auto secondConstraint = (*secondConstraints)[genericIdx];
  252. if ((!AreConstraintsSubset(firstConstraint, secondConstraint)) &&
  253. (!AreConstraintsSubset(secondConstraint, firstConstraint)))
  254. alwaysCoincide = false;
  255. }
  256. }
  257. // Only show an error if we are certain both members will always appear at the same time
  258. if (!alwaysCoincide)
  259. return true;
  260. }
  261. return false;
  262. }
  263. bool BfModule::InitType(BfType* resolvedTypeRef, BfPopulateType populateType)
  264. {
  265. BP_ZONE("BfModule::InitType");
  266. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, resolvedTypeRef->ToTypeInstance());
  267. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  268. if (mCompiler->mHotState != NULL)
  269. mCompiler->mHotState->mHasNewTypes = true;
  270. auto typeInst = resolvedTypeRef->ToTypeInstance();
  271. if (typeInst != NULL)
  272. {
  273. if (typeInst->mBaseType != NULL)
  274. BF_ASSERT((typeInst->mBaseType->mRebuildFlags & BfTypeRebuildFlag_Deleted) == 0);
  275. if ((typeInst->mTypeDef != NULL) && (typeInst->mTypeDef->mDefState == BfTypeDef::DefState_New) &&
  276. (typeInst->mTypeDef->mNextRevision == NULL))
  277. {
  278. mContext->HandleChangedTypeDef(typeInst->mTypeDef);
  279. typeInst->mTypeDef->mDefState = BfTypeDef::DefState_Defined;
  280. }
  281. typeInst->mIsReified = mIsReified;
  282. //BF_ASSERT(typeInst->mTypeDef->mTypeCode != BfTypeCode_Extension);
  283. if (resolvedTypeRef->IsTuple())
  284. {
  285. auto tupleType = (BfTupleType*)resolvedTypeRef;
  286. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  287. {
  288. auto fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  289. if (fieldInstance->GetResolvedType()->IsUnspecializedType())
  290. tupleType->mHasUnspecializedMembers = true;
  291. }
  292. }
  293. typeInst->mRevision = mCompiler->mRevision;
  294. if (typeInst->mTypeDef != NULL)
  295. BF_ASSERT(typeInst->mTypeDef->mDefState != BfTypeDef::DefState_Deleted);
  296. }
  297. if (resolvedTypeRef->IsGenericTypeInstance())
  298. {
  299. auto genericTypeInst = (BfGenericTypeInstance*)resolvedTypeRef;
  300. for (auto typeGenericArg : genericTypeInst->mTypeGenericArguments)
  301. BF_ASSERT((typeGenericArg->mRebuildFlags & BfTypeRebuildFlag_Deleted) == 0);
  302. }
  303. if (!mContext->mSavedTypeDataMap.IsEmpty())
  304. {
  305. String typeName = BfSafeMangler::Mangle(resolvedTypeRef, this);
  306. BfSavedTypeData* savedTypeData;
  307. if (mContext->mSavedTypeDataMap.Remove(typeName, &savedTypeData))
  308. {
  309. // if (resolvedTypeRef->mTypeId != -1)
  310. // {
  311. // // If we have an ID and it as the last one assigned the roll back the ID counter
  312. // if (resolvedTypeRef->mTypeId == mCompiler->mCurTypeId - 1)
  313. // mCompiler->mCurTypeId--;
  314. // }
  315. mContext->mSavedTypeData[savedTypeData->mTypeId] = NULL;
  316. resolvedTypeRef->mTypeId = savedTypeData->mTypeId;
  317. BfLogSysM("Using mSavedTypeData for %p %s\n", resolvedTypeRef, typeName.c_str());
  318. if (typeInst != NULL)
  319. {
  320. if (mCompiler->IsHotCompile())
  321. {
  322. BfLogSysM("Using mSavedTypeData HotTypeData %p for %p\n", savedTypeData->mHotTypeData, resolvedTypeRef);
  323. typeInst->mHotTypeData = savedTypeData->mHotTypeData;
  324. savedTypeData->mHotTypeData = NULL;
  325. }
  326. }
  327. delete savedTypeData;
  328. mContext->mTypes[resolvedTypeRef->mTypeId] = resolvedTypeRef;
  329. }
  330. else
  331. {
  332. BfLogSysM("No mSavedTypeData entry for %p %s\n", resolvedTypeRef, typeName.c_str());
  333. }
  334. }
  335. resolvedTypeRef->mContext = mContext;
  336. if (resolvedTypeRef->IsGenericTypeInstance())
  337. {
  338. auto genericTypeInstance = (BfGenericTypeInstance*)resolvedTypeRef;
  339. // Do it here so the location we attempted to specialize this type will throw the failure if there is one
  340. if (!BuildGenericParams(resolvedTypeRef))
  341. return false;
  342. }
  343. BfLogSysM("%p InitType: %s Type: %p TypeDef: %p Revision:%d\n", mContext, TypeToString(resolvedTypeRef).c_str(), resolvedTypeRef, (typeInst != NULL) ? typeInst->mTypeDef : NULL, mCompiler->mRevision);
  344. // When we're autocomplete, we can't do the method processing so we have to add this type to the type work list
  345. if (((populateType < BfPopulateType_Full) || (mCompiler->IsAutocomplete())) /*&& (!resolvedTypeRef->IsUnspecializedTypeVariation())*/ && (resolvedTypeRef->IsTypeInstance()) &&
  346. (!resolvedTypeRef->IsTypeAlias()))
  347. {
  348. BfTypeProcessRequest* typeProcessRequest = mContext->mPopulateTypeWorkList.Alloc();
  349. typeProcessRequest->mType = resolvedTypeRef;
  350. BF_ASSERT(resolvedTypeRef->mContext == mContext);
  351. mCompiler->mStats.mTypesQueued++;
  352. mCompiler->UpdateCompletion();
  353. }
  354. return PopulateType(resolvedTypeRef, populateType);
  355. }
  356. void BfModule::AddFieldDependency(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfType* fieldType)
  357. {
  358. auto fieldTypeInstance = fieldType->ToTypeInstance();
  359. if (fieldTypeInstance == NULL)
  360. {
  361. auto underlyingType = fieldType->GetUnderlyingType();
  362. if (underlyingType != NULL)
  363. AddFieldDependency(typeInstance, fieldInstance, underlyingType);
  364. return;
  365. }
  366. auto depFlag = fieldTypeInstance->IsValueType() ? BfDependencyMap::DependencyFlag_ValueTypeMemberData : BfDependencyMap::DependencyFlag_PtrMemberData;
  367. AddDependency(fieldTypeInstance, typeInstance, depFlag);
  368. if ((fieldTypeInstance->IsStruct()) && (fieldTypeInstance->IsGenericTypeInstance()))
  369. {
  370. // When we're a generic struct, our data layout can depend on our generic parameters as well
  371. auto genericTypeInstance = (BfGenericTypeInstance*)fieldTypeInstance;
  372. for (auto typeGenericArg : genericTypeInstance->mTypeGenericArguments)
  373. AddFieldDependency(typeInstance, fieldInstance, typeGenericArg);
  374. }
  375. }
  376. void BfModule::CheckMemberNames(BfTypeInstance* typeInst)
  377. {
  378. struct MemberRef
  379. {
  380. BfMemberDef* mMemberDef;
  381. String mName;
  382. String mKindName;
  383. BfTypeInstance* mTypeInst;
  384. BfAstNode* mNameNode;
  385. BfProtection mProtection;
  386. BfTypeDef* mDeclaringType;
  387. bool mIsOverride;
  388. };
  389. SizedArray<MemberRef, 64> memberList;
  390. // Check base types first and then current type
  391. auto checkType = typeInst;
  392. while (checkType != NULL)
  393. {
  394. for (auto prop : checkType->mTypeDef->mProperties)
  395. {
  396. BfPropertyDeclaration* propDecl = (BfPropertyDeclaration*)prop->mFieldDeclaration;
  397. if ((propDecl != NULL) && (propDecl->mExplicitInterface != NULL))
  398. continue;
  399. if (!typeInst->IsTypeMemberIncluded(prop->mDeclaringType))
  400. continue;
  401. MemberRef memberRef;
  402. memberRef.mMemberDef = prop;
  403. memberRef.mTypeInst = checkType;
  404. memberRef.mProtection = prop->mProtection;
  405. memberRef.mName = prop->mName;
  406. memberRef.mKindName = "property";
  407. if (prop->mFieldDeclaration != NULL)
  408. memberRef.mNameNode = prop->mFieldDeclaration->mNameNode;
  409. memberRef.mDeclaringType = prop->mDeclaringType;
  410. auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(prop->mFieldDeclaration);
  411. if (propertyDeclaration != NULL)
  412. memberRef.mIsOverride = (propertyDeclaration->mNewSpecifier != NULL) ||
  413. ((propertyDeclaration->mVirtualSpecifier != NULL) && (propertyDeclaration->mVirtualSpecifier->GetToken() == BfToken_Override));
  414. memberList.push_back(memberRef);
  415. }
  416. for (auto field : checkType->mTypeDef->mFields)
  417. {
  418. if (!typeInst->IsTypeMemberIncluded(field->mDeclaringType))
  419. continue;
  420. MemberRef memberRef;
  421. memberRef.mMemberDef = field;
  422. memberRef.mTypeInst = checkType;
  423. memberRef.mProtection = field->mProtection;
  424. memberRef.mName = field->mName;
  425. memberRef.mKindName = "field";
  426. memberRef.mDeclaringType = field->mDeclaringType;
  427. if (field->mFieldDeclaration != NULL)
  428. {
  429. memberRef.mNameNode = field->mFieldDeclaration->mNameNode;
  430. memberRef.mIsOverride = field->mFieldDeclaration->mNewSpecifier != NULL;
  431. }
  432. memberList.push_back(memberRef);
  433. }
  434. checkType = checkType->mBaseType;
  435. }
  436. Dictionary<String, MemberRef> memberMap;
  437. memberMap.Reserve(memberList.size());
  438. for (int i = (int)memberList.size() - 1; i >= 0; i--)
  439. {
  440. MemberRef& memberRef = memberList[i];
  441. if (memberRef.mName.empty())
  442. continue;
  443. if ((memberRef.mTypeInst == typeInst) && (!memberRef.mIsOverride))
  444. {
  445. MemberRef* prevMemberRef = NULL;
  446. if (memberMap.TryGetValue(memberRef.mName, &prevMemberRef))
  447. {
  448. //auto& prevMemberRef = itr->second;
  449. MemberRef* firstMemberRef = &memberRef;
  450. MemberRef* secondMemberRef = prevMemberRef;
  451. bool showPrevious = false;
  452. BfError* error = NULL;
  453. if (prevMemberRef->mTypeInst != typeInst)
  454. {
  455. if ((prevMemberRef->mProtection != BfProtection_Private) && (memberRef.mNameNode != NULL))
  456. {
  457. error = Warn(BfWarning_CS0108_MemberHidesInherited, StrFormat("%s hides inherited member '%s'. Use the 'new' keyword if hiding was intentional.", prevMemberRef->mKindName.c_str(), memberRef.mName.c_str()), memberRef.mNameNode, true);
  458. showPrevious = true;
  459. }
  460. }
  461. else
  462. {
  463. if (ShouldAllowMultipleDefinitions(typeInst, firstMemberRef->mDeclaringType, secondMemberRef->mDeclaringType))
  464. {
  465. if (firstMemberRef->mMemberDef != NULL)
  466. {
  467. firstMemberRef->mMemberDef->mHasMultiDefs = true;
  468. secondMemberRef->mMemberDef->mHasMultiDefs = true;
  469. }
  470. continue;
  471. }
  472. bool wantsSwap = false;
  473. if ((secondMemberRef->mNameNode != NULL) && (firstMemberRef->mNameNode != NULL) &&
  474. (secondMemberRef->mNameNode->GetSourceData() == firstMemberRef->mNameNode->GetSourceData()) &&
  475. (secondMemberRef->mNameNode->GetSrcStart() < firstMemberRef->mNameNode->GetSrcStart()))
  476. {
  477. wantsSwap = true;
  478. }
  479. if (secondMemberRef->mDeclaringType->IsExtension() != firstMemberRef->mDeclaringType->IsExtension())
  480. {
  481. wantsSwap = firstMemberRef->mDeclaringType->IsExtension();
  482. }
  483. if (wantsSwap)
  484. {
  485. std::swap(firstMemberRef, secondMemberRef);
  486. }
  487. if (secondMemberRef->mNameNode != NULL)
  488. error = Fail(StrFormat("A %s named '%s' has already been declared.", secondMemberRef->mKindName.c_str(), memberRef.mName.c_str()), secondMemberRef->mNameNode, true);
  489. showPrevious = true;
  490. }
  491. if ((secondMemberRef->mNameNode != NULL) && (error != NULL))
  492. mCompiler->mPassInstance->MoreInfo("Previous declaration", firstMemberRef->mNameNode);
  493. }
  494. }
  495. memberMap.TryAdd(memberRef.mName, memberRef);
  496. }
  497. }
  498. void BfModule::TypeFailed(BfTypeInstance* typeInstance)
  499. {
  500. BfLogSysM("TypeFailed: %p\n", typeInstance);
  501. typeInstance->mTypeFailed = true;
  502. // Punt on field types - just substitute System.Object where we have NULLs
  503. for (auto& fieldInstance : typeInstance->mFieldInstances)
  504. {
  505. if ((fieldInstance.mResolvedType == NULL) || (fieldInstance.mResolvedType->IsNull()))
  506. {
  507. fieldInstance.mResolvedType = mContext->mBfObjectType;
  508. }
  509. if (fieldInstance.mOwner == NULL)
  510. fieldInstance.mOwner = typeInstance;
  511. }
  512. if (typeInstance->mAlign == -1)
  513. typeInstance->mAlign = 1;
  514. if (typeInstance->mSize == -1)
  515. typeInstance->mSize = 1;
  516. mContext->mFailTypes.Add(typeInstance);
  517. mHadBuildError = true;
  518. }
  519. bool BfModule::CheckCircularDataError()
  520. {
  521. bool hadError = false;
  522. {
  523. int count = 0;
  524. auto checkTypeState = mContext->mCurTypeState;
  525. while (checkTypeState != NULL)
  526. {
  527. checkTypeState = checkTypeState->mPrevState;
  528. count++;
  529. }
  530. if (count > 20)
  531. {
  532. NOP;
  533. }
  534. }
  535. int checkIdx = 0;
  536. auto checkTypeState = mContext->mCurTypeState;
  537. bool isPreBaseCheck = checkTypeState->mPopulateType == BfPopulateType_Declaration;
  538. while (true)
  539. {
  540. if (checkTypeState == NULL)
  541. return hadError;
  542. if (isPreBaseCheck)
  543. {
  544. if (checkTypeState->mPopulateType != BfPopulateType_Declaration)
  545. return hadError;
  546. }
  547. else
  548. {
  549. if (checkTypeState->mPopulateType == BfPopulateType_Declaration)
  550. return hadError;
  551. if ((checkIdx > 0) && (checkTypeState->mCurBaseTypeRef == NULL) && (checkTypeState->mCurAttributeTypeRef == NULL) && (checkTypeState->mCurFieldDef == NULL))
  552. return hadError;
  553. }
  554. if ((checkTypeState->mTypeInstance == mCurTypeInstance) && (checkIdx > 0))
  555. break;
  556. checkTypeState = checkTypeState->mPrevState;
  557. checkIdx++;
  558. }
  559. checkTypeState = mContext->mCurTypeState->mPrevState;
  560. while (true)
  561. {
  562. if (checkTypeState == NULL)
  563. return hadError;
  564. if ((checkTypeState->mCurAttributeTypeRef == NULL) && (checkTypeState->mCurBaseTypeRef == NULL) && (checkTypeState->mCurFieldDef == NULL))
  565. return hadError;
  566. // We only get one chance to fire off these errors, they can't be ignored.
  567. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  568. hadError = true;
  569. if (checkTypeState->mCurAttributeTypeRef != NULL)
  570. {
  571. Fail(StrFormat("Attribute type '%s' causes a data cycle", BfTypeUtils::TypeToString(checkTypeState->mCurAttributeTypeRef).c_str()), checkTypeState->mCurAttributeTypeRef, true);
  572. }
  573. else if (checkTypeState->mCurBaseTypeRef != NULL)
  574. {
  575. Fail(StrFormat("Base type '%s' causes a data cycle", BfTypeUtils::TypeToString(checkTypeState->mCurBaseTypeRef).c_str()), checkTypeState->mCurBaseTypeRef, true);
  576. }
  577. else if (checkTypeState->mCurFieldDef->mFieldDeclaration != NULL)
  578. {
  579. Fail(StrFormat("Field '%s.%s' causes a data cycle", TypeToString(checkTypeState->mTypeInstance).c_str(), checkTypeState->mCurFieldDef->mName.c_str()),
  580. checkTypeState->mCurFieldDef->mFieldDeclaration->mTypeRef, true);
  581. }
  582. else
  583. {
  584. Fail(StrFormat("Field '%s.%s' causes a data cycle", TypeToString(checkTypeState->mTypeInstance).c_str(), checkTypeState->mCurFieldDef->mName.c_str()));
  585. }
  586. auto module = GetModuleFor(checkTypeState->mTypeInstance);
  587. if (module != NULL)
  588. module->TypeFailed(checkTypeState->mTypeInstance);
  589. else
  590. checkTypeState->mTypeInstance->mTypeFailed = true;
  591. checkTypeState = checkTypeState->mPrevState;
  592. }
  593. }
  594. bool BfModule::PopulateType(BfType* resolvedTypeRef, BfPopulateType populateType)
  595. {
  596. if ((populateType == BfPopulateType_Declaration) && (resolvedTypeRef->mDefineState >= BfTypeDefineState_Declared))
  597. return true;
  598. // Are we "demanding" to reify a type that is currently resolve-only?
  599. if (mIsReified)
  600. {
  601. if (resolvedTypeRef->IsTypeInstance())
  602. {
  603. auto typeModule = resolvedTypeRef->GetModule();
  604. if ((typeModule != NULL) && (typeModule->mIsSpecialModule))
  605. {
  606. auto typeInst = resolvedTypeRef->ToTypeInstance();
  607. if (!typeInst->mIsReified)
  608. {
  609. BfLogSysM("Reifying type %p in scratch module in PopulateType\n", resolvedTypeRef);
  610. // It's important for unspecialized types to be in the correct module --
  611. // when we process their methods, new types will be determined as
  612. // resolve-only or reified based on the module the unresolved type is in
  613. BF_ASSERT(typeInst->mModule == mContext->mUnreifiedModule);
  614. typeInst->mIsReified = true;
  615. typeInst->mModule = mContext->mScratchModule;
  616. // Why did we need to do this at all? Why is just marking the type as reified not enough?
  617. // This causes issues where we may delete a method instance that is currently being used as the generic bindings for
  618. // a method of a specialized generic type
  619. // if (typeInst->IsOnDemand())
  620. // {
  621. // RebuildMethods(typeInst);
  622. // }
  623. // else
  624. // mContext->RebuildType(typeInst, false, false);
  625. }
  626. }
  627. else
  628. {
  629. if ((typeModule != NULL) && (!typeModule->mIsReified) && (!typeModule->mReifyQueued))
  630. {
  631. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  632. BfLogSysM("Queued reification of type %p in module %p in PopulateType\n", resolvedTypeRef, typeModule);
  633. BF_ASSERT(!typeModule->mIsSpecialModule);
  634. // This caused issues - we may need to reify a type and then request a method
  635. typeModule->mReifyQueued = true;
  636. mContext->mReifyModuleWorkList.Add(typeModule);
  637. //typeModule->ReifyModule();
  638. }
  639. }
  640. }
  641. }
  642. if (!resolvedTypeRef->IsIncomplete())
  643. return true;
  644. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  645. if ((typeInstance != NULL) && (typeInstance->mTypeDef != NULL))
  646. {
  647. if (typeInstance->mTypeDef->mNextRevision != NULL)
  648. {
  649. // It's possible that our main compiler thread is generating a new typedef while we're autocompleting. This handles that case...
  650. if (typeInstance->mDefineState == BfTypeDefineState_Undefined)
  651. {
  652. if (typeInstance->IsBoxed())
  653. {
  654. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  655. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  656. PopulateType(innerType, BfPopulateType_Data);
  657. }
  658. else
  659. {
  660. mContext->HandleChangedTypeDef(typeInstance->mTypeDef);
  661. mSystem->InjectNewRevision(typeInstance->mTypeDef);
  662. }
  663. }
  664. else
  665. {
  666. BF_ASSERT(mCompiler->IsAutocomplete());
  667. }
  668. }
  669. if ((!typeInstance->IsDeleting()) && (!mCompiler->IsAutocomplete()))
  670. BF_ASSERT(typeInstance->mTypeDef->mDefState == BfTypeDef::DefState_Defined);
  671. }
  672. BF_ASSERT((resolvedTypeRef->mRebuildFlags & (BfTypeRebuildFlag_Deleted | BfTypeRebuildFlag_DeleteQueued)) == 0);
  673. /*BfTypeRebuildFlags allowedFlags = (BfTypeRebuildFlags)(BfTypeRebuildFlag_AddedToWorkList | BfTypeRebuildFlag_AwaitingReference | BfTypeRebuildFlag_UnderlyingTypeDeferred);
  674. if ((resolvedTypeRef->mRebuildFlags & ~allowedFlags) != 0)
  675. {
  676. // BfContext::UpdateAfterDeletingTypes should clear out all flags except for the Deleted flag
  677. // If this type was deleted then we should never be able to reach PopulateType here.
  678. // This may happen if dependent types were not properly rebuilt when a used type
  679. // was deleted.
  680. auto hadFlags = resolvedTypeRef->mRebuildFlags;
  681. BF_ASSERT((resolvedTypeRef->mRebuildFlags & ~allowedFlags) == 0);
  682. resolvedTypeRef->mRebuildFlags = (BfTypeRebuildFlags)(resolvedTypeRef->mRebuildFlags & ~allowedFlags);
  683. }*/
  684. bool isNew = resolvedTypeRef->mDefineState == BfTypeDefineState_Undefined;
  685. if (isNew)
  686. {
  687. BP_ZONE("BfModule::PopulateType");
  688. if (resolvedTypeRef->mTypeId == -1)
  689. {
  690. mCompiler->mTypeInitCount++;
  691. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  692. if (!mCompiler->mTypeIdFreeList.IsEmpty())
  693. {
  694. resolvedTypeRef->mTypeId = mCompiler->mTypeIdFreeList.back();
  695. mCompiler->mTypeIdFreeList.pop_back();
  696. }
  697. else
  698. resolvedTypeRef->mTypeId = mCompiler->mCurTypeId++;
  699. while (resolvedTypeRef->mTypeId >= (int)mContext->mTypes.size())
  700. mContext->mTypes.Add(NULL);
  701. mContext->mTypes[resolvedTypeRef->mTypeId] = resolvedTypeRef;
  702. if (typeInstance != NULL)
  703. {
  704. typeInstance->mSignatureRevision = mCompiler->mRevision;
  705. typeInstance->mLastNonGenericUsedRevision = mCompiler->mRevision;
  706. }
  707. }
  708. BfLogSysM("PopulateType: %p %s populateType:%d ResolveOnly:%d Reified:%d AutoComplete:%d Ctx:%p Mod:%p TypeId:%d\n", resolvedTypeRef, TypeToString(resolvedTypeRef, BfTypeNameFlags_None).c_str(), populateType, mCompiler->mIsResolveOnly, mIsReified, mCompiler->IsAutocomplete(), mContext, this, resolvedTypeRef->mTypeId);
  709. BF_ASSERT(!resolvedTypeRef->IsDeleting());
  710. }
  711. if (resolvedTypeRef->IsRef())
  712. {
  713. BfRefType* refType = (BfRefType*)resolvedTypeRef;
  714. if (refType->mElementType->IsValueType())
  715. {
  716. PopulateType(refType->mElementType, populateType);
  717. resolvedTypeRef->mDefineState = refType->mElementType->mDefineState;
  718. }
  719. else
  720. {
  721. PopulateType(refType->mElementType, BfPopulateType_Identity);
  722. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  723. }
  724. refType->mSize = refType->mAlign = mSystem->mPtrSize;
  725. return true;
  726. }
  727. if (resolvedTypeRef->IsTypeAlias())
  728. {
  729. auto typeAlias = (BfTypeInstance*)resolvedTypeRef;
  730. SetAndRestoreValue<BfTypeInstance*> prevCurType(mCurTypeInstance, typeAlias);
  731. auto typeDef = typeAlias->mTypeDef;
  732. auto typeAliasDecl = (BfTypeAliasDeclaration*)typeDef->mTypeDeclaration;
  733. BfType* aliasToType = NULL;
  734. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  735. typeState.mPopulateType = populateType;
  736. typeState.mCurBaseTypeRef = typeAliasDecl->mAliasToType;
  737. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  738. if (!CheckCircularDataError())
  739. {
  740. if (typeAliasDecl->mAliasToType != NULL)
  741. aliasToType = ResolveTypeRef(typeAliasDecl->mAliasToType, BfPopulateType_IdentityNoRemapAlias);
  742. }
  743. //typeAlias->mModule = mContext->mScratchModule;
  744. typeAlias->mTypeIncomplete = false;
  745. typeAlias->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  746. if (aliasToType != NULL)
  747. {
  748. AddDependency(aliasToType, typeAlias, BfDependencyMap::DependencyFlag_DerivedFrom);
  749. }
  750. else
  751. mContext->mFailTypes.Add(typeAlias);
  752. if (typeAlias->mTypeFailed)
  753. aliasToType = NULL;
  754. if (resolvedTypeRef->IsGenericTypeInstance())
  755. ((BfGenericTypeAliasType*)resolvedTypeRef)->mAliasToType = aliasToType;
  756. else
  757. ((BfTypeAliasType*)resolvedTypeRef)->mAliasToType = aliasToType;
  758. if (aliasToType != NULL)
  759. {
  760. resolvedTypeRef->mSize = aliasToType->mSize;
  761. resolvedTypeRef->mAlign = aliasToType->mAlign;
  762. if (auto aliasToTypeInst = aliasToType->ToTypeInstance())
  763. {
  764. typeAlias->mInstSize = aliasToTypeInst->mInstSize;
  765. typeAlias->mInstAlign = aliasToTypeInst->mInstAlign;
  766. }
  767. else
  768. {
  769. typeAlias->mInstSize = aliasToType->mSize;
  770. typeAlias->mInstAlign = aliasToType->mAlign;
  771. }
  772. }
  773. else
  774. {
  775. resolvedTypeRef->mSize = 0;
  776. resolvedTypeRef->mAlign = 1;
  777. typeAlias->mInstSize = 0;
  778. typeAlias->mInstAlign = 1;
  779. }
  780. resolvedTypeRef->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  781. resolvedTypeRef->mRebuildFlags = BfTypeRebuildFlag_None;
  782. return true;
  783. }
  784. if (resolvedTypeRef->IsSizedArray())
  785. {
  786. resolvedTypeRef->mRevision = mRevision;
  787. BfSizedArrayType* arrayType = (BfSizedArrayType*)resolvedTypeRef;
  788. auto elementType = arrayType->mElementType;
  789. if (elementType->IsValueType())
  790. {
  791. PopulateType(arrayType->mElementType, BfPopulateType_Data);
  792. resolvedTypeRef->mDefineState = arrayType->mElementType->mDefineState;
  793. AddDependency(elementType, resolvedTypeRef, BfDependencyMap::DependencyFlag_ValueTypeMemberData);
  794. }
  795. else
  796. {
  797. PopulateType(arrayType->mElementType, BfPopulateType_Identity);
  798. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  799. AddDependency(elementType, resolvedTypeRef, BfDependencyMap::DependencyFlag_PtrMemberData);
  800. }
  801. if (arrayType->mElementCount > 0)
  802. {
  803. arrayType->mSize = (arrayType->mElementType->GetStride() * ((int)arrayType->mElementCount - 1)) + arrayType->mElementType->mSize;
  804. arrayType->mAlign = std::max((int32)arrayType->mElementType->mAlign, 1);
  805. }
  806. else
  807. {
  808. arrayType->mSize = 0;
  809. arrayType->mAlign = 1;
  810. }
  811. arrayType->mWantsGCMarking = elementType->WantsGCMarking();
  812. resolvedTypeRef->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  813. resolvedTypeRef->mRebuildFlags = BfTypeRebuildFlag_None;
  814. bool isValueless = arrayType->IsValuelessType();
  815. return true;
  816. }
  817. if (isNew)
  818. {
  819. BfTypeDef* typeDef = NULL;
  820. if (typeInstance != NULL)
  821. {
  822. if ((populateType == BfPopulateType_Data) && (typeInstance->mNeedsMethodProcessing))
  823. return true;
  824. typeDef = typeInstance->mTypeDef;
  825. }
  826. if (resolvedTypeRef->IsMethodRef())
  827. return true;
  828. if (resolvedTypeRef->IsPointer())
  829. {
  830. BfPointerType* pointerType = (BfPointerType*)resolvedTypeRef;
  831. if (pointerType->mElementType->IsIncomplete())
  832. PopulateType(pointerType->mElementType, BfPopulateType_Declaration);
  833. pointerType->mSize = pointerType->mAlign = mSystem->mPtrSize;
  834. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  835. return true;
  836. }
  837. if (resolvedTypeRef->IsGenericParam())
  838. {
  839. BfGenericParamType* genericParamType = (BfGenericParamType*)resolvedTypeRef;
  840. PopulateType(mContext->mBfObjectType);
  841. genericParamType->mSize = mContext->mBfObjectType->mSize;
  842. genericParamType->mAlign = mContext->mBfObjectType->mAlign;
  843. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  844. return true;
  845. }
  846. if (resolvedTypeRef->IsRetTypeType())
  847. {
  848. BfRetTypeType* retTypeType = (BfRetTypeType*)resolvedTypeRef;
  849. BF_ASSERT(retTypeType->mElementType->IsGenericParam());
  850. resolvedTypeRef->mSize = mContext->mBfObjectType->mSize;
  851. resolvedTypeRef->mAlign = mContext->mBfObjectType->mAlign;
  852. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  853. return true;
  854. }
  855. if (resolvedTypeRef->IsConcreteInterfaceType())
  856. {
  857. BfConcreteInterfaceType* concreteInterfaceType = (BfConcreteInterfaceType*)resolvedTypeRef;
  858. BF_ASSERT(concreteInterfaceType->mInterface->IsInterface());
  859. resolvedTypeRef->mSize = concreteInterfaceType->mInterface->mSize;
  860. resolvedTypeRef->mAlign = concreteInterfaceType->mInterface->mAlign;
  861. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  862. return true;
  863. }
  864. if (resolvedTypeRef->IsConstExprValue())
  865. {
  866. resolvedTypeRef->mSize = 0;
  867. resolvedTypeRef->mAlign = 0;
  868. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  869. return true;
  870. }
  871. // The autocomplete pass doesn't need to do the method processing, allow type to be (partially) incomplete
  872. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  873. (typeInstance != NULL) && (typeInstance->mNeedsMethodProcessing) && (!typeInstance->IsDelegate()))
  874. return true;
  875. BfPrimitiveType* primitiveType = NULL;
  876. if (typeInstance == NULL)
  877. {
  878. BF_ASSERT(resolvedTypeRef->IsPrimitiveType());
  879. primitiveType = (BfPrimitiveType*)resolvedTypeRef;
  880. typeDef = primitiveType->mTypeDef;
  881. }
  882. #define PRIMITIVE_TYPE(name, llvmType, size, dType) \
  883. primitiveType->mSize = primitiveType->mAlign = size; \
  884. primitiveType->mDefineState = BfTypeDefineState_Defined;
  885. switch (typeDef->mTypeCode)
  886. {
  887. case BfTypeCode_None:
  888. primitiveType->mSize = primitiveType->mAlign = 0;
  889. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  890. return true;
  891. case BfTypeCode_Self:
  892. case BfTypeCode_Dot:
  893. case BfTypeCode_Var:
  894. case BfTypeCode_Let:
  895. {
  896. auto objType = mContext->mBfObjectType;
  897. primitiveType->mSize = objType->mSize;
  898. primitiveType->mAlign = objType->mAlign;
  899. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  900. }
  901. return true;
  902. case BfTypeCode_NullPtr:
  903. primitiveType->mSize = primitiveType->mAlign = mSystem->mPtrSize;
  904. primitiveType->mDefineState = BfTypeDefineState_Defined;
  905. return true;
  906. case BfTypeCode_Boolean:
  907. PRIMITIVE_TYPE("bool", Int1, 1, DW_ATE_boolean);
  908. return true;
  909. case BfTypeCode_Int8:
  910. PRIMITIVE_TYPE("sbyte", Int8, 1, DW_ATE_signed);
  911. return true;
  912. case BfTypeCode_UInt8:
  913. PRIMITIVE_TYPE("byte", Int8, 1, DW_ATE_unsigned);
  914. return true;
  915. case BfTypeCode_Int16:
  916. PRIMITIVE_TYPE("short", Int16, 2, DW_ATE_signed);
  917. return true;
  918. case BfTypeCode_UInt16:
  919. PRIMITIVE_TYPE("ushort", Int16, 2, DW_ATE_unsigned);
  920. return true;
  921. case BfTypeCode_Int32:
  922. PRIMITIVE_TYPE("int", Int32, 4, DW_ATE_signed);
  923. return true;
  924. case BfTypeCode_UInt32:
  925. PRIMITIVE_TYPE("uint", Int32, 4, DW_ATE_unsigned);
  926. return true;
  927. case BfTypeCode_Int64:
  928. PRIMITIVE_TYPE("long", Int64, 8, DW_ATE_signed);
  929. return true;
  930. case BfTypeCode_UInt64:
  931. PRIMITIVE_TYPE("ulong", Int64, 8, DW_ATE_unsigned);
  932. return true;
  933. case BfTypeCode_IntPtr:
  934. if (mSystem->mPtrSize == 4)
  935. {
  936. PRIMITIVE_TYPE("intptr", Int32, 4, DW_ATE_signed);
  937. }
  938. else
  939. {
  940. PRIMITIVE_TYPE("intptr", Int64, 8, DW_ATE_signed);
  941. }
  942. return true;
  943. case BfTypeCode_UIntPtr:
  944. if (mSystem->mPtrSize == 4)
  945. {
  946. PRIMITIVE_TYPE("uintptr", Int32, 4, DW_ATE_unsigned);
  947. }
  948. else
  949. {
  950. PRIMITIVE_TYPE("uintptr", Int64, 8, DW_ATE_unsigned);
  951. }
  952. return true;
  953. case BfTypeCode_IntUnknown:
  954. case BfTypeCode_UIntUnknown:
  955. return true;
  956. case BfTypeCode_Char8:
  957. PRIMITIVE_TYPE("char8", Int8, 1, DW_ATE_unsigned_char);
  958. return true;
  959. case BfTypeCode_Char16:
  960. PRIMITIVE_TYPE("char16", Int16, 2, DW_ATE_unsigned_char);
  961. return true;
  962. case BfTypeCode_Char32:
  963. PRIMITIVE_TYPE("char32", Int32, 4, DW_ATE_unsigned_char);
  964. return true;
  965. case BfTypeCode_Single:
  966. PRIMITIVE_TYPE("float", Float, 4, DW_ATE_float);
  967. return true;
  968. case BfTypeCode_Double:
  969. PRIMITIVE_TYPE("double", Double, 8, DW_ATE_float);
  970. return true;
  971. case BfTypeCode_Object:
  972. case BfTypeCode_Struct:
  973. case BfTypeCode_Interface:
  974. case BfTypeCode_Enum:
  975. // Implemented below
  976. break;
  977. case BfTypeCode_Extension:
  978. // This can only happen if we didn't actually find the type the extension referred to
  979. break;
  980. default:
  981. //NotImpl(resolvedTypeRef->mTypeRef);
  982. BF_FATAL("Invalid type");
  983. return false;
  984. }
  985. //////////////////////////////////////////////////////////////////////////
  986. BF_ASSERT(typeInstance != NULL);
  987. if (!typeInstance->IsArray())
  988. {
  989. BF_ASSERT(typeInstance->mTypeDef != mContext->mCompiler->mArray1TypeDef);
  990. }
  991. if (mContext->mBfObjectType == NULL)
  992. {
  993. if (typeInstance->mTypeDef == mCompiler->mBfObjectTypeDef)
  994. mContext->mBfObjectType = typeInstance;
  995. else
  996. ResolveTypeDef(mCompiler->mBfObjectTypeDef);
  997. }
  998. if (typeInstance->mModule == NULL)
  999. {
  1000. // Create a module for this type
  1001. mContext->HandleTypeWorkItem(resolvedTypeRef);
  1002. }
  1003. }
  1004. if (typeInstance == NULL)
  1005. return true;
  1006. auto result = typeInstance->mModule->DoPopulateType(typeInstance, populateType);
  1007. return result;
  1008. }
  1009. int BfModule::GenerateTypeOptions(BfCustomAttributes* customAttributes, BfTypeInstance* typeInstance, bool checkTypeName)
  1010. {
  1011. if (mContext->mSystem->mTypeOptions.size() == 0)
  1012. {
  1013. return -1;
  1014. }
  1015. Array<int> matchedIndices;
  1016. if ((!checkTypeName) && (typeInstance->mTypeOptionsIdx != -1))
  1017. {
  1018. // Methods should 'inherit' the owner's type options before applying type options from custom attributes
  1019. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  1020. if (typeOptions->mMatchedIndices.size() == 0)
  1021. matchedIndices.push_back(typeInstance->mTypeOptionsIdx);
  1022. else
  1023. matchedIndices = typeOptions->mMatchedIndices;
  1024. }
  1025. if (customAttributes != NULL)
  1026. {
  1027. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  1028. {
  1029. StringT<128> attrName;
  1030. for (auto& customAttrs : customAttributes->mAttributes)
  1031. {
  1032. attrName.Clear();
  1033. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  1034. Array<int>* arrPtr;
  1035. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  1036. {
  1037. for (auto optionsIdx : *arrPtr)
  1038. {
  1039. matchedIndices.Add(optionsIdx);
  1040. }
  1041. }
  1042. }
  1043. }
  1044. }
  1045. int typeOptionsCount = (int)mContext->mSystem->mTypeOptions.size();
  1046. if (checkTypeName)
  1047. {
  1048. auto _CheckTypeName = [&](const StringImpl& typeName)
  1049. {
  1050. for (int optionIdx = 0; optionIdx < (int)mContext->mSystem->mTypeOptions.size(); optionIdx++)
  1051. {
  1052. auto& typeOptions = mContext->mSystem->mTypeOptions[optionIdx];
  1053. bool matched = false;
  1054. for (auto& filter : typeOptions.mTypeFilters)
  1055. {
  1056. int filterIdx = 0;
  1057. int typeNameIdx = 0;
  1058. const char* filterPtr = filter.c_str();
  1059. const char* namePtr = typeName.c_str();
  1060. char prevFilterC = 0;
  1061. while (true)
  1062. {
  1063. char filterC;
  1064. while (true)
  1065. {
  1066. filterC = *(filterPtr++);
  1067. if (filterC != ' ')
  1068. break;
  1069. }
  1070. char nameC;
  1071. while (true)
  1072. {
  1073. nameC = *(namePtr++);
  1074. if (nameC != ' ')
  1075. break;
  1076. }
  1077. if ((filterC == 0) || (nameC == 0))
  1078. {
  1079. matched = (filterC == 0) && (nameC == 0);
  1080. break;
  1081. }
  1082. bool doWildcard = false;
  1083. if (nameC != filterC)
  1084. {
  1085. if (filterC == '*')
  1086. doWildcard = true;
  1087. else if (((filterC == ',') || (filterC == '>')) &&
  1088. ((prevFilterC == '<') || (prevFilterC == ',')))
  1089. {
  1090. doWildcard = true;
  1091. filterPtr--;
  1092. }
  1093. if (!doWildcard)
  1094. {
  1095. matched = false;
  1096. break;
  1097. }
  1098. }
  1099. if (doWildcard)
  1100. {
  1101. int openDepth = 0;
  1102. const char* startNamePtr = namePtr;
  1103. while (true)
  1104. {
  1105. nameC = *(namePtr++);
  1106. if (nameC == 0)
  1107. {
  1108. namePtr--;
  1109. if (openDepth != 0)
  1110. matched = false;
  1111. break;
  1112. }
  1113. if ((nameC == '>') && (openDepth == 0))
  1114. {
  1115. namePtr--;
  1116. break;
  1117. }
  1118. if (nameC == '<')
  1119. openDepth++;
  1120. else if (nameC == '>')
  1121. openDepth--;
  1122. else if ((nameC == ',') && (openDepth == 0))
  1123. {
  1124. namePtr--;
  1125. break;
  1126. }
  1127. }
  1128. if (!matched)
  1129. break;
  1130. }
  1131. prevFilterC = filterC;
  1132. }
  1133. }
  1134. if (matched)
  1135. matchedIndices.push_back(optionIdx);
  1136. }
  1137. };
  1138. if (typeInstance->IsTypedPrimitive())
  1139. {
  1140. auto underlyingType = typeInstance->GetUnderlyingType();
  1141. String typeName = TypeToString(underlyingType);
  1142. _CheckTypeName(typeName);
  1143. }
  1144. if ((!typeInstance->IsBoxed()) && (typeInstance->mTypeDef == mCompiler->mPointerTTypeDef))
  1145. {
  1146. BF_ASSERT(typeInstance->IsGenericTypeInstance());
  1147. auto innerType = ((BfGenericTypeInstance*)typeInstance)->mTypeGenericArguments[0];
  1148. auto ptrType = CreatePointerType(innerType);
  1149. String typeName = TypeToString(ptrType);
  1150. _CheckTypeName(typeName);
  1151. }
  1152. String typeName = TypeToString(typeInstance);
  1153. _CheckTypeName(typeName);
  1154. }
  1155. int matchedIdx = -1;
  1156. if (matchedIndices.size() == 1)
  1157. {
  1158. matchedIdx = matchedIndices[0];
  1159. }
  1160. else if (matchedIndices.size() > 1)
  1161. {
  1162. // Try to find a merged typeoptions with these indices
  1163. for (int mergedIdx = 0; mergedIdx < (int)mContext->mSystem->mMergedTypeOptions.size(); mergedIdx++)
  1164. {
  1165. auto& typeOptions = mContext->mSystem->mMergedTypeOptions[mergedIdx];
  1166. if (typeOptions.mMatchedIndices == matchedIndices)
  1167. {
  1168. matchedIdx = typeOptionsCount + mergedIdx;
  1169. break;
  1170. }
  1171. }
  1172. // Otherwise make one...
  1173. if (matchedIdx == -1)
  1174. {
  1175. auto& first = mContext->mSystem->mTypeOptions[matchedIndices[0]];
  1176. BfTypeOptions mergedTypeOptions;
  1177. mergedTypeOptions.mSIMDSetting = first.mSIMDSetting;
  1178. mergedTypeOptions.mOptimizationLevel = first.mOptimizationLevel;
  1179. mergedTypeOptions.mEmitDebugInfo = first.mEmitDebugInfo;
  1180. mergedTypeOptions.mRuntimeChecks = first.mRuntimeChecks;
  1181. mergedTypeOptions.mInitLocalVariables = first.mInitLocalVariables;
  1182. mergedTypeOptions.mEmitDynamicCastCheck = first.mEmitDynamicCastCheck;
  1183. mergedTypeOptions.mEmitObjectAccessCheck = first.mEmitObjectAccessCheck;
  1184. mergedTypeOptions.mAllocStackTraceDepth = first.mAllocStackTraceDepth;
  1185. mergedTypeOptions.mMatchedIndices = matchedIndices;
  1186. for (int idx = 1; idx < (int)matchedIndices.size(); idx++)
  1187. {
  1188. auto& typeOptions = mContext->mSystem->mTypeOptions[matchedIndices[idx]];
  1189. if (typeOptions.mSIMDSetting != -1)
  1190. mergedTypeOptions.mSIMDSetting = typeOptions.mSIMDSetting;
  1191. if (typeOptions.mOptimizationLevel != -1)
  1192. mergedTypeOptions.mOptimizationLevel = typeOptions.mOptimizationLevel;
  1193. if (typeOptions.mEmitDebugInfo != -1)
  1194. mergedTypeOptions.mEmitDebugInfo = typeOptions.mEmitDebugInfo;
  1195. if (typeOptions.mRuntimeChecks != BfOptionalBool_NotSet)
  1196. mergedTypeOptions.mRuntimeChecks = typeOptions.mRuntimeChecks;
  1197. if (typeOptions.mInitLocalVariables != BfOptionalBool_NotSet)
  1198. mergedTypeOptions.mInitLocalVariables = typeOptions.mInitLocalVariables;
  1199. if (typeOptions.mEmitDynamicCastCheck != BfOptionalBool_NotSet)
  1200. mergedTypeOptions.mEmitDynamicCastCheck = typeOptions.mEmitDynamicCastCheck;
  1201. if (typeOptions.mEmitObjectAccessCheck != BfOptionalBool_NotSet)
  1202. mergedTypeOptions.mEmitObjectAccessCheck = typeOptions.mEmitObjectAccessCheck;
  1203. if (typeOptions.mAllocStackTraceDepth != -1)
  1204. mergedTypeOptions.mAllocStackTraceDepth = typeOptions.mAllocStackTraceDepth;
  1205. }
  1206. matchedIdx = typeOptionsCount + (int)mContext->mSystem->mMergedTypeOptions.size();
  1207. mContext->mSystem->mMergedTypeOptions.push_back(mergedTypeOptions);
  1208. }
  1209. }
  1210. return matchedIdx;
  1211. }
  1212. void BfModule::SetTypeOptions(BfTypeInstance* typeInstance)
  1213. {
  1214. typeInstance->mTypeOptionsIdx = GenerateTypeOptions(typeInstance->mCustomAttributes, typeInstance, true);
  1215. }
  1216. bool BfModule::DoPopulateType(BfType* resolvedTypeRef, BfPopulateType populateType)
  1217. {
  1218. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  1219. auto typeDef = typeInstance->mTypeDef;
  1220. BF_ASSERT((typeInstance->mTypeDef->mNextRevision == NULL) || (mCompiler->IsAutocomplete()));
  1221. // This is a special case where our base type has been rebuilt but we haven't
  1222. if ((typeInstance->mBaseTypeMayBeIncomplete) && (!typeInstance->mTypeIncomplete))
  1223. {
  1224. BfLogSysM("BaseTypeMayBeIncomplete processing. Type:%p -> Base:%p\n", typeInstance, typeInstance->mBaseType);
  1225. PopulateType(typeInstance->mBaseType, populateType);
  1226. if (!typeInstance->mBaseType->IsIncomplete())
  1227. typeInstance->mBaseTypeMayBeIncomplete = false;
  1228. if (!typeInstance->mTypeIncomplete)
  1229. return true;
  1230. }
  1231. typeInstance->mBaseTypeMayBeIncomplete = false;
  1232. BF_ASSERT(mIsModuleMutable);
  1233. // Don't do type instance method processing for an autocomplete pass - this will get handled later on during
  1234. // the PopulateType worklist pass in the full resolver. We do need to handle the methods for delegates, though,
  1235. // since those can affect method declarations of other methods
  1236. // TODO: Investigate this "Delegate" claim
  1237. bool canDoMethodProcessing = ((mCompiler->mResolvePassData == NULL) || (mCompiler->mResolvePassData->mAutoComplete == NULL) /*|| (typeInstance->IsDelegate())*/);
  1238. if (populateType == BfPopulateType_Full_Force)
  1239. canDoMethodProcessing = true;
  1240. if (typeInstance->mResolvingConstField)
  1241. return !typeInstance->mTypeFailed;
  1242. if (typeInstance->mNeedsMethodProcessing)
  1243. {
  1244. if ((canDoMethodProcessing) && (populateType >= BfPopulateType_DataAndMethods))
  1245. DoTypeInstanceMethodProcessing(typeInstance);
  1246. return true;
  1247. }
  1248. // Partial population break out point
  1249. if ((populateType >= BfPopulateType_Identity) && (populateType <= BfPopulateType_IdentityNoRemapAlias))
  1250. return true;
  1251. if (!resolvedTypeRef->IsValueType())
  1252. {
  1253. resolvedTypeRef->mSize = typeInstance->mAlign = mSystem->mPtrSize;
  1254. }
  1255. BF_ASSERT((typeInstance->mMethodInstanceGroups.size() == 0) || (typeInstance->mMethodInstanceGroups.size() == typeDef->mMethods.size()));
  1256. typeInstance->mMethodInstanceGroups.Resize(typeDef->mMethods.size());
  1257. for (int i = 0; i < (int)typeInstance->mMethodInstanceGroups.size(); i++)
  1258. {
  1259. typeInstance->mMethodInstanceGroups[i].mOwner = typeInstance;
  1260. typeInstance->mMethodInstanceGroups[i].mMethodIdx = i;
  1261. }
  1262. AutoDisallowYield disableYield(mSystem);
  1263. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  1264. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  1265. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  1266. SetAndRestoreValue<bool> prevHadError(mHadBuildError, false);
  1267. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  1268. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  1269. typeState.mPopulateType = populateType;
  1270. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  1271. if (typeInstance->IsGenericTypeInstance())
  1272. {
  1273. auto genericTypeInst = (BfGenericTypeInstance*)typeInstance;
  1274. if (genericTypeInst->mGenericParams.size() == 0)
  1275. BuildGenericParams(resolvedTypeRef);
  1276. }
  1277. // Don't do TypeToString until down here. Otherwise we can infinitely loop on BuildGenericParams
  1278. bool isStruct = resolvedTypeRef->IsStruct();
  1279. bool reportErrors = true;
  1280. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  1281. reportErrors = true;
  1282. // If we're not the defining context then we don't report errors for this type, but errors will still put the system
  1283. // into an errored state
  1284. SetAndRestoreValue<bool> prevReportErrors(mReportErrors, reportErrors);
  1285. CheckCircularDataError();
  1286. bool underlyingTypeDeferred = false;
  1287. BfType* underlyingType = NULL;
  1288. if (typeInstance->mBaseType != NULL)
  1289. {
  1290. if (typeInstance->IsTypedPrimitive())
  1291. underlyingType = typeInstance->GetUnderlyingType();
  1292. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_UnderlyingTypeDeferred) != 0)
  1293. underlyingTypeDeferred = true;
  1294. }
  1295. else if (typeInstance->IsEnum())
  1296. {
  1297. bool hasPayloads = false;
  1298. for (auto fieldDef : typeDef->mFields)
  1299. {
  1300. if ((fieldDef->IsEnumCaseEntry()) && (fieldDef->mTypeRef != NULL))
  1301. {
  1302. hasPayloads = true;
  1303. break;
  1304. }
  1305. }
  1306. if (!hasPayloads)
  1307. {
  1308. bool hadType = false;
  1309. for (auto baseTypeRef : typeDef->mBaseTypes)
  1310. {
  1311. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurBaseTypeRef, baseTypeRef);
  1312. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  1313. SetAndRestoreValue<bool> prevSkipTypeProtectionChecks(typeInstance->mSkipTypeProtectionChecks, true);
  1314. auto baseType = ResolveTypeRef(baseTypeRef, BfPopulateType_Declaration);
  1315. if (baseType != NULL)
  1316. {
  1317. if (baseType->IsIntegral())
  1318. {
  1319. if (!hadType)
  1320. {
  1321. hadType = true;
  1322. underlyingType = baseType;
  1323. }
  1324. else
  1325. {
  1326. Fail("Underlying enum type already specified", baseTypeRef);
  1327. }
  1328. }
  1329. else
  1330. {
  1331. Fail("Invalid underlying enum type", baseTypeRef);
  1332. }
  1333. }
  1334. else
  1335. {
  1336. AssertErrorState();
  1337. typeInstance->mTypeFailed = true;
  1338. }
  1339. }
  1340. if (underlyingType == NULL)
  1341. {
  1342. underlyingType = GetPrimitiveType(BfTypeCode_Int64);
  1343. underlyingTypeDeferred = true;
  1344. }
  1345. }
  1346. }
  1347. else if (((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive())) &&
  1348. (!typeInstance->mTypeFailed))
  1349. {
  1350. for (auto baseTypeRef : typeDef->mBaseTypes)
  1351. {
  1352. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurBaseTypeRef, baseTypeRef);
  1353. // We ignore errors here to avoid double-errors for type lookups, but this is where data cycles are detected
  1354. // but that type of error supercedes the mIgnorErrors setting
  1355. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  1356. // Temporarily allow us to derive from private classes, to avoid infinite loop from TypeIsSubTypeOf
  1357. SetAndRestoreValue<bool> prevSkipTypeProtectionChecks(typeInstance->mSkipTypeProtectionChecks, true);
  1358. auto baseType = ResolveTypeRef(baseTypeRef, BfPopulateType_Declaration);
  1359. if (baseType != NULL)
  1360. {
  1361. if (baseType->IsPrimitiveType())
  1362. {
  1363. underlyingType = baseType;
  1364. }
  1365. else if (baseType->IsTypedPrimitive())
  1366. {
  1367. //PopulateType(baseType, true);
  1368. underlyingType = baseType->GetUnderlyingType();
  1369. BF_ASSERT(underlyingType != NULL);
  1370. }
  1371. }
  1372. else
  1373. {
  1374. AssertErrorState();
  1375. typeInstance->mTypeFailed = true;
  1376. }
  1377. }
  1378. // Incase we had re-entry, work this through ourselves again here
  1379. typeInstance->mIsTypedPrimitive = false;
  1380. }
  1381. if (underlyingTypeDeferred)
  1382. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_UnderlyingTypeDeferred);
  1383. typeInstance->mIsTypedPrimitive = underlyingType != NULL;
  1384. int wantFieldCount = (int)typeDef->mFields.size() + (((underlyingType != NULL) || (typeInstance->IsPayloadEnum())) ? 1 : 0);
  1385. if ((int)typeInstance->mFieldInstances.size() < wantFieldCount)
  1386. {
  1387. // Closures don't include the enclosed fields on their first pass through PopulateType, and they have no typeDef of their own
  1388. // so we need to take care not to truncate their fieldInstance vector here (thus the 'wantFieldCount' check above)
  1389. typeInstance->mFieldInstances.Resize(wantFieldCount);
  1390. }
  1391. if (underlyingType != NULL)
  1392. {
  1393. auto fieldInstance = &typeInstance->mFieldInstances.back();
  1394. fieldInstance->mDataOffset = 0;
  1395. fieldInstance->mDataSize = underlyingType->mSize;
  1396. fieldInstance->mOwner = typeInstance;
  1397. fieldInstance->mResolvedType = underlyingType;
  1398. typeInstance->mSize = underlyingType->mSize;
  1399. typeInstance->mAlign = underlyingType->mAlign;
  1400. typeInstance->mInstSize = underlyingType->mSize;
  1401. typeInstance->mInstAlign = underlyingType->mAlign;
  1402. typeInstance->mHasPackingHoles = underlyingType->HasPackingHoles();
  1403. }
  1404. // Partial population break out point
  1405. if (typeInstance->mDefineState < BfTypeDefineState_Declared)
  1406. {
  1407. typeInstance->mDefineState = BfTypeDefineState_Declared;
  1408. if (typeInstance->IsGenericTypeInstance())
  1409. {
  1410. auto genericTypeInstance = (BfGenericTypeInstance*)typeInstance;
  1411. // Add generic dependencies if needed
  1412. for (auto genericType : genericTypeInstance->mTypeGenericArguments)
  1413. {
  1414. if (genericType->IsPrimitiveType())
  1415. genericType = GetWrappedStructType(genericType);
  1416. if (genericType != NULL)
  1417. {
  1418. AddDependency(genericType, genericTypeInstance, BfDependencyMap::DependencyFlag_TypeGenericArg);
  1419. BfLogSysM("Adding generic dependency of %p for type %p\n", genericType, genericTypeInstance);
  1420. }
  1421. }
  1422. if (genericTypeInstance->IsSpecializedType())
  1423. {
  1424. // This ensures we rebuild the unspecialized type whenever the specialized type rebuilds. This is important
  1425. // for generic type binding
  1426. auto unspecializedTypeInstance = GetUnspecializedTypeInstance(genericTypeInstance);
  1427. BF_ASSERT(!unspecializedTypeInstance->IsUnspecializedTypeVariation());
  1428. mContext->mScratchModule->AddDependency(genericTypeInstance, unspecializedTypeInstance, BfDependencyMap::DependencyFlag_UnspecializedType);
  1429. }
  1430. }
  1431. auto _AddStaticSearch = [&](BfTypeDef* typeDef)
  1432. {
  1433. if (typeDef->mStaticSearch.IsEmpty())
  1434. return;
  1435. BfStaticSearch* staticSearch;
  1436. if (typeInstance->mStaticSearchMap.TryAdd(typeDef, NULL, &staticSearch))
  1437. {
  1438. for (auto typeRef : typeDef->mStaticSearch)
  1439. {
  1440. auto staticType = ResolveTypeRef(typeRef, NULL, BfPopulateType_Declaration);
  1441. if (staticType != NULL)
  1442. {
  1443. auto staticTypeInst = staticType->ToTypeInstance();
  1444. if (staticTypeInst == NULL)
  1445. {
  1446. Fail(StrFormat("Type '%s' cannot be used in a 'using static' declaration", TypeToString(staticType).c_str()), typeRef);
  1447. }
  1448. else
  1449. {
  1450. AddDependency(staticTypeInst, typeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  1451. }
  1452. }
  1453. }
  1454. }
  1455. };
  1456. if (typeDef->mIsCombinedPartial)
  1457. {
  1458. for (auto partialTypeDef : typeDef->mPartials)
  1459. _AddStaticSearch(partialTypeDef);
  1460. }
  1461. else
  1462. _AddStaticSearch(typeDef);
  1463. }
  1464. if (populateType == BfPopulateType_Declaration)
  1465. {
  1466. return true;
  1467. }
  1468. if ((!mCompiler->mIsResolveOnly) && (!typeInstance->mHasBeenInstantiated))
  1469. {
  1470. for (auto& dep : typeInstance->mDependencyMap)
  1471. {
  1472. auto& depEntry = dep.mValue;
  1473. if ((depEntry.mFlags & BfDependencyMap::DependencyFlag_Allocates) != 0)
  1474. {
  1475. auto depType = dep.mKey;
  1476. if (depType->mRevision == depEntry.mRevision)
  1477. {
  1478. BfLogSysM("Setting mHasBeenInstantiated for %p instantiated from %p\n", typeInstance, depType);
  1479. typeInstance->mHasBeenInstantiated = true;
  1480. }
  1481. }
  1482. }
  1483. }
  1484. BfLogSysM("Setting revision. Type: %p Revision: %d\n", typeInstance, mRevision);
  1485. typeInstance->mRevision = mRevision;
  1486. // Temporarily allow us to derive from private classes, to avoid infinite loop from TypeIsSubTypeOf
  1487. SetAndRestoreValue<bool> prevSkipTypeProtectionChecks(typeInstance->mSkipTypeProtectionChecks, true);
  1488. if ((typeDef->mOuterType != NULL) && (typeDef->mOuterType->IsGlobalsContainer()))
  1489. {
  1490. if ((typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mTypeNode != NULL))
  1491. Fail("Global blocks cannot contain type declarations", typeDef->mTypeDeclaration->mTypeNode);
  1492. }
  1493. /// Create DI data
  1494. SizedArray<BfIRType, 8> llvmFieldTypes;
  1495. int curFieldDataIdx = 0;
  1496. typeInstance->mBaseType = NULL;
  1497. BfTypeInstance* defaultBaseTypeInst = NULL;
  1498. // Find base type
  1499. BfType* baseType = NULL;
  1500. struct BfInterfaceDecl
  1501. {
  1502. BfTypeInstance* mIFaceTypeInst;
  1503. BfTypeReference* mTypeRef;
  1504. BfTypeDef* mDeclaringType;
  1505. };
  1506. SizedArray<BfInterfaceDecl, 8> interfaces;
  1507. HashSet<BfTypeInstance*> ifaceSet;
  1508. if (resolvedTypeRef == mContext->mBfObjectType)
  1509. {
  1510. baseType = NULL;
  1511. }
  1512. else if (typeInstance->IsEnum())
  1513. {
  1514. if (mCompiler->mEnumTypeDef == NULL)
  1515. {
  1516. Fail("Enum type required");
  1517. TypeFailed(typeInstance);
  1518. }
  1519. else
  1520. baseType = ResolveTypeDef(mCompiler->mEnumTypeDef)->ToTypeInstance();
  1521. }
  1522. else if (resolvedTypeRef->IsObject())
  1523. baseType = mContext->mBfObjectType;
  1524. else if (resolvedTypeRef->IsPointer())
  1525. {
  1526. baseType = ResolveTypeDef(mCompiler->mPointerTTypeDef, BfPopulateType_Data);
  1527. }
  1528. else if ((resolvedTypeRef->IsValueType()) && (typeDef != mCompiler->mValueTypeTypeDef))
  1529. {
  1530. baseType = ResolveTypeDef(mCompiler->mValueTypeTypeDef, BfPopulateType_Data)->ToTypeInstance();
  1531. }
  1532. if (baseType != NULL)
  1533. defaultBaseTypeInst = baseType->ToTypeInstance();
  1534. BfTypeReference* baseTypeRef = NULL;
  1535. if ((typeDef->mIsDelegate) && (!typeInstance->IsClosure()))
  1536. {
  1537. if (mCompiler->mDelegateTypeDef == NULL)
  1538. {
  1539. Fail("Delegate type required");
  1540. TypeFailed(typeInstance);
  1541. }
  1542. else
  1543. baseType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  1544. }
  1545. else if (typeDef->mIsFunction)
  1546. {
  1547. if (mCompiler->mFunctionTypeDef == NULL)
  1548. {
  1549. Fail("Function type required");
  1550. TypeFailed(typeInstance);
  1551. }
  1552. else
  1553. baseType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  1554. }
  1555. else
  1556. {
  1557. for (auto checkTypeRef : typeDef->mBaseTypes)
  1558. {
  1559. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurBaseTypeRef, checkTypeRef);
  1560. auto declTypeDef = typeDef;
  1561. if (typeDef->mIsCombinedPartial)
  1562. declTypeDef = typeDef->mPartials.front();
  1563. SetAndRestoreValue<BfTypeDef*> prevTypeDef(mContext->mCurTypeState->mCurTypeDef, declTypeDef);
  1564. bool populateBase = !typeInstance->mTypeFailed;
  1565. auto checkType = ResolveTypeRef(checkTypeRef, populateBase ? BfPopulateType_Data : BfPopulateType_Declaration);
  1566. if (checkType != NULL)
  1567. {
  1568. auto checkTypeInst = checkType->ToTypeInstance();
  1569. bool canDeriveFrom = checkTypeInst != NULL;
  1570. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  1571. canDeriveFrom |= checkType->IsPrimitiveType();
  1572. if ((typeInstance->IsEnum()) && (!checkType->IsInterface()))
  1573. {
  1574. if (typeInstance->IsTypedPrimitive())
  1575. continue;
  1576. if (checkType->IsPrimitiveType())
  1577. Fail(StrFormat("Enum '%s' cannot be specified as '%s' because it has a payload",
  1578. TypeToString(typeInstance).c_str(), TypeToString(checkType).c_str()),
  1579. checkTypeRef);
  1580. else
  1581. Fail("Enums cannot derive from other types", checkTypeRef);
  1582. continue;
  1583. }
  1584. if ((checkTypeInst != NULL) && (checkTypeInst->mTypeFailed))
  1585. {
  1586. // To keep circular references from breaking type invariants (ie: base type loops)
  1587. continue;
  1588. }
  1589. if (!canDeriveFrom)
  1590. {
  1591. Fail("Cannot derive from this type", checkTypeRef);
  1592. continue;
  1593. }
  1594. if (checkType->IsInterface())
  1595. {
  1596. auto ifaceInst = checkType->ToTypeInstance();
  1597. if (ifaceSet.Add(ifaceInst))
  1598. {
  1599. // Not base type
  1600. BfInterfaceDecl ifaceDecl;
  1601. ifaceDecl.mIFaceTypeInst = ifaceInst;
  1602. ifaceDecl.mTypeRef = checkTypeRef;
  1603. ifaceDecl.mDeclaringType = typeDef;
  1604. interfaces.push_back(ifaceDecl);
  1605. }
  1606. else
  1607. {
  1608. Fail(StrFormat("Interface '%s' is already specified", TypeToString(checkType).c_str()), checkTypeRef);
  1609. }
  1610. }
  1611. else if (resolvedTypeRef == mContext->mBfObjectType)
  1612. {
  1613. Fail(StrFormat("Type '%s' cannot define a base type", TypeToString(baseType).c_str()), checkTypeRef);
  1614. }
  1615. else
  1616. {
  1617. if (baseTypeRef != NULL)
  1618. {
  1619. Fail(StrFormat("Base type '%s' already declared", TypeToString(baseType).c_str()), checkTypeRef);
  1620. }
  1621. else
  1622. {
  1623. baseTypeRef = checkTypeRef;
  1624. if (checkTypeInst != NULL)
  1625. {
  1626. baseType = checkTypeInst;
  1627. /*if ((resolvedTypeRef->IsBoxed()) && (baseType->IsValueType()))
  1628. {
  1629. baseType = CreateBoxedType(baseType);
  1630. }*/
  1631. }
  1632. }
  1633. }
  1634. }
  1635. else
  1636. {
  1637. AssertErrorState();
  1638. // Why did we go around setting mTypeFailed on all these things?
  1639. //typeInstance->mTypeFailed = true;
  1640. }
  1641. }
  1642. for (auto partialTypeDef : typeDef->mPartials)
  1643. {
  1644. if (!typeInstance->IsTypeMemberIncluded(partialTypeDef))
  1645. continue;
  1646. if (partialTypeDef->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  1647. continue;
  1648. for (auto checkTypeRef : partialTypeDef->mBaseTypes)
  1649. {
  1650. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurBaseTypeRef, checkTypeRef);
  1651. SetAndRestoreValue<BfTypeDef*> prevTypeDef(mContext->mCurTypeState->mCurTypeDef, partialTypeDef);
  1652. bool populateBase = !typeInstance->mTypeFailed;
  1653. auto checkType = ResolveTypeRef(checkTypeRef, BfPopulateType_Declaration);
  1654. if (checkType != NULL)
  1655. {
  1656. if (checkType->IsInterface())
  1657. {
  1658. BfInterfaceDecl ifaceDecl;
  1659. ifaceDecl.mIFaceTypeInst = checkType->ToTypeInstance();
  1660. ifaceDecl.mTypeRef = checkTypeRef;
  1661. ifaceDecl.mDeclaringType = partialTypeDef;
  1662. interfaces.push_back(ifaceDecl);
  1663. }
  1664. else
  1665. {
  1666. Fail(StrFormat("Extensions can only specify new interfaces, type '%s' is not a valid ", TypeToString(checkType).c_str()), checkTypeRef);
  1667. }
  1668. }
  1669. }
  1670. }
  1671. }
  1672. if (resolvedTypeRef->IsBoxed())
  1673. {
  1674. if ((baseType != NULL) && (baseType->IsStruct()))
  1675. {
  1676. BfBoxedType* boxedType = (BfBoxedType*)resolvedTypeRef;
  1677. BfType* modifiedBaseType = baseType;
  1678. if (boxedType->IsBoxedStructPtr())
  1679. modifiedBaseType = CreatePointerType(modifiedBaseType);
  1680. boxedType->mBoxedBaseType = CreateBoxedType(modifiedBaseType);
  1681. PopulateType(boxedType->mBoxedBaseType);
  1682. AddDependency(boxedType->mBoxedBaseType, typeInstance, BfDependencyMap::DependencyFlag_DerivedFrom);
  1683. }
  1684. baseType = mContext->mBfObjectType;
  1685. }
  1686. BfTypeInstance* baseTypeInst = NULL;
  1687. if (baseType != NULL)
  1688. {
  1689. baseTypeInst = baseType->ToTypeInstance();
  1690. }
  1691. if (typeInstance->mBaseType != NULL)
  1692. {
  1693. BF_ASSERT(typeInstance->mBaseType == baseTypeInst);
  1694. }
  1695. BfType* outerType = GetOuterType(typeInstance);
  1696. if (outerType != NULL)
  1697. AddDependency(outerType, typeInstance, BfDependencyMap::DependencyFlag_OuterType);
  1698. if ((baseTypeInst != NULL) && (typeInstance->mBaseType == NULL))
  1699. {
  1700. //curFieldDataIdx = 1;
  1701. if (!typeInstance->mTypeFailed)
  1702. PopulateType(baseTypeInst, BfPopulateType_Data);
  1703. typeInstance->mBaseTypeMayBeIncomplete = false;
  1704. typeInstance->mMergedFieldDataCount = baseTypeInst->mMergedFieldDataCount;
  1705. if ((resolvedTypeRef->IsObject()) && (!baseTypeInst->IsObject()))
  1706. {
  1707. Fail("Class can only derive from another class", baseTypeRef, true);
  1708. //typeInstance->mTypeFailed = true;
  1709. baseTypeInst = defaultBaseTypeInst;
  1710. typeInstance->mBaseType = baseTypeInst;
  1711. }
  1712. else if ((resolvedTypeRef->IsStruct()) && (!baseTypeInst->IsValueType()))
  1713. {
  1714. Fail("Struct can only derive from another struct", baseTypeRef, true);
  1715. //typeInstance->mTypeFailed = true;
  1716. baseTypeInst = defaultBaseTypeInst;
  1717. typeInstance->mBaseType = baseTypeInst;
  1718. }
  1719. if (!typeInstance->IsIncomplete())
  1720. {
  1721. // Re-entry may cause this type to be completed already
  1722. return true;
  1723. }
  1724. //BfLogSysM("Adding DerivedFrom dependency. Used:%p Using:%p\n", baseType, typeInstance);
  1725. auto checkBaseType = baseTypeInst;
  1726. while (checkBaseType != NULL)
  1727. {
  1728. // Add 'DerivedFrom' dependency all the way up the inheritance chain
  1729. AddDependency(checkBaseType, typeInstance, BfDependencyMap::DependencyFlag_DerivedFrom);
  1730. checkBaseType = checkBaseType->mBaseType;
  1731. }
  1732. typeInstance->mBaseType = baseTypeInst;
  1733. typeInstance->mInheritDepth = baseTypeInst->mInheritDepth + 1;
  1734. typeInstance->mHasParameterizedBase = baseTypeInst->mHasParameterizedBase;
  1735. if ((baseTypeInst->IsArray()) || (baseTypeInst->IsSizedArray()) || (baseTypeInst->IsGenericTypeInstance()))
  1736. typeInstance->mHasParameterizedBase = true;
  1737. if (underlyingType == NULL)
  1738. {
  1739. typeInstance->mInstSize = baseTypeInst->mInstSize;
  1740. typeInstance->mInstAlign = baseTypeInst->mInstAlign;
  1741. typeInstance->mAlign = baseTypeInst->mAlign;
  1742. typeInstance->mSize = baseTypeInst->mSize;
  1743. typeInstance->mHasPackingHoles = baseTypeInst->mHasPackingHoles;
  1744. if (baseTypeInst->mIsTypedPrimitive)
  1745. typeInstance->mIsTypedPrimitive = true;
  1746. }
  1747. }
  1748. if (populateType <= BfPopulateType_BaseType)
  1749. return true;
  1750. if ((typeInstance->mBaseType != NULL) && (!typeInstance->IsTypedPrimitive()))
  1751. {
  1752. curFieldDataIdx++;
  1753. }
  1754. if (!interfaces.empty())
  1755. {
  1756. for (int iFaceIdx = 0; iFaceIdx < (int)interfaces.size(); iFaceIdx++)
  1757. {
  1758. auto checkInterface = interfaces[iFaceIdx].mIFaceTypeInst;
  1759. PopulateType(checkInterface, BfPopulateType_Data);
  1760. BfTypeInterfaceEntry* found = NULL;
  1761. bool foundExact = false;
  1762. for (auto& typeInterfaceInst : typeInstance->mInterfaces)
  1763. {
  1764. if (typeInterfaceInst.mInterfaceType == checkInterface)
  1765. {
  1766. if (typeInterfaceInst.mDeclaringType == interfaces[iFaceIdx].mDeclaringType)
  1767. {
  1768. foundExact = true;
  1769. break;
  1770. }
  1771. found = &typeInterfaceInst;
  1772. }
  1773. }
  1774. if (foundExact)
  1775. continue;
  1776. BfTypeInterfaceEntry typeInterfaceInst;
  1777. typeInterfaceInst.mDeclaringType = interfaces[iFaceIdx].mDeclaringType;
  1778. typeInterfaceInst.mInterfaceType = checkInterface;
  1779. typeInterfaceInst.mStartInterfaceTableIdx = -1;
  1780. typeInterfaceInst.mStartVirtualIdx = -1;
  1781. typeInterfaceInst.mIsRedeclared = false;
  1782. typeInstance->mInterfaces.push_back(typeInterfaceInst);
  1783. // Interfaces can list other interfaces in their declaration, so pull those in too
  1784. for (auto depIFace : checkInterface->mInterfaces)
  1785. {
  1786. auto depIFaceEntry = interfaces[iFaceIdx];
  1787. depIFaceEntry.mIFaceTypeInst = depIFace.mInterfaceType;
  1788. interfaces.push_back(depIFaceEntry);
  1789. }
  1790. }
  1791. }
  1792. typeInstance->mDefineState = BfTypeDefineState_HasInterfaces;
  1793. if (populateType <= BfPopulateType_Interfaces)
  1794. return true;
  1795. prevSkipTypeProtectionChecks.Restore();
  1796. typeInstance->mInstSize = std::max(0, typeInstance->mInstSize);
  1797. typeInstance->mInstAlign = std::max(0, typeInstance->mInstAlign);
  1798. if ((typeInstance->mCustomAttributes == NULL) && (typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mAttributes != NULL))
  1799. {
  1800. BfAttributeTargets attrTarget;
  1801. if ((typeDef->mIsDelegate) || (typeDef->mIsFunction))
  1802. attrTarget = BfAttributeTargets_Delegate;
  1803. else if (typeInstance->IsEnum())
  1804. attrTarget = BfAttributeTargets_Enum;
  1805. else if (typeInstance->IsInterface())
  1806. attrTarget = BfAttributeTargets_Interface;
  1807. else if (typeInstance->IsStruct())
  1808. attrTarget = BfAttributeTargets_Struct;
  1809. else
  1810. attrTarget = BfAttributeTargets_Class;
  1811. if (!typeInstance->mTypeFailed)
  1812. {
  1813. // This allows us to avoid reentrancy when checking for inner types
  1814. SetAndRestoreValue<bool> prevSkipTypeProtectionChecks(typeInstance->mSkipTypeProtectionChecks, true);
  1815. if (typeDef->mIsCombinedPartial)
  1816. {
  1817. for (auto partialTypeDef : typeDef->mPartials)
  1818. {
  1819. if (partialTypeDef->mTypeDeclaration->mAttributes == NULL)
  1820. continue;
  1821. BfTypeState typeState;
  1822. typeState.mCurTypeDef = partialTypeDef;
  1823. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  1824. if (typeInstance->mCustomAttributes == NULL)
  1825. typeInstance->mCustomAttributes = new BfCustomAttributes();
  1826. GetCustomAttributes(typeInstance->mCustomAttributes, partialTypeDef->mTypeDeclaration->mAttributes, attrTarget);
  1827. }
  1828. }
  1829. else
  1830. typeInstance->mCustomAttributes = GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, attrTarget);
  1831. }
  1832. }
  1833. if (typeInstance->mTypeOptionsIdx == -2)
  1834. {
  1835. SetTypeOptions(typeInstance);
  1836. }
  1837. ProcessCustomAttributeData();
  1838. bool isPacked = false;
  1839. bool isUnion = false;
  1840. bool isCRepr = false;
  1841. bool isOrdered = false;
  1842. ProcessTypeInstCustomAttributes(isPacked, isUnion, isCRepr, isOrdered);
  1843. typeInstance->mIsUnion = isUnion;
  1844. if ((typeInstance->IsEnum()) && (typeInstance->IsStruct()))
  1845. typeInstance->mIsUnion = true;
  1846. typeInstance->mIsPacked = isPacked;
  1847. typeInstance->mIsCRepr = isCRepr;
  1848. BfType* unionInnerType = NULL;
  1849. bool hadDeferredVars = false;
  1850. int dataPos;
  1851. if (resolvedTypeRef->IsBoxed())
  1852. {
  1853. BfBoxedType* boxedType = (BfBoxedType*)resolvedTypeRef;
  1854. BfType* innerType = boxedType->mElementType;
  1855. if (boxedType->IsBoxedStructPtr())
  1856. innerType = CreatePointerType(innerType);
  1857. if (innerType->IsIncomplete())
  1858. PopulateType(innerType, BfPopulateType_Data);
  1859. auto baseType = typeInstance->mBaseType;
  1860. dataPos = baseType->mInstSize;
  1861. int alignSize = BF_MAX(innerType->mAlign, baseType->mInstAlign);
  1862. if (alignSize > 1)
  1863. dataPos = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  1864. int dataSize = innerType->mSize;
  1865. typeInstance->mFieldInstances.push_back(BfFieldInstance());
  1866. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances.back();
  1867. fieldInstance->mDataOffset = dataPos;
  1868. fieldInstance->mDataSize = innerType->mSize;
  1869. fieldInstance->mOwner = typeInstance;
  1870. fieldInstance->mResolvedType = innerType;
  1871. if (!innerType->IsValuelessType())
  1872. {
  1873. curFieldDataIdx++;
  1874. }
  1875. dataPos += dataSize;
  1876. typeInstance->mInstAlign = std::max(baseType->mInstAlign, alignSize);
  1877. int instAlign = typeInstance->mInstAlign;
  1878. if (instAlign != 0)
  1879. {
  1880. int instSize = (dataPos + (instAlign - 1)) & ~(instAlign - 1);
  1881. if (instSize != typeInstance->mInstSize)
  1882. {
  1883. typeInstance->mInstSize = instSize;
  1884. typeInstance->mHasPackingHoles = true;
  1885. }
  1886. }
  1887. typeInstance->mInstSize = std::max(1, typeInstance->mInstSize);
  1888. }
  1889. else
  1890. {
  1891. dataPos = typeInstance->mInstSize;
  1892. if (underlyingType != NULL)
  1893. {
  1894. if (!underlyingType->IsValuelessType())
  1895. {
  1896. curFieldDataIdx++;
  1897. }
  1898. }
  1899. struct DeferredResolveEntry
  1900. {
  1901. BfFieldDef* mFieldDef;
  1902. int mTypeArrayIdx;
  1903. };
  1904. for (auto propDef : typeDef->mProperties)
  1905. {
  1906. if (!typeInstance->IsTypeMemberIncluded(propDef->mDeclaringType))
  1907. continue;
  1908. if (propDef->mFieldDeclaration != NULL)
  1909. {
  1910. if (propDef->mFieldDeclaration->mAttributes != NULL)
  1911. {
  1912. auto customAttrs = GetCustomAttributes(propDef->mFieldDeclaration->mAttributes, BfAttributeTargets_Property);
  1913. delete customAttrs;
  1914. }
  1915. if (propDef->mFieldDeclaration->mAttributes != NULL)
  1916. {
  1917. auto customAttrs = GetCustomAttributes(propDef->mFieldDeclaration->mAttributes, BfAttributeTargets_Property);
  1918. delete customAttrs;
  1919. }
  1920. auto propDecl = (BfPropertyDeclaration*)propDef->mFieldDeclaration;
  1921. if (propDecl->mExplicitInterface != NULL)
  1922. {
  1923. BfTypeState typeState;
  1924. typeState.mCurTypeDef = propDef->mDeclaringType;
  1925. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  1926. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  1927. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(propDecl->mExplicitInterface, false);
  1928. auto explicitInterface = ResolveTypeRef(propDecl->mExplicitInterface, BfPopulateType_Declaration);
  1929. if (explicitInterface != NULL)
  1930. {
  1931. bool interfaceFound = false;
  1932. for (auto ifaceInst : typeInstance->mInterfaces)
  1933. interfaceFound |= ifaceInst.mInterfaceType == explicitInterface;
  1934. if (!interfaceFound)
  1935. {
  1936. Fail("Containing class has not declared to implement this interface", propDecl->mExplicitInterface, true);
  1937. }
  1938. }
  1939. }
  1940. }
  1941. if (propDef->mMethods.IsEmpty())
  1942. {
  1943. auto nameNode = ((BfPropertyDeclaration*)propDef->mFieldDeclaration)->mNameNode;
  1944. if (nameNode != NULL)
  1945. {
  1946. Fail(StrFormat("Property or indexer '%s.%s' must have at least one accessor", TypeToString(typeInstance).c_str(), propDef->mName.c_str()),
  1947. nameNode, true); // CS0548
  1948. }
  1949. }
  1950. }
  1951. BfSizedVector<DeferredResolveEntry, 8> deferredVarResolves;
  1952. for (auto field : typeDef->mFields)
  1953. {
  1954. auto fieldInstance = &typeInstance->mFieldInstances[field->mIdx];
  1955. if (fieldInstance->mResolvedType != NULL)
  1956. continue;
  1957. if (!typeInstance->IsTypeMemberIncluded(field->mDeclaringType))
  1958. {
  1959. fieldInstance->mFieldIncluded = false;
  1960. continue;
  1961. }
  1962. fieldInstance->mOwner = typeInstance;
  1963. fieldInstance->mFieldIdx = field->mIdx;
  1964. if (typeInstance->IsInterface())
  1965. Fail("Interfaces cannot include fields. Consider making this a property", field->GetRefNode());
  1966. }
  1967. int enumCaseEntryIdx = 0;
  1968. for (auto field : typeDef->mFields)
  1969. {
  1970. auto fieldInstance = &typeInstance->mFieldInstances[field->mIdx];
  1971. if ((fieldInstance->mResolvedType != NULL) || (!fieldInstance->mFieldIncluded))
  1972. continue;
  1973. BfType* resolvedFieldType = NULL;
  1974. if (field->IsEnumCaseEntry())
  1975. {
  1976. fieldInstance->mDataIdx = -(enumCaseEntryIdx++) - 1;
  1977. resolvedFieldType = typeInstance;
  1978. BfType* payloadType = NULL;
  1979. if (field->mTypeRef != NULL)
  1980. payloadType = ResolveTypeRef(field->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  1981. if (payloadType == NULL)
  1982. {
  1983. if (!typeInstance->IsTypedPrimitive())
  1984. payloadType = CreateTupleType(BfTypeVector(), Array<String>());
  1985. }
  1986. if (payloadType != NULL)
  1987. {
  1988. AddDependency(payloadType, typeInstance, BfDependencyMap::DependencyFlag_ValueTypeMemberData);
  1989. BF_ASSERT(payloadType->IsTuple());
  1990. resolvedFieldType = payloadType;
  1991. fieldInstance->mIsEnumPayloadCase = true;
  1992. }
  1993. }
  1994. else if ((field->mTypeRef != NULL) && ((field->mTypeRef->IsExact<BfVarTypeReference>()) || (field->mTypeRef->IsExact<BfLetTypeReference>()) || (field->mTypeRef->IsExact<BfDeclTypeRef>())))
  1995. {
  1996. resolvedFieldType = GetPrimitiveType(BfTypeCode_Var);
  1997. DeferredResolveEntry resolveEntry;
  1998. resolveEntry.mFieldDef = field;
  1999. resolveEntry.mTypeArrayIdx = (int)llvmFieldTypes.size();
  2000. deferredVarResolves.push_back(resolveEntry);
  2001. fieldInstance->mIsInferredType = true;
  2002. // For 'let', make read-only
  2003. }
  2004. else
  2005. {
  2006. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, field);
  2007. resolvedFieldType = ResolveTypeRef(field->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  2008. if (resolvedFieldType == NULL)
  2009. {
  2010. // Failed, just put in placeholder 'var'
  2011. AssertErrorState();
  2012. resolvedFieldType = GetPrimitiveType(BfTypeCode_Var);
  2013. SetHadVarUsage();
  2014. }
  2015. }
  2016. if (resolvedFieldType->IsMethodRef())
  2017. {
  2018. auto methodRefType = (BfMethodRefType*)resolvedFieldType;
  2019. }
  2020. if (fieldInstance->mResolvedType == NULL)
  2021. fieldInstance->mResolvedType = resolvedFieldType;
  2022. if (field->mIsConst)
  2023. {
  2024. // Resolve in ResolveConstField after we finish populating entire FieldInstance list
  2025. }
  2026. else if (field->mIsStatic)
  2027. {
  2028. // Don't allocate this until after we're finished populating entire FieldInstance list,
  2029. // because we may have re-entry and create multiple instances of this static field
  2030. }
  2031. }
  2032. if (!resolvedTypeRef->IsIncomplete())
  2033. {
  2034. // We finished resolving ourselves through a re-entry, so we're actually done here
  2035. return true;
  2036. }
  2037. for (auto& resolveEntry : deferredVarResolves)
  2038. {
  2039. hadDeferredVars = true;
  2040. auto fieldType = ResolveVarFieldType(typeInstance, &typeInstance->mFieldInstances[resolveEntry.mFieldDef->mIdx], resolveEntry.mFieldDef);
  2041. if (fieldType == NULL)
  2042. {
  2043. fieldType = mContext->mBfObjectType;
  2044. // We used to set mTypeFailed, but mHasBuildError is enough to cause a type rebuild properly
  2045. mHadBuildError = true;
  2046. //typeInstance->mTypeFailed = true;
  2047. }
  2048. auto fieldInstance = &typeInstance->mFieldInstances[resolveEntry.mFieldDef->mIdx];
  2049. fieldInstance->SetResolvedType(fieldType);
  2050. }
  2051. if (typeInstance->mResolvingConstField)
  2052. return !typeInstance->mTypeFailed;
  2053. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  2054. {
  2055. auto fieldInstance = &fieldInstanceRef;
  2056. auto fieldDef = fieldInstance->GetFieldDef();
  2057. auto resolvedFieldType = fieldInstance->GetResolvedType();
  2058. if (!fieldInstance->mFieldIncluded)
  2059. continue;
  2060. if (resolvedFieldType == NULL)
  2061. {
  2062. if ((underlyingType != NULL) || (typeInstance->IsPayloadEnum()))
  2063. continue;
  2064. }
  2065. if (!fieldInstance->mFieldIncluded)
  2066. continue;
  2067. if (fieldDef == NULL)
  2068. continue;
  2069. if ((!fieldDef->mIsStatic) && (resolvedFieldType->IsValueType()))
  2070. {
  2071. // We need that type finished up for alignment and data size
  2072. // But if the type has failed then we need to avoid stack overflow so we don't finish it
  2073. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, fieldDef);
  2074. bool populateChildType = !typeInstance->mTypeFailed;
  2075. //bool populateChildType = true;
  2076. PopulateType(resolvedFieldType, populateChildType ? BfPopulateType_Data : BfPopulateType_Declaration);
  2077. if (populateChildType)
  2078. {
  2079. BF_ASSERT(!resolvedFieldType->IsDataIncomplete());
  2080. }
  2081. else
  2082. {
  2083. if (resolvedFieldType->IsDataIncomplete())
  2084. {
  2085. AssertErrorState();
  2086. resolvedFieldType = mContext->mBfObjectType;
  2087. fieldInstance->SetResolvedType(resolvedFieldType);
  2088. // We used to set mTypeFailed, but mHasBuildError is enough to cause a type rebuild properly
  2089. mHadBuildError = true;
  2090. }
  2091. }
  2092. }
  2093. }
  2094. }
  2095. if ((!typeInstance->IsIncomplete()) || (typeInstance->mNeedsMethodProcessing))
  2096. {
  2097. return !typeInstance->mTypeFailed;
  2098. }
  2099. BF_ASSERT(mContext->mCurTypeState == &typeState);
  2100. BF_ASSERT(!typeInstance->mIsFinishingType);
  2101. typeInstance->mIsFinishingType = true;
  2102. // No re-entry is allowed below here -- we will run all the way to the end at this point
  2103. BfSizedVector<BfIRMDNode, 8> diFieldTypes;
  2104. HashContext dataMemberHashCtx;
  2105. if (!resolvedTypeRef->IsBoxed())
  2106. {
  2107. bool isGlobalContainer = typeDef->IsGlobalsContainer();
  2108. if (typeInstance->mBaseType != NULL)
  2109. {
  2110. dataMemberHashCtx.Mixin(typeInstance->mBaseType->mTypeId);
  2111. if (typeInstance->mBaseType->mHotTypeData != NULL)
  2112. {
  2113. BfHotTypeVersion* ver = typeInstance->mBaseType->mHotTypeData->GetLatestVersion();
  2114. dataMemberHashCtx.Mixin(ver->mDataHash);
  2115. }
  2116. }
  2117. dataMemberHashCtx.Mixin(typeInstance->mIsPacked);
  2118. dataMemberHashCtx.Mixin(typeInstance->mIsCRepr);
  2119. dataMemberHashCtx.Mixin(typeInstance->mIsUnion);
  2120. int startDataPos = dataPos;
  2121. int maxDataPos = dataPos;
  2122. BfSizedVector<BfFieldInstance*, 16> dataFieldVec;
  2123. // We've resolved all the 'var' entries, so now build the actual composite type
  2124. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  2125. {
  2126. auto fieldInstance = &fieldInstanceRef;
  2127. if (!fieldInstance->mFieldIncluded)
  2128. continue;
  2129. auto resolvedFieldType = fieldInstance->GetResolvedType();
  2130. if (fieldInstance->mResolvedType == NULL)
  2131. {
  2132. if ((underlyingType == NULL) && (!typeInstance->IsPayloadEnum()))
  2133. BF_ASSERT(typeInstance->mTypeFailed);
  2134. continue;
  2135. }
  2136. if ((fieldInstance->GetFieldDef() != NULL) && (fieldInstance->GetFieldDef()->mIsConst))
  2137. {
  2138. // Resolve later
  2139. }
  2140. else if (fieldInstance->GetFieldDef() != NULL)
  2141. {
  2142. if (!fieldInstance->GetFieldDef()->mIsStatic)
  2143. AddFieldDependency(typeInstance, fieldInstance, resolvedFieldType);
  2144. else
  2145. AddDependency(resolvedFieldType, typeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  2146. }
  2147. auto fieldDef = fieldInstance->GetFieldDef();
  2148. BF_ASSERT(fieldInstance->mCustomAttributes == NULL);
  2149. if ((fieldDef != NULL) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mAttributes != NULL))
  2150. {
  2151. fieldInstance->mCustomAttributes = GetCustomAttributes(fieldDef->mFieldDeclaration->mAttributes, fieldDef->mIsStatic ? BfAttributeTargets_StaticField : BfAttributeTargets_Field);
  2152. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  2153. {
  2154. if (TypeToString(customAttr.mType) == "System.ThreadStaticAttribute")
  2155. {
  2156. if ((!fieldDef->mIsStatic) || (fieldDef->mIsConst))
  2157. {
  2158. Fail("ThreadStatic attribute can only be used on static fields", fieldDef->mFieldDeclaration->mAttributes);
  2159. }
  2160. }
  2161. }
  2162. }
  2163. if (fieldInstance->mResolvedType != NULL)
  2164. {
  2165. auto resolvedFieldType = fieldInstance->GetResolvedType();
  2166. if ((!typeInstance->IsBoxed()) && (fieldDef != NULL))
  2167. {
  2168. if (fieldInstance->mIsEnumPayloadCase)
  2169. {
  2170. PopulateType(resolvedFieldType, BfPopulateType_Data);
  2171. if (resolvedFieldType->WantsGCMarking())
  2172. typeInstance->mWantsGCMarking = true;
  2173. }
  2174. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  2175. {
  2176. PopulateType(resolvedFieldType, resolvedFieldType->IsValueType() ? BfPopulateType_Data : BfPopulateType_Declaration);
  2177. if (resolvedFieldType->WantsGCMarking())
  2178. typeInstance->mWantsGCMarking = true;
  2179. fieldInstance->mMergedDataIdx = typeInstance->mMergedFieldDataCount;
  2180. if (resolvedFieldType->IsStruct())
  2181. {
  2182. auto resolvedFieldTypeInstance = resolvedFieldType->ToTypeInstance();
  2183. typeInstance->mMergedFieldDataCount += resolvedFieldTypeInstance->mMergedFieldDataCount;
  2184. }
  2185. else if (!resolvedFieldType->IsValuelessType())
  2186. typeInstance->mMergedFieldDataCount++;
  2187. if (fieldDef->mIsExtern)
  2188. {
  2189. Fail("Cannot declare instance member as 'extern'", fieldDef->mFieldDeclaration->mExternSpecifier, true);
  2190. }
  2191. BfAstNode* nameRefNode = NULL;
  2192. if (fieldDef->mFieldDeclaration != NULL)
  2193. nameRefNode = fieldDef->mFieldDeclaration->mNameNode;
  2194. if (nameRefNode == NULL)
  2195. nameRefNode = fieldDef->mTypeRef;
  2196. if (underlyingType != NULL)
  2197. {
  2198. if (typeInstance->IsEnum())
  2199. Fail("Cannot declare instance members in an enum", nameRefNode, true);
  2200. else
  2201. Fail("Cannot declare instance members in a typed primitive struct", nameRefNode, true);
  2202. TypeFailed(typeInstance);
  2203. fieldInstance->mDataIdx = -1;
  2204. continue;
  2205. }
  2206. if (typeDef->mIsStatic)
  2207. {
  2208. //CS0708
  2209. Fail("Cannot declare instance members in a static class", nameRefNode, true);
  2210. }
  2211. if (resolvedFieldType->IsValueType())
  2212. {
  2213. BF_ASSERT(!resolvedFieldType->IsDataIncomplete());
  2214. }
  2215. if (!mCompiler->mIsResolveOnly)
  2216. {
  2217. dataMemberHashCtx.MixinStr(fieldDef->mName);
  2218. dataMemberHashCtx.Mixin(resolvedFieldType->mTypeId);
  2219. }
  2220. int dataSize = resolvedFieldType->mSize;
  2221. int alignSize = resolvedFieldType->mAlign;
  2222. fieldInstance->mDataSize = dataSize;
  2223. if (!isUnion)
  2224. {
  2225. if (!resolvedFieldType->IsValuelessType())
  2226. {
  2227. if (isCRepr)
  2228. {
  2229. dataFieldVec.push_back(fieldInstance);
  2230. }
  2231. else
  2232. {
  2233. dataFieldVec.push_back(fieldInstance);
  2234. }
  2235. }
  2236. }
  2237. else
  2238. {
  2239. BF_ASSERT(resolvedFieldType->mSize >= 0);
  2240. if ((alignSize > 1) && (!isPacked))
  2241. dataPos = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  2242. fieldInstance->mDataOffset = dataPos;
  2243. if (!isPacked)
  2244. typeInstance->mInstAlign = std::max(typeInstance->mInstAlign, alignSize);
  2245. dataPos += dataSize;
  2246. if (dataPos > maxDataPos)
  2247. {
  2248. maxDataPos = dataPos;
  2249. }
  2250. dataPos = startDataPos;
  2251. }
  2252. auto fieldTypeInst = resolvedFieldType->ToTypeInstance();
  2253. if (fieldTypeInst != NULL)
  2254. {
  2255. if ((fieldTypeInst->mRebuildFlags & BfTypeRebuildFlag_UnderlyingTypeDeferred) != 0)
  2256. {
  2257. BfAstNode* refNode = fieldDef->mFieldDeclaration;
  2258. String failStr;
  2259. failStr = StrFormat("Circular data reference detected between '%s' and '%s'", TypeToString(mCurTypeInstance).c_str(), TypeToString(fieldTypeInst).c_str());
  2260. if (!mContext->mFieldResolveReentrys.IsEmpty())
  2261. {
  2262. failStr += StrFormat(" with the following fields:", TypeToString(mCurTypeInstance).c_str());
  2263. for (int i = 0; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2264. {
  2265. auto checkField = mContext->mFieldResolveReentrys[i];
  2266. if (i > 0)
  2267. failStr += ",";
  2268. failStr += "\n '" + TypeToString(typeInstance) + "." + checkField->GetFieldDef()->mName + "'";
  2269. if (checkField->mOwner == fieldTypeInst)
  2270. refNode = checkField->GetFieldDef()->mFieldDeclaration;
  2271. }
  2272. }
  2273. BfError* err = Fail(failStr, refNode);
  2274. if (err)
  2275. err->mIsPersistent = true;
  2276. }
  2277. }
  2278. }
  2279. bool useForUnion = false;
  2280. if (fieldInstance->mIsEnumPayloadCase)
  2281. {
  2282. if (!typeInstance->IsEnum())
  2283. {
  2284. Fail("Cases can only be used in enum types", fieldDef->mFieldDeclaration);
  2285. }
  2286. else
  2287. {
  2288. BF_ASSERT(typeInstance->mIsUnion);
  2289. }
  2290. }
  2291. if ((!fieldDef->mIsStatic) && (!resolvedFieldType->IsValuelessType()))
  2292. {
  2293. if (isUnion)
  2294. {
  2295. fieldInstance->mDataIdx = curFieldDataIdx;
  2296. }
  2297. }
  2298. }
  2299. if ((!typeInstance->IsSpecializedType()) && (!typeInstance->IsOnDemand()) && (fieldDef != NULL) && (!CheckDefineMemberProtection(fieldDef->mProtection, resolvedFieldType)))
  2300. {
  2301. //CS0052
  2302. Fail(StrFormat("Inconsistent accessibility: field type '%s' is less accessible than field '%s.%s'",
  2303. TypeToString(resolvedFieldType).c_str(), TypeToString(mCurTypeInstance).c_str(), fieldDef->mName.c_str()),
  2304. fieldDef->mTypeRef, true);
  2305. }
  2306. }
  2307. }
  2308. if (typeInstance->mIsUnion)
  2309. unionInnerType = typeInstance->GetUnionInnerType();
  2310. if (!isOrdered)
  2311. {
  2312. int dataFieldCount = (int)dataFieldVec.size();
  2313. Array<Deque<BfFieldInstance*>> alignBuckets;
  2314. for (auto fieldInst : dataFieldVec)
  2315. {
  2316. int alignBits = GetHighestBitSet(fieldInst->mResolvedType->mAlign);
  2317. while (alignBits >= alignBuckets.size())
  2318. alignBuckets.Add({});
  2319. alignBuckets[alignBits].Add(fieldInst);
  2320. }
  2321. dataFieldVec.clear();
  2322. int curSize = typeInstance->mInstSize;
  2323. while (dataFieldVec.size() != dataFieldCount)
  2324. {
  2325. // Clear out completed buckets
  2326. while (alignBuckets[alignBuckets.size() - 1].IsEmpty())
  2327. {
  2328. alignBuckets.pop_back();
  2329. }
  2330. int alignBits = GetNumLowZeroBits(curSize) + 1;
  2331. alignBits = BF_MIN(alignBits, (int)alignBuckets.size() - 1);
  2332. bool foundEntry = false;
  2333. while (alignBits >= 0)
  2334. {
  2335. if (alignBuckets[alignBits].IsEmpty())
  2336. {
  2337. alignBits--;
  2338. continue;
  2339. }
  2340. bool isHighestBucket = alignBits == alignBuckets.size() - 1;
  2341. auto fieldInst = alignBuckets[alignBits][0];
  2342. alignBuckets[alignBits].RemoveAt(0);
  2343. dataFieldVec.push_back(fieldInst);
  2344. curSize = BF_ALIGN(curSize, fieldInst->mResolvedType->mAlign);
  2345. curSize += fieldInst->mResolvedType->mSize;
  2346. foundEntry = true;
  2347. if (!isHighestBucket)
  2348. {
  2349. // We may have a larger type that can fit now...
  2350. break;
  2351. }
  2352. }
  2353. if (!foundEntry)
  2354. {
  2355. // If no entries will fit, then force an entry of the smallest alignment
  2356. for (int alignBits = 0; alignBits < alignBuckets.size(); alignBits++)
  2357. {
  2358. if (!alignBuckets[alignBits].IsEmpty())
  2359. {
  2360. auto fieldInst = alignBuckets[alignBits][0];
  2361. alignBuckets[alignBits].RemoveAt(0);
  2362. dataFieldVec.push_back(fieldInst);
  2363. curSize = BF_ALIGN(curSize, fieldInst->mResolvedType->mAlign);
  2364. curSize += fieldInst->mResolvedType->mSize;
  2365. break;
  2366. }
  2367. }
  2368. }
  2369. }
  2370. }
  2371. for (auto fieldInstance : dataFieldVec)
  2372. {
  2373. auto resolvedFieldType = fieldInstance->GetResolvedType();
  2374. BF_ASSERT(resolvedFieldType->mSize >= 0);
  2375. int dataSize = resolvedFieldType->mSize;
  2376. int alignSize = resolvedFieldType->mAlign;
  2377. fieldInstance->mDataSize = dataSize;
  2378. bool needsExplicitAlignment = !isCRepr || resolvedFieldType->NeedsExplicitAlignment();
  2379. int nextDataPos = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  2380. int padding = nextDataPos - dataPos;
  2381. if ((alignSize > 1) && (needsExplicitAlignment) && (padding > 0))
  2382. {
  2383. curFieldDataIdx++;
  2384. }
  2385. dataPos = nextDataPos;
  2386. fieldInstance->mDataOffset = dataPos;
  2387. fieldInstance->mDataIdx = curFieldDataIdx++;
  2388. if (!isPacked)
  2389. typeInstance->mInstAlign = std::max(typeInstance->mInstAlign, alignSize);
  2390. dataPos += dataSize;
  2391. }
  2392. if (unionInnerType != NULL)
  2393. {
  2394. dataPos = unionInnerType->mSize;
  2395. typeInstance->mInstAlign = BF_MAX(unionInnerType->mAlign, typeInstance->mInstAlign);
  2396. }
  2397. // Old dataMemberHash location
  2398. CheckMemberNames(typeInstance);
  2399. if (isPacked)
  2400. typeInstance->mInstAlign = 1;
  2401. else
  2402. typeInstance->mInstAlign = std::max(1, typeInstance->mInstAlign);
  2403. int alignSize = typeInstance->mInstAlign;
  2404. if (isCRepr)
  2405. {
  2406. // Align size to alignment
  2407. if (alignSize >= 1)
  2408. typeInstance->mInstSize = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  2409. typeInstance->mIsCRepr = true;
  2410. }
  2411. else
  2412. {
  2413. typeInstance->mInstSize = dataPos;
  2414. typeInstance->mIsCRepr = false;
  2415. }
  2416. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  2417. {
  2418. for (auto propDef : typeInstance->mTypeDef->mProperties)
  2419. if (propDef->mFieldDeclaration != NULL)
  2420. mCompiler->mResolvePassData->mAutoComplete->CheckProperty(BfNodeDynCast<BfPropertyDeclaration>(propDef->mFieldDeclaration));
  2421. }
  2422. }
  2423. if (typeInstance->IsObjectOrInterface())
  2424. typeInstance->mWantsGCMarking = true;
  2425. if ((mCompiler->mOptions.mEnableRealtimeLeakCheck) && (!typeInstance->mWantsGCMarking))
  2426. {
  2427. typeInstance->mTypeDef->PopulateMemberSets();
  2428. BfMemberSetEntry* entry = NULL;
  2429. BfMethodDef* methodDef = NULL;
  2430. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  2431. {
  2432. methodDef = (BfMethodDef*)entry->mMemberDef;
  2433. if (methodDef->HasBody())
  2434. typeInstance->mWantsGCMarking = true;
  2435. }
  2436. }
  2437. if (typeInstance->IsValueType())
  2438. {
  2439. typeInstance->mSize = typeInstance->mInstSize;
  2440. typeInstance->mAlign = typeInstance->mInstAlign;
  2441. }
  2442. if ((mCompiler->mOptions.mAllowHotSwapping) && (typeInstance->mDefineState < BfTypeDefineState_Defined))
  2443. {
  2444. if (typeInstance->mHotTypeData == NULL)
  2445. typeInstance->mHotTypeData = new BfHotTypeData();
  2446. // Clear any unused versions (if we have errors, etc)
  2447. if (mCompiler->mHotState != NULL)
  2448. typeInstance->mHotTypeData->ClearVersionsAfter(mCompiler->mHotState->mCommittedHotCompileIdx);
  2449. else
  2450. BF_ASSERT(typeInstance->mHotTypeData->mTypeVersions.IsEmpty()); // We should have created a new HotTypeData when rebuilding the type
  2451. BfHotTypeVersion* hotTypeVersion = new BfHotTypeVersion();
  2452. hotTypeVersion->mTypeId = typeInstance->mTypeId;
  2453. if (typeInstance->mBaseType != NULL)
  2454. hotTypeVersion->mBaseType = typeInstance->mBaseType->mHotTypeData->GetLatestVersion();
  2455. hotTypeVersion->mDeclHotCompileIdx = mCompiler->mOptions.mHotCompileIdx;
  2456. if (mCompiler->IsHotCompile())
  2457. hotTypeVersion->mCommittedHotCompileIdx = -1;
  2458. else
  2459. hotTypeVersion->mCommittedHotCompileIdx = 0;
  2460. hotTypeVersion->mRefCount++;
  2461. typeInstance->mHotTypeData->mTypeVersions.Add(hotTypeVersion);
  2462. if (typeInstance->mBaseType != NULL)
  2463. {
  2464. hotTypeVersion->mMembers.Add(typeInstance->mBaseType->mHotTypeData->GetLatestVersion());
  2465. }
  2466. for (auto& fieldInst : typeInstance->mFieldInstances)
  2467. {
  2468. auto fieldDef = fieldInst.GetFieldDef();
  2469. if ((fieldDef == NULL) || (fieldDef->mIsStatic))
  2470. continue;
  2471. auto depType = fieldInst.mResolvedType;
  2472. while (depType->IsSizedArray())
  2473. depType = ((BfSizedArrayType*)depType)->mElementType;
  2474. if (depType->IsStruct())
  2475. {
  2476. PopulateType(depType);
  2477. auto depTypeInst = depType->ToTypeInstance();
  2478. BF_ASSERT(depTypeInst->mHotTypeData != NULL);
  2479. if (depTypeInst->mHotTypeData != NULL)
  2480. hotTypeVersion->mMembers.Add(depTypeInst->mHotTypeData->GetLatestVersion());
  2481. }
  2482. }
  2483. for (auto member : hotTypeVersion->mMembers)
  2484. member->mRefCount++;
  2485. BfLogSysM("BfHotTypeVersion %p created for type %p\n", hotTypeVersion, typeInstance);
  2486. }
  2487. typeInstance->mDefineState = BfTypeDefineState_Defined;
  2488. if (typeInstance->mTypeFailed)
  2489. mHadBuildError = true;
  2490. CheckAddFailType();
  2491. typeInstance->mNeedsMethodProcessing = true;
  2492. typeInstance->mIsFinishingType = false;
  2493. ///
  2494. // 'Splattable' means that we can be passed via 3 or fewer primitive/pointer values
  2495. if (typeInstance->IsStruct())
  2496. {
  2497. bool hadNonSplattable = false;
  2498. if (typeInstance->mBaseType != NULL)
  2499. PopulateType(typeInstance->mBaseType, BfPopulateType_Data);
  2500. if ((typeInstance->mBaseType == NULL) || (typeInstance->mBaseType->IsSplattable()))
  2501. {
  2502. int dataCount = 0;
  2503. std::function<void(BfType*)> splatIterate;
  2504. splatIterate = [&](BfType* checkType)
  2505. {
  2506. if (checkType->IsMethodRef())
  2507. {
  2508. // For simplicitly, any methodRef inside a struct makes the struct non-splattable. This reduces cases of needing to
  2509. // handle embedded methodRefs
  2510. hadNonSplattable = true;
  2511. }
  2512. else if (checkType->IsStruct())
  2513. {
  2514. PopulateType(checkType, BfPopulateType_Data);
  2515. auto checkTypeInstance = checkType->ToTypeInstance();
  2516. if (checkTypeInstance->mBaseType != NULL)
  2517. splatIterate(checkTypeInstance->mBaseType);
  2518. if (checkTypeInstance->mIsUnion)
  2519. {
  2520. bool wantSplat = false;
  2521. auto unionInnerType = checkTypeInstance->GetUnionInnerType(&wantSplat);
  2522. if (!wantSplat)
  2523. hadNonSplattable = true;
  2524. splatIterate(unionInnerType);
  2525. if (checkTypeInstance->IsEnum())
  2526. dataCount++; // Discriminator
  2527. }
  2528. else
  2529. {
  2530. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  2531. {
  2532. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  2533. if (fieldInstance->mDataIdx >= 0)
  2534. splatIterate(fieldInstance->GetResolvedType());
  2535. }
  2536. }
  2537. }
  2538. else if (!checkType->IsValuelessType())
  2539. {
  2540. if (checkType->IsSizedArray())
  2541. hadNonSplattable = true;
  2542. dataCount += checkType->GetSplatCount();
  2543. }
  2544. };
  2545. splatIterate(typeInstance);
  2546. if (isCRepr)
  2547. typeInstance->mIsSplattable = false;
  2548. else
  2549. typeInstance->mIsSplattable = (dataCount <= 3) && (!hadNonSplattable);
  2550. }
  2551. }
  2552. if (typeInstance->IsTypedPrimitive())
  2553. typeInstance->mIsSplattable = true;
  2554. BF_ASSERT(mContext->mCurTypeState == &typeState);
  2555. // This is only required for autocomplete and finding type references
  2556. if (!typeInstance->IsSpecializedType())
  2557. {
  2558. for (auto propDef : typeDef->mProperties)
  2559. {
  2560. if (propDef->mTypeRef == NULL)
  2561. continue;
  2562. BfTypeState typeState;
  2563. typeState.mCurTypeDef = propDef->mDeclaringType;
  2564. typeState.mTypeInstance = typeInstance;
  2565. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  2566. ResolveTypeRef(propDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowRef);
  2567. }
  2568. }
  2569. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  2570. {
  2571. auto fieldInstance = &fieldInstanceRef;
  2572. if (!fieldInstance->mFieldIncluded)
  2573. continue;
  2574. auto fieldDef = fieldInstance->GetFieldDef();
  2575. if (fieldDef == NULL)
  2576. continue;
  2577. if ((fieldInstance->mConstIdx == -1) && (fieldDef->mIsConst))
  2578. {
  2579. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, fieldDef);
  2580. typeInstance->mModule->ResolveConstField(typeInstance, fieldInstance, fieldDef);
  2581. }
  2582. }
  2583. if ((typeInstance->IsEnum()) && (!typeInstance->IsPayloadEnum()))
  2584. {
  2585. BfLogSysM("Setting underlying type %p %d\n", typeInstance, underlyingTypeDeferred);
  2586. }
  2587. if (typeInstance->IsEnum())
  2588. {
  2589. int64 min = 0;
  2590. int64 max = 0;
  2591. bool isFirst = false;
  2592. if (typeInstance->mTypeInfoEx == NULL)
  2593. typeInstance->mTypeInfoEx = new BfTypeInfoEx();
  2594. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  2595. {
  2596. auto fieldInstance = &fieldInstanceRef;
  2597. auto fieldDef = fieldInstance->GetFieldDef();
  2598. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  2599. {
  2600. if (fieldInstance->mConstIdx == -1)
  2601. continue;
  2602. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  2603. BF_ASSERT((constant->mTypeCode == BfTypeCode_Int64) || (!underlyingTypeDeferred));
  2604. if (isFirst)
  2605. {
  2606. min = constant->mInt64;
  2607. max = constant->mInt64;
  2608. isFirst = false;
  2609. }
  2610. else
  2611. {
  2612. min = BF_MIN(constant->mInt64, min);
  2613. max = BF_MAX(constant->mInt64, max);
  2614. }
  2615. }
  2616. }
  2617. typeInstance->mTypeInfoEx->mMinValue = min;
  2618. typeInstance->mTypeInfoEx->mMaxValue = max;
  2619. if (underlyingTypeDeferred)
  2620. {
  2621. BfTypeCode typeCode;
  2622. if ((min >= -0x80) && (max <= 0x7F))
  2623. typeCode = BfTypeCode_Int8;
  2624. else if ((min >= 0) && (max <= 0xFF))
  2625. typeCode = BfTypeCode_UInt8;
  2626. else if ((min >= -0x8000) && (max <= 0x7FFF))
  2627. typeCode = BfTypeCode_Int16;
  2628. else if ((min >= 0) && (max <= 0xFFFF))
  2629. typeCode = BfTypeCode_UInt16;
  2630. else if ((min >= -0x80000000LL) && (max <= 0x7FFFFFFF))
  2631. typeCode = BfTypeCode_Int32;
  2632. else if ((min >= 0) && (max <= 0xFFFFFFFFLL))
  2633. typeCode = BfTypeCode_UInt32;
  2634. else
  2635. typeCode = BfTypeCode_Int64;
  2636. if (typeCode != BfTypeCode_Int64)
  2637. {
  2638. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  2639. {
  2640. auto fieldInstance = &fieldInstanceRef;
  2641. if (fieldInstance->mConstIdx != -1)
  2642. {
  2643. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  2644. BfIRValue newConstant = typeInstance->mConstHolder->CreateConst(typeCode, constant->mUInt64);
  2645. fieldInstance->mConstIdx = newConstant.mId;
  2646. }
  2647. }
  2648. }
  2649. underlyingType = GetPrimitiveType(typeCode);
  2650. auto fieldInstance = &typeInstance->mFieldInstances.back();
  2651. fieldInstance->mResolvedType = underlyingType;
  2652. fieldInstance->mDataSize = underlyingType->mSize;
  2653. typeInstance->mTypeInfoEx->mUnderlyingType = underlyingType;
  2654. typeInstance->mSize = underlyingType->mSize;
  2655. typeInstance->mAlign = underlyingType->mAlign;
  2656. typeInstance->mInstSize = underlyingType->mSize;
  2657. typeInstance->mInstAlign = underlyingType->mAlign;
  2658. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags & ~BfTypeRebuildFlag_UnderlyingTypeDeferred);
  2659. }
  2660. }
  2661. else
  2662. {
  2663. BF_ASSERT(!underlyingTypeDeferred);
  2664. }
  2665. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  2666. {
  2667. int lastTagId = -1;
  2668. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  2669. {
  2670. auto fieldInstance = &fieldInstanceRef;
  2671. auto fieldDef = fieldInstance->GetFieldDef();
  2672. if ((fieldDef != NULL) && (fieldInstance->mDataIdx < 0))
  2673. lastTagId = -fieldInstance->mDataIdx - 1;
  2674. }
  2675. auto fieldInstance = &typeInstance->mFieldInstances.back();
  2676. BF_ASSERT(fieldInstance->mResolvedType == NULL);
  2677. BfPrimitiveType* discriminatorType;
  2678. if (lastTagId > 0x7FFFFFFF) // HOW?
  2679. discriminatorType = GetPrimitiveType(BfTypeCode_Int64);
  2680. else if (lastTagId > 0x7FFF)
  2681. discriminatorType = GetPrimitiveType(BfTypeCode_Int32);
  2682. else if (lastTagId > 0x7F)
  2683. discriminatorType = GetPrimitiveType(BfTypeCode_Int16);
  2684. else
  2685. discriminatorType = GetPrimitiveType(BfTypeCode_Int8);
  2686. fieldInstance->mResolvedType = discriminatorType;
  2687. fieldInstance->mDataOffset = unionInnerType->mSize;
  2688. fieldInstance->mDataIdx = 2; // 0 = base, 1 = payload, 2 = discriminator
  2689. if (!isPacked)
  2690. {
  2691. if ((fieldInstance->mDataOffset % discriminatorType->mAlign) != 0)
  2692. {
  2693. fieldInstance->mDataOffset = BF_ALIGN(fieldInstance->mDataOffset, discriminatorType->mAlign);
  2694. fieldInstance->mDataIdx++; // Add room for explicit padding
  2695. }
  2696. }
  2697. typeInstance->mAlign = BF_MAX(unionInnerType->mAlign, discriminatorType->mAlign);
  2698. typeInstance->mSize = fieldInstance->mDataOffset + discriminatorType->mSize;
  2699. typeInstance->mInstSize = typeInstance->mSize;
  2700. typeInstance->mInstAlign = typeInstance->mAlign;
  2701. dataMemberHashCtx.Mixin(unionInnerType->mTypeId);
  2702. dataMemberHashCtx.Mixin(discriminatorType->mTypeId);
  2703. typeInstance->mMergedFieldDataCount = 1; // Track it as a single entry
  2704. }
  2705. if (!typeInstance->IsBoxed())
  2706. {
  2707. if (typeInstance->IsTypedPrimitive())
  2708. {
  2709. auto underlyingType = typeInstance->GetUnderlyingType();
  2710. dataMemberHashCtx.Mixin(underlyingType->mTypeId);
  2711. }
  2712. Val128 dataMemberHash = dataMemberHashCtx.Finish128();
  2713. if (typeInstance->mHotTypeData != NULL)
  2714. {
  2715. auto newHotTypeVersion = typeInstance->mHotTypeData->GetLatestVersion();
  2716. newHotTypeVersion->mDataHash = dataMemberHash;
  2717. if (mCompiler->mHotState != NULL)
  2718. {
  2719. auto committedHotTypeVersion = typeInstance->mHotTypeData->GetTypeVersion(mCompiler->mHotState->mCommittedHotCompileIdx);
  2720. if (committedHotTypeVersion != NULL)
  2721. {
  2722. if ((newHotTypeVersion->mDataHash != committedHotTypeVersion->mDataHash) && (typeInstance->mIsReified))
  2723. {
  2724. BfLogSysM("Hot compile detected data changes in %p '%s'\n", resolvedTypeRef, TypeToString(typeInstance).c_str());
  2725. if (!typeInstance->mHotTypeData->mPendingDataChange)
  2726. {
  2727. mCompiler->mHotState->mPendingDataChanges.Add(typeInstance->mTypeId);
  2728. typeInstance->mHotTypeData->mPendingDataChange = true;
  2729. }
  2730. else
  2731. {
  2732. BF_ASSERT(mCompiler->mHotState->mPendingDataChanges.Contains(typeInstance->mTypeId));
  2733. }
  2734. bool baseHadChanges = (typeInstance->mBaseType != NULL) && (typeInstance->mBaseType->mHotTypeData != NULL) && (typeInstance->mBaseType->mHotTypeData->mPendingDataChange);
  2735. if (!baseHadChanges)
  2736. Warn(0, StrFormat("Hot compile detected data changes in '%s'", TypeToString(typeInstance).c_str()), typeDef->GetRefNode());
  2737. }
  2738. else if (typeInstance->mHotTypeData->mPendingDataChange)
  2739. {
  2740. BfLogSysM("Hot compile removed pending data change for %p '%s'\n", resolvedTypeRef, TypeToString(typeInstance).c_str());
  2741. mCompiler->mHotState->RemovePendingChanges(typeInstance);
  2742. }
  2743. }
  2744. }
  2745. }
  2746. }
  2747. if (typeInstance == mContext->mBfObjectType)
  2748. typeInstance->mHasBeenInstantiated = true;
  2749. if (populateType == BfPopulateType_Data)
  2750. return true;
  2751. disableYield.Release();
  2752. if (canDoMethodProcessing)
  2753. {
  2754. if (typeInstance->mNeedsMethodProcessing) // May have been handled by GetRawMethodInstanceAtIdx above
  2755. DoTypeInstanceMethodProcessing(typeInstance);
  2756. }
  2757. return true;
  2758. }
  2759. void BfModule::DoTypeInstanceMethodProcessing(BfTypeInstance* typeInstance)
  2760. {
  2761. if (typeInstance->IsSpecializedByAutoCompleteMethod())
  2762. return;
  2763. BF_ASSERT(typeInstance->mModule == this);
  2764. //TODO: This is new, make sure this is in the right place
  2765. /*if (mAwaitingInitFinish)
  2766. FinishInit();*/
  2767. AutoDisallowYield disableYield(mSystem);
  2768. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  2769. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  2770. BfLogSysM("DoTypeInstanceMethodProcessing: %p %s Revision:%d\n", typeInstance, TypeToString(typeInstance).c_str(), typeInstance->mRevision);
  2771. auto typeDef = typeInstance->mTypeDef;
  2772. // Generate all methods. Pass 0
  2773. for (auto methodDef : typeDef->mMethods)
  2774. {
  2775. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  2776. // This should still be set to the default value
  2777. BF_ASSERT((methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet) || (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude));
  2778. }
  2779. if (typeInstance == mContext->mBfObjectType)
  2780. {
  2781. BF_ASSERT(typeInstance->mInterfaceMethodTable.size() == 0);
  2782. }
  2783. int newIntefaceStartIdx = 0;
  2784. auto implBaseType = typeInstance->GetImplBaseType();
  2785. if (implBaseType != NULL)
  2786. {
  2787. auto baseTypeInst = implBaseType->ToTypeInstance();
  2788. if (implBaseType->IsIncomplete())
  2789. PopulateType(implBaseType, BfPopulateType_Full_Force);
  2790. typeInstance->mInterfaceMethodTable = baseTypeInst->mInterfaceMethodTable;
  2791. typeInstance->mVirtualMethodTable = implBaseType->mVirtualMethodTable;
  2792. typeInstance->mVirtualMethodTableSize = implBaseType->mVirtualMethodTableSize;
  2793. if ((!mCompiler->IsHotCompile()) && (!mCompiler->mPassInstance->HasFailed()) && ((mCompiler->mResolvePassData == NULL) || (mCompiler->mResolvePassData->mAutoComplete == NULL)))
  2794. {
  2795. BF_ASSERT(typeInstance->mVirtualMethodTable.size() == typeInstance->mVirtualMethodTableSize);
  2796. }
  2797. else
  2798. {
  2799. BF_ASSERT(typeInstance->mVirtualMethodTableSize >= (int)typeInstance->mVirtualMethodTable.size());
  2800. }
  2801. }
  2802. // Add new interfaces
  2803. for (int iFaceIdx = 0; iFaceIdx < (int)typeInstance->mInterfaces.size(); iFaceIdx++)
  2804. {
  2805. BfTypeInterfaceEntry& typeInterfaceInst = typeInstance->mInterfaces[iFaceIdx];
  2806. auto checkInterface = typeInterfaceInst.mInterfaceType;
  2807. if (checkInterface->IsIncomplete())
  2808. PopulateType(checkInterface, BfPopulateType_Full_Force);
  2809. typeInterfaceInst.mStartInterfaceTableIdx = (int)typeInstance->mInterfaceMethodTable.size();
  2810. // We don't add to the vtable for interface declarations, we just reference the listed interfaces
  2811. if (!typeInstance->IsInterface())
  2812. {
  2813. auto interfaceTypeDef = checkInterface->mTypeDef;
  2814. BF_ASSERT(interfaceTypeDef->mMethods.size() == checkInterface->mMethodInstanceGroups.size());
  2815. // Reserve empty entries
  2816. for (int methodIdx = 0; methodIdx < (int)interfaceTypeDef->mMethods.size(); methodIdx++)
  2817. typeInstance->mInterfaceMethodTable.push_back(BfTypeInterfaceMethodEntry());
  2818. }
  2819. }
  2820. auto checkTypeInstance = typeInstance;
  2821. while (checkTypeInstance != NULL)
  2822. {
  2823. for (auto&& interfaceEntry : checkTypeInstance->mInterfaces)
  2824. {
  2825. AddDependency(interfaceEntry.mInterfaceType, typeInstance, BfDependencyMap::DependencyFlag_ImplementsInterface);
  2826. }
  2827. checkTypeInstance = checkTypeInstance->GetImplBaseType();
  2828. }
  2829. //for (auto& intefaceInst : typeInstance->mInterfaces)
  2830. if (typeInstance == mContext->mBfObjectType)
  2831. {
  2832. BF_ASSERT(typeInstance->mInterfaceMethodTable.size() == 1);
  2833. }
  2834. if (typeInstance->mTypeDef == mCompiler->mPointerTypeDef)
  2835. {
  2836. NOP;
  2837. }
  2838. // Slot interfaces method blocks in vtable
  2839. {
  2840. int ifaceVirtIdx = 0;
  2841. std::unordered_map<BfTypeInstance*, BfTypeInterfaceEntry*> interfaceMap;
  2842. BfTypeInstance* checkType = typeInstance->GetImplBaseType();
  2843. while (checkType != NULL)
  2844. {
  2845. for (auto&& ifaceEntry : checkType->mInterfaces)
  2846. {
  2847. interfaceMap[ifaceEntry.mInterfaceType] = &ifaceEntry;
  2848. ifaceVirtIdx = std::max(ifaceVirtIdx, ifaceEntry.mStartVirtualIdx + ifaceEntry.mInterfaceType->mVirtualMethodTableSize);
  2849. }
  2850. checkType = checkType->GetImplBaseType();
  2851. }
  2852. for (int iFaceIdx = 0; iFaceIdx < (int)typeInstance->mInterfaces.size(); iFaceIdx++)
  2853. {
  2854. BfTypeInterfaceEntry& typeInterfaceInst = typeInstance->mInterfaces[iFaceIdx];
  2855. auto itr = interfaceMap.find(typeInterfaceInst.mInterfaceType);
  2856. if (itr != interfaceMap.end())
  2857. {
  2858. auto prevEntry = itr->second;
  2859. typeInterfaceInst.mStartVirtualIdx = prevEntry->mStartVirtualIdx;
  2860. }
  2861. else
  2862. {
  2863. typeInterfaceInst.mStartVirtualIdx = ifaceVirtIdx;
  2864. ifaceVirtIdx += typeInterfaceInst.mInterfaceType->mVirtualMethodTableSize;
  2865. interfaceMap[typeInterfaceInst.mInterfaceType] = &typeInterfaceInst;
  2866. }
  2867. }
  2868. }
  2869. auto isBoxed = typeInstance->IsBoxed();
  2870. typeInstance->mNeedsMethodProcessing = false;
  2871. typeInstance->mTypeIncomplete = false;
  2872. auto checkBaseType = typeInstance->GetImplBaseType();
  2873. while (checkBaseType != NULL)
  2874. {
  2875. PopulateType(checkBaseType, BfPopulateType_Full_Force);
  2876. BF_ASSERT((!checkBaseType->IsIncomplete()) || (checkBaseType->mTypeFailed));
  2877. checkBaseType = checkBaseType->GetImplBaseType();
  2878. }
  2879. if ((mCompiler->mOptions.mHasVDataExtender) && (!typeInstance->IsInterface()))
  2880. {
  2881. // This is the vExt entry for this type instance
  2882. BfVirtualMethodEntry entry;
  2883. entry.mDeclaringMethod.mMethodNum = -1;
  2884. entry.mDeclaringMethod.mTypeInstance = typeInstance;
  2885. typeInstance->mVirtualMethodTable.push_back(entry);
  2886. typeInstance->mVirtualMethodTableSize++;
  2887. }
  2888. // Fill out to correct size
  2889. if (typeInstance->mHotTypeData != NULL)
  2890. {
  2891. //auto hotLatestVersionHead = typeInstance->mHotTypeData->GetLatestVersionHead();
  2892. int wantVTableSize = typeInstance->GetBaseVTableSize() + (int)typeInstance->mHotTypeData->mVTableEntries.size();
  2893. while ((int)typeInstance->mVirtualMethodTable.size() < wantVTableSize)
  2894. {
  2895. typeInstance->mVirtualMethodTable.push_back(BfVirtualMethodEntry());
  2896. typeInstance->mVirtualMethodTableSize++;
  2897. }
  2898. }
  2899. BfAmbiguityContext ambiguityContext;
  2900. ambiguityContext.mTypeInstance = typeInstance;
  2901. ambiguityContext.mModule = this;
  2902. ambiguityContext.mIsProjectSpecific = false;
  2903. bool wantsOnDemandMethods = false;
  2904. //TODO: Testing having interface methods be "on demand"...
  2905. //if (!typeInstance->IsInterface())
  2906. //
  2907. {
  2908. if (typeInstance->IsSpecializedType())
  2909. wantsOnDemandMethods = true;
  2910. else if ((mCompiler->mOptions.mCompileOnDemandKind != BfCompileOnDemandKind_AlwaysInclude) &&
  2911. (!typeInstance->IsUnspecializedTypeVariation()))
  2912. {
  2913. //if (typeDef->mName->ToString() != "AttributeUsageAttribute")
  2914. auto attributeDef = mCompiler->mAttributeTypeDef;
  2915. auto attributeType = mContext->mUnreifiedModule->ResolveTypeDef(attributeDef, BfPopulateType_Identity)->ToTypeInstance();
  2916. if (!TypeIsSubTypeOf(mCurTypeInstance, attributeType, false))
  2917. {
  2918. wantsOnDemandMethods = true;
  2919. }
  2920. }
  2921. }
  2922. //bool allDeclsRequired = (mIsReified) && (mCompiler->mOptions.mEmitDebugInfo) && ();
  2923. bool allDeclsRequired = false;
  2924. //if ((mIsReified) && (mCompiler->mOptions.mEmitDebugInfo) && (!mCompiler->mWantsDeferMethodDecls))
  2925. // if ((mIsReified) && (mCompiler->mOptions.mEmitDebugInfo))
  2926. // {
  2927. // allDeclsRequired = true;
  2928. // }
  2929. HashSet<String> ifaceMethodNameSet;
  2930. if (wantsOnDemandMethods)
  2931. {
  2932. for (int iFaceIdx = newIntefaceStartIdx; iFaceIdx < (int)typeInstance->mInterfaces.size(); iFaceIdx++)
  2933. {
  2934. BfTypeInterfaceEntry& typeInterfaceInst = typeInstance->mInterfaces[iFaceIdx];
  2935. for (auto checkMethodDef : typeInterfaceInst.mInterfaceType->mTypeDef->mMethods)
  2936. {
  2937. ifaceMethodNameSet.Add(checkMethodDef->mName);
  2938. }
  2939. }
  2940. }
  2941. // Generate all methods. Pass 1
  2942. for (auto methodDef : typeDef->mMethods)
  2943. {
  2944. if (methodDef->mMethodType == BfMethodType_CtorClear)
  2945. {
  2946. NOP;
  2947. }
  2948. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  2949. if (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude)
  2950. continue;
  2951. // This should still be set to the default value
  2952. BF_ASSERT(methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet);
  2953. if ((isBoxed) && (!methodDef->mIsVirtual))
  2954. {
  2955. if (methodDef->mIsStatic)
  2956. continue;
  2957. bool boxedRequired = false;
  2958. if (((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mParams.size() == 0)) ||
  2959. (methodDef->mMethodType == BfMethodType_Dtor) ||
  2960. ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) || (methodDef->mName == BF_METHODNAME_INVOKE) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST)) ||
  2961. (methodDef->mGenericParams.size() != 0))
  2962. boxedRequired = true;
  2963. if (!boxedRequired)
  2964. {
  2965. if (wantsOnDemandMethods)
  2966. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  2967. continue;
  2968. }
  2969. }
  2970. if (methodDef->mMethodType == BfMethodType_Ignore)
  2971. continue;
  2972. if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) && (typeInstance->IsValueType()))
  2973. continue; // This is just a placeholder for boxed types
  2974. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  2975. if (wantsOnDemandMethods)
  2976. {
  2977. bool implRequired = false;
  2978. bool declRequired = false;
  2979. if ((!typeInstance->IsGenericTypeInstance()) && (methodDef->mGenericParams.IsEmpty()))
  2980. {
  2981. // For non-generic methods, declare all methods. This is useful for debug info.
  2982. declRequired = true;
  2983. }
  2984. if (methodDef->mMethodType == BfMethodType_CtorNoBody)
  2985. declRequired = true;
  2986. if ((methodDef->mIsStatic) &&
  2987. ((methodDef->mMethodType == BfMethodType_Dtor) || (methodDef->mMethodType == BfMethodType_Ctor)))
  2988. {
  2989. implRequired = true;
  2990. }
  2991. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  2992. {
  2993. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  2994. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS) ||
  2995. ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) && (typeInstance->IsObject())))
  2996. implRequired = true;
  2997. }
  2998. BfAttributeDirective* attributes = NULL;
  2999. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  3000. attributes = methodDeclaration->mAttributes;
  3001. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  3002. attributes = propertyDeclaration->mAttributes;
  3003. while (attributes != NULL)
  3004. {
  3005. if (attributes->mAttributeTypeRef != NULL)
  3006. {
  3007. auto typeRefName = attributes->mAttributeTypeRef->ToString();
  3008. if (typeRefName == "AlwaysInclude")
  3009. implRequired = true;
  3010. else if (typeRefName == "Export")
  3011. implRequired = true;
  3012. else if (typeRefName == "Test")
  3013. implRequired = true;
  3014. else
  3015. declRequired = true; // We need to create so we can check for AlwaysInclude in included attributes
  3016. }
  3017. attributes = attributes->mNextAttribute;
  3018. }
  3019. if ((mProject != NULL) && (mProject->mAlwaysIncludeAll) && (methodDef->mBody != NULL))
  3020. {
  3021. implRequired = true;
  3022. declRequired = true;
  3023. }
  3024. if (typeInstance->IsInterface())
  3025. declRequired = true;
  3026. if (methodDef->mIsVirtual)
  3027. declRequired = true;
  3028. if (!implRequired)
  3029. {
  3030. // Any interface with the same name causes us to not be on-demand
  3031. if (ifaceMethodNameSet.Contains(methodDef->mName))
  3032. declRequired = true;
  3033. }
  3034. // Is this strictly necessary? It will reduce our compilation speed in order to ensure methods are available for debug info
  3035. if (allDeclsRequired)
  3036. declRequired = true;
  3037. if (methodDef->mMethodDeclaration == NULL)
  3038. {
  3039. // Internal methods don't need decls
  3040. if (methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS)
  3041. declRequired = false;
  3042. }
  3043. if (!implRequired)
  3044. {
  3045. if (!mIsScratchModule)
  3046. mOnDemandMethodCount++;
  3047. if (!declRequired)
  3048. {
  3049. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  3050. continue;
  3051. }
  3052. else
  3053. {
  3054. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  3055. }
  3056. }
  3057. }
  3058. }
  3059. BfLogSysM("Starting DoTypeInstanceMethodProcessing %p GetMethodInstance pass. OnDemandMethods: %d\n", typeInstance, mOnDemandMethodCount);
  3060. // Pass 2
  3061. for (auto methodDef : typeDef->mMethods)
  3062. {
  3063. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  3064. if ((methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  3065. (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Decl_AwaitingDecl))
  3066. {
  3067. BfLogSysM("Skipping GetMethodInstance on MethodDef: %p OnDemandKind: %d\n", methodDef, methodInstanceGroup->mOnDemandKind);
  3068. continue;
  3069. }
  3070. int prevWorklistSize = (int)mContext->mMethodWorkList.size();
  3071. auto moduleMethodInstance = GetMethodInstance(typeInstance, methodDef, BfTypeVector(), ((methodDef->mGenericParams.size() != 0) || (typeInstance->IsUnspecializedType())) ? BfGetMethodInstanceFlag_UnspecializedPass : BfGetMethodInstanceFlag_None);
  3072. auto methodInstance = moduleMethodInstance.mMethodInstance;
  3073. if (methodInstance == NULL)
  3074. {
  3075. BF_ASSERT(typeInstance->IsGenericTypeInstance() && (typeInstance->mTypeDef->mIsCombinedPartial));
  3076. continue;
  3077. }
  3078. if ((!mCompiler->mIsResolveOnly) &&
  3079. ((methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) || (!typeInstance->IsReified())))
  3080. {
  3081. bool forceMethodImpl = false;
  3082. BfCustomAttributes* customAttributes = methodInstance->GetCustomAttributes();
  3083. if ((customAttributes != NULL) && (typeInstance->IsReified()))
  3084. {
  3085. for (auto& attr : customAttributes->mAttributes)
  3086. {
  3087. auto attrTypeInst = attr.mType->ToTypeInstance();
  3088. auto attrCustomAttributes = attrTypeInst->mCustomAttributes;
  3089. if (attrCustomAttributes == NULL)
  3090. continue;
  3091. for (auto& attrAttr : attrCustomAttributes->mAttributes)
  3092. {
  3093. if (attrAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  3094. {
  3095. // Check for Flags arg
  3096. if (attrAttr.mCtorArgs.size() < 2)
  3097. continue;
  3098. auto constant = attrTypeInst->mConstHolder->GetConstant(attrAttr.mCtorArgs[1]);
  3099. if (constant == NULL)
  3100. continue;
  3101. if (constant->mTypeCode == BfTypeCode_Boolean)
  3102. continue;
  3103. if ((constant->mInt8 & BfCustomAttributeFlags_AlwaysIncludeTarget) != 0)
  3104. forceMethodImpl = true;
  3105. }
  3106. }
  3107. }
  3108. }
  3109. if (typeInstance->mTypeDef->mProject->mTargetType == BfTargetType_BeefTest)
  3110. {
  3111. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mTestAttributeTypeDef)))
  3112. {
  3113. forceMethodImpl = true;
  3114. }
  3115. }
  3116. if (forceMethodImpl)
  3117. {
  3118. if (!typeInstance->IsReified())
  3119. mContext->mScratchModule->PopulateType(typeInstance, BfPopulateType_Data);
  3120. // Reify method
  3121. mContext->mScratchModule->GetMethodInstance(typeInstance, methodDef, BfTypeVector());
  3122. BF_ASSERT(methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Decl_AwaitingReference);
  3123. }
  3124. }
  3125. bool methodUsedVirtually = false;
  3126. if (typeInstance->IsInterface())
  3127. {
  3128. if ((!methodDef->mIsConcrete) && (!methodDef->mIsStatic) && (!methodInstance->HasSelf()))
  3129. SlotInterfaceMethod(methodInstance);
  3130. }
  3131. else if (!methodDef->IsEmptyPartial())
  3132. {
  3133. methodUsedVirtually = SlotVirtualMethod(methodInstance, &ambiguityContext);
  3134. }
  3135. // This is important for reducing latency of autocomplete popup, but it's important we don't allow the autocomplete
  3136. // thread to cause any reentry issues by re-populating a type at an "inopportune time". We do allow certain
  3137. // reentries in PopulateType, but not when we're resolving fields (for example)
  3138. if ((mContext->mFieldResolveReentrys.size() == 0) && (!mContext->mResolvingVarField))
  3139. {
  3140. disableYield.Release();
  3141. mSystem->CheckLockYield();
  3142. disableYield.Acquire();
  3143. }
  3144. }
  3145. BF_ASSERT(typeInstance->mVirtualMethodTable.size() == typeInstance->mVirtualMethodTableSize);
  3146. if ((isBoxed) && (!typeInstance->IsUnspecializedTypeVariation()))
  3147. {
  3148. // Any interface method that can be called virtually via an interface pointer needs to go into the boxed type
  3149. auto underlyingType = typeInstance->GetUnderlyingType();
  3150. BfTypeInstance* underlyingTypeInstance;
  3151. if (underlyingType->IsPrimitiveType())
  3152. underlyingTypeInstance = GetPrimitiveStructType(((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode);
  3153. else
  3154. underlyingTypeInstance = underlyingType->ToTypeInstance();
  3155. if (underlyingTypeInstance != NULL)
  3156. {
  3157. PopulateType(underlyingTypeInstance, BfPopulateType_Full_Force);
  3158. for (int ifaceIdx = 0; ifaceIdx < (int)underlyingTypeInstance->mInterfaces.size(); ifaceIdx++)
  3159. {
  3160. auto& underlyingIFaceTypeInst = underlyingTypeInstance->mInterfaces[ifaceIdx];
  3161. auto& boxedIFaceTypeInst = typeInstance->mInterfaces[ifaceIdx];
  3162. BF_ASSERT(underlyingIFaceTypeInst.mInterfaceType == boxedIFaceTypeInst.mInterfaceType);
  3163. auto ifaceInst = underlyingIFaceTypeInst.mInterfaceType;
  3164. int startIdx = underlyingIFaceTypeInst.mStartInterfaceTableIdx;
  3165. int boxedStartIdx = boxedIFaceTypeInst.mStartInterfaceTableIdx;
  3166. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  3167. for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  3168. {
  3169. auto matchedMethodRef = &underlyingTypeInstance->mInterfaceMethodTable[iMethodIdx + startIdx].mMethodRef;
  3170. auto boxedMatchedMethodRef = &typeInstance->mInterfaceMethodTable[iMethodIdx + boxedStartIdx].mMethodRef;
  3171. BfMethodInstance* matchedMethod = *matchedMethodRef;
  3172. auto ifaceMethodInst = ifaceInst->mMethodInstanceGroups[iMethodIdx].mDefault;
  3173. if (ifaceMethodInst->mVirtualTableIdx != -1)
  3174. {
  3175. if (matchedMethod == NULL)
  3176. {
  3177. AssertErrorState();
  3178. }
  3179. else
  3180. {
  3181. if (!matchedMethod->mIsForeignMethodDef)
  3182. {
  3183. BfMethodInstanceGroup* boxedMethodInstanceGroup = &typeInstance->mMethodInstanceGroups[matchedMethod->mMethodDef->mIdx];
  3184. if (boxedMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  3185. {
  3186. boxedMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  3187. if (!mIsScratchModule)
  3188. mOnDemandMethodCount++;
  3189. }
  3190. }
  3191. auto moduleMethodInstance = GetMethodInstance(typeInstance, matchedMethod->mMethodDef, BfTypeVector(),
  3192. matchedMethod->mIsForeignMethodDef ? BfGetMethodInstanceFlag_ForeignMethodDef : BfGetMethodInstanceFlag_None,
  3193. matchedMethod->GetForeignType());
  3194. auto methodInstance = moduleMethodInstance.mMethodInstance;
  3195. UniqueSlotVirtualMethod(methodInstance);
  3196. *boxedMatchedMethodRef = methodInstance;
  3197. }
  3198. }
  3199. }
  3200. }
  3201. }
  3202. }
  3203. if (typeInstance->mHotTypeData != NULL)
  3204. {
  3205. auto latestVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3206. auto latestVersionHead = typeInstance->mHotTypeData->GetLatestVersionHead();
  3207. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  3208. {
  3209. bool hasSlotError = false;
  3210. BF_ASSERT(mCompiler->IsHotCompile());
  3211. //typeInstance->mHotTypeData->mDirty = true;
  3212. //Val128 vtHash;
  3213. Array<int> ifaceMapping;
  3214. ifaceMapping.Resize(latestVersionHead->mInterfaceMapping.size());
  3215. typeInstance->CalcHotVirtualData(&ifaceMapping);
  3216. // Hot swapping allows for interfaces to be added to types or removed from types, but it doesn't allow
  3217. // interfaces to be added when the slot number has already been used -- even if the interface using
  3218. // that slot has been removed.
  3219. for (int slotIdx = 0; slotIdx < (int)ifaceMapping.size(); slotIdx++)
  3220. {
  3221. int newId = ifaceMapping[slotIdx];
  3222. int oldId = 0;
  3223. if (slotIdx < (int)latestVersionHead->mInterfaceMapping.size())
  3224. oldId = latestVersionHead->mInterfaceMapping[slotIdx];
  3225. if ((newId != oldId) && (newId != 0) && (oldId != 0))
  3226. {
  3227. String interfaceName;
  3228. for (auto iface : typeInstance->mInterfaces)
  3229. {
  3230. if (iface.mInterfaceType->mTypeId == newId)
  3231. interfaceName = TypeToString(iface.mInterfaceType);
  3232. }
  3233. Warn(0, StrFormat("Hot swap detected resolvable interface slot collision with '%s'.", interfaceName.c_str()), typeDef->mTypeDeclaration);
  3234. BF_ASSERT(latestVersion != latestVersionHead);
  3235. if (!hasSlotError)
  3236. {
  3237. latestVersion->mInterfaceMapping = ifaceMapping;
  3238. }
  3239. hasSlotError = true;
  3240. }
  3241. else if (hasSlotError)
  3242. {
  3243. if (oldId != 0)
  3244. latestVersion->mInterfaceMapping[slotIdx] = oldId;
  3245. }
  3246. if (oldId != 0)
  3247. ifaceMapping[slotIdx] = oldId;
  3248. }
  3249. latestVersionHead->mInterfaceMapping = ifaceMapping;
  3250. if (hasSlotError)
  3251. mCompiler->mHotState->mPendingFailedSlottings.Add(typeInstance->mTypeId);
  3252. else
  3253. mCompiler->mHotState->mPendingFailedSlottings.Remove(typeInstance->mTypeId);
  3254. }
  3255. }
  3256. if ((typeInstance->IsInterface()) && (!typeInstance->IsUnspecializedType()) && (typeInstance->mIsReified) && (typeInstance->mSlotNum == -1) && (mCompiler->IsHotCompile()))
  3257. {
  3258. mCompiler->mHotState->mHasNewInterfaceTypes = true;
  3259. }
  3260. if ((!typeInstance->IsInterface()) && (!typeInstance->IsUnspecializedTypeVariation()) && (!isBoxed))
  3261. {
  3262. if (!typeInstance->mTypeDef->mIsAbstract)
  3263. {
  3264. for (int methodIdx = 0; methodIdx < (int) typeInstance->mVirtualMethodTable.size(); methodIdx++)
  3265. {
  3266. auto& methodRef = typeInstance->mVirtualMethodTable[methodIdx].mImplementingMethod;
  3267. if (methodRef.mMethodNum == -1)
  3268. {
  3269. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  3270. if (methodRef.mTypeInstance == typeInstance)
  3271. {
  3272. if (typeInstance->GetImplBaseType() != NULL)
  3273. BF_ASSERT(methodIdx == (int)typeInstance->GetImplBaseType()->mVirtualMethodTableSize);
  3274. }
  3275. continue;
  3276. }
  3277. auto methodInstance = (BfMethodInstance*)methodRef;
  3278. if ((methodInstance != NULL) && (methodInstance->mMethodDef->mIsAbstract))
  3279. {
  3280. if (methodInstance->mMethodDef->mIsAbstract)
  3281. {
  3282. if (!typeInstance->IsUnspecializedTypeVariation())
  3283. {
  3284. if (Fail(StrFormat("'%s' does not implement inherited abstract method '%s'", TypeToString(typeInstance).c_str(), MethodToString(methodInstance).c_str()), typeDef->mTypeDeclaration->mNameNode, true) != NULL)
  3285. mCompiler->mPassInstance->MoreInfo("Abstract method declared", methodInstance->mMethodDef->GetRefNode());
  3286. }
  3287. }
  3288. else
  3289. {
  3290. if (!typeInstance->IsUnspecializedType())
  3291. AssertErrorState();
  3292. }
  3293. }
  3294. }
  3295. }
  3296. std::unordered_set<String> missingIFaceMethodNames;
  3297. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  3298. {
  3299. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  3300. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  3301. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  3302. auto declTypeDef = ifaceTypeInst.mDeclaringType;
  3303. for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  3304. {
  3305. auto matchedMethodRef = &typeInstance->mInterfaceMethodTable[iMethodIdx + startIdx].mMethodRef;
  3306. BfMethodInstance* matchedMethod = *matchedMethodRef;
  3307. auto ifaceMethodInst = ifaceInst->mMethodInstanceGroups[iMethodIdx].mDefault;
  3308. if ((matchedMethod == NULL) && (ifaceMethodInst != NULL))
  3309. {
  3310. missingIFaceMethodNames.insert(ifaceMethodInst->mMethodDef->mName);
  3311. }
  3312. }
  3313. }
  3314. if (!missingIFaceMethodNames.empty())
  3315. {
  3316. // Attempt to find matching entries in base types
  3317. ambiguityContext.mIsReslotting = true;
  3318. auto checkType = typeInstance->GetImplBaseType();
  3319. while (checkType != NULL)
  3320. {
  3321. for (auto& methodGroup : checkType->mMethodInstanceGroups)
  3322. {
  3323. auto methodInstance = methodGroup.mDefault;
  3324. if (methodInstance != NULL)
  3325. {
  3326. if ((methodInstance->mMethodDef->mProtection != BfProtection_Private) &&
  3327. (!methodInstance->mMethodDef->mIsOverride) &&
  3328. (missingIFaceMethodNames.find(methodInstance->mMethodDef->mName) != missingIFaceMethodNames.end()))
  3329. {
  3330. SlotVirtualMethod(methodInstance, &ambiguityContext);
  3331. }
  3332. }
  3333. }
  3334. checkType = checkType->GetImplBaseType();
  3335. }
  3336. }
  3337. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  3338. {
  3339. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  3340. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  3341. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  3342. auto declTypeDef = ifaceTypeInst.mDeclaringType;
  3343. for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  3344. {
  3345. auto matchedMethodRef = &typeInstance->mInterfaceMethodTable[iMethodIdx + startIdx].mMethodRef;
  3346. BfMethodInstance* matchedMethod = *matchedMethodRef;
  3347. auto ifaceMethodInst = ifaceInst->mMethodInstanceGroups[iMethodIdx].mDefault;
  3348. if (ifaceMethodInst == NULL)
  3349. continue;
  3350. // Don't even try to match generics
  3351. if (!ifaceMethodInst->mMethodDef->mGenericParams.IsEmpty())
  3352. continue;
  3353. auto iReturnType = ifaceMethodInst->mReturnType;
  3354. if (iReturnType->IsSelf())
  3355. iReturnType = typeInstance;
  3356. if (ifaceMethodInst->mMethodDef->mIsOverride)
  3357. continue; // Don't consider overrides here
  3358. // If we have "ProjA depends on LibBase", "ProjB depends on LibBase", then a type ClassC in LibBase implementing IFaceD,
  3359. // where IFaceD gets extended with MethodE in ProjA, an implementing MethodE is still required to exist on ClassC --
  3360. // the visibility is bidirectional. A type ClassF implementing IFaceD inside ProjB will not be required to implement
  3361. // MethodE, however
  3362. if ((!ifaceInst->IsTypeMemberAccessible(ifaceMethodInst->mMethodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  3363. (!ifaceInst->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, ifaceMethodInst->mMethodDef->mDeclaringType)))
  3364. continue;
  3365. if (!ifaceInst->IsTypeMemberIncluded(ifaceMethodInst->mMethodDef->mDeclaringType, ifaceTypeInst.mDeclaringType))
  3366. continue;
  3367. bool hadMatch = matchedMethod != NULL;
  3368. bool hadPubFailure = false;
  3369. bool hadMutFailure = false;
  3370. if (hadMatch)
  3371. {
  3372. if ((matchedMethod->GetExplicitInterface() == NULL) && (matchedMethod->mMethodDef->mProtection != BfProtection_Public))
  3373. {
  3374. hadMatch = false;
  3375. hadPubFailure = true;
  3376. }
  3377. if (ifaceMethodInst->mVirtualTableIdx != -1)
  3378. {
  3379. if (matchedMethod->mReturnType != iReturnType)
  3380. hadMatch = false;
  3381. }
  3382. else
  3383. {
  3384. // Concrete
  3385. if (matchedMethod->mReturnType->IsInterface())
  3386. hadMatch = false;
  3387. else if (!CanImplicitlyCast(GetFakeTypedValue(matchedMethod->mReturnType), iReturnType))
  3388. hadMatch = false;
  3389. }
  3390. // If we have mExplicitInterface set then we already gave a mut error (if needed)
  3391. if ((typeInstance->IsValueType()) && (matchedMethod->GetExplicitInterface() == NULL) &&
  3392. (matchedMethod->mMethodDef->mIsMutating) && (!ifaceMethodInst->mMethodDef->mIsMutating))
  3393. {
  3394. hadMutFailure = true;
  3395. hadMatch = false;
  3396. }
  3397. }
  3398. if (!hadMatch)
  3399. {
  3400. if (!typeInstance->IsUnspecializedTypeVariation())
  3401. {
  3402. auto bestMethodInst = ifaceMethodInst;
  3403. auto bestInterface = ifaceInst;
  3404. if (matchedMethod == NULL)
  3405. {
  3406. bool searchFailed = false;
  3407. for (auto& checkIFaceTypeInst : typeInstance->mInterfaces)
  3408. {
  3409. auto checkIFaceInst = checkIFaceTypeInst.mInterfaceType;
  3410. int checkStartIdx = checkIFaceTypeInst.mStartInterfaceTableIdx;
  3411. int checkIMethodCount = (int)checkIFaceInst->mMethodInstanceGroups.size();
  3412. for (int checkIMethodIdx = 0; checkIMethodIdx < checkIMethodCount; checkIMethodIdx++)
  3413. {
  3414. auto checkIFaceMethodInst = checkIFaceInst->mMethodInstanceGroups[checkIMethodIdx].mDefault;
  3415. if ((checkIFaceMethodInst != NULL) && (checkIFaceMethodInst->mMethodDef->mIsOverride))
  3416. {
  3417. if (CompareMethodSignatures(checkIFaceMethodInst, ifaceMethodInst))
  3418. {
  3419. bool isBetter = TypeIsSubTypeOf(checkIFaceInst, bestInterface);
  3420. bool isWorse = TypeIsSubTypeOf(bestInterface, checkIFaceInst);
  3421. if (isBetter == isWorse)
  3422. {
  3423. CompareDeclTypes(checkIFaceMethodInst->mMethodDef->mDeclaringType, bestMethodInst->mMethodDef->mDeclaringType, isBetter, isWorse);
  3424. }
  3425. if ((isBetter) && (!isWorse))
  3426. {
  3427. bestInterface = checkIFaceInst;
  3428. bestMethodInst = checkIFaceMethodInst;
  3429. }
  3430. else if (isBetter == isWorse)
  3431. {
  3432. if (!searchFailed)
  3433. {
  3434. searchFailed = true;
  3435. auto error = Fail(StrFormat("There is no most-specific default implementation of '%s'", MethodToString(ifaceMethodInst).c_str()), declTypeDef->mTypeDeclaration->mNameNode);
  3436. if (error != NULL)
  3437. {
  3438. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  3439. MethodToString(bestMethodInst).c_str()), bestMethodInst->mMethodDef->GetRefNode());
  3440. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  3441. MethodToString(checkIFaceMethodInst).c_str()), checkIFaceMethodInst->mMethodDef->GetRefNode());
  3442. }
  3443. //candidate implementations include '%s' and '%s'",
  3444. //TypeToString(checkIFaceInst).c_str(), TypeToString(bestInterface).c_str()), );
  3445. }
  3446. }
  3447. }
  3448. }
  3449. }
  3450. }
  3451. if (bestMethodInst->mReturnType != ifaceMethodInst->mReturnType)
  3452. {
  3453. auto error = Fail(StrFormat("Default interface method '%s' cannot be used does not have the return type '%s'",
  3454. MethodToString(bestMethodInst).c_str(), TypeToString(ifaceMethodInst->mReturnType).c_str()), declTypeDef->mTypeDeclaration->mNameNode);
  3455. if (error != NULL)
  3456. {
  3457. mCompiler->mPassInstance->MoreInfo("See original method declaration", ifaceMethodInst->mMethodDef->GetRefNode());
  3458. mCompiler->mPassInstance->MoreInfo("See override method declaration", bestMethodInst->mMethodDef->GetRefNode());
  3459. }
  3460. }
  3461. }
  3462. if ((bestMethodInst->mMethodDef->HasBody()) && (bestMethodInst->mMethodDef->mGenericParams.size() == 0) && (matchedMethod == NULL))
  3463. {
  3464. auto methodDef = bestMethodInst->mMethodDef;
  3465. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  3466. if ((methodDef->mGenericParams.size() != 0) || (typeInstance->IsUnspecializedType()))
  3467. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_UnspecializedPass);
  3468. auto methodInst = GetMethodInstance(typeInstance, methodDef, BfTypeVector(), flags, ifaceInst);
  3469. if (methodInst)
  3470. {
  3471. *matchedMethodRef = methodInst.mMethodInstance;
  3472. BfMethodInstance* newMethodInstance = methodInst.mMethodInstance;
  3473. BF_ASSERT(newMethodInstance->mIsForeignMethodDef);
  3474. if (newMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  3475. mOnDemandMethodCount++;
  3476. continue;
  3477. }
  3478. }
  3479. if (typeInstance->IsBoxed())
  3480. {
  3481. if (ifaceMethodInst->mMethodDef->mIsStatic)
  3482. {
  3483. // Skip the statics, those can't be invoked
  3484. }
  3485. else
  3486. {
  3487. // The unboxed version should have had the same error
  3488. if (!typeInstance->GetUnderlyingType()->IsIncomplete())
  3489. AssertErrorState();
  3490. }
  3491. }
  3492. else
  3493. {
  3494. BfError* error = Fail(StrFormat("'%s' does not implement interface member '%s'", TypeToString(typeInstance).c_str(), MethodToString(ifaceMethodInst).c_str()), declTypeDef->mTypeDeclaration->mNameNode, true);
  3495. if ((matchedMethod != NULL) && (error != NULL))
  3496. {
  3497. if (hadPubFailure)
  3498. {
  3499. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because because it is not public",
  3500. MethodToString(matchedMethod).c_str()), matchedMethod->mMethodDef->mReturnTypeRef);
  3501. }
  3502. else if (ifaceMethodInst->mReturnType->IsConcreteInterfaceType())
  3503. {
  3504. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because because it does not have a concrete return type that implements '%s'",
  3505. MethodToString(matchedMethod).c_str(), TypeToString(ifaceMethodInst->mReturnType).c_str()), matchedMethod->mMethodDef->mReturnTypeRef);
  3506. }
  3507. else if (hadMutFailure)
  3508. {
  3509. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because because it is market as 'mut' but interface method does not allow it",
  3510. MethodToString(matchedMethod).c_str()), matchedMethod->mMethodDef->GetMutNode());
  3511. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), ifaceMethodInst->mMethodDef->mMethodDeclaration);
  3512. }
  3513. else
  3514. {
  3515. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because because it does not have the return type '%s'",
  3516. MethodToString(matchedMethod).c_str(), TypeToString(ifaceMethodInst->mReturnType).c_str()), matchedMethod->mMethodDef->mReturnTypeRef);
  3517. if ((ifaceMethodInst->mVirtualTableIdx != -1) && (ifaceMethodInst->mReturnType->IsInterface()))
  3518. mCompiler->mPassInstance->MoreInfo("Declare the interface method as 'concrete' to allow matching concrete return values", ifaceMethodInst->mMethodDef->GetMethodDeclaration()->mVirtualSpecifier);
  3519. }
  3520. }
  3521. }
  3522. }
  3523. // Clear out the entry
  3524. *matchedMethodRef = BfMethodRef();
  3525. }
  3526. }
  3527. }
  3528. }
  3529. ambiguityContext.Finish();
  3530. CheckAddFailType();
  3531. typeInstance->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  3532. mCompiler->mStats.mTypesPopulated++;
  3533. mCompiler->UpdateCompletion();
  3534. BfLogSysM("Finished DoTypeInstanceMethodProcessing %p. OnDemandMethods: %d Virtual Size: %d\n", typeInstance, mOnDemandMethodCount, typeInstance->mVirtualMethodTable.size());
  3535. }
  3536. void BfModule::RebuildMethods(BfTypeInstance* typeInstance)
  3537. {
  3538. if (typeInstance->IsIncomplete())
  3539. return;
  3540. typeInstance->mNeedsMethodProcessing = true;
  3541. typeInstance->mDefineState = BfTypeDefineState_Defined;
  3542. typeInstance->mTypeIncomplete = true;
  3543. for (auto& methodInstanceGroup : typeInstance->mMethodInstanceGroups)
  3544. {
  3545. delete methodInstanceGroup.mDefault;
  3546. methodInstanceGroup.mDefault = NULL;
  3547. delete methodInstanceGroup.mMethodSpecializationMap;
  3548. methodInstanceGroup.mMethodSpecializationMap = NULL;
  3549. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_NotSet;
  3550. }
  3551. BfTypeProcessRequest* typeProcessRequest = mContext->mPopulateTypeWorkList.Alloc();
  3552. typeProcessRequest->mType = typeInstance;
  3553. BF_ASSERT(typeInstance->mContext == mContext);
  3554. mCompiler->mStats.mTypesQueued++;
  3555. mCompiler->UpdateCompletion();
  3556. }
  3557. BfModule* BfModule::GetModuleFor(BfType* type)
  3558. {
  3559. auto typeInst = type->ToTypeInstance();
  3560. if (typeInst == NULL)
  3561. return NULL;
  3562. return typeInst->mModule;
  3563. }
  3564. void BfModule::AddMethodToWorkList(BfMethodInstance* methodInstance)
  3565. {
  3566. BF_ASSERT(!methodInstance->mMethodDef->mIsAbstract);
  3567. if (methodInstance->IsSpecializedByAutoCompleteMethod())
  3568. return;
  3569. BF_ASSERT(mCompiler->mCompileState != BfCompiler::CompileState_VData);
  3570. if ((methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized))
  3571. {
  3572. BF_ASSERT(mCompiler->mCompileState != BfCompiler::CompileState_Unreified);
  3573. }
  3574. if (methodInstance->mIsUnspecializedVariation)
  3575. {
  3576. return;
  3577. }
  3578. BF_ASSERT(methodInstance->mMethodProcessRequest == NULL);
  3579. auto defaultMethod = methodInstance->mMethodInstanceGroup->mDefault;
  3580. if (defaultMethod != methodInstance)
  3581. {
  3582. BF_ASSERT(defaultMethod != NULL);
  3583. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  3584. {
  3585. AddMethodToWorkList(defaultMethod);
  3586. }
  3587. }
  3588. if (methodInstance->mDeclModule != NULL)
  3589. {
  3590. if (methodInstance->mDeclModule != this)
  3591. {
  3592. methodInstance->mDeclModule->AddMethodToWorkList(methodInstance);
  3593. return;
  3594. }
  3595. }
  3596. else
  3597. {
  3598. auto module = GetOrCreateMethodModule(methodInstance);
  3599. methodInstance->mDeclModule = module;
  3600. BfIRValue func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  3601. methodInstance->mIRFunction = func;
  3602. module->mFuncReferences[methodInstance] = func;
  3603. module->AddMethodToWorkList(methodInstance);
  3604. return;
  3605. }
  3606. if ((!methodInstance->mIRFunction) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) &&
  3607. (methodInstance->GetImportCallKind() == BfImportCallKind_None))
  3608. {
  3609. if (!mIsModuleMutable)
  3610. PrepareForIRWriting(methodInstance->GetOwner());
  3611. BfIRValue func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  3612. methodInstance->mIRFunction = func;
  3613. mFuncReferences[methodInstance] = func;
  3614. }
  3615. BF_ASSERT(methodInstance->mDeclModule == this);
  3616. if (defaultMethod == methodInstance)
  3617. {
  3618. if (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude)
  3619. {
  3620. auto owningModule = methodInstance->GetOwner()->GetModule();
  3621. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced);
  3622. if (!mIsScratchModule)
  3623. {
  3624. if (owningModule->mParentModule != NULL)
  3625. BF_ASSERT(owningModule->mParentModule->mOnDemandMethodCount > 0);
  3626. else
  3627. BF_ASSERT(owningModule->mOnDemandMethodCount > 0);
  3628. }
  3629. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_InWorkList;
  3630. }
  3631. }
  3632. else
  3633. {
  3634. BF_ASSERT(defaultMethod->mMethodInstanceGroup->IsImplemented());
  3635. }
  3636. BF_ASSERT(methodInstance->mDeclModule != NULL);
  3637. auto typeInstance = methodInstance->GetOwner();
  3638. BfMethodProcessRequest* methodProcessRequest = mContext->mMethodWorkList.Alloc();
  3639. methodProcessRequest->mType = typeInstance;
  3640. methodProcessRequest->mMethodInstance = methodInstance;
  3641. methodProcessRequest->mRevision = typeInstance->mRevision;
  3642. methodProcessRequest->mFromModuleRebuildIdx = mRebuildIdx;
  3643. methodProcessRequest->mFromModule = this;
  3644. if ((!mCompiler->mIsResolveOnly) && (methodInstance->mIsReified))
  3645. BF_ASSERT(mIsModuleMutable || mReifyQueued);
  3646. BF_ASSERT(mBfIRBuilder != NULL);
  3647. if (methodInstance->mMethodDef->mName == "Hey")
  3648. {
  3649. NOP;
  3650. }
  3651. BfLogSysM("Adding to mMethodWorkList Module: %p IncompleteMethodCount: %d Type %p MethodInstance: %p Name:%s TypeRevision: %d ModuleRevision: %d ReqId:%d\n", this, mIncompleteMethodCount, typeInstance, methodInstance, methodInstance->mMethodDef->mName.c_str(), methodProcessRequest->mRevision, methodProcessRequest->mFromModuleRevision, methodProcessRequest->mReqId);
  3652. if (mAwaitingFinish)
  3653. {
  3654. BfLogSysM("Module: %p No longer awaiting finish\n", this);
  3655. mAwaitingFinish = false;
  3656. }
  3657. mCompiler->mStats.mMethodsQueued++;
  3658. mCompiler->UpdateCompletion();
  3659. mIncompleteMethodCount++;
  3660. if (methodInstance->GetNumGenericArguments() != 0)
  3661. mHasGenericMethods = true;
  3662. methodInstance->mMethodProcessRequest = methodProcessRequest;
  3663. }
  3664. BfArrayType* BfModule::CreateArrayType(BfType* resolvedType, int dimensions)
  3665. {
  3666. BF_ASSERT(!resolvedType->IsVar());
  3667. auto arrayType = mContext->mArrayTypePool.Get();
  3668. arrayType->mContext = mContext;
  3669. arrayType->mTypeDef = mCompiler->GetArrayTypeDef(dimensions);
  3670. arrayType->mDimensions = dimensions;
  3671. arrayType->mTypeGenericArguments.clear();
  3672. arrayType->mTypeGenericArguments.push_back(resolvedType);
  3673. auto resolvedArrayType = ResolveType(arrayType);
  3674. if (resolvedArrayType != arrayType)
  3675. mContext->mArrayTypePool.GiveBack(arrayType);
  3676. return (BfArrayType*)resolvedArrayType;
  3677. }
  3678. BfSizedArrayType* BfModule::CreateSizedArrayType(BfType * resolvedType, int size)
  3679. {
  3680. BF_ASSERT(!resolvedType->IsVar());
  3681. auto arrayType = mContext->mSizedArrayTypePool.Get();
  3682. arrayType->mContext = mContext;
  3683. arrayType->mElementType = resolvedType;
  3684. arrayType->mElementCount = size;
  3685. auto resolvedArrayType = ResolveType(arrayType);
  3686. if (resolvedArrayType != arrayType)
  3687. mContext->mSizedArrayTypePool.GiveBack(arrayType);
  3688. return (BfSizedArrayType*)resolvedArrayType;
  3689. }
  3690. BfUnknownSizedArrayType* BfModule::CreateUnknownSizedArrayType(BfType* resolvedType, BfType* sizeParam)
  3691. {
  3692. BF_ASSERT(!resolvedType->IsVar());
  3693. BF_ASSERT(sizeParam->IsGenericParam());
  3694. auto arrayType = mContext->mUnknownSizedArrayTypePool.Get();
  3695. arrayType->mContext = mContext;
  3696. arrayType->mElementType = resolvedType;
  3697. arrayType->mElementCount = -1;
  3698. arrayType->mElementCountSource = sizeParam;
  3699. auto resolvedArrayType = ResolveType(arrayType);
  3700. if (resolvedArrayType != arrayType)
  3701. mContext->mUnknownSizedArrayTypePool.GiveBack(arrayType);
  3702. return (BfUnknownSizedArrayType*)resolvedArrayType;
  3703. }
  3704. BfPointerType* BfModule::CreatePointerType(BfType* resolvedType)
  3705. {
  3706. auto pointerType = mContext->mPointerTypePool.Get();
  3707. pointerType->mContext = mContext;
  3708. pointerType->mElementType = resolvedType;
  3709. auto resolvedPointerType = (BfPointerType*)ResolveType(pointerType);
  3710. if (resolvedPointerType != pointerType)
  3711. mContext->mPointerTypePool.GiveBack(pointerType);
  3712. BF_ASSERT(resolvedPointerType->mElementType == resolvedType);
  3713. return resolvedPointerType;
  3714. }
  3715. BfConstExprValueType* BfModule::CreateConstExprValueType(const BfTypedValue& typedValue)
  3716. {
  3717. auto variant = TypedValueToVariant(NULL, typedValue);
  3718. if (variant.mTypeCode == BfTypeCode_None)
  3719. return NULL;
  3720. auto constExprValueType = mContext->mConstExprValueTypePool.Get();
  3721. constExprValueType->mContext = mContext;
  3722. constExprValueType->mType = typedValue.mType;
  3723. constExprValueType->mValue = variant;
  3724. auto resolvedConstExprValueType = (BfConstExprValueType*)ResolveType(constExprValueType);
  3725. if (resolvedConstExprValueType != constExprValueType)
  3726. mContext->mConstExprValueTypePool.GiveBack(constExprValueType);
  3727. BF_ASSERT(resolvedConstExprValueType->mValue.mInt64 == constExprValueType->mValue.mInt64);
  3728. return resolvedConstExprValueType;
  3729. }
  3730. BfTypeInstance* BfModule::GetWrappedStructType(BfType* type, bool allowSpecialized)
  3731. {
  3732. if (type->IsPointer())
  3733. {
  3734. if (allowSpecialized)
  3735. {
  3736. BfPointerType* pointerType = (BfPointerType*)type;
  3737. BfTypeVector typeVector;
  3738. typeVector.Add(pointerType->mElementType);
  3739. return ResolveTypeDef(mCompiler->mPointerTTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  3740. }
  3741. else
  3742. return ResolveTypeDef(mCompiler->mPointerTTypeDef, BfPopulateType_Data)->ToTypeInstance();
  3743. }
  3744. else if (type->IsMethodRef())
  3745. {
  3746. if (allowSpecialized)
  3747. {
  3748. BfMethodRefType* methodRefType = (BfMethodRefType*)type;
  3749. BfTypeVector typeVector;
  3750. typeVector.Add(methodRefType);
  3751. return ResolveTypeDef(mCompiler->mMethodRefTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  3752. }
  3753. else
  3754. return ResolveTypeDef(mCompiler->mMethodRefTypeDef, BfPopulateType_Data)->ToTypeInstance();
  3755. }
  3756. else if (type->IsSizedArray())
  3757. {
  3758. if (allowSpecialized)
  3759. {
  3760. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)type;
  3761. BfTypeVector typeVector;
  3762. typeVector.Add(sizedArrayType->mElementType);
  3763. auto sizeValue = BfTypedValue(GetConstValue(sizedArrayType->mElementCount), GetPrimitiveType(BfTypeCode_IntPtr));
  3764. typeVector.Add(CreateConstExprValueType(sizeValue));
  3765. return ResolveTypeDef(mCompiler->mSizedArrayTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  3766. }
  3767. else
  3768. return ResolveTypeDef(mCompiler->mSizedArrayTypeDef, BfPopulateType_Data)->ToTypeInstance();
  3769. }
  3770. BF_ASSERT(type->IsPrimitiveType());
  3771. return GetPrimitiveStructType(((BfPrimitiveType*)type)->mTypeDef->mTypeCode);
  3772. }
  3773. BfPrimitiveType* BfModule::GetPrimitiveType(BfTypeCode typeCode)
  3774. {
  3775. BfPrimitiveType* primType = mContext->mPrimitiveTypes[typeCode];
  3776. if (primType == NULL)
  3777. {
  3778. switch (typeCode)
  3779. {
  3780. case BfTypeCode_NullPtr:
  3781. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeNullPtr);
  3782. break;
  3783. case BfTypeCode_Self:
  3784. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeSelf);
  3785. break;
  3786. case BfTypeCode_Dot:
  3787. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeDot);
  3788. break;
  3789. case BfTypeCode_Var:
  3790. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeVar);
  3791. break;
  3792. case BfTypeCode_Let:
  3793. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeLet);
  3794. break;
  3795. case BfTypeCode_None:
  3796. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeVoid);
  3797. break;
  3798. case BfTypeCode_Boolean:
  3799. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeBool);
  3800. break;
  3801. case BfTypeCode_Int8:
  3802. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeInt8);
  3803. break;
  3804. case BfTypeCode_UInt8:
  3805. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUInt8);
  3806. break;
  3807. case BfTypeCode_Int16:
  3808. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeInt16);
  3809. break;
  3810. case BfTypeCode_UInt16:
  3811. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUInt16);
  3812. break;
  3813. case BfTypeCode_Int32:
  3814. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeInt32);
  3815. break;
  3816. case BfTypeCode_UInt32:
  3817. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUInt32);
  3818. break;
  3819. case BfTypeCode_Int64:
  3820. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeInt64);
  3821. break;
  3822. case BfTypeCode_UInt64:
  3823. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUInt64);
  3824. break;
  3825. case BfTypeCode_Char8:
  3826. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeChar8);
  3827. break;
  3828. case BfTypeCode_Char16:
  3829. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeChar16);
  3830. break;
  3831. case BfTypeCode_Char32:
  3832. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeChar32);
  3833. break;
  3834. case BfTypeCode_Single:
  3835. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeSingle);
  3836. break;
  3837. case BfTypeCode_Double:
  3838. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeDouble);
  3839. break;
  3840. case BfTypeCode_IntPtr:
  3841. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeIntPtr);
  3842. break;
  3843. case BfTypeCode_UIntPtr:
  3844. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUIntPtr);
  3845. break;
  3846. case BfTypeCode_IntUnknown:
  3847. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeIntUnknown);
  3848. break;
  3849. case BfTypeCode_UIntUnknown:
  3850. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUIntUnknown);
  3851. break;
  3852. default: break;
  3853. }
  3854. mContext->mPrimitiveTypes[typeCode] = primType;
  3855. }
  3856. return primType;
  3857. }
  3858. BfMethodRefType* BfModule::CreateMethodRefType(BfMethodInstance* methodInstance, bool mustAlreadyExist)
  3859. {
  3860. auto methodRefType = new BfMethodRefType();
  3861. methodRefType->mContext = mContext;
  3862. //methodRefType->mCaptureType = NULL;
  3863. methodRefType->mMethodRef = methodInstance;
  3864. methodRefType->mOwner = methodInstance->GetOwner();
  3865. methodRefType->mOwnerRevision = methodRefType->mOwner->mRevision;
  3866. //methodRefType->mMangledName = BfMangler::Mangle(mCompiler->GetMangleKind(), methodInstance);
  3867. methodRefType->mIsAutoCompleteMethod = methodInstance->mIsAutocompleteMethod;
  3868. methodRefType->mIsUnspecialized = methodInstance->mIsUnspecialized;
  3869. methodRefType->mIsUnspecializedVariation = methodInstance->mIsUnspecializedVariation;
  3870. methodRefType->mSize = 0;
  3871. BfResolvedTypeSet::LookupContext lookupCtx;
  3872. lookupCtx.mModule = this;
  3873. BfResolvedTypeSet::Entry* typeEntry = NULL;
  3874. auto inserted = mContext->mResolvedTypes.Insert(methodRefType, &lookupCtx, &typeEntry);
  3875. if (typeEntry->mValue == NULL)
  3876. {
  3877. BF_ASSERT(!mustAlreadyExist);
  3878. BF_ASSERT(!methodInstance->mHasMethodRefType);
  3879. InitType(methodRefType, BfPopulateType_Identity);
  3880. methodRefType->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  3881. methodInstance->mHasMethodRefType = true;
  3882. methodInstance->mMethodInstanceGroup->mRefCount++;
  3883. typeEntry->mValue = methodRefType;
  3884. BfLogSysM("Create MethodRefType %p MethodInstance: %p\n", methodRefType, methodInstance);
  3885. methodRefType->mRevision = 0;
  3886. AddDependency(methodInstance->GetOwner(), methodRefType, BfDependencyMap::DependencyFlag_Calls);
  3887. BfTypeVector tupleTypes;
  3888. Array<String> tupleNames;
  3889. int offset = 0;
  3890. methodRefType->mAlign = 1;
  3891. int dataIdx = 0;
  3892. // CRepr, just because we're lazy (for now)
  3893. int implicitParamCount = methodInstance->GetImplicitParamCount();
  3894. for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  3895. {
  3896. auto paramType = methodInstance->GetParamType(implicitParamIdx);
  3897. if (!paramType->IsValuelessType())
  3898. {
  3899. methodRefType->mDataToParamIdx.Add(implicitParamIdx);
  3900. if (implicitParamIdx >= 0)
  3901. methodRefType->mParamToDataIdx.Add(dataIdx);
  3902. offset = BF_ALIGN(offset, paramType->mAlign);
  3903. offset += paramType->mSize;
  3904. methodRefType->mAlign = std::max(methodRefType->mAlign, paramType->mAlign);
  3905. dataIdx++;
  3906. }
  3907. else
  3908. {
  3909. methodRefType->mParamToDataIdx.Add(-1);
  3910. }
  3911. }
  3912. offset = BF_ALIGN(offset, methodRefType->mAlign);
  3913. methodRefType->mSize = offset;
  3914. // if (!tupleTypes.empty())
  3915. // {
  3916. // methodRefType->mCaptureType = CreateTupleType(tupleTypes, tupleNames);
  3917. // AddDependency(methodRefType->mCaptureType, methodRefType, BfDependencyMap::DependencyFlag_ReadFields);
  3918. //
  3919. // methodRefType->mSize = methodRefType->mCaptureType->mSize;
  3920. // methodRefType->mAlign = methodRefType->mCaptureType->mAlign;
  3921. // }
  3922. // else
  3923. // {
  3924. // methodRefType->mSize = 0;
  3925. // methodRefType->mAlign = 0;
  3926. // }
  3927. }
  3928. else
  3929. {
  3930. methodRefType->mMethodRef = NULL;
  3931. delete methodRefType;
  3932. methodRefType = (BfMethodRefType*)typeEntry->mValue;
  3933. }
  3934. return methodRefType;
  3935. }
  3936. BfType* BfModule::FixIntUnknown(BfType* type)
  3937. {
  3938. if ((type != NULL) && (type->IsPrimitiveType()))
  3939. {
  3940. auto primType = (BfPrimitiveType*)type;
  3941. if (primType->mTypeDef->mTypeCode == BfTypeCode_IntUnknown)
  3942. return GetPrimitiveType(BfTypeCode_IntPtr);
  3943. if (primType->mTypeDef->mTypeCode == BfTypeCode_UIntUnknown)
  3944. return GetPrimitiveType(BfTypeCode_UIntPtr);
  3945. }
  3946. return type;
  3947. }
  3948. void BfModule::FixIntUnknown(BfTypedValue& typedVal)
  3949. {
  3950. if (!typedVal.mValue.IsConst())
  3951. {
  3952. if ((typedVal.mType != NULL) && (typedVal.mType->IsPrimitiveType()))
  3953. {
  3954. auto primType = (BfPrimitiveType*)typedVal.mType;
  3955. BF_ASSERT((primType->mTypeDef->mTypeCode != BfTypeCode_IntUnknown) && (primType->mTypeDef->mTypeCode != BfTypeCode_UIntUnknown));
  3956. }
  3957. return;
  3958. }
  3959. if (!typedVal.mType->IsPrimitiveType())
  3960. return;
  3961. BfTypeCode wantTypeCode;
  3962. auto primType = (BfPrimitiveType*)typedVal.mType;
  3963. if (primType->mTypeDef->mTypeCode == BfTypeCode_IntUnknown)
  3964. wantTypeCode = BfTypeCode_IntPtr;
  3965. else if (primType->mTypeDef->mTypeCode == BfTypeCode_UIntUnknown)
  3966. wantTypeCode = BfTypeCode_UIntPtr;
  3967. else
  3968. return;
  3969. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  3970. if (mSystem->mPtrSize == 4)
  3971. {
  3972. if (primType->mTypeDef->mTypeCode == BfTypeCode_IntUnknown)
  3973. {
  3974. if ((constant->mInt64 >= -0x80000000LL) && (constant->mInt64 <= 0x7FFFFFFFLL))
  3975. {
  3976. typedVal.mValue = mBfIRBuilder->CreateNumericCast(typedVal.mValue, true, BfTypeCode_IntPtr);
  3977. typedVal.mType = GetPrimitiveType(BfTypeCode_IntPtr);
  3978. }
  3979. else
  3980. typedVal.mType = GetPrimitiveType(BfTypeCode_Int64);
  3981. return;
  3982. }
  3983. else
  3984. {
  3985. if ((constant->mInt64 >= 0) && (constant->mInt64 <= 0xFFFFFFFF))
  3986. {
  3987. typedVal.mValue = mBfIRBuilder->CreateNumericCast(typedVal.mValue, false, BfTypeCode_IntPtr);
  3988. typedVal.mType = GetPrimitiveType(BfTypeCode_UIntPtr);
  3989. }
  3990. else
  3991. typedVal.mType = GetPrimitiveType(BfTypeCode_UInt64);
  3992. return;
  3993. }
  3994. }
  3995. typedVal.mType = GetPrimitiveType(wantTypeCode);
  3996. }
  3997. void BfModule::FixIntUnknown(BfTypedValue& lhs, BfTypedValue& rhs)
  3998. {
  3999. if ((lhs.mType != NULL) && (lhs.mType->IsIntUnknown()) && (rhs.mType != NULL) && (rhs.mType->IsInteger()))
  4000. {
  4001. if (CanImplicitlyCast(lhs, rhs.mType))
  4002. {
  4003. lhs = Cast(NULL, lhs, rhs.mType, BfCastFlags_SilentFail);
  4004. if (!lhs)
  4005. lhs = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  4006. return;
  4007. }
  4008. }
  4009. if ((rhs.mType != NULL) && (rhs.mType->IsIntUnknown()) && (lhs.mType != NULL) && (lhs.mType->IsInteger()))
  4010. {
  4011. if (CanImplicitlyCast(rhs, lhs.mType))
  4012. {
  4013. rhs = Cast(NULL, rhs, lhs.mType, BfCastFlags_SilentFail);
  4014. if (!rhs)
  4015. rhs = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  4016. return;
  4017. }
  4018. }
  4019. FixIntUnknown(lhs);
  4020. FixIntUnknown(rhs);
  4021. }
  4022. BfTypeInstance* BfModule::GetPrimitiveStructType(BfTypeCode typeCode)
  4023. {
  4024. BfTypeInstance* typeInst = NULL;
  4025. switch (typeCode)
  4026. {
  4027. case BfTypeCode_None:
  4028. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Void"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4029. case BfTypeCode_Boolean:
  4030. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Boolean"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4031. case BfTypeCode_Int8:
  4032. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int8"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4033. case BfTypeCode_UInt8:
  4034. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt8"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4035. case BfTypeCode_Int16:
  4036. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int16"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4037. case BfTypeCode_UInt16:
  4038. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt16"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4039. case BfTypeCode_Int32:
  4040. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int32"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4041. case BfTypeCode_UInt32:
  4042. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt32"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4043. case BfTypeCode_Int64:
  4044. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int64"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4045. case BfTypeCode_UInt64:
  4046. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt64"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4047. case BfTypeCode_IntPtr:
  4048. case BfTypeCode_IntUnknown:
  4049. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4050. case BfTypeCode_UIntPtr:
  4051. case BfTypeCode_UIntUnknown:
  4052. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4053. case BfTypeCode_Char8:
  4054. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Char8"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4055. case BfTypeCode_Char16:
  4056. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Char16"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4057. case BfTypeCode_Char32:
  4058. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Char32"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4059. case BfTypeCode_Single:
  4060. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Float"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4061. case BfTypeCode_Double:
  4062. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Double"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4063. default:
  4064. //BF_FATAL("not implemented");
  4065. break;
  4066. }
  4067. return typeInst;
  4068. }
  4069. BfBoxedType* BfModule::CreateBoxedType(BfType* resolvedTypeRef)
  4070. {
  4071. bool isStructPtr = false;
  4072. // if (resolvedTypeRef->IsPointer())
  4073. // resolvedTypeRef = ((BfPointerType*)resolvedTypeRef)->mElementType;
  4074. if (resolvedTypeRef->IsPrimitiveType())
  4075. {
  4076. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  4077. resolvedTypeRef = GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  4078. if (resolvedTypeRef == NULL)
  4079. {
  4080. BF_FATAL("Unable to find primitive type");
  4081. return NULL;
  4082. }
  4083. }
  4084. else if (resolvedTypeRef->IsPointer())
  4085. {
  4086. BfPointerType* pointerType = (BfPointerType*)resolvedTypeRef;
  4087. if (pointerType->mElementType->IsStruct())
  4088. {
  4089. resolvedTypeRef = pointerType->mElementType;
  4090. isStructPtr = true;
  4091. }
  4092. else
  4093. {
  4094. BfTypeVector typeVector;
  4095. typeVector.Add(pointerType->mElementType);
  4096. resolvedTypeRef = ResolveTypeDef(mCompiler->mPointerTTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  4097. }
  4098. }
  4099. else if (resolvedTypeRef->IsMethodRef())
  4100. {
  4101. BfMethodRefType* methodRefType = (BfMethodRefType*)resolvedTypeRef;
  4102. BfTypeVector typeVector;
  4103. typeVector.Add(methodRefType);
  4104. resolvedTypeRef = ResolveTypeDef(mCompiler->mMethodRefTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  4105. }
  4106. else if (resolvedTypeRef->IsSizedArray())
  4107. {
  4108. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)resolvedTypeRef;
  4109. BfTypeVector typeVector;
  4110. typeVector.Add(sizedArrayType->mElementType);
  4111. auto sizeValue = BfTypedValue(GetConstValue(sizedArrayType->mElementCount), GetPrimitiveType(BfTypeCode_IntPtr));
  4112. typeVector.Add(CreateConstExprValueType(sizeValue));
  4113. resolvedTypeRef = ResolveTypeDef(mCompiler->mSizedArrayTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  4114. }
  4115. BfTypeInstance* typeInst = resolvedTypeRef->ToTypeInstance();
  4116. if (typeInst == NULL)
  4117. return NULL;
  4118. auto boxedType = mContext->mBoxedTypePool.Get();
  4119. boxedType->mContext = mContext;
  4120. boxedType->mElementType = typeInst;
  4121. boxedType->mTypeDef = boxedType->mElementType->mTypeDef;
  4122. boxedType->mBoxedFlags = isStructPtr ? BfBoxedType::BoxedFlags_StructPtr : BfBoxedType::BoxedFlags_None;
  4123. auto resolvedBoxedType = ResolveType(boxedType);
  4124. if (resolvedBoxedType != boxedType)
  4125. mContext->mBoxedTypePool.GiveBack(boxedType);
  4126. return (BfBoxedType*)resolvedBoxedType;
  4127. }
  4128. BfTupleType* BfModule::CreateTupleType(const BfTypeVector& fieldTypes, const Array<String>& fieldNames)
  4129. {
  4130. auto tupleType = mContext->mTupleTypePool.Get();
  4131. tupleType->mContext = mContext;
  4132. tupleType->mFieldInstances.Resize(fieldTypes.size());
  4133. auto baseType = (BfTypeInstance*)ResolveTypeDef(mContext->mCompiler->mValueTypeTypeDef);
  4134. tupleType->Init(baseType->mTypeDef->mProject, baseType);
  4135. for (int fieldIdx = 0; fieldIdx < (int)fieldTypes.size(); fieldIdx++)
  4136. {
  4137. BfFieldInstance* fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  4138. fieldInstance->mFieldIdx = fieldIdx;
  4139. fieldInstance->SetResolvedType(fieldTypes[fieldIdx]);
  4140. fieldInstance->mOwner = tupleType;
  4141. String fieldName;
  4142. if (fieldIdx < (int)fieldNames.size())
  4143. fieldName = fieldNames[fieldIdx];
  4144. if (fieldName.empty())
  4145. fieldName = StrFormat("%d", fieldIdx);
  4146. BfFieldDef* fieldDef = tupleType->AddField(fieldName);
  4147. }
  4148. auto resolvedTupleType = ResolveType(tupleType);
  4149. if (resolvedTupleType != tupleType)
  4150. mContext->mTupleTypePool.GiveBack(tupleType);
  4151. return (BfTupleType*)resolvedTupleType;
  4152. }
  4153. BfTupleType * BfModule::SantizeTupleType(BfTupleType* tupleType)
  4154. {
  4155. bool needsSanitize = false;
  4156. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  4157. {
  4158. BfFieldInstance* fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  4159. if ((fieldInstance->mResolvedType->IsVar()) || (fieldInstance->mResolvedType->IsLet()))
  4160. {
  4161. needsSanitize = true;
  4162. break;
  4163. }
  4164. }
  4165. if (!needsSanitize)
  4166. return tupleType;
  4167. BfTypeVector fieldTypes;
  4168. Array<String> fieldNames;
  4169. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  4170. {
  4171. BfFieldInstance* fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  4172. auto fieldDef = fieldInstance->GetFieldDef();
  4173. if ((fieldInstance->mResolvedType->IsVar()) || (fieldInstance->mResolvedType->IsLet()))
  4174. fieldTypes.Add(mContext->mBfObjectType);
  4175. else
  4176. fieldTypes.Add(fieldInstance->mResolvedType);
  4177. if (!fieldDef->IsUnnamedTupleField())
  4178. {
  4179. for (int i = 0; i < fieldIdx; i++)
  4180. fieldNames.Add(String());
  4181. fieldNames.Add(fieldDef->mName);
  4182. }
  4183. }
  4184. return CreateTupleType(fieldTypes, fieldNames);
  4185. }
  4186. BfRefType* BfModule::CreateRefType(BfType* resolvedTypeRef, BfRefType::RefKind refKind)
  4187. {
  4188. auto refType = mContext->mRefTypePool.Get();
  4189. refType->mContext = mContext;
  4190. refType->mElementType = resolvedTypeRef;
  4191. refType->mRefKind = refKind;
  4192. auto resolvedRefType = ResolveType(refType);
  4193. if (resolvedRefType != refType)
  4194. mContext->mRefTypePool.GiveBack(refType);
  4195. return (BfRefType*)resolvedRefType;
  4196. }
  4197. BfRetTypeType* BfModule::CreateRetTypeType(BfType* resolvedTypeRef)
  4198. {
  4199. auto retTypeType = mContext->mRetTypeTypePool.Get();
  4200. retTypeType->mContext = mContext;
  4201. retTypeType->mElementType = resolvedTypeRef;
  4202. auto resolvedRetTypeType = ResolveType(retTypeType);
  4203. if (resolvedRetTypeType != retTypeType)
  4204. mContext->mRetTypeTypePool.GiveBack(retTypeType);
  4205. return (BfRetTypeType*)resolvedRetTypeType;
  4206. }
  4207. BfConcreteInterfaceType* BfModule::CreateConcreteInterfaceType(BfTypeInstance* interfaceType)
  4208. {
  4209. auto concreteInterfaceType = mContext->mConcreteInterfaceTypePool.Get();
  4210. concreteInterfaceType->mContext = mContext;
  4211. concreteInterfaceType->mInterface = interfaceType;
  4212. auto resolvedConcreteInterfaceType = ResolveType(concreteInterfaceType);
  4213. if (resolvedConcreteInterfaceType != concreteInterfaceType)
  4214. mContext->mConcreteInterfaceTypePool.GiveBack(concreteInterfaceType);
  4215. return (BfConcreteInterfaceType*)resolvedConcreteInterfaceType;
  4216. }
  4217. BfPointerType* BfModule::CreatePointerType(BfTypeReference* typeRef)
  4218. {
  4219. auto resolvedTypeRef = ResolveTypeRef(typeRef);
  4220. if (resolvedTypeRef == NULL)
  4221. return NULL;
  4222. return CreatePointerType(resolvedTypeRef);
  4223. }
  4224. BfType* BfModule::ResolveTypeDef(BfTypeDef* typeDef, BfPopulateType populateType)
  4225. {
  4226. //BF_ASSERT(typeDef->mTypeCode != BfTypeCode_Extension);
  4227. BF_ASSERT(!typeDef->mIsPartial || typeDef->mIsCombinedPartial);
  4228. if (typeDef->mGenericParamDefs.size() != 0)
  4229. return ResolveTypeDef(typeDef, BfTypeVector(), populateType);
  4230. auto typeDefTypeRef = mContext->mTypeDefTypeRefPool.Get();
  4231. typeDefTypeRef->mTypeDef = typeDef;
  4232. auto resolvedtypeDefType = ResolveTypeRef(typeDefTypeRef, populateType);
  4233. if (resolvedtypeDefType == NULL)
  4234. {
  4235. mContext->mTypeDefTypeRefPool.GiveBack(typeDefTypeRef);
  4236. return NULL;
  4237. }
  4238. mContext->mTypeDefTypeRefPool.GiveBack(typeDefTypeRef);
  4239. //BF_ASSERT(resolvedtypeDefType->IsTypeInstance() || resolvedtypeDefType->IsPrimitiveType());
  4240. return resolvedtypeDefType;
  4241. }
  4242. // Get BaseClass even when we haven't populated the type yet
  4243. BfTypeInstance* BfModule::GetBaseType(BfTypeInstance* typeInst)
  4244. {
  4245. if ((typeInst->mBaseType == NULL) && (typeInst != mContext->mBfObjectType))
  4246. PopulateType(typeInst, BfPopulateType_BaseType);
  4247. return typeInst->mBaseType;
  4248. }
  4249. void BfModule::HandleTypeGenericParamRef(BfAstNode* refNode, BfTypeDef* typeDef, int typeGenericParamIdx)
  4250. {
  4251. if (mCompiler->IsAutocomplete())
  4252. {
  4253. BfAutoComplete* autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  4254. if ((autoComplete != NULL) && (autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(refNode)))
  4255. {
  4256. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  4257. (autoComplete->mDefProp == NULL))
  4258. {
  4259. autoComplete->mDefType = typeDef;
  4260. autoComplete->mDefTypeGenericParamIdx = typeGenericParamIdx;
  4261. autoComplete->SetDefinitionLocation(refNode);
  4262. }
  4263. }
  4264. }
  4265. if (mCompiler->mResolvePassData != NULL)
  4266. mCompiler->mResolvePassData->HandleTypeGenericParam(refNode, typeDef, typeGenericParamIdx);
  4267. }
  4268. void BfModule::HandleMethodGenericParamRef(BfAstNode* refNode, BfTypeDef* typeDef, BfMethodDef* methodDef, int methodGenericParamIdx)
  4269. {
  4270. if (mCompiler->IsAutocomplete())
  4271. {
  4272. BfAutoComplete* autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  4273. if ((autoComplete != NULL) && (autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(refNode)))
  4274. {
  4275. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  4276. (autoComplete->mDefProp == NULL))
  4277. {
  4278. autoComplete->mDefType = typeDef;
  4279. autoComplete->mDefMethod = methodDef;
  4280. autoComplete->mDefMethodGenericParamIdx = methodGenericParamIdx;
  4281. autoComplete->SetDefinitionLocation(refNode);
  4282. }
  4283. }
  4284. }
  4285. if (mCompiler->mResolvePassData != NULL)
  4286. mCompiler->mResolvePassData->HandleMethodGenericParam(refNode, typeDef, methodDef, methodGenericParamIdx);
  4287. }
  4288. BfType* BfModule::ResolveInnerType(BfType* outerType, BfTypeReference* typeRef, BfPopulateType populateType, bool ignoreErrors)
  4289. {
  4290. BfTypeDef* nestedTypeDef = NULL;
  4291. if (outerType->IsBoxed())
  4292. outerType = outerType->GetUnderlyingType();
  4293. BfNamedTypeReference* namedTypeRef = NULL;
  4294. BfGenericInstanceTypeRef* genericTypeRef = NULL;
  4295. BfDirectStrTypeReference* directStrTypeRef = NULL;
  4296. if ((namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef)))
  4297. {
  4298. //TYPEDEF nestedTypeDef = namedTypeRef->mTypeDef;
  4299. }
  4300. else if ((genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef)))
  4301. {
  4302. namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(genericTypeRef->mElementType);
  4303. //TYPEDEF nestedTypeDef = namedTypeRef->mTypeDef;
  4304. }
  4305. else if ((directStrTypeRef = BfNodeDynCast<BfDirectStrTypeReference>(typeRef)))
  4306. {
  4307. //
  4308. }
  4309. BF_ASSERT((namedTypeRef != NULL) || (directStrTypeRef != NULL));
  4310. if (nestedTypeDef == NULL)
  4311. {
  4312. StringView findName;
  4313. if (namedTypeRef != NULL)
  4314. findName = namedTypeRef->mNameNode->ToStringView();
  4315. else
  4316. findName = directStrTypeRef->mTypeName;
  4317. if (!findName.Contains('.'))
  4318. {
  4319. if (outerType->IsTypeInstance())
  4320. {
  4321. auto outerTypeInstance = outerType->ToTypeInstance();
  4322. for (int pass = 0; pass < 2; pass++)
  4323. {
  4324. bool isFailurePass = pass == 1;
  4325. bool allowPrivate = (mCurTypeInstance != NULL) &&
  4326. ((mCurTypeInstance == outerTypeInstance) || TypeHasParent(mCurTypeInstance->mTypeDef, outerTypeInstance->mTypeDef));
  4327. bool allowProtected = allowPrivate;/*(mCurTypeInstance != NULL) &&
  4328. (allowPrivate || (mCurTypeInstance->mSkipTypeProtectionChecks) || TypeIsSubTypeOf(mCurTypeInstance, outerTypeInstance));*/
  4329. auto checkOuterType = outerTypeInstance;
  4330. while (checkOuterType != NULL)
  4331. {
  4332. for (auto checkType : checkOuterType->mTypeDef->mNestedTypes)
  4333. {
  4334. auto latestCheckType = checkType->GetLatest();
  4335. if ((!isFailurePass) && (!CheckProtection(latestCheckType->mProtection, allowProtected, allowPrivate)))
  4336. continue;
  4337. if (checkType->mName->mString == findName)
  4338. {
  4339. if (isFailurePass)
  4340. {
  4341. // This is the one error we don't ignore when ignoreErrors is set
  4342. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(checkOuterType).c_str(), BfTypeUtils::TypeToString(typeRef).c_str()), typeRef); // CS0122
  4343. }
  4344. nestedTypeDef = checkType;
  4345. break;
  4346. }
  4347. }
  4348. if (nestedTypeDef != NULL)
  4349. break;
  4350. allowPrivate = false;
  4351. checkOuterType = GetBaseType(checkOuterType);
  4352. }
  4353. if (nestedTypeDef != NULL)
  4354. break;
  4355. }
  4356. }
  4357. }
  4358. if (nestedTypeDef == NULL)
  4359. {
  4360. if (!mIgnoreErrors && !ignoreErrors)
  4361. {
  4362. StringT<64> name;
  4363. name.Append(findName);
  4364. Fail(StrFormat("'%s' does not contain a definition for '%s'", TypeToString(outerType).c_str(), name.c_str()), typeRef);
  4365. }
  4366. return NULL;
  4367. }
  4368. }
  4369. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, ignoreErrors || mIgnoreErrors);
  4370. if ((genericTypeRef != NULL) || (outerType->IsGenericTypeInstance()))
  4371. {
  4372. BfTypeVector genericArgs;
  4373. if (outerType->IsGenericTypeInstance())
  4374. {
  4375. auto genericTypeInst = (BfGenericTypeInstance*)outerType;
  4376. genericArgs = genericTypeInst->mTypeGenericArguments;
  4377. }
  4378. if (genericTypeRef != NULL)
  4379. {
  4380. for (auto genericArgTypeRef : genericTypeRef->mGenericArguments)
  4381. {
  4382. auto genericArgType = ResolveTypeRef(genericArgTypeRef, BfPopulateType_IdentityNoRemapAlias);
  4383. if (genericArgType == NULL)
  4384. return NULL;
  4385. genericArgs.push_back(genericArgType);
  4386. }
  4387. }
  4388. if (genericArgs.size() != nestedTypeDef->mGenericParamDefs.size())
  4389. {
  4390. if (populateType == BfPopulateType_TypeDef)
  4391. {
  4392. // Probably from inside ResolveGenericInstanceDef, just return unresolved typedef
  4393. genericArgs.clear();
  4394. }
  4395. else
  4396. {
  4397. ShowGenericArgCountError(typeRef, (int)nestedTypeDef->mGenericParamDefs.size() - (int)nestedTypeDef->mOuterType->mGenericParamDefs.size());
  4398. return NULL;
  4399. }
  4400. }
  4401. if (nestedTypeDef->mIsPartial)
  4402. {
  4403. nestedTypeDef = GetCombinedPartialTypeDef(nestedTypeDef);
  4404. if (nestedTypeDef == NULL)
  4405. return NULL;
  4406. }
  4407. return ResolveTypeDef(nestedTypeDef, genericArgs, BfPopulateType_IdentityNoRemapAlias);
  4408. }
  4409. else
  4410. {
  4411. if (nestedTypeDef->mIsPartial)
  4412. {
  4413. nestedTypeDef = GetCombinedPartialTypeDef(nestedTypeDef);
  4414. if (nestedTypeDef == NULL)
  4415. return NULL;
  4416. }
  4417. return ResolveTypeDef(nestedTypeDef, BfPopulateType_IdentityNoRemapAlias);
  4418. }
  4419. return NULL;
  4420. }
  4421. BfTypeDef* BfModule::GetCombinedPartialTypeDef(BfTypeDef* typeDef)
  4422. {
  4423. BF_ASSERT(!typeDef->mIsExplicitPartial);
  4424. if (!typeDef->mIsPartial)
  4425. return typeDef;
  4426. auto result = mSystem->FindTypeDef(typeDef->mFullName.ToString(), (int)typeDef->mGenericParamDefs.size());
  4427. return result;
  4428. }
  4429. BfTypeInstance* BfModule::GetOuterType(BfType* type)
  4430. {
  4431. if (type == NULL)
  4432. return NULL;
  4433. if (type->IsBoxed())
  4434. return GetOuterType(((BfBoxedType*)type)->mElementType);
  4435. auto typeInst = type->ToTypeInstance();
  4436. if ((typeInst == NULL) || (typeInst->mTypeDef->mOuterType == NULL))
  4437. return NULL;
  4438. auto outerTypeDef = typeInst->mTypeDef->mOuterType;
  4439. if (outerTypeDef->mIsPartial)
  4440. {
  4441. outerTypeDef = GetCombinedPartialTypeDef(outerTypeDef);
  4442. if (outerTypeDef == NULL)
  4443. return NULL;
  4444. }
  4445. BfTypeVector typeGenericArguments;
  4446. if (type->IsGenericTypeInstance())
  4447. {
  4448. auto genericType = (BfGenericTypeInstance*)type;
  4449. typeGenericArguments = genericType->mTypeGenericArguments;
  4450. }
  4451. BF_ASSERT((intptr)typeGenericArguments.size() >= (intptr)outerTypeDef->mGenericParamDefs.size());
  4452. typeGenericArguments.resize(outerTypeDef->mGenericParamDefs.size());
  4453. auto outerType = ResolveTypeDef(outerTypeDef, typeGenericArguments, BfPopulateType_Declaration);
  4454. if (outerType == NULL)
  4455. return NULL;
  4456. return outerType->ToTypeInstance();
  4457. }
  4458. bool BfModule::IsInnerType(BfType* checkInnerType, BfType* checkOuterType)
  4459. {
  4460. BfType* outerType = GetOuterType(checkInnerType);
  4461. if (outerType == NULL)
  4462. return false;
  4463. if (outerType == checkOuterType)
  4464. return true;
  4465. return IsInnerType(outerType, checkOuterType);
  4466. }
  4467. bool BfModule::IsInnerType(BfTypeDef* checkInnerType, BfTypeDef* checkOuterType)
  4468. {
  4469. if (checkInnerType->mNestDepth <= checkOuterType->mNestDepth)
  4470. return false;
  4471. while (true)
  4472. {
  4473. BfTypeDef* outerType = checkInnerType->mOuterType;
  4474. if (outerType == NULL)
  4475. return false;
  4476. if (outerType == checkOuterType)
  4477. return true;
  4478. checkInnerType = checkInnerType->mOuterType;
  4479. }
  4480. }
  4481. BfType* BfModule::ResolveTypeDef(BfTypeDef* typeDef, const BfTypeVector& genericArgs, BfPopulateType populateType)
  4482. {
  4483. if (typeDef->mGenericParamDefs.size() == 0)
  4484. return ResolveTypeDef(typeDef, populateType);
  4485. if ((typeDef == mCompiler->mArray1TypeDef) || (typeDef == mCompiler->mArray2TypeDef))
  4486. {
  4487. auto arrayInstType = mContext->mArrayTypeInstancePool.Get();
  4488. arrayInstType->mContext = mContext;
  4489. if (typeDef == mCompiler->mArray1TypeDef)
  4490. arrayInstType->mDimensions = 1;
  4491. else
  4492. arrayInstType->mDimensions = 2;
  4493. auto typeRef = mContext->mTypeDefTypeRefPool.Get();
  4494. typeRef->mTypeDef = typeDef;
  4495. arrayInstType->mTypeDef = typeDef;
  4496. arrayInstType->mIsUnspecialized = false;
  4497. arrayInstType->mTypeGenericArguments.clear();
  4498. for (auto genericArg : genericArgs)
  4499. {
  4500. arrayInstType->mIsUnspecialized |= genericArg->IsGenericParam();
  4501. arrayInstType->mTypeGenericArguments.push_back(genericArg);
  4502. }
  4503. if (genericArgs.size() == 0)
  4504. {
  4505. for (int i = 0; i < (int)typeDef->mGenericParamDefs.size(); i++)
  4506. {
  4507. auto genericParamTypeRef = GetGenericParamType(BfGenericParamKind_Type, i);
  4508. arrayInstType->mTypeGenericArguments.push_back(genericParamTypeRef);
  4509. arrayInstType->mIsUnspecialized = true;
  4510. }
  4511. }
  4512. auto resolvedType = ResolveType(arrayInstType, populateType);
  4513. if (resolvedType != arrayInstType)
  4514. {
  4515. mContext->mArrayTypeInstancePool.GiveBack(arrayInstType);
  4516. mContext->mTypeDefTypeRefPool.GiveBack(typeRef);
  4517. }
  4518. BF_ASSERT((resolvedType == NULL) || resolvedType->IsTypeInstance() || resolvedType->IsPrimitiveType());
  4519. return resolvedType;
  4520. }
  4521. BfGenericTypeInstance* genericInstType;
  4522. if (typeDef->mTypeCode == BfTypeCode_TypeAlias)
  4523. genericInstType = mContext->mGenericTypeAliasPool.Get();
  4524. else
  4525. genericInstType = mContext->mGenericTypeInstancePool.Get();
  4526. genericInstType->mContext = mContext;
  4527. auto typeRef = mContext->mTypeDefTypeRefPool.Get();
  4528. typeRef->mTypeDef = typeDef;
  4529. genericInstType->mTypeDef = typeDef;
  4530. genericInstType->mIsUnspecialized = false;
  4531. genericInstType->mTypeGenericArguments.clear();
  4532. for (auto genericArg : genericArgs)
  4533. {
  4534. genericInstType->mIsUnspecialized |= genericArg->IsGenericParam();
  4535. genericInstType->mTypeGenericArguments.push_back(genericArg);
  4536. }
  4537. if (genericArgs.size() == 0)
  4538. {
  4539. for (int i = 0; i < (int)typeDef->mGenericParamDefs.size(); i++)
  4540. {
  4541. auto genericParamTypeRef = GetGenericParamType(BfGenericParamKind_Type, i);
  4542. genericInstType->mTypeGenericArguments.push_back(genericParamTypeRef);
  4543. genericInstType->mIsUnspecialized = true;
  4544. }
  4545. }
  4546. auto resolvedType = ResolveType(genericInstType, populateType);
  4547. if (resolvedType != genericInstType)
  4548. {
  4549. if (typeDef->mTypeCode == BfTypeCode_TypeAlias)
  4550. mContext->mGenericTypeAliasPool.GiveBack((BfGenericTypeAliasType*)genericInstType);
  4551. else
  4552. mContext->mGenericTypeInstancePool.GiveBack(genericInstType);
  4553. mContext->mTypeDefTypeRefPool.GiveBack(typeRef);
  4554. }
  4555. BF_ASSERT((resolvedType == NULL) || resolvedType->IsTypeInstance() || resolvedType->IsPrimitiveType());
  4556. return resolvedType;
  4557. }
  4558. int checkIdx = 0;
  4559. BfTypeDef* BfModule::ResolveGenericInstanceDef(BfGenericInstanceTypeRef* genericTypeRef)
  4560. {
  4561. BfTypeReference* typeRef = genericTypeRef->mElementType;
  4562. int numGenericParams = genericTypeRef->GetGenericArgCount();
  4563. BfTypeDef* curTypeDef = NULL;
  4564. if (mCurTypeInstance != NULL)
  4565. curTypeDef = mCurTypeInstance->mTypeDef;
  4566. if (auto directTypeDef = BfNodeDynCast<BfDirectTypeReference>(typeRef))
  4567. {
  4568. auto typeInst = directTypeDef->mType->ToTypeInstance();
  4569. return typeInst->mTypeDef;
  4570. }
  4571. auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef);
  4572. auto directStrTypeDef = BfNodeDynCastExact<BfDirectStrTypeReference>(typeRef);
  4573. if ((namedTypeRef != NULL) || (directStrTypeDef != NULL))
  4574. {
  4575. BfTypeLookupError error;
  4576. error.mRefNode = typeRef;
  4577. BfTypeDef* typeDef = FindTypeDef(typeRef, NULL, &error, numGenericParams);
  4578. if (typeDef != NULL)
  4579. {
  4580. BfAutoComplete* autoComplete = NULL;
  4581. if (mCompiler->IsAutocomplete())
  4582. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  4583. if ((autoComplete != NULL) && (autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(typeRef)))
  4584. {
  4585. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  4586. (autoComplete->mDefProp == NULL) && (typeDef->mTypeDeclaration != NULL))
  4587. {
  4588. autoComplete->mDefType = typeDef;
  4589. autoComplete->SetDefinitionLocation(typeDef->mTypeDeclaration->mNameNode);
  4590. }
  4591. }
  4592. if (mCompiler->mResolvePassData != NULL)
  4593. mCompiler->mResolvePassData->HandleTypeReference(typeRef, typeDef);
  4594. return typeDef;
  4595. }
  4596. if (mCurTypeInstance != NULL)
  4597. {
  4598. bool wasGenericParam = false;
  4599. // Check generics first
  4600. if (typeRef->IsA<BfNamedTypeReference>())
  4601. {
  4602. String findName = typeRef->ToString();
  4603. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsGenericTypeInstance()))
  4604. {
  4605. auto genericTypeInst = (BfGenericTypeInstance*)mCurTypeInstance;
  4606. for (int genericParamIdx = 0; genericParamIdx < (int)curTypeDef->mGenericParamDefs.size(); genericParamIdx++)
  4607. {
  4608. String genericName = curTypeDef->mGenericParamDefs[genericParamIdx]->mName;
  4609. if (genericName == findName)
  4610. wasGenericParam = true;
  4611. }
  4612. }
  4613. if (mCurMethodInstance != NULL)
  4614. {
  4615. for (int genericParamIdx = 0; genericParamIdx < (int)mCurMethodInstance->mMethodDef->mGenericParams.size(); genericParamIdx++)
  4616. {
  4617. String genericName = mCurMethodInstance->mMethodDef->mGenericParams[genericParamIdx]->mName;
  4618. if (genericName == findName)
  4619. wasGenericParam = true;
  4620. }
  4621. }
  4622. }
  4623. if (wasGenericParam)
  4624. Fail("Cannot use generic param as generic instance type", typeRef);
  4625. }
  4626. //if (mCurTypeInstance != NULL)
  4627. //{
  4628. // String findName;
  4629. // if (directStrTypeDef != NULL)
  4630. // findName = directStrTypeDef->mTypeName;
  4631. // else
  4632. // findName = namedTypeRef->mNameNode->ToString();
  4633. // auto outerTypeInstance = mCurTypeInstance;
  4634. // for (int pass = 0; pass < 2; pass++)
  4635. // {
  4636. // bool isFailurePass = pass == 1;
  4637. // bool allowPrivate = true;
  4638. // bool allowProtected = true;
  4639. // auto checkOuterType = outerTypeInstance;
  4640. // while (checkOuterType != NULL)
  4641. // {
  4642. // for (auto checkType : checkOuterType->mTypeDef->mNestedTypes)
  4643. // {
  4644. // if ((!isFailurePass) && (!CheckProtection(checkType->mProtection, allowProtected, allowPrivate)))
  4645. // continue;
  4646. // if (checkType->mName->mString == findName)
  4647. // {
  4648. // if (isFailurePass)
  4649. // {
  4650. // // This is the one error we don't ignore when ignoreErrors is set
  4651. // Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(checkOuterType).c_str(), BfTypeUtils::TypeToString(namedTypeRef).c_str()), namedTypeRef); // CS0122
  4652. // }
  4653. // return checkType;
  4654. // }
  4655. // }
  4656. // allowPrivate = false;
  4657. // if (checkOuterType == mContext->mBfObjectType)
  4658. // break;
  4659. // checkOuterType = GetBaseType(checkOuterType);
  4660. // }
  4661. // }
  4662. //}
  4663. if (typeDef == NULL)
  4664. {
  4665. TypeRefNotFound(typeRef);
  4666. return NULL;
  4667. }
  4668. }
  4669. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  4670. {
  4671. BfAutoParentNodeEntry autoParentNodeEntry(this, genericTypeRef);
  4672. auto type = ResolveTypeRef(qualifiedTypeRef, BfPopulateType_TypeDef);
  4673. if (type == NULL)
  4674. return NULL;
  4675. auto typeInst = type->ToTypeInstance();
  4676. if (typeInst != NULL)
  4677. return typeInst->mTypeDef;
  4678. }
  4679. Fail("Invalid generic type", typeRef);
  4680. return NULL;
  4681. }
  4682. BfType* BfModule::ResolveGenericType(BfType* unspecializedType, const BfTypeVector& methodGenericArguments, bool allowFail)
  4683. {
  4684. if (unspecializedType->IsGenericParam())
  4685. {
  4686. auto genericParam = (BfGenericParamType*)unspecializedType;
  4687. if (genericParam->mGenericParamKind == BfGenericParamKind_Method)
  4688. {
  4689. if (genericParam->mGenericParamIdx < (int)methodGenericArguments.size())
  4690. {
  4691. return methodGenericArguments[genericParam->mGenericParamIdx];
  4692. }
  4693. BF_ASSERT(allowFail);
  4694. }
  4695. return unspecializedType;
  4696. }
  4697. if (unspecializedType->IsUnknownSizedArray())
  4698. {
  4699. auto* arrayType = (BfUnknownSizedArrayType*)unspecializedType;
  4700. auto elementType = ResolveGenericType(arrayType->mElementType, methodGenericArguments, allowFail);
  4701. if (elementType == NULL)
  4702. return NULL;
  4703. auto sizeType = ResolveGenericType(arrayType->mElementCountSource, methodGenericArguments, allowFail);
  4704. if (sizeType == NULL)
  4705. return NULL;
  4706. if (sizeType->IsConstExprValue())
  4707. {
  4708. return CreateSizedArrayType(elementType, ((BfConstExprValueType*)sizeType)->mValue.mInt32);
  4709. }
  4710. return CreateUnknownSizedArrayType(elementType, sizeType);
  4711. }
  4712. if (unspecializedType->IsSizedArray())
  4713. {
  4714. auto* arrayType = (BfSizedArrayType*)unspecializedType;
  4715. auto elementType = ResolveGenericType(arrayType->mElementType, methodGenericArguments, allowFail);
  4716. if (elementType == NULL)
  4717. return NULL;
  4718. return CreateSizedArrayType(elementType, (int)arrayType->mElementCount);
  4719. }
  4720. if (unspecializedType->IsRef())
  4721. {
  4722. auto refType = (BfRefType*)unspecializedType;
  4723. auto elementType = ResolveGenericType(refType->GetUnderlyingType(), methodGenericArguments, allowFail);
  4724. if (elementType == NULL)
  4725. return NULL;
  4726. return CreateRefType(elementType, refType->mRefKind);
  4727. }
  4728. if (unspecializedType->IsArray())
  4729. {
  4730. auto arrayType = (BfArrayType*)unspecializedType;
  4731. auto elementType = ResolveGenericType(arrayType->GetUnderlyingType(), methodGenericArguments, allowFail);
  4732. if (elementType == NULL)
  4733. return NULL;
  4734. return CreateArrayType(elementType, arrayType->mDimensions);
  4735. }
  4736. if (unspecializedType->IsGenericTypeInstance())
  4737. {
  4738. auto genericTypeInst = (BfGenericTypeInstance*)unspecializedType;
  4739. BfTypeVector genericArgs;
  4740. for (auto genericArg : genericTypeInst->mTypeGenericArguments)
  4741. {
  4742. if (genericArg->IsUnspecializedType())
  4743. {
  4744. auto resolvedArg = ResolveGenericType(genericArg, methodGenericArguments, allowFail);
  4745. if (resolvedArg == NULL)
  4746. return NULL;
  4747. genericArgs.push_back(resolvedArg);
  4748. }
  4749. else
  4750. genericArgs.push_back(genericArg);
  4751. }
  4752. return ResolveTypeDef(genericTypeInst->mTypeDef, genericArgs);
  4753. }
  4754. if (unspecializedType->IsTuple())
  4755. {
  4756. auto tupleType = (BfTupleType*)unspecializedType;
  4757. Array<String> names;
  4758. BfTypeVector genericArgs;
  4759. bool hadChange = false;
  4760. for (auto& fieldInstance : tupleType->mFieldInstances)
  4761. {
  4762. names.push_back(fieldInstance.GetFieldDef()->mName);
  4763. auto origGenericArg = fieldInstance.mResolvedType;
  4764. auto newGenericArg = ResolveGenericType(origGenericArg, methodGenericArguments, allowFail);
  4765. if (newGenericArg == NULL)
  4766. return NULL;
  4767. if (newGenericArg != origGenericArg)
  4768. hadChange = true;
  4769. genericArgs.push_back(newGenericArg);
  4770. }
  4771. if (!hadChange)
  4772. return unspecializedType;
  4773. return CreateTupleType(genericArgs, names);
  4774. }
  4775. return unspecializedType;
  4776. }
  4777. BfType* BfModule::ResolveType(BfType* lookupType, BfPopulateType populateType)
  4778. {
  4779. BfResolvedTypeSet::LookupContext lookupCtx;
  4780. lookupCtx.mModule = this;
  4781. BfResolvedTypeSet::Entry* resolvedEntry = NULL;
  4782. bool inserted = mContext->mResolvedTypes.Insert(lookupType, &lookupCtx, &resolvedEntry);
  4783. if (!inserted)
  4784. {
  4785. auto resolvedTypeRef = resolvedEntry->mValue;
  4786. PopulateType(resolvedTypeRef, populateType);
  4787. return resolvedTypeRef;
  4788. }
  4789. if (lookupType->IsGenericTypeInstance())
  4790. CheckUnspecializedGenericType((BfGenericTypeInstance*)lookupType, populateType);
  4791. if (lookupType->IsTuple())
  4792. {
  4793. auto tupleType = (BfTupleType*)lookupType;
  4794. tupleType->Finish();
  4795. }
  4796. resolvedEntry->mValue = lookupType;
  4797. if (!InitType(lookupType, populateType))
  4798. return NULL;
  4799. return lookupType;
  4800. }
  4801. bool BfModule::IsUnboundGeneric(BfType* type)
  4802. {
  4803. if (type->IsVar())
  4804. return true;
  4805. if (!type->IsGenericParam())
  4806. return false;
  4807. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)type);
  4808. return (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0;
  4809. }
  4810. BfGenericParamInstance* BfModule::GetGenericParamInstance(BfGenericParamType* type)
  4811. {
  4812. if (type->mGenericParamKind == BfGenericParamKind_Method)
  4813. return mCurMethodInstance->mMethodInfoEx->mGenericParams[type->mGenericParamIdx];
  4814. // When we're evaluating a method, make sure the params refer back to that method context
  4815. auto curTypeInstance = mCurTypeInstance;
  4816. if (mCurMethodInstance != NULL)
  4817. curTypeInstance = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  4818. BfGenericTypeInstance* genericTypeInst = curTypeInstance->ToGenericTypeInstance();
  4819. if ((genericTypeInst->IsIncomplete()) && (genericTypeInst->mGenericParams.size() == 0))
  4820. {
  4821. // Set this to NULL so we don't recurse infinitely
  4822. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, NULL);
  4823. PopulateType(genericTypeInst, BfPopulateType_Declaration);
  4824. }
  4825. if (genericTypeInst->mGenericExtensionInfo != NULL)
  4826. {
  4827. auto activeTypeDef = GetActiveTypeDef(NULL, true);
  4828. if ((activeTypeDef->mTypeDeclaration != genericTypeInst->mTypeDef->mTypeDeclaration) && (activeTypeDef->IsExtension()))
  4829. {
  4830. BfGenericExtensionEntry* genericExEntry;
  4831. if (genericTypeInst->mGenericExtensionInfo->mExtensionMap.TryGetValue(activeTypeDef, &genericExEntry))
  4832. {
  4833. return genericExEntry->mGenericParams[type->mGenericParamIdx];
  4834. }
  4835. else
  4836. {
  4837. if ((mCompiler->mResolvePassData == NULL) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  4838. {
  4839. BF_FATAL("Invalid GetGenericParamInstance with extention");
  4840. }
  4841. }
  4842. }
  4843. }
  4844. BF_ASSERT(genericTypeInst != NULL);
  4845. return genericTypeInst->mGenericParams[type->mGenericParamIdx];
  4846. }
  4847. BfType* BfModule::ResolveTypeResult(BfTypeReference* typeRef, BfType* resolvedTypeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  4848. {
  4849. if (mCompiler->mIsResolveOnly)
  4850. {
  4851. BfSourceData* typeRefSource = NULL;
  4852. if (typeRef->IsTemporary())
  4853. {
  4854. BfTypeReference* checkTypeRef = typeRef;
  4855. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(checkTypeRef))
  4856. checkTypeRef = genericTypeRef->mElementType;
  4857. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(checkTypeRef))
  4858. typeRefSource = namedTypeRef->mNameNode->GetSourceData();
  4859. }
  4860. else
  4861. typeRefSource = typeRef->GetSourceData();
  4862. if ((mCompiler->mResolvePassData->mSourceClassifier != NULL) && (typeRefSource != NULL) && (mCompiler->mResolvePassData->mParser != NULL) &&
  4863. (typeRefSource == mCompiler->mResolvePassData->mParser->mSourceData))
  4864. {
  4865. //TODO: By only breaking out for "mIgnoreErrors", we classified elements (below) even when a resolvedTypeRef was not found!
  4866. //Why did we have this mIgnoreErrors check in there?
  4867. // if ((resolvedTypeRef == NULL) && (mIgnoreErrors))
  4868. if (resolvedTypeRef == NULL)
  4869. {
  4870. return NULL;
  4871. }
  4872. BfTypeInstance* resolvedTypeInstance = NULL;
  4873. if (resolvedTypeRef != NULL)
  4874. resolvedTypeInstance = resolvedTypeRef->ToTypeInstance();
  4875. bool isNamespace = false;
  4876. auto checkTypeRef = typeRef;
  4877. if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(checkTypeRef))
  4878. checkTypeRef = elementedTypeRef->mElementType;
  4879. if (!mIsInsideAutoComplete)
  4880. {
  4881. if ((resolvedTypeInstance != NULL) && (resolvedTypeInstance->mTypeDef->IsGlobalsContainer()))
  4882. {
  4883. isNamespace = true;
  4884. }
  4885. else
  4886. {
  4887. //TODO: This broke colorizing of inner expressions for things like "T2[T3]"
  4888. //mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(typeRef);
  4889. }
  4890. }
  4891. while (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(checkTypeRef))
  4892. {
  4893. StringView leftString = qualifiedTypeRef->mLeft->ToStringView();
  4894. BfSizedAtomComposite leftComposite;
  4895. bool isValid = mSystem->ParseAtomComposite(leftString, leftComposite);
  4896. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(qualifiedTypeRef->mRight, isNamespace ? BfSourceElementType_Namespace : BfSourceElementType_TypeRef);
  4897. if (resolvedTypeInstance == NULL)
  4898. {
  4899. if ((isValid) && (mCompiler->mSystem->ContainsNamespace(leftComposite, mCurTypeInstance->mTypeDef->mProject)))
  4900. isNamespace = true;
  4901. }
  4902. else if ((isValid) && (resolvedTypeInstance->mTypeDef->mNamespace.EndsWith(leftComposite)))
  4903. isNamespace = true;
  4904. checkTypeRef = qualifiedTypeRef->mLeft;
  4905. }
  4906. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(checkTypeRef))
  4907. {
  4908. auto checkNameNode = namedTypeRef->mNameNode;
  4909. while (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(checkNameNode))
  4910. {
  4911. StringView leftString = qualifiedNameNode->mLeft->ToStringView();
  4912. BfSizedAtomComposite leftComposite;
  4913. bool isValid = mSystem->ParseAtomComposite(leftString, leftComposite);
  4914. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(qualifiedNameNode->mRight, isNamespace ? BfSourceElementType_Namespace : BfSourceElementType_TypeRef);
  4915. if (resolvedTypeInstance == NULL)
  4916. {
  4917. if ((isValid) && (mCompiler->mSystem->ContainsNamespace(leftComposite, mCurTypeInstance->mTypeDef->mProject)))
  4918. isNamespace = true;
  4919. }
  4920. else if ((isValid) && (resolvedTypeInstance->mTypeDef->mNamespace.EndsWith(leftComposite)))
  4921. isNamespace = true;
  4922. checkNameNode = qualifiedNameNode->mLeft;
  4923. }
  4924. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(checkNameNode, isNamespace ? BfSourceElementType_Namespace : BfSourceElementType_TypeRef);
  4925. }
  4926. }
  4927. bool isGetDefinition = false;
  4928. BfAutoComplete* autoComplete = NULL;
  4929. if (mCompiler->IsAutocomplete())
  4930. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  4931. if (autoComplete != NULL)
  4932. {
  4933. isGetDefinition = autoComplete->mIsGetDefinition;
  4934. }
  4935. if (((mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Type) || (isGetDefinition)) &&
  4936. ((resolveFlags & BfResolveTypeRefFlag_FromIndirectSource) == 0) && (resolvedTypeRef != NULL) && (typeRefSource != NULL))
  4937. {
  4938. BfAstNode* elementTypeRef = typeRef;
  4939. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(elementTypeRef))
  4940. elementTypeRef = namedTypeRef->mNameNode;
  4941. if (elementTypeRef != NULL)
  4942. {
  4943. BfType* elementType = resolvedTypeRef;
  4944. if (BfTypeInstance* elementTypeInst = elementType->ToTypeInstance())
  4945. {
  4946. mCompiler->mResolvePassData->HandleTypeReference(elementTypeRef, elementTypeInst->mTypeDef);
  4947. if (mCompiler->IsAutocomplete())
  4948. {
  4949. BfAutoComplete* autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  4950. if ((autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(elementTypeRef)))
  4951. {
  4952. BfAstNode* baseNode = elementTypeRef;
  4953. while (true)
  4954. {
  4955. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(baseNode))
  4956. {
  4957. baseNode = qualifiedTypeRef->mRight;
  4958. }
  4959. else if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(baseNode))
  4960. {
  4961. baseNode = elementedTypeRef->mElementType;
  4962. }
  4963. else if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(baseNode))
  4964. {
  4965. baseNode = namedTypeRef->mNameNode;
  4966. }
  4967. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(baseNode))
  4968. {
  4969. baseNode = qualifiedNameNode->mRight;
  4970. }
  4971. else if (auto declTypeRef = BfNodeDynCast<BfDeclTypeRef>(baseNode))
  4972. {
  4973. baseNode = NULL;
  4974. break;
  4975. }
  4976. else
  4977. break;
  4978. }
  4979. if ((baseNode != NULL) && (autoComplete->IsAutocompleteNode(baseNode)))
  4980. {
  4981. // We didn't have this mDefType check before - why? We always want to catch the FIRST definition,
  4982. // so 'Type?' will catch on 'Type' and not 'Type?'
  4983. if ((autoComplete->mDefType == NULL) &&
  4984. (autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  4985. (autoComplete->mDefProp == NULL) && (elementTypeInst->mTypeDef->mTypeDeclaration != NULL))
  4986. {
  4987. autoComplete->mDefType = elementTypeInst->mTypeDef;
  4988. autoComplete->SetDefinitionLocation(elementTypeInst->mTypeDef->mTypeDeclaration->mNameNode);
  4989. }
  4990. }
  4991. }
  4992. }
  4993. }
  4994. }
  4995. }
  4996. }
  4997. if (resolvedTypeRef == NULL)
  4998. return NULL;
  4999. if (resolvedTypeRef->IsTuple())
  5000. {
  5001. // Add the fields from the tuple as references since those inner fields types would have been explicitly stated, so we need
  5002. // to make sure to record the current type instance as a referring type. This mostly matters for symbol renaming.
  5003. BfTupleType* payloadTupleType = (BfTupleType*)resolvedTypeRef;
  5004. for (auto& payloadFieldInst : payloadTupleType->mFieldInstances)
  5005. {
  5006. auto payloadFieldType = payloadFieldInst.mResolvedType;
  5007. AddDependency(payloadFieldType, mCurTypeInstance, BfDependencyMap::DependencyFlag_TypeReference);
  5008. }
  5009. }
  5010. else if (resolvedTypeRef->IsDelegateFromTypeRef() || resolvedTypeRef->IsFunctionFromTypeRef())
  5011. {
  5012. auto delegateType = (BfDelegateType*)resolvedTypeRef;
  5013. auto invokeMethod = GetDelegateInvokeMethod(delegateType);
  5014. AddDependency(invokeMethod->mReturnType, mCurTypeInstance, BfDependencyMap::DependencyFlag_TypeReference);
  5015. for (auto& param : invokeMethod->mParams)
  5016. {
  5017. AddDependency(param.mResolvedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_TypeReference);
  5018. }
  5019. }
  5020. BfGenericTypeInstance* genericTypeInstance = NULL;
  5021. if (resolvedTypeRef != NULL)
  5022. genericTypeInstance = resolvedTypeRef->ToGenericTypeInstance();
  5023. bool hadError = false;
  5024. hadError = !PopulateType(resolvedTypeRef, populateType);
  5025. if ((genericTypeInstance != NULL) && (populateType > BfPopulateType_Identity))
  5026. {
  5027. if (((genericTypeInstance->mHadValidateErrors) || (!genericTypeInstance->mValidatedGenericConstraints) || (genericTypeInstance->mIsUnspecializedVariation)) &&
  5028. ((mCurMethodInstance == NULL) || (!mCurMethodInstance->mIsUnspecializedVariation)) &&
  5029. ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsUnspecializedTypeVariation())))
  5030. ValidateGenericConstraints(typeRef, genericTypeInstance, false);
  5031. }
  5032. if (populateType != BfPopulateType_IdentityNoRemapAlias)
  5033. {
  5034. while ((resolvedTypeRef != NULL) && (resolvedTypeRef->IsTypeAlias()))
  5035. {
  5036. if (mCurTypeInstance != NULL)
  5037. AddDependency(resolvedTypeRef, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  5038. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  5039. }
  5040. }
  5041. return resolvedTypeRef;
  5042. }
  5043. void BfModule::ShowAmbiguousTypeError(BfAstNode* refNode, BfTypeDef* typeDef, BfTypeDef* otherTypeDef)
  5044. {
  5045. BfType* type = ResolveTypeDef(typeDef, BfPopulateType_Identity);
  5046. if (type == NULL)
  5047. return;
  5048. BfType* otherType = ResolveTypeDef(otherTypeDef, BfPopulateType_Identity);
  5049. if (otherType == NULL)
  5050. return;
  5051. auto error = Fail(StrFormat("'%s' is an ambiguous reference between '%s' and '%s'",
  5052. refNode->ToString().c_str(), TypeToString(type, BfTypeNameFlags_None).c_str(), TypeToString(otherType, BfTypeNameFlags_None).c_str()), refNode); // CS0104
  5053. if (error != NULL)
  5054. {
  5055. mCompiler->mPassInstance->MoreInfo("See first definition", typeDef->mTypeDeclaration->mNameNode);
  5056. mCompiler->mPassInstance->MoreInfo("See second definition", otherTypeDef->mTypeDeclaration->mNameNode);
  5057. }
  5058. }
  5059. void BfModule::ShowGenericArgCountError(BfTypeReference* typeRef, int wantedGenericParams)
  5060. {
  5061. BfGenericInstanceTypeRef* genericTypeInstRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef);
  5062. BfAstNode* lastNode = typeRef;
  5063. int genericArgDiffCount;
  5064. if (genericTypeInstRef != NULL)
  5065. {
  5066. genericArgDiffCount = (int)genericTypeInstRef->mGenericArguments.size() - wantedGenericParams;
  5067. lastNode = genericTypeInstRef->mOpenChevron;
  5068. if (genericTypeInstRef->mCloseChevron != NULL)
  5069. lastNode = genericTypeInstRef->mCloseChevron;
  5070. if (genericTypeInstRef->mGenericArguments.size() > wantedGenericParams)
  5071. {
  5072. lastNode = genericTypeInstRef->mGenericArguments[wantedGenericParams];
  5073. if (genericArgDiffCount == 1)
  5074. Fail("Too many generic parameters, expected one fewer", lastNode);
  5075. else
  5076. Fail(StrFormat("Too many generic parameters, expected %d fewer", genericArgDiffCount), lastNode);
  5077. return;
  5078. }
  5079. }
  5080. else
  5081. genericArgDiffCount = -wantedGenericParams;
  5082. if (wantedGenericParams == 1)
  5083. Fail("Too few generic parameters, expected one more", lastNode);
  5084. else
  5085. Fail(StrFormat("Too few generic parameters, expected %d more", -genericArgDiffCount), lastNode);
  5086. }
  5087. BfTypeDef* BfModule::GetActiveTypeDef(BfTypeInstance* typeInstanceOverride, bool useMixinDecl)
  5088. {
  5089. BfTypeDef* useTypeDef = NULL;
  5090. BfTypeInstance* typeInstance = (typeInstanceOverride != NULL) ? typeInstanceOverride : mCurTypeInstance;
  5091. if (typeInstance != NULL)
  5092. useTypeDef = typeInstance->mTypeDef;
  5093. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (useMixinDecl))
  5094. useTypeDef = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType;
  5095. else if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType != NULL))
  5096. useTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  5097. else if (mContext->mCurTypeState != NULL)
  5098. {
  5099. if ((mContext->mCurTypeState->mCurFieldDef != NULL) && (mContext->mCurTypeState->mCurFieldDef->mDeclaringType != NULL))
  5100. useTypeDef = mContext->mCurTypeState->mCurFieldDef->mDeclaringType;
  5101. else if (mContext->mCurTypeState->mCurTypeDef != NULL)
  5102. useTypeDef = mContext->mCurTypeState->mCurTypeDef;
  5103. }
  5104. return useTypeDef;
  5105. }
  5106. BfTypeDef* BfModule::FindTypeDefRaw(const BfAtomComposite& findName, int numGenericArgs, BfTypeInstance* typeInstance, BfTypeDef* useTypeDef, BfTypeLookupError* error)
  5107. {
  5108. if ((findName.mSize == 1) && (findName.mParts[0]->mIsSystemType))
  5109. {
  5110. //BP_ZONE("BfModule::FindTypeDefRaw_1");
  5111. return mSystem->FindTypeDef(findName, 0, useTypeDef->mProject);
  5112. }
  5113. BfTypeInstance* skipCheckBaseType = NULL;
  5114. if ((mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mCurBaseTypeRef != NULL))
  5115. skipCheckBaseType = mContext->mCurTypeState->mTypeInstance;
  5116. BfTypeDefLookupContext lookupCtx;
  5117. bool allowPrivate = true;
  5118. int curPri = 1000;
  5119. auto checkTypeInst = typeInstance;
  5120. BfTypeDef* protErrorTypeDef = NULL;
  5121. BfTypeInstance* protErrorOuterType = NULL;
  5122. if (!lookupCtx.HasValidMatch())
  5123. {
  5124. std::function<bool(BfTypeInstance*)> _CheckType = [&](BfTypeInstance* typeInstance)
  5125. {
  5126. auto checkTypeInst = typeInstance;
  5127. allowPrivate = true;
  5128. while (checkTypeInst != NULL)
  5129. {
  5130. if (!checkTypeInst->mTypeDef->mNestedTypes.IsEmpty())
  5131. {
  5132. if (mSystem->FindTypeDef(findName, numGenericArgs, useTypeDef->mProject, checkTypeInst->mTypeDef->mFullNameEx, allowPrivate, &lookupCtx))
  5133. {
  5134. if (lookupCtx.HasValidMatch())
  5135. return true;
  5136. if ((lookupCtx.mBestTypeDef->mProtection == BfProtection_Private) && (!allowPrivate))
  5137. {
  5138. protErrorTypeDef = lookupCtx.mBestTypeDef;
  5139. protErrorOuterType = checkTypeInst;
  5140. }
  5141. }
  5142. }
  5143. if (checkTypeInst == skipCheckBaseType)
  5144. break;
  5145. checkTypeInst = GetBaseType(checkTypeInst);
  5146. allowPrivate = false;
  5147. }
  5148. checkTypeInst = typeInstance;
  5149. allowPrivate = true;
  5150. while (checkTypeInst != NULL)
  5151. {
  5152. auto outerTypeInst = GetOuterType(checkTypeInst);
  5153. if (outerTypeInst != NULL)
  5154. {
  5155. if (_CheckType(outerTypeInst))
  5156. return true;
  5157. }
  5158. if (checkTypeInst == skipCheckBaseType)
  5159. break;
  5160. checkTypeInst = GetBaseType(checkTypeInst);
  5161. allowPrivate = false;
  5162. }
  5163. return false;
  5164. };
  5165. _CheckType(typeInstance);
  5166. }
  5167. if (!lookupCtx.HasValidMatch())
  5168. {
  5169. if (mSystem->mTypeDefs.TryGet(findName, NULL))
  5170. mSystem->FindTypeDef(findName, numGenericArgs, useTypeDef->mProject, BfAtomComposite(), allowPrivate, &lookupCtx);
  5171. for (auto& checkNamespace : useTypeDef->mNamespaceSearch)
  5172. {
  5173. BfAtom* atom = findName.mParts[0];
  5174. BfAtom* prevAtom = checkNamespace.mParts[checkNamespace.mSize - 1];
  5175. if (atom->mPrevNamesMap.ContainsKey(prevAtom))
  5176. mSystem->FindTypeDef(findName, numGenericArgs, useTypeDef->mProject, checkNamespace, allowPrivate, &lookupCtx);
  5177. }
  5178. }
  5179. if ((error != NULL) && (lookupCtx.mAmbiguousTypeDef != NULL))
  5180. {
  5181. if (error->mErrorKind == BfTypeLookupError::BfErrorKind_None)
  5182. error->mErrorKind = BfTypeLookupError::BfErrorKind_Ambiguous;
  5183. error->mAmbiguousTypeDef = lookupCtx.mAmbiguousTypeDef;
  5184. if (error->mRefNode != NULL)
  5185. ShowAmbiguousTypeError(error->mRefNode, lookupCtx.mBestTypeDef, lookupCtx.mAmbiguousTypeDef);
  5186. }
  5187. if ((protErrorTypeDef != NULL) && (lookupCtx.mBestTypeDef == protErrorTypeDef) && (error != NULL) && (error->mRefNode != NULL))
  5188. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(protErrorOuterType).c_str(), findName.ToString().c_str()), error->mRefNode); // CS0122
  5189. return lookupCtx.mBestTypeDef;
  5190. }
  5191. BfTypeDef* BfModule::FindTypeDef(const BfAtomComposite& findName, int numGenericArgs, BfTypeInstance* typeInstanceOverride, BfTypeLookupError* error)
  5192. {
  5193. BP_ZONE("BfModule::FindTypeDef_1");
  5194. BfTypeInstance* typeInstance = (typeInstanceOverride != NULL) ? typeInstanceOverride : mCurTypeInstance;
  5195. if (typeInstance == NULL)
  5196. {
  5197. BfProject* project = NULL;
  5198. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mParser != NULL))
  5199. project = mCompiler->mResolvePassData->mParser->mProject;
  5200. BP_ZONE("System.FindTypeDef_2");
  5201. BfTypeDef* ambiguousTypeDef = NULL;
  5202. BfTypeDef *result = mSystem->FindTypeDef(findName, numGenericArgs, project, Array<BfAtomComposite>(), &ambiguousTypeDef);
  5203. if ((ambiguousTypeDef != NULL) && (error != NULL))
  5204. {
  5205. error->mErrorKind = BfTypeLookupError::BfErrorKind_Ambiguous;
  5206. error->mAmbiguousTypeDef = ambiguousTypeDef;
  5207. if (error->mRefNode != NULL)
  5208. ShowAmbiguousTypeError(error->mRefNode, result, ambiguousTypeDef);
  5209. }
  5210. return result;
  5211. }
  5212. auto useTypeDef = GetActiveTypeDef(typeInstanceOverride, true);
  5213. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  5214. {
  5215. if (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(useTypeDef))
  5216. return FindTypeDefRaw(findName, numGenericArgs, typeInstance, useTypeDef, error);
  5217. }
  5218. BfTypeLookupEntry typeLookupEntry;
  5219. typeLookupEntry.mName = findName;
  5220. typeLookupEntry.mNumGenericParams = numGenericArgs;
  5221. typeLookupEntry.mUseTypeDef = useTypeDef;
  5222. BfTypeLookupEntry* typeLookupEntryPtr = NULL;
  5223. BfTypeLookupResult* resultPtr = NULL;
  5224. if (typeInstance->mLookupResults.TryAdd(typeLookupEntry, &typeLookupEntryPtr, &resultPtr))
  5225. {
  5226. typeLookupEntryPtr->mAtomUpdateIdx = typeLookupEntry.mName.GetAtomUpdateIdx();
  5227. // FindTypeDefRaw may re-enter when finding base types, so we need to expect that resultPtr can change
  5228. resultPtr->mForceLookup = true;
  5229. resultPtr->mTypeDef = NULL;
  5230. int prevAllocSize = (int)typeInstance->mLookupResults.size();
  5231. BfTypeLookupError localError;
  5232. BfTypeLookupError* errorPtr = (error != NULL) ? error : &localError;
  5233. auto typeDef = FindTypeDefRaw(findName, numGenericArgs, typeInstance, useTypeDef, errorPtr);
  5234. if (prevAllocSize != typeInstance->mLookupResults.size())
  5235. {
  5236. bool found = typeInstance->mLookupResults.TryGetValue(typeLookupEntry, &resultPtr);
  5237. BF_ASSERT(found);
  5238. }
  5239. resultPtr->mTypeDef = typeDef;
  5240. resultPtr->mForceLookup = errorPtr->mErrorKind != BfTypeLookupError::BfErrorKind_None;
  5241. return typeDef;
  5242. }
  5243. else
  5244. {
  5245. if (resultPtr->mForceLookup)
  5246. return FindTypeDefRaw(findName, numGenericArgs, typeInstance, useTypeDef, error);
  5247. else
  5248. return resultPtr->mTypeDef;
  5249. }
  5250. }
  5251. BfTypeDef* BfModule::FindTypeDef(const StringImpl& typeName, int numGenericArgs, BfTypeInstance* typeInstanceOverride, BfTypeLookupError* error)
  5252. {
  5253. BP_ZONE("BfModule::FindTypeDef_4");
  5254. BfSizedAtomComposite findName;
  5255. if (!mSystem->ParseAtomComposite(typeName, findName))
  5256. return NULL;
  5257. auto result = FindTypeDef(findName, numGenericArgs, typeInstanceOverride, error);
  5258. BF_ASSERT((result == NULL) || (result->mTypeCode != BfTypeCode_Extension));
  5259. return result;
  5260. }
  5261. BfTypeDef* BfModule::FindTypeDef(BfTypeReference* typeRef, BfTypeInstance* typeInstanceOverride, BfTypeLookupError* error, int numGenericParams)
  5262. {
  5263. BP_ZONE("BfModule::FindTypeDef_5");
  5264. if (auto typeDefTypeRef = BfNodeDynCast<BfDirectTypeDefReference>(typeRef))
  5265. {
  5266. if (typeDefTypeRef->mTypeDef != NULL)
  5267. return mSystem->FilterDeletedTypeDef(typeDefTypeRef->mTypeDef);
  5268. }
  5269. //TODO: When does this get called?
  5270. if (auto elementedType = BfNodeDynCast<BfElementedTypeRef>(typeRef))
  5271. return FindTypeDef(elementedType->mElementType, typeInstanceOverride, error);
  5272. BF_ASSERT(typeRef->IsA<BfNamedTypeReference>() || typeRef->IsA<BfQualifiedTypeReference>() || typeRef->IsA<BfDirectStrTypeReference>());
  5273. auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef);
  5274. StringView findNameStr;
  5275. if (namedTypeRef != NULL)
  5276. findNameStr = namedTypeRef->mNameNode->ToStringView();
  5277. else
  5278. {
  5279. auto directStrTypeDef = BfNodeDynCastExact<BfDirectStrTypeReference>(typeRef);
  5280. if (directStrTypeDef != NULL)
  5281. findNameStr = directStrTypeDef->mTypeName;
  5282. else
  5283. BF_FATAL("Error?");
  5284. }
  5285. if (findNameStr.mLength == 6)
  5286. {
  5287. if (findNameStr == "object")
  5288. {
  5289. findNameStr = "System.Object";
  5290. Fail("'object' alias not supported, use 'Object'", typeRef);
  5291. }
  5292. else if (findNameStr == "string")
  5293. {
  5294. findNameStr = "System.String";
  5295. Fail("'string' alias not supported, use 'String'", typeRef);
  5296. }
  5297. }
  5298. BfSizedAtomComposite findName;
  5299. if (!mSystem->ParseAtomComposite(findNameStr, findName))
  5300. {
  5301. return NULL;
  5302. }
  5303. #ifdef BF_AST_HAS_PARENT_MEMBER
  5304. if (auto parentGenericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef->mParent))
  5305. {
  5306. if (parentGenericTypeRef->mElementType == typeRef)
  5307. BF_ASSERT(numGenericParams == parentGenericTypeRef->GetGenericArgCount());
  5308. }
  5309. #endif
  5310. auto typeDef = FindTypeDef(findName, numGenericParams, typeInstanceOverride, error);
  5311. //TYPEDEF if (namedTypeRef != NULL)
  5312. // namedTypeRef->mTypeDef = typeDef;
  5313. return typeDef;
  5314. }
  5315. void BfModule::CheckTypeRefFixit(BfAstNode* typeRef, const char* appendName)
  5316. {
  5317. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((typeRef))))
  5318. {
  5319. String typeName = typeRef->ToString();
  5320. if (appendName != NULL)
  5321. typeName += appendName;
  5322. std::set<String> fixitNamespaces;
  5323. //TODO: Do proper value for numGenericArgs
  5324. //mSystem->FindFixitNamespaces(typeName, -1, typeRef->GetSourceData()->mProject, fixitNamespaces);
  5325. mSystem->FindFixitNamespaces(typeName, -1, mCompiler->mResolvePassData->mParser->mProject, fixitNamespaces);
  5326. int insertLoc = 0;
  5327. BfUsingFinder usingFinder;
  5328. usingFinder.VisitMembers(typeRef->GetSourceData()->mRootNode);
  5329. for (auto& namespaceStr : fixitNamespaces)
  5330. {
  5331. BfParserData* parser = typeRef->GetSourceData()->ToParserData();
  5332. if (parser != NULL)
  5333. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("using %s;\tusing|%s|%d||using %s;", namespaceStr.c_str(), parser->mFileName.c_str(), usingFinder.mLastIdx, namespaceStr.c_str()).c_str()));
  5334. }
  5335. }
  5336. }
  5337. void BfModule::CheckIdentifierFixit(BfAstNode* node)
  5338. {
  5339. //TODO: Check globals, possibly spelling mistakes?
  5340. }
  5341. void BfModule::TypeRefNotFound(BfTypeReference* typeRef, const char* appendName)
  5342. {
  5343. if (typeRef->IsTemporary())
  5344. return;
  5345. Fail("Type could not be found (are you missing a using directive or library reference?)", typeRef);
  5346. if (!mIgnoreErrors)
  5347. {
  5348. while (auto elementedType = BfNodeDynCast<BfElementedTypeRef>(typeRef))
  5349. typeRef = elementedType->mElementType;
  5350. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef))
  5351. {
  5352. String findNameStr = namedTypeRef->mNameNode->ToString();
  5353. if (appendName != NULL)
  5354. findNameStr += appendName;
  5355. BfSizedAtomComposite findName;
  5356. if ((!mSystem->ParseAtomComposite(findNameStr, findName)) && (mCurTypeInstance != NULL))
  5357. {
  5358. //BfTypeInstance* typeInstance = (typeInstanceOverride != NULL) ? typeInstanceOverride : mCurTypeInstance;
  5359. // We don't need a typeInstanceOverride because that is used to lookup references
  5360. // from mixins, but it's the type using the mixin (mCurTypeInstance) that needs
  5361. // rebuilding if the lookup fails
  5362. BfTypeInstance* typeInstance = mCurTypeInstance;
  5363. BfTypeLookupEntry typeLookupEntry;
  5364. typeLookupEntry.mNumGenericParams = 0;
  5365. typeLookupEntry.mAtomUpdateIdx = mSystem->mAtomUpdateIdx;
  5366. typeInstance->mLookupResults.TryAdd(typeLookupEntry, BfTypeLookupResult());
  5367. }
  5368. }
  5369. }
  5370. CheckTypeRefFixit(typeRef, appendName);
  5371. }
  5372. bool BfModule::ValidateTypeWildcard(BfTypeReference* typeRef, bool isAttributeRef)
  5373. {
  5374. if (typeRef == NULL)
  5375. return false;
  5376. if (auto wildcardTypeRef = BfNodeDynCast<BfWildcardTypeReference>(typeRef))
  5377. return true;
  5378. StringT<128> nameStr;
  5379. typeRef->ToString(nameStr);
  5380. if (isAttributeRef)
  5381. nameStr.Append("Attribute");
  5382. auto typeDef = mSystem->FindTypeDef(nameStr, (BfProject*)NULL);
  5383. if ((typeDef != NULL) && (typeDef->mGenericParamDefs.IsEmpty()))
  5384. return true;
  5385. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  5386. {
  5387. if (qualifiedTypeRef->mLeft == NULL)
  5388. return false;
  5389. StringT<128> leftNameStr;
  5390. BfType* leftType = NULL;
  5391. BfAtomComposite leftComposite;
  5392. qualifiedTypeRef->mLeft->ToString(leftNameStr);
  5393. if (!mSystem->ParseAtomComposite(leftNameStr, leftComposite))
  5394. return false;
  5395. if (auto wildcardTypeRef = BfNodeDynCast<BfWildcardTypeReference>(qualifiedTypeRef->mRight))
  5396. {
  5397. if (mSystem->ContainsNamespace(leftComposite, NULL))
  5398. return true;
  5399. return ValidateTypeWildcard(qualifiedTypeRef->mLeft, false);
  5400. }
  5401. }
  5402. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  5403. {
  5404. StringT<128> nameStr;
  5405. genericTypeRef->mElementType->ToString(nameStr);
  5406. auto typeDef = mSystem->FindTypeDef(nameStr, (int)genericTypeRef->mGenericArguments.size(), NULL);
  5407. if (typeDef == NULL)
  5408. return false;
  5409. if (typeDef->mGenericParamDefs.size() != genericTypeRef->GetGenericArgCount())
  5410. return false;
  5411. for (auto genericArgTypeRef : genericTypeRef->mGenericArguments)
  5412. {
  5413. if ((genericTypeRef != NULL) && (!ValidateTypeWildcard(genericArgTypeRef, false)))
  5414. return false;
  5415. }
  5416. return true;
  5417. }
  5418. if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(typeRef))
  5419. {
  5420. return ValidateTypeWildcard(elementedTypeRef->mElementType, false);
  5421. }
  5422. return false;
  5423. }
  5424. //int sResolveTypeRefIdx = 0;
  5425. BfTypedValue BfModule::TryLookupGenericConstVaue(BfIdentifierNode* identifierNode, BfType* expectingType)
  5426. {
  5427. BfTypeInstance* contextTypeInstance = mCurTypeInstance;
  5428. BfMethodInstance* contextMethodInstance = mCurMethodInstance;
  5429. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  5430. {
  5431. contextTypeInstance = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  5432. contextMethodInstance = mCurMethodState->mMixinState->mMixinMethodInstance;
  5433. }
  5434. BfTypeDef* curTypeDef = NULL;
  5435. if (contextTypeInstance != NULL)
  5436. {
  5437. curTypeDef = contextTypeInstance->mTypeDef;
  5438. StringT<128> findName;
  5439. identifierNode->ToString(findName);
  5440. auto genericCheckTypeInstance = contextTypeInstance;
  5441. if (contextTypeInstance->IsBoxed())
  5442. genericCheckTypeInstance = contextTypeInstance->GetUnderlyingType()->ToTypeInstance();
  5443. bool doFakeVal = false;
  5444. if (genericCheckTypeInstance->IsUnspecializedTypeVariation())
  5445. {
  5446. genericCheckTypeInstance = GetUnspecializedTypeInstance(genericCheckTypeInstance);
  5447. doFakeVal = true;
  5448. }
  5449. BfGenericParamDef* genericParamDef = NULL;
  5450. BfType* genericParamResult = NULL;
  5451. BfType* genericTypeConstraint = NULL;
  5452. bool disallowConstExprValue = false;
  5453. if ((genericCheckTypeInstance != NULL) && (genericCheckTypeInstance->IsGenericTypeInstance()))
  5454. {
  5455. auto genericTypeInst = (BfGenericTypeInstance*)genericCheckTypeInstance;
  5456. auto* genericParams = &curTypeDef->mGenericParamDefs;
  5457. if (genericTypeInst->mGenericExtensionInfo != NULL)
  5458. {
  5459. auto activeTypeDef = GetActiveTypeDef(NULL, true);
  5460. genericParams = &activeTypeDef->mGenericParamDefs;
  5461. }
  5462. for (int genericParamIdx = (int)genericParams->size() - 1; genericParamIdx >= 0; genericParamIdx--)
  5463. {
  5464. auto checkGenericParamDef = (*genericParams)[genericParamIdx];
  5465. String genericName = checkGenericParamDef->mName;
  5466. if (genericName == findName)
  5467. {
  5468. genericParamDef = checkGenericParamDef;
  5469. genericParamResult = genericTypeInst->mTypeGenericArguments[genericParamIdx];
  5470. genericTypeConstraint = genericTypeInst->mGenericParams[genericParamIdx]->mTypeConstraint;
  5471. HandleTypeGenericParamRef(identifierNode, genericTypeInst->mTypeDef, genericParamIdx);
  5472. }
  5473. }
  5474. }
  5475. if ((contextMethodInstance != NULL) && (genericParamResult == NULL))
  5476. {
  5477. for (int genericParamIdx = (int)contextMethodInstance->mMethodDef->mGenericParams.size() - 1; genericParamIdx >= 0; genericParamIdx--)
  5478. {
  5479. auto checkGenericParamDef = contextMethodInstance->mMethodDef->mGenericParams[genericParamIdx];
  5480. String genericName = checkGenericParamDef->mName;
  5481. if (genericName == findName)
  5482. {
  5483. genericParamDef = checkGenericParamDef;
  5484. genericParamResult = contextMethodInstance->mMethodInfoEx->mMethodGenericArguments[genericParamIdx];
  5485. genericTypeConstraint = contextMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx]->mTypeConstraint;
  5486. HandleMethodGenericParamRef(identifierNode, contextMethodInstance->GetOwner()->mTypeDef, contextMethodInstance->mMethodDef, genericParamIdx);
  5487. }
  5488. }
  5489. }
  5490. if (genericParamResult != NULL)
  5491. {
  5492. auto typeRefSource = identifierNode->GetSourceData();
  5493. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (typeRefSource != NULL) && (typeRefSource == mCompiler->mResolvePassData->mParser->mSourceData))
  5494. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(identifierNode, BfSourceElementType_TypeRef);
  5495. if (genericParamResult->IsConstExprValue())
  5496. {
  5497. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericParamResult;
  5498. BfExprEvaluator exprEvaluator(this);
  5499. exprEvaluator.mExpectingType = genericTypeConstraint;
  5500. exprEvaluator.GetLiteral(identifierNode, constExprValueType->mValue);
  5501. // We don't want to validate type here
  5502. return exprEvaluator.mResult;
  5503. }
  5504. else if (genericParamResult->IsGenericParam())
  5505. {
  5506. if ((doFakeVal) && (genericTypeConstraint != NULL))
  5507. {
  5508. return BfTypedValue(mBfIRBuilder->GetFakeVal(), genericTypeConstraint);
  5509. }
  5510. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) == 0)
  5511. Fail("Only const generic parameters can be used a value", identifierNode);
  5512. if ((genericTypeConstraint != NULL) && (expectingType != NULL))
  5513. {
  5514. if (!CanImplicitlyCast(BfTypedValue(mBfIRBuilder->GetFakeVal(), genericTypeConstraint), expectingType))
  5515. {
  5516. Fail(StrFormat("Generic constraint '%s' is not convertible to 'int'", TypeToString(genericTypeConstraint).c_str()), identifierNode);
  5517. }
  5518. }
  5519. BfTypedValue result;
  5520. result.mType = genericParamResult;
  5521. result.mKind = BfTypedValueKind_GenericConstValue;
  5522. return result;
  5523. }
  5524. }
  5525. }
  5526. return BfTypedValue();
  5527. }
  5528. BfType* BfModule::ResolveTypeRef(BfTypeReference* typeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  5529. {
  5530. BP_ZONE("BfModule::ResolveTypeRef");
  5531. if (typeRef == NULL)
  5532. {
  5533. AssertErrorState();
  5534. return NULL;
  5535. }
  5536. if (resolveFlags & BfResolveTypeRefFlag_AutoComplete)
  5537. {
  5538. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags & ~BfResolveTypeRefFlag_AutoComplete);
  5539. auto autoComplete = mCompiler->GetAutoComplete();
  5540. if (autoComplete != NULL)
  5541. autoComplete->CheckTypeRef(typeRef, false);
  5542. }
  5543. if ((resolveFlags & BfResolveTypeRefFlag_AllowRef) == 0)
  5544. {
  5545. if (auto refTypeRef = BfNodeDynCast<BfRefTypeRef>(typeRef))
  5546. {
  5547. const char* refTypeStr = BfTokenToString(refTypeRef->mRefToken->mToken);
  5548. Fail(StrFormat("Invalid use of '%s'. Only method parameters, return types, and local variables can be declared as %s types", refTypeStr, refTypeStr), refTypeRef->mRefToken);
  5549. return ResolveTypeRef(refTypeRef->mElementType);
  5550. }
  5551. }
  5552. if (auto directTypeRef = BfNodeDynCastExact<BfDirectTypeReference>(typeRef))
  5553. {
  5554. return directTypeRef->mType;
  5555. }
  5556. if (auto dotType = BfNodeDynCastExact<BfDotTypeReference>(typeRef))
  5557. {
  5558. Fail("Invalid use of '.'", typeRef);
  5559. return NULL;
  5560. }
  5561. if (auto varRefType = BfNodeDynCastExact<BfVarRefTypeReference>(typeRef))
  5562. {
  5563. Fail("Invalid use of 'var ref'. Generally references are generated with a 'var' declaration with 'ref' applied to the initializer", typeRef);
  5564. return NULL;
  5565. }
  5566. if (mNoResolveGenericParams)
  5567. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoResolveGenericParam);
  5568. SetAndRestoreValue<bool> prevNoResolveGenericParams(mNoResolveGenericParams, (resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0);
  5569. //
  5570. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags & ~BfResolveTypeRefFlag_NoResolveGenericParam);
  5571. BfTypeInstance* contextTypeInstance = mCurTypeInstance;
  5572. BfMethodInstance* contextMethodInstance = mCurMethodInstance;
  5573. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  5574. {
  5575. contextTypeInstance = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  5576. contextMethodInstance = mCurMethodState->mMixinState->mMixinMethodInstance;
  5577. }
  5578. BfTypeDef* curTypeDef = NULL;
  5579. if (contextTypeInstance != NULL)
  5580. {
  5581. curTypeDef = contextTypeInstance->mTypeDef;
  5582. // Check generics first
  5583. auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(typeRef);
  5584. auto directStrTypeRef = BfNodeDynCastExact<BfDirectStrTypeReference>(typeRef);
  5585. if (((namedTypeRef != NULL) && (namedTypeRef->mNameNode != NULL)) || (directStrTypeRef != NULL))
  5586. {
  5587. StringT<128> findName;
  5588. if (namedTypeRef != NULL)
  5589. namedTypeRef->mNameNode->ToString(findName);
  5590. else
  5591. findName = directStrTypeRef->mTypeName;
  5592. if (findName == "Self")
  5593. {
  5594. BfType* selfType = mCurTypeInstance;
  5595. if (selfType->IsInterface()) // For interfaces, 'Self' refers to the identity of the implementing type, so we use a placeholder
  5596. return GetPrimitiveType(BfTypeCode_Self);
  5597. else
  5598. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_FromIndirectSource);
  5599. if (selfType->IsBoxed())
  5600. selfType = selfType->GetUnderlyingType();
  5601. if ((resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0)
  5602. {
  5603. if ((selfType->IsSpecializedType()) || (selfType->IsUnspecializedTypeVariation()))
  5604. selfType = ResolveTypeDef(selfType->ToTypeInstance()->mTypeDef, populateType);
  5605. }
  5606. if (selfType == NULL)
  5607. {
  5608. Fail("'Self' type is not usable here", typeRef);
  5609. }
  5610. return ResolveTypeResult(typeRef, selfType, populateType, resolveFlags);
  5611. }
  5612. else if (findName == "SelfBase")
  5613. {
  5614. BfType* selfType = mCurTypeInstance;
  5615. if (selfType->IsInterface())
  5616. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_FromIndirectSource);
  5617. if (selfType->IsBoxed())
  5618. selfType = selfType->GetUnderlyingType();
  5619. if ((resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0)
  5620. {
  5621. if ((selfType->IsSpecializedType()) || (selfType->IsUnspecializedTypeVariation()))
  5622. selfType = ResolveTypeDef(selfType->ToTypeInstance()->mTypeDef, populateType);
  5623. }
  5624. BfType* baseType = NULL;
  5625. if (selfType != NULL)
  5626. {
  5627. if (selfType->IsTypedPrimitive())
  5628. baseType = selfType->GetUnderlyingType();
  5629. else
  5630. {
  5631. auto selfTypeInst = selfType->ToTypeInstance();
  5632. if (selfTypeInst != NULL)
  5633. {
  5634. baseType = selfTypeInst->mBaseType;
  5635. }
  5636. }
  5637. }
  5638. if (baseType == NULL)
  5639. {
  5640. Fail("'SelfBase' type is not usable here", typeRef);
  5641. }
  5642. return ResolveTypeResult(typeRef, baseType, populateType, resolveFlags);
  5643. }
  5644. else if (findName == "ExpectedType")
  5645. {
  5646. Fail("'ExpectedType' is not usable here", typeRef);
  5647. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  5648. }
  5649. auto genericCheckTypeInstance = contextTypeInstance;
  5650. if (contextTypeInstance->IsBoxed())
  5651. genericCheckTypeInstance = contextTypeInstance->GetUnderlyingType()->ToTypeInstance();
  5652. BfGenericParamDef* genericParamDef = NULL;
  5653. BfType* genericParamResult = NULL;
  5654. bool disallowConstExprValue = false;
  5655. if ((genericCheckTypeInstance != NULL) && (genericCheckTypeInstance->IsGenericTypeInstance()))
  5656. {
  5657. auto genericTypeInst = (BfGenericTypeInstance*)genericCheckTypeInstance;
  5658. auto* genericParams = &curTypeDef->mGenericParamDefs;
  5659. if (genericTypeInst->mGenericExtensionInfo != NULL)
  5660. {
  5661. auto activeTypeDef = GetActiveTypeDef(NULL, true);
  5662. genericParams = &activeTypeDef->mGenericParamDefs;
  5663. }
  5664. for (int genericParamIdx = (int)genericParams->size() - 1; genericParamIdx >= 0; genericParamIdx--)
  5665. {
  5666. auto checkGenericParamDef = (*genericParams)[genericParamIdx];
  5667. String genericName = checkGenericParamDef->mName;
  5668. if (genericName == findName)
  5669. {
  5670. genericParamDef = checkGenericParamDef;
  5671. if (((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  5672. ((resolveFlags & BfResolveTypeRefFlag_AllowGenericTypeParamConstValue) == 0))
  5673. disallowConstExprValue = true;
  5674. HandleTypeGenericParamRef(typeRef, curTypeDef, genericParamIdx);
  5675. if ((resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0)
  5676. return GetGenericParamType(BfGenericParamKind_Type, genericParamIdx);
  5677. else
  5678. {
  5679. SetAndRestoreValue<BfGetSymbolReferenceKind> prevSymbolRefKind;
  5680. if (mCompiler->mResolvePassData != NULL) // Don't add these typeRefs, they are indirect
  5681. prevSymbolRefKind.Init(mCompiler->mResolvePassData->mGetSymbolReferenceKind, BfGetSymbolReferenceKind_None);
  5682. genericParamResult = genericTypeInst->mTypeGenericArguments[genericParamIdx];
  5683. if ((genericParamResult != NULL) &&
  5684. (genericParamResult->IsConstExprValue()) &&
  5685. ((resolveFlags & BfResolveTypeRefFlag_AllowGenericTypeParamConstValue) == 0))
  5686. disallowConstExprValue = true;
  5687. }
  5688. }
  5689. }
  5690. }
  5691. if ((contextMethodInstance != NULL) && (genericParamResult == NULL))
  5692. {
  5693. BfMethodInstance* prevMethodInstance = NULL;
  5694. // If we're in a closure then use the outside method generic arguments
  5695. auto checkMethodInstance = contextMethodInstance;
  5696. if ((mCurMethodState != NULL) && (checkMethodInstance->mIsClosure))
  5697. {
  5698. auto checkMethodState = mCurMethodState;
  5699. while (checkMethodState != NULL)
  5700. {
  5701. if ((checkMethodState->mMethodInstance != NULL) && (checkMethodState->mMethodInstance->mIsClosure))
  5702. {
  5703. checkMethodInstance = checkMethodState->mPrevMethodState->mMethodInstance;
  5704. }
  5705. checkMethodState = checkMethodState->mPrevMethodState;
  5706. }
  5707. }
  5708. for (int genericParamIdx = (int)checkMethodInstance->mMethodDef->mGenericParams.size() - 1; genericParamIdx >= 0; genericParamIdx--)
  5709. {
  5710. auto checkGenericParamDef = checkMethodInstance->mMethodDef->mGenericParams[genericParamIdx];
  5711. String genericName = checkGenericParamDef->mName;
  5712. if (genericName == findName)
  5713. {
  5714. genericParamDef = checkGenericParamDef;
  5715. if (((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  5716. ((resolveFlags & BfResolveTypeRefFlag_AllowGenericMethodParamConstValue) == 0))
  5717. disallowConstExprValue = true;
  5718. HandleMethodGenericParamRef(typeRef, checkMethodInstance->GetOwner()->mTypeDef, checkMethodInstance->mMethodDef, genericParamIdx);
  5719. if ((resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0)
  5720. return GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  5721. else
  5722. {
  5723. SetAndRestoreValue<BfGetSymbolReferenceKind> prevSymbolRefKind;
  5724. if (mCompiler->mResolvePassData != NULL) // Don't add these typeRefs, they are indirect
  5725. prevSymbolRefKind.Init(mCompiler->mResolvePassData->mGetSymbolReferenceKind, BfGetSymbolReferenceKind_None);
  5726. genericParamResult = checkMethodInstance->mMethodInfoEx->mMethodGenericArguments[genericParamIdx];
  5727. if ((genericParamResult != NULL) &&
  5728. (genericParamResult->IsConstExprValue()) &&
  5729. ((resolveFlags & BfResolveTypeRefFlag_AllowGenericMethodParamConstValue) == 0))
  5730. disallowConstExprValue = true;
  5731. }
  5732. }
  5733. }
  5734. }
  5735. if (genericParamResult != NULL)
  5736. {
  5737. if (disallowConstExprValue)
  5738. {
  5739. Fail("Invalid use of constant generic value", typeRef);
  5740. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  5741. }
  5742. if (genericParamResult->IsRef())
  5743. {
  5744. if ((resolveFlags & BfResolveTypeRefFlag_AllowRefGeneric) == 0)
  5745. genericParamResult = genericParamResult->GetUnderlyingType();
  5746. }
  5747. return ResolveTypeResult(typeRef, genericParamResult, populateType, (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_FromIndirectSource));
  5748. }
  5749. }
  5750. }
  5751. BfTypeDef* typeDef = NULL;
  5752. if (typeRef->IsNamedTypeReference())
  5753. {
  5754. BfTypeLookupError error;
  5755. error.mRefNode = typeRef;
  5756. typeDef = FindTypeDef(typeRef, contextTypeInstance, &error);
  5757. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef))
  5758. {
  5759. if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(namedTypeRef->mNameNode))
  5760. {
  5761. // This handles the case where we have an "BaseClass.InnerClass", but the name is qualified as "DerivedClass.InnerClass"
  5762. auto leftType = ResolveTypeRef(qualifiedNameNode->mLeft, NULL, BfPopulateType_Identity, (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef));
  5763. if ((leftType != NULL) && (qualifiedNameNode->mRight != NULL))
  5764. {
  5765. // Try searching within inner type
  5766. auto resolvedType = ResolveInnerType(leftType, qualifiedNameNode->mRight, populateType, true);
  5767. if (resolvedType != NULL)
  5768. {
  5769. if (mCurTypeInstance != NULL)
  5770. AddDependency(leftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  5771. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  5772. }
  5773. }
  5774. }
  5775. }
  5776. if ((typeDef == NULL) && (mCurTypeInstance != NULL))
  5777. {
  5778. // Try searching within inner type
  5779. auto checkOuterType = mCurTypeInstance;
  5780. while (checkOuterType != NULL)
  5781. {
  5782. // We check for mBaseType to not be NULL because we can't inherit from an inner type, so don't even search there
  5783. // Causes reference cycles (bad).
  5784. if ((checkOuterType != mCurTypeInstance) || (checkOuterType->mBaseType != NULL))
  5785. {
  5786. auto resolvedType = ResolveInnerType(checkOuterType, typeRef, populateType, true);
  5787. if (resolvedType != NULL)
  5788. {
  5789. if (mCurTypeInstance != NULL)
  5790. AddDependency(checkOuterType, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  5791. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  5792. }
  5793. }
  5794. checkOuterType = GetOuterType(checkOuterType);
  5795. }
  5796. }
  5797. if (typeDef == NULL)
  5798. {
  5799. #ifdef BF_AST_HAS_PARENT_MEMBER
  5800. if (auto parentQualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef->mParent))
  5801. {
  5802. BF_ASSERT(typeRef->mParent == mParentNodeEntry->mNode);
  5803. }
  5804. #endif
  5805. if (mParentNodeEntry != NULL)
  5806. {
  5807. if (auto parentQualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(mParentNodeEntry->mNode))
  5808. {
  5809. if (typeRef == parentQualifiedTypeRef->mLeft)
  5810. {
  5811. if ((resolveFlags & BfResolveTypeRefFlag_IgnoreLookupError) == 0)
  5812. TypeRefNotFound(typeRef);
  5813. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  5814. }
  5815. }
  5816. }
  5817. if ((resolveFlags & BfResolveTypeRefFlag_IgnoreLookupError) == 0)
  5818. {
  5819. TypeRefNotFound(typeRef);
  5820. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  5821. }
  5822. return NULL;
  5823. }
  5824. }
  5825. else if (auto typeDefTypeRef = BfNodeDynCastExact<BfDirectTypeDefReference>(typeRef))
  5826. {
  5827. typeDef = typeDefTypeRef->mTypeDef;
  5828. }
  5829. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  5830. {
  5831. //TODO: Determine why we had this prevIgnoreErrors set here. It causes things like IEnumerator<Hey.Test<INVALIDNAME>> not fail
  5832. // properly on INVALIDNAME
  5833. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, /*true*/mIgnoreErrors);
  5834. StringView leftNameStr;
  5835. BfType* leftType = NULL;
  5836. BfSizedAtomComposite leftComposite;
  5837. bool leftIsValid = false;
  5838. //bool leftIsValid = (qualifiedTypeRef->mLeft != NULL) && mSystem->ParseAtomComposite(qualifiedTypeRef->mLeft->ToString(), leftComposite);
  5839. if (qualifiedTypeRef->mLeft != NULL)
  5840. {
  5841. leftNameStr = qualifiedTypeRef->mLeft->ToStringView();
  5842. if (mSystem->ParseAtomComposite(leftNameStr, leftComposite))
  5843. leftIsValid = true;
  5844. }
  5845. if ((leftIsValid) && (qualifiedTypeRef->mRight != NULL))
  5846. {
  5847. StringT<128> findName;
  5848. auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(qualifiedTypeRef->mRight);
  5849. auto activeTypeDef = GetActiveTypeDef();
  5850. BfProject* bfProject = NULL;
  5851. if (activeTypeDef != NULL)
  5852. bfProject = activeTypeDef->mProject;
  5853. if (mSystem->ContainsNamespace(leftComposite, bfProject))
  5854. {
  5855. qualifiedTypeRef->mLeft->ToString(findName);
  5856. findName.Append('.');
  5857. if (genericTypeRef != NULL)
  5858. genericTypeRef->mElementType->ToString(findName);
  5859. else
  5860. qualifiedTypeRef->mRight->ToString(findName);
  5861. }
  5862. else if ((activeTypeDef != NULL) && (activeTypeDef->mNamespace.EndsWith(leftComposite)))
  5863. {
  5864. // Partial namespace reference, extend to a full reference
  5865. findName += activeTypeDef->mNamespace.ToString();
  5866. findName.Append('.');
  5867. qualifiedTypeRef->mRight->ToString(findName);
  5868. }
  5869. if (!findName.IsEmpty())
  5870. {
  5871. int wantNumGenericArgs = 0;
  5872. #ifdef BF_AST_HAS_PARENT_MEMBER
  5873. if (auto genericTypeParent = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef->mParent))
  5874. {
  5875. BF_ASSERT(mParentNodeEntry->mNode == genericTypeParent);
  5876. //wantNumGenericArgs = (int)genericTypeParent->mGenericArguments.size();
  5877. //genericTypeRef = genericTypeParent;
  5878. }
  5879. #endif
  5880. if (mParentNodeEntry != NULL)
  5881. {
  5882. if (auto genericTypeParent = BfNodeDynCast<BfGenericInstanceTypeRef>(mParentNodeEntry->mNode))
  5883. {
  5884. wantNumGenericArgs = (int)genericTypeParent->mGenericArguments.size();
  5885. genericTypeRef = genericTypeParent;
  5886. }
  5887. }
  5888. BfTypeDef* ambiguousTypeDef = NULL;
  5889. auto typeDef = mSystem->FindTypeDef(findName, wantNumGenericArgs, bfProject, {}, &ambiguousTypeDef);
  5890. if (typeDef != NULL)
  5891. {
  5892. if (ambiguousTypeDef != NULL)
  5893. ShowAmbiguousTypeError(typeRef, typeDef, ambiguousTypeDef);
  5894. BfTypeVector genericArgs;
  5895. if (populateType != BfPopulateType_TypeDef)
  5896. {
  5897. if (genericTypeRef != NULL)
  5898. {
  5899. for (auto genericParamTypeRef : genericTypeRef->mGenericArguments)
  5900. {
  5901. auto genericParam = ResolveTypeRef(genericParamTypeRef, BfPopulateType_Declaration);
  5902. if (genericParam == NULL)
  5903. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  5904. genericArgs.push_back(genericParam);
  5905. }
  5906. }
  5907. if (typeDef->mGenericParamDefs.size() != genericArgs.size())
  5908. {
  5909. prevIgnoreErrors.Restore();
  5910. BfAstNode* refNode = typeRef;
  5911. if (genericTypeRef != NULL)
  5912. refNode = genericTypeRef->mOpenChevron;
  5913. int wantedGenericParams = (int)typeDef->mGenericParamDefs.size();
  5914. if (wantedGenericParams == 1)
  5915. Fail("Expected one generic argument", refNode);
  5916. else
  5917. Fail(StrFormat("Expected %d generic arguments", wantedGenericParams), refNode);
  5918. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  5919. }
  5920. }
  5921. return ResolveTypeResult(typeRef, ResolveTypeDef(typeDef, genericArgs, populateType), populateType, resolveFlags);
  5922. }
  5923. }
  5924. }
  5925. if (leftType == NULL)
  5926. {
  5927. BfAutoParentNodeEntry autoParentNodeEntry(this, qualifiedTypeRef);
  5928. leftType = ResolveTypeRef(qualifiedTypeRef->mLeft, BfPopulateType_Declaration, BfResolveTypeRefFlag_IgnoreLookupError); // We throw an error below if we can't find the type
  5929. }
  5930. if (leftType == NULL)
  5931. {
  5932. mIgnoreErrors = prevIgnoreErrors.mPrevVal;
  5933. BfTypeReference* errorRefNode = qualifiedTypeRef->mLeft;
  5934. if ((leftIsValid) && (mCurTypeInstance != NULL) && (mSystem->ContainsNamespace(leftComposite, mCurTypeInstance->mTypeDef->mProject)))
  5935. {
  5936. // The left was a namespace name, so throw an error on the whole string
  5937. errorRefNode = qualifiedTypeRef;
  5938. }
  5939. TypeRefNotFound(errorRefNode);
  5940. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  5941. }
  5942. prevIgnoreErrors.Restore();
  5943. if (qualifiedTypeRef->mRight == NULL)
  5944. {
  5945. FailAfter("Expected identifier", qualifiedTypeRef->mDot);
  5946. //AssertErrorState();
  5947. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  5948. }
  5949. auto resolvedType = ResolveInnerType(leftType, qualifiedTypeRef->mRight, populateType);
  5950. if ((resolvedType != NULL) && (mCurTypeInstance != NULL))
  5951. AddDependency(leftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  5952. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  5953. // If we did a ResolveTypeResult, then that may process an alias as the alias-to type instead of the actual alias
  5954. //return ResolveInnerType(leftType, qualifiedTypeRef->mRight, populateType);
  5955. }
  5956. if (auto resolvedTypeRef = BfNodeDynCast<BfResolvedTypeReference>(typeRef))
  5957. {
  5958. return ResolveTypeResult(typeRef, resolvedTypeRef->mType, populateType, resolveFlags);
  5959. }
  5960. if (auto retTypeTypeRef = BfNodeDynCastExact<BfRetTypeTypeRef>(typeRef))
  5961. {
  5962. bool allowThrough = false;
  5963. BfType* resolvedType = NULL;
  5964. if (retTypeTypeRef->mElementType != NULL)
  5965. {
  5966. auto innerType = ResolveTypeRef(retTypeTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  5967. if (innerType != NULL)
  5968. {
  5969. if ((innerType->IsDelegate()) || (innerType->IsFunction()))
  5970. {
  5971. PopulateType(innerType, BfPopulateType_DataAndMethods);
  5972. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(innerType->ToTypeInstance(), 0, "Invoke");
  5973. if (invokeMethodInstance != NULL)
  5974. {
  5975. resolvedType = invokeMethodInstance->mReturnType;
  5976. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  5977. }
  5978. }
  5979. else if (innerType->IsGenericParam())
  5980. {
  5981. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  5982. {
  5983. // We could have case where we have "rettype(@T0)" and @T0 gets a type variation of @M0, but we can't do a
  5984. // GetGenericParamInstance on that
  5985. allowThrough = true;
  5986. }
  5987. else
  5988. {
  5989. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)innerType);
  5990. if (genericParamInstance->mTypeConstraint != NULL)
  5991. {
  5992. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()))
  5993. {
  5994. resolvedType = GetDelegateReturnType(genericParamInstance->mTypeConstraint);
  5995. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  5996. }
  5997. else if ((genericParamInstance->mTypeConstraint->IsTypeInstance()) &&
  5998. ((genericParamInstance->mTypeConstraint->ToTypeInstance()->mTypeDef == mCompiler->mDelegateTypeDef) ||
  5999. (genericParamInstance->mTypeConstraint->ToTypeInstance()->mTypeDef == mCompiler->mFunctionTypeDef)))
  6000. {
  6001. allowThrough = true;
  6002. }
  6003. }
  6004. }
  6005. }
  6006. else if (innerType->IsMethodRef())
  6007. {
  6008. auto methodRefType = (BfMethodRefType*)innerType;
  6009. resolvedType = methodRefType->mMethodRef->mReturnType;
  6010. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  6011. }
  6012. }
  6013. }
  6014. if (!allowThrough)
  6015. {
  6016. Fail("'rettype' can only be used on delegate or function types", retTypeTypeRef->mRetTypeToken);
  6017. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  6018. }
  6019. }
  6020. if (auto refTypeRef = BfNodeDynCastExact<BfRefTypeRef>(typeRef))
  6021. {
  6022. if ((refTypeRef->mRefToken != NULL) && (refTypeRef->mRefToken->GetToken() == BfToken_Mut) && (refTypeRef->mElementType != NULL))
  6023. {
  6024. bool needsRefWrap = false;
  6025. auto resolvedType = ResolveTypeRef(refTypeRef->mElementType, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  6026. if (resolvedType != NULL)
  6027. {
  6028. if ((resolvedType->IsComposite()) || (resolvedType->IsGenericParam()))
  6029. needsRefWrap = true;
  6030. }
  6031. if (!needsRefWrap)
  6032. {
  6033. // Non-composites (including pointers) don't actually need ref-wrapping for 'mut'
  6034. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  6035. }
  6036. }
  6037. }
  6038. BfResolvedTypeSet::LookupContext lookupCtx;
  6039. lookupCtx.mRootTypeRef = typeRef;
  6040. lookupCtx.mRootTypeDef = typeDef;
  6041. lookupCtx.mModule = this;
  6042. BfResolvedTypeSet::Entry* resolvedEntry = NULL;
  6043. auto inserted = mContext->mResolvedTypes.Insert(typeRef, &lookupCtx, &resolvedEntry);
  6044. if (resolvedEntry == NULL)
  6045. {
  6046. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6047. }
  6048. if (!inserted)
  6049. {
  6050. BF_ASSERT(resolvedEntry->mValue != NULL);
  6051. return ResolveTypeResult(typeRef, resolvedEntry->mValue, populateType, resolveFlags);
  6052. }
  6053. if (typeRef->IsTypeDefTypeReference())
  6054. {
  6055. //BF_ASSERT(typeDefTypeRef->mTypeDef != NULL); // Resolved higher up
  6056. //auto typeDef = typeDefTypeRef->mTypeDef;
  6057. if ((typeDef->mTypeCode >= BfTypeCode_None) && (typeDef->mTypeCode <= BfTypeCode_Double))
  6058. {
  6059. BfPrimitiveType* primType = new BfPrimitiveType();
  6060. primType->mTypeDef = typeDef;
  6061. resolvedEntry->mValue = primType;
  6062. BF_ASSERT(BfResolvedTypeSet::Hash(primType, &lookupCtx, false) == resolvedEntry->mHash);
  6063. InitType(primType, populateType);
  6064. return ResolveTypeResult(typeRef, primType, populateType, resolveFlags);
  6065. }
  6066. if ((mCurTypeInstance != NULL) && (typeDef->mGenericParamDefs.size() != 0))
  6067. {
  6068. // Try to inherit generic params from current parent
  6069. auto outerType = typeDef->mOuterType;
  6070. BF_ASSERT(!outerType->mIsPartial);
  6071. if (TypeHasParent(mCurTypeInstance->mTypeDef, outerType))
  6072. {
  6073. BfType* checkCurType = mCurTypeInstance;
  6074. if (checkCurType->IsBoxed())
  6075. checkCurType = checkCurType->GetUnderlyingType();
  6076. if (checkCurType->IsTypeAlias())
  6077. checkCurType = GetOuterType(checkCurType);
  6078. BF_ASSERT(checkCurType->IsGenericTypeInstance());
  6079. int numParentGenericParams = (int)outerType->mGenericParamDefs.size();
  6080. int wantedGenericParams = (int)typeDef->mGenericParamDefs.size() - numParentGenericParams;
  6081. if (wantedGenericParams != 0)
  6082. {
  6083. if (wantedGenericParams == 1)
  6084. Fail("Expected generic argument", typeRef);
  6085. else
  6086. Fail(StrFormat("Expected %d generic arguments", wantedGenericParams), typeRef);
  6087. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6088. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6089. }
  6090. auto parentGenericTypeInstance = (BfGenericTypeInstance*)checkCurType;
  6091. BfGenericTypeInstance* genericTypeInst;
  6092. if (typeDef->mTypeCode == BfTypeCode_TypeAlias)
  6093. {
  6094. auto typeAliasType = new BfGenericTypeAliasType();
  6095. genericTypeInst = typeAliasType;
  6096. }
  6097. else
  6098. genericTypeInst = new BfGenericTypeInstance();
  6099. genericTypeInst->mTypeDef = typeDef;
  6100. for (int i = 0; i < numParentGenericParams; i++)
  6101. {
  6102. genericTypeInst->mGenericParams.push_back(parentGenericTypeInstance->mGenericParams[i]->AddRef());
  6103. genericTypeInst->mTypeGenericArguments.push_back(parentGenericTypeInstance->mTypeGenericArguments[i]);
  6104. }
  6105. CheckUnspecializedGenericType(genericTypeInst, populateType);
  6106. resolvedEntry->mValue = genericTypeInst;
  6107. BF_ASSERT(BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx) == resolvedEntry->mHash);
  6108. InitType(genericTypeInst, populateType);
  6109. return ResolveTypeResult(typeRef, genericTypeInst, populateType, resolveFlags);
  6110. }
  6111. }
  6112. BfTypeInstance* typeInst;
  6113. if (typeDef->mTypeCode == BfTypeCode_TypeAlias)
  6114. {
  6115. auto typeAliasType = new BfTypeAliasType();
  6116. typeInst = typeAliasType;
  6117. }
  6118. else
  6119. {
  6120. typeInst = new BfTypeInstance();
  6121. }
  6122. typeInst->mTypeDef = typeDef;
  6123. if (typeInst->mTypeDef->mGenericParamDefs.size() != 0)
  6124. {
  6125. Fail("Generic type arguments expected", typeRef);
  6126. delete typeInst;
  6127. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6128. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6129. }
  6130. resolvedEntry->mValue = typeInst;
  6131. BF_ASSERT(BfResolvedTypeSet::Hash(typeInst, &lookupCtx) == resolvedEntry->mHash);
  6132. InitType(typeInst, populateType);
  6133. return ResolveTypeResult(typeRef, typeInst, populateType, resolveFlags);
  6134. }
  6135. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(typeRef))
  6136. {
  6137. if (arrayTypeRef->mDimensions > 4)
  6138. {
  6139. Fail("Too many array dimensions, consider using a jagged array.", arrayTypeRef);
  6140. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6141. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6142. }
  6143. auto elementType = ResolveTypeRef(arrayTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  6144. if (elementType == NULL)
  6145. {
  6146. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6147. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6148. }
  6149. if ((arrayTypeRef->mDimensions == 1) && (arrayTypeRef->mParams.size() == 1))
  6150. {
  6151. intptr elementCount = -1;
  6152. BfExpression* sizeExpr = BfNodeDynCast<BfExpression>(arrayTypeRef->mParams[0]);
  6153. BF_ASSERT(sizeExpr != NULL);
  6154. if (sizeExpr != NULL)
  6155. {
  6156. BfConstResolver constResolver(this);
  6157. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  6158. constResolver.mExpectingType = intType;
  6159. constResolver.mAllowGenericConstValue = true;
  6160. BfTypedValue typedVal;
  6161. {
  6162. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  6163. typedVal = constResolver.Resolve(sizeExpr);
  6164. }
  6165. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  6166. {
  6167. BfUnknownSizedArrayType* arrayType = new BfUnknownSizedArrayType();
  6168. arrayType->mContext = mContext;
  6169. arrayType->mElementType = elementType;
  6170. arrayType->mElementCount = -1;
  6171. arrayType->mElementCountSource = typedVal.mType;
  6172. resolvedEntry->mValue = arrayType;
  6173. BF_ASSERT(BfResolvedTypeSet::Hash(arrayType, &lookupCtx) == resolvedEntry->mHash);
  6174. InitType(arrayType, populateType);
  6175. return ResolveTypeResult(typeRef, arrayType, populateType, resolveFlags);
  6176. }
  6177. if (typedVal)
  6178. typedVal = Cast(sizeExpr, typedVal, intType);
  6179. if (typedVal)
  6180. {
  6181. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  6182. if (constant != NULL)
  6183. {
  6184. if (constant->mConstType == BfConstType_Undef)
  6185. elementCount = -1; // Undef marker
  6186. else if (BfIRBuilder::IsInt(constant->mTypeCode))
  6187. elementCount = constant->mInt32;
  6188. }
  6189. }
  6190. }
  6191. /*if (elementCount < 0)
  6192. {
  6193. Fail(StrFormat("Array length '%d' is illegal", elementCount), arrayTypeRef->mParams[0]);
  6194. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6195. return CreateSizedArrayType(elementType, 0);
  6196. }*/
  6197. BfSizedArrayType* arrayType = new BfSizedArrayType();
  6198. arrayType->mContext = mContext;
  6199. arrayType->mElementType = elementType;
  6200. arrayType->mElementCount = elementCount;
  6201. arrayType->mWantsGCMarking = false; // Fill in in InitType
  6202. resolvedEntry->mValue = arrayType;
  6203. BF_ASSERT(BfResolvedTypeSet::Hash(arrayType, &lookupCtx) == resolvedEntry->mHash);
  6204. InitType(arrayType, populateType);
  6205. return ResolveTypeResult(typeRef, arrayType, populateType, resolveFlags);
  6206. }
  6207. BfArrayType* arrayType = new BfArrayType();
  6208. arrayType->mContext = mContext;
  6209. arrayType->mDimensions = arrayTypeRef->mDimensions;
  6210. arrayType->mTypeDef = mCompiler->GetArrayTypeDef(arrayType->mDimensions);
  6211. arrayType->mTypeGenericArguments.push_back(elementType);
  6212. resolvedEntry->mValue = arrayType;
  6213. CheckUnspecializedGenericType(arrayType, populateType);
  6214. BF_ASSERT(BfResolvedTypeSet::Hash(arrayType, &lookupCtx) == resolvedEntry->mHash);
  6215. InitType(arrayType, populateType);
  6216. return ResolveTypeResult(typeRef, arrayType, populateType, resolveFlags);
  6217. }
  6218. else if (auto genericTypeInstRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  6219. {
  6220. int wantNumGenericParams = genericTypeInstRef->GetGenericArgCount();
  6221. BfTypeDef* ambiguousTypeDef = NULL;
  6222. BfTypeDef* typeDef = ResolveGenericInstanceDef(genericTypeInstRef);
  6223. BfGenericTypeInstance* genericTypeInst;
  6224. if ((typeDef != NULL) && (typeDef->mTypeCode == BfTypeCode_TypeAlias))
  6225. {
  6226. auto typeAliasType = new BfGenericTypeAliasType();
  6227. genericTypeInst = typeAliasType;
  6228. }
  6229. else
  6230. genericTypeInst = new BfGenericTypeInstance();
  6231. genericTypeInst->mContext = mContext;
  6232. if (ambiguousTypeDef != NULL)
  6233. ShowAmbiguousTypeError(typeRef, typeDef, ambiguousTypeDef);
  6234. if (typeDef == NULL)
  6235. {
  6236. Fail("Unable to resolve type", typeRef);
  6237. delete genericTypeInst;
  6238. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6239. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6240. }
  6241. BF_ASSERT(typeDef->mDefState != BfTypeDef::DefState_Deleted);
  6242. if (typeDef->mGenericParamDefs.size() == 0)
  6243. {
  6244. Fail("Not a generic type", typeRef);
  6245. delete genericTypeInst;
  6246. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6247. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6248. }
  6249. int startDefGenericParamIdx = 0;
  6250. genericTypeInst->mTypeDef = typeDef;
  6251. if (mCurTypeInstance != NULL)
  6252. {
  6253. // Copy generic params for our parent type if the current type instance shares that parent type
  6254. //auto outerType = mSystem->GetOuterTypeNonPartial(typeDef);
  6255. auto outerType = typeDef->mOuterType;
  6256. BfTypeDef* commonOuterType = FindCommonOuterType(mCurTypeInstance->mTypeDef, outerType);
  6257. if ((commonOuterType) && (mCurTypeInstance->IsGenericTypeInstance()))
  6258. {
  6259. startDefGenericParamIdx = (int)commonOuterType->mGenericParamDefs.size();
  6260. auto parentTypeInstance = (BfGenericTypeInstance*)mCurTypeInstance;
  6261. if (parentTypeInstance->IsTypeAlias())
  6262. parentTypeInstance = (BfGenericTypeInstance*)GetOuterType(parentTypeInstance)->ToTypeInstance();
  6263. for (int i = 0; i < startDefGenericParamIdx; i++)
  6264. {
  6265. genericTypeInst->mGenericParams.push_back(parentTypeInstance->mGenericParams[i]->AddRef());
  6266. genericTypeInst->mTypeGenericArguments.push_back(parentTypeInstance->mTypeGenericArguments[i]);
  6267. auto typeGenericArg = genericTypeInst->mTypeGenericArguments[i];
  6268. genericTypeInst->mIsUnspecialized |= typeGenericArg->IsGenericParam() || typeGenericArg->IsUnspecializedType();
  6269. }
  6270. }
  6271. }
  6272. Array<BfTypeReference*> genericArguments;
  6273. std::function<void(BfTypeReference*)> _GetTypeRefs = [&](BfTypeReference* typeRef)
  6274. {
  6275. if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(typeRef))
  6276. {
  6277. _GetTypeRefs(elementedTypeRef->mElementType);
  6278. }
  6279. else if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  6280. {
  6281. _GetTypeRefs(qualifiedTypeRef->mLeft);
  6282. }
  6283. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  6284. {
  6285. for (auto genericArg : genericTypeRef->mGenericArguments)
  6286. genericArguments.push_back(genericArg);
  6287. }
  6288. };
  6289. _GetTypeRefs(genericTypeInstRef);
  6290. int wantedGenericParams = (int)typeDef->mGenericParamDefs.size() - startDefGenericParamIdx;
  6291. int genericArgDiffCount = (int)genericArguments.size() - wantedGenericParams;
  6292. if (genericArgDiffCount != 0)
  6293. {
  6294. int innerWantedGenericParams = (int)typeDef->mGenericParamDefs.size();
  6295. if (typeDef->mOuterType != NULL)
  6296. innerWantedGenericParams -= (int)typeDef->mOuterType->mGenericParamDefs.size();
  6297. ShowGenericArgCountError(genericTypeInstRef, innerWantedGenericParams);
  6298. delete genericTypeInst;
  6299. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6300. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6301. }
  6302. int genericParamIdx = 0;
  6303. for (auto genericArgRef : genericArguments)
  6304. {
  6305. auto genericArg = ResolveTypeRef(genericArgRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowGenericMethodParamConstValue);
  6306. if (genericArg == NULL)
  6307. {
  6308. delete genericTypeInst;
  6309. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6310. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6311. }
  6312. genericTypeInst->mTypeGenericArguments.push_back(genericArg);
  6313. genericTypeInst->mTypeGenericArgumentRefs.push_back(genericArgRef);
  6314. genericParamIdx++;
  6315. }
  6316. resolvedEntry->mValue = genericTypeInst;
  6317. CheckUnspecializedGenericType(genericTypeInst, populateType);
  6318. BF_ASSERT(BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx) == resolvedEntry->mHash);
  6319. InitType(genericTypeInst, populateType);
  6320. return ResolveTypeResult(typeRef, genericTypeInst, populateType, resolveFlags);
  6321. }
  6322. else if (auto tupleTypeRef = BfNodeDynCast<BfTupleTypeRef>(typeRef))
  6323. {
  6324. Array<BfType*> types;
  6325. Array<String> names;
  6326. for (int fieldIdx = 0; fieldIdx < (int)tupleTypeRef->mFieldTypes.size(); fieldIdx++)
  6327. {
  6328. BfTypeReference* typeRef = tupleTypeRef->mFieldTypes[fieldIdx];
  6329. auto type = ResolveTypeRef(typeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  6330. if (type == NULL)
  6331. {
  6332. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6333. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6334. }
  6335. String fieldName;
  6336. BfIdentifierNode* identifierNode = NULL;
  6337. if (fieldIdx < (int)tupleTypeRef->mFieldNames.size())
  6338. identifierNode = tupleTypeRef->mFieldNames[fieldIdx];
  6339. if (identifierNode != NULL)
  6340. fieldName = identifierNode->ToString();
  6341. else
  6342. fieldName = StrFormat("%d", fieldIdx);
  6343. String typeName = TypeToString(type);
  6344. types.push_back(type);
  6345. names.push_back(fieldName);
  6346. }
  6347. auto baseType = (BfTypeInstance*)ResolveTypeDef(mContext->mCompiler->mValueTypeTypeDef, BfPopulateType_Identity);
  6348. BfTupleType* tupleType = new BfTupleType();
  6349. //TODO: Add to correct project
  6350. tupleType->Init(baseType->mTypeDef->mProject, baseType);
  6351. tupleType->mFieldInstances.Resize(types.size());
  6352. for (int fieldIdx = 0; fieldIdx < (int)types.size(); fieldIdx++)
  6353. {
  6354. BfFieldDef* fieldDef = tupleType->AddField(names[fieldIdx]);
  6355. fieldDef->mProtection = (names[fieldIdx][0] == '_') ? BfProtection_Private : BfProtection_Public;
  6356. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  6357. fieldInstance->mFieldIdx = fieldIdx;
  6358. fieldInstance->SetResolvedType(types[fieldIdx]);
  6359. fieldInstance->mOwner = tupleType;
  6360. }
  6361. tupleType->Finish();
  6362. resolvedEntry->mValue = tupleType;
  6363. BF_ASSERT(BfResolvedTypeSet::Hash(tupleType, &lookupCtx) == resolvedEntry->mHash);
  6364. InitType(tupleType, populateType);
  6365. return ResolveTypeResult(typeRef, tupleType, populateType, resolveFlags);
  6366. }
  6367. else if (auto nullableTypeRef = BfNodeDynCast<BfNullableTypeRef>(typeRef))
  6368. {
  6369. BfTypeReference* elementTypeRef = nullableTypeRef->mElementType;
  6370. auto typeDef = mCompiler->mNullableTypeDef;
  6371. auto elementType = ResolveTypeRef(elementTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  6372. if (elementType == NULL)
  6373. {
  6374. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6375. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6376. }
  6377. BfGenericTypeInstance* genericTypeInst = new BfGenericTypeInstance();
  6378. genericTypeInst->mContext = mContext;
  6379. genericTypeInst->mTypeDef = typeDef;
  6380. auto genericParamInstance = new BfGenericTypeParamInstance(typeDef, 0);
  6381. genericTypeInst->mGenericParams.push_back(genericParamInstance);
  6382. genericTypeInst->mTypeGenericArguments.push_back(elementType);
  6383. //genericTypeInst->mIsUnspecialized = elementType->IsGenericParam() || elementType->IsUnspecializedType();
  6384. CheckUnspecializedGenericType(genericTypeInst, populateType);
  6385. resolvedEntry->mValue = genericTypeInst;
  6386. BF_ASSERT(BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx) == resolvedEntry->mHash);
  6387. InitType(genericTypeInst, populateType);
  6388. return ResolveTypeResult(typeRef, genericTypeInst, populateType, resolveFlags);
  6389. }
  6390. else if (auto pointerTypeRef = BfNodeDynCast<BfPointerTypeRef>(typeRef))
  6391. {
  6392. BfPointerType* pointerType = new BfPointerType();
  6393. pointerType->mElementType = ResolveTypeRef(pointerTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  6394. pointerType->mContext = mContext;
  6395. if (pointerType->mElementType == NULL)
  6396. {
  6397. delete pointerType;
  6398. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6399. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6400. }
  6401. resolvedEntry->mValue = pointerType;
  6402. //int hashVal = mContext->mResolvedTypes.Hash(typeRef, &lookupCtx);
  6403. BF_ASSERT(BfResolvedTypeSet::Hash(pointerType, &lookupCtx) == resolvedEntry->mHash);
  6404. InitType(pointerType, populateType);
  6405. return ResolveTypeResult(typeRef, pointerType, populateType, resolveFlags);
  6406. }
  6407. else if (auto refTypeRef = BfNodeDynCast<BfRefTypeRef>(typeRef))
  6408. {
  6409. BfRefType* refType = new BfRefType();
  6410. refType->mRefKind = BfRefType::RefKind_Ref;
  6411. if (refTypeRef->mRefToken == NULL)
  6412. refType->mRefKind = BfRefType::RefKind_Ref;
  6413. else if (refTypeRef->mRefToken->GetToken() == BfToken_Out)
  6414. refType->mRefKind = BfRefType::RefKind_Out;
  6415. else if (refTypeRef->mRefToken->GetToken() == BfToken_Mut)
  6416. refType->mRefKind = BfRefType::RefKind_Mut;
  6417. refType->mElementType = ResolveTypeRef(refTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  6418. if (refType->mElementType == NULL)
  6419. {
  6420. delete refType;
  6421. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6422. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6423. }
  6424. resolvedEntry->mValue = refType;
  6425. BF_ASSERT(BfResolvedTypeSet::Hash(refType, &lookupCtx) == resolvedEntry->mHash);
  6426. InitType(refType, populateType);
  6427. return ResolveTypeResult(typeRef, refType, populateType, resolveFlags);
  6428. }
  6429. else if (auto delegateTypeRef = BfNodeDynCast<BfDelegateTypeRef>(typeRef))
  6430. {
  6431. auto returnType = ResolveTypeRef(delegateTypeRef->mReturnType);
  6432. if (returnType == NULL)
  6433. {
  6434. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  6435. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6436. }
  6437. auto baseDelegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  6438. BfDelegateType* delegateType = new BfDelegateType();
  6439. Val128 hashContext;
  6440. BfTypeDef* typeDef = new BfTypeDef();
  6441. typeDef->mProject = baseDelegateType->mTypeDef->mProject;
  6442. typeDef->mSystem = mCompiler->mSystem;
  6443. typeDef->mName = mSystem->mEmptyAtom;
  6444. if (delegateTypeRef->mTypeToken->GetToken() == BfToken_Delegate)
  6445. {
  6446. typeDef->mIsDelegate = true;
  6447. typeDef->mTypeCode = BfTypeCode_Object;
  6448. }
  6449. else
  6450. {
  6451. typeDef->mIsFunction = true;
  6452. typeDef->mTypeCode = BfTypeCode_Struct;
  6453. }
  6454. BfMethodDef* methodDef = new BfMethodDef();
  6455. methodDef->mDeclaringType = typeDef;
  6456. methodDef->mName = "Invoke";
  6457. methodDef->mProtection = BfProtection_Public;
  6458. methodDef->mIdx = 0;
  6459. methodDef->mIsStatic = !typeDef->mIsDelegate;
  6460. auto directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  6461. delegateType->mDirectAllocNodes.push_back(directTypeRef);
  6462. if (typeDef->mIsDelegate)
  6463. directTypeRef->Init(delegateType);
  6464. else
  6465. directTypeRef->Init(ResolveTypeDef(mCompiler->mFunctionTypeDef));
  6466. typeDef->mBaseTypes.push_back(directTypeRef);
  6467. directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  6468. delegateType->mDirectAllocNodes.push_back(directTypeRef);
  6469. directTypeRef->Init(returnType);
  6470. methodDef->mReturnTypeRef = directTypeRef;
  6471. AddDependency(directTypeRef->mType, baseDelegateType, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  6472. auto hashVal = mContext->mResolvedTypes.Hash(typeRef, &lookupCtx);
  6473. int paramIdx = 0;
  6474. for (auto param : delegateTypeRef->mParams)
  6475. {
  6476. auto paramType = ResolveTypeRef(param->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowRef);
  6477. String paramName;
  6478. if (param->mNameNode != NULL)
  6479. paramName = param->mNameNode->ToString();
  6480. if (paramType->IsUnspecializedType())
  6481. delegateType->mIsUnspecializedType = true;
  6482. if (paramType->IsUnspecializedTypeVariation())
  6483. delegateType->mIsUnspecializedTypeVariation = true;
  6484. if (!paramType->IsReified())
  6485. delegateType->mIsReified = false;
  6486. if (paramType->IsGenericParam())
  6487. {
  6488. delegateType->mIsUnspecializedTypeVariation = true;
  6489. }
  6490. auto directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  6491. delegateType->mDirectAllocNodes.push_back(directTypeRef);
  6492. directTypeRef->Init(paramType);
  6493. BfParameterDef* paramDef = new BfParameterDef();
  6494. paramDef->mTypeRef = directTypeRef;
  6495. paramDef->mName = paramName;
  6496. methodDef->mParams.push_back(paramDef);
  6497. paramIdx++;
  6498. AddDependency(paramType, baseDelegateType, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  6499. }
  6500. typeDef->mMethods.push_back(methodDef);
  6501. //
  6502. BfDefBuilder::AddMethod(typeDef, BfMethodType_Ctor, BfProtection_Public, false, "");
  6503. if (typeDef->mIsDelegate)
  6504. BfDefBuilder::AddDynamicCastMethods(typeDef);
  6505. delegateType->mContext = mContext;
  6506. delegateType->mTypeDef = typeDef;
  6507. InitType(delegateType, BfPopulateType_DataAndMethods);
  6508. resolvedEntry->mValue = delegateType;
  6509. // #ifdef _DEBUG
  6510. // if (BfResolvedTypeSet::Hash(delegateType, &lookupCtx) != resolvedEntry->mHash)
  6511. // {
  6512. // int refHash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx);
  6513. // int typeHash = BfResolvedTypeSet::Hash(delegateType, &lookupCtx);
  6514. // BF_ASSERT(refHash == typeHash);
  6515. // }
  6516. // #endif
  6517. BF_ASSERT(BfResolvedTypeSet::Hash(delegateType, &lookupCtx) == resolvedEntry->mHash);
  6518. return ResolveTypeResult(typeRef, delegateType, populateType, resolveFlags);
  6519. }
  6520. else if (auto genericParamTypeRef = BfNodeDynCast<BfGenericParamTypeRef>(typeRef))
  6521. {
  6522. auto genericParamType = GetGenericParamType(genericParamTypeRef->mGenericParamKind, genericParamTypeRef->mGenericParamIdx);
  6523. resolvedEntry->mValue = genericParamType;
  6524. BF_ASSERT(BfResolvedTypeSet::Hash(genericParamType, &lookupCtx) == resolvedEntry->mHash);
  6525. return ResolveTypeResult(typeRef, genericParamType, populateType, resolveFlags);
  6526. }
  6527. else if (auto retTypeTypeRef = BfNodeDynCast<BfRetTypeTypeRef>(typeRef))
  6528. {
  6529. auto retTypeType = new BfRetTypeType();
  6530. retTypeType->mElementType = ResolveTypeRef(retTypeTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  6531. // We know this is a generic param type, it can't fail to resolve
  6532. BF_ASSERT(retTypeType->mElementType);
  6533. resolvedEntry->mValue = retTypeType;
  6534. BF_ASSERT(BfResolvedTypeSet::Hash(retTypeType, &lookupCtx) == resolvedEntry->mHash);
  6535. InitType(retTypeType, populateType);
  6536. return ResolveTypeResult(typeRef, retTypeType, populateType, resolveFlags);
  6537. }
  6538. else if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  6539. {
  6540. auto leftType = ResolveTypeRef(qualifiedTypeRef->mLeft, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  6541. if (leftType == NULL)
  6542. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6543. return ResolveTypeResult(typeRef, ResolveInnerType(leftType, qualifiedTypeRef->mRight), populateType, resolveFlags);
  6544. }
  6545. else if (auto constTypeRef = BfNodeDynCastExact<BfConstTypeRef>(typeRef))
  6546. {
  6547. return ResolveTypeRef(constTypeRef->mElementType, populateType, (BfResolveTypeRefFlags)(resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam));
  6548. }
  6549. else if (auto constExprTypeRef = BfNodeDynCastExact<BfConstExprTypeRef>(typeRef))
  6550. {
  6551. auto constExprType = new BfConstExprValueType();
  6552. constExprType->mContext = mContext;
  6553. BfVariant result;
  6554. if (constExprTypeRef->mConstExpr != NULL)
  6555. {
  6556. BfType* constGenericParam = NULL;
  6557. result = mContext->mResolvedTypes.EvaluateToVariant(&lookupCtx, constExprTypeRef->mConstExpr, constGenericParam);
  6558. BF_ASSERT(constGenericParam == NULL);
  6559. }
  6560. constExprType->mType = GetPrimitiveType(result.mTypeCode);
  6561. constExprType->mValue = result;
  6562. resolvedEntry->mValue = constExprType;
  6563. BF_ASSERT(BfResolvedTypeSet::Hash(constExprType, &lookupCtx) == resolvedEntry->mHash);
  6564. InitType(constExprType, populateType);
  6565. return constExprType;
  6566. }
  6567. else
  6568. {
  6569. BF_FATAL("Not implemented!");
  6570. NotImpl(typeRef);
  6571. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6572. }
  6573. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  6574. }
  6575. BfType* BfModule::ResolveTypeRefAllowUnboundGenerics(BfTypeReference* typeRef, BfPopulateType populateType, bool resolveGenericParam)
  6576. {
  6577. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  6578. {
  6579. if (genericTypeRef->mGenericArguments.size() == 0)
  6580. {
  6581. auto genericTypeDef = ResolveGenericInstanceDef(genericTypeRef);
  6582. if (genericTypeDef == NULL)
  6583. return NULL;
  6584. BfTypeVector typeVector;
  6585. for (int i = 0; i < (int)genericTypeDef->mGenericParamDefs.size(); i++)
  6586. typeVector.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  6587. return ResolveTypeDef(genericTypeDef, typeVector);
  6588. }
  6589. }
  6590. return ResolveTypeRef(typeRef, populateType, resolveGenericParam ? (BfResolveTypeRefFlags)0 : BfResolveTypeRefFlag_NoResolveGenericParam);
  6591. }
  6592. // This finds non-default unspecialized generic type instances and converts them into a BfUnspecializedGenericTypeVariation
  6593. BfType* BfModule::CheckUnspecializedGenericType(BfGenericTypeInstance* genericTypeInst, BfPopulateType populateType)
  6594. {
  6595. int argCount = (int)genericTypeInst->mTypeGenericArguments.size();
  6596. bool isDefaultUnspecialized = true;
  6597. for (int argIdx = 0; argIdx < argCount; argIdx++)
  6598. {
  6599. auto argType = genericTypeInst->mTypeGenericArguments[argIdx];
  6600. if (argType->IsGenericParam())
  6601. {
  6602. auto genericParamType = (BfGenericParamType*)argType;
  6603. if ((genericParamType->mGenericParamKind != BfGenericParamKind_Type) || (genericParamType->mGenericParamIdx != argIdx))
  6604. isDefaultUnspecialized = false;
  6605. genericTypeInst->mIsUnspecialized = true;
  6606. }
  6607. else if (argType->IsUnspecializedType())
  6608. {
  6609. isDefaultUnspecialized = false;
  6610. genericTypeInst->mIsUnspecialized = true;
  6611. }
  6612. else
  6613. isDefaultUnspecialized = false;
  6614. }
  6615. if (genericTypeInst->mIsUnspecialized)
  6616. genericTypeInst->mIsUnspecializedVariation = !isDefaultUnspecialized;
  6617. return genericTypeInst;
  6618. }
  6619. BfTypeInstance* BfModule::GetUnspecializedTypeInstance(BfTypeInstance* typeInst)
  6620. {
  6621. if (!typeInst->IsGenericTypeInstance())
  6622. return typeInst;
  6623. auto genericTypeInst = (BfGenericTypeInstance*)typeInst;
  6624. auto result = ResolveTypeDef(genericTypeInst->mTypeDef, BfPopulateType_Declaration);
  6625. BF_ASSERT((result != NULL) && (result->IsUnspecializedType()));
  6626. if (result == NULL)
  6627. return NULL;
  6628. return result->ToTypeInstance();
  6629. }
  6630. BfType* BfModule::ResolveInnerType(BfType* outerType, BfIdentifierNode* identifier, BfPopulateType populateType, bool ignoreErrors)
  6631. {
  6632. BfDirectStrTypeReference typeRef;
  6633. typeRef.Init(identifier->ToString());
  6634. auto type = ResolveInnerType(outerType, &typeRef, populateType, ignoreErrors);
  6635. return type;
  6636. }
  6637. BfType* BfModule::ResolveTypeRef(BfAstNode* astNode, const BfSizedArray<BfTypeReference*>* genericArgs, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  6638. {
  6639. if ((genericArgs == NULL) || (genericArgs->size() == 0))
  6640. {
  6641. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(astNode))
  6642. {
  6643. BfNamedTypeReference typeRef;
  6644. typeRef.mNameNode = identifier;
  6645. typeRef.mSrcEnd = 0;
  6646. typeRef.mToken = BfToken_None;
  6647. auto type = ResolveTypeRef(&typeRef, populateType, resolveFlags);
  6648. return type;
  6649. }
  6650. }
  6651. BfAstAllocator alloc;
  6652. alloc.mSourceData = astNode->GetSourceData();
  6653. std::function<BfTypeReference*(BfAstNode*)> _ConvType = [&] (BfAstNode* astNode) -> BfTypeReference*
  6654. {
  6655. if (auto typeRef = BfNodeDynCast<BfTypeReference>(astNode))
  6656. return typeRef;
  6657. BfTypeReference* result = NULL;
  6658. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(astNode))
  6659. {
  6660. auto* typeRef = alloc.Alloc<BfNamedTypeReference>();
  6661. typeRef->mNameNode = identifier;
  6662. result = typeRef;
  6663. }
  6664. else if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(astNode))
  6665. {
  6666. auto qualifiedTypeRef = alloc.Alloc<BfQualifiedTypeReference>();
  6667. qualifiedTypeRef->mLeft = _ConvType(memberRefExpr->mTarget);
  6668. qualifiedTypeRef->mDot = memberRefExpr->mDotToken;
  6669. qualifiedTypeRef->mRight = _ConvType(memberRefExpr->mMemberName);
  6670. if ((qualifiedTypeRef->mLeft == NULL) || (qualifiedTypeRef->mRight == NULL))
  6671. return NULL;
  6672. result = qualifiedTypeRef;
  6673. }
  6674. if (result == NULL)
  6675. return NULL;
  6676. result->SetSrcStart(astNode->GetSrcStart());
  6677. result->SetSrcEnd(astNode->GetSrcEnd());
  6678. return result;
  6679. };
  6680. auto typeRef = _ConvType(astNode);
  6681. if (typeRef == NULL)
  6682. return NULL;
  6683. if ((genericArgs != NULL) && (genericArgs->size() != 0))
  6684. {
  6685. auto genericInstanceTypeRef = alloc.Alloc<BfGenericInstanceTypeRef>();
  6686. genericInstanceTypeRef->SetSrcStart(typeRef->GetSrcStart());
  6687. genericInstanceTypeRef->mElementType = typeRef;
  6688. #ifdef BF_AST_HAS_PARENT_MEMBER
  6689. typeRef->mParent = genericInstanceTypeRef;
  6690. #endif
  6691. BfDeferredAstSizedArray<BfTypeReference*> arguments(genericInstanceTypeRef->mGenericArguments, &alloc);
  6692. for (auto genericArg : *genericArgs)
  6693. {
  6694. if (genericArg != NULL)
  6695. {
  6696. arguments.push_back(genericArg);
  6697. genericInstanceTypeRef->SetSrcEnd(genericArg->GetSrcEnd());
  6698. }
  6699. }
  6700. typeRef = genericInstanceTypeRef;
  6701. }
  6702. return ResolveTypeRef(typeRef, populateType, resolveFlags);
  6703. }
  6704. // This flow should mirror CastToValue
  6705. bool BfModule::CanImplicitlyCast(BfTypedValue typedVal, BfType* toType, BfCastFlags castFlags)
  6706. {
  6707. BfType* fromType = typedVal.mType;
  6708. if (fromType == toType)
  6709. return true;
  6710. // Ref X to Ref Y, X* to Y*
  6711. {
  6712. bool checkUnderlying = false;
  6713. if (((typedVal.mType->IsRef()) && (toType->IsRef())))
  6714. {
  6715. auto fromRefType = (BfRefType*)typedVal.mType;
  6716. auto toRefType = (BfRefType*)toType;
  6717. if (fromRefType->mRefKind == toRefType->mRefKind)
  6718. checkUnderlying = true;
  6719. else if ((fromRefType->mRefKind == BfRefType::RefKind_Ref) && (toRefType->mRefKind == BfRefType::RefKind_Mut))
  6720. checkUnderlying = true; // Allow a ref-to-mut implicit conversion
  6721. }
  6722. if ((typedVal.mType->IsPointer()) && (toType->IsPointer()))
  6723. checkUnderlying = true;
  6724. if (checkUnderlying)
  6725. {
  6726. auto fromInner = typedVal.mType->GetUnderlyingType();
  6727. auto toInner = toType->GetUnderlyingType();
  6728. if (fromInner == toInner)
  6729. return true;
  6730. // ref int <-> ref int64/int32 (of same size)
  6731. if (((fromInner->IsInteger()) && (toInner->IsInteger())) &&
  6732. (fromInner->mSize == toInner->mSize) &&
  6733. (fromInner->IsSigned() == toInner->IsSigned()))
  6734. return true;
  6735. }
  6736. }
  6737. // Generic param -> *
  6738. if ((typedVal.mType->IsGenericParam()) && (!toType->IsGenericParam()))
  6739. {
  6740. if (toType == mContext->mBfObjectType)
  6741. {
  6742. //auto resolvedType = ResolveGenericType(typedVal.mType);
  6743. //auto resolvedType = typedVal.mType;
  6744. /*if (!resolvedType->IsGenericParam())
  6745. return CanImplicitlyCast(BfTypedValue(typedVal.mValue, resolvedType), toType);*/
  6746. // Can we never NOT do this?
  6747. return true;
  6748. }
  6749. // For these casts, it's just important we get *A* value to work with here,
  6750. // as this is just use for unspecialized parsing. We don't use the generated code
  6751. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  6752. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  6753. {
  6754. return true;
  6755. }
  6756. if (toType->IsInterface())
  6757. {
  6758. for (auto iface : genericParamInst->mInterfaceConstraints)
  6759. if (TypeIsSubTypeOf(iface, toType->ToTypeInstance()))
  6760. return true;
  6761. }
  6762. if (genericParamInst->mTypeConstraint != NULL)
  6763. {
  6764. auto defaultFromValue = GetDefaultTypedValue(genericParamInst->mTypeConstraint);
  6765. auto result = CanImplicitlyCast(defaultFromValue, toType);
  6766. if ((result) && (genericParamInst->mTypeConstraint->IsDelegate()) && (toType->IsDelegate()))
  6767. {
  6768. // Don't allow cast when we are constrained by a delegate type, because BfMethodRefs can match and we require an actual alloc
  6769. return false;
  6770. }
  6771. return result;
  6772. }
  6773. // Generic constrained with class or pointer type -> void*
  6774. if (toType->IsVoidPtr())
  6775. {
  6776. if ((genericParamInst->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_StructPtr)) ||
  6777. ((genericParamInst->mTypeConstraint != NULL) &&
  6778. ((genericParamInst->mTypeConstraint->IsPointer()) || (genericParamInst->mTypeConstraint->IsObjectOrInterface()))))
  6779. {
  6780. return true;
  6781. }
  6782. }
  6783. }
  6784. // * -> Generic param
  6785. if (toType->IsGenericParam())
  6786. {
  6787. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)toType);
  6788. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var)
  6789. return true;
  6790. if (typedVal.mType->IsNull())
  6791. {
  6792. bool allowCast = (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) || (genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr);
  6793. if ((!allowCast) && (genericParamInst->mTypeConstraint != NULL))
  6794. allowCast = genericParamInst->mTypeConstraint->IsObject() || genericParamInst->mTypeConstraint->IsPointer();
  6795. if (allowCast)
  6796. return true;
  6797. }
  6798. if (genericParamInst->mTypeConstraint != NULL)
  6799. {
  6800. if (CanImplicitlyCast(typedVal, genericParamInst->mTypeConstraint))
  6801. return true;
  6802. }
  6803. }
  6804. // Struct truncate
  6805. if ((fromType->IsStruct()) && (toType->IsStruct()))
  6806. {
  6807. auto fromTypeInstance = fromType->ToTypeInstance();
  6808. auto toTypeInstance = toType->ToTypeInstance();
  6809. if (TypeIsSubTypeOf(fromTypeInstance, toTypeInstance))
  6810. return true;
  6811. }
  6812. if ((fromType->IsVar()) || (toType->IsVar()))
  6813. return true;
  6814. // Null -> ObjectInst|IFace|ptr
  6815. if ((fromType->IsNull()) &&
  6816. ((toType->IsObjectOrInterface()) || (toType->IsPointer()) || (toType->IsPointer())))
  6817. {
  6818. return true;
  6819. }
  6820. // Object/struct -> object/struct|IFace
  6821. if ((fromType->IsTypeInstance()) && ((toType->IsTypeInstance() || (toType->IsInterface()))))
  6822. {
  6823. auto fromTypeInstance = fromType->ToTypeInstance();
  6824. auto toTypeInstance = toType->ToTypeInstance();
  6825. if (TypeIsSubTypeOf(fromTypeInstance, toTypeInstance))
  6826. return true;
  6827. }
  6828. // concrete IFace -> object|IFace
  6829. if ((fromType->IsConcreteInterfaceType()) && ((toType->IsObject() || (toType->IsInterface()))))
  6830. {
  6831. auto concreteInterfaceType = (BfConcreteInterfaceType*)fromType;
  6832. if ((toType->IsObject()) || (concreteInterfaceType->mInterface == toType))
  6833. return true;
  6834. }
  6835. // IFace -> object
  6836. if ((fromType->IsInterface()) && (toType == mContext->mBfObjectType))
  6837. return true;
  6838. if (toType->IsPointer())
  6839. {
  6840. // Ptr -> Ptr
  6841. if (fromType->IsPointer())
  6842. {
  6843. bool allowCast = false;
  6844. auto fromPointerType = (BfPointerType*)typedVal.mType;
  6845. auto toPointerType = (BfPointerType*)toType;
  6846. auto fromUnderlying = fromPointerType->mElementType;
  6847. auto toUnderlying = toPointerType->mElementType;
  6848. // Allow cast from T[size]* to T* implicitly
  6849. // And from T* to T[size]* explicitly
  6850. if (fromUnderlying->IsSizedArray())
  6851. fromUnderlying = fromUnderlying->GetUnderlyingType();
  6852. // if ((toUnderlying->IsSizedArray()) && (explicitCast))
  6853. // toUnderlying = toUnderlying->GetUnderlyingType();
  6854. if ((fromUnderlying == toUnderlying) ||
  6855. (TypeIsSubTypeOf(fromUnderlying->ToTypeInstance(), toUnderlying->ToTypeInstance())) ||
  6856. (toUnderlying->IsVoid()))
  6857. allowCast = true;
  6858. if (allowCast)
  6859. return true;
  6860. }
  6861. else if (fromType->IsObject())
  6862. {
  6863. auto fromTypeInst = fromType->ToTypeInstance();
  6864. auto charType = GetPrimitiveType(BfTypeCode_Char8);
  6865. auto charPtrType = CreatePointerType(charType);
  6866. if ((fromTypeInst->mTypeDef == mCompiler->mStringTypeDef) && (toType == charPtrType))
  6867. {
  6868. // String Object -> char* literal
  6869. return true;
  6870. }
  6871. }
  6872. /*else if (typedVal.mType->IsSizedArray())
  6873. {
  6874. if (typedVal.IsAddr())
  6875. {
  6876. BfSizedArrayType* arrayType = (BfSizedArrayType*)typedVal.mType;
  6877. BfTypedValue returnPointer(typedVal.mValue, CreatePointerType(arrayType->mElementType));
  6878. return CanImplicitlyCast(returnPointer, toType);
  6879. }
  6880. }*/
  6881. }
  6882. // Boxing?
  6883. if (((fromType->IsValueType()) || (fromType->IsPointer()) || (fromType->IsValuelessType())) &&
  6884. ((toType->IsInterface()) || (toType == mContext->mBfObjectType)))
  6885. {
  6886. // if (fromType->IsPointer())
  6887. // {
  6888. // if (toType == mContext->mBfObjectType)
  6889. // return true;
  6890. // return false;
  6891. // }
  6892. if (toType == mContext->mBfObjectType)
  6893. return true;
  6894. BfTypeInstance* fromStructTypeInstance = NULL;
  6895. fromStructTypeInstance = fromType->ToTypeInstance();
  6896. if (fromStructTypeInstance == NULL)
  6897. {
  6898. if (fromType->IsPrimitiveType())
  6899. {
  6900. auto primType = (BfPrimitiveType*)fromType;
  6901. fromStructTypeInstance = GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  6902. }
  6903. else
  6904. return false;
  6905. }
  6906. auto toTypeInstance = toType->ToTypeInstance();
  6907. // Need to box it
  6908. if (TypeIsSubTypeOf(fromStructTypeInstance, toTypeInstance))
  6909. return true;
  6910. }
  6911. if (fromType->IsRef())
  6912. {
  6913. if (toType->IsRef())
  6914. {
  6915. BfTypedValue unrefValue = BfTypedValue(typedVal.mValue, fromType->GetUnderlyingType(), true);
  6916. return CanImplicitlyCast(unrefValue, toType->GetUnderlyingType());
  6917. }
  6918. else
  6919. {
  6920. // ref T -> T
  6921. return fromType->GetUnderlyingType() == toType;
  6922. }
  6923. }
  6924. // Int -> Enum
  6925. if ((typedVal.mType->IsIntegral()) && (toType->IsEnum()))
  6926. {
  6927. // Allow implicit cast of zero
  6928. if (typedVal.mValue)
  6929. {
  6930. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  6931. if ((constant != NULL) && (BfIRBuilder::IsInt(constant->mTypeCode)))
  6932. {
  6933. int64 srcVal = constant->mInt64;
  6934. if (srcVal == 0)
  6935. return true;
  6936. }
  6937. }
  6938. }
  6939. // Tuple -> Tuple
  6940. if ((typedVal.mType->IsTuple()) && (toType->IsTuple()))
  6941. {
  6942. auto fromTupleType = (BfTupleType*)typedVal.mType;
  6943. auto toTupleType = (BfTupleType*)toType;
  6944. if (fromTupleType->mFieldInstances.size() == toTupleType->mFieldInstances.size())
  6945. {
  6946. for (int valueIdx = 0; valueIdx < (int)fromTupleType->mFieldInstances.size(); valueIdx++)
  6947. {
  6948. BfFieldInstance* fromFieldInstance = &fromTupleType->mFieldInstances[valueIdx];
  6949. BfFieldInstance* toFieldInstance = &toTupleType->mFieldInstances[valueIdx];
  6950. BfFieldDef* fromFieldDef = fromFieldInstance->GetFieldDef();
  6951. BfFieldDef* toFieldDef = toFieldInstance->GetFieldDef();
  6952. auto fromFieldType = fromFieldInstance->GetResolvedType();
  6953. auto toFieldType = toFieldInstance->GetResolvedType();
  6954. // Either the names have to match or one has to be unnamed
  6955. if ((!fromFieldDef->IsUnnamedTupleField()) && (!toFieldDef->IsUnnamedTupleField()) &&
  6956. (fromFieldDef->mName != toFieldDef->mName))
  6957. return false;
  6958. if (toFieldType->IsVoid())
  6959. continue; // Allow sinking to void
  6960. if (!CanImplicitlyCast(GetFakeTypedValue(fromFieldType), toFieldType))
  6961. return false;
  6962. }
  6963. return true;
  6964. }
  6965. }
  6966. // -> const <value>
  6967. if (toType->IsConstExprValue())
  6968. {
  6969. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  6970. if (constant != NULL)
  6971. {
  6972. BfConstExprValueType* toConstExprValueType = (BfConstExprValueType*)toType;
  6973. auto variantVal = TypedValueToVariant(NULL, typedVal);
  6974. if ((mBfIRBuilder->IsInt(variantVal.mTypeCode)) && (mBfIRBuilder->IsInt(toConstExprValueType->mValue.mTypeCode)))
  6975. {
  6976. if (variantVal.mInt64 == toConstExprValueType->mValue.mInt64)
  6977. return true;
  6978. }
  6979. else if ((mBfIRBuilder->IsFloat(variantVal.mTypeCode)) && (mBfIRBuilder->IsFloat(toConstExprValueType->mValue.mTypeCode)))
  6980. {
  6981. if (variantVal.ToDouble() == toConstExprValueType->mValue.ToDouble())
  6982. return true;
  6983. }
  6984. }
  6985. }
  6986. if ((fromType->IsPrimitiveType()) && (toType->IsPrimitiveType()))
  6987. {
  6988. auto fromPrimType = (BfPrimitiveType*)fromType;
  6989. auto toPrimType = (BfPrimitiveType*)toType;
  6990. BfTypeCode fromTypeCode = fromPrimType->mTypeDef->mTypeCode;
  6991. BfTypeCode toTypeCode = toPrimType->mTypeDef->mTypeCode;
  6992. // Must be from a default int to do an implicit constant cast, not casted by user, ie: (ushort)123
  6993. if ((toType->IsIntegral()) && (typedVal.mValue))
  6994. {
  6995. // Allow constant ints to be implicitly casted to a smaller type if they fit
  6996. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  6997. if (constant != NULL)
  6998. {
  6999. if (BfIRBuilder::IsInt(constant->mTypeCode))
  7000. {
  7001. int64 srcVal = constant->mInt64;
  7002. if (toPrimType->IsChar())
  7003. {
  7004. if (srcVal == 0)
  7005. return true;
  7006. }
  7007. else if ((fromPrimType->IsChar()) && (!toPrimType->IsChar()))
  7008. {
  7009. // Never allow this
  7010. }
  7011. else if ((constant->mTypeCode == BfTypeCode_UInt64) && (srcVal < 0))
  7012. {
  7013. // There's nothing that this could fit into
  7014. }
  7015. else if (toType->IsSigned())
  7016. {
  7017. int64 minVal = -(1LL << (8 * toType->mSize - 1));
  7018. int64 maxVal = (1LL << (8 * toType->mSize - 1)) - 1;
  7019. if ((srcVal >= minVal) && (srcVal <= maxVal))
  7020. return true;
  7021. }
  7022. else if (toType->mSize == 8) // ulong
  7023. {
  7024. if (srcVal >= 0)
  7025. return true;
  7026. }
  7027. else
  7028. {
  7029. int64 minVal = 0;
  7030. int64 maxVal = (1LL << (8 * toType->mSize)) - 1;
  7031. if ((srcVal >= minVal) && (srcVal <= maxVal))
  7032. return true;
  7033. }
  7034. }
  7035. else if (constant->mConstType == BfConstType_Undef)
  7036. {
  7037. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  7038. auto undefConst = (BfConstantUndef*)constant;
  7039. auto fakeVal = GetFakeTypedValue(GetPrimitiveType(undefConst->mTypeCode));
  7040. if (CanImplicitlyCast(fakeVal, toType))
  7041. return true;
  7042. }
  7043. }
  7044. }
  7045. switch (toTypeCode)
  7046. {
  7047. case BfTypeCode_UInt8:
  7048. switch (fromTypeCode)
  7049. {
  7050. case BfTypeCode_UInt8:
  7051. return true;
  7052. default: break;
  7053. }
  7054. break;
  7055. case BfTypeCode_Char16:
  7056. switch (fromTypeCode)
  7057. {
  7058. case BfTypeCode_Char8:
  7059. return true;
  7060. default: break;
  7061. }
  7062. break;
  7063. case BfTypeCode_Int16:
  7064. switch (fromTypeCode)
  7065. {
  7066. case BfTypeCode_Int8:
  7067. return true;
  7068. case BfTypeCode_UInt8:
  7069. return true;
  7070. default: break;
  7071. }
  7072. break;
  7073. case BfTypeCode_UInt16:
  7074. switch (fromTypeCode)
  7075. {
  7076. case BfTypeCode_UInt8:
  7077. return true;
  7078. default: break;
  7079. }
  7080. break;
  7081. case BfTypeCode_Int32:
  7082. switch (fromTypeCode)
  7083. {
  7084. case BfTypeCode_Int8:
  7085. case BfTypeCode_Int16:
  7086. return true;
  7087. case BfTypeCode_IntPtr:
  7088. if (mCompiler->mSystem->mPtrSize == 4)
  7089. return true;
  7090. break;
  7091. case BfTypeCode_UInt8:
  7092. case BfTypeCode_UInt16:
  7093. return true;
  7094. default: break;
  7095. }
  7096. break;
  7097. case BfTypeCode_Char32:
  7098. switch (fromTypeCode)
  7099. {
  7100. case BfTypeCode_Char8:
  7101. case BfTypeCode_Char16:
  7102. return true;
  7103. default: break;
  7104. }
  7105. break;
  7106. case BfTypeCode_UInt32:
  7107. switch (fromTypeCode)
  7108. {
  7109. case BfTypeCode_UInt8:
  7110. case BfTypeCode_UInt16:
  7111. case BfTypeCode_UInt32:
  7112. return true;
  7113. case BfTypeCode_UIntPtr:
  7114. if (mCompiler->mSystem->mPtrSize == 4)
  7115. return true;
  7116. break;
  7117. default: break;
  7118. }
  7119. break;
  7120. case BfTypeCode_Int64:
  7121. switch (fromTypeCode)
  7122. {
  7123. case BfTypeCode_Int8:
  7124. case BfTypeCode_Int16:
  7125. case BfTypeCode_Int32:
  7126. case BfTypeCode_IntPtr:
  7127. return true;
  7128. case BfTypeCode_UInt8:
  7129. case BfTypeCode_UInt16:
  7130. case BfTypeCode_UInt32:
  7131. return true;
  7132. default: break;
  7133. }
  7134. break;
  7135. case BfTypeCode_UInt64:
  7136. switch (fromTypeCode)
  7137. {
  7138. case BfTypeCode_UInt8:
  7139. case BfTypeCode_UInt16:
  7140. case BfTypeCode_UInt32:
  7141. case BfTypeCode_UIntPtr:
  7142. return true;
  7143. default: break;
  7144. }
  7145. break;
  7146. case BfTypeCode_IntPtr:
  7147. switch (fromTypeCode)
  7148. {
  7149. case BfTypeCode_Int8:
  7150. case BfTypeCode_Int16:
  7151. case BfTypeCode_Int32:
  7152. return true;
  7153. case BfTypeCode_UInt8:
  7154. case BfTypeCode_UInt16:
  7155. return true;
  7156. case BfTypeCode_UInt32:
  7157. case BfTypeCode_Int64:
  7158. if (mCompiler->mSystem->mPtrSize == 8)
  7159. return true;
  7160. break;
  7161. default: break;
  7162. }
  7163. break;
  7164. case BfTypeCode_UIntPtr:
  7165. switch (fromTypeCode)
  7166. {
  7167. case BfTypeCode_UInt8:
  7168. case BfTypeCode_UInt16:
  7169. case BfTypeCode_UInt32:
  7170. return true;
  7171. case BfTypeCode_UInt64:
  7172. if (mCompiler->mSystem->mPtrSize == 8)
  7173. return true;
  7174. break;
  7175. default: break;
  7176. }
  7177. break;
  7178. case BfTypeCode_Single:
  7179. switch (fromTypeCode)
  7180. {
  7181. case BfTypeCode_Int8:
  7182. case BfTypeCode_Int16:
  7183. case BfTypeCode_Int32:
  7184. case BfTypeCode_Int64:
  7185. case BfTypeCode_IntPtr:
  7186. case BfTypeCode_IntUnknown:
  7187. return true;
  7188. case BfTypeCode_UInt8:
  7189. case BfTypeCode_UInt16:
  7190. case BfTypeCode_UInt32:
  7191. case BfTypeCode_UInt64:
  7192. case BfTypeCode_UIntPtr:
  7193. case BfTypeCode_UIntUnknown:
  7194. return true;
  7195. default: break;
  7196. }
  7197. break;
  7198. case BfTypeCode_Double:
  7199. switch (fromTypeCode)
  7200. {
  7201. case BfTypeCode_Int8:
  7202. case BfTypeCode_Int16:
  7203. case BfTypeCode_Int32:
  7204. case BfTypeCode_Int64:
  7205. case BfTypeCode_IntPtr:
  7206. case BfTypeCode_IntUnknown:
  7207. return true;
  7208. case BfTypeCode_UInt8:
  7209. case BfTypeCode_UInt16:
  7210. case BfTypeCode_UInt32:
  7211. case BfTypeCode_UInt64:
  7212. case BfTypeCode_UIntPtr:
  7213. case BfTypeCode_UIntUnknown:
  7214. return true;
  7215. case BfTypeCode_Single:
  7216. return true;
  7217. default: break;
  7218. }
  7219. break;
  7220. default: break;
  7221. }
  7222. }
  7223. // wrappable -> struct
  7224. // if ((fromType->IsWrappableType()) && (toType->IsStruct()))
  7225. // {
  7226. // auto wrappableType = GetWrappedStructType(fromType);
  7227. // if (TypeIsSubTypeOf(wrappableType, toType->ToTypeInstance()))
  7228. // return true;
  7229. // }
  7230. // Check user-defined operators
  7231. // {
  7232. // auto fromTypeInstance = fromType->ToTypeInstance();
  7233. // auto toTypeInstance = toType->ToTypeInstance();
  7234. //
  7235. // int bestFromDist = INT_MAX;
  7236. // BfType* bestFromType = NULL;
  7237. // int bestNegFromDist = INT_MAX;
  7238. // BfType* bestNegFromType = NULL;
  7239. //
  7240. // int bestToDist = INT_MAX;
  7241. // BfType* bestToType = NULL;
  7242. // int bestNegToDist = INT_MAX;
  7243. // BfType* bestNegToType = NULL;
  7244. //
  7245. // for (int pass = 0; pass < 2; pass++)
  7246. // {
  7247. // BfBaseClassWalker baseClassWalker(fromType, toType, this);
  7248. // while (true)
  7249. // {
  7250. // auto entry = baseClassWalker.Next();
  7251. // auto checkInstance = entry.mTypeInstance;
  7252. // if (checkInstance == NULL)
  7253. // break;
  7254. //
  7255. // for (auto operatorDef : checkInstance->mTypeDef->mOperators)
  7256. // {
  7257. // if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  7258. // {
  7259. // if ((operatorDef->mOperatorDeclaration->mExplicitToken != NULL) &&
  7260. // (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit))
  7261. // continue;
  7262. //
  7263. // // Get in native module so our module doesn't get a reference to it - we may not end up calling it at all!
  7264. // auto methodInst = checkInstance->mModule->GetRawMethodInstanceAtIdx(checkInstance, operatorDef->mIdx);
  7265. //
  7266. // if (methodInst->GetParamCount() != 1)
  7267. // {
  7268. // //AssertErrorState();
  7269. // continue;
  7270. // }
  7271. //
  7272. // auto checkFromType = methodInst->GetParamType(0);
  7273. // if (checkFromType->IsSelf())
  7274. // checkFromType = entry.mSrcType;
  7275. //
  7276. // // Selection pass
  7277. // if (pass == 0)
  7278. // {
  7279. // int fromDist = GetTypeDistance(checkFromType, fromType);
  7280. // int toDist = GetTypeDistance(toType, methodInst->mReturnType);
  7281. //
  7282. // if ((fromDist == INT_MAX) || (toDist == INT_MAX))
  7283. // continue;
  7284. //
  7285. // if ((fromDist >= 0) && (toDist >= 0))
  7286. // {
  7287. // if ((fromDist >= 0) && (fromDist < bestFromDist))
  7288. // {
  7289. // bestFromDist = fromDist;
  7290. // bestFromType = checkFromType;
  7291. // }
  7292. //
  7293. // if ((fromDist >= 0) && (toDist < bestToDist))
  7294. // {
  7295. // bestToDist = toDist;
  7296. // bestToType = methodInst->mReturnType;
  7297. // }
  7298. // }
  7299. // }
  7300. // else // Execution Pass
  7301. // {
  7302. // auto returnType = methodInst->mReturnType;
  7303. // if (returnType->IsSelf())
  7304. // returnType = entry.mSrcType;
  7305. //
  7306. // if ((checkFromType == bestFromType) && (methodInst->mReturnType == bestToType))
  7307. // {
  7308. // return true;
  7309. // }
  7310. // }
  7311. // }
  7312. // }
  7313. // }
  7314. //
  7315. // if (bestFromType == NULL)
  7316. // bestFromType = bestNegFromType;
  7317. // if (bestToType == NULL)
  7318. // bestToType = bestNegToType;
  7319. //
  7320. // if ((bestFromType == NULL) || (bestToType == NULL))
  7321. // break;
  7322. // }
  7323. // }
  7324. // Check user-defined operators
  7325. if ((castFlags & BfCastFlags_NoConversionOperator) == 0)
  7326. {
  7327. auto fromType = typedVal.mType;
  7328. auto fromTypeInstance = fromType->ToTypeInstance();
  7329. auto toTypeInstance = toType->ToTypeInstance();
  7330. auto liftedFromType = ((fromTypeInstance != NULL) && fromTypeInstance->IsNullable()) ? fromTypeInstance->GetUnderlyingType() : NULL;
  7331. auto liftedToType = ((toTypeInstance != NULL) && toTypeInstance->IsNullable()) ? toTypeInstance->GetUnderlyingType() : NULL;
  7332. int bestFromDist = INT_MAX;
  7333. BfType* bestFromType = NULL;
  7334. int bestNegFromDist = INT_MAX;
  7335. BfType* bestNegFromType = NULL;
  7336. int bestToDist = INT_MAX;
  7337. BfType* bestToType = NULL;
  7338. int bestNegToDist = INT_MAX;
  7339. BfType* bestNegToType = NULL;
  7340. bool isAmbiguousCast = false;
  7341. BfIRValue conversionResult;
  7342. BfMethodInstance* opMethodInstance = NULL;
  7343. BfType* opMethodSrcType = NULL;
  7344. // Normal, lifted, execute
  7345. for (int pass = 0; pass < 3; pass++)
  7346. {
  7347. auto checkToType = toType;
  7348. auto checkFromType = fromType;
  7349. if (pass == 1)
  7350. {
  7351. if ((bestFromType != NULL) && (bestToType != NULL))
  7352. continue;
  7353. if (liftedFromType != NULL)
  7354. checkFromType = liftedFromType;
  7355. if (liftedToType != NULL)
  7356. checkToType = liftedToType;
  7357. }
  7358. else if (pass == 2)
  7359. {
  7360. if ((bestFromType == NULL) || (bestToType == NULL))
  7361. break;
  7362. }
  7363. BfBaseClassWalker baseClassWalker(fromType, toType, this);
  7364. while (true)
  7365. {
  7366. auto entry = baseClassWalker.Next();
  7367. auto checkInstance = entry.mTypeInstance;
  7368. if (checkInstance == NULL)
  7369. break;
  7370. for (auto operatorDef : checkInstance->mTypeDef->mOperators)
  7371. {
  7372. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  7373. {
  7374. if ((operatorDef->mOperatorDeclaration->mExplicitToken != NULL) &&
  7375. (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit))
  7376. continue;
  7377. auto methodInst = GetRawMethodInstanceAtIdx(checkInstance, operatorDef->mIdx);
  7378. if (methodInst->GetParamCount() != 1)
  7379. {
  7380. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  7381. continue;
  7382. }
  7383. auto methodFromType = methodInst->GetParamType(0);
  7384. auto methodToType = methodInst->mReturnType;
  7385. if (methodFromType->IsSelf())
  7386. methodFromType = entry.mSrcType;
  7387. if (methodToType->IsSelf())
  7388. methodToType = entry.mSrcType;
  7389. // Selection pass
  7390. if (pass < 2)
  7391. {
  7392. auto methodCheckFromType = methodFromType;
  7393. auto methodCheckToType = methodToType;
  7394. if (pass == 1)
  7395. {
  7396. // Only check inner type on lifted types when we aren't checking conversions within lifted class
  7397. // This avoid some infinite conversions
  7398. if ((methodCheckFromType->IsNullable()) && (!checkInstance->IsNullable()))
  7399. methodCheckFromType = methodCheckFromType->GetUnderlyingType();
  7400. if ((methodCheckToType->IsNullable()) && (!checkInstance->IsNullable()))
  7401. methodCheckToType = methodCheckToType->GetUnderlyingType();
  7402. }
  7403. int fromDist = GetTypeDistance(methodCheckFromType, checkFromType);
  7404. if (fromDist < 0)
  7405. {
  7406. // Allow us to cast a constant int to a smaller type if it satisfies the cast operator
  7407. if ((typedVal.mValue.IsConst()) && (methodCheckFromType != toType) && (CanImplicitlyCast(typedVal, methodCheckFromType)))
  7408. {
  7409. fromDist = 0;
  7410. }
  7411. }
  7412. int toDist = GetTypeDistance(methodCheckToType, checkToType);
  7413. if ((fromDist == INT_MAX) || (toDist == INT_MAX))
  7414. continue;
  7415. if ((fromDist >= 0) && (toDist >= 0))
  7416. {
  7417. if ((fromDist >= 0) && (fromDist < bestFromDist))
  7418. {
  7419. bestFromDist = fromDist;
  7420. bestFromType = methodFromType;
  7421. }
  7422. if ((toDist >= 0) && (toDist < bestToDist))
  7423. {
  7424. bestToDist = toDist;
  7425. bestToType = methodToType;
  7426. }
  7427. }
  7428. }
  7429. else if (pass == 2) // Execution Pass
  7430. {
  7431. if ((methodFromType == bestFromType) && (methodToType == bestToType))
  7432. {
  7433. return true;
  7434. }
  7435. }
  7436. }
  7437. }
  7438. if (isAmbiguousCast)
  7439. break;
  7440. }
  7441. if (bestFromType == NULL)
  7442. bestFromType = bestNegFromType;
  7443. if (bestToType == NULL)
  7444. bestToType = bestNegToType;
  7445. }
  7446. }
  7447. return false;
  7448. }
  7449. bool BfModule::AreSplatsCompatible(BfType* fromType, BfType* toType, bool* outNeedsMemberCasting)
  7450. {
  7451. if ((fromType->IsTypeInstance()) && (!fromType->IsSplattable()))
  7452. return false;
  7453. if ((toType->IsTypeInstance()) && (!toType->IsSplattable()))
  7454. return false;
  7455. auto _GetTypes = [&](BfType* type, Array<BfType*>& types)
  7456. {
  7457. BfTypeUtils::SplatIterate([&](BfType* memberType) { types.Add(memberType); }, type);
  7458. };
  7459. Array<BfType*> fromTypes;
  7460. _GetTypes(fromType, fromTypes);
  7461. Array<BfType*> toTypes;
  7462. _GetTypes(toType, toTypes);
  7463. if (toTypes.size() > fromTypes.size())
  7464. return false;
  7465. for (int i = 0; i < toTypes.size(); i++)
  7466. {
  7467. BfType* fromMemberType = fromTypes[i];
  7468. BfType* toMemberType = toTypes[i];
  7469. if (fromMemberType != toMemberType)
  7470. {
  7471. if ((outNeedsMemberCasting != NULL) &&
  7472. (fromMemberType->IsIntPtrable()) && (toMemberType->IsIntPtrable()))
  7473. *outNeedsMemberCasting = true;
  7474. else
  7475. return false;
  7476. }
  7477. }
  7478. return true;
  7479. }
  7480. BfIRValue BfModule::CastToFunction(BfAstNode* srcNode, BfMethodInstance* methodInstance, BfType* toType, BfCastFlags castFlags)
  7481. {
  7482. auto invokeMethodInstance = GetDelegateInvokeMethod(toType->ToTypeInstance());
  7483. if (invokeMethodInstance->IsExactMatch(methodInstance, false, true))
  7484. {
  7485. BfModuleMethodInstance methodRefMethod;
  7486. if (methodInstance->mDeclModule == this)
  7487. methodRefMethod = methodInstance;
  7488. else
  7489. methodRefMethod = ReferenceExternalMethodInstance(methodInstance);
  7490. auto dataType = GetPrimitiveType(BfTypeCode_IntPtr);
  7491. if (!methodRefMethod.mFunc)
  7492. {
  7493. if (HasCompiledOutput())
  7494. AssertErrorState();
  7495. return GetDefaultValue(dataType);
  7496. }
  7497. auto bindFuncVal = methodRefMethod.mFunc;
  7498. if (mCompiler->mOptions.mAllowHotSwapping)
  7499. bindFuncVal = mBfIRBuilder->RemapBindFunction(bindFuncVal);
  7500. return mBfIRBuilder->CreatePtrToInt(bindFuncVal, BfTypeCode_IntPtr);
  7501. }
  7502. if ((castFlags & BfCastFlags_SilentFail) == 0)
  7503. {
  7504. if (invokeMethodInstance->IsExactMatch(methodInstance, true, true))
  7505. {
  7506. Fail(StrFormat("Non-static method '%s' cannot match '%s' because it contains captured variables, consider using a delegate or removing captures", MethodToString(methodInstance).c_str(), TypeToString(toType).c_str()), srcNode);
  7507. }
  7508. else if (invokeMethodInstance->IsExactMatch(methodInstance, false, false))
  7509. {
  7510. Fail(StrFormat("Non-static method '%s' cannot match '%s', consider adding '%s this' to the function parameters", MethodToString(methodInstance).c_str(), TypeToString(toType).c_str(), TypeToString(methodInstance->GetParamType(-1)).c_str()), srcNode);
  7511. }
  7512. }
  7513. return BfIRValue();
  7514. }
  7515. BfIRValue BfModule::CastToValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, BfCastFlags castFlags, BfCastResultFlags* resultFlags)
  7516. {
  7517. bool explicitCast = (castFlags & BfCastFlags_Explicit) != 0;
  7518. if (typedVal.mType == toType)
  7519. {
  7520. if (resultFlags != NULL)
  7521. {
  7522. if (typedVal.IsAddr())
  7523. *resultFlags = (BfCastResultFlags)(*resultFlags | BfCastResultFlags_IsAddr);
  7524. if (typedVal.mKind == BfTypedValueKind_TempAddr)
  7525. *resultFlags = (BfCastResultFlags)(*resultFlags | BfCastResultFlags_IsTemp);
  7526. }
  7527. else if (typedVal.IsAddr())
  7528. typedVal = LoadValue(typedVal);
  7529. return typedVal.mValue;
  7530. }
  7531. BF_ASSERT(typedVal.mType->mContext == mContext);
  7532. BF_ASSERT(toType->mContext == mContext);
  7533. if ((typedVal.IsAddr()) && (!typedVal.mType->IsValueType()))
  7534. typedVal = LoadValue(typedVal);
  7535. //BF_ASSERT(!typedVal.IsAddr() || typedVal.mType->IsGenericParam() || typedVal.mType->IsValueType());
  7536. // Ref X to Ref Y, X* to Y*
  7537. {
  7538. bool checkUnderlying = false;
  7539. if (((typedVal.mType->IsRef()) && (toType->IsRef())))
  7540. {
  7541. auto fromRefType = (BfRefType*)typedVal.mType;
  7542. auto toRefType = (BfRefType*)toType;
  7543. if (fromRefType->mRefKind == toRefType->mRefKind)
  7544. checkUnderlying = true;
  7545. else if ((fromRefType->mRefKind == BfRefType::RefKind_Ref) && (toRefType->mRefKind == BfRefType::RefKind_Mut))
  7546. checkUnderlying = true; // Allow a ref-to-mut implicit conversion
  7547. }
  7548. if ((typedVal.mType->IsPointer()) && (toType->IsPointer()))
  7549. checkUnderlying = true;
  7550. if (checkUnderlying)
  7551. {
  7552. auto fromInner = typedVal.mType->GetUnderlyingType();
  7553. auto toInner = toType->GetUnderlyingType();
  7554. if (fromInner == toInner)
  7555. {
  7556. return typedVal.mValue;
  7557. }
  7558. // ref int <-> ref int64/int32 (of same size)
  7559. if (((fromInner->IsInteger()) && (toInner->IsInteger())) &&
  7560. (fromInner->mSize == toInner->mSize) &&
  7561. (fromInner->IsSigned() == toInner->IsSigned()))
  7562. return typedVal.mValue;
  7563. }
  7564. }
  7565. // Null -> ObjectInst|IFace|ptr
  7566. if ((typedVal.mType->IsNull()) &&
  7567. ((toType->IsObjectOrInterface()) || (toType->IsPointer() || (toType->IsFunction()))))
  7568. {
  7569. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  7570. }
  7571. if (explicitCast)
  7572. {
  7573. // Object -> void*
  7574. if ((typedVal.mType->IsObject()) && (toType->IsVoidPtr()))
  7575. {
  7576. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  7577. }
  7578. // Func -> void*
  7579. if ((typedVal.mType->IsFunction()) && (toType->IsVoidPtr()))
  7580. {
  7581. return mBfIRBuilder->CreateIntToPtr(typedVal.mValue, mBfIRBuilder->MapType(toType));
  7582. }
  7583. // void* -> Func
  7584. if ((typedVal.mType->IsVoidPtr()) && (toType->IsFunction()))
  7585. {
  7586. return mBfIRBuilder->CreatePtrToInt(typedVal.mValue, BfTypeCode_IntPtr);
  7587. }
  7588. // * -> Valueless
  7589. if (toType->IsValuelessType())
  7590. return mBfIRBuilder->GetFakeVal();
  7591. // void* -> intptr
  7592. if ((typedVal.mType->IsPointer()) && (toType->IsIntPtr()))
  7593. {
  7594. //TODO: Put back
  7595. /*if ((!typedVal.mType->GetUnderlyingType()->IsVoid()) && ((castFlags & BfCastFlags_FromCompiler) == 0))
  7596. {
  7597. Fail(StrFormat("Unable to cast direct from '%s' to '%s', consider casting to void* first", TypeToString(typedVal.mType).c_str(), TypeToString(toType).c_str()), srcNode);
  7598. }*/
  7599. auto toPrimitive = (BfPrimitiveType*)toType;
  7600. return mBfIRBuilder->CreatePtrToInt(typedVal.mValue, toPrimitive->mTypeDef->mTypeCode);
  7601. }
  7602. // intptr -> void*
  7603. if ((typedVal.mType->IsIntPtr()) && (toType->IsPointer()))
  7604. {
  7605. //TODO: Put back
  7606. /*if ((!toType->GetUnderlyingType()->IsVoid()) && ((castFlags & BfCastFlags_FromCompiler) == 0))
  7607. {
  7608. Fail(StrFormat("Unable to cast direct from '%s' to '%s', consider casting to void* first", TypeToString(typedVal.mType).c_str(), TypeToString(toType).c_str()), srcNode);
  7609. }*/
  7610. return mBfIRBuilder->CreateIntToPtr(typedVal.mValue, mBfIRBuilder->MapType(toType));
  7611. }
  7612. }
  7613. // * <-> Var
  7614. if ((typedVal.mType->IsVar()) || (toType->IsVar()))
  7615. {
  7616. BF_ASSERT(((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized)) ||
  7617. ((mCurMethodState != NULL) && (mCurMethodState->mClosureState != NULL)) ||
  7618. (mHadVarUsage));
  7619. return GetDefaultValue(toType);
  7620. }
  7621. // Generic param -> *
  7622. if ((typedVal.mType->IsGenericParam()) && (!toType->IsGenericParam()))
  7623. {
  7624. if (toType == mContext->mBfObjectType)
  7625. {
  7626. /*auto resolvedType = ResolveGenericType(typedVal.mType);
  7627. if (!resolvedType->IsGenericParam())
  7628. return CastToValue(srcNode, BfTypedValue(typedVal.mValue, resolvedType), toType, castFlags, silentFail);
  7629. return typedVal.mValue;*/
  7630. // Always allow casting to generic
  7631. return typedVal.mValue;
  7632. }
  7633. // For these casts, it's just important we get *A* value to work with here,
  7634. // as this is just use for unspecialized parsing. We don't use the generated code
  7635. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  7636. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  7637. {
  7638. return typedVal.mValue;
  7639. }
  7640. if (toType->IsInterface())
  7641. {
  7642. for (auto iface : genericParamInst->mInterfaceConstraints)
  7643. if (TypeIsSubTypeOf(iface, toType->ToTypeInstance()))
  7644. return GetDefaultValue(toType);
  7645. }
  7646. if (genericParamInst->mTypeConstraint != NULL)
  7647. {
  7648. auto constraintTypeInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  7649. if ((constraintTypeInst != NULL) && (constraintTypeInst->mTypeDef == mCompiler->mEnumTypeDef))
  7650. {
  7651. // Enum->int
  7652. if (toType->IsInteger())
  7653. return GetDefaultValue(toType);
  7654. }
  7655. auto defaultFromValue = GetDefaultTypedValue(genericParamInst->mTypeConstraint);
  7656. auto result = CastToValue(srcNode, defaultFromValue, toType, (BfCastFlags)(castFlags | BfCastFlags_SilentFail));
  7657. if (result)
  7658. {
  7659. if ((genericParamInst->mTypeConstraint->IsDelegate()) && (toType->IsDelegate()))
  7660. {
  7661. // Don't allow cast when we are constrained by a delegate type, because BfMethodRefs can match and we require an actual alloc
  7662. Fail(StrFormat("Unable to cast '%s' to '%s' because delegate constraints allow valueless direct method references", TypeToString(typedVal.mType).c_str(), TypeToString(toType).c_str()), srcNode);
  7663. return BfIRValue();
  7664. }
  7665. return result;
  7666. }
  7667. }
  7668. // Generic constrained with class or pointer type -> void*
  7669. if (toType->IsVoidPtr())
  7670. {
  7671. if ((genericParamInst->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_StructPtr)) ||
  7672. ((genericParamInst->mTypeConstraint != NULL) &&
  7673. ((genericParamInst->mTypeConstraint->IsPointer()) || (genericParamInst->mTypeConstraint->IsObjectOrInterface()))))
  7674. {
  7675. return GetDefaultValue(toType);
  7676. }
  7677. }
  7678. }
  7679. // * -> Generic param
  7680. if (toType->IsGenericParam())
  7681. {
  7682. if (explicitCast)
  7683. {
  7684. // Either an upcast or an unbox
  7685. if ((typedVal.mType == mContext->mBfObjectType) || (typedVal.mType->IsInterface()))
  7686. {
  7687. return GetDefaultValue(toType);
  7688. }
  7689. }
  7690. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)toType);
  7691. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var)
  7692. return GetDefaultValue(toType);
  7693. if (typedVal.mType->IsNull())
  7694. {
  7695. bool allowCast = (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Class) || (genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr);
  7696. if ((!allowCast) && (genericParamInst->mTypeConstraint != NULL))
  7697. allowCast = genericParamInst->mTypeConstraint->IsObject() || genericParamInst->mTypeConstraint->IsPointer();
  7698. if (allowCast)
  7699. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  7700. }
  7701. if (genericParamInst->mTypeConstraint != NULL)
  7702. {
  7703. auto castedVal = CastToValue(srcNode, typedVal, genericParamInst->mTypeConstraint, (BfCastFlags)(castFlags | BfCastFlags_SilentFail));
  7704. if (castedVal)
  7705. return castedVal;
  7706. //TODO: WHy did we do 'GetDefaultValue'? This messes up setting up method param defaults, which is important for inferring const generic params
  7707. //return GetDefaultValue(toType);
  7708. }
  7709. }
  7710. // ObjectInst|IFace -> object|IFace
  7711. if ((typedVal.mType->IsObject() || (typedVal.mType->IsInterface())) && ((toType->IsObject() || (toType->IsInterface()))))
  7712. {
  7713. bool allowCast = false;
  7714. auto fromTypeInstance = typedVal.mType->ToTypeInstance();
  7715. auto toTypeInstance = toType->ToTypeInstance();
  7716. if (TypeIsSubTypeOf(fromTypeInstance, toTypeInstance))
  7717. allowCast = true;
  7718. else if ((explicitCast) &&
  7719. ((toType->IsInterface()) || (TypeIsSubTypeOf(toTypeInstance, fromTypeInstance))))
  7720. {
  7721. if (toType->IsObjectOrInterface())
  7722. {
  7723. if ((castFlags & BfCastFlags_Unchecked) == 0)
  7724. EmitDynamicCastCheck(typedVal, toType, true);
  7725. }
  7726. allowCast = true;
  7727. }
  7728. if (allowCast)
  7729. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  7730. }
  7731. // MethodRef -> Function
  7732. if ((typedVal.mType->IsMethodRef()) && (toType->IsFunction()))
  7733. {
  7734. BfMethodInstance* methodInstance = ((BfMethodRefType*)typedVal.mType)->mMethodRef;
  7735. auto result = CastToFunction(srcNode, methodInstance, toType, castFlags);
  7736. if (result)
  7737. return result;
  7738. }
  7739. // concrete IFace -> object|IFace
  7740. if ((typedVal.mType->IsConcreteInterfaceType()) && ((toType->IsObject() || (toType->IsInterface()))))
  7741. {
  7742. auto concreteInterfaceType = (BfConcreteInterfaceType*)typedVal.mType;
  7743. if ((toType->IsObject()) || (concreteInterfaceType->mInterface == toType))
  7744. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  7745. }
  7746. // IFace -> object
  7747. if ((typedVal.mType->IsInterface()) && (toType == mContext->mBfObjectType))
  7748. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  7749. // * -> Pointer
  7750. if (toType->IsPointer())
  7751. {
  7752. // Ptr -> Ptr
  7753. if (typedVal.mType->IsPointer())
  7754. {
  7755. bool allowCast = explicitCast;
  7756. auto fromPointerType = (BfPointerType*)typedVal.mType;
  7757. auto toPointerType = (BfPointerType*)toType;
  7758. auto fromUnderlying = fromPointerType->mElementType;
  7759. auto toUnderlying = toPointerType->mElementType;
  7760. // Allow cast from T[size]* to T* implicitly
  7761. // And from T* to T[size]* explicitly
  7762. while (fromUnderlying->IsSizedArray())
  7763. fromUnderlying = fromUnderlying->GetUnderlyingType();
  7764. while ((toUnderlying->IsSizedArray()) && (explicitCast))
  7765. toUnderlying = toUnderlying->GetUnderlyingType();
  7766. if ((fromUnderlying == toUnderlying) ||
  7767. (TypeIsSubTypeOf(fromUnderlying->ToTypeInstance(), toUnderlying->ToTypeInstance())) ||
  7768. (toUnderlying->IsVoid()))
  7769. allowCast = true;
  7770. if (allowCast)
  7771. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  7772. }
  7773. else if (typedVal.mType->IsObject())
  7774. {
  7775. // ???
  7776. }
  7777. /*else if (typedVal.mType->IsSizedArray())
  7778. {
  7779. if (typedVal.IsAddr())
  7780. {
  7781. BfSizedArrayType* arrayType = (BfSizedArrayType*)typedVal.mType;
  7782. auto ptrType = CreatePointerType(arrayType->mElementType);
  7783. BfTypedValue returnPointer(mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(ptrType)), ptrType);
  7784. return CastToValue(srcNode, returnPointer, toType, castFlags, silentFail);
  7785. }
  7786. }*/
  7787. }
  7788. // Boxing?
  7789. bool mayBeBox = false;
  7790. if (((typedVal.mType->IsValueType()) || (typedVal.mType->IsPointer()) || (typedVal.mType->IsValuelessType())) &&
  7791. ((toType->IsInterface()) || (toType == mContext->mBfObjectType)))
  7792. {
  7793. // Make sure there's no conversion operator before we box
  7794. if ((!typedVal.mType->IsRef()) && (!typedVal.mType->IsRetTypeType()))
  7795. mayBeBox = true;
  7796. }
  7797. //TODO: the IsGenericParam is not valid - why did we have that? The generic param could be a struct for example...
  7798. if ((explicitCast) && ((typedVal.mType->IsInterface()) || (typedVal.mType == mContext->mBfObjectType) /*|| (typedVal.mType->IsGenericParam())*/) &&
  7799. ((toType->IsValueType()) || (toType->IsPointer())))
  7800. {
  7801. if (toType->IsValuelessType())
  7802. {
  7803. return mBfIRBuilder->GetFakeVal();
  7804. }
  7805. // Unbox!
  7806. if ((castFlags & BfCastFlags_Unchecked) == 0)
  7807. {
  7808. EmitDynamicCastCheck(typedVal, toType, false);
  7809. EmitObjectAccessCheck(typedVal);
  7810. }
  7811. if (toType->IsNullable())
  7812. {
  7813. auto toTypeInst = toType->ToTypeInstance();
  7814. int valueIdx = toTypeInst->mFieldInstances[0].mDataIdx;
  7815. int hasValueIdx = toTypeInst->mFieldInstances[1].mDataIdx;
  7816. typedVal = MakeAddressable(typedVal);
  7817. auto elementType = toType->GetUnderlyingType();
  7818. auto ptrElementType = CreatePointerType(elementType);
  7819. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  7820. auto allocaInst = CreateAlloca(toType, true, "unboxN");
  7821. auto prevBB = mBfIRBuilder->GetInsertBlock();
  7822. auto nullBB = mBfIRBuilder->CreateBlock("unboxN.null");
  7823. auto notNullBB = mBfIRBuilder->CreateBlock("unboxN.notNull");
  7824. auto endBB = mBfIRBuilder->CreateBlock("unboxN.end");
  7825. auto isNull = mBfIRBuilder->CreateIsNull(typedVal.mValue);
  7826. mBfIRBuilder->CreateCondBr(isNull, nullBB, notNullBB);
  7827. int dataIdx = toTypeInst->mFieldInstances[1].mDataIdx;
  7828. mBfIRBuilder->AddBlock(nullBB);
  7829. mBfIRBuilder->SetInsertPoint(nullBB);
  7830. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, hasValueIdx); // has_value
  7831. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), hasValueAddr);
  7832. auto nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, valueIdx); // value
  7833. auto nullableValueBits = mBfIRBuilder->CreateBitCast(nullableValueAddr, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  7834. mBfIRBuilder->CreateMemSet(nullableValueBits, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)), GetConstValue(elementType->mSize), elementType->mAlign);
  7835. mBfIRBuilder->CreateBr(endBB);
  7836. mBfIRBuilder->AddBlock(notNullBB);
  7837. mBfIRBuilder->SetInsertPoint(notNullBB);
  7838. hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, hasValueIdx); // has_value
  7839. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), hasValueAddr);
  7840. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, valueIdx); // value
  7841. auto srcObjBits = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(ptrElementType));
  7842. auto boxedValueAddr = mBfIRBuilder->CreateInBoundsGEP(srcObjBits, 1); // Skip over vdata
  7843. auto boxedValue = mBfIRBuilder->CreateLoad(boxedValueAddr);
  7844. mBfIRBuilder->CreateStore(boxedValue, nullableValueAddr);
  7845. mBfIRBuilder->CreateBr(endBB);
  7846. mBfIRBuilder->AddBlock(endBB);
  7847. mBfIRBuilder->SetInsertPoint(endBB);
  7848. if (resultFlags != NULL)
  7849. *resultFlags = (BfCastResultFlags)(BfCastResultFlags_IsAddr | BfCastResultFlags_IsTemp);
  7850. return allocaInst;
  7851. }
  7852. auto boxedType = CreateBoxedType(toType);
  7853. mBfIRBuilder->PopulateType(boxedType);
  7854. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  7855. auto boxedObj = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(boxedType));
  7856. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(boxedObj, 0, 1);
  7857. if ((toType->IsPrimitiveType()) || (toType->IsTypedPrimitive()) || (toType->IsPointer()) || (toType->IsSizedArray()) || (toType->IsMethodRef()))
  7858. {
  7859. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(toType)));
  7860. }
  7861. if ((toType->IsComposite()) && (resultFlags != NULL))
  7862. {
  7863. *resultFlags = BfCastResultFlags_IsAddr;
  7864. return valPtr;
  7865. }
  7866. else
  7867. return mBfIRBuilder->CreateLoad(valPtr, false);
  7868. }
  7869. // Null -> Nullable<T>
  7870. if ((typedVal.mType->IsNull()) && (toType->IsNullable()))
  7871. {
  7872. if ((castFlags & BfCastFlags_PreferAddr) != 0)
  7873. {
  7874. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  7875. auto toTypeInst = toType->ToTypeInstance();
  7876. int hasValueIdx = toTypeInst->mFieldInstances[1].mDataIdx;
  7877. auto allocaInst = CreateAlloca(toType);
  7878. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, hasValueIdx); // has_value
  7879. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), hasValueAddr);
  7880. auto typedValue = BfTypedValue(allocaInst, toType, true);
  7881. if (resultFlags != NULL)
  7882. *resultFlags = (BfCastResultFlags)(BfCastResultFlags_IsAddr | BfCastResultFlags_IsTemp);
  7883. return allocaInst;
  7884. }
  7885. auto zeroNullable = mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(toType));
  7886. return zeroNullable;
  7887. }
  7888. // Nullable<A> -> Nullable<B>
  7889. if ((typedVal.mType->IsNullable()) && (toType->IsNullable()))
  7890. {
  7891. auto fromNullableType = (BfGenericTypeInstance*)typedVal.mType;
  7892. auto toNullableType = (BfGenericTypeInstance*)toType;
  7893. BfIRValue srcPtr = typedVal.mValue;
  7894. if (!typedVal.IsAddr())
  7895. {
  7896. auto srcAlloca = CreateAllocaInst(fromNullableType);
  7897. mBfIRBuilder->CreateStore(typedVal.mValue, srcAlloca);
  7898. srcPtr = srcAlloca;
  7899. }
  7900. auto srcAddr = mBfIRBuilder->CreateInBoundsGEP(srcPtr, 0, 1); // mValue
  7901. auto srcVal = mBfIRBuilder->CreateLoad(srcAddr);
  7902. auto toVal = CastToValue(srcNode, BfTypedValue(srcVal, fromNullableType->mTypeGenericArguments[0]), toNullableType->mTypeGenericArguments[0]);
  7903. if (!toVal)
  7904. return BfIRValue();
  7905. auto allocaInst = CreateAllocaInst(toNullableType);
  7906. auto destAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // mValue
  7907. mBfIRBuilder->CreateStore(toVal, destAddr);
  7908. srcAddr = mBfIRBuilder->CreateInBoundsGEP(srcPtr, 0, 2); // mHasValue
  7909. srcVal = mBfIRBuilder->CreateLoad(srcAddr);
  7910. destAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 2); // mHasValue
  7911. mBfIRBuilder->CreateStore(srcVal, destAddr);
  7912. if (resultFlags != NULL)
  7913. *resultFlags = (BfCastResultFlags)(BfCastResultFlags_IsAddr | BfCastResultFlags_IsTemp);
  7914. return allocaInst;
  7915. }
  7916. // Tuple -> Tuple
  7917. if ((typedVal.mType->IsTuple()) && (toType->IsTuple()))
  7918. {
  7919. auto fromTupleType = (BfTupleType*)typedVal.mType;
  7920. auto toTupleType = (BfTupleType*)toType;
  7921. if (fromTupleType->mFieldInstances.size() == toTupleType->mFieldInstances.size())
  7922. {
  7923. typedVal = LoadValue(typedVal);
  7924. BfIRValue curTupleValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(toTupleType));
  7925. for (int valueIdx = 0; valueIdx < (int)fromTupleType->mFieldInstances.size(); valueIdx++)
  7926. {
  7927. BfFieldInstance* fromFieldInstance = &fromTupleType->mFieldInstances[valueIdx];
  7928. BfFieldInstance* toFieldInstance = &toTupleType->mFieldInstances[valueIdx];
  7929. if (!explicitCast)
  7930. {
  7931. BfFieldDef* fromFieldDef = fromFieldInstance->GetFieldDef();
  7932. BfFieldDef* toFieldDef = toFieldInstance->GetFieldDef();
  7933. // Either the names have to match or one has to be unnamed
  7934. if ((!fromFieldDef->IsUnnamedTupleField()) && (!toFieldDef->IsUnnamedTupleField()) &&
  7935. (fromFieldDef->mName != toFieldDef->mName))
  7936. {
  7937. curTupleValue = BfIRValue();
  7938. break;
  7939. }
  7940. }
  7941. auto fromFieldType = fromFieldInstance->GetResolvedType();
  7942. auto toFieldType = toFieldInstance->GetResolvedType();
  7943. if (toFieldType->IsVoid())
  7944. continue; // Allow sinking to void
  7945. BfIRValue fromFieldValue;
  7946. if (fromFieldInstance->mDataIdx >= 0)
  7947. fromFieldValue = mBfIRBuilder->CreateExtractValue(typedVal.mValue, fromFieldInstance->mDataIdx);
  7948. BfIRValue toFieldValue = CastToValue(srcNode, BfTypedValue(fromFieldValue, fromFieldType), toFieldType, (BfCastFlags)(castFlags | BfCastFlags_Explicit));
  7949. if (!toFieldValue)
  7950. {
  7951. curTupleValue = BfIRValue();
  7952. break;
  7953. }
  7954. if (toFieldInstance->mDataIdx >= 0)
  7955. curTupleValue = mBfIRBuilder->CreateInsertValue(curTupleValue, toFieldValue, toFieldInstance->mDataIdx);
  7956. }
  7957. if (curTupleValue)
  7958. return curTupleValue;
  7959. }
  7960. }
  7961. // -> const <value>
  7962. if (toType->IsConstExprValue())
  7963. {
  7964. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  7965. if (constant != NULL)
  7966. {
  7967. BfConstExprValueType* toConstExprValueType = (BfConstExprValueType*)toType;
  7968. auto variantVal = TypedValueToVariant(srcNode, typedVal);
  7969. if ((mBfIRBuilder->IsInt(variantVal.mTypeCode)) && (mBfIRBuilder->IsInt(toConstExprValueType->mValue.mTypeCode)))
  7970. {
  7971. if (variantVal.mInt64 == toConstExprValueType->mValue.mInt64)
  7972. return typedVal.mValue;
  7973. }
  7974. else if ((mBfIRBuilder->IsFloat(variantVal.mTypeCode)) && (mBfIRBuilder->IsFloat(toConstExprValueType->mValue.mTypeCode)))
  7975. {
  7976. if (variantVal.ToDouble() == toConstExprValueType->mValue.ToDouble())
  7977. return typedVal.mValue;
  7978. }
  7979. if ((castFlags & BfCastFlags_SilentFail) == 0)
  7980. {
  7981. String valStr;
  7982. VariantToString(valStr, variantVal);
  7983. Fail(StrFormat("Unable to cast '%s %s' to '%s'", TypeToString(typedVal.mType).c_str(), valStr.c_str(), TypeToString(toType).c_str()), srcNode);
  7984. }
  7985. }
  7986. }
  7987. if ((typedVal.mType->IsPrimitiveType()) && (toType->IsPrimitiveType()))
  7988. {
  7989. auto fromPrimType = (BfPrimitiveType*)typedVal.mType;
  7990. auto toPrimType = (BfPrimitiveType*)toType;
  7991. BfTypeCode fromTypeCode = fromPrimType->mTypeDef->mTypeCode;
  7992. BfTypeCode toTypeCode = toPrimType->mTypeDef->mTypeCode;
  7993. if (toType->IsIntegral())
  7994. {
  7995. // Allow constant ints to be implicitly casted to a smaller type if they fit
  7996. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  7997. if (constant != NULL)
  7998. {
  7999. if (mBfIRBuilder->IsInt(constant->mTypeCode))
  8000. {
  8001. int64 srcVal = constant->mInt64;
  8002. if (toPrimType->IsChar())
  8003. {
  8004. if (srcVal == 0)
  8005. explicitCast = true;
  8006. }
  8007. else if ((fromPrimType->IsChar()) && (!toPrimType->IsChar()))
  8008. {
  8009. // Never allow this
  8010. }
  8011. else if ((constant->mTypeCode == BfTypeCode_UInt64) && (srcVal < 0))
  8012. {
  8013. // There's nothing that this could fit into
  8014. }
  8015. else if (toType->IsSigned())
  8016. {
  8017. int64 minVal = -(1LL << (8 * toType->mSize - 1));
  8018. int64 maxVal = (1LL << (8 * toType->mSize - 1)) - 1;
  8019. if ((srcVal >= minVal) && (srcVal <= maxVal))
  8020. explicitCast = true;
  8021. }
  8022. else if (toType->mSize == 8) // ulong
  8023. {
  8024. if (srcVal >= 0)
  8025. explicitCast = true;
  8026. }
  8027. else
  8028. {
  8029. int64 minVal = 0;
  8030. int64 maxVal = (1LL << (8 * toType->mSize)) - 1;
  8031. if ((srcVal >= minVal) && (srcVal <= maxVal))
  8032. explicitCast = true;
  8033. }
  8034. }
  8035. else if (constant->mConstType == BfConstType_Undef)
  8036. {
  8037. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  8038. auto undefConst = (BfConstantUndef*)constant;
  8039. auto fakeVal = GetFakeTypedValue(GetPrimitiveType(undefConst->mTypeCode));
  8040. auto val = CastToValue(srcNode, fakeVal, toType, (BfCastFlags)(castFlags | BfCastFlags_Explicit));
  8041. if (val)
  8042. return val;
  8043. }
  8044. }
  8045. }
  8046. bool allowCast = false;
  8047. switch (toTypeCode)
  8048. {
  8049. case BfTypeCode_Char16:
  8050. switch (fromTypeCode)
  8051. {
  8052. case BfTypeCode_Char8:
  8053. allowCast = true; break;
  8054. default: break;
  8055. }
  8056. break;
  8057. case BfTypeCode_Int16:
  8058. switch (fromTypeCode)
  8059. {
  8060. case BfTypeCode_Int8:
  8061. allowCast = true; break;
  8062. case BfTypeCode_UInt8:
  8063. allowCast = true; break;
  8064. default: break;
  8065. }
  8066. break;
  8067. case BfTypeCode_UInt16:
  8068. switch (fromTypeCode)
  8069. {
  8070. case BfTypeCode_UInt8:
  8071. allowCast = true; break;
  8072. default: break;
  8073. }
  8074. break;
  8075. case BfTypeCode_Int32:
  8076. switch (fromTypeCode)
  8077. {
  8078. case BfTypeCode_Int8:
  8079. case BfTypeCode_Int16:
  8080. allowCast = true; break;
  8081. case BfTypeCode_IntPtr:
  8082. if (mCompiler->mSystem->mPtrSize == 4)
  8083. allowCast = true;
  8084. break;
  8085. case BfTypeCode_UInt8:
  8086. case BfTypeCode_UInt16:
  8087. allowCast = true; break;
  8088. default: break;
  8089. }
  8090. break;
  8091. case BfTypeCode_Char32:
  8092. switch (fromTypeCode)
  8093. {
  8094. case BfTypeCode_Char8:
  8095. case BfTypeCode_Char16:
  8096. allowCast = true; break;
  8097. default: break;
  8098. }
  8099. break;
  8100. case BfTypeCode_UInt32:
  8101. switch (fromTypeCode)
  8102. {
  8103. case BfTypeCode_UInt8:
  8104. case BfTypeCode_UInt16:
  8105. case BfTypeCode_UInt32:
  8106. allowCast = true; break;
  8107. case BfTypeCode_UIntPtr:
  8108. if (mCompiler->mSystem->mPtrSize == 4)
  8109. allowCast = true;
  8110. break;
  8111. default: break;
  8112. }
  8113. break;
  8114. case BfTypeCode_Int64:
  8115. switch (fromTypeCode)
  8116. {
  8117. case BfTypeCode_Int8:
  8118. case BfTypeCode_Int16:
  8119. case BfTypeCode_Int32:
  8120. case BfTypeCode_IntPtr:
  8121. allowCast = true; break;
  8122. case BfTypeCode_UInt8:
  8123. case BfTypeCode_UInt16:
  8124. case BfTypeCode_UInt32:
  8125. allowCast = true; break;
  8126. default: break;
  8127. }
  8128. break;
  8129. case BfTypeCode_UInt64:
  8130. switch (fromTypeCode)
  8131. {
  8132. case BfTypeCode_UInt8:
  8133. case BfTypeCode_UInt16:
  8134. case BfTypeCode_UInt32:
  8135. case BfTypeCode_UIntPtr:
  8136. allowCast = true; break;
  8137. default: break;
  8138. }
  8139. break;
  8140. case BfTypeCode_IntPtr:
  8141. switch (fromTypeCode)
  8142. {
  8143. case BfTypeCode_Int8:
  8144. case BfTypeCode_Int16:
  8145. case BfTypeCode_Int32:
  8146. allowCast = true; break;
  8147. case BfTypeCode_UInt8:
  8148. case BfTypeCode_UInt16:
  8149. allowCast = true; break;
  8150. case BfTypeCode_UInt32:
  8151. case BfTypeCode_Int64:
  8152. // It may seem that we want this to require an explicit cast,
  8153. // but consider the case of
  8154. // int val = Math.Max(intA, intB)
  8155. // Math.Max has an int32 and int64 override, so we want the correct one to be chosen and
  8156. // to be able to have the int64 return value implicitly used in a 64-bit build
  8157. if (mCompiler->mSystem->mPtrSize == 8)
  8158. allowCast = true;
  8159. break;
  8160. default: break;
  8161. }
  8162. break;
  8163. case BfTypeCode_UIntPtr:
  8164. switch (fromTypeCode)
  8165. {
  8166. case BfTypeCode_UInt8:
  8167. case BfTypeCode_UInt16:
  8168. case BfTypeCode_UInt32:
  8169. allowCast = true; break;
  8170. case BfTypeCode_UInt64:
  8171. if (mCompiler->mSystem->mPtrSize == 8)
  8172. allowCast = true;
  8173. break;
  8174. default: break;
  8175. }
  8176. break;
  8177. case BfTypeCode_Single:
  8178. switch (fromTypeCode)
  8179. {
  8180. case BfTypeCode_Int8:
  8181. case BfTypeCode_Int16:
  8182. case BfTypeCode_Int32:
  8183. case BfTypeCode_Int64:
  8184. case BfTypeCode_IntPtr:
  8185. case BfTypeCode_IntUnknown:
  8186. allowCast = true; break;
  8187. case BfTypeCode_UInt8:
  8188. case BfTypeCode_UInt16:
  8189. case BfTypeCode_UInt32:
  8190. case BfTypeCode_UInt64:
  8191. case BfTypeCode_UIntPtr:
  8192. case BfTypeCode_UIntUnknown:
  8193. allowCast = true; break;
  8194. default: break;
  8195. }
  8196. break;
  8197. case BfTypeCode_Double:
  8198. switch (fromTypeCode)
  8199. {
  8200. case BfTypeCode_Int8:
  8201. case BfTypeCode_Int16:
  8202. case BfTypeCode_Int32:
  8203. case BfTypeCode_Int64:
  8204. case BfTypeCode_IntPtr:
  8205. case BfTypeCode_IntUnknown:
  8206. allowCast = true; break;
  8207. case BfTypeCode_UInt8:
  8208. case BfTypeCode_UInt16:
  8209. case BfTypeCode_UInt32:
  8210. case BfTypeCode_UInt64:
  8211. case BfTypeCode_UIntPtr:
  8212. case BfTypeCode_UIntUnknown:
  8213. allowCast = true; break;
  8214. case BfTypeCode_Single:
  8215. allowCast = true; break;
  8216. default: break;
  8217. }
  8218. break;
  8219. default: break;
  8220. }
  8221. if (explicitCast)
  8222. {
  8223. if (((fromPrimType->IsIntegral()) || (fromPrimType->IsFloat())) &&
  8224. ((toType->IsIntegral()) || (toType->IsFloat())))
  8225. allowCast = true;
  8226. }
  8227. if (allowCast)
  8228. {
  8229. return mBfIRBuilder->CreateNumericCast(typedVal.mValue, typedVal.mType->IsSigned(), toTypeCode);
  8230. }
  8231. }
  8232. // Check user-defined operators
  8233. if ((castFlags & BfCastFlags_NoConversionOperator) == 0)
  8234. {
  8235. auto fromType = typedVal.mType;
  8236. auto fromTypeInstance = typedVal.mType->ToTypeInstance();
  8237. auto toTypeInstance = toType->ToTypeInstance();
  8238. auto liftedFromType = ((fromTypeInstance != NULL) && fromTypeInstance->IsNullable()) ? fromTypeInstance->GetUnderlyingType() : NULL;
  8239. auto liftedToType = ((toTypeInstance != NULL) && toTypeInstance->IsNullable()) ? toTypeInstance->GetUnderlyingType() : NULL;
  8240. int bestFromDist = INT_MAX;
  8241. BfType* bestFromType = NULL;
  8242. int bestNegFromDist = INT_MAX;
  8243. BfType* bestNegFromType = NULL;
  8244. int bestToDist = INT_MAX;
  8245. BfType* bestToType = NULL;
  8246. int bestNegToDist = INT_MAX;
  8247. BfType* bestNegToType = NULL;
  8248. bool isAmbiguousCast = false;
  8249. BfIRValue conversionResult;
  8250. BfMethodInstance* opMethodInstance = NULL;
  8251. BfType* opMethodSrcType = NULL;
  8252. // Normal, lifted, execute
  8253. for (int pass = 0; pass < 3; pass++)
  8254. {
  8255. auto checkToType = toType;
  8256. auto checkFromType = fromType;
  8257. if (pass == 1)
  8258. {
  8259. if ((bestFromType != NULL) && (bestToType != NULL))
  8260. continue;
  8261. if (liftedFromType != NULL)
  8262. checkFromType = liftedFromType;
  8263. if (liftedToType != NULL)
  8264. checkToType = liftedToType;
  8265. }
  8266. else if (pass == 2)
  8267. {
  8268. if ((bestFromType == NULL) || (bestToType == NULL))
  8269. break;
  8270. }
  8271. BfBaseClassWalker baseClassWalker(fromType, toType, this);
  8272. while (true)
  8273. {
  8274. auto entry = baseClassWalker.Next();
  8275. auto checkInstance = entry.mTypeInstance;
  8276. if (checkInstance == NULL)
  8277. break;
  8278. for (auto operatorDef : checkInstance->mTypeDef->mOperators)
  8279. {
  8280. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  8281. {
  8282. if ((!explicitCast) && (operatorDef->mOperatorDeclaration->mExplicitToken != NULL) &&
  8283. (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit))
  8284. continue;
  8285. auto methodInst = GetRawMethodInstanceAtIdx(checkInstance, operatorDef->mIdx);
  8286. if (methodInst->GetParamCount() != 1)
  8287. {
  8288. BF_ASSERT(mCompiler->mPassInstance->HasFailed());
  8289. continue;
  8290. }
  8291. auto methodFromType = methodInst->GetParamType(0);
  8292. auto methodToType = methodInst->mReturnType;
  8293. if (methodFromType->IsSelf())
  8294. methodFromType = entry.mSrcType;
  8295. if (methodToType->IsSelf())
  8296. methodToType = entry.mSrcType;
  8297. // Selection pass
  8298. if (pass < 2)
  8299. {
  8300. auto methodCheckFromType = methodFromType;
  8301. auto methodCheckToType = methodToType;
  8302. if (pass == 1)
  8303. {
  8304. // Only check inner type on lifted types when we aren't checking conversions within lifted class
  8305. // This avoid some infinite conversions
  8306. if ((methodCheckFromType->IsNullable()) && (!checkInstance->IsNullable()))
  8307. methodCheckFromType = methodCheckFromType->GetUnderlyingType();
  8308. if ((methodCheckToType->IsNullable()) && (!checkInstance->IsNullable()))
  8309. methodCheckToType = methodCheckToType->GetUnderlyingType();
  8310. }
  8311. int fromDist = GetTypeDistance(methodCheckFromType, checkFromType);
  8312. if (fromDist < 0)
  8313. {
  8314. // Allow us to cast a constant int to a smaller type if it satisfies the cast operator
  8315. if ((typedVal.mValue.IsConst()) && (CanImplicitlyCast(typedVal, methodCheckFromType)))
  8316. {
  8317. fromDist = 0;
  8318. }
  8319. }
  8320. int toDist = GetTypeDistance(methodCheckToType, checkToType);
  8321. if ((fromDist == INT_MAX) || (toDist == INT_MAX))
  8322. continue;
  8323. if (((fromDist >= 0) && (toDist >= 0)) || (explicitCast))
  8324. {
  8325. if ((fromDist >= 0) && (fromDist < bestFromDist))
  8326. {
  8327. bestFromDist = fromDist;
  8328. bestFromType = methodFromType;
  8329. }
  8330. if ((toDist >= 0) && (toDist < bestToDist))
  8331. {
  8332. bestToDist = toDist;
  8333. bestToType = methodToType;
  8334. }
  8335. }
  8336. if (explicitCast)
  8337. {
  8338. fromDist = abs(fromDist);
  8339. toDist = abs(toDist);
  8340. if ((fromDist >= 0) && (fromDist < bestNegFromDist))
  8341. {
  8342. bestNegFromDist = fromDist;
  8343. bestNegFromType = methodFromType;
  8344. }
  8345. if ((toDist >= 0) && (toDist < bestNegToDist))
  8346. {
  8347. bestNegToDist = toDist;
  8348. bestNegToType = methodInst->mReturnType;
  8349. }
  8350. }
  8351. }
  8352. else if (pass == 2) // Execution Pass
  8353. {
  8354. if ((methodFromType == bestFromType) && (methodToType == bestToType))
  8355. {
  8356. // Get in native module so our module doesn't get a reference to it - we may not end up calling it at all!
  8357. //BfModuleMethodInstance methodInstance = checkInstance->mModule->GetMethodInstanceAtIdx(checkInstance, operatorDef->mIdx);
  8358. BfMethodInstance* methodInstance = GetRawMethodInstanceAtIdx(checkInstance, operatorDef->mIdx);
  8359. if (opMethodInstance != NULL)
  8360. {
  8361. int prevGenericCount = GetGenericParamAndReturnCount(opMethodInstance);
  8362. int newGenericCount = GetGenericParamAndReturnCount(methodInstance);
  8363. if (newGenericCount > prevGenericCount)
  8364. {
  8365. // Prefer generic match
  8366. opMethodInstance = methodInstance;
  8367. opMethodSrcType = entry.mSrcType;
  8368. }
  8369. else if (newGenericCount < prevGenericCount)
  8370. {
  8371. // Previous was a generic match
  8372. continue;
  8373. }
  8374. else
  8375. {
  8376. isAmbiguousCast = true;
  8377. break;
  8378. }
  8379. }
  8380. else
  8381. {
  8382. opMethodInstance = methodInstance;
  8383. opMethodSrcType = entry.mSrcType;
  8384. }
  8385. }
  8386. }
  8387. }
  8388. }
  8389. if (isAmbiguousCast)
  8390. break;
  8391. if (opMethodInstance != NULL)
  8392. {
  8393. if (mayBeBox)
  8394. {
  8395. if (Fail("Ambiguous cast, may be conversion operator or may be boxing request", srcNode) != NULL)
  8396. mCompiler->mPassInstance->MoreInfo("See conversion operator", opMethodInstance->mMethodDef->GetRefNode());
  8397. }
  8398. BfModuleMethodInstance moduleMethodInstance = GetMethodInstance(opMethodInstance->GetOwner(), opMethodInstance->mMethodDef, BfTypeVector());
  8399. auto methodDeclaration = moduleMethodInstance.mMethodInstance->mMethodDef->GetMethodDeclaration();
  8400. if (methodDeclaration->mBody == NULL)
  8401. {
  8402. // Handle the typedPrim<->underlying part implicitly
  8403. if (fromType->IsTypedPrimitive())
  8404. {
  8405. auto convTypedValue = BfTypedValue(typedVal.mValue, fromType->GetUnderlyingType());
  8406. return CastToValue(srcNode, convTypedValue, toType, (BfCastFlags)(castFlags & ~BfCastFlags_Explicit), NULL);
  8407. }
  8408. else if (toType->IsTypedPrimitive())
  8409. {
  8410. auto castedVal = CastToValue(srcNode, typedVal, toType->GetUnderlyingType(), (BfCastFlags)(castFlags & ~BfCastFlags_Explicit), NULL);
  8411. return castedVal;
  8412. }
  8413. // Cannot cast (was error)
  8414. return BfIRValue();
  8415. }
  8416. // Actually perform conversion
  8417. BfExprEvaluator exprEvaluator(this);
  8418. auto castedFromValue = Cast(srcNode, typedVal, bestFromType, castFlags);
  8419. if (!castedFromValue)
  8420. return BfIRValue();
  8421. SizedArray<BfIRValue, 1> args;
  8422. exprEvaluator.PushArg(castedFromValue, args);
  8423. auto operatorOut = exprEvaluator.CreateCall(moduleMethodInstance.mMethodInstance, mCompiler->IsSkippingExtraResolveChecks() ? BfIRValue() : moduleMethodInstance.mFunc, false, args);
  8424. if ((operatorOut.mType != NULL) && (operatorOut.mType->IsSelf()))
  8425. {
  8426. BF_ASSERT(IsInGeneric());
  8427. operatorOut = GetDefaultTypedValue(opMethodSrcType);
  8428. }
  8429. return CastToValue(srcNode, operatorOut, toType, castFlags, resultFlags);
  8430. }
  8431. }
  8432. if (bestFromType == NULL)
  8433. bestFromType = bestNegFromType;
  8434. if (bestToType == NULL)
  8435. bestToType = bestNegToType;
  8436. }
  8437. isAmbiguousCast |= ((bestFromType != NULL) && (bestToType != NULL));
  8438. if (isAmbiguousCast)
  8439. {
  8440. const char* errStr = "Ambiguous conversion operators for casting from '%s' to '%s'";
  8441. Fail(StrFormat(errStr, TypeToString(typedVal.mType).c_str(), TypeToString(toType).c_str()), srcNode);
  8442. return BfIRValue();
  8443. }
  8444. }
  8445. // Default typed primitive 'underlying casts' happen after checking cast operators
  8446. if (explicitCast)
  8447. {
  8448. // TypedPrimitive -> Primitive
  8449. if ((typedVal.mType->IsTypedPrimitive()) && (toType->IsPrimitiveType()))
  8450. {
  8451. auto fromTypedPrimitiveType = typedVal.mType->ToTypeInstance();
  8452. auto primTypedVal = BfTypedValue(typedVal.mValue, fromTypedPrimitiveType->mFieldInstances.back().mResolvedType, typedVal.IsAddr());
  8453. primTypedVal = LoadValue(primTypedVal);
  8454. return CastToValue(srcNode, primTypedVal, toType, castFlags);
  8455. }
  8456. // TypedPrimitive -> TypedPrimitive
  8457. if ((typedVal.mType->IsTypedPrimitive()) && (toType->IsTypedPrimitive()))
  8458. {
  8459. auto fromTypedPrimitiveType = typedVal.mType->ToTypeInstance();
  8460. auto toTypedPrimitiveType = toType->ToTypeInstance();
  8461. auto fromUnderlyingType = fromTypedPrimitiveType->GetUnderlyingType();
  8462. auto toUnderlyingType = toTypedPrimitiveType->GetUnderlyingType();
  8463. BfTypedValue underlyingTypedValue(typedVal.mValue, fromUnderlyingType, typedVal.IsAddr());
  8464. underlyingTypedValue = LoadValue(underlyingTypedValue);
  8465. BfIRValue castedToValue = CastToValue(srcNode, underlyingTypedValue, toUnderlyingType, (BfCastFlags)(castFlags | BfCastFlags_Explicit));
  8466. if (castedToValue)
  8467. return castedToValue;
  8468. }
  8469. }
  8470. else if ((typedVal.mType->IsTypedPrimitive()) && (toType->IsTypedPrimitive()))
  8471. {
  8472. if (TypeIsSubTypeOf(typedVal.mType->ToTypeInstance(), toType->ToTypeInstance()))
  8473. {
  8474. // These have the same underlying primitive type, just keep it all the same
  8475. if ((resultFlags != NULL) && (typedVal.IsAddr()))
  8476. *resultFlags = BfCastResultFlags_IsAddr;
  8477. return typedVal.mValue;
  8478. }
  8479. }
  8480. // Prim -> TypedPrimitive
  8481. if ((typedVal.mType->IsPrimitiveType()) && (toType->IsTypedPrimitive()))
  8482. {
  8483. bool allowCast = explicitCast;
  8484. if (toType == mCurTypeInstance)
  8485. allowCast = true;
  8486. if ((!allowCast) && (typedVal.mType->IsIntegral()) && (!toType->IsEnum()))
  8487. {
  8488. // Allow implicit cast of zero
  8489. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  8490. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8491. {
  8492. allowCast = constant->mInt64 == 0;
  8493. }
  8494. }
  8495. if (allowCast)
  8496. {
  8497. return CastToValue(srcNode, typedVal, toType->GetUnderlyingType(), castFlags);
  8498. }
  8499. }
  8500. if (mayBeBox)
  8501. {
  8502. BfScopeData* scopeData = NULL;
  8503. if (mCurMethodState != NULL)
  8504. scopeData = mCurMethodState->mCurScope;
  8505. if ((castFlags & BfCastFlags_WarnOnBox) != 0)
  8506. {
  8507. Warn(0, "This implicit boxing will only be in scope during the constructor. Consider using a longer-term allocation such as 'box new'", srcNode);
  8508. }
  8509. auto value = BoxValue(srcNode, typedVal, toType, scopeData, (castFlags & BfCastFlags_NoBoxDtor) == 0);
  8510. if (value)
  8511. return value.mValue;
  8512. }
  8513. if ((castFlags & BfCastFlags_SilentFail) == 0)
  8514. {
  8515. const char* errStr = explicitCast ?
  8516. "Unable to cast '%s' to '%s'" :
  8517. "Unable to implicitly cast '%s' to '%s'";
  8518. auto error = Fail(StrFormat(errStr, TypeToString(typedVal.mType).c_str(), TypeToString(toType).c_str()), srcNode);
  8519. if ((error != NULL) && (srcNode != NULL))
  8520. {
  8521. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((srcNode))))
  8522. {
  8523. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites);
  8524. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  8525. if (CastToValue(srcNode, typedVal, toType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail)))
  8526. {
  8527. bool doWrap = false;
  8528. if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(srcNode))
  8529. {
  8530. if ((unaryOpExpr->mOp != BfUnaryOp_AddressOf) && (unaryOpExpr->mOp != BfUnaryOp_Dereference))
  8531. doWrap = true;
  8532. }
  8533. if ((srcNode->IsA<BfCastExpression>()) ||
  8534. (srcNode->IsA<BfBinaryOperatorExpression>()))
  8535. doWrap = true;
  8536. BfParserData* parser = srcNode->GetSourceData()->ToParserData();
  8537. String typeName = TypeToString(toType);
  8538. if (doWrap)
  8539. {
  8540. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit",
  8541. StrFormat("(%s)\tcast|%s|%d|(%s)(|`%d|)", typeName.c_str(), parser->mFileName.c_str(), srcNode->GetSrcStart(), typeName.c_str(), srcNode->GetSrcLength()).c_str()));
  8542. }
  8543. else
  8544. {
  8545. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit",
  8546. StrFormat("(%s)\tcast|%s|%d|(%s)", typeName.c_str(), parser->mFileName.c_str(), srcNode->GetSrcStart(), typeName.c_str()).c_str()));
  8547. }
  8548. }
  8549. }
  8550. }
  8551. }
  8552. return BfIRValue();
  8553. }
  8554. BfTypedValue BfModule::Cast(BfAstNode* srcNode, const BfTypedValue& typedVal, BfType* toType, BfCastFlags castFlags)
  8555. {
  8556. bool explicitCast = (castFlags & BfCastFlags_Explicit) != 0;
  8557. if (typedVal.mType == toType)
  8558. return typedVal;
  8559. PopulateType(toType, ((castFlags & BfCastFlags_NoConversionOperator) != 0) ? BfPopulateType_Data : BfPopulateType_DataAndMethods);
  8560. if ((castFlags & BfCastFlags_Force) != 0)
  8561. {
  8562. if (toType->IsValuelessType())
  8563. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  8564. if ((typedVal.mType->IsValueType()) && (!typedVal.IsAddr()) && (typedVal.IsSplat()) && (toType->IsValueType()))
  8565. {
  8566. bool needsMemberCasting = false;
  8567. if (AreSplatsCompatible(typedVal.mType, toType, &needsMemberCasting))
  8568. {
  8569. return BfTypedValue(typedVal.mValue, toType, needsMemberCasting ? BfTypedValueKind_SplatHead_NeedsCasting : BfTypedValueKind_SplatHead);
  8570. }
  8571. }
  8572. if (typedVal.mType->IsValueType())
  8573. {
  8574. auto addrTypedValue = MakeAddressable(typedVal);
  8575. auto toPtrType = CreatePointerType(toType);
  8576. return BfTypedValue(mBfIRBuilder->CreateBitCast(addrTypedValue.mValue, mBfIRBuilder->MapType(toPtrType)), toType, BfTypedValueKind_Addr);
  8577. }
  8578. return BfTypedValue(mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType)), toType);
  8579. }
  8580. // This tuple cast may create a new type if the toType contains 'var' entries
  8581. if ((typedVal.mType->IsTuple()) && (toType->IsTuple()))
  8582. {
  8583. //auto loadedVal = LoadValue(typedVal);
  8584. PopulateType(toType);
  8585. auto fromTupleType = (BfTupleType*)typedVal.mType;
  8586. auto toTupleType = (BfTupleType*)toType;
  8587. if (fromTupleType == toTupleType)
  8588. return typedVal;
  8589. if (fromTupleType->mFieldInstances.size() == toTupleType->mFieldInstances.size())
  8590. {
  8591. BfTypeVector fieldTypes;
  8592. Array<String> fieldNames;
  8593. bool isCompatible = true;
  8594. bool isExactTypeMatch = true;
  8595. for (int fieldIdx = 0; fieldIdx < (int)fromTupleType->mFieldInstances.size(); fieldIdx++)
  8596. {
  8597. auto fromFieldInst = &fromTupleType->mFieldInstances[fieldIdx];
  8598. auto toFieldInst = &toTupleType->mFieldInstances[fieldIdx];
  8599. auto fromFieldDef = fromFieldInst->GetFieldDef();
  8600. auto toFieldDef = toFieldInst->GetFieldDef();
  8601. if (!toFieldDef->IsUnnamedTupleField())
  8602. {
  8603. if ((!fromFieldDef->IsUnnamedTupleField()) &&
  8604. (fromFieldDef->mName != toFieldDef->mName))
  8605. isCompatible = false;
  8606. fieldNames.push_back(toFieldDef->mName);
  8607. }
  8608. else
  8609. fieldNames.push_back("");
  8610. if (toFieldInst->mResolvedType->IsVar())
  8611. fieldTypes.push_back(fromFieldInst->mResolvedType);
  8612. else
  8613. {
  8614. if (fromFieldInst->mResolvedType != toFieldInst->mResolvedType)
  8615. isExactTypeMatch = false;
  8616. // The unused-token '?' comes out as 'void', so we allow that to match here. We may want to wrap that with a different fake type
  8617. // so we can give normal implicit-cast-to-void errors
  8618. if ((fromFieldInst->mResolvedType != toFieldInst->mResolvedType) && (!toFieldInst->mResolvedType->IsVoid()) &&
  8619. (!CanImplicitlyCast(GetFakeTypedValue(fromFieldInst->mResolvedType), toFieldInst->mResolvedType)))
  8620. isCompatible = false;
  8621. fieldTypes.push_back(toFieldInst->mResolvedType);
  8622. }
  8623. }
  8624. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  8625. AddDependency(tupleType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  8626. mBfIRBuilder->PopulateType(tupleType);
  8627. if (isExactTypeMatch)
  8628. {
  8629. if (typedVal.mKind == BfTypedValueKind_TempAddr)
  8630. {
  8631. return BfTypedValue(mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapTypeInstPtr(tupleType)), tupleType, BfTypedValueKind_TempAddr);
  8632. }
  8633. else if (typedVal.IsAddr())
  8634. {
  8635. return BfTypedValue(mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapTypeInstPtr(tupleType)), tupleType, BfTypedValueKind_ReadOnlyAddr);
  8636. }
  8637. BfIRValue curTupleValue = CreateAlloca(tupleType);
  8638. auto loadedVal = LoadValue(typedVal);
  8639. mBfIRBuilder->CreateStore(loadedVal.mValue, mBfIRBuilder->CreateBitCast(curTupleValue, mBfIRBuilder->MapTypeInstPtr(fromTupleType)));
  8640. return BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  8641. }
  8642. if (isCompatible)
  8643. {
  8644. BfIRValue curTupleValue = CreateAlloca(tupleType);
  8645. for (int fieldIdx = 0; fieldIdx < (int)fromTupleType->mFieldInstances.size(); fieldIdx++)
  8646. {
  8647. BfFieldInstance* fromFieldInstance = &fromTupleType->mFieldInstances[fieldIdx];
  8648. BfFieldInstance* toFieldInstance = &tupleType->mFieldInstances[fieldIdx];
  8649. if (toFieldInstance->mDataIdx >= 0)
  8650. {
  8651. if (fromFieldInstance->mDataIdx >= 0)
  8652. {
  8653. auto elementVal = ExtractValue(typedVal, fromFieldInstance, fromFieldInstance->mDataIdx);
  8654. elementVal = LoadValue(elementVal);
  8655. auto castedElementVal = Cast(srcNode, elementVal, toFieldInstance->GetResolvedType(), castFlags);
  8656. if (!castedElementVal)
  8657. return BfTypedValue();
  8658. auto fieldRef = mBfIRBuilder->CreateInBoundsGEP(curTupleValue, 0, toFieldInstance->mDataIdx);
  8659. mBfIRBuilder->CreateStore(castedElementVal.mValue, fieldRef);
  8660. }
  8661. else
  8662. isCompatible = false;
  8663. }
  8664. }
  8665. return BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  8666. }
  8667. }
  8668. const char* errStr = explicitCast ?
  8669. "Unable to cast '%s' to '%s'" :
  8670. "Unable to implicitly cast '%s' to '%s'";
  8671. Fail(StrFormat(errStr, TypeToString(typedVal.mType).c_str(), TypeToString(toType).c_str()), srcNode);
  8672. return BfTypedValue();
  8673. }
  8674. // Struct truncate
  8675. if ((typedVal.mType->IsStruct()) && (toType->IsStruct()))
  8676. {
  8677. auto fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  8678. auto toStructTypeInstance = toType->ToTypeInstance();
  8679. if (TypeIsSubTypeOf(fromStructTypeInstance, toStructTypeInstance))
  8680. {
  8681. if (typedVal.IsSplat())
  8682. {
  8683. BF_ASSERT(toStructTypeInstance->IsSplattable() || (toStructTypeInstance->mInstSize == 0));
  8684. return BfTypedValue(typedVal.mValue, toStructTypeInstance, typedVal.IsThis() ? BfTypedValueKind_ThisSplatHead : BfTypedValueKind_SplatHead);
  8685. }
  8686. if (typedVal.IsAddr())
  8687. {
  8688. BfIRValue castedIRValue;
  8689. if (typedVal.mValue.IsFake())
  8690. castedIRValue = typedVal.mValue;
  8691. else
  8692. castedIRValue = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapTypeInstPtr(toStructTypeInstance));
  8693. return BfTypedValue(castedIRValue, toType, typedVal.IsThis() ?
  8694. (typedVal.IsReadOnly() ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  8695. (typedVal.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  8696. }
  8697. BfTypedValue curTypedVal = typedVal;
  8698. while (curTypedVal.mType != toStructTypeInstance)
  8699. {
  8700. mBfIRBuilder->PopulateType(curTypedVal.mType);
  8701. auto curTypeInstance = curTypedVal.mType->ToTypeInstance();
  8702. BfIRValue extractedValue;
  8703. if (toStructTypeInstance->IsValuelessType())
  8704. extractedValue = mBfIRBuilder->GetFakeVal();
  8705. else
  8706. extractedValue = mBfIRBuilder->CreateExtractValue(curTypedVal.mValue, 0);
  8707. curTypedVal = BfTypedValue(extractedValue, curTypeInstance->mBaseType, typedVal.IsThis() ?
  8708. (typedVal.IsReadOnly() ? BfTypedValueKind_ReadOnlyThisValue : BfTypedValueKind_ThisValue) :
  8709. BfTypedValueKind_Value);
  8710. }
  8711. return curTypedVal;
  8712. }
  8713. }
  8714. if ((explicitCast) && (toType->IsValuelessType()))
  8715. {
  8716. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  8717. }
  8718. BfCastResultFlags castResultFlags = BfCastResultFlags_None;
  8719. auto castedValue = CastToValue(srcNode, typedVal, toType, castFlags, &castResultFlags);
  8720. if (!castedValue)
  8721. return BfTypedValue();
  8722. if ((castResultFlags & BfCastResultFlags_IsAddr) != 0)
  8723. {
  8724. if ((castResultFlags & BfCastResultFlags_IsTemp) != 0)
  8725. return BfTypedValue(castedValue, toType, BfTypedValueKind_TempAddr);
  8726. return BfTypedValue(castedValue, toType, BfTypedValueKind_Addr);
  8727. }
  8728. return BfTypedValue(castedValue, toType, BfTypedValueKind_Value);
  8729. }
  8730. BfPrimitiveType* BfModule::GetIntCoercibleType(BfType* type)
  8731. {
  8732. if (type->IsSizedArray())
  8733. {
  8734. auto sizedArray = (BfSizedArrayType*)type;
  8735. if ((sizedArray->mElementType->IsChar()) && (sizedArray->mElementType->mSize == 1))
  8736. {
  8737. auto primType = (BfPrimitiveType*)sizedArray->mElementType;
  8738. if (sizedArray->mElementCount == 1)
  8739. return GetPrimitiveType(BfTypeCode_UInt8);
  8740. if (sizedArray->mElementCount == 2)
  8741. return GetPrimitiveType(BfTypeCode_UInt16);
  8742. if (sizedArray->mElementCount == 4)
  8743. return GetPrimitiveType(BfTypeCode_UInt32);
  8744. if (sizedArray->mElementCount == 8)
  8745. return GetPrimitiveType(BfTypeCode_UInt64);
  8746. }
  8747. }
  8748. return NULL;
  8749. }
  8750. BfTypedValue BfModule::GetIntCoercible(const BfTypedValue& typedValue)
  8751. {
  8752. auto intType = GetIntCoercibleType(typedValue.mType);
  8753. if (intType == NULL)
  8754. return BfTypedValue();
  8755. if (typedValue.mValue.IsConst())
  8756. {
  8757. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  8758. if (constant->mConstType == BfConstType_Array)
  8759. {
  8760. uint64 intVal = 0;
  8761. auto constantArray = (BfConstantArray*)constant;
  8762. int memberIdx = 0;
  8763. for (int memberIdx = 0; memberIdx < (int)constantArray->mValues.size(); memberIdx++)
  8764. {
  8765. auto memberConstant = mBfIRBuilder->GetConstant(constantArray->mValues[memberIdx]);
  8766. if (memberConstant->mTypeCode == BfTypeCode_Char8)
  8767. {
  8768. intVal |= (uint64)(memberConstant->mUInt8) << (8 * memberIdx);
  8769. //intVal = (intVal << 8) | memberConstant->mUInt8;
  8770. }
  8771. }
  8772. return BfTypedValue(mBfIRBuilder->CreateConst(intType->mTypeDef->mTypeCode, intVal), intType);
  8773. }
  8774. }
  8775. auto convTypedValue = typedValue;
  8776. convTypedValue = MakeAddressable(convTypedValue);
  8777. auto intPtrType = CreatePointerType(intType);
  8778. auto addrVal = mBfIRBuilder->CreateBitCast(convTypedValue.mValue, mBfIRBuilder->MapType(intPtrType));
  8779. auto val = mBfIRBuilder->CreateLoad(addrVal);
  8780. return BfTypedValue(val, intType);
  8781. }
  8782. bool BfModule::TypeHasParent(BfTypeDef* checkChildTypeDef, BfTypeDef* checkParentTypeDef)
  8783. {
  8784. BfTypeDef* checkType = checkChildTypeDef;
  8785. while (checkType != NULL)
  8786. {
  8787. if (checkType == checkParentTypeDef)
  8788. return true;
  8789. checkType = checkType->mOuterType;
  8790. }
  8791. return false;
  8792. }
  8793. BfTypeDef* BfModule::FindCommonOuterType(BfTypeDef* type, BfTypeDef* type2)
  8794. {
  8795. if ((type == NULL) || (type2 == NULL))
  8796. return NULL;
  8797. int curNestDepth = std::min(type->mNestDepth, type2->mNestDepth);
  8798. while (type->mNestDepth > curNestDepth)
  8799. type = type->mOuterType;
  8800. while (type2->mNestDepth > curNestDepth)
  8801. type2 = type2->mOuterType;
  8802. while (curNestDepth >= 0)
  8803. {
  8804. if (type == type2)
  8805. return type;
  8806. type = type->mOuterType;
  8807. type2 = type2->mOuterType;
  8808. curNestDepth--;
  8809. }
  8810. return NULL;
  8811. }
  8812. bool BfModule::TypeIsSubTypeOf(BfTypeInstance* srcType, BfTypeInstance* wantType, bool checkAccessibility)
  8813. {
  8814. if ((srcType == NULL) || (wantType == NULL))
  8815. return false;
  8816. if (srcType == wantType)
  8817. return true;
  8818. if (srcType->mDefineState < BfTypeDefineState_HasInterfaces)
  8819. {
  8820. // Type is incomplete. We don't do the IsIncomplete check here because of re-entry
  8821. // While handling 'var' resolution, we don't want to force a PopulateType reentry
  8822. // but we do have enough information for TypeIsSubTypeOf
  8823. PopulateType(srcType, BfPopulateType_Interfaces);
  8824. }
  8825. if (wantType->IsInterface())
  8826. {
  8827. BfTypeDef* checkActiveTypeDef = NULL;
  8828. bool checkAccessibility = true;
  8829. if (IsInSpecializedSection())
  8830. {
  8831. // When we have a specialized section, the generic params may not be considered "included"
  8832. // in the module that contains the generic type definition. We rely on any casting errors
  8833. // to be thrown on the unspecialized type pass. We have a similar issue with injecting mixins.
  8834. checkAccessibility = false;
  8835. }
  8836. auto checkType = srcType;
  8837. while (checkType != NULL)
  8838. {
  8839. for (auto ifaceInst : checkType->mInterfaces)
  8840. {
  8841. if (ifaceInst.mInterfaceType == wantType)
  8842. {
  8843. if (checkAccessibility)
  8844. {
  8845. if (checkActiveTypeDef == NULL)
  8846. checkActiveTypeDef = GetActiveTypeDef(NULL, false);
  8847. // We need to be lenient when validating generic constraints
  8848. // Otherwise "T<A> where T : IB" declared in a lib won't be able to match a type B in a using project 'C',
  8849. // because this check will see the lib using 'C', which it won't consider visible
  8850. if ((checkActiveTypeDef != NULL) &&
  8851. ((mCurMethodInstance != NULL) && (mContext->mCurTypeState != NULL) && (!mContext->mCurTypeState->mBuildingGenericParams)))
  8852. {
  8853. if ((!srcType->IsTypeMemberAccessible(ifaceInst.mDeclaringType, checkActiveTypeDef)) ||
  8854. (!srcType->IsTypeMemberIncluded(ifaceInst.mDeclaringType, checkActiveTypeDef, this)))
  8855. {
  8856. continue;
  8857. }
  8858. }
  8859. }
  8860. return true;
  8861. }
  8862. }
  8863. checkType = checkType->GetImplBaseType();
  8864. if ((checkType != NULL) && (checkType->mDefineState < BfTypeDefineState_HasInterfaces))
  8865. {
  8866. PopulateType(checkType, BfPopulateType_Interfaces);
  8867. }
  8868. }
  8869. if (srcType->IsTypedPrimitive())
  8870. {
  8871. BfType* underlyingType = srcType->GetUnderlyingType();
  8872. if (underlyingType->IsWrappableType())
  8873. {
  8874. BfTypeInstance* wrappedType = GetWrappedStructType(underlyingType);
  8875. if ((wrappedType != NULL) && (wrappedType != srcType))
  8876. return TypeIsSubTypeOf(wrappedType, wantType, checkAccessibility);
  8877. }
  8878. }
  8879. return false;
  8880. }
  8881. auto srcBaseType = srcType->mBaseType;
  8882. return TypeIsSubTypeOf(srcBaseType, wantType);
  8883. }
  8884. // Positive value means that toType encompasses fromType, negative value means toType is encompassed by formType
  8885. // INT_MAX means the types are not related
  8886. int BfModule::GetTypeDistance(BfType* fromType, BfType* toType)
  8887. {
  8888. if (fromType == toType)
  8889. return 0;
  8890. if (fromType->IsPrimitiveType())
  8891. {
  8892. if (!toType->IsPrimitiveType())
  8893. return INT_MAX;
  8894. auto fromPrimType = (BfPrimitiveType*)fromType;
  8895. auto toPrimType = (BfPrimitiveType*)toType;
  8896. if ((fromPrimType->IsIntegral()) && (toPrimType->IsIntegral()))
  8897. {
  8898. int fromBitSize = fromPrimType->mSize * 8;
  8899. if (fromPrimType->IsSigned())
  8900. fromBitSize--;
  8901. int toBitSize = toPrimType->mSize * 8;
  8902. if (toPrimType->IsSigned())
  8903. toBitSize--;
  8904. return fromBitSize - toBitSize;
  8905. }
  8906. if ((fromPrimType->IsFloat()) && (toPrimType->IsFloat()))
  8907. {
  8908. return (fromPrimType->mSize * 8) - (toPrimType->mSize * 8);
  8909. }
  8910. if (((fromPrimType->IsIntegral()) || (fromPrimType->IsFloat())) &&
  8911. ((toPrimType->IsIntegral()) || (toPrimType->IsFloat())))
  8912. {
  8913. int sizeDiff = (fromPrimType->mSize * 8) - (toPrimType->mSize * 8);
  8914. if (sizeDiff < 0)
  8915. sizeDiff--;
  8916. else
  8917. sizeDiff++;
  8918. return sizeDiff;
  8919. }
  8920. return INT_MAX;
  8921. }
  8922. auto fromTypeInstance = fromType->ToTypeInstance();
  8923. auto toTypeInstance = toType->ToTypeInstance();
  8924. if ((fromTypeInstance != NULL) != (toTypeInstance != NULL))
  8925. return INT_MAX; // Ever valid?
  8926. if ((fromTypeInstance != NULL) && (toTypeInstance != NULL))
  8927. {
  8928. if ((fromTypeInstance->IsNullable()) && (toTypeInstance->IsNullable()))
  8929. return GetTypeDistance(fromTypeInstance->GetUnderlyingType(), toTypeInstance->GetUnderlyingType());
  8930. int inheritDistance = toTypeInstance->mInheritDepth - fromTypeInstance->mInheritDepth;
  8931. auto mostSpecificInstance = (inheritDistance < 0) ? fromTypeInstance : toTypeInstance;
  8932. auto leastSpecificInstance = (inheritDistance < 0) ? toTypeInstance : fromTypeInstance;
  8933. while (mostSpecificInstance != NULL)
  8934. {
  8935. if (mostSpecificInstance == leastSpecificInstance)
  8936. return inheritDistance;
  8937. mostSpecificInstance = mostSpecificInstance->mBaseType;
  8938. }
  8939. }
  8940. return INT_MAX;
  8941. }
  8942. bool BfModule::IsTypeMoreSpecific(BfType* leftType, BfType* rightType)
  8943. {
  8944. if (leftType->IsGenericTypeInstance())
  8945. {
  8946. if (!rightType->IsGenericTypeInstance())
  8947. return true;
  8948. auto leftGenericType = (BfGenericTypeInstance*)leftType;
  8949. auto rightGenericType = (BfGenericTypeInstance*)rightType;
  8950. if (leftGenericType->mTypeDef != rightGenericType->mTypeDef)
  8951. return false;
  8952. bool isBetter = false;
  8953. bool isWorse = false;
  8954. for (int argIdx = 0; argIdx < (int)leftGenericType->mTypeGenericArguments.size(); argIdx++)
  8955. {
  8956. if (IsTypeMoreSpecific(leftGenericType->mTypeGenericArguments[argIdx], rightGenericType->mTypeGenericArguments[argIdx]))
  8957. isBetter = true;
  8958. if (IsTypeMoreSpecific(rightGenericType->mTypeGenericArguments[argIdx], leftGenericType->mTypeGenericArguments[argIdx]))
  8959. isWorse = true;
  8960. }
  8961. return (isBetter) && (!isWorse);
  8962. }
  8963. return false;
  8964. }
  8965. StringT<128> BfModule::TypeToString(BfType* resolvedType)
  8966. {
  8967. BfTypeNameFlags flags = BfTypeNameFlags_None;
  8968. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  8969. flags = BfTypeNameFlag_ResolveGenericParamNames;
  8970. StringT<128> str;
  8971. DoTypeToString(str, resolvedType, flags);
  8972. return str;
  8973. }
  8974. StringT<128> BfModule::TypeToString(BfType* resolvedType, BfTypeNameFlags typeNameFlags, Array<String>* genericMethodParamNameOverrides)
  8975. {
  8976. StringT<128> str;
  8977. DoTypeToString(str, resolvedType, typeNameFlags, genericMethodParamNameOverrides);
  8978. return str;
  8979. }
  8980. void BfModule::VariantToString(StringImpl& str, const BfVariant& variant)
  8981. {
  8982. switch (variant.mTypeCode)
  8983. {
  8984. case BfTypeCode_Char8:
  8985. case BfTypeCode_Int8:
  8986. case BfTypeCode_UInt8:
  8987. case BfTypeCode_Int16:
  8988. case BfTypeCode_UInt16:
  8989. case BfTypeCode_Int32:
  8990. str += StrFormat("%d", variant.mInt32);
  8991. break;
  8992. case BfTypeCode_UInt32:
  8993. str += StrFormat("%lu", variant.mUInt32);
  8994. break;
  8995. case BfTypeCode_Int64:
  8996. str += StrFormat("%lld", variant.mInt64);
  8997. break;
  8998. case BfTypeCode_UInt64:
  8999. str += StrFormat("%llu", variant.mInt64);
  9000. break;
  9001. case BfTypeCode_Single:
  9002. {
  9003. char cstr[64];
  9004. ExactMinimalFloatToStr(variant.mSingle, cstr);
  9005. str += cstr;
  9006. if (strchr(cstr, '.') == NULL)
  9007. str += ".0f";
  9008. else
  9009. str += "f";
  9010. }
  9011. break;
  9012. case BfTypeCode_Double:
  9013. {
  9014. char cstr[64];
  9015. ExactMinimalDoubleToStr(variant.mDouble, cstr);
  9016. str += cstr;
  9017. if (strchr(cstr, '.') == NULL)
  9018. str += ".0";
  9019. }
  9020. break;
  9021. default: break;
  9022. }
  9023. }
  9024. void BfModule::DoTypeToString(StringImpl& str, BfType* resolvedType, BfTypeNameFlags typeNameFlags, Array<String>* genericMethodNameOverrides)
  9025. {
  9026. BP_ZONE("BfModule::DoTypeToString");
  9027. // This is clearly wrong. If we pass in @T0 from a generic type, this would immediately disable the ability to get its name
  9028. /*if (resolvedType->IsUnspecializedType())
  9029. typeNameFlags = (BfTypeNameFlags)(typeNameFlags & ~BfTypeNameFlag_ResolveGenericParamNames);*/
  9030. if (resolvedType->IsBoxed())
  9031. {
  9032. auto boxedType = (BfBoxedType*)resolvedType;
  9033. str += "boxed ";
  9034. DoTypeToString(str, boxedType->mElementType, typeNameFlags, genericMethodNameOverrides);
  9035. if (boxedType->mBoxedFlags == BfBoxedType::BoxedFlags_StructPtr)
  9036. str += "*";
  9037. return;
  9038. }
  9039. else if ((resolvedType->IsArray()) && ((typeNameFlags & BfTypeNameFlag_UseArrayImplType) == 0))
  9040. {
  9041. auto arrayType = (BfArrayType*)resolvedType;
  9042. DoTypeToString(str, arrayType->mTypeGenericArguments[0], typeNameFlags, genericMethodNameOverrides);
  9043. str += "[";
  9044. for (int i = 1; i < arrayType->mDimensions; i++)
  9045. str += ",";
  9046. str += "]";
  9047. return;
  9048. }
  9049. else if ((resolvedType->IsNullable()) && (!resolvedType->IsUnspecializedType()))
  9050. {
  9051. auto genericType = (BfGenericTypeInstance*)resolvedType;
  9052. auto elementType = genericType->mTypeGenericArguments[0];
  9053. DoTypeToString(str, elementType, typeNameFlags, genericMethodNameOverrides);
  9054. str += "?";
  9055. return;
  9056. }
  9057. else if (resolvedType->IsTuple())
  9058. {
  9059. BfTupleType* tupleType = (BfTupleType*)resolvedType;
  9060. str += "(";
  9061. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  9062. {
  9063. if (fieldIdx > 0)
  9064. str += ", ";
  9065. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  9066. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  9067. DoTypeToString(str, fieldInstance->GetResolvedType(), (BfTypeNameFlags)(typeNameFlags & ~(BfTypeNameFlag_OmitNamespace | BfTypeNameFlag_OmitOuterType)), genericMethodNameOverrides);
  9068. char c = fieldDef->mName[0];
  9069. if ((c < '0') || (c > '9'))
  9070. {
  9071. str += " ";
  9072. str += fieldDef->mName;
  9073. }
  9074. }
  9075. str += ")";
  9076. return;
  9077. }
  9078. else if (resolvedType->IsDelegateFromTypeRef() || resolvedType->IsFunctionFromTypeRef())
  9079. {
  9080. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance);
  9081. auto delegateType = (BfDelegateType*)resolvedType;
  9082. if (mCurTypeInstance == delegateType)
  9083. {
  9084. // Don't try to use ourselves for generic param resolution. This should only happen for debug printings from
  9085. // within InitType and such, not actual user-facing display
  9086. mCurTypeInstance = NULL;
  9087. }
  9088. auto methodDef = delegateType->mTypeDef->mMethods[0];
  9089. if (resolvedType->IsDelegateFromTypeRef())
  9090. str += "delegate ";
  9091. else
  9092. str += "function ";
  9093. DoTypeToString(str, ResolveTypeRef(methodDef->mReturnTypeRef));
  9094. str += "(";
  9095. for (int paramIdx = 0; paramIdx < methodDef->mParams.size(); paramIdx++)
  9096. {
  9097. if (paramIdx > 0)
  9098. str += ", ";
  9099. auto paramDef = methodDef->mParams[paramIdx];
  9100. BfTypeNameFlags innerFlags = (BfTypeNameFlags)(typeNameFlags & ~(BfTypeNameFlag_OmitNamespace | BfTypeNameFlag_OmitOuterType));
  9101. if (delegateType->mIsUnspecializedTypeVariation)
  9102. innerFlags = (BfTypeNameFlags)(innerFlags & ~BfTypeNameFlag_ResolveGenericParamNames);
  9103. DoTypeToString(str, ResolveTypeRef(paramDef->mTypeRef), innerFlags, genericMethodNameOverrides);
  9104. str += " ";
  9105. str += paramDef->mName;
  9106. }
  9107. str += ")";
  9108. return;
  9109. }
  9110. else if (resolvedType->IsMethodRef())
  9111. {
  9112. auto methodRefType = (BfMethodRefType*)resolvedType;
  9113. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  9114. if (methodRefType->IsDeleting())
  9115. {
  9116. str += "DELETED METHODREF";
  9117. return;
  9118. }
  9119. if (methodInstance == NULL)
  9120. {
  9121. str += "method NULL";
  9122. return;
  9123. }
  9124. str += "method ";
  9125. str += MethodToString(methodInstance);
  9126. return;
  9127. }
  9128. else if (resolvedType->IsTypeInstance())
  9129. {
  9130. BfTypeInstance* typeInstance = (BfTypeInstance*)resolvedType;
  9131. auto checkTypeInst = typeInstance;
  9132. auto checkTypeDef = typeInstance->mTypeDef;
  9133. auto checkCurTypeInst = mCurTypeInstance; // Only used for ReduceName
  9134. BfTypeDef* checkCurTypeDef = NULL;
  9135. if (checkCurTypeInst != NULL)
  9136. checkCurTypeDef = checkCurTypeInst->mTypeDef;
  9137. std::function<void(BfTypeDef*, int)> _AddTypeName = [&](BfTypeDef* checkTypeDef, int depth)
  9138. {
  9139. if (depth > 0)
  9140. {
  9141. if ((typeNameFlags & BfTypeNameFlag_OmitOuterType) != 0)
  9142. return;
  9143. if ((typeNameFlags & BfTypeNameFlag_ReduceName) != 0)
  9144. {
  9145. auto outerTypeInst = GetOuterType(checkTypeInst);
  9146. if (outerTypeInst == NULL)
  9147. return;
  9148. checkTypeInst = outerTypeInst;
  9149. while (checkCurTypeDef->mNestDepth > checkTypeDef->mNestDepth)
  9150. {
  9151. checkCurTypeInst = GetOuterType(checkCurTypeInst);
  9152. checkCurTypeDef = checkCurTypeInst->mTypeDef;
  9153. }
  9154. if (TypeIsSubTypeOf(checkCurTypeInst, checkTypeInst))
  9155. return; // Found outer type
  9156. }
  9157. }
  9158. auto parentTypeDef = checkTypeDef->mOuterType;
  9159. if (parentTypeDef != NULL)
  9160. {
  9161. _AddTypeName(parentTypeDef, depth + 1);
  9162. }
  9163. if (checkTypeDef->IsGlobalsContainer())
  9164. {
  9165. if ((typeNameFlags & BfTypeNameFlag_AddGlobalContainerName) != 0)
  9166. {
  9167. str += "G$";
  9168. str += checkTypeDef->mProject->mName;
  9169. }
  9170. }
  9171. else
  9172. {
  9173. checkTypeDef->mName->ToString(str);
  9174. if (!checkTypeDef->mGenericParamDefs.IsEmpty())
  9175. {
  9176. for (int ofs = 0; ofs < 3; ofs++)
  9177. {
  9178. int checkIdx = (int)str.length() - 1 - ofs;
  9179. if (checkIdx < 0)
  9180. break;
  9181. if (str[checkIdx] == '`')
  9182. {
  9183. str.RemoveToEnd(checkIdx);
  9184. break;
  9185. }
  9186. }
  9187. }
  9188. if (((typeNameFlags & BfTypeNameFlag_DisambiguateDups) != 0) && (checkTypeDef->mDupDetectedRevision != -1))
  9189. {
  9190. str += StrFormat("_%p", checkTypeDef);
  9191. }
  9192. }
  9193. int prevGenericParamCount = 0;
  9194. if (checkTypeDef->mOuterType != NULL)
  9195. {
  9196. prevGenericParamCount = (int)checkTypeDef->mOuterType->mGenericParamDefs.size();
  9197. }
  9198. if (resolvedType->IsGenericTypeInstance())
  9199. {
  9200. auto genericTypeInst = (BfGenericTypeInstance*)resolvedType;
  9201. if (prevGenericParamCount != (int)checkTypeDef->mGenericParamDefs.size())
  9202. {
  9203. str += '<';
  9204. for (int i = prevGenericParamCount; i < (int)checkTypeDef->mGenericParamDefs.size(); i++)
  9205. {
  9206. BfType* typeGenericArg = genericTypeInst->mTypeGenericArguments[i];
  9207. if (typeGenericArg->IsGenericParam())
  9208. {
  9209. if ((typeNameFlags & BfTypeNameFlag_ResolveGenericParamNames) == 0)
  9210. {
  9211. // We don't want the param names, just the commas (this is an unspecialized type reference)
  9212. if (i > prevGenericParamCount)
  9213. str += ',';
  9214. continue;
  9215. }
  9216. }
  9217. if (i > prevGenericParamCount)
  9218. str += ", ";
  9219. DoTypeToString(str, typeGenericArg, (BfTypeNameFlags)(typeNameFlags & ~(BfTypeNameFlag_OmitNamespace | BfTypeNameFlag_OmitOuterType)), genericMethodNameOverrides);
  9220. }
  9221. str += '>';
  9222. }
  9223. }
  9224. if (depth > 0)
  9225. str += '.';
  9226. };
  9227. bool omitNamespace = (typeNameFlags & BfTypeNameFlag_OmitNamespace) != 0;
  9228. if ((typeNameFlags & BfTypeNameFlag_ReduceName) != 0)
  9229. {
  9230. for (auto& checkNamespace : mCurTypeInstance->mTypeDef->mNamespaceSearch)
  9231. {
  9232. if (checkNamespace == typeInstance->mTypeDef->mNamespace)
  9233. omitNamespace = true;
  9234. }
  9235. }
  9236. if ((!typeInstance->mTypeDef->mNamespace.IsEmpty()) && (!omitNamespace))
  9237. {
  9238. if (!typeInstance->mTypeDef->mNamespace.IsEmpty())
  9239. {
  9240. typeInstance->mTypeDef->mNamespace.ToString(str);
  9241. if (!typeInstance->mTypeDef->IsGlobalsContainer())
  9242. str += '.';
  9243. }
  9244. }
  9245. _AddTypeName(typeInstance->mTypeDef, 0);
  9246. return;
  9247. }
  9248. else if (resolvedType->IsPrimitiveType())
  9249. {
  9250. auto primitiveType = (BfPrimitiveType*)resolvedType;
  9251. if (!primitiveType->mTypeDef->mNamespace.IsEmpty())
  9252. {
  9253. primitiveType->mTypeDef->mNamespace.ToString(str);
  9254. str += '.';
  9255. primitiveType->mTypeDef->mName->ToString(str);
  9256. return;
  9257. }
  9258. else
  9259. {
  9260. primitiveType->mTypeDef->mName->ToString(str);
  9261. return;
  9262. }
  9263. }
  9264. else if (resolvedType->IsPointer())
  9265. {
  9266. auto pointerType = (BfPointerType*)resolvedType;
  9267. DoTypeToString(str, pointerType->mElementType, typeNameFlags, genericMethodNameOverrides);
  9268. str += '*';
  9269. return;
  9270. }
  9271. else if (resolvedType->IsGenericParam())
  9272. {
  9273. bool doResolveGenericParams = (typeNameFlags & BfTypeNameFlag_ResolveGenericParamNames) != 0;
  9274. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  9275. doResolveGenericParams = false;
  9276. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecializedVariation))
  9277. doResolveGenericParams = false;
  9278. auto genericParam = (BfGenericParamType*)resolvedType;
  9279. if (!doResolveGenericParams)
  9280. {
  9281. if (genericParam->mGenericParamKind == BfGenericParamKind_Method)
  9282. {
  9283. str += StrFormat("@M%d", genericParam->mGenericParamIdx);
  9284. return;
  9285. }
  9286. str += StrFormat("@T%d", genericParam->mGenericParamIdx);
  9287. return;
  9288. }
  9289. if ((genericParam->mGenericParamKind == BfGenericParamKind_Type) && (mCurTypeInstance == NULL))
  9290. {
  9291. str += StrFormat("@T%d", genericParam->mGenericParamIdx);
  9292. return;
  9293. }
  9294. if (genericParam->mGenericParamKind == BfGenericParamKind_Method)
  9295. {
  9296. if (genericMethodNameOverrides != NULL)
  9297. {
  9298. str += (*genericMethodNameOverrides)[genericParam->mGenericParamIdx];
  9299. return;
  9300. }
  9301. if (mCurMethodInstance == NULL)
  9302. {
  9303. str += StrFormat("@M%d", genericParam->mGenericParamIdx);
  9304. return;
  9305. }
  9306. }
  9307. //TEMPORARY
  9308. if (genericParam->mGenericParamKind == BfGenericParamKind_Type)
  9309. {
  9310. auto curTypeInstance = mCurTypeInstance;
  9311. if (mCurMethodInstance != NULL)
  9312. curTypeInstance = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  9313. if ((curTypeInstance == NULL) || (!curTypeInstance->IsGenericTypeInstance()))
  9314. {
  9315. str += StrFormat("@T%d", genericParam->mGenericParamIdx);
  9316. return;
  9317. }
  9318. }
  9319. auto genericParamInstance = GetGenericParamInstance(genericParam);
  9320. str += genericParamInstance->GetGenericParamDef()->mName;
  9321. return;
  9322. }
  9323. else if (resolvedType->IsRef())
  9324. {
  9325. auto refType = (BfRefType*)resolvedType;
  9326. if (refType->mRefKind == BfRefType::RefKind_Ref)
  9327. {
  9328. str += "ref ";
  9329. DoTypeToString(str, refType->mElementType, typeNameFlags, genericMethodNameOverrides);
  9330. return;
  9331. }
  9332. else if (refType->mRefKind == BfRefType::RefKind_Out)
  9333. {
  9334. str += "out ";
  9335. DoTypeToString(str, refType->mElementType, typeNameFlags, genericMethodNameOverrides);
  9336. return;
  9337. }
  9338. else
  9339. {
  9340. str += "mut ";
  9341. DoTypeToString(str, refType->mElementType, typeNameFlags, genericMethodNameOverrides);
  9342. return;
  9343. }
  9344. }
  9345. else if (resolvedType->IsRetTypeType())
  9346. {
  9347. auto retTypeType = (BfRetTypeType*)resolvedType;
  9348. str += "rettype(";
  9349. DoTypeToString(str, retTypeType->mElementType, typeNameFlags, genericMethodNameOverrides);
  9350. str += ")";
  9351. return;
  9352. }
  9353. else if (resolvedType->IsConcreteInterfaceType())
  9354. {
  9355. auto concreteTypeType = (BfConcreteInterfaceType*)resolvedType;
  9356. str += "concrete ";
  9357. DoTypeToString(str, concreteTypeType->mInterface, typeNameFlags, genericMethodNameOverrides);
  9358. return;
  9359. }
  9360. else if (resolvedType->IsUnknownSizedArray())
  9361. {
  9362. auto arrayType = (BfUnknownSizedArrayType*)resolvedType;
  9363. DoTypeToString(str, arrayType->mElementType, typeNameFlags, genericMethodNameOverrides);
  9364. str += "[";
  9365. DoTypeToString(str, arrayType->mElementCountSource, typeNameFlags, genericMethodNameOverrides);
  9366. str += "]";
  9367. return;
  9368. }
  9369. else if (resolvedType->IsSizedArray())
  9370. {
  9371. auto arrayType = (BfSizedArrayType*)resolvedType;
  9372. if (arrayType->mElementCount == -1)
  9373. {
  9374. DoTypeToString(str, arrayType->mElementType, typeNameFlags, genericMethodNameOverrides);
  9375. str += "[?]";
  9376. return;
  9377. }
  9378. DoTypeToString(str, arrayType->mElementType, typeNameFlags, genericMethodNameOverrides);
  9379. str += StrFormat("[%d]", arrayType->mElementCount);
  9380. return;
  9381. }
  9382. else if (resolvedType->IsConstExprValue())
  9383. {
  9384. auto constExprValueType = (BfConstExprValueType*)resolvedType;
  9385. str += "const ";
  9386. DoTypeToString(str, constExprValueType->mType, typeNameFlags, genericMethodNameOverrides);
  9387. str += " ";
  9388. VariantToString(str, constExprValueType->mValue);
  9389. return;
  9390. }
  9391. BF_FATAL("Not implemented");
  9392. str += "???";
  9393. return;
  9394. }