2
0

BfModuleTypeUtils.cpp 352 KB

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