BfModuleTypeUtils.cpp 365 KB

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