BfModuleTypeUtils.cpp 426 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462
  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(BfTypeInstance* genericTypeInst, BfTypeDef* partialTypeDef)
  35. {
  36. if (!partialTypeDef->IsExtension())
  37. return NULL;
  38. if (partialTypeDef->mGenericParamDefs.size() != genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size())
  39. {
  40. AssertErrorState();
  41. return NULL;
  42. }
  43. BfGenericExtensionInfo* genericExtensionInfo = genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo;
  44. if (genericExtensionInfo == NULL)
  45. {
  46. genericExtensionInfo = new BfGenericExtensionInfo();
  47. genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo = genericExtensionInfo;
  48. }
  49. BfTypeState typeState;
  50. typeState.mPrevState = mContext->mCurTypeState;
  51. typeState.mTypeInstance = genericTypeInst;
  52. typeState.mCurTypeDef = partialTypeDef;
  53. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  54. BfGenericExtensionEntry* genericExEntry;
  55. genericExtensionInfo->mExtensionMap.TryAdd(partialTypeDef, NULL, &genericExEntry);
  56. int startDefGenericParamIdx = (int)genericExEntry->mGenericParams.size();
  57. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size(); paramIdx++)
  58. {
  59. auto genericParamInstance = new BfGenericTypeParamInstance(partialTypeDef, paramIdx);
  60. genericParamInstance->mExternType = GetGenericParamType(BfGenericParamKind_Type, paramIdx);
  61. auto prevPtr = genericExEntry->mGenericParams.mVals;
  62. genericExEntry->mGenericParams.push_back(genericParamInstance);
  63. }
  64. for (int externConstraintIdx = 0; externConstraintIdx < (int)partialTypeDef->mExternalConstraints.size(); externConstraintIdx++)
  65. {
  66. auto& genericConstraint = partialTypeDef->mExternalConstraints[externConstraintIdx];
  67. auto genericParamInstance = new BfGenericTypeParamInstance(partialTypeDef, externConstraintIdx + (int)partialTypeDef->mGenericParamDefs.size());
  68. genericParamInstance->mExternType = ResolveTypeRef(genericConstraint.mTypeRef, BfPopulateType_Identity);
  69. auto autoComplete = mCompiler->GetAutoComplete();
  70. if (autoComplete != NULL)
  71. autoComplete->CheckTypeRef(genericConstraint.mTypeRef, false);
  72. if (genericParamInstance->mExternType == NULL)
  73. genericParamInstance->mExternType = GetPrimitiveType(BfTypeCode_Var);
  74. ResolveGenericParamConstraints(genericParamInstance, genericTypeInst->IsUnspecializedType());
  75. genericExEntry->mGenericParams.push_back(genericParamInstance);
  76. }
  77. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size(); paramIdx++)
  78. {
  79. auto genericParamInstance = genericExEntry->mGenericParams[paramIdx];
  80. auto rootGenericParamInstance = genericTypeInst->mGenericTypeInfo->mGenericParams[paramIdx];
  81. genericParamInstance->mTypeConstraint = rootGenericParamInstance->mTypeConstraint;
  82. genericParamInstance->mInterfaceConstraints = rootGenericParamInstance->mInterfaceConstraints;
  83. genericParamInstance->mGenericParamFlags |= rootGenericParamInstance->mGenericParamFlags;
  84. ResolveGenericParamConstraints(genericParamInstance, genericTypeInst->IsUnspecializedType());
  85. }
  86. for (auto genericParam : genericExEntry->mGenericParams)
  87. {
  88. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  89. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  90. if (genericParam->mTypeConstraint != NULL)
  91. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  92. }
  93. return genericExEntry;
  94. }
  95. bool BfModule::InitGenericParams(BfType* resolvedTypeRef)
  96. {
  97. BfTypeState typeState;
  98. typeState.mPrevState = mContext->mCurTypeState;
  99. typeState.mResolveKind = BfTypeState::ResolveKind_BuildingGenericParams;
  100. typeState.mTypeInstance = resolvedTypeRef->ToTypeInstance();
  101. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  102. BF_ASSERT(mCurMethodInstance == NULL);
  103. auto genericTypeInst = resolvedTypeRef->ToGenericTypeInstance();
  104. genericTypeInst->mGenericTypeInfo->mInitializedGenericParams = true;
  105. if (genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0]->IsGenericParam())
  106. {
  107. BF_ASSERT(genericTypeInst->mGenericTypeInfo->mIsUnspecialized);
  108. }
  109. auto typeDef = genericTypeInst->mTypeDef;
  110. int startDefGenericParamIdx = (int)genericTypeInst->mGenericTypeInfo->mGenericParams.size();
  111. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size(); paramIdx++)
  112. {
  113. auto genericParamInstance = new BfGenericTypeParamInstance(typeDef, paramIdx);
  114. genericParamInstance->mExternType = GetGenericParamType(BfGenericParamKind_Type, paramIdx);
  115. genericTypeInst->mGenericTypeInfo->mGenericParams.push_back(genericParamInstance);
  116. }
  117. for (int externConstraintIdx = 0; externConstraintIdx < (int)typeDef->mExternalConstraints.size(); externConstraintIdx++)
  118. {
  119. auto genericParamInstance = new BfGenericTypeParamInstance(typeDef, externConstraintIdx + (int)typeDef->mGenericParamDefs.size());
  120. genericTypeInst->mGenericTypeInfo->mGenericParams.push_back(genericParamInstance);
  121. }
  122. return true;
  123. }
  124. bool BfModule::FinishGenericParams(BfType* resolvedTypeRef)
  125. {
  126. BfTypeState typeState;
  127. typeState.mPrevState = mContext->mCurTypeState;
  128. typeState.mResolveKind = BfTypeState::ResolveKind_BuildingGenericParams;
  129. typeState.mTypeInstance = resolvedTypeRef->ToTypeInstance();
  130. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  131. BF_ASSERT(mCurMethodInstance == NULL);
  132. auto genericTypeInst = resolvedTypeRef->ToGenericTypeInstance();
  133. genericTypeInst->mGenericTypeInfo->mFinishedGenericParams = true;
  134. if (genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0]->IsGenericParam())
  135. {
  136. BF_ASSERT(genericTypeInst->mGenericTypeInfo->mIsUnspecialized);
  137. }
  138. auto typeDef = genericTypeInst->mTypeDef;
  139. int startDefGenericParamIdx = (int)genericTypeInst->mGenericTypeInfo->mGenericParams.size();
  140. if ((!resolvedTypeRef->IsTuple()) && (!resolvedTypeRef->IsDelegateFromTypeRef()) && (!resolvedTypeRef->IsFunctionFromTypeRef()))
  141. {
  142. startDefGenericParamIdx = startDefGenericParamIdx -
  143. (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size() -
  144. (int)typeDef->mExternalConstraints.size();
  145. }
  146. BF_ASSERT(startDefGenericParamIdx >= 0);
  147. if (!typeDef->mPartials.empty())
  148. {
  149. for (auto partialTypeDef : typeDef->mPartials)
  150. {
  151. if (!partialTypeDef->IsExtension())
  152. {
  153. typeState.mCurTypeDef = partialTypeDef;
  154. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mGenericTypeInfo->mGenericParams.size(); paramIdx++)
  155. {
  156. auto genericParamInstance = genericTypeInst->mGenericTypeInfo->mGenericParams[paramIdx];
  157. auto genericParamDef = genericParamInstance->GetGenericParamDef();
  158. if (paramIdx < (int)typeDef->mGenericParamDefs.size())
  159. {
  160. genericParamInstance->mExternType = GetGenericParamType(BfGenericParamKind_Type, paramIdx);
  161. }
  162. else
  163. {
  164. auto externConstraintDef = genericParamInstance->GetExternConstraintDef();
  165. genericParamInstance->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  166. if (genericParamInstance->mExternType == NULL)
  167. genericParamInstance->mExternType = GetPrimitiveType(BfTypeCode_Var);
  168. }
  169. ResolveGenericParamConstraints(genericParamInstance, genericTypeInst->IsUnspecializedType());
  170. if (genericParamDef != NULL)
  171. {
  172. for (auto nameNode : genericParamDef->mNameNodes)
  173. {
  174. HandleTypeGenericParamRef(nameNode, typeDef, paramIdx);
  175. }
  176. }
  177. }
  178. }
  179. else
  180. {
  181. auto genericExEntry = BuildGenericExtensionInfo(genericTypeInst, partialTypeDef);
  182. if (genericExEntry == NULL)
  183. continue;
  184. if (!genericTypeInst->IsUnspecializedType())
  185. {
  186. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  187. for (int paramIdx = 0; paramIdx < genericExEntry->mGenericParams.size(); paramIdx++)
  188. {
  189. auto genericParamInstance = genericExEntry->mGenericParams[paramIdx];
  190. BfGenericParamSource genericParamSource;
  191. genericParamSource.mCheckAccessibility = false;
  192. genericParamSource.mTypeInstance = genericTypeInst;
  193. BfError* error = NULL;
  194. BfType* genericArg;
  195. if (paramIdx < (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size())
  196. {
  197. genericArg = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[paramIdx];
  198. }
  199. else
  200. {
  201. genericArg = genericParamInstance->mExternType;
  202. }
  203. if ((genericArg == NULL) || (!CheckGenericConstraints(genericParamSource, genericArg, NULL, genericParamInstance, NULL, &error)))
  204. {
  205. genericExEntry->mConstraintsPassed = false;
  206. }
  207. }
  208. }
  209. }
  210. }
  211. }
  212. else
  213. {
  214. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mGenericTypeInfo->mGenericParams.size(); paramIdx++)
  215. {
  216. auto genericParamInstance = genericTypeInst->mGenericTypeInfo->mGenericParams[paramIdx];
  217. if (paramIdx < (int)typeDef->mGenericParamDefs.size())
  218. {
  219. genericParamInstance->mExternType = GetGenericParamType(BfGenericParamKind_Type, paramIdx);
  220. }
  221. else
  222. {
  223. auto externConstraintDef = genericParamInstance->GetExternConstraintDef();
  224. genericParamInstance->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  225. auto autoComplete = mCompiler->GetAutoComplete();
  226. if (autoComplete != NULL)
  227. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  228. if (genericParamInstance->mExternType != NULL)
  229. {
  230. //
  231. }
  232. else
  233. genericParamInstance->mExternType = GetPrimitiveType(BfTypeCode_Var);
  234. }
  235. ResolveGenericParamConstraints(genericParamInstance, genericTypeInst->IsUnspecializedType());
  236. auto genericParamDef = genericParamInstance->GetGenericParamDef();
  237. if (genericParamDef != NULL)
  238. {
  239. for (auto nameNode : genericParamDef->mNameNodes)
  240. {
  241. HandleTypeGenericParamRef(nameNode, typeDef, paramIdx);
  242. }
  243. }
  244. }
  245. }
  246. for (auto genericParam : genericTypeInst->mGenericTypeInfo->mGenericParams)
  247. {
  248. for (auto constraintTypeInst : genericParam->mInterfaceConstraints)
  249. AddDependency(constraintTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  250. if (genericParam->mTypeConstraint != NULL)
  251. AddDependency(genericParam->mTypeConstraint, mCurTypeInstance, BfDependencyMap::DependencyFlag_Constraint);
  252. }
  253. return true;
  254. }
  255. bool BfModule::ValidateGenericConstraints(BfTypeReference* typeRef, BfTypeInstance* genericTypeInst, bool ignoreErrors)
  256. {
  257. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsTypeAlias()))
  258. {
  259. // Don't validate constraints during the population of a concrete generic type alias instance, we want to
  260. // throw those errors at the usage sites
  261. return true;
  262. }
  263. // We don't validate constraints for things like Tuples/Delegates
  264. if (genericTypeInst->IsOnDemand())
  265. return true;
  266. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, mIgnoreErrors || ignoreErrors);
  267. genericTypeInst->mGenericTypeInfo->mValidatedGenericConstraints = true;
  268. if (!genericTypeInst->mGenericTypeInfo->mFinishedGenericParams)
  269. PopulateType(genericTypeInst, BfPopulateType_Interfaces);
  270. if (genericTypeInst->IsTypeAlias())
  271. {
  272. auto underlyingType = genericTypeInst->GetUnderlyingType();
  273. if ((underlyingType != NULL) && (underlyingType->IsGenericTypeInstance()))
  274. {
  275. PopulateType(underlyingType, BfPopulateType_Declaration);
  276. return ValidateGenericConstraints(typeRef, (BfTypeInstance*)underlyingType, ignoreErrors);
  277. }
  278. return true;
  279. }
  280. auto typeDef = genericTypeInst->mTypeDef;
  281. for (int paramIdx = 0; paramIdx < (int)genericTypeInst->mGenericTypeInfo->mGenericParams.size(); paramIdx++)
  282. {
  283. auto genericParamInstance = genericTypeInst->mGenericTypeInfo->mGenericParams[paramIdx];
  284. BfType* genericArg;
  285. if (paramIdx < (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size())
  286. {
  287. genericArg = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[paramIdx];
  288. }
  289. else
  290. {
  291. genericArg = genericParamInstance->mExternType;
  292. }
  293. BfError* error = NULL;
  294. if ((genericArg == NULL) || (!CheckGenericConstraints(BfGenericParamSource(genericTypeInst), genericArg, typeRef, genericParamInstance, NULL, &error)))
  295. {
  296. genericTypeInst->mGenericTypeInfo->mHadValidateErrors = true;
  297. return false;
  298. }
  299. }
  300. return true;
  301. }
  302. bool BfModule::AreConstraintsSubset(BfGenericParamInstance* checkInner, BfGenericParamInstance* checkOuter)
  303. {
  304. // Added new flags?
  305. if ((checkInner->mGenericParamFlags | checkOuter->mGenericParamFlags) != checkOuter->mGenericParamFlags)
  306. {
  307. // If the outer had a type flag and the inner has a specific type constraint, then see if those are compatible
  308. auto outerFlags = checkOuter->mGenericParamFlags;
  309. if ((outerFlags & BfGenericParamFlag_Enum) != 0)
  310. outerFlags |= BfGenericParamFlag_Struct;
  311. if (checkOuter->mTypeConstraint != NULL)
  312. {
  313. if (checkOuter->mTypeConstraint->IsStruct())
  314. outerFlags |= BfGenericParamFlag_Struct;
  315. else if (checkOuter->mTypeConstraint->IsStructOrStructPtr())
  316. outerFlags |= BfGenericParamFlag_StructPtr;
  317. else if (checkOuter->mTypeConstraint->IsObject())
  318. outerFlags |= BfGenericParamFlag_Class;
  319. else if (checkOuter->mTypeConstraint->IsEnum())
  320. outerFlags |= BfGenericParamFlag_Enum | BfGenericParamFlag_Struct;
  321. else if (checkOuter->mTypeConstraint->IsInterface())
  322. outerFlags |= BfGenericParamFlag_Interface;
  323. }
  324. auto innerFlags = checkInner->mGenericParamFlags;
  325. if ((innerFlags & BfGenericParamFlag_Enum) != 0)
  326. innerFlags |= BfGenericParamFlag_Struct;
  327. if (((innerFlags | outerFlags) & ~BfGenericParamFlag_Var) != (outerFlags & ~BfGenericParamFlag_Var))
  328. return false;
  329. }
  330. if (checkInner->mTypeConstraint != NULL)
  331. {
  332. if (checkOuter->mTypeConstraint == NULL)
  333. return false;
  334. if (!TypeIsSubTypeOf(checkOuter->mTypeConstraint->ToTypeInstance(), checkInner->mTypeConstraint->ToTypeInstance()))
  335. return false;
  336. }
  337. for (auto& innerIFace : checkInner->mInterfaceConstraints)
  338. {
  339. if (!checkOuter->mInterfaceConstraints.Contains(innerIFace))
  340. return false;
  341. }
  342. for (auto& innerOp : checkInner->mOperatorConstraints)
  343. {
  344. if (!checkOuter->mOperatorConstraints.Contains(innerOp))
  345. return false;
  346. }
  347. return true;
  348. }
  349. bool BfModule::CheckConstraintState(BfAstNode* refNode)
  350. {
  351. if (mContext->mCurConstraintState == NULL)
  352. return true;
  353. auto checkState = mContext->mCurConstraintState->mPrevState;
  354. while (checkState != NULL)
  355. {
  356. if (*checkState == *mContext->mCurConstraintState)
  357. {
  358. if (refNode != NULL)
  359. {
  360. Fail("Constraints cause circular operator invocations", refNode);
  361. }
  362. return false;
  363. }
  364. checkState = checkState->mPrevState;
  365. }
  366. return true;
  367. }
  368. bool BfModule::ShouldAllowMultipleDefinitions(BfTypeInstance* typeInst, BfTypeDef* firstDeclaringTypeDef, BfTypeDef* secondDeclaringTypeDef)
  369. {
  370. if (firstDeclaringTypeDef == secondDeclaringTypeDef)
  371. return false;
  372. // Since we will use shared debugging info, we won't be able to differentiate between these two fields.
  373. // If we created per-target debug info then we could "fix" this.
  374. // Can these projects even see each other?
  375. if ((!firstDeclaringTypeDef->mProject->ContainsReference(secondDeclaringTypeDef->mProject)) &&
  376. (!secondDeclaringTypeDef->mProject->ContainsReference(firstDeclaringTypeDef->mProject)))
  377. return true;
  378. if (typeInst->IsUnspecializedType())
  379. {
  380. bool alwaysCoincide = true;
  381. auto genericTypeInst = (BfTypeInstance*)typeInst;
  382. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  383. {
  384. auto firstConstraints = genericTypeInst->GetGenericParamsVector(firstDeclaringTypeDef);
  385. auto secondConstraints = genericTypeInst->GetGenericParamsVector(secondDeclaringTypeDef);
  386. for (int genericIdx = 0; genericIdx < (int)firstConstraints->size(); genericIdx++)
  387. {
  388. auto firstConstraint = (*firstConstraints)[genericIdx];
  389. auto secondConstraint = (*secondConstraints)[genericIdx];
  390. if ((!AreConstraintsSubset(firstConstraint, secondConstraint)) &&
  391. (!AreConstraintsSubset(secondConstraint, firstConstraint)))
  392. alwaysCoincide = false;
  393. }
  394. }
  395. // Only show an error if we are certain both members will always appear at the same time
  396. if (!alwaysCoincide)
  397. return true;
  398. }
  399. return false;
  400. }
  401. void BfModule::CheckInjectNewRevision(BfTypeInstance* typeInstance)
  402. {
  403. if ((typeInstance != NULL) && (typeInstance->mTypeDef != NULL))
  404. {
  405. if (typeInstance->mTypeDef->mNextRevision != NULL)
  406. {
  407. // It's possible that our main compiler thread is generating a new typedef while we're autocompleting. This handles that case...
  408. if (typeInstance->mDefineState == BfTypeDefineState_Undefined)
  409. {
  410. if (typeInstance->IsBoxed())
  411. {
  412. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  413. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  414. PopulateType(innerType, BfPopulateType_Data);
  415. }
  416. else
  417. {
  418. mContext->HandleChangedTypeDef(typeInstance->mTypeDef);
  419. mSystem->InjectNewRevision(typeInstance->mTypeDef);
  420. }
  421. }
  422. else
  423. {
  424. BF_ASSERT(mCompiler->IsAutocomplete());
  425. }
  426. }
  427. if ((!typeInstance->IsDeleting()) && (!mCompiler->IsAutocomplete()))
  428. BF_ASSERT((typeInstance->mTypeDef->mDefState == BfTypeDef::DefState_Defined) || (typeInstance->mTypeDef->mDefState == BfTypeDef::DefState_New));
  429. }
  430. }
  431. void BfModule::InitType(BfType* resolvedTypeRef, BfPopulateType populateType)
  432. {
  433. BP_ZONE("BfModule::InitType");
  434. if (auto depType = resolvedTypeRef->ToDependedType())
  435. {
  436. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL))
  437. {
  438. depType->mDependencyMap.mMinDependDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  439. }
  440. else if (mCurTypeInstance != NULL)
  441. {
  442. depType->mDependencyMap.mMinDependDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  443. }
  444. }
  445. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, resolvedTypeRef->ToTypeInstance());
  446. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  447. if (mCompiler->mHotState != NULL)
  448. mCompiler->mHotState->mHasNewTypes = true;
  449. auto typeInst = resolvedTypeRef->ToTypeInstance();
  450. if (typeInst != NULL)
  451. {
  452. CheckInjectNewRevision(typeInst);
  453. if (typeInst->mBaseType != NULL)
  454. BF_ASSERT((typeInst->mBaseType->mRebuildFlags & BfTypeRebuildFlag_Deleted) == 0);
  455. if ((typeInst->mTypeDef != NULL) && (typeInst->mTypeDef->mDefState == BfTypeDef::DefState_New) &&
  456. (typeInst->mTypeDef->mNextRevision == NULL))
  457. {
  458. mContext->HandleChangedTypeDef(typeInst->mTypeDef);
  459. typeInst->mTypeDef->mDefState = BfTypeDef::DefState_Defined;
  460. }
  461. typeInst->mIsReified = mIsReified;
  462. //BF_ASSERT(typeInst->mTypeDef->mTypeCode != BfTypeCode_Extension);
  463. if (resolvedTypeRef->IsTuple())
  464. {
  465. auto tupleType = (BfTypeInstance*)resolvedTypeRef;
  466. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  467. {
  468. auto fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  469. // if (fieldInstance->GetResolvedType()->IsUnspecializedType())
  470. // tupleType->mHasUnspecializedMembers = true;
  471. }
  472. }
  473. typeInst->mRevision = mCompiler->mRevision;
  474. if (typeInst->mTypeDef != NULL)
  475. BF_ASSERT(typeInst->mTypeDef->mDefState != BfTypeDef::DefState_Deleted);
  476. }
  477. if (resolvedTypeRef->IsGenericTypeInstance())
  478. {
  479. auto genericTypeInst = (BfTypeInstance*)resolvedTypeRef;
  480. //BF_ASSERT(genericTypeInst->mGenericParams.size() <= genericTypeInst->mTypeGenericArguments.size());
  481. // BF_ASSERT((genericTypeInst->mGenericParams.size() == 0) ||
  482. // (genericTypeInst->mGenericParams.size() == genericTypeInst->mTypeGenericArguments.size()));
  483. for (auto typeGenericArg : genericTypeInst->mGenericTypeInfo->mTypeGenericArguments)
  484. BF_ASSERT((typeGenericArg->mRebuildFlags & BfTypeRebuildFlag_Deleted) == 0);
  485. }
  486. if (!mContext->mSavedTypeDataMap.IsEmpty())
  487. {
  488. String typeName = BfSafeMangler::Mangle(resolvedTypeRef, this);
  489. BfSavedTypeData* savedTypeData;
  490. if (mContext->mSavedTypeDataMap.Remove(typeName, &savedTypeData))
  491. {
  492. // if (resolvedTypeRef->mTypeId != -1)
  493. // {
  494. // // If we have an ID and it as the last one assigned the roll back the ID counter
  495. // if (resolvedTypeRef->mTypeId == mCompiler->mCurTypeId - 1)
  496. // mCompiler->mCurTypeId--;
  497. // }
  498. mContext->mSavedTypeData[savedTypeData->mTypeId] = NULL;
  499. resolvedTypeRef->mTypeId = savedTypeData->mTypeId;
  500. BfLogSysM("Using mSavedTypeData for %p %s\n", resolvedTypeRef, typeName.c_str());
  501. if (typeInst != NULL)
  502. {
  503. if (mCompiler->IsHotCompile())
  504. {
  505. BfLogSysM("Using mSavedTypeData HotTypeData %p for %p\n", savedTypeData->mHotTypeData, resolvedTypeRef);
  506. typeInst->mHotTypeData = savedTypeData->mHotTypeData;
  507. savedTypeData->mHotTypeData = NULL;
  508. }
  509. }
  510. delete savedTypeData;
  511. mContext->mTypes[resolvedTypeRef->mTypeId] = resolvedTypeRef;
  512. }
  513. else
  514. {
  515. BfLogSysM("No mSavedTypeData entry for %p %s\n", resolvedTypeRef, typeName.c_str());
  516. }
  517. }
  518. resolvedTypeRef->mContext = mContext;
  519. if (resolvedTypeRef->IsGenericTypeInstance())
  520. {
  521. auto genericTypeInstance = (BfTypeInstance*)resolvedTypeRef;
  522. #ifdef _DEBUG
  523. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  524. BF_ASSERT(!genericArg->IsVar());
  525. #endif
  526. // Do it here so the location we attempted to specialize this type will throw the failure if there is one
  527. if (!InitGenericParams(resolvedTypeRef))
  528. return;
  529. }
  530. BfLogSysM("%p InitType: %s Type: %p TypeDef: %p Revision:%d\n", mContext, TypeToString(resolvedTypeRef).c_str(), resolvedTypeRef, (typeInst != NULL) ? typeInst->mTypeDef : NULL, mCompiler->mRevision);
  531. // When we're autocomplete, we can't do the method processing so we have to add this type to the type work list
  532. if (((populateType < BfPopulateType_Full) || (mCompiler->IsAutocomplete())) /*&& (!resolvedTypeRef->IsUnspecializedTypeVariation())*/ && (resolvedTypeRef->IsTypeInstance()) &&
  533. (!resolvedTypeRef->IsTypeAlias()))
  534. {
  535. BfTypeProcessRequest* typeProcessRequest = mContext->mPopulateTypeWorkList.Alloc();
  536. typeProcessRequest->mType = resolvedTypeRef;
  537. BF_ASSERT(resolvedTypeRef->mContext == mContext);
  538. mCompiler->mStats.mTypesQueued++;
  539. mCompiler->UpdateCompletion();
  540. }
  541. PopulateType(resolvedTypeRef, populateType);
  542. }
  543. void BfModule::AddFieldDependency(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfType* fieldType)
  544. {
  545. auto fieldTypeInstance = fieldType->ToTypeInstance();
  546. if (fieldTypeInstance == NULL)
  547. {
  548. auto underlyingType = fieldType->GetUnderlyingType();
  549. if (underlyingType != NULL)
  550. AddFieldDependency(typeInstance, fieldInstance, underlyingType);
  551. return;
  552. }
  553. auto depFlag = fieldTypeInstance->IsValueType() ? BfDependencyMap::DependencyFlag_ValueTypeMemberData : BfDependencyMap::DependencyFlag_PtrMemberData;
  554. AddDependency(fieldTypeInstance, typeInstance, depFlag);
  555. if ((fieldTypeInstance->IsStruct()) && (fieldTypeInstance->IsGenericTypeInstance()))
  556. {
  557. // When we're a generic struct, our data layout can depend on our generic parameters as well
  558. auto genericTypeInstance = (BfTypeInstance*)fieldTypeInstance;
  559. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  560. AddFieldDependency(typeInstance, fieldInstance, typeGenericArg);
  561. }
  562. }
  563. BfFieldInstance* BfModule::GetFieldByName(BfTypeInstance* typeInstance, const StringImpl& fieldName, bool isRequired, BfAstNode* refNode)
  564. {
  565. PopulateType(typeInstance);
  566. typeInstance->mTypeDef->PopulateMemberSets();
  567. BfMemberSetEntry* entry = NULL;
  568. BfFieldDef* fieldDef = NULL;
  569. if (typeInstance->mTypeDef->mFieldSet.TryGetWith(fieldName, &entry))
  570. {
  571. fieldDef = (BfFieldDef*)entry->mMemberDef;
  572. return &typeInstance->mFieldInstances[fieldDef->mIdx];
  573. }
  574. if (isRequired)
  575. {
  576. FailInternal(StrFormat("Field '%s' not found in '%s'", fieldName.c_str(), TypeToString(typeInstance).c_str()), refNode);
  577. }
  578. return NULL;
  579. }
  580. void BfModule::CheckMemberNames(BfTypeInstance* typeInst)
  581. {
  582. struct MemberRef
  583. {
  584. BfMemberDef* mMemberDef;
  585. String mName;
  586. String mKindName;
  587. BfTypeInstance* mTypeInst;
  588. BfAstNode* mNameNode;
  589. BfProtection mProtection;
  590. BfTypeDef* mDeclaringType;
  591. bool mIsOverride;
  592. };
  593. SizedArray<MemberRef, 64> memberList;
  594. // Check base types first and then current type
  595. auto checkType = typeInst;
  596. while (checkType != NULL)
  597. {
  598. for (auto prop : checkType->mTypeDef->mProperties)
  599. {
  600. BfPropertyDeclaration* propDecl = (BfPropertyDeclaration*)prop->mFieldDeclaration;
  601. if ((propDecl != NULL) && (propDecl->mExplicitInterface != NULL))
  602. continue;
  603. if (!typeInst->IsTypeMemberIncluded(prop->mDeclaringType))
  604. continue;
  605. MemberRef memberRef = { 0 };
  606. memberRef.mMemberDef = prop;
  607. memberRef.mTypeInst = checkType;
  608. memberRef.mProtection = prop->mProtection;
  609. memberRef.mName = prop->mName;
  610. memberRef.mKindName = "property";
  611. if (prop->mFieldDeclaration != NULL)
  612. memberRef.mNameNode = prop->mFieldDeclaration->mNameNode;
  613. memberRef.mDeclaringType = prop->mDeclaringType;
  614. auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(prop->mFieldDeclaration);
  615. if (propertyDeclaration != NULL)
  616. memberRef.mIsOverride = (propertyDeclaration->mNewSpecifier != NULL) ||
  617. ((propertyDeclaration->mVirtualSpecifier != NULL) && (propertyDeclaration->mVirtualSpecifier->GetToken() == BfToken_Override));
  618. memberList.push_back(memberRef);
  619. }
  620. for (auto field : checkType->mTypeDef->mFields)
  621. {
  622. if (!typeInst->IsTypeMemberIncluded(field->mDeclaringType))
  623. continue;
  624. MemberRef memberRef = { 0 };
  625. memberRef.mMemberDef = field;
  626. memberRef.mTypeInst = checkType;
  627. memberRef.mProtection = field->mProtection;
  628. memberRef.mName = field->mName;
  629. memberRef.mKindName = "field";
  630. memberRef.mDeclaringType = field->mDeclaringType;
  631. if (field->mFieldDeclaration != NULL)
  632. {
  633. memberRef.mNameNode = field->mFieldDeclaration->mNameNode;
  634. memberRef.mIsOverride = field->mFieldDeclaration->mNewSpecifier != NULL;
  635. }
  636. memberList.push_back(memberRef);
  637. }
  638. checkType = checkType->mBaseType;
  639. }
  640. Dictionary<String, MemberRef> memberMap;
  641. memberMap.Reserve(memberList.size());
  642. for (int i = (int)memberList.size() - 1; i >= 0; i--)
  643. {
  644. MemberRef& memberRef = memberList[i];
  645. if (memberRef.mName.empty())
  646. continue;
  647. if ((memberRef.mTypeInst == typeInst) && (!memberRef.mIsOverride))
  648. {
  649. MemberRef* prevMemberRef = NULL;
  650. if (memberMap.TryGetValue(memberRef.mName, &prevMemberRef))
  651. {
  652. //auto& prevMemberRef = itr->second;
  653. MemberRef* firstMemberRef = &memberRef;
  654. MemberRef* secondMemberRef = prevMemberRef;
  655. bool showPrevious = false;
  656. BfError* error = NULL;
  657. if (prevMemberRef->mTypeInst != typeInst)
  658. {
  659. if ((prevMemberRef->mProtection != BfProtection_Private) && (memberRef.mNameNode != NULL))
  660. {
  661. 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);
  662. showPrevious = true;
  663. }
  664. }
  665. else
  666. {
  667. if (ShouldAllowMultipleDefinitions(typeInst, firstMemberRef->mDeclaringType, secondMemberRef->mDeclaringType))
  668. {
  669. if (firstMemberRef->mMemberDef != NULL)
  670. {
  671. firstMemberRef->mMemberDef->mHasMultiDefs = true;
  672. secondMemberRef->mMemberDef->mHasMultiDefs = true;
  673. }
  674. continue;
  675. }
  676. bool wantsSwap = false;
  677. if ((secondMemberRef->mNameNode != NULL) && (firstMemberRef->mNameNode != NULL) &&
  678. (secondMemberRef->mNameNode->GetSourceData() == firstMemberRef->mNameNode->GetSourceData()) &&
  679. (secondMemberRef->mNameNode->GetSrcStart() < firstMemberRef->mNameNode->GetSrcStart()))
  680. {
  681. wantsSwap = true;
  682. }
  683. if (secondMemberRef->mDeclaringType->IsExtension() != firstMemberRef->mDeclaringType->IsExtension())
  684. {
  685. wantsSwap = firstMemberRef->mDeclaringType->IsExtension();
  686. }
  687. if (wantsSwap)
  688. {
  689. std::swap(firstMemberRef, secondMemberRef);
  690. }
  691. if (typeInst->mTypeDef->mIsCombinedPartial)
  692. {
  693. if ((firstMemberRef->mKindName == "property") && (secondMemberRef->mKindName == "property"))
  694. {
  695. auto firstPropertyDef = (BfPropertyDef*)firstMemberRef->mMemberDef;
  696. auto secondPropertyDef = (BfPropertyDef*)secondMemberRef->mMemberDef;
  697. if (auto secondPropertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(secondPropertyDef->mFieldDeclaration))
  698. {
  699. if ((secondPropertyDeclaration->mVirtualSpecifier != NULL) && (secondPropertyDeclaration->mVirtualSpecifier->mToken == BfToken_Override))
  700. continue;
  701. }
  702. }
  703. }
  704. if (secondMemberRef->mNameNode != NULL)
  705. error = Fail(StrFormat("A %s named '%s' has already been declared.", secondMemberRef->mKindName.c_str(), memberRef.mName.c_str()), secondMemberRef->mNameNode, true);
  706. showPrevious = true;
  707. typeInst->mHasDeclError = true;
  708. }
  709. if ((secondMemberRef->mNameNode != NULL) && (error != NULL))
  710. mCompiler->mPassInstance->MoreInfo("Previous declaration", firstMemberRef->mNameNode);
  711. }
  712. }
  713. memberMap.TryAdd(memberRef.mName, memberRef);
  714. }
  715. }
  716. void BfModule::TypeFailed(BfTypeInstance* typeInstance)
  717. {
  718. BfLogSysM("TypeFailed: %p\n", typeInstance);
  719. typeInstance->mTypeFailed = true;
  720. // Punt on field types - just substitute 'var' where we have NULLs
  721. for (auto& fieldInstance : typeInstance->mFieldInstances)
  722. {
  723. if ((fieldInstance.mResolvedType == NULL) || (fieldInstance.mResolvedType->IsNull()))
  724. {
  725. if (fieldInstance.mDataIdx >= 0)
  726. fieldInstance.mResolvedType = GetPrimitiveType(BfTypeCode_Var);
  727. }
  728. if (fieldInstance.mOwner == NULL)
  729. fieldInstance.mOwner = typeInstance;
  730. }
  731. if (typeInstance->mAlign == -1)
  732. typeInstance->mAlign = 1;
  733. if (typeInstance->mSize == -1)
  734. typeInstance->mSize = 1;
  735. mContext->mFailTypes.Add(typeInstance);
  736. mHadBuildError = true;
  737. }
  738. bool BfModule::CheckCircularDataError()
  739. {
  740. bool hadError = false;
  741. int checkIdx = 0;
  742. auto checkTypeState = mContext->mCurTypeState;
  743. bool isPreBaseCheck = checkTypeState->mPopulateType == BfPopulateType_Declaration;
  744. while (true)
  745. {
  746. if (checkTypeState == NULL)
  747. return hadError;
  748. if (checkTypeState->mResolveKind == BfTypeState::ResolveKind_UnionInnerType)
  749. {
  750. checkTypeState = checkTypeState->mPrevState;
  751. continue;
  752. }
  753. if (isPreBaseCheck)
  754. {
  755. if (checkTypeState->mPopulateType != BfPopulateType_Declaration)
  756. return hadError;
  757. }
  758. else
  759. {
  760. if (checkTypeState->mPopulateType == BfPopulateType_Declaration)
  761. return hadError;
  762. if ((checkIdx > 0) && (checkTypeState->mCurBaseTypeRef == NULL) && (checkTypeState->mCurAttributeTypeRef == NULL) && (checkTypeState->mCurFieldDef == NULL))
  763. return hadError;
  764. }
  765. if ((checkTypeState->mTypeInstance == mCurTypeInstance) && (checkIdx > 0))
  766. break;
  767. checkTypeState = checkTypeState->mPrevState;
  768. checkIdx++;
  769. }
  770. checkTypeState = mContext->mCurTypeState->mPrevState;
  771. while (true)
  772. {
  773. if (checkTypeState == NULL)
  774. return hadError;
  775. if (checkTypeState->mResolveKind == BfTypeState::ResolveKind_UnionInnerType)
  776. {
  777. // Skip over this to actual data references
  778. checkTypeState = checkTypeState->mPrevState;
  779. continue;
  780. }
  781. if ((checkTypeState->mCurAttributeTypeRef == NULL) && (checkTypeState->mCurBaseTypeRef == NULL) && (checkTypeState->mCurFieldDef == NULL) )
  782. return hadError;
  783. // We only get one chance to fire off these errors, they can't be ignored.
  784. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  785. hadError = true;
  786. if (checkTypeState->mCurAttributeTypeRef != NULL)
  787. {
  788. Fail(StrFormat("Attribute type '%s' causes a data cycle", BfTypeUtils::TypeToString(checkTypeState->mCurAttributeTypeRef).c_str()), checkTypeState->mCurAttributeTypeRef, true);
  789. }
  790. else if (checkTypeState->mCurBaseTypeRef != NULL)
  791. {
  792. Fail(StrFormat("Base type '%s' causes a data cycle", BfTypeUtils::TypeToString(checkTypeState->mCurBaseTypeRef).c_str()), checkTypeState->mCurBaseTypeRef, true);
  793. }
  794. else if (checkTypeState->mCurFieldDef->mFieldDeclaration != NULL)
  795. {
  796. Fail(StrFormat("Field '%s.%s' causes a data cycle", TypeToString(checkTypeState->mTypeInstance).c_str(), checkTypeState->mCurFieldDef->mName.c_str()),
  797. checkTypeState->mCurFieldDef->mFieldDeclaration->mTypeRef, true);
  798. }
  799. else
  800. {
  801. Fail(StrFormat("Field '%s.%s' causes a data cycle", TypeToString(checkTypeState->mTypeInstance).c_str(), checkTypeState->mCurFieldDef->mName.c_str()));
  802. }
  803. auto module = GetModuleFor(checkTypeState->mTypeInstance);
  804. if (module != NULL)
  805. module->TypeFailed(checkTypeState->mTypeInstance);
  806. else
  807. checkTypeState->mTypeInstance->mTypeFailed = true;
  808. checkTypeState = checkTypeState->mPrevState;
  809. }
  810. }
  811. void BfModule::PopulateType(BfType* resolvedTypeRef, BfPopulateType populateType)
  812. {
  813. if ((populateType == BfPopulateType_Declaration) && (resolvedTypeRef->mDefineState >= BfTypeDefineState_Declared))
  814. return;
  815. // Are we "demanding" to reify a type that is currently resolve-only?
  816. if ((mIsReified) && (populateType >= BfPopulateType_Declaration))
  817. {
  818. if (resolvedTypeRef->IsTypeInstance())
  819. {
  820. auto typeModule = resolvedTypeRef->GetModule();
  821. if ((typeModule != NULL) && (typeModule->mIsSpecialModule))
  822. {
  823. auto typeInst = resolvedTypeRef->ToTypeInstance();
  824. if (!typeInst->mIsReified)
  825. {
  826. BfLogSysM("Reifying type %p in scratch module in PopulateType\n", resolvedTypeRef);
  827. // It's important for unspecialized types to be in the correct module --
  828. // when we process their methods, new types will be determined as
  829. // resolve-only or reified based on the module the unresolved type is in
  830. BF_ASSERT(typeInst->mModule == mContext->mUnreifiedModule);
  831. typeInst->mIsReified = true;
  832. typeInst->mModule = mContext->mScratchModule;
  833. // Why did we need to do this at all? Why is just marking the type as reified not enough?
  834. // This causes issues where we may delete a method instance that is currently being used as the generic bindings for
  835. // a method of a specialized generic type
  836. // if (typeInst->IsOnDemand())
  837. // {
  838. // RebuildMethods(typeInst);
  839. // }
  840. // else
  841. // mContext->RebuildType(typeInst, false, false);
  842. }
  843. }
  844. else
  845. {
  846. if ((typeModule != NULL) && (!typeModule->mIsReified) && (!typeModule->mReifyQueued))
  847. {
  848. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  849. BfLogSysM("Queued reification of type %p in module %p in PopulateType\n", resolvedTypeRef, typeModule);
  850. BF_ASSERT((typeModule != mContext->mUnreifiedModule) && (typeModule != mContext->mScratchModule));
  851. BF_ASSERT(!typeModule->mIsSpecialModule);
  852. // This caused issues - we may need to reify a type and then request a method
  853. typeModule->mReifyQueued = true;
  854. mContext->mReifyModuleWorkList.Add(typeModule);
  855. //typeModule->ReifyModule();
  856. }
  857. }
  858. }
  859. }
  860. if (!resolvedTypeRef->IsIncomplete())
  861. return;
  862. if (populateType <= BfPopulateType_TypeDef)
  863. return;
  864. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  865. CheckInjectNewRevision(typeInstance);
  866. BF_ASSERT((resolvedTypeRef->mRebuildFlags & (BfTypeRebuildFlag_Deleted | BfTypeRebuildFlag_DeleteQueued)) == 0);
  867. /*BfTypeRebuildFlags allowedFlags = (BfTypeRebuildFlags)(BfTypeRebuildFlag_AddedToWorkList | BfTypeRebuildFlag_AwaitingReference | BfTypeRebuildFlag_UnderlyingTypeDeferred);
  868. if ((resolvedTypeRef->mRebuildFlags & ~allowedFlags) != 0)
  869. {
  870. // BfContext::UpdateAfterDeletingTypes should clear out all flags except for the Deleted flag
  871. // If this type was deleted then we should never be able to reach PopulateType here.
  872. // This may happen if dependent types were not properly rebuilt when a used type
  873. // was deleted.
  874. auto hadFlags = resolvedTypeRef->mRebuildFlags;
  875. BF_ASSERT((resolvedTypeRef->mRebuildFlags & ~allowedFlags) == 0);
  876. resolvedTypeRef->mRebuildFlags = (BfTypeRebuildFlags)(resolvedTypeRef->mRebuildFlags & ~allowedFlags);
  877. }*/
  878. bool isNew = resolvedTypeRef->mDefineState == BfTypeDefineState_Undefined;
  879. if (isNew)
  880. {
  881. BP_ZONE("BfModule::PopulateType");
  882. if (resolvedTypeRef->mTypeId == -1)
  883. {
  884. mCompiler->mTypeInitCount++;
  885. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  886. if (!mCompiler->mTypeIdFreeList.IsEmpty())
  887. {
  888. resolvedTypeRef->mTypeId = mCompiler->mTypeIdFreeList.back();
  889. mCompiler->mTypeIdFreeList.pop_back();
  890. }
  891. else
  892. resolvedTypeRef->mTypeId = mCompiler->mCurTypeId++;
  893. while (resolvedTypeRef->mTypeId >= (int)mContext->mTypes.size())
  894. mContext->mTypes.Add(NULL);
  895. mContext->mTypes[resolvedTypeRef->mTypeId] = resolvedTypeRef;
  896. if (typeInstance != NULL)
  897. {
  898. typeInstance->mSignatureRevision = mCompiler->mRevision;
  899. typeInstance->mLastNonGenericUsedRevision = mCompiler->mRevision;
  900. }
  901. }
  902. 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);
  903. BF_ASSERT(!resolvedTypeRef->IsDeleting());
  904. }
  905. if (resolvedTypeRef->IsRef())
  906. {
  907. BfRefType* refType = (BfRefType*)resolvedTypeRef;
  908. if (refType->mElementType->IsValueType())
  909. {
  910. PopulateType(refType->mElementType, populateType);
  911. resolvedTypeRef->mDefineState = refType->mElementType->mDefineState;
  912. }
  913. else
  914. {
  915. PopulateType(refType->mElementType, BfPopulateType_Identity);
  916. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  917. }
  918. refType->mSize = refType->mAlign = mSystem->mPtrSize;
  919. return;
  920. }
  921. if (resolvedTypeRef->IsTypeAlias())
  922. {
  923. auto typeAlias = (BfTypeInstance*)resolvedTypeRef;
  924. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  925. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  926. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  927. BF_ASSERT(mCurMethodInstance == NULL);
  928. auto typeDef = typeAlias->mTypeDef;
  929. auto typeAliasDecl = (BfTypeAliasDeclaration*)typeDef->mTypeDeclaration;
  930. BfType* aliasToType = NULL;
  931. resolvedTypeRef->mDefineState = BfTypeDefineState_ResolvingBaseType;
  932. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  933. typeState.mPopulateType = populateType;
  934. typeState.mCurBaseTypeRef = typeAliasDecl->mAliasToType;
  935. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  936. if (!CheckCircularDataError())
  937. {
  938. if (typeAliasDecl->mAliasToType != NULL)
  939. aliasToType = ResolveTypeRef(typeAliasDecl->mAliasToType, BfPopulateType_IdentityNoRemapAlias);
  940. }
  941. if (aliasToType != NULL)
  942. {
  943. AddDependency(aliasToType, typeAlias, BfDependencyMap::DependencyFlag_DerivedFrom);
  944. }
  945. else
  946. mContext->mFailTypes.Add(typeAlias);
  947. if (typeAlias->mTypeFailed)
  948. aliasToType = NULL;
  949. ((BfTypeAliasType*)resolvedTypeRef)->mAliasToType = aliasToType;
  950. if (aliasToType != NULL)
  951. {
  952. resolvedTypeRef->mSize = aliasToType->mSize;
  953. resolvedTypeRef->mAlign = aliasToType->mAlign;
  954. if (auto aliasToTypeInst = aliasToType->ToTypeInstance())
  955. {
  956. typeAlias->mInstSize = aliasToTypeInst->mInstSize;
  957. typeAlias->mInstAlign = aliasToTypeInst->mInstAlign;
  958. }
  959. else
  960. {
  961. typeAlias->mInstSize = aliasToType->mSize;
  962. typeAlias->mInstAlign = aliasToType->mAlign;
  963. }
  964. }
  965. else
  966. {
  967. resolvedTypeRef->mSize = 0;
  968. resolvedTypeRef->mAlign = 1;
  969. typeAlias->mInstSize = 0;
  970. typeAlias->mInstAlign = 1;
  971. }
  972. resolvedTypeRef->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  973. resolvedTypeRef->mRebuildFlags = BfTypeRebuildFlag_None;
  974. if ((typeInstance->mCustomAttributes == NULL) && (typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mAttributes != NULL))
  975. typeInstance->mCustomAttributes = GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, BfAttributeTargets_Alias);
  976. // Fall through so generic params are populated in DoPopulateType
  977. }
  978. if (resolvedTypeRef->IsSizedArray())
  979. {
  980. resolvedTypeRef->mRevision = mRevision;
  981. bool typeFailed = false;
  982. BfSizedArrayType* arrayType = (BfSizedArrayType*)resolvedTypeRef;
  983. auto elementType = arrayType->mElementType;
  984. if (elementType->IsValueType())
  985. {
  986. resolvedTypeRef->mDefineState = BfTypeDefineState_ResolvingBaseType;
  987. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  988. typeState.mPopulateType = populateType;
  989. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  990. if (!CheckCircularDataError())
  991. {
  992. PopulateType(arrayType->mElementType, BfPopulateType_Data);
  993. }
  994. else
  995. {
  996. typeFailed = true;
  997. PopulateType(arrayType->mElementType, BfPopulateType_Identity);
  998. }
  999. resolvedTypeRef->mDefineState = arrayType->mElementType->mDefineState;
  1000. AddDependency(elementType, resolvedTypeRef, BfDependencyMap::DependencyFlag_ValueTypeMemberData);
  1001. }
  1002. else
  1003. {
  1004. PopulateType(arrayType->mElementType, BfPopulateType_Identity);
  1005. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1006. AddDependency(elementType, resolvedTypeRef, BfDependencyMap::DependencyFlag_PtrMemberData);
  1007. }
  1008. if (arrayType->mElementCount > 0)
  1009. {
  1010. arrayType->mSize = (arrayType->mElementType->GetStride() * ((int)arrayType->mElementCount - 1)) + arrayType->mElementType->mSize;
  1011. arrayType->mAlign = std::max((int32)arrayType->mElementType->mAlign, 1);
  1012. }
  1013. else if (arrayType->mElementCount < 0)
  1014. {
  1015. // Unknown size, don't assume it's valueless
  1016. arrayType->mSize = 1;
  1017. arrayType->mAlign = 1;
  1018. }
  1019. else
  1020. {
  1021. arrayType->mSize = 0;
  1022. arrayType->mAlign = 1;
  1023. }
  1024. if (!typeFailed)
  1025. arrayType->mWantsGCMarking = elementType->WantsGCMarking();
  1026. resolvedTypeRef->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  1027. resolvedTypeRef->mRebuildFlags = BfTypeRebuildFlag_None;
  1028. bool isValueless = arrayType->IsValuelessType();
  1029. return;
  1030. }
  1031. if (isNew)
  1032. {
  1033. BfTypeDef* typeDef = NULL;
  1034. if (typeInstance != NULL)
  1035. {
  1036. if ((populateType == BfPopulateType_Data) && (typeInstance->mNeedsMethodProcessing))
  1037. return;
  1038. typeDef = typeInstance->mTypeDef;
  1039. }
  1040. if (resolvedTypeRef->IsMethodRef())
  1041. return;
  1042. if (resolvedTypeRef->IsPointer())
  1043. {
  1044. BfPointerType* pointerType = (BfPointerType*)resolvedTypeRef;
  1045. if (pointerType->mElementType->IsIncomplete())
  1046. PopulateType(pointerType->mElementType, BfPopulateType_Declaration);
  1047. pointerType->mSize = pointerType->mAlign = mSystem->mPtrSize;
  1048. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1049. return;
  1050. }
  1051. if (resolvedTypeRef->IsGenericParam())
  1052. {
  1053. BfGenericParamType* genericParamType = (BfGenericParamType*)resolvedTypeRef;
  1054. PopulateType(mContext->mBfObjectType);
  1055. genericParamType->mSize = mContext->mBfObjectType->mSize;
  1056. genericParamType->mAlign = mContext->mBfObjectType->mAlign;
  1057. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1058. return;
  1059. }
  1060. if (resolvedTypeRef->IsModifiedTypeType())
  1061. {
  1062. BfModifiedTypeType* retTypeType = (BfModifiedTypeType*)resolvedTypeRef;
  1063. BF_ASSERT(retTypeType->mElementType->IsGenericParam());
  1064. resolvedTypeRef->mSize = mContext->mBfObjectType->mSize;
  1065. resolvedTypeRef->mAlign = mContext->mBfObjectType->mAlign;
  1066. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1067. return;
  1068. }
  1069. if (resolvedTypeRef->IsConcreteInterfaceType())
  1070. {
  1071. BfConcreteInterfaceType* concreteInterfaceType = (BfConcreteInterfaceType*)resolvedTypeRef;
  1072. BF_ASSERT(concreteInterfaceType->mInterface->IsInterface());
  1073. resolvedTypeRef->mSize = concreteInterfaceType->mInterface->mSize;
  1074. resolvedTypeRef->mAlign = concreteInterfaceType->mInterface->mAlign;
  1075. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1076. return;
  1077. }
  1078. if (resolvedTypeRef->IsConstExprValue())
  1079. {
  1080. resolvedTypeRef->mSize = 0;
  1081. resolvedTypeRef->mAlign = 0;
  1082. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1083. return;
  1084. }
  1085. // The autocomplete pass doesn't need to do the method processing, allow type to be (partially) incomplete
  1086. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  1087. (typeInstance != NULL) && (typeInstance->mNeedsMethodProcessing) && (!typeInstance->IsDelegate()))
  1088. return;
  1089. BfPrimitiveType* primitiveType = NULL;
  1090. if (typeInstance == NULL)
  1091. {
  1092. BF_ASSERT(resolvedTypeRef->IsPrimitiveType());
  1093. primitiveType = (BfPrimitiveType*)resolvedTypeRef;
  1094. typeDef = primitiveType->mTypeDef;
  1095. }
  1096. #define PRIMITIVE_TYPE(name, llvmType, size, dType) \
  1097. primitiveType->mSize = primitiveType->mAlign = size; \
  1098. primitiveType->mDefineState = BfTypeDefineState_Defined;
  1099. switch (typeDef->mTypeCode)
  1100. {
  1101. case BfTypeCode_None:
  1102. primitiveType->mSize = primitiveType->mAlign = 0;
  1103. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1104. return;
  1105. case BfTypeCode_Self:
  1106. case BfTypeCode_Dot:
  1107. case BfTypeCode_Var:
  1108. case BfTypeCode_Let:
  1109. {
  1110. auto objType = mContext->mBfObjectType;
  1111. primitiveType->mSize = objType->mSize;
  1112. primitiveType->mAlign = objType->mAlign;
  1113. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1114. }
  1115. return;
  1116. case BfTypeCode_NullPtr:
  1117. primitiveType->mSize = primitiveType->mAlign = mSystem->mPtrSize;
  1118. primitiveType->mDefineState = BfTypeDefineState_Defined;
  1119. return;
  1120. case BfTypeCode_Boolean:
  1121. PRIMITIVE_TYPE("bool", Int1, 1, DW_ATE_boolean);
  1122. return;
  1123. case BfTypeCode_Int8:
  1124. PRIMITIVE_TYPE("sbyte", Int8, 1, DW_ATE_signed);
  1125. return;
  1126. case BfTypeCode_UInt8:
  1127. PRIMITIVE_TYPE("byte", Int8, 1, DW_ATE_unsigned);
  1128. return;
  1129. case BfTypeCode_Int16:
  1130. PRIMITIVE_TYPE("short", Int16, 2, DW_ATE_signed);
  1131. return;
  1132. case BfTypeCode_UInt16:
  1133. PRIMITIVE_TYPE("ushort", Int16, 2, DW_ATE_unsigned);
  1134. return;
  1135. case BfTypeCode_Int32:
  1136. PRIMITIVE_TYPE("int", Int32, 4, DW_ATE_signed);
  1137. return;
  1138. case BfTypeCode_UInt32:
  1139. PRIMITIVE_TYPE("uint", Int32, 4, DW_ATE_unsigned);
  1140. return;
  1141. case BfTypeCode_Int64:
  1142. PRIMITIVE_TYPE("long", Int64, 8, DW_ATE_signed);
  1143. return;
  1144. case BfTypeCode_UInt64:
  1145. PRIMITIVE_TYPE("ulong", Int64, 8, DW_ATE_unsigned);
  1146. return;
  1147. case BfTypeCode_IntPtr:
  1148. if (mSystem->mPtrSize == 4)
  1149. {
  1150. PRIMITIVE_TYPE("intptr", Int32, 4, DW_ATE_signed);
  1151. }
  1152. else
  1153. {
  1154. PRIMITIVE_TYPE("intptr", Int64, 8, DW_ATE_signed);
  1155. }
  1156. return;
  1157. case BfTypeCode_UIntPtr:
  1158. if (mSystem->mPtrSize == 4)
  1159. {
  1160. PRIMITIVE_TYPE("uintptr", Int32, 4, DW_ATE_unsigned);
  1161. }
  1162. else
  1163. {
  1164. PRIMITIVE_TYPE("uintptr", Int64, 8, DW_ATE_unsigned);
  1165. }
  1166. return;
  1167. case BfTypeCode_IntUnknown:
  1168. case BfTypeCode_UIntUnknown:
  1169. return;
  1170. case BfTypeCode_Char8:
  1171. PRIMITIVE_TYPE("char8", Int8, 1, DW_ATE_unsigned_char);
  1172. return;
  1173. case BfTypeCode_Char16:
  1174. PRIMITIVE_TYPE("char16", Int16, 2, DW_ATE_unsigned_char);
  1175. return;
  1176. case BfTypeCode_Char32:
  1177. PRIMITIVE_TYPE("char32", Int32, 4, DW_ATE_unsigned_char);
  1178. return;
  1179. case BfTypeCode_Float:
  1180. PRIMITIVE_TYPE("float", Float, 4, DW_ATE_float);
  1181. return;
  1182. case BfTypeCode_Double:
  1183. PRIMITIVE_TYPE("double", Double, 8, DW_ATE_float);
  1184. return;
  1185. case BfTypeCode_Object:
  1186. case BfTypeCode_Struct:
  1187. case BfTypeCode_Interface:
  1188. case BfTypeCode_Enum:
  1189. case BfTypeCode_TypeAlias:
  1190. // Implemented below
  1191. break;
  1192. case BfTypeCode_Extension:
  1193. // This can only happen if we didn't actually find the type the extension referred to
  1194. break;
  1195. default:
  1196. //NotImpl(resolvedTypeRef->mTypeRef);
  1197. BFMODULE_FATAL(this, "Invalid type");
  1198. return;
  1199. }
  1200. //////////////////////////////////////////////////////////////////////////
  1201. BF_ASSERT(typeInstance != NULL);
  1202. if (!typeInstance->IsArray())
  1203. {
  1204. BF_ASSERT(typeInstance->mTypeDef != mContext->mCompiler->mArray1TypeDef);
  1205. }
  1206. if (mContext->mBfObjectType == NULL)
  1207. {
  1208. if (typeInstance->mTypeDef == mCompiler->mBfObjectTypeDef)
  1209. mContext->mBfObjectType = typeInstance;
  1210. else
  1211. ResolveTypeDef(mCompiler->mBfObjectTypeDef);
  1212. }
  1213. if (typeInstance->mModule == NULL)
  1214. {
  1215. // Create a module for this type
  1216. mContext->HandleTypeWorkItem(resolvedTypeRef);
  1217. }
  1218. }
  1219. if (typeInstance == NULL)
  1220. return;
  1221. if (typeInstance->mModule == NULL)
  1222. {
  1223. BF_ASSERT(typeInstance->mTypeFailed);
  1224. return;
  1225. }
  1226. typeInstance->mModule->DoPopulateType(typeInstance, populateType);
  1227. }
  1228. BfTypeOptions* BfModule::GetTypeOptions(BfTypeDef* typeDef)
  1229. {
  1230. if (mContext->mSystem->mTypeOptions.size() == 0)
  1231. {
  1232. return NULL;
  1233. }
  1234. Array<int> matchedIndices;
  1235. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  1236. {
  1237. auto customAttributes = typeDef->mTypeDeclaration->mAttributes;
  1238. while (customAttributes != NULL)
  1239. {
  1240. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  1241. {
  1242. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  1243. auto typeRef = customAttributes->mAttributeTypeRef;
  1244. // StringT<128> attrName;
  1245. // for (auto& customAttrs : customAttributes->mAttributeTypeRef)
  1246. // {
  1247. // attrName.Clear();
  1248. // customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  1249. // Array<int>* arrPtr;
  1250. // if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  1251. // {
  1252. // for (auto optionsIdx : *arrPtr)
  1253. // {
  1254. // matchedIndices.Add(optionsIdx);
  1255. // }
  1256. // }
  1257. // }
  1258. }
  1259. customAttributes = customAttributes->mNextAttribute;
  1260. }
  1261. }
  1262. int typeOptionsCount = (int)mContext->mSystem->mTypeOptions.size();
  1263. auto _CheckTypeName = [&](const StringImpl& typeName)
  1264. {
  1265. for (int optionIdx = 0; optionIdx < (int)mContext->mSystem->mTypeOptions.size(); optionIdx++)
  1266. {
  1267. auto& typeOptions = mContext->mSystem->mTypeOptions[optionIdx];
  1268. bool matched = false;
  1269. for (auto& filter : typeOptions.mTypeFilters)
  1270. {
  1271. int filterIdx = 0;
  1272. int typeNameIdx = 0;
  1273. const char* filterPtr = filter.c_str();
  1274. const char* namePtr = typeName.c_str();
  1275. char prevFilterC = 0;
  1276. while (true)
  1277. {
  1278. char filterC;
  1279. while (true)
  1280. {
  1281. filterC = *(filterPtr++);
  1282. if (filterC != ' ')
  1283. break;
  1284. }
  1285. char nameC;
  1286. while (true)
  1287. {
  1288. nameC = *(namePtr++);
  1289. if (nameC != ' ')
  1290. break;
  1291. }
  1292. if ((filterC == 0) || (nameC == 0))
  1293. {
  1294. matched = (filterC == 0) && (nameC == 0);
  1295. break;
  1296. }
  1297. bool doWildcard = false;
  1298. if (nameC != filterC)
  1299. {
  1300. if (filterC == '*')
  1301. doWildcard = true;
  1302. else if (((filterC == ',') || (filterC == '>')) &&
  1303. ((prevFilterC == '<') || (prevFilterC == ',')))
  1304. {
  1305. doWildcard = true;
  1306. filterPtr--;
  1307. }
  1308. if (!doWildcard)
  1309. {
  1310. matched = false;
  1311. break;
  1312. }
  1313. }
  1314. if (doWildcard)
  1315. {
  1316. int openDepth = 0;
  1317. const char* startNamePtr = namePtr;
  1318. while (true)
  1319. {
  1320. nameC = *(namePtr++);
  1321. if (nameC == 0)
  1322. {
  1323. namePtr--;
  1324. if (openDepth != 0)
  1325. matched = false;
  1326. break;
  1327. }
  1328. if ((nameC == '>') && (openDepth == 0))
  1329. {
  1330. namePtr--;
  1331. break;
  1332. }
  1333. if (nameC == '<')
  1334. openDepth++;
  1335. else if (nameC == '>')
  1336. openDepth--;
  1337. else if ((nameC == ',') && (openDepth == 0))
  1338. {
  1339. namePtr--;
  1340. break;
  1341. }
  1342. }
  1343. if (!matched)
  1344. break;
  1345. }
  1346. prevFilterC = filterC;
  1347. }
  1348. }
  1349. if (matched)
  1350. matchedIndices.push_back(optionIdx);
  1351. }
  1352. };
  1353. // if (typeInstance->IsTypedPrimitive())
  1354. // {
  1355. // auto underlyingType = typeInstance->GetUnderlyingType();
  1356. // if (underlyingType != NULL)
  1357. // {
  1358. // String typeName = TypeToString(underlyingType);
  1359. // _CheckTypeName(typeName);
  1360. // }
  1361. // else
  1362. // {
  1363. // // Can this only happen for functions that are being extended?
  1364. // }
  1365. // }
  1366. //
  1367. // if ((!typeInstance->IsBoxed()) && (typeInstance->mTypeDef == mCompiler->mPointerTTypeDef))
  1368. // {
  1369. // BF_ASSERT(typeInstance->IsGenericTypeInstance());
  1370. // auto innerType = typeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  1371. // auto ptrType = CreatePointerType(innerType);
  1372. // String typeName = TypeToString(ptrType);
  1373. // _CheckTypeName(typeName);
  1374. // }
  1375. String typeName = BfTypeUtils::TypeToString(typeDef);
  1376. _CheckTypeName(typeName);
  1377. int matchedIdx = -1;
  1378. if (matchedIndices.size() == 1)
  1379. {
  1380. matchedIdx = matchedIndices[0];
  1381. }
  1382. else if (matchedIndices.size() > 1)
  1383. {
  1384. // Try to find a merged typeoptions with these indices
  1385. for (int mergedIdx = 0; mergedIdx < (int)mContext->mSystem->mMergedTypeOptions.size(); mergedIdx++)
  1386. {
  1387. auto& typeOptions = mContext->mSystem->mMergedTypeOptions[mergedIdx];
  1388. if (typeOptions.mMatchedIndices == matchedIndices)
  1389. {
  1390. matchedIdx = typeOptionsCount + mergedIdx;
  1391. break;
  1392. }
  1393. }
  1394. // Otherwise make one...
  1395. if (matchedIdx == -1)
  1396. {
  1397. auto& first = mContext->mSystem->mTypeOptions[matchedIndices[0]];
  1398. BfTypeOptions mergedTypeOptions;
  1399. mergedTypeOptions.mSIMDSetting = first.mSIMDSetting;
  1400. mergedTypeOptions.mOptimizationLevel = first.mOptimizationLevel;
  1401. mergedTypeOptions.mEmitDebugInfo = first.mEmitDebugInfo;
  1402. mergedTypeOptions.mAndFlags = first.mAndFlags;
  1403. mergedTypeOptions.mOrFlags = first.mOrFlags;
  1404. mergedTypeOptions.mAllocStackTraceDepth = first.mAllocStackTraceDepth;
  1405. mergedTypeOptions.mReflectMethodFilters = first.mReflectMethodFilters;
  1406. mergedTypeOptions.mReflectMethodAttributeFilters = first.mReflectMethodAttributeFilters;
  1407. mergedTypeOptions.mMatchedIndices = matchedIndices;
  1408. for (int idx = 1; idx < (int)matchedIndices.size(); idx++)
  1409. {
  1410. auto& typeOptions = mContext->mSystem->mTypeOptions[matchedIndices[idx]];
  1411. if (typeOptions.mSIMDSetting != -1)
  1412. mergedTypeOptions.mSIMDSetting = typeOptions.mSIMDSetting;
  1413. if (typeOptions.mOptimizationLevel != -1)
  1414. mergedTypeOptions.mOptimizationLevel = typeOptions.mOptimizationLevel;
  1415. if (typeOptions.mEmitDebugInfo != -1)
  1416. mergedTypeOptions.mEmitDebugInfo = typeOptions.mEmitDebugInfo;
  1417. if (typeOptions.mReflectMethodFilters.IsEmpty())
  1418. mergedTypeOptions.mOrFlags = (BfOptionFlags)(mergedTypeOptions.mOrFlags | typeOptions.mOrFlags);
  1419. mergedTypeOptions.mAndFlags = (BfOptionFlags)(mergedTypeOptions.mAndFlags | typeOptions.mOrFlags);
  1420. mergedTypeOptions.mAndFlags = (BfOptionFlags)(mergedTypeOptions.mAndFlags & typeOptions.mAndFlags);
  1421. mergedTypeOptions.mOrFlags = (BfOptionFlags)(mergedTypeOptions.mOrFlags & typeOptions.mAndFlags);
  1422. if (mergedTypeOptions.HasReflectMethodFilters())
  1423. {
  1424. // If merging filter has non-default method flags but no filter then we need to append it as a filtered modification
  1425. if ((!typeOptions.HasReflectMethodFilters()) &&
  1426. (((typeOptions.mAndFlags & BfOptionFlags_Reflect_MethodMask) != BfOptionFlags_Reflect_MethodMask) ||
  1427. ((typeOptions.mOrFlags & BfOptionFlags_Reflect_MethodMask) != 0)))
  1428. {
  1429. mergedTypeOptions.mReflectMethodFilters.Add({"*", typeOptions.mAndFlags, typeOptions.mOrFlags});
  1430. }
  1431. mergedTypeOptions.mAndFlags = (BfOptionFlags)(mergedTypeOptions.mAndFlags | BfOptionFlags_Reflect_MethodMask);
  1432. mergedTypeOptions.mOrFlags = (BfOptionFlags)(mergedTypeOptions.mOrFlags & ~BfOptionFlags_Reflect_MethodMask);
  1433. }
  1434. if (typeOptions.mAllocStackTraceDepth != -1)
  1435. mergedTypeOptions.mAllocStackTraceDepth = typeOptions.mAllocStackTraceDepth;
  1436. for (auto filter : typeOptions.mReflectMethodFilters)
  1437. mergedTypeOptions.mReflectMethodFilters.Add(filter);
  1438. for (auto filter : typeOptions.mReflectMethodAttributeFilters)
  1439. mergedTypeOptions.mReflectMethodAttributeFilters.Add(filter);
  1440. }
  1441. matchedIdx = typeOptionsCount + (int)mContext->mSystem->mMergedTypeOptions.size();
  1442. mContext->mSystem->mMergedTypeOptions.push_back(mergedTypeOptions);
  1443. }
  1444. }
  1445. return mSystem->GetTypeOptions( matchedIdx);
  1446. }
  1447. bool BfModule::ApplyTypeOptionMethodFilters(bool includeMethod, BfMethodDef* methodDef, BfTypeOptions* typeOptions)
  1448. {
  1449. BfOptionFlags findFlag = BfOptionFlags_None;
  1450. if (methodDef->mMethodType == BfMethodType_Ctor)
  1451. findFlag = BfOptionFlags_ReflectConstructors;
  1452. else if (methodDef->mIsStatic)
  1453. findFlag = BfOptionFlags_ReflectStaticMethods;
  1454. else
  1455. findFlag = BfOptionFlags_ReflectNonStaticMethods;
  1456. if ((typeOptions->mAndFlags & findFlag) == 0)
  1457. includeMethod = false;
  1458. if ((typeOptions->mOrFlags & findFlag) != 0)
  1459. includeMethod = true;
  1460. if (!typeOptions->mReflectMethodFilters.IsEmpty())
  1461. {
  1462. for (auto& filter : typeOptions->mReflectMethodFilters)
  1463. {
  1464. if (BfCheckWildcard(filter.mFilter, methodDef->mName))
  1465. {
  1466. if ((filter.mAndFlags & findFlag) == 0)
  1467. includeMethod = false;
  1468. if ((filter.mAndFlags | findFlag) != 0)
  1469. includeMethod = true;
  1470. }
  1471. }
  1472. }
  1473. return includeMethod;
  1474. }
  1475. int BfModule::GenerateTypeOptions(BfCustomAttributes* customAttributes, BfTypeInstance* typeInstance, bool checkTypeName)
  1476. {
  1477. if (mContext->mSystem->mTypeOptions.size() == 0)
  1478. {
  1479. return -1;
  1480. }
  1481. Array<int> matchedIndices;
  1482. if ((!checkTypeName) && (typeInstance->mTypeOptionsIdx != -1))
  1483. {
  1484. // Methods should 'inherit' the owner's type options before applying type options from custom attributes
  1485. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  1486. if (typeOptions->mMatchedIndices.size() == 0)
  1487. matchedIndices.push_back(typeInstance->mTypeOptionsIdx);
  1488. else
  1489. matchedIndices = typeOptions->mMatchedIndices;
  1490. }
  1491. if (customAttributes != NULL)
  1492. {
  1493. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  1494. {
  1495. StringT<128> attrName;
  1496. for (auto& customAttrs : customAttributes->mAttributes)
  1497. {
  1498. attrName.Clear();
  1499. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  1500. Array<int>* arrPtr;
  1501. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  1502. {
  1503. for (auto optionsIdx : *arrPtr)
  1504. {
  1505. matchedIndices.Add(optionsIdx);
  1506. }
  1507. }
  1508. }
  1509. }
  1510. }
  1511. int typeOptionsCount = (int)mContext->mSystem->mTypeOptions.size();
  1512. if (checkTypeName)
  1513. {
  1514. auto _CheckType = [&](BfType* type)
  1515. {
  1516. StringImpl typeName = TypeToString(type);
  1517. for (int optionIdx = 0; optionIdx < (int)mContext->mSystem->mTypeOptions.size(); optionIdx++)
  1518. {
  1519. auto& typeOptions = mContext->mSystem->mTypeOptions[optionIdx];
  1520. bool matched = false;
  1521. for (auto& filter : typeOptions.mTypeFilters)
  1522. {
  1523. int filterIdx = 0;
  1524. int typeNameIdx = 0;
  1525. if (filter.StartsWith(':'))
  1526. {
  1527. BfTypeInstance* typeInst = type->ToTypeInstance();
  1528. if (typeInst != NULL)
  1529. {
  1530. int startPos = 1;
  1531. for (; startPos < (int)filter.length(); startPos++)
  1532. if (filter[startPos] != ' ')
  1533. break;
  1534. String checkFilter;
  1535. checkFilter.Reference(filter.c_str() + startPos, filter.mLength - startPos);
  1536. BfTypeInstance* checkTypeInst = typeInst;
  1537. while (checkTypeInst != NULL)
  1538. {
  1539. for (auto& iface : checkTypeInst->mInterfaces)
  1540. {
  1541. StringT<128> ifaceName = TypeToString(iface.mInterfaceType);
  1542. if (BfCheckWildcard(checkFilter, ifaceName))
  1543. {
  1544. matched = true;
  1545. break;
  1546. }
  1547. }
  1548. checkTypeInst = checkTypeInst->mBaseType;
  1549. }
  1550. if (matched)
  1551. break;
  1552. }
  1553. }
  1554. else if (BfCheckWildcard(filter, typeName))
  1555. {
  1556. matched = true;
  1557. break;
  1558. }
  1559. }
  1560. if (matched)
  1561. matchedIndices.push_back(optionIdx);
  1562. }
  1563. };
  1564. if (typeInstance->IsTypedPrimitive())
  1565. {
  1566. auto underlyingType = typeInstance->GetUnderlyingType();
  1567. if (underlyingType != NULL)
  1568. {
  1569. _CheckType(underlyingType);
  1570. }
  1571. else
  1572. {
  1573. // Can this only happen for functions that are being extended?
  1574. }
  1575. }
  1576. if ((!typeInstance->IsBoxed()) && (typeInstance->mTypeDef == mCompiler->mPointerTTypeDef))
  1577. {
  1578. BF_ASSERT(typeInstance->IsGenericTypeInstance());
  1579. auto innerType = typeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  1580. auto ptrType = CreatePointerType(innerType);
  1581. _CheckType(ptrType);
  1582. }
  1583. _CheckType(typeInstance);
  1584. }
  1585. int matchedIdx = -1;
  1586. if (matchedIndices.size() == 1)
  1587. {
  1588. matchedIdx = matchedIndices[0];
  1589. }
  1590. else if (matchedIndices.size() > 1)
  1591. {
  1592. // Try to find a merged typeoptions with these indices
  1593. for (int mergedIdx = 0; mergedIdx < (int)mContext->mSystem->mMergedTypeOptions.size(); mergedIdx++)
  1594. {
  1595. auto& typeOptions = mContext->mSystem->mMergedTypeOptions[mergedIdx];
  1596. if (typeOptions.mMatchedIndices == matchedIndices)
  1597. {
  1598. matchedIdx = typeOptionsCount + mergedIdx;
  1599. break;
  1600. }
  1601. }
  1602. // Otherwise make one...
  1603. if (matchedIdx == -1)
  1604. {
  1605. auto& first = mContext->mSystem->mTypeOptions[matchedIndices[0]];
  1606. BfTypeOptions mergedTypeOptions;
  1607. mergedTypeOptions.mSIMDSetting = first.mSIMDSetting;
  1608. mergedTypeOptions.mOptimizationLevel = first.mOptimizationLevel;
  1609. mergedTypeOptions.mEmitDebugInfo = first.mEmitDebugInfo;
  1610. mergedTypeOptions.mAndFlags = first.mAndFlags;
  1611. mergedTypeOptions.mOrFlags = first.mOrFlags;
  1612. mergedTypeOptions.mAllocStackTraceDepth = first.mAllocStackTraceDepth;
  1613. mergedTypeOptions.mReflectMethodFilters = first.mReflectMethodFilters;
  1614. mergedTypeOptions.mReflectMethodAttributeFilters = first.mReflectMethodAttributeFilters;
  1615. mergedTypeOptions.mMatchedIndices = matchedIndices;
  1616. for (int idx = 1; idx < (int)matchedIndices.size(); idx++)
  1617. {
  1618. auto& typeOptions = mContext->mSystem->mTypeOptions[matchedIndices[idx]];
  1619. if (typeOptions.mSIMDSetting != -1)
  1620. mergedTypeOptions.mSIMDSetting = typeOptions.mSIMDSetting;
  1621. if (typeOptions.mOptimizationLevel != -1)
  1622. mergedTypeOptions.mOptimizationLevel = typeOptions.mOptimizationLevel;
  1623. if (typeOptions.mEmitDebugInfo != -1)
  1624. mergedTypeOptions.mEmitDebugInfo = typeOptions.mEmitDebugInfo;
  1625. mergedTypeOptions.mOrFlags = (BfOptionFlags)(mergedTypeOptions.mOrFlags | typeOptions.mOrFlags);
  1626. mergedTypeOptions.mAndFlags = (BfOptionFlags)(mergedTypeOptions.mAndFlags | typeOptions.mOrFlags);
  1627. mergedTypeOptions.mAndFlags = (BfOptionFlags)(mergedTypeOptions.mAndFlags & typeOptions.mAndFlags);
  1628. mergedTypeOptions.mOrFlags = (BfOptionFlags)(mergedTypeOptions.mOrFlags & typeOptions.mAndFlags);
  1629. if (typeOptions.mAllocStackTraceDepth != -1)
  1630. mergedTypeOptions.mAllocStackTraceDepth = typeOptions.mAllocStackTraceDepth;
  1631. for (auto& filter : typeOptions.mReflectMethodFilters)
  1632. mergedTypeOptions.mReflectMethodFilters.Add(filter);
  1633. for (auto& filter : typeOptions.mReflectMethodAttributeFilters)
  1634. mergedTypeOptions.mReflectMethodAttributeFilters.Add(filter);
  1635. }
  1636. matchedIdx = typeOptionsCount + (int)mContext->mSystem->mMergedTypeOptions.size();
  1637. mContext->mSystem->mMergedTypeOptions.push_back(mergedTypeOptions);
  1638. }
  1639. }
  1640. return matchedIdx;
  1641. }
  1642. void BfModule::SetTypeOptions(BfTypeInstance* typeInstance)
  1643. {
  1644. typeInstance->mTypeOptionsIdx = GenerateTypeOptions(typeInstance->mCustomAttributes, typeInstance, true);
  1645. }
  1646. void BfModule::DoPopulateType(BfType* resolvedTypeRef, BfPopulateType populateType)
  1647. {
  1648. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  1649. auto typeDef = typeInstance->mTypeDef;
  1650. BF_ASSERT((typeInstance->mTypeDef->mNextRevision == NULL) || (mCompiler->IsAutocomplete()));
  1651. // This is a special case where our base type has been rebuilt but we haven't
  1652. if ((typeInstance->mBaseTypeMayBeIncomplete) && (!typeInstance->mTypeIncomplete))
  1653. {
  1654. BfLogSysM("BaseTypeMayBeIncomplete processing. Type:%p -> Base:%p\n", typeInstance, typeInstance->mBaseType);
  1655. PopulateType(typeInstance->mBaseType, populateType);
  1656. if (!typeInstance->mBaseType->IsIncomplete())
  1657. typeInstance->mBaseTypeMayBeIncomplete = false;
  1658. if (!typeInstance->mTypeIncomplete)
  1659. return;
  1660. }
  1661. typeInstance->mBaseTypeMayBeIncomplete = false;
  1662. BF_ASSERT(mIsModuleMutable);
  1663. // Don't do type instance method processing for an autocomplete pass - this will get handled later on during
  1664. // the PopulateType worklist pass in the full resolver. We do need to handle the methods for delegates, though,
  1665. // since those can affect method declarations of other methods
  1666. // TODO: Investigate this "Delegate" claim
  1667. bool canDoMethodProcessing = ((mCompiler->mResolvePassData == NULL) || (mCompiler->mResolvePassData->mAutoComplete == NULL) /*|| (typeInstance->IsDelegate())*/);
  1668. if (populateType == BfPopulateType_Full_Force)
  1669. canDoMethodProcessing = true;
  1670. if (typeInstance->mResolvingConstField)
  1671. return;
  1672. auto _CheckTypeDone = [&]()
  1673. {
  1674. if (typeInstance->mNeedsMethodProcessing)
  1675. {
  1676. BF_ASSERT(typeInstance->mDefineState >= BfTypeDefineState_Defined);
  1677. if ((canDoMethodProcessing) && (populateType >= BfPopulateType_DataAndMethods))
  1678. DoTypeInstanceMethodProcessing(typeInstance);
  1679. return true;
  1680. }
  1681. return false;
  1682. };
  1683. if (_CheckTypeDone())
  1684. return;
  1685. // Partial population break out point
  1686. if ((populateType >= BfPopulateType_Identity) && (populateType <= BfPopulateType_IdentityNoRemapAlias))
  1687. return;
  1688. if (!resolvedTypeRef->IsValueType())
  1689. {
  1690. resolvedTypeRef->mSize = typeInstance->mAlign = mSystem->mPtrSize;
  1691. }
  1692. BF_ASSERT((typeInstance->mMethodInstanceGroups.size() == 0) || (typeInstance->mMethodInstanceGroups.size() == typeDef->mMethods.size()));
  1693. typeInstance->mMethodInstanceGroups.Resize(typeDef->mMethods.size());
  1694. for (int i = 0; i < (int)typeInstance->mMethodInstanceGroups.size(); i++)
  1695. {
  1696. typeInstance->mMethodInstanceGroups[i].mOwner = typeInstance;
  1697. typeInstance->mMethodInstanceGroups[i].mMethodIdx = i;
  1698. }
  1699. AutoDisallowYield disableYield(mSystem);
  1700. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  1701. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  1702. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  1703. SetAndRestoreValue<bool> prevHadError(mHadBuildError, false);
  1704. SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  1705. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  1706. typeState.mPopulateType = populateType;
  1707. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  1708. if (typeInstance->IsGenericTypeInstance())
  1709. {
  1710. auto genericTypeInst = (BfTypeInstance*)typeInstance;
  1711. if (!genericTypeInst->mGenericTypeInfo->mInitializedGenericParams)
  1712. InitGenericParams(resolvedTypeRef);
  1713. }
  1714. if (resolvedTypeRef->IsTypeAlias())
  1715. {
  1716. typeInstance->mTypeIncomplete = false;
  1717. resolvedTypeRef->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  1718. return;
  1719. }
  1720. if (_CheckTypeDone())
  1721. return;
  1722. // Don't do TypeToString until down here. Otherwise we can infinitely loop on BuildGenericParams
  1723. bool isStruct = resolvedTypeRef->IsStruct();
  1724. bool reportErrors = true;
  1725. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  1726. reportErrors = true;
  1727. // If we're not the defining context then we don't report errors for this type, but errors will still put the system
  1728. // into an errored state
  1729. SetAndRestoreValue<bool> prevReportErrors(mReportErrors, reportErrors);
  1730. if (typeInstance->mIsFinishingType)
  1731. {
  1732. // This type already failed
  1733. return;
  1734. }
  1735. CheckCircularDataError();
  1736. bool underlyingTypeDeferred = false;
  1737. BfType* underlyingType = NULL;
  1738. if (typeInstance->mBaseType != NULL)
  1739. {
  1740. if (typeInstance->IsTypedPrimitive())
  1741. underlyingType = typeInstance->GetUnderlyingType();
  1742. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_UnderlyingTypeDeferred) != 0)
  1743. underlyingTypeDeferred = true;
  1744. }
  1745. else if (typeInstance->IsEnum())
  1746. {
  1747. bool hasPayloads = false;
  1748. for (auto fieldDef : typeDef->mFields)
  1749. {
  1750. if ((fieldDef->IsEnumCaseEntry()) && (fieldDef->mTypeRef != NULL))
  1751. {
  1752. hasPayloads = true;
  1753. break;
  1754. }
  1755. }
  1756. if (!hasPayloads)
  1757. {
  1758. bool hadType = false;
  1759. for (auto baseTypeRef : typeDef->mBaseTypes)
  1760. {
  1761. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurBaseTypeRef, baseTypeRef);
  1762. SetAndRestoreValue<BfTypeDefineState> prevDefineState(typeInstance->mDefineState, BfTypeDefineState_ResolvingBaseType);
  1763. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  1764. SetAndRestoreValue<bool> prevSkipTypeProtectionChecks(typeInstance->mSkipTypeProtectionChecks, true);
  1765. auto baseType = ResolveTypeRef(baseTypeRef, BfPopulateType_Declaration);
  1766. if (baseType != NULL)
  1767. {
  1768. if (baseType->IsIntegral())
  1769. {
  1770. if (!hadType)
  1771. {
  1772. hadType = true;
  1773. underlyingType = baseType;
  1774. }
  1775. else
  1776. {
  1777. Fail("Underlying enum type already specified", baseTypeRef);
  1778. }
  1779. }
  1780. else
  1781. {
  1782. Fail("Invalid underlying enum type", baseTypeRef);
  1783. }
  1784. }
  1785. else
  1786. {
  1787. AssertErrorState();
  1788. typeInstance->mTypeFailed = true;
  1789. }
  1790. }
  1791. if (underlyingType == NULL)
  1792. {
  1793. underlyingType = GetPrimitiveType(BfTypeCode_Int64);
  1794. underlyingTypeDeferred = true;
  1795. }
  1796. }
  1797. }
  1798. // else if (typeInstance->IsFunction())
  1799. // {
  1800. // underlyingType = GetPrimitiveType(BfTypeCode_NullPtr);
  1801. // }
  1802. else if (((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive())) &&
  1803. (!typeInstance->mTypeFailed))
  1804. {
  1805. for (auto baseTypeRef : typeDef->mBaseTypes)
  1806. {
  1807. auto declTypeDef = typeDef;
  1808. if (typeDef->mIsCombinedPartial)
  1809. declTypeDef = typeDef->mPartials.front();
  1810. SetAndRestoreValue<BfTypeDef*> prevTypeDef(mContext->mCurTypeState->mCurTypeDef, declTypeDef);
  1811. SetAndRestoreValue<BfTypeDefineState> prevDefineState(typeInstance->mDefineState, BfTypeDefineState_ResolvingBaseType);
  1812. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurBaseTypeRef, baseTypeRef);
  1813. // We ignore errors here to avoid double-errors for type lookups, but this is where data cycles are detected
  1814. // but that type of error supersedes the mIgnoreErrors setting
  1815. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  1816. // Temporarily allow us to derive from private classes, to avoid infinite loop from TypeIsSubTypeOf
  1817. SetAndRestoreValue<bool> prevSkipTypeProtectionChecks(typeInstance->mSkipTypeProtectionChecks, true);
  1818. auto baseType = ResolveTypeRef(baseTypeRef, BfPopulateType_Declaration);
  1819. if (baseType != NULL)
  1820. {
  1821. if (baseType->IsPrimitiveType())
  1822. {
  1823. underlyingType = baseType;
  1824. }
  1825. else if (baseType->IsTypedPrimitive())
  1826. {
  1827. //PopulateType(baseType, true);
  1828. underlyingType = baseType->GetUnderlyingType();
  1829. BF_ASSERT(underlyingType != NULL);
  1830. }
  1831. }
  1832. else
  1833. {
  1834. AssertErrorState();
  1835. typeInstance->mTypeFailed = true;
  1836. }
  1837. }
  1838. // Incase we had re-entry, work this through ourselves again here
  1839. typeInstance->mIsTypedPrimitive = false;
  1840. }
  1841. if (underlyingTypeDeferred)
  1842. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_UnderlyingTypeDeferred);
  1843. typeInstance->mIsTypedPrimitive = underlyingType != NULL;
  1844. int wantFieldCount = (int)typeDef->mFields.size() + (((underlyingType != NULL) || (typeInstance->IsPayloadEnum())) ? 1 : 0);
  1845. if ((int)typeInstance->mFieldInstances.size() < wantFieldCount)
  1846. {
  1847. // Closures don't include the enclosed fields on their first pass through PopulateType, and they have no typeDef of their own
  1848. // so we need to take care not to truncate their fieldInstance vector here (thus the 'wantFieldCount' check above)
  1849. typeInstance->mFieldInstances.Resize(wantFieldCount);
  1850. }
  1851. if (underlyingType != NULL)
  1852. {
  1853. auto fieldInstance = &typeInstance->mFieldInstances.back();
  1854. fieldInstance->mDataOffset = 0;
  1855. fieldInstance->mDataSize = underlyingType->mSize;
  1856. fieldInstance->mOwner = typeInstance;
  1857. fieldInstance->mResolvedType = underlyingType;
  1858. typeInstance->mSize = underlyingType->mSize;
  1859. typeInstance->mAlign = underlyingType->mAlign;
  1860. typeInstance->mInstSize = underlyingType->mSize;
  1861. typeInstance->mInstAlign = underlyingType->mAlign;
  1862. typeInstance->mHasPackingHoles = underlyingType->HasPackingHoles();
  1863. }
  1864. // Partial population break out point
  1865. if (typeInstance->mDefineState < BfTypeDefineState_Declared)
  1866. {
  1867. typeInstance->mDefineState = BfTypeDefineState_Declared;
  1868. if (typeInstance->IsGenericTypeInstance())
  1869. {
  1870. auto genericTypeInstance = (BfTypeInstance*)typeInstance;
  1871. // Add generic dependencies if needed
  1872. for (auto genericType : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  1873. {
  1874. if (genericType->IsPrimitiveType())
  1875. genericType = GetWrappedStructType(genericType);
  1876. if (genericType != NULL)
  1877. {
  1878. AddDependency(genericType, genericTypeInstance, BfDependencyMap::DependencyFlag_TypeGenericArg);
  1879. BfLogSysM("Adding generic dependency of %p for type %p\n", genericType, genericTypeInstance);
  1880. }
  1881. }
  1882. if ((genericTypeInstance->IsSpecializedType()) &&
  1883. (!genericTypeInstance->IsDelegateFromTypeRef()) &&
  1884. (!genericTypeInstance->IsFunctionFromTypeRef()))
  1885. {
  1886. // This ensures we rebuild the unspecialized type whenever the specialized type rebuilds. This is important
  1887. // for generic type binding
  1888. auto unspecializedTypeInstance = GetUnspecializedTypeInstance(genericTypeInstance);
  1889. BF_ASSERT(!unspecializedTypeInstance->IsUnspecializedTypeVariation());
  1890. mContext->mScratchModule->AddDependency(genericTypeInstance, unspecializedTypeInstance, BfDependencyMap::DependencyFlag_UnspecializedType);
  1891. }
  1892. }
  1893. auto _AddStaticSearch = [&](BfTypeDef* typeDef)
  1894. {
  1895. if (!typeDef->mStaticSearch.IsEmpty())
  1896. {
  1897. BfStaticSearch* staticSearch;
  1898. if (typeInstance->mStaticSearchMap.TryAdd(typeDef, NULL, &staticSearch))
  1899. {
  1900. for (auto typeRef : typeDef->mStaticSearch)
  1901. {
  1902. auto staticType = ResolveTypeRef(typeRef, NULL, BfPopulateType_Identity);
  1903. if (staticType != NULL)
  1904. {
  1905. auto staticTypeInst = staticType->ToTypeInstance();
  1906. if (staticTypeInst == NULL)
  1907. {
  1908. Fail(StrFormat("Type '%s' cannot be used in a 'using static' declaration", TypeToString(staticType).c_str()), typeRef);
  1909. }
  1910. else
  1911. {
  1912. staticSearch->mStaticTypes.Add(staticTypeInst);
  1913. AddDependency(staticTypeInst, typeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  1914. }
  1915. }
  1916. }
  1917. }
  1918. }
  1919. if (!typeDef->mInternalAccessSet.IsEmpty())
  1920. {
  1921. BfInternalAccessSet* internalAccessSet;
  1922. if (typeInstance->mInternalAccessMap.TryAdd(typeDef, NULL, &internalAccessSet))
  1923. {
  1924. for (auto typeRef : typeDef->mInternalAccessSet)
  1925. {
  1926. if ((typeRef->IsA<BfNamedTypeReference>()) ||
  1927. (typeRef->IsA<BfQualifiedTypeReference>()))
  1928. {
  1929. String checkNamespaceStr;
  1930. typeRef->ToString(checkNamespaceStr);
  1931. BfAtomComposite checkNamespace;
  1932. if (mSystem->ParseAtomComposite(checkNamespaceStr, checkNamespace))
  1933. {
  1934. if (mSystem->ContainsNamespace(checkNamespace, typeDef->mProject))
  1935. {
  1936. mSystem->RefAtomComposite(checkNamespace);
  1937. internalAccessSet->mNamespaces.Add(checkNamespace);
  1938. continue;
  1939. }
  1940. }
  1941. }
  1942. BfType* internalType = NULL;
  1943. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  1944. internalType = mContext->mScratchModule->ResolveTypeRefAllowUnboundGenerics(typeRef, BfPopulateType_Identity);
  1945. else
  1946. internalType = ResolveTypeRef(typeRef, NULL, BfPopulateType_Identity);
  1947. if (internalType != NULL)
  1948. {
  1949. auto internalTypeInst = internalType->ToTypeInstance();
  1950. if (internalTypeInst == NULL)
  1951. {
  1952. Fail(StrFormat("Type '%s' cannot be used in a 'using internal' declaration", TypeToString(internalType).c_str()), typeRef);
  1953. }
  1954. else
  1955. {
  1956. internalAccessSet->mTypes.Add(internalTypeInst);
  1957. AddDependency(internalTypeInst, typeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  1958. }
  1959. }
  1960. }
  1961. }
  1962. }
  1963. };
  1964. if (typeDef->mIsCombinedPartial)
  1965. {
  1966. for (auto partialTypeDef : typeDef->mPartials)
  1967. _AddStaticSearch(partialTypeDef);
  1968. }
  1969. else
  1970. _AddStaticSearch(typeDef);
  1971. }
  1972. if (populateType == BfPopulateType_Declaration)
  1973. {
  1974. return;
  1975. }
  1976. if ((!mCompiler->mIsResolveOnly) && (!typeInstance->mHasBeenInstantiated))
  1977. {
  1978. for (auto& dep : typeInstance->mDependencyMap)
  1979. {
  1980. auto& depEntry = dep.mValue;
  1981. if ((depEntry.mFlags & BfDependencyMap::DependencyFlag_Allocates) != 0)
  1982. {
  1983. auto depType = dep.mKey;
  1984. if (depType->mRevision == depEntry.mRevision)
  1985. {
  1986. BfLogSysM("Setting mHasBeenInstantiated for %p instantiated from %p\n", typeInstance, depType);
  1987. typeInstance->mHasBeenInstantiated = true;
  1988. }
  1989. }
  1990. }
  1991. }
  1992. //BfLogSysM("Setting revision. Type: %p Revision: %d\n", typeInstance, mRevision);
  1993. //typeInstance->mRevision = mRevision;
  1994. // Temporarily allow us to derive from private classes, to avoid infinite loop from TypeIsSubTypeOf
  1995. SetAndRestoreValue<bool> prevSkipTypeProtectionChecks(typeInstance->mSkipTypeProtectionChecks, true);
  1996. if ((typeDef->mOuterType != NULL) && (typeDef->mOuterType->IsGlobalsContainer()))
  1997. {
  1998. if ((typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mTypeNode != NULL))
  1999. Fail("Global blocks cannot contain type declarations", typeDef->mTypeDeclaration->mTypeNode);
  2000. }
  2001. /// Create DI data
  2002. SizedArray<BfIRType, 8> llvmFieldTypes;
  2003. int curFieldDataIdx = 0;
  2004. typeInstance->mBaseType = NULL;
  2005. BfTypeInstance* defaultBaseTypeInst = NULL;
  2006. // Find base type
  2007. BfType* baseType = NULL;
  2008. struct BfInterfaceDecl
  2009. {
  2010. BfTypeInstance* mIFaceTypeInst;
  2011. BfTypeReference* mTypeRef;
  2012. BfTypeDef* mDeclaringType;
  2013. };
  2014. SizedArray<BfInterfaceDecl, 8> interfaces;
  2015. HashSet<BfTypeInstance*> ifaceSet;
  2016. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_ResolvingBase);
  2017. if (resolvedTypeRef == mContext->mBfObjectType)
  2018. {
  2019. baseType = NULL;
  2020. }
  2021. else if (typeInstance->IsEnum())
  2022. {
  2023. if (mCompiler->mEnumTypeDef == NULL)
  2024. {
  2025. Fail("Enum type required");
  2026. TypeFailed(typeInstance);
  2027. }
  2028. else
  2029. baseType = ResolveTypeDef(mCompiler->mEnumTypeDef)->ToTypeInstance();
  2030. }
  2031. else if (resolvedTypeRef->IsObject())
  2032. baseType = mContext->mBfObjectType;
  2033. else if (resolvedTypeRef->IsPointer())
  2034. {
  2035. baseType = ResolveTypeDef(mCompiler->mPointerTTypeDef, BfPopulateType_Data);
  2036. }
  2037. else if ((resolvedTypeRef->IsValueType()) && (typeDef != mCompiler->mValueTypeTypeDef))
  2038. {
  2039. baseType = ResolveTypeDef(mCompiler->mValueTypeTypeDef, BfPopulateType_Data)->ToTypeInstance();
  2040. }
  2041. if (baseType != NULL)
  2042. defaultBaseTypeInst = baseType->ToTypeInstance();
  2043. struct _DeferredValidate
  2044. {
  2045. BfTypeReference* mTypeRef;
  2046. BfTypeInstance* mGenericType;
  2047. bool mIgnoreErrors;
  2048. };
  2049. Array<_DeferredValidate> deferredTypeValidateList;
  2050. bool wantPopulateInterfaces = false;
  2051. BfTypeReference* baseTypeRef = NULL;
  2052. if ((typeDef->mIsDelegate) && (!typeInstance->IsClosure()))
  2053. {
  2054. if (mCompiler->mDelegateTypeDef == NULL)
  2055. {
  2056. Fail("Delegate type required");
  2057. TypeFailed(typeInstance);
  2058. }
  2059. else
  2060. baseType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  2061. }
  2062. else if (typeDef->mIsFunction)
  2063. {
  2064. if (mCompiler->mFunctionTypeDef == NULL)
  2065. {
  2066. Fail("Function type required");
  2067. TypeFailed(typeInstance);
  2068. }
  2069. else
  2070. baseType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  2071. }
  2072. else
  2073. {
  2074. for (auto checkTypeRef : typeDef->mBaseTypes)
  2075. {
  2076. auto declTypeDef = typeDef;
  2077. if (typeDef->mIsCombinedPartial)
  2078. declTypeDef = typeDef->mPartials.front();
  2079. SetAndRestoreValue<BfTypeDef*> prevTypeDef(mContext->mCurTypeState->mCurTypeDef, declTypeDef);
  2080. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurBaseTypeRef, checkTypeRef);
  2081. SetAndRestoreValue<BfTypeDefineState> prevDefineState(typeInstance->mDefineState, BfTypeDefineState_ResolvingBaseType);
  2082. bool populateBase = !typeInstance->mTypeFailed;
  2083. auto checkType = ResolveTypeRef(checkTypeRef, BfPopulateType_Declaration);
  2084. if ((checkType != NULL) && (!checkType->IsInterface()) && (populateBase))
  2085. PopulateType(checkType, BfPopulateType_Data);
  2086. if (typeInstance->mDefineState >= BfTypeDefineState_Defined)
  2087. {
  2088. prevDefineState.CancelRestore();
  2089. return;
  2090. }
  2091. if (checkType != NULL)
  2092. {
  2093. if (auto genericTypeInst = checkType->ToGenericTypeInstance())
  2094. {
  2095. // Specialized type variations don't need to validate their constraints
  2096. if (!typeInstance->IsUnspecializedTypeVariation())
  2097. deferredTypeValidateList.Add({ checkTypeRef, genericTypeInst, false });
  2098. }
  2099. auto checkTypeInst = checkType->ToTypeInstance();
  2100. bool canDeriveFrom = checkTypeInst != NULL;
  2101. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  2102. canDeriveFrom |= checkType->IsPrimitiveType();
  2103. if ((typeInstance->IsEnum()) && (!checkType->IsInterface()))
  2104. {
  2105. if (typeInstance->IsTypedPrimitive())
  2106. continue;
  2107. if (checkType->IsPrimitiveType())
  2108. Fail(StrFormat("Enum '%s' cannot be specified as '%s' because it has a payload",
  2109. TypeToString(typeInstance).c_str(), TypeToString(checkType).c_str()),
  2110. checkTypeRef, true);
  2111. else
  2112. Fail("Enums cannot derive from other types", checkTypeRef);
  2113. continue;
  2114. }
  2115. if ((checkTypeInst != NULL) && (checkTypeInst->mTypeFailed))
  2116. {
  2117. // To keep circular references from breaking type invariants (ie: base type loops)
  2118. continue;
  2119. }
  2120. if (!canDeriveFrom)
  2121. {
  2122. Fail("Cannot derive from this type", checkTypeRef);
  2123. continue;
  2124. }
  2125. if (checkType->IsInterface())
  2126. {
  2127. auto ifaceInst = checkType->ToTypeInstance();
  2128. if (ifaceSet.Add(ifaceInst))
  2129. {
  2130. // Not base type
  2131. BfInterfaceDecl ifaceDecl;
  2132. ifaceDecl.mIFaceTypeInst = ifaceInst;
  2133. ifaceDecl.mTypeRef = checkTypeRef;
  2134. ifaceDecl.mDeclaringType = typeDef;
  2135. interfaces.push_back(ifaceDecl);
  2136. }
  2137. else
  2138. {
  2139. Fail(StrFormat("Interface '%s' is already specified", TypeToString(checkType).c_str()), checkTypeRef);
  2140. }
  2141. }
  2142. else if (resolvedTypeRef == mContext->mBfObjectType)
  2143. {
  2144. Fail(StrFormat("Type '%s' cannot define a base type", TypeToString(baseType).c_str()), checkTypeRef);
  2145. }
  2146. else
  2147. {
  2148. if (baseTypeRef != NULL)
  2149. {
  2150. Fail(StrFormat("Base type '%s' already declared", TypeToString(baseType).c_str()), checkTypeRef);
  2151. }
  2152. else
  2153. {
  2154. baseTypeRef = checkTypeRef;
  2155. if (checkTypeInst != NULL)
  2156. {
  2157. auto checkOuter = checkTypeInst;
  2158. while (checkOuter != NULL)
  2159. {
  2160. if (checkOuter == typeInstance)
  2161. {
  2162. Fail(StrFormat("Type '%s' cannot be declare inner type '%s' as a base type",
  2163. TypeToString(typeInstance).c_str(),
  2164. TypeToString(checkTypeInst).c_str()), checkTypeRef, true);
  2165. checkTypeInst = NULL;
  2166. break;
  2167. }
  2168. checkOuter = GetOuterType(checkOuter);
  2169. }
  2170. }
  2171. if (checkTypeInst != NULL)
  2172. {
  2173. baseType = checkTypeInst;
  2174. }
  2175. }
  2176. }
  2177. }
  2178. else
  2179. {
  2180. AssertErrorState();
  2181. // Why did we go around setting mTypeFailed on all these things?
  2182. //typeInstance->mTypeFailed = true;
  2183. }
  2184. }
  2185. wantPopulateInterfaces = true;
  2186. }
  2187. if (resolvedTypeRef->IsBoxed())
  2188. {
  2189. if ((baseType != NULL) && (baseType->IsStruct()))
  2190. {
  2191. BfBoxedType* boxedType = (BfBoxedType*)resolvedTypeRef;
  2192. BfType* modifiedBaseType = baseType;
  2193. if (boxedType->IsBoxedStructPtr())
  2194. modifiedBaseType = CreatePointerType(modifiedBaseType);
  2195. boxedType->mBoxedBaseType = CreateBoxedType(modifiedBaseType);
  2196. PopulateType(boxedType->mBoxedBaseType);
  2197. AddDependency(boxedType->mBoxedBaseType, typeInstance, BfDependencyMap::DependencyFlag_DerivedFrom);
  2198. }
  2199. baseType = mContext->mBfObjectType;
  2200. }
  2201. BfTypeInstance* baseTypeInst = NULL;
  2202. if (baseType != NULL)
  2203. {
  2204. baseTypeInst = baseType->ToTypeInstance();
  2205. }
  2206. if (typeInstance->mBaseType != NULL)
  2207. {
  2208. BF_ASSERT(typeInstance->mBaseType == baseTypeInst);
  2209. }
  2210. if (auto genericTypeInst = typeInstance->ToGenericTypeInstance())
  2211. {
  2212. if ((genericTypeInst->IsSpecializedType()) && (!genericTypeInst->mGenericTypeInfo->mValidatedGenericConstraints) && (!typeInstance->IsBoxed()))
  2213. {
  2214. deferredTypeValidateList.Add({ NULL, genericTypeInst, true });
  2215. }
  2216. }
  2217. if (!typeInstance->IsBoxed())
  2218. {
  2219. BfType* outerType = GetOuterType(typeInstance);
  2220. if (outerType != NULL)
  2221. {
  2222. PopulateType(outerType, BfPopulateType_Identity);
  2223. AddDependency(outerType, typeInstance, BfDependencyMap::DependencyFlag_OuterType);
  2224. }
  2225. }
  2226. if ((baseTypeInst != NULL) && (typeInstance->mBaseType == NULL))
  2227. {
  2228. if (typeInstance->mTypeFailed)
  2229. {
  2230. if (baseTypeInst->IsDataIncomplete())
  2231. {
  2232. if (baseTypeInst->IsStruct())
  2233. baseTypeInst = ResolveTypeDef(mCompiler->mValueTypeTypeDef)->ToTypeInstance();
  2234. else if (baseTypeInst->IsObject())
  2235. baseTypeInst = ResolveTypeDef(mCompiler->mBfObjectTypeDef)->ToTypeInstance();
  2236. }
  2237. }
  2238. PopulateType(baseTypeInst, BfPopulateType_Data);
  2239. typeInstance->mBaseTypeMayBeIncomplete = false;
  2240. typeInstance->mMergedFieldDataCount = baseTypeInst->mMergedFieldDataCount;
  2241. if ((resolvedTypeRef->IsObject()) && (!baseTypeInst->IsObject()))
  2242. {
  2243. Fail("Class can only derive from another class", baseTypeRef, true);
  2244. //typeInstance->mTypeFailed = true;
  2245. baseTypeInst = defaultBaseTypeInst;
  2246. typeInstance->mBaseType = baseTypeInst;
  2247. }
  2248. else if ((resolvedTypeRef->IsStruct()) && (!baseTypeInst->IsValueType()))
  2249. {
  2250. Fail("Struct can only derive from another struct", baseTypeRef, true);
  2251. //typeInstance->mTypeFailed = true;
  2252. baseTypeInst = defaultBaseTypeInst;
  2253. typeInstance->mBaseType = baseTypeInst;
  2254. }
  2255. if (!typeInstance->IsIncomplete())
  2256. {
  2257. // Re-entry may cause this type to be completed already
  2258. return;
  2259. }
  2260. //BfLogSysM("Adding DerivedFrom dependency. Used:%p Using:%p\n", baseType, typeInstance);
  2261. auto checkBaseType = baseTypeInst;
  2262. while (checkBaseType != NULL)
  2263. {
  2264. // Add 'DerivedFrom' dependency all the way up the inheritance chain
  2265. AddDependency(checkBaseType, typeInstance, BfDependencyMap::DependencyFlag_DerivedFrom);
  2266. checkBaseType = checkBaseType->mBaseType;
  2267. }
  2268. typeInstance->mBaseType = baseTypeInst;
  2269. typeInstance->mInheritDepth = baseTypeInst->mInheritDepth + 1;
  2270. typeInstance->mHasParameterizedBase = baseTypeInst->mHasParameterizedBase;
  2271. if ((baseTypeInst->IsArray()) || (baseTypeInst->IsSizedArray()) || (baseTypeInst->IsGenericTypeInstance()))
  2272. typeInstance->mHasParameterizedBase = true;
  2273. if (underlyingType == NULL)
  2274. {
  2275. typeInstance->mInstSize = baseTypeInst->mInstSize;
  2276. typeInstance->mInstAlign = baseTypeInst->mInstAlign;
  2277. typeInstance->mAlign = baseTypeInst->mAlign;
  2278. typeInstance->mSize = baseTypeInst->mSize;
  2279. typeInstance->mHasPackingHoles = baseTypeInst->mHasPackingHoles;
  2280. if (baseTypeInst->mIsTypedPrimitive)
  2281. typeInstance->mIsTypedPrimitive = true;
  2282. }
  2283. }
  2284. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags & ~BfTypeRebuildFlag_ResolvingBase);
  2285. if (populateType <= BfPopulateType_BaseType)
  2286. return;
  2287. if (typeInstance->IsGenericTypeInstance())
  2288. {
  2289. auto genericTypeInst = (BfTypeInstance*)typeInstance;
  2290. // if (!genericTypeInst->mGenericTypeInfo->mInitializedGenericParams)
  2291. // InitGenericParams(resolvedTypeRef);
  2292. if (!genericTypeInst->mGenericTypeInfo->mFinishedGenericParams)
  2293. FinishGenericParams(resolvedTypeRef);
  2294. }
  2295. if (wantPopulateInterfaces)
  2296. {
  2297. for (auto partialTypeDef : typeDef->mPartials)
  2298. {
  2299. if (!typeInstance->IsTypeMemberIncluded(partialTypeDef))
  2300. continue;
  2301. if (partialTypeDef->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  2302. continue;
  2303. for (auto checkTypeRef : partialTypeDef->mBaseTypes)
  2304. {
  2305. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurBaseTypeRef, checkTypeRef);
  2306. SetAndRestoreValue<BfTypeDef*> prevTypeDef(mContext->mCurTypeState->mCurTypeDef, partialTypeDef);
  2307. bool populateBase = !typeInstance->mTypeFailed;
  2308. auto checkType = ResolveTypeRef(checkTypeRef, BfPopulateType_Declaration);
  2309. if (checkType != NULL)
  2310. {
  2311. if (checkType->IsInterface())
  2312. {
  2313. BfInterfaceDecl ifaceDecl;
  2314. ifaceDecl.mIFaceTypeInst = checkType->ToTypeInstance();
  2315. ifaceDecl.mTypeRef = checkTypeRef;
  2316. ifaceDecl.mDeclaringType = partialTypeDef;
  2317. interfaces.push_back(ifaceDecl);
  2318. }
  2319. else
  2320. {
  2321. Fail(StrFormat("Extensions can only specify new interfaces, type '%s' is not a valid ", TypeToString(checkType).c_str()), checkTypeRef);
  2322. }
  2323. }
  2324. }
  2325. }
  2326. }
  2327. if ((typeInstance->mBaseType != NULL) && (!typeInstance->IsTypedPrimitive()))
  2328. {
  2329. curFieldDataIdx++;
  2330. }
  2331. if (!interfaces.empty())
  2332. {
  2333. for (int iFaceIdx = 0; iFaceIdx < (int)interfaces.size(); iFaceIdx++)
  2334. {
  2335. auto checkInterface = interfaces[iFaceIdx].mIFaceTypeInst;
  2336. PopulateType(checkInterface, BfPopulateType_Data);
  2337. BfTypeInterfaceEntry* found = NULL;
  2338. bool foundExact = false;
  2339. for (auto& typeInterfaceInst : typeInstance->mInterfaces)
  2340. {
  2341. if (typeInterfaceInst.mInterfaceType == checkInterface)
  2342. {
  2343. if (typeInterfaceInst.mDeclaringType == interfaces[iFaceIdx].mDeclaringType)
  2344. {
  2345. foundExact = true;
  2346. break;
  2347. }
  2348. found = &typeInterfaceInst;
  2349. }
  2350. }
  2351. if (foundExact)
  2352. continue;
  2353. BfTypeInterfaceEntry typeInterfaceInst;
  2354. typeInterfaceInst.mDeclaringType = interfaces[iFaceIdx].mDeclaringType;
  2355. typeInterfaceInst.mInterfaceType = checkInterface;
  2356. typeInterfaceInst.mStartInterfaceTableIdx = -1;
  2357. typeInterfaceInst.mStartVirtualIdx = -1;
  2358. typeInterfaceInst.mIsRedeclared = false;
  2359. typeInstance->mInterfaces.push_back(typeInterfaceInst);
  2360. AddDependency(checkInterface, typeInstance, BfDependencyMap::DependencyFlag_ImplementsInterface);
  2361. // Interfaces can list other interfaces in their declaration, so pull those in too
  2362. for (auto depIFace : checkInterface->mInterfaces)
  2363. {
  2364. auto depIFaceEntry = interfaces[iFaceIdx];
  2365. depIFaceEntry.mIFaceTypeInst = depIFace.mInterfaceType;
  2366. interfaces.push_back(depIFaceEntry);
  2367. }
  2368. }
  2369. }
  2370. BF_ASSERT(!typeInstance->mNeedsMethodProcessing);
  2371. typeInstance->mDefineState = BfTypeDefineState_HasInterfaces;
  2372. for (auto& validateEntry : deferredTypeValidateList)
  2373. {
  2374. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, mIgnoreErrors | validateEntry.mIgnoreErrors);
  2375. ValidateGenericConstraints(validateEntry.mTypeRef, validateEntry.mGenericType, false);
  2376. }
  2377. if (populateType <= BfPopulateType_Interfaces)
  2378. return;
  2379. prevSkipTypeProtectionChecks.Restore();
  2380. typeInstance->mInstSize = std::max(0, typeInstance->mInstSize);
  2381. typeInstance->mInstAlign = std::max(0, typeInstance->mInstAlign);
  2382. if (!typeInstance->IsBoxed())
  2383. {
  2384. if ((typeInstance->mCustomAttributes == NULL) && (typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mAttributes != NULL))
  2385. {
  2386. BfAttributeTargets attrTarget;
  2387. if ((typeDef->mIsDelegate) || (typeDef->mIsFunction))
  2388. attrTarget = BfAttributeTargets_Delegate;
  2389. else if (typeInstance->IsEnum())
  2390. attrTarget = BfAttributeTargets_Enum;
  2391. else if (typeInstance->IsInterface())
  2392. attrTarget = BfAttributeTargets_Interface;
  2393. else if (typeInstance->IsStruct())
  2394. attrTarget = BfAttributeTargets_Struct;
  2395. else
  2396. attrTarget = BfAttributeTargets_Class;
  2397. if (!typeInstance->mTypeFailed)
  2398. {
  2399. // This allows us to avoid reentrancy when checking for inner types
  2400. SetAndRestoreValue<bool> prevSkipTypeProtectionChecks(typeInstance->mSkipTypeProtectionChecks, true);
  2401. if (typeDef->mIsCombinedPartial)
  2402. {
  2403. for (auto partialTypeDef : typeDef->mPartials)
  2404. {
  2405. if (partialTypeDef->mTypeDeclaration->mAttributes == NULL)
  2406. continue;
  2407. BfTypeState typeState;
  2408. typeState.mPrevState = mContext->mCurTypeState;
  2409. typeState.mCurTypeDef = partialTypeDef;
  2410. typeState.mTypeInstance = typeInstance;
  2411. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  2412. if (typeInstance->mCustomAttributes == NULL)
  2413. typeInstance->mCustomAttributes = new BfCustomAttributes();
  2414. GetCustomAttributes(typeInstance->mCustomAttributes, partialTypeDef->mTypeDeclaration->mAttributes, attrTarget);
  2415. }
  2416. }
  2417. else
  2418. typeInstance->mCustomAttributes = GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, attrTarget);
  2419. }
  2420. }
  2421. }
  2422. if (typeInstance->mTypeOptionsIdx == -2)
  2423. SetTypeOptions(typeInstance);
  2424. ProcessCustomAttributeData();
  2425. bool isPacked = false;
  2426. bool isUnion = false;
  2427. bool isCRepr = false;
  2428. bool isOrdered = false;
  2429. int alignOverride = 0;
  2430. BfType* underlyingArrayType = NULL;
  2431. int underlyingArraySize = -1;
  2432. ProcessTypeInstCustomAttributes(isPacked, isUnion, isCRepr, isOrdered, alignOverride, underlyingArrayType, underlyingArraySize);
  2433. if (underlyingArraySize > 0)
  2434. {
  2435. typeInstance->mHasUnderlyingArray = true;
  2436. curFieldDataIdx = 0;
  2437. }
  2438. if (isPacked) // Packed infers ordered
  2439. isOrdered = true;
  2440. typeInstance->mIsUnion = isUnion;
  2441. if ((typeInstance->IsEnum()) && (typeInstance->IsStruct()))
  2442. typeInstance->mIsUnion = true;
  2443. typeInstance->mIsPacked = isPacked;
  2444. typeInstance->mIsCRepr = isCRepr;
  2445. if (typeInstance->mTypeOptionsIdx >= 0)
  2446. {
  2447. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  2448. if (typeOptions != NULL)
  2449. {
  2450. typeInstance->mHasBeenInstantiated = typeOptions->Apply(typeInstance->mHasBeenInstantiated, BfOptionFlags_ReflectAssumeInstantiated);
  2451. }
  2452. }
  2453. BfType* unionInnerType = NULL;
  2454. bool hadDeferredVars = false;
  2455. int dataPos;
  2456. if (resolvedTypeRef->IsBoxed())
  2457. {
  2458. BfBoxedType* boxedType = (BfBoxedType*)resolvedTypeRef;
  2459. BfType* innerType = boxedType->mElementType;
  2460. if (boxedType->IsBoxedStructPtr())
  2461. innerType = CreatePointerType(innerType);
  2462. if (innerType->IsIncomplete())
  2463. PopulateType(innerType, BfPopulateType_Data);
  2464. auto baseType = typeInstance->mBaseType;
  2465. dataPos = baseType->mInstSize;
  2466. int alignSize = BF_MAX(innerType->mAlign, baseType->mInstAlign);
  2467. if (alignSize > 1)
  2468. dataPos = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  2469. int dataSize = innerType->mSize;
  2470. typeInstance->mFieldInstances.push_back(BfFieldInstance());
  2471. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances.back();
  2472. fieldInstance->mDataOffset = dataPos;
  2473. fieldInstance->mDataSize = innerType->mSize;
  2474. fieldInstance->mOwner = typeInstance;
  2475. fieldInstance->mResolvedType = innerType;
  2476. if (!innerType->IsValuelessType())
  2477. {
  2478. curFieldDataIdx++;
  2479. }
  2480. dataPos += dataSize;
  2481. typeInstance->mInstAlign = std::max(baseType->mInstAlign, alignSize);
  2482. int instAlign = typeInstance->mInstAlign;
  2483. if (instAlign != 0)
  2484. {
  2485. int instSize = (dataPos + (instAlign - 1)) & ~(instAlign - 1);
  2486. if (instSize != typeInstance->mInstSize)
  2487. {
  2488. typeInstance->mInstSize = instSize;
  2489. typeInstance->mHasPackingHoles = true;
  2490. }
  2491. }
  2492. typeInstance->mInstSize = std::max(1, typeInstance->mInstSize);
  2493. }
  2494. else
  2495. {
  2496. dataPos = typeInstance->mInstSize;
  2497. if (underlyingType != NULL)
  2498. {
  2499. if (!underlyingType->IsValuelessType())
  2500. {
  2501. curFieldDataIdx++;
  2502. }
  2503. }
  2504. struct DeferredResolveEntry
  2505. {
  2506. BfFieldDef* mFieldDef;
  2507. int mTypeArrayIdx;
  2508. };
  2509. BfSizedVector<DeferredResolveEntry, 8> deferredVarResolves;
  2510. for (auto field : typeDef->mFields)
  2511. {
  2512. auto fieldInstance = &typeInstance->mFieldInstances[field->mIdx];
  2513. if (fieldInstance->mResolvedType != NULL)
  2514. continue;
  2515. if (!typeInstance->IsTypeMemberIncluded(field->mDeclaringType))
  2516. {
  2517. fieldInstance->mFieldIncluded = false;
  2518. continue;
  2519. }
  2520. fieldInstance->mOwner = typeInstance;
  2521. fieldInstance->mFieldIdx = field->mIdx;
  2522. if (typeInstance->IsInterface())
  2523. Fail("Interfaces cannot include fields. Consider making this a property", field->GetRefNode());
  2524. }
  2525. int enumCaseEntryIdx = 0;
  2526. for (int pass = 0; pass < 2; pass++)
  2527. {
  2528. for (auto field : typeDef->mFields)
  2529. {
  2530. // Do consts then non-consts. Somewhat of a hack for using consts as sized array size
  2531. if (field->mIsConst != (pass == 0))
  2532. continue;
  2533. auto fieldInstance = &typeInstance->mFieldInstances[field->mIdx];
  2534. if ((fieldInstance->mResolvedType != NULL) || (!fieldInstance->mFieldIncluded))
  2535. continue;
  2536. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, field);
  2537. BfType* resolvedFieldType = NULL;
  2538. if (field->IsEnumCaseEntry())
  2539. {
  2540. fieldInstance->mDataIdx = -(enumCaseEntryIdx++) - 1;
  2541. resolvedFieldType = typeInstance;
  2542. BfType* payloadType = NULL;
  2543. if (field->mTypeRef != NULL)
  2544. payloadType = ResolveTypeRef(field->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  2545. if (payloadType == NULL)
  2546. {
  2547. if (!typeInstance->IsTypedPrimitive())
  2548. payloadType = CreateTupleType(BfTypeVector(), Array<String>());
  2549. }
  2550. if (payloadType != NULL)
  2551. {
  2552. AddDependency(payloadType, typeInstance, BfDependencyMap::DependencyFlag_ValueTypeMemberData);
  2553. BF_ASSERT(payloadType->IsTuple());
  2554. resolvedFieldType = payloadType;
  2555. fieldInstance->mIsEnumPayloadCase = true;
  2556. }
  2557. }
  2558. else if ((field->mTypeRef != NULL) && ((field->mTypeRef->IsExact<BfVarTypeReference>()) || (field->mTypeRef->IsExact<BfLetTypeReference>()) || (field->mTypeRef->IsExact<BfDeclTypeRef>())))
  2559. {
  2560. resolvedFieldType = GetPrimitiveType(BfTypeCode_Var);
  2561. DeferredResolveEntry resolveEntry;
  2562. resolveEntry.mFieldDef = field;
  2563. resolveEntry.mTypeArrayIdx = (int)llvmFieldTypes.size();
  2564. deferredVarResolves.push_back(resolveEntry);
  2565. fieldInstance->mIsInferredType = true;
  2566. // For 'let', make read-only
  2567. }
  2568. else
  2569. {
  2570. resolvedFieldType = ResolveTypeRef(field->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  2571. if (resolvedFieldType == NULL)
  2572. {
  2573. // Failed, just put in placeholder 'var'
  2574. AssertErrorState();
  2575. resolvedFieldType = GetPrimitiveType(BfTypeCode_Var);
  2576. }
  2577. }
  2578. if (resolvedFieldType->IsMethodRef())
  2579. {
  2580. auto methodRefType = (BfMethodRefType*)resolvedFieldType;
  2581. }
  2582. if (fieldInstance->mResolvedType == NULL)
  2583. fieldInstance->mResolvedType = resolvedFieldType;
  2584. if (field->mIsConst)
  2585. {
  2586. // Resolve in ResolveConstField after we finish populating entire FieldInstance list
  2587. }
  2588. else if (field->mIsStatic)
  2589. {
  2590. // Don't allocate this until after we're finished populating entire FieldInstance list,
  2591. // because we may have re-entry and create multiple instances of this static field
  2592. }
  2593. }
  2594. }
  2595. if (!resolvedTypeRef->IsIncomplete())
  2596. {
  2597. // We finished resolving ourselves through a re-entry, so we're actually done here
  2598. return;
  2599. }
  2600. for (auto& resolveEntry : deferredVarResolves)
  2601. {
  2602. hadDeferredVars = true;
  2603. auto fieldType = ResolveVarFieldType(typeInstance, &typeInstance->mFieldInstances[resolveEntry.mFieldDef->mIdx], resolveEntry.mFieldDef);
  2604. if (fieldType == NULL)
  2605. {
  2606. fieldType = mContext->mBfObjectType;
  2607. // We used to set mTypeFailed, but mHasBuildError is enough to cause a type rebuild properly
  2608. mHadBuildError = true;
  2609. //typeInstance->mTypeFailed = true;
  2610. }
  2611. auto fieldInstance = &typeInstance->mFieldInstances[resolveEntry.mFieldDef->mIdx];
  2612. fieldInstance->SetResolvedType(fieldType);
  2613. }
  2614. if (typeInstance->mResolvingConstField)
  2615. return;
  2616. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  2617. {
  2618. auto fieldInstance = &fieldInstanceRef;
  2619. auto fieldDef = fieldInstance->GetFieldDef();
  2620. auto resolvedFieldType = fieldInstance->GetResolvedType();
  2621. if (!fieldInstance->mFieldIncluded)
  2622. continue;
  2623. if (resolvedFieldType == NULL)
  2624. {
  2625. if ((underlyingType != NULL) || (typeInstance->IsPayloadEnum()))
  2626. continue;
  2627. }
  2628. if (!fieldInstance->mFieldIncluded)
  2629. continue;
  2630. if (fieldDef == NULL)
  2631. continue;
  2632. if ((!fieldDef->mIsStatic) && (resolvedFieldType->IsValueType()))
  2633. {
  2634. // We need that type finished up for alignment and data size
  2635. // But if the type has failed then we need to avoid stack overflow so we don't finish it
  2636. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, fieldDef);
  2637. bool populateChildType = !typeInstance->mTypeFailed;
  2638. //bool populateChildType = true;
  2639. PopulateType(resolvedFieldType, populateChildType ? BfPopulateType_Data : BfPopulateType_Declaration);
  2640. if (populateChildType)
  2641. {
  2642. BF_ASSERT(!resolvedFieldType->IsDataIncomplete());
  2643. }
  2644. else
  2645. {
  2646. if (resolvedFieldType->IsDataIncomplete())
  2647. {
  2648. AssertErrorState();
  2649. resolvedFieldType = mContext->mBfObjectType;
  2650. fieldInstance->SetResolvedType(resolvedFieldType);
  2651. // We used to set mTypeFailed, but mHasBuildError is enough to cause a type rebuild properly
  2652. mHadBuildError = true;
  2653. }
  2654. }
  2655. }
  2656. }
  2657. }
  2658. if (_CheckTypeDone())
  2659. return;
  2660. BF_ASSERT(mContext->mCurTypeState == &typeState);
  2661. //BF_ASSERT(!typeInstance->mIsFinishingType);
  2662. typeInstance->mIsFinishingType = true;
  2663. // No re-entry is allowed below here -- we will run all the way to the end at this point
  2664. BfSizedVector<BfIRMDNode, 8> diFieldTypes;
  2665. HashContext dataMemberHashCtx;
  2666. if (!resolvedTypeRef->IsBoxed())
  2667. {
  2668. for (auto propDef : typeDef->mProperties)
  2669. {
  2670. if (!typeInstance->IsTypeMemberIncluded(propDef->mDeclaringType))
  2671. continue;
  2672. if (propDef->mFieldDeclaration != NULL)
  2673. {
  2674. BfTypeState typeState;
  2675. typeState.mPrevState = mContext->mCurTypeState;
  2676. typeState.mCurTypeDef = propDef->mDeclaringType;
  2677. typeState.mCurFieldDef = propDef;
  2678. typeState.mTypeInstance = typeInstance;
  2679. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  2680. BfAttributeTargets target = BfAttributeTargets_Property;
  2681. if (propDef->IsExpressionBodied())
  2682. target = (BfAttributeTargets)(target | BfAttributeTargets_Method);
  2683. if (propDef->mFieldDeclaration->mAttributes != NULL)
  2684. {
  2685. auto customAttrs = GetCustomAttributes(propDef->mFieldDeclaration->mAttributes, target);
  2686. delete customAttrs;
  2687. }
  2688. auto propDecl = (BfPropertyDeclaration*)propDef->mFieldDeclaration;
  2689. if (propDecl->mExplicitInterface != NULL)
  2690. {
  2691. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  2692. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(propDecl->mExplicitInterface, false);
  2693. auto explicitInterface = ResolveTypeRef(propDecl->mExplicitInterface, BfPopulateType_Declaration);
  2694. if (explicitInterface != NULL)
  2695. {
  2696. bool interfaceFound = false;
  2697. for (auto ifaceInst : typeInstance->mInterfaces)
  2698. interfaceFound |= ifaceInst.mInterfaceType == explicitInterface;
  2699. if (!interfaceFound)
  2700. {
  2701. Fail("Containing class has not declared to implement this interface", propDecl->mExplicitInterface, true);
  2702. }
  2703. }
  2704. }
  2705. }
  2706. if (propDef->mMethods.IsEmpty())
  2707. {
  2708. auto nameNode = ((BfPropertyDeclaration*)propDef->mFieldDeclaration)->mNameNode;
  2709. if (nameNode != NULL)
  2710. {
  2711. Fail(StrFormat("Property or indexer '%s.%s' must have at least one accessor", TypeToString(typeInstance).c_str(), propDef->mName.c_str()),
  2712. nameNode, true); // CS0548
  2713. }
  2714. }
  2715. }
  2716. bool isGlobalContainer = typeDef->IsGlobalsContainer();
  2717. if (typeInstance->mBaseType != NULL)
  2718. {
  2719. dataMemberHashCtx.Mixin(typeInstance->mBaseType->mTypeId);
  2720. if (typeInstance->mBaseType->mHotTypeData != NULL)
  2721. {
  2722. BfHotTypeVersion* ver = typeInstance->mBaseType->mHotTypeData->GetLatestVersion();
  2723. dataMemberHashCtx.Mixin(ver->mDataHash);
  2724. }
  2725. }
  2726. dataMemberHashCtx.Mixin(typeInstance->mIsPacked);
  2727. dataMemberHashCtx.Mixin(typeInstance->mIsCRepr);
  2728. dataMemberHashCtx.Mixin(typeInstance->mIsUnion);
  2729. int startDataPos = dataPos;
  2730. int maxDataPos = dataPos;
  2731. BfSizedVector<BfFieldInstance*, 16> dataFieldVec;
  2732. bool allowInstanceFields = (underlyingType == NULL);
  2733. if (typeInstance->IsTypedPrimitive())
  2734. allowInstanceFields = false;
  2735. // We've resolved all the 'var' entries, so now build the actual composite type
  2736. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  2737. {
  2738. auto fieldInstance = &fieldInstanceRef;
  2739. if (!fieldInstance->mFieldIncluded)
  2740. continue;
  2741. auto resolvedFieldType = fieldInstance->GetResolvedType();
  2742. if (fieldInstance->mResolvedType == NULL)
  2743. {
  2744. if ((underlyingType == NULL) && (!typeInstance->IsPayloadEnum()))
  2745. BF_ASSERT(typeInstance->mTypeFailed);
  2746. continue;
  2747. }
  2748. if ((fieldInstance->GetFieldDef() != NULL) && (fieldInstance->GetFieldDef()->mIsConst))
  2749. {
  2750. // Resolve later
  2751. }
  2752. else if (fieldInstance->GetFieldDef() != NULL)
  2753. {
  2754. if (!fieldInstance->GetFieldDef()->mIsStatic)
  2755. AddFieldDependency(typeInstance, fieldInstance, resolvedFieldType);
  2756. else
  2757. AddDependency(resolvedFieldType, typeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  2758. }
  2759. auto fieldDef = fieldInstance->GetFieldDef();
  2760. BF_ASSERT(fieldInstance->mCustomAttributes == NULL);
  2761. if ((fieldDef != NULL) && (fieldDef->mFieldDeclaration != NULL) && (fieldDef->mFieldDeclaration->mAttributes != NULL))
  2762. {
  2763. BfTypeState typeState;
  2764. typeState.mPrevState = mContext->mCurTypeState;
  2765. typeState.mCurFieldDef = fieldDef;
  2766. typeState.mCurTypeDef = fieldDef->mDeclaringType;
  2767. typeState.mTypeInstance = typeInstance;
  2768. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  2769. fieldInstance->mCustomAttributes = GetCustomAttributes(fieldDef->mFieldDeclaration->mAttributes, fieldDef->mIsStatic ? BfAttributeTargets_StaticField : BfAttributeTargets_Field);
  2770. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  2771. {
  2772. if (TypeToString(customAttr.mType) == "System.ThreadStaticAttribute")
  2773. {
  2774. if ((!fieldDef->mIsStatic) || (fieldDef->mIsConst))
  2775. {
  2776. Fail("ThreadStatic attribute can only be used on static fields", fieldDef->mFieldDeclaration->mAttributes);
  2777. }
  2778. }
  2779. }
  2780. }
  2781. if (fieldInstance->mResolvedType != NULL)
  2782. {
  2783. auto resolvedFieldType = fieldInstance->GetResolvedType();
  2784. if ((!typeInstance->IsBoxed()) && (fieldDef != NULL))
  2785. {
  2786. if (fieldInstance->mIsEnumPayloadCase)
  2787. {
  2788. PopulateType(resolvedFieldType, BfPopulateType_Data);
  2789. if (resolvedFieldType->WantsGCMarking())
  2790. typeInstance->mWantsGCMarking = true;
  2791. }
  2792. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  2793. {
  2794. PopulateType(resolvedFieldType, resolvedFieldType->IsValueType() ? BfPopulateType_Data : BfPopulateType_Declaration);
  2795. if (resolvedFieldType->WantsGCMarking())
  2796. typeInstance->mWantsGCMarking = true;
  2797. fieldInstance->mMergedDataIdx = typeInstance->mMergedFieldDataCount;
  2798. if (resolvedFieldType->IsStruct())
  2799. {
  2800. auto resolvedFieldTypeInstance = resolvedFieldType->ToTypeInstance();
  2801. typeInstance->mMergedFieldDataCount += resolvedFieldTypeInstance->mMergedFieldDataCount;
  2802. }
  2803. else if (!resolvedFieldType->IsValuelessType())
  2804. typeInstance->mMergedFieldDataCount++;
  2805. if (fieldDef->mIsExtern)
  2806. {
  2807. Fail("Cannot declare instance member as 'extern'", fieldDef->mFieldDeclaration->mExternSpecifier, true);
  2808. }
  2809. BfAstNode* nameRefNode = NULL;
  2810. if (fieldDef->mFieldDeclaration != NULL)
  2811. nameRefNode = fieldDef->mFieldDeclaration->mNameNode;
  2812. if (nameRefNode == NULL)
  2813. nameRefNode = fieldDef->mTypeRef;
  2814. if (!allowInstanceFields)
  2815. {
  2816. if (typeInstance->IsEnum())
  2817. Fail("Cannot declare instance members in an enum", nameRefNode, true);
  2818. else if (typeInstance->IsFunction())
  2819. Fail("Cannot declare instance members in a function", nameRefNode, true);
  2820. else
  2821. Fail("Cannot declare instance members in a typed primitive struct", nameRefNode, true);
  2822. TypeFailed(typeInstance);
  2823. fieldInstance->mDataIdx = -1;
  2824. continue;
  2825. }
  2826. if (typeDef->mIsStatic)
  2827. {
  2828. //CS0708
  2829. Fail("Cannot declare instance members in a static class", nameRefNode, true);
  2830. }
  2831. if (resolvedFieldType->IsValueType())
  2832. {
  2833. BF_ASSERT(!resolvedFieldType->IsDataIncomplete());
  2834. }
  2835. if (!mCompiler->mIsResolveOnly)
  2836. {
  2837. dataMemberHashCtx.MixinStr(fieldDef->mName);
  2838. dataMemberHashCtx.Mixin(resolvedFieldType->mTypeId);
  2839. }
  2840. int dataSize = resolvedFieldType->mSize;
  2841. int alignSize = resolvedFieldType->mAlign;
  2842. fieldInstance->mDataSize = dataSize;
  2843. if (!isUnion)
  2844. {
  2845. if (!resolvedFieldType->IsValuelessType())
  2846. {
  2847. if (isCRepr)
  2848. {
  2849. dataFieldVec.push_back(fieldInstance);
  2850. }
  2851. else
  2852. {
  2853. dataFieldVec.push_back(fieldInstance);
  2854. }
  2855. }
  2856. }
  2857. else
  2858. {
  2859. BF_ASSERT(resolvedFieldType->mSize >= 0);
  2860. if ((alignSize > 1) && (!isPacked))
  2861. dataPos = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  2862. fieldInstance->mDataOffset = dataPos;
  2863. if (!isPacked)
  2864. typeInstance->mInstAlign = std::max(typeInstance->mInstAlign, alignSize);
  2865. dataPos += dataSize;
  2866. if (dataPos > maxDataPos)
  2867. {
  2868. maxDataPos = dataPos;
  2869. }
  2870. dataPos = startDataPos;
  2871. }
  2872. auto fieldTypeInst = resolvedFieldType->ToTypeInstance();
  2873. if (fieldTypeInst != NULL)
  2874. {
  2875. if ((fieldTypeInst->mRebuildFlags & BfTypeRebuildFlag_UnderlyingTypeDeferred) != 0)
  2876. {
  2877. BfAstNode* refNode = fieldDef->mFieldDeclaration;
  2878. String failStr;
  2879. failStr = StrFormat("Circular data reference detected between '%s' and '%s'", TypeToString(mCurTypeInstance).c_str(), TypeToString(fieldTypeInst).c_str());
  2880. if (!mContext->mFieldResolveReentrys.IsEmpty())
  2881. {
  2882. failStr += StrFormat(" with the following fields:", TypeToString(mCurTypeInstance).c_str());
  2883. for (int i = 0; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  2884. {
  2885. auto checkField = mContext->mFieldResolveReentrys[i];
  2886. if (i > 0)
  2887. failStr += ",";
  2888. failStr += "\n '" + TypeToString(typeInstance) + "." + checkField->GetFieldDef()->mName + "'";
  2889. if (checkField->mOwner == fieldTypeInst)
  2890. refNode = checkField->GetFieldDef()->mFieldDeclaration;
  2891. }
  2892. }
  2893. BfError* err = Fail(failStr, refNode);
  2894. if (err)
  2895. err->mIsPersistent = true;
  2896. }
  2897. }
  2898. }
  2899. bool useForUnion = false;
  2900. if (fieldInstance->mIsEnumPayloadCase)
  2901. {
  2902. if (!typeInstance->IsEnum())
  2903. {
  2904. Fail("Cases can only be used in enum types", fieldDef->mFieldDeclaration);
  2905. }
  2906. else
  2907. {
  2908. BF_ASSERT(typeInstance->mIsUnion);
  2909. }
  2910. }
  2911. if ((!fieldDef->mIsStatic) && (!resolvedFieldType->IsValuelessType()))
  2912. {
  2913. if (isUnion)
  2914. {
  2915. fieldInstance->mDataIdx = curFieldDataIdx;
  2916. }
  2917. }
  2918. }
  2919. if ((!typeInstance->IsSpecializedType()) && (!typeInstance->IsOnDemand()) && (fieldDef != NULL) && (!CheckDefineMemberProtection(fieldDef->mProtection, resolvedFieldType)))
  2920. {
  2921. //CS0052
  2922. Fail(StrFormat("Inconsistent accessibility: field type '%s' is less accessible than field '%s.%s'",
  2923. TypeToString(resolvedFieldType).c_str(), TypeToString(mCurTypeInstance).c_str(), fieldDef->mName.c_str()),
  2924. fieldDef->mTypeRef, true);
  2925. }
  2926. }
  2927. }
  2928. if (typeInstance->mIsUnion)
  2929. {
  2930. SetAndRestoreValue<BfTypeState::ResolveKind> prevResolveKind(typeState.mResolveKind, BfTypeState::ResolveKind_UnionInnerType);
  2931. unionInnerType = typeInstance->GetUnionInnerType();
  2932. }
  2933. if (!isOrdered)
  2934. {
  2935. int dataFieldCount = (int)dataFieldVec.size();
  2936. Array<Deque<BfFieldInstance*>> alignBuckets;
  2937. for (auto fieldInst : dataFieldVec)
  2938. {
  2939. int alignBits = GetHighestBitSet(fieldInst->mResolvedType->mAlign);
  2940. while (alignBits >= alignBuckets.size())
  2941. alignBuckets.Add({});
  2942. alignBuckets[alignBits].Add(fieldInst);
  2943. }
  2944. dataFieldVec.clear();
  2945. int curSize = typeInstance->mInstSize;
  2946. while (dataFieldVec.size() != dataFieldCount)
  2947. {
  2948. // Clear out completed buckets
  2949. while (alignBuckets[alignBuckets.size() - 1].IsEmpty())
  2950. {
  2951. alignBuckets.pop_back();
  2952. }
  2953. int alignBits = GetNumLowZeroBits(curSize) + 1;
  2954. alignBits = BF_MIN(alignBits, (int)alignBuckets.size() - 1);
  2955. bool foundEntry = false;
  2956. while (alignBits >= 0)
  2957. {
  2958. if (alignBuckets[alignBits].IsEmpty())
  2959. {
  2960. alignBits--;
  2961. continue;
  2962. }
  2963. bool isHighestBucket = alignBits == alignBuckets.size() - 1;
  2964. auto fieldInst = alignBuckets[alignBits][0];
  2965. alignBuckets[alignBits].RemoveAt(0);
  2966. dataFieldVec.push_back(fieldInst);
  2967. curSize = BF_ALIGN(curSize, fieldInst->mResolvedType->mAlign);
  2968. curSize += fieldInst->mResolvedType->mSize;
  2969. foundEntry = true;
  2970. if (!isHighestBucket)
  2971. {
  2972. // We may have a larger type that can fit now...
  2973. break;
  2974. }
  2975. }
  2976. if (!foundEntry)
  2977. {
  2978. // If no entries will fit, then force an entry of the smallest alignment
  2979. for (int alignBits = 0; alignBits < alignBuckets.size(); alignBits++)
  2980. {
  2981. if (!alignBuckets[alignBits].IsEmpty())
  2982. {
  2983. auto fieldInst = alignBuckets[alignBits][0];
  2984. alignBuckets[alignBits].RemoveAt(0);
  2985. dataFieldVec.push_back(fieldInst);
  2986. curSize = BF_ALIGN(curSize, fieldInst->mResolvedType->mAlign);
  2987. curSize += fieldInst->mResolvedType->mSize;
  2988. break;
  2989. }
  2990. }
  2991. }
  2992. }
  2993. }
  2994. //bool needsExplicitAlignment = !isCRepr || ((typeInstance->mBaseType != NULL) && (!typeInstance->mBaseType->mIsCRepr));
  2995. bool needsExplicitAlignment = true;
  2996. for (int fieldIdx = 0; fieldIdx < (int)dataFieldVec.size(); fieldIdx++)
  2997. {
  2998. auto fieldInstance = dataFieldVec[fieldIdx];
  2999. auto resolvedFieldType = fieldInstance->GetResolvedType();
  3000. BF_ASSERT(resolvedFieldType->mSize >= 0);
  3001. int dataSize = resolvedFieldType->mSize;
  3002. int alignSize = resolvedFieldType->mAlign;
  3003. fieldInstance->mDataSize = dataSize;
  3004. //bool needsExplicitAlignment = !isCRepr || resolvedFieldType->NeedsExplicitAlignment();
  3005. int nextDataPos = dataPos;
  3006. if (!isPacked)
  3007. nextDataPos = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  3008. int padding = nextDataPos - dataPos;
  3009. if ((alignSize > 1) && (needsExplicitAlignment) && (padding > 0))
  3010. {
  3011. curFieldDataIdx++;
  3012. }
  3013. dataPos = nextDataPos;
  3014. fieldInstance->mDataOffset = dataPos;
  3015. fieldInstance->mDataIdx = curFieldDataIdx++;
  3016. if (!isPacked)
  3017. typeInstance->mInstAlign = std::max(typeInstance->mInstAlign, alignSize);
  3018. dataPos += dataSize;
  3019. }
  3020. if (unionInnerType != NULL)
  3021. {
  3022. dataPos = unionInnerType->mSize;
  3023. typeInstance->mInstAlign = BF_MAX(unionInnerType->mAlign, typeInstance->mInstAlign);
  3024. }
  3025. // Old dataMemberHash location
  3026. CheckMemberNames(typeInstance);
  3027. if (alignOverride > 0)
  3028. typeInstance->mInstAlign = alignOverride;
  3029. else if (isPacked)
  3030. typeInstance->mInstAlign = 1;
  3031. else
  3032. typeInstance->mInstAlign = std::max(1, typeInstance->mInstAlign);
  3033. int alignSize = typeInstance->mInstAlign;
  3034. if (isCRepr)
  3035. {
  3036. // Align size to alignment
  3037. if (alignSize >= 1)
  3038. typeInstance->mInstSize = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  3039. typeInstance->mIsCRepr = true;
  3040. }
  3041. else
  3042. {
  3043. typeInstance->mInstSize = dataPos;
  3044. typeInstance->mIsCRepr = false;
  3045. }
  3046. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  3047. {
  3048. for (auto propDef : typeInstance->mTypeDef->mProperties)
  3049. if (propDef->mFieldDeclaration != NULL)
  3050. mCompiler->mResolvePassData->mAutoComplete->CheckProperty(BfNodeDynCast<BfPropertyDeclaration>(propDef->mFieldDeclaration));
  3051. }
  3052. }
  3053. if (typeInstance->IsObjectOrInterface())
  3054. typeInstance->mWantsGCMarking = true;
  3055. if ((mCompiler->mOptions.mEnableRealtimeLeakCheck) && (!typeInstance->mWantsGCMarking))
  3056. {
  3057. typeInstance->mTypeDef->PopulateMemberSets();
  3058. BfMemberSetEntry* entry = NULL;
  3059. BfMethodDef* methodDef = NULL;
  3060. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  3061. {
  3062. methodDef = (BfMethodDef*)entry->mMemberDef;
  3063. if (methodDef->HasBody())
  3064. typeInstance->mWantsGCMarking = true;
  3065. }
  3066. }
  3067. if (typeInstance->IsValueType())
  3068. {
  3069. typeInstance->mSize = typeInstance->mInstSize;
  3070. typeInstance->mAlign = typeInstance->mInstAlign;
  3071. }
  3072. if ((mCompiler->mOptions.mAllowHotSwapping) && (typeInstance->mDefineState < BfTypeDefineState_Defined))
  3073. {
  3074. if (typeInstance->mHotTypeData == NULL)
  3075. {
  3076. typeInstance->mHotTypeData = new BfHotTypeData();
  3077. BfLogSysM("Created HotTypeData %p created for type %p in DoPopulateType\n", typeInstance->mHotTypeData, typeInstance);
  3078. }
  3079. // Clear any unused versions (if we have errors, etc)
  3080. if (mCompiler->mHotState != NULL)
  3081. typeInstance->mHotTypeData->ClearVersionsAfter(mCompiler->mHotState->mCommittedHotCompileIdx);
  3082. else
  3083. BF_ASSERT(typeInstance->mHotTypeData->mTypeVersions.IsEmpty()); // We should have created a new HotTypeData when rebuilding the type
  3084. BfHotTypeVersion* hotTypeVersion = new BfHotTypeVersion();
  3085. hotTypeVersion->mTypeId = typeInstance->mTypeId;
  3086. if (typeInstance->mBaseType != NULL)
  3087. {
  3088. if (typeInstance->mBaseType->mHotTypeData != NULL)
  3089. hotTypeVersion->mBaseType = typeInstance->mBaseType->mHotTypeData->GetLatestVersion();
  3090. else
  3091. {
  3092. AssertErrorState();
  3093. }
  3094. }
  3095. hotTypeVersion->mDeclHotCompileIdx = mCompiler->mOptions.mHotCompileIdx;
  3096. if (mCompiler->IsHotCompile())
  3097. hotTypeVersion->mCommittedHotCompileIdx = -1;
  3098. else
  3099. hotTypeVersion->mCommittedHotCompileIdx = 0;
  3100. hotTypeVersion->mRefCount++;
  3101. typeInstance->mHotTypeData->mTypeVersions.Add(hotTypeVersion);
  3102. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType->mHotTypeData != NULL))
  3103. {
  3104. hotTypeVersion->mMembers.Add(typeInstance->mBaseType->mHotTypeData->GetLatestVersion());
  3105. }
  3106. for (auto& fieldInst : typeInstance->mFieldInstances)
  3107. {
  3108. auto fieldDef = fieldInst.GetFieldDef();
  3109. if ((fieldDef == NULL) || (fieldDef->mIsStatic))
  3110. continue;
  3111. auto depType = fieldInst.mResolvedType;
  3112. while (depType->IsSizedArray())
  3113. depType = ((BfSizedArrayType*)depType)->mElementType;
  3114. if (depType->IsStruct())
  3115. {
  3116. PopulateType(depType);
  3117. auto depTypeInst = depType->ToTypeInstance();
  3118. BF_ASSERT(depTypeInst->mHotTypeData != NULL);
  3119. if (depTypeInst->mHotTypeData != NULL)
  3120. hotTypeVersion->mMembers.Add(depTypeInst->mHotTypeData->GetLatestVersion());
  3121. }
  3122. }
  3123. for (auto member : hotTypeVersion->mMembers)
  3124. member->mRefCount++;
  3125. BfLogSysM("BfHotTypeVersion %p created for type %p\n", hotTypeVersion, typeInstance);
  3126. }
  3127. typeInstance->mDefineState = BfTypeDefineState_Defined;
  3128. if (typeInstance->mTypeFailed)
  3129. mHadBuildError = true;
  3130. CheckAddFailType();
  3131. BfLogSysM("Setting mNeedsMethodProcessing on %p\n", typeInstance);
  3132. typeInstance->mNeedsMethodProcessing = true;
  3133. typeInstance->mIsFinishingType = false;
  3134. ///
  3135. // 'Splattable' means that we can be passed via 3 or fewer primitive/pointer values
  3136. if (typeInstance->mHasUnderlyingArray)
  3137. {
  3138. // Never splat
  3139. }
  3140. else if (typeInstance->IsStruct())
  3141. {
  3142. bool hadNonSplattable = false;
  3143. if (typeInstance->mBaseType != NULL)
  3144. PopulateType(typeInstance->mBaseType, BfPopulateType_Data);
  3145. if ((typeInstance->mBaseType == NULL) || (typeInstance->mBaseType->IsSplattable()))
  3146. {
  3147. int dataCount = 0;
  3148. std::function<void(BfType*)> splatIterate;
  3149. splatIterate = [&](BfType* checkType)
  3150. {
  3151. if (checkType->IsValueType())
  3152. PopulateType(checkType, BfPopulateType_Data);
  3153. if (checkType->IsMethodRef())
  3154. {
  3155. // For simplicity, any methodRef inside a struct makes the struct non-splattable. This reduces cases of needing to
  3156. // handle embedded methodRefs
  3157. hadNonSplattable = true;
  3158. }
  3159. else if (checkType->IsStruct())
  3160. {
  3161. auto checkTypeInstance = checkType->ToTypeInstance();
  3162. if (checkTypeInstance->mBaseType != NULL)
  3163. splatIterate(checkTypeInstance->mBaseType);
  3164. if (checkTypeInstance->mIsUnion)
  3165. {
  3166. bool wantSplat = false;
  3167. auto unionInnerType = checkTypeInstance->GetUnionInnerType(&wantSplat);
  3168. if (!wantSplat)
  3169. hadNonSplattable = true;
  3170. splatIterate(unionInnerType);
  3171. if (checkTypeInstance->IsEnum())
  3172. dataCount++; // Discriminator
  3173. }
  3174. else
  3175. {
  3176. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  3177. {
  3178. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  3179. if (fieldInstance->mDataIdx >= 0)
  3180. splatIterate(fieldInstance->GetResolvedType());
  3181. }
  3182. }
  3183. }
  3184. else if (!checkType->IsValuelessType())
  3185. {
  3186. if (checkType->IsSizedArray())
  3187. hadNonSplattable = true;
  3188. dataCount += checkType->GetSplatCount();
  3189. }
  3190. };
  3191. splatIterate(typeInstance);
  3192. if (isCRepr)
  3193. {
  3194. typeInstance->mIsSplattable = false;
  3195. }
  3196. else
  3197. typeInstance->mIsSplattable = (dataCount <= 3) && (!hadNonSplattable);
  3198. }
  3199. }
  3200. if (typeInstance->IsTypedPrimitive())
  3201. typeInstance->mIsSplattable = true;
  3202. BF_ASSERT(mContext->mCurTypeState == &typeState);
  3203. // This is only required for autocomplete and finding type references
  3204. if (!typeInstance->IsSpecializedType())
  3205. {
  3206. for (auto propDef : typeDef->mProperties)
  3207. {
  3208. if (propDef->mTypeRef == NULL)
  3209. continue;
  3210. BfTypeState typeState;
  3211. typeState.mPrevState = mContext->mCurTypeState;
  3212. typeState.mCurTypeDef = propDef->mDeclaringType;
  3213. typeState.mTypeInstance = typeInstance;
  3214. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3215. ResolveTypeRef(propDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowRef);
  3216. }
  3217. }
  3218. // Const handling
  3219. {
  3220. Dictionary<int64, BfFieldDef*> valueMap;
  3221. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  3222. {
  3223. auto fieldInstance = &fieldInstanceRef;
  3224. if (!fieldInstance->mFieldIncluded)
  3225. continue;
  3226. auto fieldDef = fieldInstance->GetFieldDef();
  3227. if (fieldDef == NULL)
  3228. continue;
  3229. if ((fieldInstance->mConstIdx == -1) && (fieldDef->mIsConst))
  3230. {
  3231. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, fieldDef);
  3232. typeInstance->mModule->ResolveConstField(typeInstance, fieldInstance, fieldDef);
  3233. // Check enum cases for duplicates
  3234. if (mCurTypeInstance->IsEnum())
  3235. {
  3236. auto underlyingType = fieldInstance->mResolvedType->GetUnderlyingType();
  3237. if ((fieldDef->IsEnumCaseEntry()) && (fieldInstance->mConstIdx != -1) && (underlyingType->IsIntegral()))
  3238. {
  3239. auto foreignConst = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  3240. BfFieldDef** fieldDefPtr;
  3241. if (valueMap.TryAdd(foreignConst->mInt64, NULL, &fieldDefPtr))
  3242. {
  3243. *fieldDefPtr = fieldDef;
  3244. }
  3245. else if ((typeInstance->mCustomAttributes == NULL) || (typeInstance->mCustomAttributes->Get(mCompiler->mAllowDuplicatesAttributeTypeDef) == NULL))
  3246. {
  3247. auto error = Warn(0, StrFormat("Enum value '%lld' for field '%s' is not unique. Considering adding [AllowDuplicates] to the type declaration.", foreignConst->mInt64, fieldDef->mName.c_str()), fieldDef->GetRefNode(), true);
  3248. if (error != NULL)
  3249. mCompiler->mPassInstance->MoreInfo(StrFormat("This value was previously used for field '%s'", (*fieldDefPtr)->mName.c_str()), (*fieldDefPtr)->GetRefNode());
  3250. }
  3251. }
  3252. }
  3253. }
  3254. }
  3255. }
  3256. if ((typeInstance->IsEnum()) && (!typeInstance->IsPayloadEnum()))
  3257. {
  3258. BfLogSysM("Setting underlying type %p %d\n", typeInstance, underlyingTypeDeferred);
  3259. }
  3260. if (typeInstance->IsEnum())
  3261. {
  3262. int64 min = 0;
  3263. int64 max = 0;
  3264. bool isFirst = false;
  3265. if (typeInstance->mTypeInfoEx == NULL)
  3266. typeInstance->mTypeInfoEx = new BfTypeInfoEx();
  3267. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  3268. {
  3269. auto fieldInstance = &fieldInstanceRef;
  3270. auto fieldDef = fieldInstance->GetFieldDef();
  3271. if ((fieldDef != NULL) && (fieldDef->IsEnumCaseEntry()))
  3272. {
  3273. if (fieldInstance->mConstIdx == -1)
  3274. continue;
  3275. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  3276. BF_ASSERT((constant->mTypeCode == BfTypeCode_Int64) || (!underlyingTypeDeferred));
  3277. if (isFirst)
  3278. {
  3279. min = constant->mInt64;
  3280. max = constant->mInt64;
  3281. isFirst = false;
  3282. }
  3283. else
  3284. {
  3285. min = BF_MIN(constant->mInt64, min);
  3286. max = BF_MAX(constant->mInt64, max);
  3287. }
  3288. }
  3289. }
  3290. typeInstance->mTypeInfoEx->mMinValue = min;
  3291. typeInstance->mTypeInfoEx->mMaxValue = max;
  3292. if (underlyingTypeDeferred)
  3293. {
  3294. BfTypeCode typeCode;
  3295. if ((min >= -0x80) && (max <= 0x7F))
  3296. typeCode = BfTypeCode_Int8;
  3297. else if ((min >= 0) && (max <= 0xFF))
  3298. typeCode = BfTypeCode_UInt8;
  3299. else if ((min >= -0x8000) && (max <= 0x7FFF))
  3300. typeCode = BfTypeCode_Int16;
  3301. else if ((min >= 0) && (max <= 0xFFFF))
  3302. typeCode = BfTypeCode_UInt16;
  3303. else if ((min >= -0x80000000LL) && (max <= 0x7FFFFFFF))
  3304. typeCode = BfTypeCode_Int32;
  3305. else if ((min >= 0) && (max <= 0xFFFFFFFFLL))
  3306. typeCode = BfTypeCode_UInt32;
  3307. else
  3308. typeCode = BfTypeCode_Int64;
  3309. if (typeCode != BfTypeCode_Int64)
  3310. {
  3311. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  3312. {
  3313. auto fieldInstance = &fieldInstanceRef;
  3314. if (fieldInstance->mConstIdx == -1)
  3315. continue;
  3316. if (!fieldInstance->GetFieldDef()->IsEnumCaseEntry())
  3317. continue;
  3318. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  3319. BfIRValue newConstant = typeInstance->mConstHolder->CreateConst(typeCode, constant->mUInt64);
  3320. fieldInstance->mConstIdx = newConstant.mId;
  3321. }
  3322. }
  3323. underlyingType = GetPrimitiveType(typeCode);
  3324. auto fieldInstance = &typeInstance->mFieldInstances.back();
  3325. fieldInstance->mResolvedType = underlyingType;
  3326. fieldInstance->mDataSize = underlyingType->mSize;
  3327. typeInstance->mTypeInfoEx->mUnderlyingType = underlyingType;
  3328. typeInstance->mSize = underlyingType->mSize;
  3329. typeInstance->mAlign = underlyingType->mAlign;
  3330. typeInstance->mInstSize = underlyingType->mSize;
  3331. typeInstance->mInstAlign = underlyingType->mAlign;
  3332. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags & ~BfTypeRebuildFlag_UnderlyingTypeDeferred);
  3333. }
  3334. }
  3335. else
  3336. {
  3337. BF_ASSERT(!underlyingTypeDeferred);
  3338. }
  3339. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  3340. {
  3341. int lastTagId = -1;
  3342. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  3343. {
  3344. auto fieldInstance = &fieldInstanceRef;
  3345. auto fieldDef = fieldInstance->GetFieldDef();
  3346. if ((fieldDef != NULL) && (fieldInstance->mDataIdx < 0))
  3347. lastTagId = -fieldInstance->mDataIdx - 1;
  3348. }
  3349. auto fieldInstance = &typeInstance->mFieldInstances.back();
  3350. BF_ASSERT(fieldInstance->mResolvedType == NULL);
  3351. BfPrimitiveType* discriminatorType;
  3352. if (lastTagId > 0x7FFFFFFF) // HOW?
  3353. discriminatorType = GetPrimitiveType(BfTypeCode_Int64);
  3354. else if (lastTagId > 0x7FFF)
  3355. discriminatorType = GetPrimitiveType(BfTypeCode_Int32);
  3356. else if (lastTagId > 0x7F)
  3357. discriminatorType = GetPrimitiveType(BfTypeCode_Int16);
  3358. else
  3359. discriminatorType = GetPrimitiveType(BfTypeCode_Int8);
  3360. fieldInstance->mResolvedType = discriminatorType;
  3361. fieldInstance->mDataOffset = unionInnerType->mSize;
  3362. fieldInstance->mDataIdx = 2; // 0 = base, 1 = payload, 2 = discriminator
  3363. if (!isPacked)
  3364. {
  3365. if ((fieldInstance->mDataOffset % discriminatorType->mAlign) != 0)
  3366. {
  3367. fieldInstance->mDataOffset = BF_ALIGN(fieldInstance->mDataOffset, discriminatorType->mAlign);
  3368. fieldInstance->mDataIdx++; // Add room for explicit padding
  3369. }
  3370. }
  3371. typeInstance->mAlign = BF_MAX(unionInnerType->mAlign, discriminatorType->mAlign);
  3372. typeInstance->mSize = fieldInstance->mDataOffset + discriminatorType->mSize;
  3373. typeInstance->mInstSize = typeInstance->mSize;
  3374. typeInstance->mInstAlign = typeInstance->mAlign;
  3375. dataMemberHashCtx.Mixin(unionInnerType->mTypeId);
  3376. dataMemberHashCtx.Mixin(discriminatorType->mTypeId);
  3377. typeInstance->mMergedFieldDataCount = 1; // Track it as a single entry
  3378. }
  3379. if (!typeInstance->IsBoxed())
  3380. {
  3381. if (typeInstance->IsTypedPrimitive())
  3382. {
  3383. auto underlyingType = typeInstance->GetUnderlyingType();
  3384. dataMemberHashCtx.Mixin(underlyingType->mTypeId);
  3385. }
  3386. Val128 dataMemberHash = dataMemberHashCtx.Finish128();
  3387. if (typeInstance->mHotTypeData != NULL)
  3388. {
  3389. auto newHotTypeVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3390. newHotTypeVersion->mDataHash = dataMemberHash;
  3391. if (mCompiler->mHotState != NULL)
  3392. {
  3393. auto committedHotTypeVersion = typeInstance->mHotTypeData->GetTypeVersion(mCompiler->mHotState->mCommittedHotCompileIdx);
  3394. if (committedHotTypeVersion != NULL)
  3395. {
  3396. if ((newHotTypeVersion->mDataHash != committedHotTypeVersion->mDataHash) && (typeInstance->mIsReified))
  3397. {
  3398. BfLogSysM("Hot compile detected data changes in %p '%s'\n", resolvedTypeRef, TypeToString(typeInstance).c_str());
  3399. if (!typeInstance->mHotTypeData->mPendingDataChange)
  3400. {
  3401. mCompiler->mHotState->mPendingDataChanges.Add(typeInstance->mTypeId);
  3402. typeInstance->mHotTypeData->mPendingDataChange = true;
  3403. }
  3404. else
  3405. {
  3406. BF_ASSERT(mCompiler->mHotState->mPendingDataChanges.Contains(typeInstance->mTypeId));
  3407. }
  3408. bool baseHadChanges = (typeInstance->mBaseType != NULL) && (typeInstance->mBaseType->mHotTypeData != NULL) && (typeInstance->mBaseType->mHotTypeData->mPendingDataChange);
  3409. if (!baseHadChanges)
  3410. Warn(0, StrFormat("Hot compile detected data changes in '%s'", TypeToString(typeInstance).c_str()), typeDef->GetRefNode());
  3411. }
  3412. else if (typeInstance->mHotTypeData->mPendingDataChange)
  3413. {
  3414. BfLogSysM("Hot compile removed pending data change for %p '%s'\n", resolvedTypeRef, TypeToString(typeInstance).c_str());
  3415. mCompiler->mHotState->RemovePendingChanges(typeInstance);
  3416. }
  3417. }
  3418. }
  3419. }
  3420. }
  3421. if (typeInstance == mContext->mBfObjectType)
  3422. typeInstance->mHasBeenInstantiated = true;
  3423. auto _HandleTypeDeclaration = [&](BfTypeDeclaration* typeDeclaration)
  3424. {
  3425. if ((typeDeclaration != NULL) && (typeDeclaration->mNameNode != NULL))
  3426. {
  3427. auto typeRefSource = typeDeclaration->mNameNode->GetParserData();
  3428. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (typeRefSource != NULL) && (typeRefSource == mCompiler->mResolvePassData->mParser->mSourceData))
  3429. {
  3430. BfSourceElementType elemType = BfSourceElementType_Type;
  3431. if (typeInstance->IsInterface())
  3432. elemType = BfSourceElementType_Interface;
  3433. else if (typeInstance->IsObject())
  3434. elemType = BfSourceElementType_RefType;
  3435. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(typeDeclaration->mNameNode, elemType);
  3436. }
  3437. }
  3438. };
  3439. if (!typeInstance->IsBoxed())
  3440. {
  3441. _HandleTypeDeclaration(typeDef->mTypeDeclaration);
  3442. for (auto partial : typeDef->mPartials)
  3443. _HandleTypeDeclaration(partial->mTypeDeclaration);
  3444. }
  3445. if (typeInstance->IsGenericTypeInstance())
  3446. {
  3447. auto genericTypeInst = (BfTypeInstance*)typeInstance;
  3448. if (!genericTypeInst->mGenericTypeInfo->mFinishedGenericParams)
  3449. FinishGenericParams(resolvedTypeRef);
  3450. }
  3451. if (populateType == BfPopulateType_Data)
  3452. return;
  3453. disableYield.Release();
  3454. prevTypeState.Restore();
  3455. if (canDoMethodProcessing)
  3456. {
  3457. if (typeInstance->mNeedsMethodProcessing) // May have been handled by GetRawMethodInstanceAtIdx above
  3458. DoTypeInstanceMethodProcessing(typeInstance);
  3459. }
  3460. }
  3461. void BfModule::DoTypeInstanceMethodProcessing(BfTypeInstance* typeInstance)
  3462. {
  3463. if (typeInstance->IsSpecializedByAutoCompleteMethod())
  3464. return;
  3465. BF_ASSERT(typeInstance->mModule == this);
  3466. //TODO: This is new, make sure this is in the right place
  3467. /*if (mAwaitingInitFinish)
  3468. FinishInit();*/
  3469. AutoDisallowYield disableYield(mSystem);
  3470. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3471. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3472. BfLogSysM("DoTypeInstanceMethodProcessing: %p %s Revision:%d\n", typeInstance, TypeToString(typeInstance).c_str(), typeInstance->mRevision);
  3473. auto typeDef = typeInstance->mTypeDef;
  3474. BfTypeOptions* typeOptions = NULL;
  3475. if (typeInstance->mTypeOptionsIdx >= 0)
  3476. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  3477. // Generate all methods. Pass 0
  3478. for (auto methodDef : typeDef->mMethods)
  3479. {
  3480. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  3481. // This should still be set to the default value
  3482. BF_ASSERT((methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet) || (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude));
  3483. }
  3484. if (typeInstance == mContext->mBfObjectType)
  3485. {
  3486. BF_ASSERT(typeInstance->mInterfaceMethodTable.size() == 0);
  3487. }
  3488. int newIntefaceStartIdx = 0;
  3489. auto implBaseType = typeInstance->GetImplBaseType();
  3490. if (implBaseType != NULL)
  3491. {
  3492. auto baseTypeInst = implBaseType->ToTypeInstance();
  3493. if (implBaseType->IsIncomplete())
  3494. PopulateType(implBaseType, BfPopulateType_Full_Force);
  3495. typeInstance->mInterfaceMethodTable = baseTypeInst->mInterfaceMethodTable;
  3496. typeInstance->mVirtualMethodTable = implBaseType->mVirtualMethodTable;
  3497. typeInstance->mVirtualMethodTableSize = implBaseType->mVirtualMethodTableSize;
  3498. if ((!mCompiler->IsHotCompile()) && (!mCompiler->mPassInstance->HasFailed()) && ((mCompiler->mResolvePassData == NULL) || (mCompiler->mResolvePassData->mAutoComplete == NULL)))
  3499. {
  3500. BF_ASSERT(typeInstance->mVirtualMethodTable.size() == typeInstance->mVirtualMethodTableSize);
  3501. }
  3502. else
  3503. {
  3504. BF_ASSERT(typeInstance->mVirtualMethodTableSize >= (int)typeInstance->mVirtualMethodTable.size());
  3505. }
  3506. }
  3507. // Add new interfaces
  3508. for (int iFaceIdx = 0; iFaceIdx < (int)typeInstance->mInterfaces.size(); iFaceIdx++)
  3509. {
  3510. BfTypeInterfaceEntry& typeInterfaceInst = typeInstance->mInterfaces[iFaceIdx];
  3511. auto checkInterface = typeInterfaceInst.mInterfaceType;
  3512. if (checkInterface->IsIncomplete())
  3513. PopulateType(checkInterface, BfPopulateType_Full_Force);
  3514. typeInterfaceInst.mStartInterfaceTableIdx = (int)typeInstance->mInterfaceMethodTable.size();
  3515. // We don't add to the vtable for interface declarations, we just reference the listed interfaces
  3516. if (!typeInstance->IsInterface())
  3517. {
  3518. auto interfaceTypeDef = checkInterface->mTypeDef;
  3519. BF_ASSERT(interfaceTypeDef->mMethods.size() == checkInterface->mMethodInstanceGroups.size());
  3520. // Reserve empty entries
  3521. for (int methodIdx = 0; methodIdx < (int)interfaceTypeDef->mMethods.size(); methodIdx++)
  3522. typeInstance->mInterfaceMethodTable.push_back(BfTypeInterfaceMethodEntry());
  3523. }
  3524. }
  3525. auto checkTypeInstance = typeInstance;
  3526. while (checkTypeInstance != NULL)
  3527. {
  3528. // These may have been already added
  3529. for (auto&& interfaceEntry : checkTypeInstance->mInterfaces)
  3530. AddDependency(interfaceEntry.mInterfaceType, typeInstance, BfDependencyMap::DependencyFlag_ImplementsInterface);
  3531. checkTypeInstance = checkTypeInstance->GetImplBaseType();
  3532. }
  3533. //for (auto& intefaceInst : typeInstance->mInterfaces)
  3534. if (typeInstance == mContext->mBfObjectType)
  3535. {
  3536. BF_ASSERT(typeInstance->mInterfaceMethodTable.size() == 1);
  3537. }
  3538. // Slot interfaces method blocks in vtable
  3539. {
  3540. int ifaceVirtIdx = 0;
  3541. std::unordered_map<BfTypeInstance*, BfTypeInterfaceEntry*> interfaceMap;
  3542. BfTypeInstance* checkType = typeInstance->GetImplBaseType();
  3543. while (checkType != NULL)
  3544. {
  3545. for (auto&& ifaceEntry : checkType->mInterfaces)
  3546. {
  3547. interfaceMap[ifaceEntry.mInterfaceType] = &ifaceEntry;
  3548. ifaceVirtIdx = std::max(ifaceVirtIdx, ifaceEntry.mStartVirtualIdx + ifaceEntry.mInterfaceType->mVirtualMethodTableSize);
  3549. }
  3550. checkType = checkType->GetImplBaseType();
  3551. }
  3552. for (int iFaceIdx = 0; iFaceIdx < (int)typeInstance->mInterfaces.size(); iFaceIdx++)
  3553. {
  3554. BfTypeInterfaceEntry& typeInterfaceInst = typeInstance->mInterfaces[iFaceIdx];
  3555. auto itr = interfaceMap.find(typeInterfaceInst.mInterfaceType);
  3556. if (itr != interfaceMap.end())
  3557. {
  3558. auto prevEntry = itr->second;
  3559. typeInterfaceInst.mStartVirtualIdx = prevEntry->mStartVirtualIdx;
  3560. }
  3561. else
  3562. {
  3563. typeInterfaceInst.mStartVirtualIdx = ifaceVirtIdx;
  3564. ifaceVirtIdx += typeInterfaceInst.mInterfaceType->mVirtualMethodTableSize;
  3565. interfaceMap[typeInterfaceInst.mInterfaceType] = &typeInterfaceInst;
  3566. }
  3567. }
  3568. }
  3569. auto isBoxed = typeInstance->IsBoxed();
  3570. BfLogSysM("Setting mTypeIncomplete = false on %p\n", typeInstance);
  3571. typeInstance->mNeedsMethodProcessing = false;
  3572. typeInstance->mTypeIncomplete = false;
  3573. auto checkBaseType = typeInstance->GetImplBaseType();
  3574. while (checkBaseType != NULL)
  3575. {
  3576. PopulateType(checkBaseType, BfPopulateType_Full_Force);
  3577. BF_ASSERT((!checkBaseType->IsIncomplete()) || (checkBaseType->mTypeFailed));
  3578. checkBaseType = checkBaseType->GetImplBaseType();
  3579. }
  3580. if ((mCompiler->mOptions.mHasVDataExtender) && (!typeInstance->IsInterface()))
  3581. {
  3582. // This is the vExt entry for this type instance
  3583. BfVirtualMethodEntry entry;
  3584. entry.mDeclaringMethod.mMethodNum = -1;
  3585. entry.mDeclaringMethod.mTypeInstance = typeInstance;
  3586. typeInstance->mVirtualMethodTable.push_back(entry);
  3587. typeInstance->mVirtualMethodTableSize++;
  3588. }
  3589. // Fill out to correct size
  3590. if (typeInstance->mHotTypeData != NULL)
  3591. {
  3592. //auto hotLatestVersionHead = typeInstance->mHotTypeData->GetLatestVersionHead();
  3593. int wantVTableSize = typeInstance->GetImplBaseVTableSize() + (int)typeInstance->mHotTypeData->mVTableEntries.size();
  3594. while ((int)typeInstance->mVirtualMethodTable.size() < wantVTableSize)
  3595. {
  3596. typeInstance->mVirtualMethodTable.push_back(BfVirtualMethodEntry());
  3597. typeInstance->mVirtualMethodTableSize++;
  3598. }
  3599. }
  3600. BfAmbiguityContext ambiguityContext;
  3601. ambiguityContext.mTypeInstance = typeInstance;
  3602. ambiguityContext.mModule = this;
  3603. ambiguityContext.mIsProjectSpecific = false;
  3604. bool wantsOnDemandMethods = false;
  3605. //TODO: Testing having interface methods be "on demand"...
  3606. //if (!typeInstance->IsInterface())
  3607. //
  3608. {
  3609. if (typeInstance->IsSpecializedType())
  3610. wantsOnDemandMethods = true;
  3611. else if ((mCompiler->mOptions.mCompileOnDemandKind != BfCompileOnDemandKind_AlwaysInclude) &&
  3612. (!typeInstance->IsUnspecializedTypeVariation()))
  3613. {
  3614. //if (typeDef->mName->ToString() != "AttributeUsageAttribute")
  3615. auto attributeDef = mCompiler->mAttributeTypeDef;
  3616. auto attributeType = mContext->mUnreifiedModule->ResolveTypeDef(attributeDef, BfPopulateType_Identity)->ToTypeInstance();
  3617. if (!TypeIsSubTypeOf(mCurTypeInstance, attributeType, false))
  3618. {
  3619. wantsOnDemandMethods = true;
  3620. }
  3621. }
  3622. }
  3623. //bool allDeclsRequired = (mIsReified) && (mCompiler->mOptions.mEmitDebugInfo) && ();
  3624. bool allDeclsRequired = false;
  3625. //if ((mIsReified) && (mCompiler->mOptions.mEmitDebugInfo) && (!mCompiler->mWantsDeferMethodDecls))
  3626. // if ((mIsReified) && (mCompiler->mOptions.mEmitDebugInfo))
  3627. // {
  3628. // allDeclsRequired = true;
  3629. // }
  3630. HashSet<String> ifaceMethodNameSet;
  3631. if (wantsOnDemandMethods)
  3632. {
  3633. for (int iFaceIdx = newIntefaceStartIdx; iFaceIdx < (int)typeInstance->mInterfaces.size(); iFaceIdx++)
  3634. {
  3635. BfTypeInterfaceEntry& typeInterfaceInst = typeInstance->mInterfaces[iFaceIdx];
  3636. for (auto checkMethodDef : typeInterfaceInst.mInterfaceType->mTypeDef->mMethods)
  3637. {
  3638. ifaceMethodNameSet.Add(checkMethodDef->mName);
  3639. }
  3640. }
  3641. }
  3642. bool isFailedType = mCurTypeInstance->mTypeFailed;
  3643. if (auto genericTypeInst = mCurTypeInstance->ToGenericTypeInstance())
  3644. {
  3645. if (genericTypeInst->mGenericTypeInfo->mHadValidateErrors)
  3646. isFailedType = true;
  3647. }
  3648. bool typeOptionsIncludeAll = false;
  3649. if (typeOptions != NULL)
  3650. typeOptionsIncludeAll = typeOptions->Apply(typeOptionsIncludeAll, BfOptionFlags_ReflectAlwaysIncludeAll);
  3651. // Generate all methods. Pass 1
  3652. for (auto methodDef : typeDef->mMethods)
  3653. {
  3654. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  3655. if (typeOptions != NULL)
  3656. {
  3657. BfOptionFlags optionFlags = BfOptionFlags_ReflectNonStaticMethods;
  3658. if (methodDef->mMethodType == BfMethodType_Ctor)
  3659. optionFlags = BfOptionFlags_ReflectConstructors;
  3660. else if (methodDef->mIsStatic)
  3661. optionFlags = BfOptionFlags_ReflectStaticMethods;
  3662. methodInstanceGroup->mExplicitlyReflected = typeOptions->Apply(false, optionFlags);
  3663. methodInstanceGroup->mExplicitlyReflected = ApplyTypeOptionMethodFilters(methodInstanceGroup->mExplicitlyReflected, methodDef, typeOptions);
  3664. }
  3665. if ((typeInstance->mCustomAttributes != NULL) && (typeInstance->mCustomAttributes->Contains(mCompiler->mReflectAttributeTypeDef)))
  3666. methodInstanceGroup->mExplicitlyReflected = true;
  3667. if (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude)
  3668. continue;
  3669. if (isFailedType)
  3670. {
  3671. // We don't want method decls from failed generic types to clog up our type system
  3672. continue;
  3673. }
  3674. // This should still be set to the default value
  3675. BF_ASSERT(methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet);
  3676. if ((isBoxed) && (!methodDef->mIsVirtual))
  3677. {
  3678. if (methodDef->mIsStatic)
  3679. continue;
  3680. bool boxedRequired = false;
  3681. if (((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mParams.size() == 0)) ||
  3682. (methodDef->mMethodType == BfMethodType_Dtor) ||
  3683. ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) || (methodDef->mName == BF_METHODNAME_INVOKE) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST)) ||
  3684. (methodDef->mGenericParams.size() != 0))
  3685. boxedRequired = true;
  3686. if (!boxedRequired)
  3687. {
  3688. if (wantsOnDemandMethods)
  3689. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  3690. continue;
  3691. }
  3692. }
  3693. if (methodDef->mMethodType == BfMethodType_Ignore)
  3694. continue;
  3695. if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) && (typeInstance->IsValueType()))
  3696. continue; // This is just a placeholder for boxed types
  3697. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  3698. if (wantsOnDemandMethods)
  3699. {
  3700. bool implRequired = false;
  3701. bool declRequired = false;
  3702. if ((!typeInstance->IsGenericTypeInstance()) && (methodDef->mGenericParams.IsEmpty()))
  3703. {
  3704. // For non-generic methods, declare all methods. This is useful for debug info.
  3705. declRequired = true;
  3706. }
  3707. if (methodDef->mMethodType == BfMethodType_CtorNoBody)
  3708. declRequired = true;
  3709. if ((methodDef->mIsStatic) &&
  3710. ((methodDef->mMethodType == BfMethodType_Dtor) || (methodDef->mMethodType == BfMethodType_Ctor)))
  3711. {
  3712. implRequired = true;
  3713. }
  3714. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  3715. {
  3716. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  3717. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS) ||
  3718. ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) && (typeInstance->IsObject())))
  3719. implRequired = true;
  3720. }
  3721. BfAttributeDirective* attributes = NULL;
  3722. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  3723. attributes = methodDeclaration->mAttributes;
  3724. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  3725. attributes = propertyDeclaration->mAttributes;
  3726. while (attributes != NULL)
  3727. {
  3728. if (attributes->mAttributeTypeRef != NULL)
  3729. {
  3730. auto typeRefName = attributes->mAttributeTypeRef->ToString();
  3731. if (typeRefName == "AlwaysInclude")
  3732. implRequired = true;
  3733. else if (typeRefName == "Export")
  3734. implRequired = true;
  3735. else if (typeRefName == "Test")
  3736. implRequired = true;
  3737. else
  3738. declRequired = true; // We need to create so we can check for AlwaysInclude in included attributes
  3739. }
  3740. attributes = attributes->mNextAttribute;
  3741. }
  3742. if ((mProject != NULL) && (mProject->mAlwaysIncludeAll) && (methodDef->mBody != NULL))
  3743. {
  3744. implRequired = true;
  3745. declRequired = true;
  3746. }
  3747. if (typeInstance->mIncludeAllMethods)
  3748. implRequired = true;
  3749. if ((typeOptionsIncludeAll) && (ApplyTypeOptionMethodFilters(true, methodDef, typeOptions)))
  3750. implRequired = true;
  3751. // if ((typeOptions != NULL) && (CheckTypeOptionMethodFilters(typeOptions, methodDef)))
  3752. // implRequired = true;
  3753. if (typeInstance->IsInterface())
  3754. declRequired = true;
  3755. if (methodDef->mIsVirtual)
  3756. declRequired = true;
  3757. if (!implRequired)
  3758. {
  3759. // Any interface with the same name causes us to not be on-demand
  3760. if (ifaceMethodNameSet.Contains(methodDef->mName))
  3761. declRequired = true;
  3762. }
  3763. // Is this strictly necessary? It will reduce our compilation speed in order to ensure methods are available for debug info
  3764. if (allDeclsRequired)
  3765. declRequired = true;
  3766. if (methodDef->mMethodDeclaration == NULL)
  3767. {
  3768. // Internal methods don't need decls
  3769. if ((methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS) ||
  3770. (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS))
  3771. declRequired = false;
  3772. }
  3773. if (methodDef->mMethodType == BfMethodType_Init)
  3774. {
  3775. declRequired = false;
  3776. implRequired = false;
  3777. }
  3778. if (!implRequired)
  3779. {
  3780. if (!mIsScratchModule)
  3781. mOnDemandMethodCount++;
  3782. if (!declRequired)
  3783. {
  3784. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  3785. continue;
  3786. }
  3787. else
  3788. {
  3789. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  3790. }
  3791. }
  3792. }
  3793. }
  3794. BfLogSysM("Starting DoTypeInstanceMethodProcessing %p GetMethodInstance pass. OnDemandMethods: %d\n", typeInstance, mOnDemandMethodCount);
  3795. // Def passes. First non-overrides then overrides (for in-place overrides in methods)
  3796. for (int pass = 0; pass < 2; pass++)
  3797. {
  3798. for (auto methodDef : typeDef->mMethods)
  3799. {
  3800. if ((pass == 1) != (methodDef->mIsOverride))
  3801. continue;
  3802. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  3803. if ((methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  3804. (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Decl_AwaitingDecl))
  3805. {
  3806. BfLogSysM("Skipping GetMethodInstance on MethodDef: %p OnDemandKind: %d\n", methodDef, methodInstanceGroup->mOnDemandKind);
  3807. continue;
  3808. }
  3809. if (methodDef->mMethodType == BfMethodType_Init)
  3810. continue;
  3811. int prevWorklistSize = (int)mContext->mMethodWorkList.size();
  3812. auto moduleMethodInstance = GetMethodInstance(typeInstance, methodDef, BfTypeVector(), ((methodDef->mGenericParams.size() != 0) || (typeInstance->IsUnspecializedType())) ? BfGetMethodInstanceFlag_UnspecializedPass : BfGetMethodInstanceFlag_None);
  3813. auto methodInstance = moduleMethodInstance.mMethodInstance;
  3814. if (methodInstance == NULL)
  3815. {
  3816. BF_ASSERT(typeInstance->IsGenericTypeInstance() && (typeInstance->mTypeDef->mIsCombinedPartial));
  3817. continue;
  3818. }
  3819. if ((!mCompiler->mIsResolveOnly) &&
  3820. ((methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) || (!typeInstance->IsReified())))
  3821. {
  3822. bool forceMethodImpl = false;
  3823. BfCustomAttributes* customAttributes = methodInstance->GetCustomAttributes();
  3824. if ((customAttributes != NULL) && (typeInstance->IsReified()))
  3825. {
  3826. for (auto& attr : customAttributes->mAttributes)
  3827. {
  3828. auto attrTypeInst = attr.mType->ToTypeInstance();
  3829. auto attrCustomAttributes = attrTypeInst->mCustomAttributes;
  3830. if (attrCustomAttributes == NULL)
  3831. continue;
  3832. for (auto& attrAttr : attrCustomAttributes->mAttributes)
  3833. {
  3834. if (attrAttr.mType->ToTypeInstance()->mTypeDef == mCompiler->mAttributeUsageAttributeTypeDef)
  3835. {
  3836. // Check for Flags arg
  3837. if (attrAttr.mCtorArgs.size() < 2)
  3838. continue;
  3839. auto constant = attrTypeInst->mConstHolder->GetConstant(attrAttr.mCtorArgs[1]);
  3840. if (constant == NULL)
  3841. continue;
  3842. if (constant->mTypeCode == BfTypeCode_Boolean)
  3843. continue;
  3844. if ((constant->mInt8 & BfCustomAttributeFlags_AlwaysIncludeTarget) != 0)
  3845. forceMethodImpl = true;
  3846. }
  3847. }
  3848. }
  3849. }
  3850. if (typeInstance->mTypeDef->mProject->mTargetType == BfTargetType_BeefTest)
  3851. {
  3852. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mTestAttributeTypeDef)))
  3853. {
  3854. forceMethodImpl = true;
  3855. }
  3856. }
  3857. if (forceMethodImpl)
  3858. {
  3859. if (!typeInstance->IsReified())
  3860. mContext->mScratchModule->PopulateType(typeInstance, BfPopulateType_Data);
  3861. // Reify method
  3862. mContext->mScratchModule->GetMethodInstance(typeInstance, methodDef, BfTypeVector());
  3863. BF_ASSERT(methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Decl_AwaitingReference);
  3864. }
  3865. }
  3866. bool methodUsedVirtually = false;
  3867. if (typeInstance->IsInterface())
  3868. {
  3869. if ((!methodDef->mIsConcrete) && (!methodDef->mIsStatic) && (!methodInstance->HasSelf()))
  3870. SlotInterfaceMethod(methodInstance);
  3871. }
  3872. else if (!methodDef->IsEmptyPartial())
  3873. {
  3874. methodUsedVirtually = SlotVirtualMethod(methodInstance, &ambiguityContext);
  3875. }
  3876. // This is important for reducing latency of autocomplete popup, but it's important we don't allow the autocomplete
  3877. // thread to cause any reentry issues by re-populating a type at an "inopportune time". We do allow certain
  3878. // reentries in PopulateType, but not when we're resolving fields (for example)
  3879. if ((mContext->mFieldResolveReentrys.size() == 0) && (!mContext->mResolvingVarField))
  3880. {
  3881. disableYield.Release();
  3882. mSystem->CheckLockYield();
  3883. disableYield.Acquire();
  3884. }
  3885. }
  3886. }
  3887. BF_ASSERT(typeInstance->mVirtualMethodTable.size() == typeInstance->mVirtualMethodTableSize);
  3888. if ((isBoxed) && (!typeInstance->IsUnspecializedTypeVariation()))
  3889. {
  3890. // Any interface method that can be called virtually via an interface pointer needs to go into the boxed type
  3891. auto underlyingType = typeInstance->GetUnderlyingType();
  3892. BfTypeInstance* underlyingTypeInstance;
  3893. if (underlyingType->IsPrimitiveType())
  3894. underlyingTypeInstance = GetPrimitiveStructType(((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode);
  3895. else
  3896. underlyingTypeInstance = underlyingType->ToTypeInstance();
  3897. if (underlyingTypeInstance != NULL)
  3898. {
  3899. PopulateType(underlyingTypeInstance, BfPopulateType_Full_Force);
  3900. for (int ifaceIdx = 0; ifaceIdx < (int)underlyingTypeInstance->mInterfaces.size(); ifaceIdx++)
  3901. {
  3902. auto& underlyingIFaceTypeInst = underlyingTypeInstance->mInterfaces[ifaceIdx];
  3903. auto& boxedIFaceTypeInst = typeInstance->mInterfaces[ifaceIdx];
  3904. BF_ASSERT(underlyingIFaceTypeInst.mInterfaceType == boxedIFaceTypeInst.mInterfaceType);
  3905. auto ifaceInst = underlyingIFaceTypeInst.mInterfaceType;
  3906. int startIdx = underlyingIFaceTypeInst.mStartInterfaceTableIdx;
  3907. int boxedStartIdx = boxedIFaceTypeInst.mStartInterfaceTableIdx;
  3908. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  3909. for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  3910. {
  3911. auto matchedMethodRef = &underlyingTypeInstance->mInterfaceMethodTable[iMethodIdx + startIdx].mMethodRef;
  3912. auto boxedMatchedMethodRef = &typeInstance->mInterfaceMethodTable[iMethodIdx + boxedStartIdx].mMethodRef;
  3913. BfMethodInstance* matchedMethod = *matchedMethodRef;
  3914. auto ifaceMethodInst = ifaceInst->mMethodInstanceGroups[iMethodIdx].mDefault;
  3915. if (ifaceMethodInst->mVirtualTableIdx != -1)
  3916. {
  3917. if (matchedMethod == NULL)
  3918. {
  3919. AssertErrorState();
  3920. }
  3921. else
  3922. {
  3923. if (!matchedMethod->mIsForeignMethodDef)
  3924. {
  3925. BfMethodInstanceGroup* boxedMethodInstanceGroup = &typeInstance->mMethodInstanceGroups[matchedMethod->mMethodDef->mIdx];
  3926. if (boxedMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  3927. {
  3928. boxedMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  3929. if (!mIsScratchModule)
  3930. mOnDemandMethodCount++;
  3931. }
  3932. }
  3933. auto moduleMethodInstance = GetMethodInstance(typeInstance, matchedMethod->mMethodDef, BfTypeVector(),
  3934. matchedMethod->mIsForeignMethodDef ? BfGetMethodInstanceFlag_ForeignMethodDef : BfGetMethodInstanceFlag_None,
  3935. matchedMethod->GetForeignType());
  3936. auto methodInstance = moduleMethodInstance.mMethodInstance;
  3937. UniqueSlotVirtualMethod(methodInstance);
  3938. *boxedMatchedMethodRef = methodInstance;
  3939. }
  3940. }
  3941. }
  3942. }
  3943. }
  3944. }
  3945. if (typeInstance->mHotTypeData != NULL)
  3946. {
  3947. auto latestVersion = typeInstance->mHotTypeData->GetLatestVersion();
  3948. auto latestVersionHead = typeInstance->mHotTypeData->GetLatestVersionHead();
  3949. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  3950. {
  3951. bool hasSlotError = false;
  3952. BF_ASSERT(mCompiler->IsHotCompile());
  3953. //typeInstance->mHotTypeData->mDirty = true;
  3954. //Val128 vtHash;
  3955. Array<int> ifaceMapping;
  3956. ifaceMapping.Resize(latestVersionHead->mInterfaceMapping.size());
  3957. typeInstance->CalcHotVirtualData(&ifaceMapping);
  3958. // Hot swapping allows for interfaces to be added to types or removed from types, but it doesn't allow
  3959. // interfaces to be added when the slot number has already been used -- even if the interface using
  3960. // that slot has been removed.
  3961. for (int slotIdx = 0; slotIdx < (int)ifaceMapping.size(); slotIdx++)
  3962. {
  3963. int newId = ifaceMapping[slotIdx];
  3964. int oldId = 0;
  3965. if (slotIdx < (int)latestVersionHead->mInterfaceMapping.size())
  3966. oldId = latestVersionHead->mInterfaceMapping[slotIdx];
  3967. if ((newId != oldId) && (newId != 0) && (oldId != 0))
  3968. {
  3969. String interfaceName;
  3970. for (auto iface : typeInstance->mInterfaces)
  3971. {
  3972. if (iface.mInterfaceType->mTypeId == newId)
  3973. interfaceName = TypeToString(iface.mInterfaceType);
  3974. }
  3975. Warn(0, StrFormat("Hot swap detected resolvable interface slot collision with '%s'.", interfaceName.c_str()), typeDef->mTypeDeclaration);
  3976. BF_ASSERT(latestVersion != latestVersionHead);
  3977. if (!hasSlotError)
  3978. {
  3979. latestVersion->mInterfaceMapping = ifaceMapping;
  3980. }
  3981. hasSlotError = true;
  3982. }
  3983. else if (hasSlotError)
  3984. {
  3985. if (oldId != 0)
  3986. latestVersion->mInterfaceMapping[slotIdx] = oldId;
  3987. }
  3988. if (oldId != 0)
  3989. ifaceMapping[slotIdx] = oldId;
  3990. }
  3991. latestVersionHead->mInterfaceMapping = ifaceMapping;
  3992. if (hasSlotError)
  3993. mCompiler->mHotState->mPendingFailedSlottings.Add(typeInstance->mTypeId);
  3994. else
  3995. mCompiler->mHotState->mPendingFailedSlottings.Remove(typeInstance->mTypeId);
  3996. }
  3997. }
  3998. if ((typeInstance->IsInterface()) && (!typeInstance->IsUnspecializedType()) && (typeInstance->mIsReified) && (typeInstance->mSlotNum == -1) && (mCompiler->IsHotCompile()))
  3999. {
  4000. mCompiler->mHotState->mHasNewInterfaceTypes = true;
  4001. }
  4002. if ((!typeInstance->IsInterface()) && (!typeInstance->IsUnspecializedTypeVariation()) && (!isBoxed) && (!isFailedType))
  4003. {
  4004. if (!typeInstance->mTypeDef->mIsAbstract)
  4005. {
  4006. for (int methodIdx = 0; methodIdx < (int) typeInstance->mVirtualMethodTable.size(); methodIdx++)
  4007. {
  4008. auto& methodRef = typeInstance->mVirtualMethodTable[methodIdx].mImplementingMethod;
  4009. if (methodRef.mMethodNum == -1)
  4010. {
  4011. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  4012. if (methodRef.mTypeInstance == typeInstance)
  4013. {
  4014. if (typeInstance->GetImplBaseType() != NULL)
  4015. BF_ASSERT(methodIdx == (int)typeInstance->GetImplBaseType()->mVirtualMethodTableSize);
  4016. }
  4017. continue;
  4018. }
  4019. auto methodInstance = (BfMethodInstance*)methodRef;
  4020. if ((methodInstance != NULL) && (methodInstance->mMethodDef->mIsAbstract))
  4021. {
  4022. if (methodInstance->mMethodDef->mIsAbstract)
  4023. {
  4024. if (!typeInstance->IsUnspecializedTypeVariation())
  4025. {
  4026. if (Fail(StrFormat("'%s' does not implement inherited abstract method '%s'", TypeToString(typeInstance).c_str(), MethodToString(methodInstance).c_str()), typeDef->mTypeDeclaration->mNameNode, true) != NULL)
  4027. mCompiler->mPassInstance->MoreInfo("Abstract method declared", methodInstance->mMethodDef->GetRefNode());
  4028. }
  4029. }
  4030. else
  4031. {
  4032. if (!typeInstance->IsUnspecializedType())
  4033. AssertErrorState();
  4034. }
  4035. }
  4036. }
  4037. }
  4038. std::unordered_set<String> missingIFaceMethodNames;
  4039. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  4040. {
  4041. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  4042. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  4043. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  4044. auto declTypeDef = ifaceTypeInst.mDeclaringType;
  4045. for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  4046. {
  4047. auto matchedMethodRef = &typeInstance->mInterfaceMethodTable[iMethodIdx + startIdx].mMethodRef;
  4048. BfMethodInstance* matchedMethod = *matchedMethodRef;
  4049. auto ifaceMethodInst = ifaceInst->mMethodInstanceGroups[iMethodIdx].mDefault;
  4050. if ((matchedMethod == NULL) && (ifaceMethodInst != NULL))
  4051. {
  4052. missingIFaceMethodNames.insert(ifaceMethodInst->mMethodDef->mName);
  4053. }
  4054. }
  4055. }
  4056. if (!missingIFaceMethodNames.empty())
  4057. {
  4058. // Attempt to find matching entries in base types
  4059. ambiguityContext.mIsReslotting = true;
  4060. auto checkType = typeInstance->GetImplBaseType();
  4061. while (checkType != NULL)
  4062. {
  4063. for (auto& methodGroup : checkType->mMethodInstanceGroups)
  4064. {
  4065. auto methodInstance = methodGroup.mDefault;
  4066. if (methodInstance != NULL)
  4067. {
  4068. if ((methodInstance->mMethodDef->mProtection != BfProtection_Private) &&
  4069. (!methodInstance->mMethodDef->mIsOverride) &&
  4070. (missingIFaceMethodNames.find(methodInstance->mMethodDef->mName) != missingIFaceMethodNames.end()))
  4071. {
  4072. SlotVirtualMethod(methodInstance, &ambiguityContext);
  4073. }
  4074. }
  4075. }
  4076. checkType = checkType->GetImplBaseType();
  4077. }
  4078. }
  4079. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  4080. {
  4081. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  4082. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  4083. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  4084. auto declTypeDef = ifaceTypeInst.mDeclaringType;
  4085. for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  4086. {
  4087. auto matchedMethodRef = &typeInstance->mInterfaceMethodTable[iMethodIdx + startIdx].mMethodRef;
  4088. BfMethodInstance* matchedMethod = *matchedMethodRef;
  4089. auto ifaceMethodInst = ifaceInst->mMethodInstanceGroups[iMethodIdx].mDefault;
  4090. if (ifaceMethodInst == NULL)
  4091. continue;
  4092. auto iReturnType = ifaceMethodInst->mReturnType;
  4093. if (iReturnType->IsSelf())
  4094. iReturnType = typeInstance;
  4095. if (ifaceMethodInst->mMethodDef->mIsOverride)
  4096. continue; // Don't consider overrides here
  4097. // If we have "ProjA depends on LibBase", "ProjB depends on LibBase", then a type ClassC in LibBase implementing IFaceD,
  4098. // where IFaceD gets extended with MethodE in ProjA, an implementing MethodE is still required to exist on ClassC --
  4099. // the visibility is bidirectional. A type ClassF implementing IFaceD inside ProjB will not be required to implement
  4100. // MethodE, however
  4101. if ((!ifaceInst->IsTypeMemberAccessible(ifaceMethodInst->mMethodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  4102. (!ifaceInst->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, ifaceMethodInst->mMethodDef->mDeclaringType)))
  4103. continue;
  4104. if (!ifaceInst->IsTypeMemberIncluded(ifaceMethodInst->mMethodDef->mDeclaringType, ifaceTypeInst.mDeclaringType))
  4105. continue;
  4106. bool hadMatch = matchedMethod != NULL;
  4107. bool hadPubFailure = false;
  4108. bool hadStaticFailure = false;
  4109. bool hadMutFailure = false;
  4110. if (hadMatch)
  4111. {
  4112. if ((matchedMethod->GetExplicitInterface() == NULL) && (matchedMethod->mMethodDef->mProtection != BfProtection_Public))
  4113. {
  4114. hadMatch = false;
  4115. hadPubFailure = true;
  4116. }
  4117. if (matchedMethod->mMethodDef->mIsStatic != ifaceMethodInst->mMethodDef->mIsStatic)
  4118. {
  4119. hadMatch = false;
  4120. hadStaticFailure = true;
  4121. }
  4122. if (ifaceMethodInst->mVirtualTableIdx != -1)
  4123. {
  4124. if (matchedMethod->mReturnType != iReturnType)
  4125. hadMatch = false;
  4126. }
  4127. else
  4128. {
  4129. // Concrete/generic
  4130. if (!CanCast(GetFakeTypedValue(matchedMethod->mReturnType), iReturnType))
  4131. hadMatch = false;
  4132. }
  4133. // If we have mExplicitInterface set then we already gave a mut error (if needed)
  4134. if ((typeInstance->IsValueType()) && (matchedMethod->GetExplicitInterface() == NULL) &&
  4135. (matchedMethod->mMethodDef->mIsMutating) && (!ifaceMethodInst->mMethodDef->mIsMutating))
  4136. {
  4137. hadMutFailure = true;
  4138. hadMatch = false;
  4139. }
  4140. }
  4141. if (!hadMatch)
  4142. {
  4143. if (!typeInstance->IsUnspecializedTypeVariation())
  4144. {
  4145. auto bestMethodInst = ifaceMethodInst;
  4146. auto bestInterface = ifaceInst;
  4147. if (matchedMethod == NULL)
  4148. {
  4149. bool searchFailed = false;
  4150. for (auto& checkIFaceTypeInst : typeInstance->mInterfaces)
  4151. {
  4152. auto checkIFaceInst = checkIFaceTypeInst.mInterfaceType;
  4153. int checkStartIdx = checkIFaceTypeInst.mStartInterfaceTableIdx;
  4154. int checkIMethodCount = (int)checkIFaceInst->mMethodInstanceGroups.size();
  4155. for (int checkIMethodIdx = 0; checkIMethodIdx < checkIMethodCount; checkIMethodIdx++)
  4156. {
  4157. auto checkIFaceMethodInst = checkIFaceInst->mMethodInstanceGroups[checkIMethodIdx].mDefault;
  4158. if ((checkIFaceMethodInst != NULL) && (checkIFaceMethodInst->mMethodDef->mIsOverride))
  4159. {
  4160. if (CompareMethodSignatures(checkIFaceMethodInst, ifaceMethodInst))
  4161. {
  4162. bool isBetter = TypeIsSubTypeOf(checkIFaceInst, bestInterface);
  4163. bool isWorse = TypeIsSubTypeOf(bestInterface, checkIFaceInst);
  4164. if (isBetter == isWorse)
  4165. {
  4166. CompareDeclTypes(checkIFaceMethodInst->mMethodDef->mDeclaringType, bestMethodInst->mMethodDef->mDeclaringType, isBetter, isWorse);
  4167. }
  4168. if ((isBetter) && (!isWorse))
  4169. {
  4170. bestInterface = checkIFaceInst;
  4171. bestMethodInst = checkIFaceMethodInst;
  4172. }
  4173. else if (isBetter == isWorse)
  4174. {
  4175. if (!searchFailed)
  4176. {
  4177. searchFailed = true;
  4178. auto error = Fail(StrFormat("There is no most-specific default implementation of '%s'", MethodToString(ifaceMethodInst).c_str()), declTypeDef->mTypeDeclaration->mNameNode);
  4179. if (error != NULL)
  4180. {
  4181. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  4182. MethodToString(bestMethodInst).c_str()), bestMethodInst->mMethodDef->GetRefNode());
  4183. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  4184. MethodToString(checkIFaceMethodInst).c_str()), checkIFaceMethodInst->mMethodDef->GetRefNode());
  4185. }
  4186. //candidate implementations include '%s' and '%s'",
  4187. //TypeToString(checkIFaceInst).c_str(), TypeToString(bestInterface).c_str()), );
  4188. }
  4189. }
  4190. }
  4191. }
  4192. }
  4193. }
  4194. if (bestMethodInst->mReturnType != ifaceMethodInst->mReturnType)
  4195. {
  4196. auto error = Fail(StrFormat("Default interface method '%s' cannot be used because it doesn't have the return type '%s'",
  4197. MethodToString(bestMethodInst).c_str(), TypeToString(ifaceMethodInst->mReturnType).c_str()), declTypeDef->mTypeDeclaration->mNameNode);
  4198. if (error != NULL)
  4199. {
  4200. mCompiler->mPassInstance->MoreInfo("See original method declaration", ifaceMethodInst->mMethodDef->GetRefNode());
  4201. mCompiler->mPassInstance->MoreInfo("See override method declaration", bestMethodInst->mMethodDef->GetRefNode());
  4202. }
  4203. }
  4204. }
  4205. if ((bestMethodInst->mMethodDef->HasBody()) && (matchedMethod == NULL))
  4206. {
  4207. auto methodDef = bestMethodInst->mMethodDef;
  4208. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_ForeignMethodDef;
  4209. if ((methodDef->mGenericParams.size() != 0) || (typeInstance->IsUnspecializedType()))
  4210. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_UnspecializedPass);
  4211. auto methodInst = GetMethodInstance(typeInstance, methodDef, BfTypeVector(), flags, ifaceInst);
  4212. if (methodInst)
  4213. {
  4214. *matchedMethodRef = methodInst.mMethodInstance;
  4215. BfMethodInstance* newMethodInstance = methodInst.mMethodInstance;
  4216. BF_ASSERT(newMethodInstance->mIsForeignMethodDef);
  4217. if (newMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  4218. mOnDemandMethodCount++;
  4219. continue;
  4220. }
  4221. }
  4222. if (typeInstance->IsBoxed())
  4223. {
  4224. if (ifaceMethodInst->mMethodDef->mIsStatic)
  4225. {
  4226. // Skip the statics, those can't be invoked
  4227. }
  4228. else
  4229. {
  4230. // The unboxed version should have had the same error
  4231. if (!typeInstance->GetUnderlyingType()->IsIncomplete())
  4232. AssertErrorState();
  4233. }
  4234. }
  4235. else
  4236. {
  4237. String methodString;
  4238. ///
  4239. {
  4240. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ifaceMethodInst);
  4241. methodString = MethodToString(ifaceMethodInst);
  4242. }
  4243. BfTypeDeclaration* typeDecl = declTypeDef->mTypeDeclaration;
  4244. BfError* error = Fail(StrFormat("'%s' does not implement interface member '%s'", TypeToString(typeInstance).c_str(), methodString.c_str()), typeDecl->mNameNode, true);
  4245. if ((matchedMethod != NULL) && (error != NULL))
  4246. {
  4247. if (hadStaticFailure)
  4248. {
  4249. auto staticNodeRef = matchedMethod->mMethodDef->GetRefNode();
  4250. if (auto methodDecl = BfNodeDynCast<BfMethodDeclaration>(matchedMethod->mMethodDef->mMethodDeclaration))
  4251. if (methodDecl->mStaticSpecifier != NULL)
  4252. staticNodeRef = methodDecl->mStaticSpecifier;
  4253. if (matchedMethod->mMethodDef->mIsStatic)
  4254. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because because it's static",
  4255. methodString.c_str()), staticNodeRef);
  4256. else
  4257. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because because it's not static",
  4258. methodString.c_str()), staticNodeRef);
  4259. }
  4260. else if (hadPubFailure)
  4261. {
  4262. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because because it's not public",
  4263. methodString.c_str()), matchedMethod->mMethodDef->mReturnTypeRef);
  4264. }
  4265. else if (ifaceMethodInst->mReturnType->IsConcreteInterfaceType())
  4266. {
  4267. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because because it does not have a concrete return type that implements '%s'",
  4268. methodString.c_str(), TypeToString(ifaceMethodInst->mReturnType).c_str()), matchedMethod->mMethodDef->mReturnTypeRef);
  4269. }
  4270. else if (hadMutFailure)
  4271. {
  4272. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because because it's market as 'mut' but interface method does not allow it",
  4273. methodString.c_str()), matchedMethod->mMethodDef->GetMutNode());
  4274. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), ifaceMethodInst->mMethodDef->mMethodDeclaration);
  4275. }
  4276. else
  4277. {
  4278. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because because it does not have the return type '%s'",
  4279. methodString.c_str(), TypeToString(ifaceMethodInst->mReturnType).c_str()), matchedMethod->mMethodDef->mReturnTypeRef);
  4280. if ((ifaceMethodInst->mVirtualTableIdx != -1) && (ifaceMethodInst->mReturnType->IsInterface()))
  4281. mCompiler->mPassInstance->MoreInfo("Declare the interface method as 'concrete' to allow matching concrete return values", ifaceMethodInst->mMethodDef->GetMethodDeclaration()->mVirtualSpecifier);
  4282. }
  4283. }
  4284. }
  4285. }
  4286. // Clear out the entry
  4287. *matchedMethodRef = BfMethodRef();
  4288. }
  4289. }
  4290. }
  4291. }
  4292. ambiguityContext.Finish();
  4293. CheckAddFailType();
  4294. typeInstance->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  4295. mCompiler->mStats.mTypesPopulated++;
  4296. mCompiler->UpdateCompletion();
  4297. BfLogSysM("Finished DoTypeInstanceMethodProcessing %p. OnDemandMethods: %d Virtual Size: %d\n", typeInstance, mOnDemandMethodCount, typeInstance->mVirtualMethodTable.size());
  4298. }
  4299. void BfModule::RebuildMethods(BfTypeInstance* typeInstance)
  4300. {
  4301. if (typeInstance->IsIncomplete())
  4302. return;
  4303. typeInstance->mNeedsMethodProcessing = true;
  4304. typeInstance->mDefineState = BfTypeDefineState_Defined;
  4305. typeInstance->mTypeIncomplete = true;
  4306. for (auto& methodInstanceGroup : typeInstance->mMethodInstanceGroups)
  4307. {
  4308. delete methodInstanceGroup.mDefault;
  4309. methodInstanceGroup.mDefault = NULL;
  4310. delete methodInstanceGroup.mMethodSpecializationMap;
  4311. methodInstanceGroup.mMethodSpecializationMap = NULL;
  4312. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_NotSet;
  4313. }
  4314. BfTypeProcessRequest* typeProcessRequest = mContext->mPopulateTypeWorkList.Alloc();
  4315. typeProcessRequest->mType = typeInstance;
  4316. BF_ASSERT(typeInstance->mContext == mContext);
  4317. mCompiler->mStats.mTypesQueued++;
  4318. mCompiler->UpdateCompletion();
  4319. }
  4320. BfModule* BfModule::GetModuleFor(BfType* type)
  4321. {
  4322. auto typeInst = type->ToTypeInstance();
  4323. if (typeInst == NULL)
  4324. return NULL;
  4325. return typeInst->mModule;
  4326. }
  4327. void BfModule::AddMethodToWorkList(BfMethodInstance* methodInstance)
  4328. {
  4329. BF_ASSERT(!methodInstance->mMethodDef->mIsAbstract);
  4330. if (methodInstance->IsSpecializedByAutoCompleteMethod())
  4331. return;
  4332. BF_ASSERT(mCompiler->mCompileState != BfCompiler::CompileState_VData);
  4333. if ((methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized))
  4334. {
  4335. BF_ASSERT(mCompiler->mCompileState != BfCompiler::CompileState_Unreified);
  4336. }
  4337. if (methodInstance->IsOrInUnspecializedVariation())
  4338. {
  4339. return;
  4340. }
  4341. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedTypeVariation());
  4342. BF_ASSERT(methodInstance->mMethodProcessRequest == NULL);
  4343. auto defaultMethod = methodInstance->mMethodInstanceGroup->mDefault;
  4344. if (defaultMethod != methodInstance)
  4345. {
  4346. BF_ASSERT(defaultMethod != NULL);
  4347. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  4348. {
  4349. if ((defaultMethod->mIsReified) && (!defaultMethod->mDeclModule->mIsModuleMutable))
  4350. {
  4351. defaultMethod->mDeclModule->PrepareForIRWriting(methodInstance->GetOwner());
  4352. }
  4353. AddMethodToWorkList(defaultMethod);
  4354. }
  4355. }
  4356. if (methodInstance->mDeclModule != NULL)
  4357. {
  4358. if (methodInstance->mDeclModule != this)
  4359. {
  4360. methodInstance->mDeclModule->AddMethodToWorkList(methodInstance);
  4361. return;
  4362. }
  4363. }
  4364. else
  4365. {
  4366. auto module = GetOrCreateMethodModule(methodInstance);
  4367. methodInstance->mDeclModule = module;
  4368. BfIRValue func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  4369. methodInstance->mIRFunction = func;
  4370. module->mFuncReferences[methodInstance] = func;
  4371. module->AddMethodToWorkList(methodInstance);
  4372. return;
  4373. }
  4374. if ((!methodInstance->mIRFunction) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) &&
  4375. (methodInstance->GetImportCallKind() == BfImportCallKind_None))
  4376. {
  4377. if (!mIsModuleMutable)
  4378. PrepareForIRWriting(methodInstance->GetOwner());
  4379. BfIRValue func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  4380. if (func)
  4381. {
  4382. methodInstance->mIRFunction = func;
  4383. mFuncReferences[methodInstance] = func;
  4384. }
  4385. }
  4386. BF_ASSERT(methodInstance->mDeclModule == this);
  4387. if (defaultMethod == methodInstance)
  4388. {
  4389. if (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude)
  4390. {
  4391. auto owningModule = methodInstance->GetOwner()->GetModule();
  4392. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced);
  4393. if (!mIsScratchModule)
  4394. {
  4395. if (owningModule->mParentModule != NULL)
  4396. BF_ASSERT(owningModule->mParentModule->mOnDemandMethodCount > 0);
  4397. else
  4398. BF_ASSERT(owningModule->mOnDemandMethodCount > 0);
  4399. }
  4400. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_InWorkList;
  4401. }
  4402. }
  4403. else
  4404. {
  4405. BF_ASSERT(defaultMethod->mMethodInstanceGroup->IsImplemented());
  4406. }
  4407. BF_ASSERT(methodInstance->mDeclModule != NULL);
  4408. auto typeInstance = methodInstance->GetOwner();
  4409. BfMethodProcessRequest* methodProcessRequest = mContext->mMethodWorkList.Alloc();
  4410. methodProcessRequest->mType = typeInstance;
  4411. methodProcessRequest->mMethodInstance = methodInstance;
  4412. methodProcessRequest->mRevision = typeInstance->mRevision;
  4413. methodProcessRequest->mFromModuleRebuildIdx = mRebuildIdx;
  4414. methodProcessRequest->mFromModule = this;
  4415. if ((!mCompiler->mIsResolveOnly) && (methodInstance->mIsReified))
  4416. BF_ASSERT(mIsModuleMutable || mReifyQueued);
  4417. BF_ASSERT(mBfIRBuilder != NULL);
  4418. 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);
  4419. if (mAwaitingFinish)
  4420. {
  4421. BfLogSysM("Module: %p No longer awaiting finish\n", this);
  4422. mAwaitingFinish = false;
  4423. }
  4424. mCompiler->mStats.mMethodsQueued++;
  4425. mCompiler->UpdateCompletion();
  4426. mIncompleteMethodCount++;
  4427. if (methodInstance->GetNumGenericArguments() != 0)
  4428. mHasGenericMethods = true;
  4429. methodInstance->mMethodProcessRequest = methodProcessRequest;
  4430. }
  4431. BfArrayType* BfModule::CreateArrayType(BfType* resolvedType, int dimensions)
  4432. {
  4433. BF_ASSERT(!resolvedType->IsVar());
  4434. BF_ASSERT(!resolvedType->IsIntUnknown());
  4435. auto arrayType = mContext->mArrayTypePool.Get();
  4436. delete arrayType->mGenericTypeInfo;
  4437. arrayType->mGenericTypeInfo = new BfGenericTypeInfo();
  4438. arrayType->mContext = mContext;
  4439. arrayType->mTypeDef = mCompiler->GetArrayTypeDef(dimensions);
  4440. arrayType->mDimensions = dimensions;
  4441. arrayType->mGenericTypeInfo->mTypeGenericArguments.clear();
  4442. arrayType->mGenericTypeInfo->mTypeGenericArguments.push_back(resolvedType);
  4443. auto resolvedArrayType = ResolveType(arrayType);
  4444. if (resolvedArrayType != arrayType)
  4445. mContext->mArrayTypePool.GiveBack(arrayType);
  4446. return (BfArrayType*)resolvedArrayType;
  4447. }
  4448. BfSizedArrayType* BfModule::CreateSizedArrayType(BfType * resolvedType, int size)
  4449. {
  4450. BF_ASSERT(!resolvedType->IsVar());
  4451. auto arrayType = mContext->mSizedArrayTypePool.Get();
  4452. arrayType->mContext = mContext;
  4453. arrayType->mElementType = resolvedType;
  4454. arrayType->mElementCount = size;
  4455. auto resolvedArrayType = ResolveType(arrayType);
  4456. if (resolvedArrayType != arrayType)
  4457. mContext->mSizedArrayTypePool.GiveBack(arrayType);
  4458. return (BfSizedArrayType*)resolvedArrayType;
  4459. }
  4460. BfUnknownSizedArrayType* BfModule::CreateUnknownSizedArrayType(BfType* resolvedType, BfType* sizeParam)
  4461. {
  4462. BF_ASSERT(!resolvedType->IsVar());
  4463. BF_ASSERT(sizeParam->IsGenericParam());
  4464. auto arrayType = mContext->mUnknownSizedArrayTypePool.Get();
  4465. arrayType->mContext = mContext;
  4466. arrayType->mElementType = resolvedType;
  4467. arrayType->mElementCount = -1;
  4468. arrayType->mElementCountSource = sizeParam;
  4469. auto resolvedArrayType = ResolveType(arrayType);
  4470. if (resolvedArrayType != arrayType)
  4471. mContext->mUnknownSizedArrayTypePool.GiveBack(arrayType);
  4472. return (BfUnknownSizedArrayType*)resolvedArrayType;
  4473. }
  4474. BfPointerType* BfModule::CreatePointerType(BfType* resolvedType)
  4475. {
  4476. BF_ASSERT(!resolvedType->IsVar());
  4477. auto pointerType = mContext->mPointerTypePool.Get();
  4478. pointerType->mContext = mContext;
  4479. pointerType->mElementType = resolvedType;
  4480. auto resolvedPointerType = (BfPointerType*)ResolveType(pointerType);
  4481. if (resolvedPointerType != pointerType)
  4482. mContext->mPointerTypePool.GiveBack(pointerType);
  4483. BF_ASSERT(resolvedPointerType->mElementType == resolvedType);
  4484. return resolvedPointerType;
  4485. }
  4486. BfConstExprValueType* BfModule::CreateConstExprValueType(const BfTypedValue& typedValue, bool allowCreate)
  4487. {
  4488. BfPopulateType populateType = allowCreate ? BfPopulateType_Data : BfPopulateType_Identity;
  4489. BfResolveTypeRefFlags resolveFlags = allowCreate ? BfResolveTypeRefFlag_None : BfResolveTypeRefFlag_NoCreate;
  4490. auto variant = TypedValueToVariant(NULL, typedValue);
  4491. if (variant.mTypeCode == BfTypeCode_None)
  4492. return NULL;
  4493. auto constExprValueType = mContext->mConstExprValueTypePool.Get();
  4494. constExprValueType->mContext = mContext;
  4495. constExprValueType->mType = typedValue.mType;
  4496. constExprValueType->mValue = variant;
  4497. auto resolvedConstExprValueType = (BfConstExprValueType*)ResolveType(constExprValueType, populateType, resolveFlags);
  4498. if (resolvedConstExprValueType != constExprValueType)
  4499. mContext->mConstExprValueTypePool.GiveBack(constExprValueType);
  4500. if (resolvedConstExprValueType != NULL)
  4501. BF_ASSERT(resolvedConstExprValueType->mValue.mInt64 == constExprValueType->mValue.mInt64);
  4502. return resolvedConstExprValueType;
  4503. }
  4504. BfTypeInstance* BfModule::GetWrappedStructType(BfType* type, bool allowSpecialized)
  4505. {
  4506. if (type->IsPointer())
  4507. {
  4508. if (allowSpecialized)
  4509. {
  4510. BfPointerType* pointerType = (BfPointerType*)type;
  4511. BfTypeVector typeVector;
  4512. typeVector.Add(pointerType->mElementType);
  4513. return ResolveTypeDef(mCompiler->mPointerTTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  4514. }
  4515. else
  4516. return ResolveTypeDef(mCompiler->mPointerTTypeDef, BfPopulateType_Data)->ToTypeInstance();
  4517. }
  4518. else if (type->IsMethodRef())
  4519. {
  4520. if (allowSpecialized)
  4521. {
  4522. BfMethodRefType* methodRefType = (BfMethodRefType*)type;
  4523. BfTypeVector typeVector;
  4524. typeVector.Add(methodRefType);
  4525. return ResolveTypeDef(mCompiler->mMethodRefTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  4526. }
  4527. else
  4528. return ResolveTypeDef(mCompiler->mMethodRefTypeDef, BfPopulateType_Data)->ToTypeInstance();
  4529. }
  4530. else if (type->IsSizedArray())
  4531. {
  4532. if (allowSpecialized)
  4533. {
  4534. if (type->IsUnknownSizedArray())
  4535. {
  4536. BfUnknownSizedArrayType* sizedArrayType = (BfUnknownSizedArrayType*)type;
  4537. BfTypeVector typeVector;
  4538. typeVector.Add(sizedArrayType->mElementType);
  4539. typeVector.Add(sizedArrayType->mElementCountSource);
  4540. return ResolveTypeDef(mCompiler->mSizedArrayTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  4541. }
  4542. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)type;
  4543. BfTypeVector typeVector;
  4544. typeVector.Add(sizedArrayType->mElementType);
  4545. auto sizeValue = BfTypedValue(GetConstValue(BF_MAX(sizedArrayType->mElementCount, 0)), GetPrimitiveType(BfTypeCode_IntPtr));
  4546. typeVector.Add(CreateConstExprValueType(sizeValue));
  4547. return ResolveTypeDef(mCompiler->mSizedArrayTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  4548. }
  4549. else
  4550. return ResolveTypeDef(mCompiler->mSizedArrayTypeDef, BfPopulateType_Data)->ToTypeInstance();
  4551. }
  4552. BF_ASSERT(type->IsPrimitiveType());
  4553. return GetPrimitiveStructType(((BfPrimitiveType*)type)->mTypeDef->mTypeCode);
  4554. }
  4555. BfPrimitiveType* BfModule::GetPrimitiveType(BfTypeCode typeCode)
  4556. {
  4557. BfPrimitiveType* primType = mContext->mPrimitiveTypes[typeCode];
  4558. if (primType == NULL)
  4559. {
  4560. switch (typeCode)
  4561. {
  4562. case BfTypeCode_NullPtr:
  4563. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeNullPtr);
  4564. break;
  4565. case BfTypeCode_Self:
  4566. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeSelf);
  4567. break;
  4568. case BfTypeCode_Dot:
  4569. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeDot);
  4570. break;
  4571. case BfTypeCode_Var:
  4572. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeVar);
  4573. break;
  4574. case BfTypeCode_Let:
  4575. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeLet);
  4576. break;
  4577. case BfTypeCode_None:
  4578. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeVoid);
  4579. break;
  4580. case BfTypeCode_Boolean:
  4581. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeBool);
  4582. break;
  4583. case BfTypeCode_Int8:
  4584. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeInt8);
  4585. break;
  4586. case BfTypeCode_UInt8:
  4587. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUInt8);
  4588. break;
  4589. case BfTypeCode_Int16:
  4590. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeInt16);
  4591. break;
  4592. case BfTypeCode_UInt16:
  4593. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUInt16);
  4594. break;
  4595. case BfTypeCode_Int32:
  4596. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeInt32);
  4597. break;
  4598. case BfTypeCode_UInt32:
  4599. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUInt32);
  4600. break;
  4601. case BfTypeCode_Int64:
  4602. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeInt64);
  4603. break;
  4604. case BfTypeCode_UInt64:
  4605. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUInt64);
  4606. break;
  4607. case BfTypeCode_Char8:
  4608. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeChar8);
  4609. break;
  4610. case BfTypeCode_Char16:
  4611. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeChar16);
  4612. break;
  4613. case BfTypeCode_Char32:
  4614. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeChar32);
  4615. break;
  4616. case BfTypeCode_Float:
  4617. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeSingle);
  4618. break;
  4619. case BfTypeCode_Double:
  4620. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeDouble);
  4621. break;
  4622. case BfTypeCode_IntPtr:
  4623. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeIntPtr);
  4624. break;
  4625. case BfTypeCode_UIntPtr:
  4626. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUIntPtr);
  4627. break;
  4628. case BfTypeCode_IntUnknown:
  4629. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeIntUnknown);
  4630. break;
  4631. case BfTypeCode_UIntUnknown:
  4632. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUIntUnknown);
  4633. break;
  4634. case BfTypeCode_StringId:
  4635. BFMODULE_FATAL(this, "Invalid use of StringId");
  4636. break;
  4637. default:
  4638. BF_DBG_FATAL("Invalid type");
  4639. break;
  4640. }
  4641. mContext->mPrimitiveTypes[typeCode] = primType;
  4642. }
  4643. return primType;
  4644. }
  4645. BfIRType BfModule::GetIRLoweredType(BfTypeCode loweredTypeCode, BfTypeCode loweredTypeCode2)
  4646. {
  4647. BF_ASSERT(!mIsConstModule);
  4648. BF_ASSERT(loweredTypeCode != BfTypeCode_None);
  4649. if (loweredTypeCode2 == BfTypeCode_None)
  4650. return mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  4651. SizedArray<BfIRType, 2> types;
  4652. types.push_back(mBfIRBuilder->GetPrimitiveType(loweredTypeCode));
  4653. types.push_back(mBfIRBuilder->GetPrimitiveType(loweredTypeCode2));
  4654. return mBfIRBuilder->CreateStructType(types);
  4655. }
  4656. BfMethodRefType* BfModule::CreateMethodRefType(BfMethodInstance* methodInstance, bool mustAlreadyExist)
  4657. {
  4658. // Make sure we don't have a partially-formed local method or lambda coming in, because those may be replaced
  4659. // after the capture phase
  4660. BF_ASSERT(!methodInstance->mDisallowCalling);
  4661. auto methodRefType = new BfMethodRefType();
  4662. methodRefType->mContext = mContext;
  4663. //methodRefType->mCaptureType = NULL;
  4664. methodRefType->mMethodRef = methodInstance;
  4665. methodRefType->mOwner = methodInstance->GetOwner();
  4666. methodRefType->mOwnerRevision = methodRefType->mOwner->mRevision;
  4667. //methodRefType->mMangledName = BfMangler::Mangle(mCompiler->GetMangleKind(), methodInstance);
  4668. methodRefType->mIsAutoCompleteMethod = methodInstance->mIsAutocompleteMethod;
  4669. methodRefType->mIsUnspecialized = methodInstance->mIsUnspecialized;
  4670. methodRefType->mIsUnspecializedVariation = methodInstance->mIsUnspecializedVariation;
  4671. methodRefType->mSize = 0;
  4672. BfResolvedTypeSet::LookupContext lookupCtx;
  4673. lookupCtx.mModule = this;
  4674. BfResolvedTypeSet::Entry* typeEntry = NULL;
  4675. auto inserted = mContext->mResolvedTypes.Insert(methodRefType, &lookupCtx, &typeEntry);
  4676. if (typeEntry->mValue == NULL)
  4677. {
  4678. BF_ASSERT(!mustAlreadyExist);
  4679. BF_ASSERT(!methodInstance->mHasMethodRefType);
  4680. InitType(methodRefType, BfPopulateType_Identity);
  4681. methodRefType->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  4682. methodInstance->mHasMethodRefType = true;
  4683. methodInstance->mMethodInstanceGroup->mRefCount++;
  4684. typeEntry->mValue = methodRefType;
  4685. BfLogSysM("Create MethodRefType %p MethodInstance: %p\n", methodRefType, methodInstance);
  4686. methodRefType->mRevision = 0;
  4687. AddDependency(methodInstance->GetOwner(), methodRefType, BfDependencyMap::DependencyFlag_Calls);
  4688. BfTypeVector tupleTypes;
  4689. Array<String> tupleNames;
  4690. int offset = 0;
  4691. methodRefType->mAlign = 1;
  4692. int dataIdx = 0;
  4693. // CRepr, just because we're lazy (for now)
  4694. int implicitParamCount = methodInstance->GetImplicitParamCount();
  4695. for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  4696. {
  4697. auto paramType = methodInstance->GetParamType(implicitParamIdx);
  4698. if (!paramType->IsValuelessType())
  4699. {
  4700. methodRefType->mDataToParamIdx.Add(implicitParamIdx);
  4701. if (implicitParamIdx >= 0)
  4702. methodRefType->mParamToDataIdx.Add(dataIdx);
  4703. offset = BF_ALIGN(offset, paramType->mAlign);
  4704. offset += paramType->mSize;
  4705. methodRefType->mAlign = std::max(methodRefType->mAlign, paramType->mAlign);
  4706. dataIdx++;
  4707. }
  4708. else
  4709. {
  4710. methodRefType->mParamToDataIdx.Add(-1);
  4711. }
  4712. }
  4713. offset = BF_ALIGN(offset, methodRefType->mAlign);
  4714. methodRefType->mSize = offset;
  4715. // if (!tupleTypes.empty())
  4716. // {
  4717. // methodRefType->mCaptureType = CreateTupleType(tupleTypes, tupleNames);
  4718. // AddDependency(methodRefType->mCaptureType, methodRefType, BfDependencyMap::DependencyFlag_ReadFields);
  4719. //
  4720. // methodRefType->mSize = methodRefType->mCaptureType->mSize;
  4721. // methodRefType->mAlign = methodRefType->mCaptureType->mAlign;
  4722. // }
  4723. // else
  4724. // {
  4725. // methodRefType->mSize = 0;
  4726. // methodRefType->mAlign = 0;
  4727. // }
  4728. }
  4729. else
  4730. {
  4731. methodRefType->mMethodRef = NULL;
  4732. delete methodRefType;
  4733. methodRefType = (BfMethodRefType*)typeEntry->mValue;
  4734. }
  4735. return methodRefType;
  4736. }
  4737. BfType* BfModule::FixIntUnknown(BfType* type)
  4738. {
  4739. if ((type != NULL) && (type->IsPrimitiveType()))
  4740. {
  4741. auto primType = (BfPrimitiveType*)type;
  4742. if (primType->mTypeDef->mTypeCode == BfTypeCode_IntUnknown)
  4743. return GetPrimitiveType(BfTypeCode_IntPtr);
  4744. if (primType->mTypeDef->mTypeCode == BfTypeCode_UIntUnknown)
  4745. return GetPrimitiveType(BfTypeCode_UIntPtr);
  4746. }
  4747. return type;
  4748. }
  4749. void BfModule::FixIntUnknown(BfTypedValue& typedVal, BfType* matchType)
  4750. {
  4751. if (!typedVal.mValue.IsConst())
  4752. {
  4753. if ((typedVal.mType != NULL) && (typedVal.mType->IsPrimitiveType()))
  4754. {
  4755. auto primType = (BfPrimitiveType*)typedVal.mType;
  4756. BF_ASSERT((primType->mTypeDef->mTypeCode != BfTypeCode_IntUnknown) && (primType->mTypeDef->mTypeCode != BfTypeCode_UIntUnknown));
  4757. }
  4758. return;
  4759. }
  4760. if (!typedVal.mType->IsPrimitiveType())
  4761. return;
  4762. BfTypeCode wantTypeCode;
  4763. auto primType = (BfPrimitiveType*)typedVal.mType;
  4764. if (primType->mTypeDef->mTypeCode == BfTypeCode_IntUnknown)
  4765. wantTypeCode = BfTypeCode_IntPtr;
  4766. else if (primType->mTypeDef->mTypeCode == BfTypeCode_UIntUnknown)
  4767. wantTypeCode = BfTypeCode_UIntPtr;
  4768. else
  4769. return;
  4770. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  4771. if ((matchType != NULL) && (matchType->IsPrimitiveType()) && (mBfIRBuilder->IsInt(matchType->ToPrimitiveType()->mTypeDef->mTypeCode)))
  4772. {
  4773. auto wantTypeCode = matchType->ToPrimitiveType()->mTypeDef->mTypeCode;
  4774. if (matchType->mSize < 8)
  4775. {
  4776. int64 minVal = -(1LL << (8 * matchType->mSize - 1));
  4777. int64 maxVal = (1LL << (8 * matchType->mSize - 1)) - 1;
  4778. if ((constant->mInt64 >= minVal) && (constant->mInt64 <= maxVal))
  4779. {
  4780. typedVal.mValue = mBfIRBuilder->CreateNumericCast(typedVal.mValue, mBfIRBuilder->IsSigned(wantTypeCode), wantTypeCode);
  4781. typedVal.mType = GetPrimitiveType(wantTypeCode);
  4782. return;
  4783. }
  4784. }
  4785. }
  4786. if (mSystem->mPtrSize == 4)
  4787. {
  4788. if (primType->mTypeDef->mTypeCode == BfTypeCode_IntUnknown)
  4789. {
  4790. if ((constant->mInt64 >= -0x80000000LL) && (constant->mInt64 <= 0x7FFFFFFFLL))
  4791. {
  4792. typedVal.mValue = mBfIRBuilder->CreateNumericCast(typedVal.mValue, true, BfTypeCode_IntPtr);
  4793. typedVal.mType = GetPrimitiveType(BfTypeCode_IntPtr);
  4794. }
  4795. else
  4796. typedVal.mType = GetPrimitiveType(BfTypeCode_Int64);
  4797. return;
  4798. }
  4799. else
  4800. {
  4801. if ((constant->mInt64 >= 0) && (constant->mInt64 <= 0xFFFFFFFF))
  4802. {
  4803. typedVal.mValue = mBfIRBuilder->CreateNumericCast(typedVal.mValue, false, BfTypeCode_IntPtr);
  4804. typedVal.mType = GetPrimitiveType(BfTypeCode_UIntPtr);
  4805. }
  4806. else
  4807. typedVal.mType = GetPrimitiveType(BfTypeCode_UInt64);
  4808. return;
  4809. }
  4810. }
  4811. typedVal.mType = GetPrimitiveType(wantTypeCode);
  4812. }
  4813. void BfModule::FixIntUnknown(BfTypedValue& lhs, BfTypedValue& rhs)
  4814. {
  4815. if ((lhs.mType != NULL) && (lhs.mType->IsIntUnknown()) && (rhs.mType != NULL) && (rhs.mType->IsInteger()))
  4816. {
  4817. if (CanCast(lhs, rhs.mType))
  4818. {
  4819. lhs = Cast(NULL, lhs, rhs.mType, BfCastFlags_SilentFail);
  4820. if (!lhs)
  4821. lhs = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  4822. return;
  4823. }
  4824. }
  4825. if ((rhs.mType != NULL) && (rhs.mType->IsIntUnknown()) && (lhs.mType != NULL) && (lhs.mType->IsInteger()))
  4826. {
  4827. if (CanCast(rhs, lhs.mType))
  4828. {
  4829. rhs = Cast(NULL, rhs, lhs.mType, BfCastFlags_SilentFail);
  4830. if (!rhs)
  4831. rhs = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  4832. return;
  4833. }
  4834. }
  4835. FixIntUnknown(lhs);
  4836. FixIntUnknown(rhs);
  4837. }
  4838. BfTypeInstance* BfModule::GetPrimitiveStructType(BfTypeCode typeCode)
  4839. {
  4840. BfTypeInstance* typeInst = NULL;
  4841. switch (typeCode)
  4842. {
  4843. case BfTypeCode_None:
  4844. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Void"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4845. case BfTypeCode_Boolean:
  4846. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Boolean"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4847. case BfTypeCode_Int8:
  4848. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int8"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4849. case BfTypeCode_UInt8:
  4850. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt8"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4851. case BfTypeCode_Int16:
  4852. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int16"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4853. case BfTypeCode_UInt16:
  4854. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt16"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4855. case BfTypeCode_Int32:
  4856. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int32"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4857. case BfTypeCode_UInt32:
  4858. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt32"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4859. case BfTypeCode_Int64:
  4860. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int64"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4861. case BfTypeCode_UInt64:
  4862. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt64"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4863. case BfTypeCode_IntPtr:
  4864. case BfTypeCode_IntUnknown:
  4865. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4866. case BfTypeCode_UIntPtr:
  4867. case BfTypeCode_UIntUnknown:
  4868. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4869. case BfTypeCode_Char8:
  4870. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Char8"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4871. case BfTypeCode_Char16:
  4872. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Char16"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4873. case BfTypeCode_Char32:
  4874. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Char32"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4875. case BfTypeCode_Float:
  4876. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Float"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4877. case BfTypeCode_Double:
  4878. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Double"), BfPopulateType_Identity)->ToTypeInstance(); break;
  4879. default:
  4880. //BF_FATAL("not implemented");
  4881. break;
  4882. }
  4883. return typeInst;
  4884. }
  4885. BfBoxedType* BfModule::CreateBoxedType(BfType* resolvedTypeRef, bool allowCreate)
  4886. {
  4887. bool isStructPtr = false;
  4888. BfPopulateType populateType = allowCreate ? BfPopulateType_Data : BfPopulateType_Identity;
  4889. BfResolveTypeRefFlags resolveFlags = allowCreate ? BfResolveTypeRefFlag_None : BfResolveTypeRefFlag_NoCreate;
  4890. if (resolvedTypeRef->IsPrimitiveType())
  4891. {
  4892. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  4893. resolvedTypeRef = GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  4894. if (resolvedTypeRef == NULL)
  4895. return NULL;
  4896. }
  4897. else if (resolvedTypeRef->IsPointer())
  4898. {
  4899. BfPointerType* pointerType = (BfPointerType*)resolvedTypeRef;
  4900. if (pointerType->mElementType->IsStruct())
  4901. {
  4902. resolvedTypeRef = pointerType->mElementType;
  4903. isStructPtr = true;
  4904. }
  4905. else
  4906. {
  4907. BfTypeVector typeVector;
  4908. typeVector.Add(pointerType->mElementType);
  4909. resolvedTypeRef = ResolveTypeDef(mCompiler->mPointerTTypeDef, typeVector, populateType, resolveFlags);
  4910. if (resolvedTypeRef == NULL)
  4911. return NULL;
  4912. }
  4913. }
  4914. else if (resolvedTypeRef->IsMethodRef())
  4915. {
  4916. BfMethodRefType* methodRefType = (BfMethodRefType*)resolvedTypeRef;
  4917. BfTypeVector typeVector;
  4918. typeVector.Add(methodRefType);
  4919. resolvedTypeRef = ResolveTypeDef(mCompiler->mMethodRefTypeDef, typeVector, populateType, resolveFlags);
  4920. if (resolvedTypeRef == NULL)
  4921. return NULL;
  4922. }
  4923. else if (resolvedTypeRef->IsSizedArray())
  4924. {
  4925. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)resolvedTypeRef;
  4926. BfTypeVector typeVector;
  4927. typeVector.Add(sizedArrayType->mElementType);
  4928. auto sizeValue = BfTypedValue(GetConstValue(sizedArrayType->mElementCount), GetPrimitiveType(BfTypeCode_IntPtr));
  4929. auto sizeValueType = CreateConstExprValueType(sizeValue, allowCreate);
  4930. if (sizeValueType == NULL)
  4931. return NULL;
  4932. typeVector.Add(sizeValueType);
  4933. resolvedTypeRef = ResolveTypeDef(mCompiler->mSizedArrayTypeDef, typeVector, populateType, resolveFlags);
  4934. if (resolvedTypeRef == NULL)
  4935. return NULL;
  4936. }
  4937. BfTypeInstance* typeInst = resolvedTypeRef->ToTypeInstance();
  4938. if ((typeInst == NULL) && (!resolvedTypeRef->IsGenericParam()))
  4939. return NULL;
  4940. auto boxedType = mContext->mBoxedTypePool.Get();
  4941. boxedType->mContext = mContext;
  4942. boxedType->mElementType = resolvedTypeRef;
  4943. if (typeInst != NULL)
  4944. boxedType->mTypeDef = typeInst->mTypeDef;
  4945. else
  4946. boxedType->mTypeDef = mCompiler->mValueTypeTypeDef;
  4947. boxedType->mBoxedFlags = isStructPtr ? BfBoxedType::BoxedFlags_StructPtr : BfBoxedType::BoxedFlags_None;
  4948. auto resolvedBoxedType = ResolveType(boxedType, populateType, resolveFlags);
  4949. if (resolvedBoxedType != boxedType)
  4950. mContext->mBoxedTypePool.GiveBack(boxedType);
  4951. return (BfBoxedType*)resolvedBoxedType;
  4952. }
  4953. BfTypeInstance* BfModule::CreateTupleType(const BfTypeVector& fieldTypes, const Array<String>& fieldNames, bool allowVar)
  4954. {
  4955. auto baseType = (BfTypeInstance*)ResolveTypeDef(mContext->mCompiler->mValueTypeTypeDef);
  4956. BfTupleType* tupleType = NULL;
  4957. auto actualTupleType = mContext->mTupleTypePool.Get();
  4958. actualTupleType->Init(baseType->mTypeDef->mProject, baseType);
  4959. bool isUnspecialzied = false;
  4960. for (int fieldIdx = 0; fieldIdx < (int)fieldTypes.size(); fieldIdx++)
  4961. {
  4962. String fieldName;
  4963. if (fieldIdx < (int)fieldNames.size())
  4964. fieldName = fieldNames[fieldIdx];
  4965. if (fieldName.empty())
  4966. fieldName = StrFormat("%d", fieldIdx);
  4967. BfFieldDef* fieldDef = actualTupleType->AddField(fieldName);
  4968. auto fieldType = fieldTypes[fieldIdx];
  4969. if ((fieldType->IsUnspecializedType()) || (fieldType->IsVar()))
  4970. isUnspecialzied = true;
  4971. }
  4972. tupleType = actualTupleType;
  4973. tupleType->mContext = mContext;
  4974. tupleType->mFieldInstances.Resize(fieldTypes.size());
  4975. for (int fieldIdx = 0; fieldIdx < (int)fieldTypes.size(); fieldIdx++)
  4976. {
  4977. BfFieldInstance* fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  4978. fieldInstance->mFieldIdx = fieldIdx;
  4979. BfType* fieldType = fieldTypes[fieldIdx];
  4980. if ((fieldType->IsVar()) && (!allowVar))
  4981. fieldType = mContext->mBfObjectType;
  4982. fieldInstance->SetResolvedType(fieldType);
  4983. fieldInstance->mOwner = tupleType;
  4984. }
  4985. tupleType->mIsUnspecializedType = false;
  4986. tupleType->mIsUnspecializedTypeVariation = false;
  4987. if (isUnspecialzied)
  4988. {
  4989. tupleType->mIsUnspecializedType = true;
  4990. tupleType->mIsUnspecializedTypeVariation = true;
  4991. }
  4992. auto resolvedTupleType = ResolveType(tupleType);
  4993. if (resolvedTupleType != tupleType)
  4994. {
  4995. BF_ASSERT(tupleType->mContext != NULL);
  4996. mContext->mTupleTypePool.GiveBack((BfTupleType*)tupleType);
  4997. }
  4998. return (BfTupleType*)resolvedTupleType;
  4999. }
  5000. BfTypeInstance* BfModule::SantizeTupleType(BfTypeInstance* tupleType)
  5001. {
  5002. bool needsSanitize = false;
  5003. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  5004. {
  5005. BfFieldInstance* fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  5006. if ((fieldInstance->mResolvedType->IsVar()) || (fieldInstance->mResolvedType->IsLet()))
  5007. {
  5008. needsSanitize = true;
  5009. break;
  5010. }
  5011. }
  5012. if (!needsSanitize)
  5013. return tupleType;
  5014. BfTypeVector fieldTypes;
  5015. Array<String> fieldNames;
  5016. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  5017. {
  5018. BfFieldInstance* fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  5019. auto fieldDef = fieldInstance->GetFieldDef();
  5020. if ((fieldInstance->mResolvedType->IsVar()) || (fieldInstance->mResolvedType->IsLet()))
  5021. fieldTypes.Add(mContext->mBfObjectType);
  5022. else
  5023. fieldTypes.Add(fieldInstance->mResolvedType);
  5024. if (!fieldDef->IsUnnamedTupleField())
  5025. {
  5026. for (int i = 0; i < fieldIdx; i++)
  5027. fieldNames.Add(String());
  5028. fieldNames.Add(fieldDef->mName);
  5029. }
  5030. }
  5031. return CreateTupleType(fieldTypes, fieldNames);
  5032. }
  5033. BfRefType* BfModule::CreateRefType(BfType* resolvedTypeRef, BfRefType::RefKind refKind)
  5034. {
  5035. auto refType = mContext->mRefTypePool.Get();
  5036. refType->mContext = mContext;
  5037. refType->mElementType = resolvedTypeRef;
  5038. refType->mRefKind = refKind;
  5039. auto resolvedRefType = ResolveType(refType);
  5040. if (resolvedRefType != refType)
  5041. mContext->mRefTypePool.GiveBack(refType);
  5042. return (BfRefType*)resolvedRefType;
  5043. }
  5044. BfModifiedTypeType* BfModule::CreateModifiedTypeType(BfType* resolvedTypeRef, BfToken modifiedKind)
  5045. {
  5046. auto retTypeType = mContext->mModifiedTypeTypePool.Get();
  5047. retTypeType->mContext = mContext;
  5048. retTypeType->mModifiedKind = modifiedKind;
  5049. retTypeType->mElementType = resolvedTypeRef;
  5050. auto resolvedRetTypeType = ResolveType(retTypeType);
  5051. if (resolvedRetTypeType != retTypeType)
  5052. mContext->mModifiedTypeTypePool.GiveBack(retTypeType);
  5053. return (BfModifiedTypeType*)resolvedRetTypeType;
  5054. }
  5055. BfConcreteInterfaceType* BfModule::CreateConcreteInterfaceType(BfTypeInstance* interfaceType)
  5056. {
  5057. auto concreteInterfaceType = mContext->mConcreteInterfaceTypePool.Get();
  5058. concreteInterfaceType->mContext = mContext;
  5059. concreteInterfaceType->mInterface = interfaceType;
  5060. auto resolvedConcreteInterfaceType = ResolveType(concreteInterfaceType);
  5061. if (resolvedConcreteInterfaceType != concreteInterfaceType)
  5062. mContext->mConcreteInterfaceTypePool.GiveBack(concreteInterfaceType);
  5063. return (BfConcreteInterfaceType*)resolvedConcreteInterfaceType;
  5064. }
  5065. BfPointerType* BfModule::CreatePointerType(BfTypeReference* typeRef)
  5066. {
  5067. auto resolvedTypeRef = ResolveTypeRef(typeRef);
  5068. if (resolvedTypeRef == NULL)
  5069. return NULL;
  5070. return CreatePointerType(resolvedTypeRef);
  5071. }
  5072. BfType* BfModule::ResolveTypeDef(BfTypeDef* typeDef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  5073. {
  5074. //BF_ASSERT(typeDef->mTypeCode != BfTypeCode_Extension);
  5075. BF_ASSERT(!typeDef->mIsPartial || typeDef->mIsCombinedPartial);
  5076. BF_ASSERT(typeDef->mDefState != BfTypeDef::DefState_Deleted);
  5077. BF_ASSERT((typeDef->mOuterType == NULL) || (typeDef->mOuterType->mDefState != BfTypeDef::DefState_Deleted));
  5078. if (typeDef->mGenericParamDefs.size() != 0)
  5079. return ResolveTypeDef(typeDef, BfTypeVector(), populateType, resolveFlags);
  5080. auto typeDefTypeRef = mContext->mTypeDefTypeRefPool.Get();
  5081. typeDefTypeRef->mTypeDef = typeDef;
  5082. auto resolvedtypeDefType = ResolveTypeRef(typeDefTypeRef, populateType);
  5083. if (resolvedtypeDefType == NULL)
  5084. {
  5085. mContext->mTypeDefTypeRefPool.GiveBack(typeDefTypeRef);
  5086. return NULL;
  5087. }
  5088. mContext->mTypeDefTypeRefPool.GiveBack(typeDefTypeRef);
  5089. //BF_ASSERT(resolvedtypeDefType->IsTypeInstance() || resolvedtypeDefType->IsPrimitiveType());
  5090. return resolvedtypeDefType;
  5091. }
  5092. // Get BaseClass even when we haven't populated the type yet2
  5093. BfTypeInstance* BfModule::GetBaseType(BfTypeInstance* typeInst)
  5094. {
  5095. if ((mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mTypeInstance == typeInst))
  5096. {
  5097. if (typeInst->mBaseType == NULL)
  5098. return NULL;
  5099. }
  5100. if ((typeInst->mBaseType == NULL) && (typeInst != mContext->mBfObjectType))
  5101. PopulateType(typeInst, BfPopulateType_BaseType);
  5102. return typeInst->mBaseType;
  5103. }
  5104. void BfModule::HandleTypeGenericParamRef(BfAstNode* refNode, BfTypeDef* typeDef, int typeGenericParamIdx)
  5105. {
  5106. if (mCompiler->IsAutocomplete())
  5107. {
  5108. BfAutoComplete* autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  5109. if ((autoComplete != NULL) && (autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(refNode)))
  5110. {
  5111. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  5112. (autoComplete->mDefProp == NULL))
  5113. {
  5114. autoComplete->mDefType = typeDef;
  5115. autoComplete->mDefTypeGenericParamIdx = typeGenericParamIdx;
  5116. autoComplete->SetDefinitionLocation(refNode);
  5117. }
  5118. }
  5119. }
  5120. if (mCompiler->mResolvePassData != NULL)
  5121. mCompiler->mResolvePassData->HandleTypeGenericParam(refNode, typeDef, typeGenericParamIdx);
  5122. }
  5123. void BfModule::HandleMethodGenericParamRef(BfAstNode* refNode, BfTypeDef* typeDef, BfMethodDef* methodDef, int methodGenericParamIdx)
  5124. {
  5125. if (mCompiler->IsAutocomplete())
  5126. {
  5127. BfAutoComplete* autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  5128. if ((autoComplete != NULL) && (autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(refNode)))
  5129. {
  5130. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  5131. (autoComplete->mDefProp == NULL))
  5132. {
  5133. autoComplete->mDefType = typeDef;
  5134. autoComplete->mDefMethod = methodDef;
  5135. autoComplete->mDefMethodGenericParamIdx = methodGenericParamIdx;
  5136. autoComplete->SetDefinitionLocation(refNode);
  5137. }
  5138. }
  5139. }
  5140. if (mCompiler->mResolvePassData != NULL)
  5141. mCompiler->mResolvePassData->HandleMethodGenericParam(refNode, typeDef, methodDef, methodGenericParamIdx);
  5142. }
  5143. BfType* BfModule::ResolveInnerType(BfType* outerType, BfTypeReference* typeRef, BfPopulateType populateType, bool ignoreErrors, int numGenericArgs)
  5144. {
  5145. BfTypeDef* nestedTypeDef = NULL;
  5146. if (outerType->IsBoxed())
  5147. outerType = outerType->GetUnderlyingType();
  5148. BfNamedTypeReference* namedTypeRef = NULL;
  5149. BfGenericInstanceTypeRef* genericTypeRef = NULL;
  5150. BfDirectStrTypeReference* directStrTypeRef = NULL;
  5151. if ((namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef)))
  5152. {
  5153. //TYPEDEF nestedTypeDef = namedTypeRef->mTypeDef;
  5154. }
  5155. else if ((genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef)))
  5156. {
  5157. namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(genericTypeRef->mElementType);
  5158. //TYPEDEF nestedTypeDef = namedTypeRef->mTypeDef;
  5159. }
  5160. else if ((directStrTypeRef = BfNodeDynCast<BfDirectStrTypeReference>(typeRef)))
  5161. {
  5162. //
  5163. }
  5164. BF_ASSERT((namedTypeRef != NULL) || (directStrTypeRef != NULL));
  5165. if (nestedTypeDef == NULL)
  5166. {
  5167. StringView findName;
  5168. if (namedTypeRef != NULL)
  5169. findName = namedTypeRef->mNameNode->ToStringView();
  5170. else
  5171. findName = directStrTypeRef->mTypeName;
  5172. if (!findName.Contains('.'))
  5173. {
  5174. if (outerType->IsTypeInstance())
  5175. {
  5176. auto outerTypeInstance = outerType->ToTypeInstance();
  5177. for (int pass = 0; pass < 2; pass++)
  5178. {
  5179. bool isFailurePass = pass == 1;
  5180. bool allowPrivate = (mCurTypeInstance != NULL) &&
  5181. ((mCurTypeInstance == outerTypeInstance) || TypeHasParentOrEquals(mCurTypeInstance->mTypeDef, outerTypeInstance->mTypeDef));
  5182. bool allowProtected = allowPrivate;/*(mCurTypeInstance != NULL) &&
  5183. (allowPrivate || (mCurTypeInstance->mSkipTypeProtectionChecks) || TypeIsSubTypeOf(mCurTypeInstance, outerTypeInstance));*/
  5184. auto checkOuterType = outerTypeInstance;
  5185. while (checkOuterType != NULL)
  5186. {
  5187. for (auto checkType : checkOuterType->mTypeDef->mNestedTypes)
  5188. {
  5189. auto latestCheckType = checkType->GetLatest();
  5190. if ((!isFailurePass) && (!CheckProtection(latestCheckType->mProtection, latestCheckType, allowProtected, allowPrivate)))
  5191. continue;
  5192. if (checkType->mProject != checkOuterType->mTypeDef->mProject)
  5193. {
  5194. auto visibleProjectSet = GetVisibleProjectSet();
  5195. if ((visibleProjectSet == NULL) || (!visibleProjectSet->Contains(checkType->mProject)))
  5196. continue;
  5197. }
  5198. if ((checkType->mName->mString == findName) && (checkType->GetSelfGenericParamCount() == numGenericArgs))
  5199. {
  5200. if (isFailurePass)
  5201. {
  5202. // This is the one error we don't ignore when ignoreErrors is set
  5203. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(checkOuterType).c_str(), BfTypeUtils::TypeToString(typeRef).c_str()), typeRef); // CS0122
  5204. }
  5205. nestedTypeDef = checkType;
  5206. break;
  5207. }
  5208. }
  5209. if (nestedTypeDef != NULL)
  5210. break;
  5211. allowPrivate = false;
  5212. checkOuterType = GetBaseType(checkOuterType);
  5213. }
  5214. if (nestedTypeDef != NULL)
  5215. break;
  5216. }
  5217. }
  5218. }
  5219. if (nestedTypeDef == NULL)
  5220. {
  5221. if (!mIgnoreErrors && !ignoreErrors)
  5222. {
  5223. StringT<64> name;
  5224. name.Append(findName);
  5225. Fail(StrFormat("'%s' does not contain a definition for '%s'", TypeToString(outerType).c_str(), name.c_str()), typeRef);
  5226. }
  5227. return NULL;
  5228. }
  5229. }
  5230. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, ignoreErrors || mIgnoreErrors);
  5231. if ((genericTypeRef != NULL) || (outerType->IsGenericTypeInstance()))
  5232. {
  5233. BfTypeVector genericArgs;
  5234. if (outerType->IsGenericTypeInstance())
  5235. {
  5236. auto genericTypeInst = (BfTypeInstance*)outerType;
  5237. genericArgs = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments;
  5238. }
  5239. if (genericTypeRef != NULL)
  5240. {
  5241. for (auto genericArgTypeRef : genericTypeRef->mGenericArguments)
  5242. {
  5243. auto genericArgType = ResolveTypeRef(genericArgTypeRef, BfPopulateType_IdentityNoRemapAlias);
  5244. if (genericArgType == NULL)
  5245. return NULL;
  5246. genericArgs.push_back(genericArgType);
  5247. }
  5248. }
  5249. if (genericArgs.size() != nestedTypeDef->mGenericParamDefs.size())
  5250. {
  5251. if (populateType == BfPopulateType_TypeDef)
  5252. {
  5253. // Probably from inside ResolveGenericInstanceDef, just return unresolved typedef
  5254. genericArgs.clear();
  5255. }
  5256. else
  5257. {
  5258. ShowGenericArgCountError(typeRef, (int)nestedTypeDef->mGenericParamDefs.size() - (int)nestedTypeDef->mOuterType->mGenericParamDefs.size());
  5259. return NULL;
  5260. }
  5261. }
  5262. if (nestedTypeDef->mIsPartial)
  5263. {
  5264. nestedTypeDef = GetCombinedPartialTypeDef(nestedTypeDef);
  5265. if (nestedTypeDef == NULL)
  5266. return NULL;
  5267. }
  5268. return ResolveTypeDef(nestedTypeDef, genericArgs, BfPopulateType_IdentityNoRemapAlias);
  5269. }
  5270. else
  5271. {
  5272. if (nestedTypeDef->mIsPartial)
  5273. {
  5274. nestedTypeDef = GetCombinedPartialTypeDef(nestedTypeDef);
  5275. if (nestedTypeDef == NULL)
  5276. return NULL;
  5277. }
  5278. return ResolveTypeDef(nestedTypeDef, BfPopulateType_IdentityNoRemapAlias);
  5279. }
  5280. return NULL;
  5281. }
  5282. BfTypeDef* BfModule::GetCombinedPartialTypeDef(BfTypeDef* typeDef)
  5283. {
  5284. BF_ASSERT(!typeDef->mIsExplicitPartial);
  5285. if (!typeDef->mIsPartial)
  5286. return typeDef;
  5287. auto result = mSystem->FindTypeDef(typeDef->mFullName.ToString(), (int)typeDef->mGenericParamDefs.size());
  5288. return result;
  5289. }
  5290. BfTypeInstance* BfModule::GetOuterType(BfType* type)
  5291. {
  5292. if (type == NULL)
  5293. return NULL;
  5294. if (type->IsBoxed())
  5295. return GetOuterType(((BfBoxedType*)type)->mElementType);
  5296. auto typeInst = type->ToTypeInstance();
  5297. if ((typeInst == NULL) || (typeInst->mTypeDef->mOuterType == NULL))
  5298. return NULL;
  5299. auto outerTypeDef = typeInst->mTypeDef->mOuterType;
  5300. if (outerTypeDef->mIsPartial)
  5301. {
  5302. outerTypeDef = GetCombinedPartialTypeDef(outerTypeDef);
  5303. if (outerTypeDef == NULL)
  5304. return NULL;
  5305. }
  5306. BfTypeVector typeGenericArguments;
  5307. if (type->IsGenericTypeInstance())
  5308. {
  5309. auto genericType = (BfTypeInstance*)type;
  5310. typeGenericArguments = genericType->mGenericTypeInfo->mTypeGenericArguments;
  5311. }
  5312. BF_ASSERT((intptr)typeGenericArguments.size() >= (intptr)outerTypeDef->mGenericParamDefs.size());
  5313. typeGenericArguments.resize(outerTypeDef->mGenericParamDefs.size());
  5314. //auto outerType = ResolveTypeDef(outerTypeDef, typeGenericArguments, BfPopulateType_Declaration);
  5315. auto outerType = ResolveTypeDef(outerTypeDef, typeGenericArguments, BfPopulateType_Identity);
  5316. if (outerType == NULL)
  5317. return NULL;
  5318. return outerType->ToTypeInstance();
  5319. }
  5320. bool BfModule::IsInnerType(BfType* checkInnerType, BfType* checkOuterType)
  5321. {
  5322. BfType* outerType = GetOuterType(checkInnerType);
  5323. if (outerType == NULL)
  5324. return false;
  5325. if (outerType == checkOuterType)
  5326. return true;
  5327. return IsInnerType(outerType, checkOuterType);
  5328. }
  5329. bool BfModule::IsInnerType(BfTypeDef* checkInnerType, BfTypeDef* checkOuterType)
  5330. {
  5331. BF_ASSERT(!checkOuterType->mIsPartial);
  5332. if (checkInnerType->mNestDepth <= checkOuterType->mNestDepth)
  5333. return false;
  5334. while (true)
  5335. {
  5336. BfTypeDef* outerType = checkInnerType->mOuterType;
  5337. if (outerType == NULL)
  5338. return false;
  5339. if (outerType->mIsPartial)
  5340. outerType = mSystem->GetCombinedPartial(outerType);
  5341. if (outerType == checkOuterType)
  5342. return true;
  5343. checkInnerType = checkInnerType->mOuterType;
  5344. }
  5345. }
  5346. BfType* BfModule::ResolveTypeDef(BfTypeDef* typeDef, const BfTypeVector& genericArgs, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  5347. {
  5348. if (typeDef->mGenericParamDefs.size() == 0)
  5349. return ResolveTypeDef(typeDef, populateType, resolveFlags);
  5350. if ((typeDef == mCompiler->mArray1TypeDef) || (typeDef == mCompiler->mArray2TypeDef))
  5351. {
  5352. auto arrayInstType = mContext->mArrayTypeInstancePool.Get();
  5353. arrayInstType->mContext = mContext;
  5354. if (typeDef == mCompiler->mArray1TypeDef)
  5355. arrayInstType->mDimensions = 1;
  5356. else
  5357. arrayInstType->mDimensions = 2;
  5358. auto typeRef = mContext->mTypeDefTypeRefPool.Get();
  5359. typeRef->mTypeDef = typeDef;
  5360. delete arrayInstType->mGenericTypeInfo;
  5361. arrayInstType->mGenericTypeInfo = new BfGenericTypeInfo();
  5362. arrayInstType->mTypeDef = typeDef;
  5363. arrayInstType->mGenericTypeInfo->mIsUnspecialized = false;
  5364. arrayInstType->mGenericTypeInfo->mTypeGenericArguments.clear();
  5365. for (auto genericArg : genericArgs)
  5366. {
  5367. arrayInstType->mGenericTypeInfo->mIsUnspecialized |= genericArg->IsGenericParam();
  5368. arrayInstType->mGenericTypeInfo->mTypeGenericArguments.push_back(genericArg);
  5369. }
  5370. if (genericArgs.size() == 0)
  5371. {
  5372. for (int i = 0; i < (int)typeDef->mGenericParamDefs.size(); i++)
  5373. {
  5374. auto genericParamTypeRef = GetGenericParamType(BfGenericParamKind_Type, i);
  5375. arrayInstType->mGenericTypeInfo->mTypeGenericArguments.push_back(genericParamTypeRef);
  5376. arrayInstType->mGenericTypeInfo->mIsUnspecialized = true;
  5377. }
  5378. }
  5379. auto resolvedType = ResolveType(arrayInstType, populateType, resolveFlags);
  5380. if (resolvedType != arrayInstType)
  5381. {
  5382. delete arrayInstType->mGenericTypeInfo;
  5383. arrayInstType->mGenericTypeInfo = NULL;
  5384. mContext->mArrayTypeInstancePool.GiveBack(arrayInstType);
  5385. mContext->mTypeDefTypeRefPool.GiveBack(typeRef);
  5386. }
  5387. BF_ASSERT((resolvedType == NULL) || resolvedType->IsTypeInstance() || resolvedType->IsPrimitiveType());
  5388. return resolvedType;
  5389. }
  5390. BfTypeInstance* genericInstType;
  5391. if (typeDef->mTypeCode == BfTypeCode_TypeAlias)
  5392. genericInstType = mContext->mAliasTypePool.Get();
  5393. else
  5394. genericInstType = mContext->mGenericTypeInstancePool.Get();
  5395. delete genericInstType->mGenericTypeInfo;
  5396. genericInstType->mGenericTypeInfo = new BfGenericTypeInfo();
  5397. BF_ASSERT(genericInstType->mGenericTypeInfo->mGenericParams.size() == 0);
  5398. BF_ASSERT((genericInstType->mRebuildFlags & BfTypeRebuildFlag_AddedToWorkList) == 0);
  5399. genericInstType->mRebuildFlags = (BfTypeRebuildFlags)(genericInstType->mRebuildFlags & ~BfTypeRebuildFlag_InTempPool);
  5400. genericInstType->mContext = mContext;
  5401. auto typeRef = mContext->mTypeDefTypeRefPool.Get();
  5402. typeRef->mTypeDef = typeDef;
  5403. genericInstType->mTypeDef = typeDef;
  5404. genericInstType->mGenericTypeInfo->mIsUnspecialized = false;
  5405. genericInstType->mGenericTypeInfo->mTypeGenericArguments.clear();
  5406. genericInstType->mTypeFailed = false;
  5407. for (auto genericArg : genericArgs)
  5408. {
  5409. genericInstType->mGenericTypeInfo->mIsUnspecialized |= genericArg->IsGenericParam();
  5410. genericInstType->mGenericTypeInfo->mTypeGenericArguments.push_back(genericArg);
  5411. }
  5412. if (genericArgs.size() == 0)
  5413. {
  5414. for (int i = 0; i < (int)typeDef->mGenericParamDefs.size(); i++)
  5415. {
  5416. auto genericParamTypeRef = GetGenericParamType(BfGenericParamKind_Type, i);
  5417. genericInstType->mGenericTypeInfo->mTypeGenericArguments.push_back(genericParamTypeRef);
  5418. genericInstType->mGenericTypeInfo->mIsUnspecialized = true;
  5419. }
  5420. }
  5421. BfType* resolvedType = NULL;
  5422. bool failed = false;
  5423. // if (typeDef->mTypeCode == BfTypeCode_TypeAlias)
  5424. // {
  5425. // auto aliasType = (BfGenericTypeAliasType*)genericInstType;
  5426. // aliasType->mAliasToType = NULL;
  5427. // auto typeAliasDecl = (BfTypeAliasDeclaration*)typeDef->mTypeDeclaration;
  5428. // SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, aliasType);
  5429. // SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  5430. // BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  5431. // typeState.mCurTypeDef = typeDef;
  5432. // SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  5433. // if (typeAliasDecl->mAliasToType != NULL)
  5434. // aliasType->mAliasToType = ResolveTypeRef(typeAliasDecl->mAliasToType);
  5435. //
  5436. // resolvedType = ResolveType(genericInstType, BfPopulateType_IdentityNoRemapAlias);
  5437. // if ((resolvedType != NULL) && (populateType >= BfPopulateType_Declaration))
  5438. // PopulateType(resolvedType, populateType);
  5439. // }
  5440. // else
  5441. {
  5442. resolvedType = ResolveType(genericInstType, populateType, resolveFlags);
  5443. }
  5444. if (resolvedType != genericInstType)
  5445. {
  5446. BF_ASSERT(genericInstType->mGenericTypeInfo->mGenericParams.size() == 0);
  5447. BF_ASSERT((genericInstType->mRebuildFlags & BfTypeRebuildFlag_AddedToWorkList) == 0);
  5448. genericInstType->mRebuildFlags = (BfTypeRebuildFlags)(genericInstType->mRebuildFlags | BfTypeRebuildFlag_InTempPool);
  5449. delete genericInstType->mGenericTypeInfo;
  5450. genericInstType->mGenericTypeInfo = NULL;
  5451. if (typeDef->mTypeCode == BfTypeCode_TypeAlias)
  5452. mContext->mAliasTypePool.GiveBack((BfTypeAliasType*)genericInstType);
  5453. else
  5454. mContext->mGenericTypeInstancePool.GiveBack(genericInstType);
  5455. mContext->mTypeDefTypeRefPool.GiveBack(typeRef);
  5456. }
  5457. BF_ASSERT((resolvedType == NULL) || resolvedType->IsTypeInstance() || resolvedType->IsPrimitiveType());
  5458. return resolvedType;
  5459. }
  5460. int checkIdx = 0;
  5461. BfTypeDef* BfModule::ResolveGenericInstanceDef(BfGenericInstanceTypeRef* genericTypeRef, BfType** outType, BfResolveTypeRefFlags resolveFlags)
  5462. {
  5463. if (outType != NULL)
  5464. *outType = NULL;
  5465. BfTypeReference* typeRef = genericTypeRef->mElementType;
  5466. int numGenericParams = genericTypeRef->GetGenericArgCount();
  5467. BfTypeDef* curTypeDef = NULL;
  5468. if (mCurTypeInstance != NULL)
  5469. curTypeDef = mCurTypeInstance->mTypeDef;
  5470. if (auto directTypeDef = BfNodeDynCast<BfDirectTypeReference>(typeRef))
  5471. {
  5472. auto typeInst = directTypeDef->mType->ToTypeInstance();
  5473. return typeInst->mTypeDef;
  5474. }
  5475. auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef);
  5476. auto directStrTypeDef = BfNodeDynCastExact<BfDirectStrTypeReference>(typeRef);
  5477. if ((namedTypeRef != NULL) || (directStrTypeDef != NULL))
  5478. {
  5479. BfTypeLookupError error;
  5480. error.mRefNode = typeRef;
  5481. BfTypeDef* typeDef = FindTypeDef(typeRef, NULL, &error, numGenericParams);
  5482. if (typeDef != NULL)
  5483. {
  5484. BfAutoComplete* autoComplete = NULL;
  5485. if (mCompiler->IsAutocomplete())
  5486. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  5487. if ((autoComplete != NULL) && (autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(typeRef)))
  5488. {
  5489. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  5490. (autoComplete->mDefProp == NULL) && (typeDef->mTypeDeclaration != NULL))
  5491. {
  5492. autoComplete->mDefType = typeDef;
  5493. autoComplete->SetDefinitionLocation(typeDef->mTypeDeclaration->mNameNode);
  5494. }
  5495. }
  5496. if (mCompiler->mResolvePassData != NULL)
  5497. mCompiler->mResolvePassData->HandleTypeReference(typeRef, typeDef);
  5498. return typeDef;
  5499. }
  5500. if (mCurTypeInstance != NULL)
  5501. {
  5502. bool wasGenericParam = false;
  5503. // Check generics first
  5504. if (typeRef->IsA<BfNamedTypeReference>())
  5505. {
  5506. String findName = typeRef->ToString();
  5507. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsGenericTypeInstance()))
  5508. {
  5509. auto genericTypeInst = (BfTypeInstance*)mCurTypeInstance;
  5510. for (int genericParamIdx = 0; genericParamIdx < (int)curTypeDef->mGenericParamDefs.size(); genericParamIdx++)
  5511. {
  5512. String genericName = curTypeDef->mGenericParamDefs[genericParamIdx]->mName;
  5513. if (genericName == findName)
  5514. wasGenericParam = true;
  5515. }
  5516. }
  5517. if (mCurMethodInstance != NULL)
  5518. {
  5519. for (int genericParamIdx = 0; genericParamIdx < (int)mCurMethodInstance->mMethodDef->mGenericParams.size(); genericParamIdx++)
  5520. {
  5521. String genericName = mCurMethodInstance->mMethodDef->mGenericParams[genericParamIdx]->mName;
  5522. if (genericName == findName)
  5523. wasGenericParam = true;
  5524. }
  5525. }
  5526. }
  5527. if ((wasGenericParam) && ((resolveFlags & BfResolveTypeRefFlag_IgnoreLookupError) == 0))
  5528. Fail("Cannot use generic param as generic instance type", typeRef);
  5529. }
  5530. if (typeDef == NULL)
  5531. {
  5532. if ((resolveFlags & BfResolveTypeRefFlag_IgnoreLookupError) == 0)
  5533. TypeRefNotFound(typeRef);
  5534. return NULL;
  5535. }
  5536. }
  5537. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  5538. {
  5539. BfAutoParentNodeEntry autoParentNodeEntry(this, genericTypeRef);
  5540. auto type = ResolveTypeRef(qualifiedTypeRef, BfPopulateType_TypeDef, BfResolveTypeRefFlag_None, numGenericParams);
  5541. if (type == NULL)
  5542. return NULL;
  5543. if (outType != NULL)
  5544. *outType = type;
  5545. auto typeInst = type->ToTypeInstance();
  5546. if (typeInst != NULL)
  5547. return typeInst->mTypeDef;
  5548. }
  5549. if ((resolveFlags & BfResolveTypeRefFlag_IgnoreLookupError) == 0)
  5550. Fail("Invalid generic type", typeRef);
  5551. return NULL;
  5552. }
  5553. BfType* BfModule::ResolveGenericType(BfType* unspecializedType, BfTypeVector* typeGenericArguments, BfTypeVector* methodGenericArguments, bool allowFail)
  5554. {
  5555. if (unspecializedType->IsGenericParam())
  5556. {
  5557. auto genericParam = (BfGenericParamType*)unspecializedType;
  5558. if ((genericParam->mGenericParamKind == BfGenericParamKind_Type) && (typeGenericArguments != NULL))
  5559. {
  5560. if (genericParam->mGenericParamIdx < (int)typeGenericArguments->size())
  5561. return (*typeGenericArguments)[genericParam->mGenericParamIdx];
  5562. BF_ASSERT(allowFail);
  5563. }
  5564. if ((genericParam->mGenericParamKind == BfGenericParamKind_Method) && (methodGenericArguments != NULL))
  5565. {
  5566. if (genericParam->mGenericParamIdx < (int)methodGenericArguments->size())
  5567. return (*methodGenericArguments)[genericParam->mGenericParamIdx];
  5568. BF_ASSERT(allowFail);
  5569. }
  5570. return unspecializedType;
  5571. }
  5572. if (!unspecializedType->IsUnspecializedType())
  5573. return unspecializedType;
  5574. if (unspecializedType->IsUnknownSizedArray())
  5575. {
  5576. auto* arrayType = (BfUnknownSizedArrayType*)unspecializedType;
  5577. auto elementType = ResolveGenericType(arrayType->mElementType, typeGenericArguments, methodGenericArguments, allowFail);
  5578. if (elementType == NULL)
  5579. return NULL;
  5580. if (elementType->IsVar())
  5581. return elementType;
  5582. auto sizeType = ResolveGenericType(arrayType->mElementCountSource, typeGenericArguments, methodGenericArguments, allowFail);
  5583. if (sizeType == NULL)
  5584. return NULL;
  5585. if (sizeType->IsConstExprValue())
  5586. {
  5587. return CreateSizedArrayType(elementType, ((BfConstExprValueType*)sizeType)->mValue.mInt32);
  5588. }
  5589. return CreateUnknownSizedArrayType(elementType, sizeType);
  5590. }
  5591. if (unspecializedType->IsSizedArray())
  5592. {
  5593. auto* arrayType = (BfSizedArrayType*)unspecializedType;
  5594. auto elementType = ResolveGenericType(arrayType->mElementType, typeGenericArguments, methodGenericArguments, allowFail);
  5595. if (elementType == NULL)
  5596. return NULL;
  5597. if (elementType->IsVar())
  5598. return elementType;
  5599. elementType = FixIntUnknown(elementType);
  5600. return CreateSizedArrayType(elementType, (int)arrayType->mElementCount);
  5601. }
  5602. if (unspecializedType->IsRef())
  5603. {
  5604. auto refType = (BfRefType*)unspecializedType;
  5605. auto elementType = ResolveGenericType(refType->GetUnderlyingType(), typeGenericArguments, methodGenericArguments, allowFail);
  5606. if (elementType == NULL)
  5607. return NULL;
  5608. if (elementType->IsVar())
  5609. return elementType;
  5610. elementType = FixIntUnknown(elementType);
  5611. return CreateRefType(elementType, refType->mRefKind);
  5612. }
  5613. if (unspecializedType->IsPointer())
  5614. {
  5615. auto ptrType = (BfPointerType*)unspecializedType;
  5616. auto elementType = ResolveGenericType(ptrType->GetUnderlyingType(), typeGenericArguments, methodGenericArguments, allowFail);
  5617. if (elementType == NULL)
  5618. return NULL;
  5619. if (elementType->IsVar())
  5620. return elementType;
  5621. elementType = FixIntUnknown(elementType);
  5622. return CreatePointerType(elementType);
  5623. }
  5624. if (unspecializedType->IsArray())
  5625. {
  5626. auto arrayType = (BfArrayType*)unspecializedType;
  5627. auto elementType = ResolveGenericType(arrayType->GetUnderlyingType(), typeGenericArguments, methodGenericArguments, allowFail);
  5628. if (elementType == NULL)
  5629. return NULL;
  5630. if (elementType->IsVar())
  5631. return elementType;
  5632. elementType = FixIntUnknown(elementType);
  5633. return CreateArrayType(elementType, arrayType->mDimensions);
  5634. }
  5635. if (unspecializedType->IsTuple())
  5636. {
  5637. bool wantGeneric = false;
  5638. bool isUnspecialized = false;
  5639. auto unspecializedTupleType = (BfTypeInstance*)unspecializedType;
  5640. auto unspecializedGenericTupleType = unspecializedTupleType->ToGenericTypeInstance();
  5641. Array<String> fieldNames;
  5642. BfTypeVector fieldTypes;
  5643. bool hadChange = false;
  5644. for (auto& fieldInstance : unspecializedTupleType->mFieldInstances)
  5645. {
  5646. fieldNames.push_back(fieldInstance.GetFieldDef()->mName);
  5647. auto origGenericArg = fieldInstance.mResolvedType;
  5648. auto newGenericArg = ResolveGenericType(origGenericArg, typeGenericArguments, methodGenericArguments, allowFail);
  5649. if (newGenericArg == NULL)
  5650. return NULL;
  5651. if (newGenericArg->IsVar())
  5652. return newGenericArg;
  5653. if (newGenericArg->IsGenericParam())
  5654. wantGeneric = true;
  5655. if (newGenericArg->IsUnspecializedType())
  5656. isUnspecialized = true;
  5657. if (newGenericArg->IsVar())
  5658. wantGeneric = mContext->mBfObjectType;
  5659. //wantGeneric = true;
  5660. if (newGenericArg != origGenericArg)
  5661. hadChange = true;
  5662. fieldTypes.push_back(newGenericArg);
  5663. }
  5664. if (!hadChange)
  5665. return unspecializedType;
  5666. if (unspecializedGenericTupleType == NULL)
  5667. wantGeneric = false;
  5668. auto baseType = (BfTypeInstance*)ResolveTypeDef(mContext->mCompiler->mValueTypeTypeDef);
  5669. BfTypeInstance* tupleType = NULL;
  5670. if (wantGeneric)
  5671. {
  5672. Array<BfType*> genericArgs;
  5673. for (int genericArgIdx = 0; genericArgIdx < (int)unspecializedGenericTupleType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  5674. {
  5675. BfType* resolvedArg = unspecializedGenericTupleType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx];
  5676. if (resolvedArg->IsUnspecializedType())
  5677. {
  5678. resolvedArg = ResolveGenericType(resolvedArg, typeGenericArguments, methodGenericArguments, allowFail);
  5679. if (resolvedArg == NULL)
  5680. return NULL;
  5681. if (resolvedArg->IsVar())
  5682. return resolvedArg;
  5683. }
  5684. genericArgs.push_back(resolvedArg);
  5685. }
  5686. auto actualTupleType = mContext->mTupleTypePool.Get();
  5687. delete actualTupleType->mGenericTypeInfo;
  5688. actualTupleType->mGenericTypeInfo = new BfGenericTypeInfo();
  5689. actualTupleType->mGenericTypeInfo->mIsUnspecialized = false;
  5690. actualTupleType->mGenericTypeInfo->mIsUnspecializedVariation = false;
  5691. actualTupleType->mGenericTypeInfo->mTypeGenericArguments = genericArgs;
  5692. for (int genericArgIdx = 0; genericArgIdx < (int)unspecializedGenericTupleType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  5693. {
  5694. auto typeGenericArg = genericArgs[genericArgIdx];
  5695. if ((typeGenericArg->IsGenericParam()) || (typeGenericArg->IsUnspecializedType()))
  5696. actualTupleType->mGenericTypeInfo->mIsUnspecialized = true;
  5697. actualTupleType->mGenericTypeInfo->mGenericParams.push_back(unspecializedGenericTupleType->mGenericTypeInfo->mGenericParams[genericArgIdx]->AddRef());
  5698. }
  5699. CheckUnspecializedGenericType(actualTupleType, BfPopulateType_Identity);
  5700. if (isUnspecialized)
  5701. {
  5702. actualTupleType->mGenericTypeInfo->mIsUnspecialized = true;
  5703. actualTupleType->mGenericTypeInfo->mIsUnspecializedVariation = true;
  5704. }
  5705. actualTupleType->mIsUnspecializedType = actualTupleType->mGenericTypeInfo->mIsUnspecialized;
  5706. actualTupleType->mIsUnspecializedTypeVariation = actualTupleType->mGenericTypeInfo->mIsUnspecializedVariation;
  5707. actualTupleType->Init(baseType->mTypeDef->mProject, baseType);
  5708. for (int fieldIdx = 0; fieldIdx < (int)fieldTypes.size(); fieldIdx++)
  5709. {
  5710. String fieldName = fieldNames[fieldIdx];
  5711. BfFieldDef* fieldDef = actualTupleType->AddField(fieldName);
  5712. }
  5713. tupleType = actualTupleType;
  5714. }
  5715. else
  5716. {
  5717. auto actualTupleType = new BfTupleType();
  5718. actualTupleType->mIsUnspecializedType = isUnspecialized;
  5719. actualTupleType->mIsUnspecializedTypeVariation = isUnspecialized;
  5720. actualTupleType->Init(baseType->mTypeDef->mProject, baseType);
  5721. for (int fieldIdx = 0; fieldIdx < (int)fieldTypes.size(); fieldIdx++)
  5722. {
  5723. String fieldName = fieldNames[fieldIdx];
  5724. BfFieldDef* fieldDef = actualTupleType->AddField(fieldName);
  5725. }
  5726. tupleType = actualTupleType;
  5727. }
  5728. tupleType->mContext = mContext;
  5729. tupleType->mFieldInstances.Resize(fieldTypes.size());
  5730. for (int fieldIdx = 0; fieldIdx < (int)fieldTypes.size(); fieldIdx++)
  5731. {
  5732. BfFieldInstance* fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  5733. fieldInstance->mFieldIdx = fieldIdx;
  5734. fieldInstance->SetResolvedType(fieldTypes[fieldIdx]);
  5735. fieldInstance->mOwner = tupleType;
  5736. }
  5737. bool failed = false;
  5738. BfType* resolvedType = NULL;
  5739. if (!failed)
  5740. resolvedType = ResolveType(tupleType, BfPopulateType_Identity);
  5741. if (resolvedType != tupleType)
  5742. {
  5743. delete tupleType->mGenericTypeInfo;
  5744. tupleType->mGenericTypeInfo = NULL;
  5745. mContext->mTupleTypePool.GiveBack((BfTupleType*)tupleType);
  5746. }
  5747. BF_ASSERT((resolvedType == NULL) || resolvedType->IsTypeInstance() || resolvedType->IsPrimitiveType());
  5748. return resolvedType;
  5749. }
  5750. if ((unspecializedType->IsDelegateFromTypeRef()) || (unspecializedType->IsFunctionFromTypeRef()))
  5751. {
  5752. BfTypeInstance* unspecializedDelegateType = (BfTypeInstance*)unspecializedType;
  5753. BfTypeInstance* unspecializedGenericDelegateType = unspecializedType->ToGenericTypeInstance();
  5754. BfDelegateInfo* unspecializedDelegateInfo = unspecializedType->GetDelegateInfo();
  5755. bool wantGeneric = false;
  5756. bool isUnspecialized = false;
  5757. auto _CheckType = [&](BfType* type)
  5758. {
  5759. if (type->IsGenericParam())
  5760. wantGeneric = true;
  5761. if (type->IsUnspecializedType())
  5762. isUnspecialized = true;
  5763. };
  5764. bool failed = false;
  5765. bool hasTypeGenerics = false;
  5766. auto returnType = ResolveGenericType(unspecializedDelegateInfo->mReturnType, typeGenericArguments, methodGenericArguments, allowFail);
  5767. if (returnType == NULL)
  5768. return NULL;
  5769. if (returnType->IsVar())
  5770. return returnType;
  5771. _CheckType(returnType);
  5772. if (returnType->IsGenericParam())
  5773. hasTypeGenerics |= ((BfGenericParamType*)returnType)->mGenericParamKind == BfGenericParamKind_Type;
  5774. Array<BfType*> paramTypes;
  5775. for (auto param : unspecializedDelegateInfo->mParams)
  5776. {
  5777. auto paramType = ResolveGenericType(param, typeGenericArguments, methodGenericArguments, allowFail);
  5778. if (paramType == NULL)
  5779. return NULL;
  5780. if (paramType->IsVar())
  5781. return paramType;
  5782. paramTypes.Add(paramType);
  5783. _CheckType(paramType);
  5784. }
  5785. if (unspecializedGenericDelegateType == NULL)
  5786. wantGeneric = false;
  5787. BfTypeInstance* delegateType = NULL;
  5788. auto baseDelegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  5789. if (wantGeneric)
  5790. {
  5791. Array<BfType*> genericArgs;
  5792. for (int genericArgIdx = 0; genericArgIdx < (int)unspecializedGenericDelegateType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  5793. {
  5794. BfType* resolvedArg = unspecializedGenericDelegateType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx];
  5795. if (resolvedArg->IsUnspecializedType())
  5796. {
  5797. resolvedArg = ResolveGenericType(resolvedArg, typeGenericArguments, methodGenericArguments, allowFail);
  5798. if (resolvedArg == NULL)
  5799. return NULL;
  5800. if (resolvedArg->IsVar())
  5801. return resolvedArg;
  5802. }
  5803. genericArgs.push_back(resolvedArg);
  5804. }
  5805. auto dlgType = mContext->mDelegateTypePool.Get();
  5806. delete dlgType->mGenericTypeInfo;
  5807. dlgType->mGenericTypeInfo = new BfGenericTypeInfo();
  5808. dlgType->mGenericTypeInfo->mFinishedGenericParams = true;
  5809. dlgType->mGenericTypeInfo->mIsUnspecialized = false;
  5810. dlgType->mGenericTypeInfo->mIsUnspecializedVariation = false;
  5811. dlgType->mGenericTypeInfo->mTypeGenericArguments = genericArgs;
  5812. for (int genericArgIdx = 0; genericArgIdx < (int)unspecializedGenericDelegateType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  5813. {
  5814. auto typeGenericArg = genericArgs[genericArgIdx];
  5815. if ((typeGenericArg->IsGenericParam()) || (typeGenericArg->IsUnspecializedType()))
  5816. dlgType->mGenericTypeInfo->mIsUnspecialized = true;
  5817. dlgType->mGenericTypeInfo->mGenericParams.push_back(unspecializedGenericDelegateType->mGenericTypeInfo->mGenericParams[genericArgIdx]->AddRef());
  5818. }
  5819. CheckUnspecializedGenericType(dlgType, BfPopulateType_Identity);
  5820. if (isUnspecialized)
  5821. {
  5822. dlgType->mGenericTypeInfo->mIsUnspecialized = true;
  5823. dlgType->mGenericTypeInfo->mIsUnspecializedVariation = true;
  5824. }
  5825. dlgType->mIsUnspecializedType = dlgType->mGenericTypeInfo->mIsUnspecialized;
  5826. dlgType->mIsUnspecializedTypeVariation = dlgType->mGenericTypeInfo->mIsUnspecializedVariation;
  5827. delegateType = dlgType;
  5828. }
  5829. else
  5830. {
  5831. auto dlgType = mContext->mDelegateTypePool.Get();
  5832. dlgType->mIsUnspecializedType = isUnspecialized;
  5833. dlgType->mIsUnspecializedTypeVariation = isUnspecialized;
  5834. delegateType = dlgType;
  5835. }
  5836. delete delegateType->mTypeDef;
  5837. delegateType->mTypeDef = NULL;
  5838. BfDelegateInfo* delegateInfo = delegateType->GetDelegateInfo();
  5839. delegateInfo->mParams.Clear();
  5840. BfTypeDef* typeDef = new BfTypeDef();
  5841. typeDef->mProject = baseDelegateType->mTypeDef->mProject;
  5842. typeDef->mSystem = mCompiler->mSystem;
  5843. typeDef->mName = mSystem->mEmptyAtom;
  5844. typeDef->mTypeCode = unspecializedDelegateType->mTypeDef->mTypeCode;
  5845. typeDef->mIsDelegate = unspecializedDelegateType->mTypeDef->mIsDelegate;
  5846. typeDef->mIsFunction = unspecializedDelegateType->mTypeDef->mIsFunction;
  5847. BfMethodDef* unspecializedInvokeMethodDef = unspecializedDelegateType->mTypeDef->GetMethodByName("Invoke");
  5848. BfMethodDef* methodDef = new BfMethodDef();
  5849. methodDef->mDeclaringType = typeDef;
  5850. methodDef->mName = "Invoke";
  5851. methodDef->mProtection = BfProtection_Public;
  5852. methodDef->mIdx = 0;
  5853. methodDef->mIsStatic = !typeDef->mIsDelegate && !unspecializedDelegateInfo->mHasExplicitThis;
  5854. methodDef->mHasExplicitThis = unspecializedDelegateInfo->mHasExplicitThis;
  5855. auto directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  5856. delegateInfo->mDirectAllocNodes.push_back(directTypeRef);
  5857. if (typeDef->mIsDelegate)
  5858. directTypeRef->Init(delegateType);
  5859. else
  5860. directTypeRef->Init(ResolveTypeDef(mCompiler->mFunctionTypeDef));
  5861. typeDef->mBaseTypes.push_back(directTypeRef);
  5862. directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  5863. delegateInfo->mDirectAllocNodes.push_back(directTypeRef);
  5864. directTypeRef->Init(returnType);
  5865. methodDef->mReturnTypeRef = directTypeRef;
  5866. delegateInfo->mReturnType = returnType;
  5867. delegateInfo->mHasExplicitThis = unspecializedDelegateInfo->mHasExplicitThis;
  5868. int paramIdx = 0;
  5869. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  5870. {
  5871. auto paramType = paramTypes[paramIdx];
  5872. BfParameterDef* unspecializedParamDef = unspecializedInvokeMethodDef->mParams[paramIdx];
  5873. if (!paramType->IsReified())
  5874. delegateType->mIsReified = false;
  5875. auto directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  5876. delegateInfo->mDirectAllocNodes.push_back(directTypeRef);
  5877. directTypeRef->Init(paramType);
  5878. BfParameterDef* paramDef = new BfParameterDef();
  5879. paramDef->mTypeRef = directTypeRef;
  5880. paramDef->mName = unspecializedParamDef->mName;
  5881. methodDef->mParams.push_back(paramDef);
  5882. paramIdx++;
  5883. delegateInfo->mParams.Add(paramType);
  5884. }
  5885. typeDef->mMethods.push_back(methodDef);
  5886. if (unspecializedInvokeMethodDef->mIsMutating)
  5887. {
  5888. if ((delegateInfo->mParams[0]->IsValueType()) || (delegateInfo->mParams[0]->IsGenericParam()))
  5889. methodDef->mIsMutating = unspecializedInvokeMethodDef->mIsMutating;
  5890. }
  5891. //
  5892. if (typeDef->mIsDelegate)
  5893. {
  5894. BfDefBuilder::AddMethod(typeDef, BfMethodType_Ctor, BfProtection_Public, false, "");
  5895. BfDefBuilder::AddDynamicCastMethods(typeDef);
  5896. }
  5897. delegateType->mContext = mContext;
  5898. delegateType->mTypeDef = typeDef;
  5899. BfType* resolvedType = NULL;
  5900. if (!failed)
  5901. resolvedType = ResolveType(delegateType, BfPopulateType_Identity);
  5902. if (resolvedType == delegateType)
  5903. {
  5904. AddDependency(directTypeRef->mType, delegateType, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  5905. for (auto paramType : paramTypes)
  5906. AddDependency(paramType, delegateType, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  5907. }
  5908. else
  5909. {
  5910. delete delegateType->mGenericTypeInfo;
  5911. delegateType->mGenericTypeInfo = NULL;
  5912. mContext->mDelegateTypePool.GiveBack((BfDelegateType*)delegateType);
  5913. }
  5914. BF_ASSERT((resolvedType == NULL) || resolvedType->IsTypeInstance() || resolvedType->IsPrimitiveType());
  5915. return resolvedType;
  5916. }
  5917. if (unspecializedType->IsGenericTypeInstance())
  5918. {
  5919. auto genericTypeInst = (BfTypeInstance*)unspecializedType;
  5920. BfTypeVector genericArgs;
  5921. for (auto genericArg : genericTypeInst->mGenericTypeInfo->mTypeGenericArguments)
  5922. {
  5923. if (genericArg->IsUnspecializedType())
  5924. {
  5925. auto resolvedArg = ResolveGenericType(genericArg, typeGenericArguments, methodGenericArguments, allowFail);
  5926. if (resolvedArg == NULL)
  5927. return NULL;
  5928. if (resolvedArg->IsVar())
  5929. return resolvedArg;
  5930. genericArgs.push_back(resolvedArg);
  5931. }
  5932. else
  5933. genericArgs.push_back(genericArg);
  5934. }
  5935. auto resolvedType = ResolveTypeDef(genericTypeInst->mTypeDef, genericArgs, BfPopulateType_BaseType);
  5936. BfTypeInstance* specializedType = NULL;
  5937. if (resolvedType != NULL)
  5938. specializedType = resolvedType->ToGenericTypeInstance();
  5939. if (specializedType != NULL)
  5940. {
  5941. if (specializedType->mGenericTypeInfo->mHadValidateErrors)
  5942. return NULL;
  5943. }
  5944. return specializedType;
  5945. }
  5946. return unspecializedType;
  5947. }
  5948. BfType* BfModule::ResolveType(BfType* lookupType, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  5949. {
  5950. BfResolvedTypeSet::LookupContext lookupCtx;
  5951. lookupCtx.mModule = this;
  5952. lookupCtx.mResolveFlags = resolveFlags;
  5953. BfResolvedTypeSet::Entry* resolvedEntry = NULL;
  5954. bool inserted = mContext->mResolvedTypes.Insert(lookupType, &lookupCtx, &resolvedEntry);
  5955. if (resolvedEntry == NULL)
  5956. return NULL;
  5957. if (!inserted)
  5958. {
  5959. auto resolvedTypeRef = resolvedEntry->mValue;
  5960. PopulateType(resolvedTypeRef, populateType);
  5961. return resolvedTypeRef;
  5962. }
  5963. if (lookupType->IsGenericTypeInstance())
  5964. CheckUnspecializedGenericType((BfTypeInstance*)lookupType, populateType);
  5965. if (lookupType->IsTuple())
  5966. {
  5967. auto tupleType = (BfTupleType*)lookupType;
  5968. tupleType->Finish();
  5969. }
  5970. resolvedEntry->mValue = lookupType;
  5971. InitType(lookupType, populateType);
  5972. return lookupType;
  5973. }
  5974. bool BfModule::IsUnboundGeneric(BfType* type)
  5975. {
  5976. if (type->IsVar())
  5977. return true;
  5978. if (!type->IsGenericParam())
  5979. return false;
  5980. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)type);
  5981. return (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0;
  5982. }
  5983. BfGenericParamInstance* BfModule::GetGenericTypeParamInstance(int genericParamIdx)
  5984. {
  5985. // When we're evaluating a method, make sure the params refer back to that method context
  5986. auto curTypeInstance = mCurTypeInstance;
  5987. //TODO: This caused MethodToString issues with interface "implementation method not found" errors
  5988. // if (mCurMethodInstance != NULL)
  5989. // curTypeInstance = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  5990. BfTypeInstance* genericTypeInst = curTypeInstance->ToGenericTypeInstance();
  5991. if ((genericTypeInst->IsIncomplete()) && (genericTypeInst->mGenericTypeInfo->mGenericParams.size() == 0))
  5992. {
  5993. // Set this to NULL so we don't recurse infinitely
  5994. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, NULL);
  5995. PopulateType(genericTypeInst, BfPopulateType_Declaration);
  5996. }
  5997. if (genericParamIdx >= (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size())
  5998. {
  5999. // Extern constraints should always be directly used - they don't get extended
  6000. return genericTypeInst->mGenericTypeInfo->mGenericParams[genericParamIdx];
  6001. }
  6002. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  6003. {
  6004. auto activeTypeDef = GetActiveTypeDef(NULL, true);
  6005. if ((activeTypeDef->mTypeDeclaration != genericTypeInst->mTypeDef->mTypeDeclaration) && (activeTypeDef->IsExtension()))
  6006. {
  6007. BfTypeDef* lookupTypeDef = activeTypeDef;
  6008. while (lookupTypeDef->mNestDepth > genericTypeInst->mTypeDef->mNestDepth)
  6009. lookupTypeDef = lookupTypeDef->mOuterType;
  6010. BfGenericExtensionEntry* genericExEntry;
  6011. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.TryGetValue(lookupTypeDef, &genericExEntry))
  6012. {
  6013. return genericExEntry->mGenericParams[genericParamIdx];
  6014. }
  6015. else
  6016. {
  6017. if ((mCompiler->mResolvePassData == NULL) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  6018. {
  6019. BFMODULE_FATAL(this, "Invalid GetGenericParamInstance with extension");
  6020. }
  6021. }
  6022. }
  6023. }
  6024. BF_ASSERT(genericTypeInst != NULL);
  6025. return genericTypeInst->mGenericTypeInfo->mGenericParams[genericParamIdx];
  6026. }
  6027. void BfModule::GetActiveTypeGenericParamInstances(SizedArray<BfGenericParamInstance*, 4>& genericParamInstances)
  6028. {
  6029. // When we're evaluating a method, make sure the params refer back to that method context
  6030. auto curTypeInstance = mCurTypeInstance;
  6031. if (mCurMethodInstance != NULL)
  6032. curTypeInstance = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  6033. BfTypeInstance* genericTypeInst = curTypeInstance->ToGenericTypeInstance();
  6034. if ((genericTypeInst->IsIncomplete()) && (genericTypeInst->mGenericTypeInfo->mGenericParams.size() == 0))
  6035. {
  6036. // Set this to NULL so we don't recurse infinitely
  6037. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, NULL);
  6038. PopulateType(genericTypeInst, BfPopulateType_Declaration);
  6039. }
  6040. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  6041. {
  6042. auto activeTypeDef = GetActiveTypeDef(NULL, true);
  6043. if ((activeTypeDef->mTypeDeclaration != genericTypeInst->mTypeDef->mTypeDeclaration) && (activeTypeDef->IsExtension()))
  6044. {
  6045. BfTypeDef* lookupTypeDef = activeTypeDef;
  6046. while (lookupTypeDef->mNestDepth > genericTypeInst->mTypeDef->mNestDepth)
  6047. lookupTypeDef = lookupTypeDef->mOuterType;
  6048. BfGenericExtensionEntry* genericExEntry;
  6049. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.TryGetValue(lookupTypeDef, &genericExEntry))
  6050. {
  6051. for (auto entry : genericExEntry->mGenericParams)
  6052. genericParamInstances.Add(entry);
  6053. auto genericTypeInfo = genericTypeInst->mGenericTypeInfo;
  6054. // Add root extern constraints - they don't get extended
  6055. for (int genericParamIdx = (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size(); genericParamIdx < genericTypeInst->mGenericTypeInfo->mGenericParams.size(); genericParamIdx++)
  6056. genericParamInstances.Add(genericTypeInst->mGenericTypeInfo->mGenericParams[genericParamIdx]);
  6057. return;
  6058. }
  6059. else
  6060. {
  6061. if ((mCompiler->mResolvePassData == NULL) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  6062. {
  6063. BFMODULE_FATAL(this, "Invalid GetGenericParamInstance with extension");
  6064. }
  6065. }
  6066. }
  6067. }
  6068. BF_ASSERT(genericTypeInst != NULL);
  6069. for (auto entry : genericTypeInst->mGenericTypeInfo->mGenericParams)
  6070. genericParamInstances.Add(entry);
  6071. }
  6072. BfGenericParamInstance* BfModule::GetGenericParamInstance(BfGenericParamType* type)
  6073. {
  6074. if (type->mGenericParamKind == BfGenericParamKind_Method)
  6075. {
  6076. return mCurMethodInstance->mMethodInfoEx->mGenericParams[type->mGenericParamIdx];
  6077. }
  6078. return GetGenericTypeParamInstance(type->mGenericParamIdx);
  6079. }
  6080. BfType* BfModule::ResolveTypeResult(BfTypeReference* typeRef, BfType* resolvedTypeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  6081. {
  6082. if (mCompiler->mIsResolveOnly)
  6083. {
  6084. bool isGetDefinition = false;
  6085. BfAutoComplete* autoComplete = NULL;
  6086. if (mCompiler->IsAutocomplete())
  6087. {
  6088. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  6089. isGetDefinition = autoComplete->mIsGetDefinition || (autoComplete->mResolveType == BfResolveType_GetResultString);
  6090. }
  6091. BfSourceData* typeRefSource = NULL;
  6092. if (typeRef->IsTemporary())
  6093. {
  6094. BfTypeReference* checkTypeRef = typeRef;
  6095. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(checkTypeRef))
  6096. checkTypeRef = genericTypeRef->mElementType;
  6097. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(checkTypeRef))
  6098. typeRefSource = namedTypeRef->mNameNode->GetSourceData();
  6099. }
  6100. else
  6101. typeRefSource = typeRef->GetSourceData();
  6102. bool wantsFileNamespaceInfo = (((mCompiler->mResolvePassData->mSourceClassifier != NULL) || (isGetDefinition) || (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Namespace)) &&
  6103. (typeRefSource != NULL) && (mCompiler->mResolvePassData->mParser != NULL) &&
  6104. (typeRefSource == mCompiler->mResolvePassData->mParser->mSourceData));
  6105. bool wantsAllNamespaceInfo = (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Namespace) && (mCompiler->mResolvePassData->mParser == NULL);
  6106. if (wantsFileNamespaceInfo || wantsAllNamespaceInfo)
  6107. {
  6108. //TODO: By only breaking out for "mIgnoreErrors", we classified elements (below) even when a resolvedTypeRef was not found!
  6109. //Why did we have this mIgnoreErrors check in there?
  6110. // if ((resolvedTypeRef == NULL) && (mIgnoreErrors))
  6111. if (resolvedTypeRef == NULL)
  6112. {
  6113. return NULL;
  6114. }
  6115. BfTypeInstance* resolvedTypeInstance = NULL;
  6116. if (resolvedTypeRef != NULL)
  6117. resolvedTypeInstance = resolvedTypeRef->ToTypeInstance();
  6118. bool isNamespace = false;
  6119. auto checkTypeRef = typeRef;
  6120. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(checkTypeRef))
  6121. checkTypeRef = genericTypeRef->mElementType;
  6122. auto headTypeRef = checkTypeRef;
  6123. if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(checkTypeRef))
  6124. checkTypeRef = elementedTypeRef->mElementType;
  6125. if (!mIsInsideAutoComplete)
  6126. {
  6127. if ((resolvedTypeInstance != NULL) && (resolvedTypeInstance->mTypeDef->IsGlobalsContainer()))
  6128. {
  6129. isNamespace = true;
  6130. }
  6131. else
  6132. {
  6133. //TODO: This broke colorizing of inner expressions for things like "T2[T3]"
  6134. //mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(typeRef);
  6135. }
  6136. }
  6137. while (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(checkTypeRef))
  6138. {
  6139. if ((mCompiler->mResolvePassData->mSourceClassifier != NULL) && (checkTypeRef == headTypeRef) && (resolvedTypeRef->IsObjectOrInterface()))
  6140. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(qualifiedTypeRef->mRight, resolvedTypeRef->IsInterface() ? BfSourceElementType_Interface : BfSourceElementType_RefType);
  6141. StringView leftString = qualifiedTypeRef->mLeft->ToStringView();
  6142. BfSizedAtomComposite leftComposite;
  6143. bool isValid = mSystem->ParseAtomComposite(leftString, leftComposite);
  6144. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  6145. mCompiler->mResolvePassData->mSourceClassifier->SetHighestElementType(qualifiedTypeRef->mRight, isNamespace ? BfSourceElementType_Namespace : BfSourceElementType_Type);
  6146. if (resolvedTypeInstance == NULL)
  6147. {
  6148. if ((isValid) && (mCompiler->mSystem->ContainsNamespace(leftComposite, mCurTypeInstance->mTypeDef->mProject)))
  6149. isNamespace = true;
  6150. }
  6151. else if ((isValid) && (resolvedTypeInstance->mTypeDef->mNamespace.EndsWith(leftComposite)) && (resolvedTypeInstance->mTypeDef->mOuterType == NULL))
  6152. {
  6153. if (autoComplete != NULL)
  6154. {
  6155. if (autoComplete->CheckFixit(typeRef))
  6156. autoComplete->FixitCheckNamespace(GetActiveTypeDef(), qualifiedTypeRef->mLeft, qualifiedTypeRef->mDot);
  6157. autoComplete->CheckNamespace(qualifiedTypeRef->mLeft, resolvedTypeInstance->mTypeDef->mNamespace);
  6158. }
  6159. mCompiler->mResolvePassData->HandleNamespaceReference(qualifiedTypeRef->mLeft, resolvedTypeInstance->mTypeDef->mNamespace);
  6160. isNamespace = true;
  6161. }
  6162. checkTypeRef = qualifiedTypeRef->mLeft;
  6163. }
  6164. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(checkTypeRef))
  6165. {
  6166. auto checkNameNode = namedTypeRef->mNameNode;
  6167. bool setType = false;
  6168. if ((mCompiler->mResolvePassData->mSourceClassifier != NULL) && (checkTypeRef == headTypeRef) && (resolvedTypeRef->IsObjectOrInterface()))
  6169. {
  6170. if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(checkNameNode))
  6171. {
  6172. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(qualifiedNameNode->mRight, resolvedTypeRef->IsInterface() ? BfSourceElementType_Interface : BfSourceElementType_RefType);
  6173. }
  6174. else
  6175. {
  6176. setType = true;
  6177. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(checkNameNode, resolvedTypeRef->IsInterface() ? BfSourceElementType_Interface : BfSourceElementType_RefType);
  6178. }
  6179. }
  6180. while (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(checkNameNode))
  6181. {
  6182. StringView leftString = qualifiedNameNode->mLeft->ToStringView();
  6183. BfSizedAtomComposite leftComposite;
  6184. bool isValid = mSystem->ParseAtomComposite(leftString, leftComposite);
  6185. if (mCompiler->mResolvePassData->mSourceClassifier != NULL)
  6186. mCompiler->mResolvePassData->mSourceClassifier->SetHighestElementType(qualifiedNameNode->mRight, isNamespace ? BfSourceElementType_Namespace : BfSourceElementType_Type);
  6187. if (resolvedTypeInstance == NULL)
  6188. {
  6189. if ((isValid) && (mCompiler->mSystem->ContainsNamespace(leftComposite, mCurTypeInstance->mTypeDef->mProject)))
  6190. isNamespace = true;
  6191. }
  6192. else if ((isValid) && (resolvedTypeInstance->mTypeDef->mOuterType == NULL) && (resolvedTypeInstance->mTypeDef->mNamespace.EndsWith(leftComposite)))
  6193. {
  6194. if (autoComplete != NULL)
  6195. {
  6196. if (autoComplete->CheckFixit(typeRef))
  6197. autoComplete->FixitCheckNamespace(GetActiveTypeDef(), qualifiedNameNode->mLeft, qualifiedNameNode->mDot);
  6198. autoComplete->CheckNamespace(qualifiedNameNode->mLeft, resolvedTypeInstance->mTypeDef->mNamespace);
  6199. }
  6200. mCompiler->mResolvePassData->HandleNamespaceReference(qualifiedNameNode->mLeft, resolvedTypeInstance->mTypeDef->mNamespace);
  6201. isNamespace = true;
  6202. }
  6203. checkNameNode = qualifiedNameNode->mLeft;
  6204. }
  6205. if ((mCompiler->mResolvePassData->mSourceClassifier != NULL) &&
  6206. ((!setType) || (checkNameNode != namedTypeRef->mNameNode)))
  6207. mCompiler->mResolvePassData->mSourceClassifier->SetHighestElementType(checkNameNode, isNamespace ? BfSourceElementType_Namespace : BfSourceElementType_Type);
  6208. }
  6209. }
  6210. if (((mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Type) || (isGetDefinition)) &&
  6211. ((resolveFlags & BfResolveTypeRefFlag_FromIndirectSource) == 0) && (resolvedTypeRef != NULL) && (typeRefSource != NULL))
  6212. {
  6213. BfAstNode* elementTypeRef = typeRef;
  6214. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(elementTypeRef))
  6215. elementTypeRef = namedTypeRef->mNameNode;
  6216. if (elementTypeRef != NULL)
  6217. {
  6218. BfType* elementType = resolvedTypeRef;
  6219. if (BfTypeInstance* elementTypeInst = elementType->ToTypeInstance())
  6220. {
  6221. mCompiler->mResolvePassData->HandleTypeReference(elementTypeRef, elementTypeInst->mTypeDef);
  6222. if (mCompiler->IsAutocomplete())
  6223. {
  6224. BfAutoComplete* autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  6225. if ((isGetDefinition) && (autoComplete->IsAutocompleteNode(elementTypeRef)))
  6226. {
  6227. BfAstNode* baseNode = elementTypeRef;
  6228. while (true)
  6229. {
  6230. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(baseNode))
  6231. {
  6232. baseNode = qualifiedTypeRef->mRight;
  6233. }
  6234. else if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(baseNode))
  6235. {
  6236. baseNode = elementedTypeRef->mElementType;
  6237. }
  6238. else if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(baseNode))
  6239. {
  6240. baseNode = namedTypeRef->mNameNode;
  6241. }
  6242. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(baseNode))
  6243. {
  6244. baseNode = qualifiedNameNode->mRight;
  6245. }
  6246. else if (auto declTypeRef = BfNodeDynCast<BfDeclTypeRef>(baseNode))
  6247. {
  6248. baseNode = NULL;
  6249. break;
  6250. }
  6251. else
  6252. break;
  6253. }
  6254. if ((baseNode != NULL) && (autoComplete->IsAutocompleteNode(baseNode)))
  6255. {
  6256. // We didn't have this mDefType check before - why? We always want to catch the FIRST definition,
  6257. // so 'Type?' will catch on 'Type' and not 'Type?'
  6258. if ((autoComplete->mDefType == NULL) &&
  6259. (autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  6260. (autoComplete->mDefProp == NULL) && (elementTypeInst->mTypeDef->mTypeDeclaration != NULL))
  6261. {
  6262. autoComplete->mDefType = elementTypeInst->mTypeDef;
  6263. autoComplete->SetDefinitionLocation(elementTypeInst->mTypeDef->mTypeDeclaration->mNameNode);
  6264. }
  6265. if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (resolvedTypeRef != NULL))
  6266. {
  6267. autoComplete->SetResultStringType(resolvedTypeRef);
  6268. }
  6269. }
  6270. }
  6271. }
  6272. }
  6273. }
  6274. }
  6275. }
  6276. if (resolvedTypeRef == NULL)
  6277. return NULL;
  6278. if (mCurTypeInstance == NULL)
  6279. {
  6280. // No deps
  6281. }
  6282. else if (resolvedTypeRef->IsTuple())
  6283. {
  6284. // Add the fields from the tuple as references since those inner fields types would have been explicitly stated, so we need
  6285. // to make sure to record the current type instance as a referring type. This mostly matters for symbol renaming.
  6286. BfTypeInstance* payloadTupleType = (BfTypeInstance*)resolvedTypeRef;
  6287. for (auto& payloadFieldInst : payloadTupleType->mFieldInstances)
  6288. {
  6289. auto payloadFieldType = payloadFieldInst.mResolvedType;
  6290. AddDependency(payloadFieldType, mCurTypeInstance, BfDependencyMap::DependencyFlag_TypeReference);
  6291. }
  6292. }
  6293. else if (resolvedTypeRef->IsDelegateFromTypeRef() || resolvedTypeRef->IsFunctionFromTypeRef())
  6294. {
  6295. auto delegateInfo = resolvedTypeRef->GetDelegateInfo();
  6296. // if (delegateInfo->mFunctionThisType != NULL)
  6297. // AddDependency(delegateInfo->mFunctionThisType, mCurTypeInstance, BfDependencyMap::DependencyFlag_TypeReference);
  6298. AddDependency(delegateInfo->mReturnType, mCurTypeInstance, BfDependencyMap::DependencyFlag_TypeReference);
  6299. for (auto& param : delegateInfo->mParams)
  6300. AddDependency(param, mCurTypeInstance, BfDependencyMap::DependencyFlag_TypeReference);
  6301. }
  6302. BfTypeInstance* typeInstance = resolvedTypeRef->ToTypeInstance();
  6303. BfTypeInstance* genericTypeInstance = resolvedTypeRef->ToGenericTypeInstance();
  6304. auto populateModule = this;
  6305. if ((resolveFlags & BfResolveTypeRefFlag_NoReify) != 0)
  6306. populateModule = mContext->mUnreifiedModule;
  6307. populateModule->PopulateType(resolvedTypeRef, populateType);
  6308. if ((genericTypeInstance != NULL) && (genericTypeInstance != mCurTypeInstance) && (populateType > BfPopulateType_Identity))
  6309. {
  6310. bool doValidate = (genericTypeInstance->mGenericTypeInfo->mHadValidateErrors) ||
  6311. (!genericTypeInstance->mGenericTypeInfo->mValidatedGenericConstraints) ||
  6312. (genericTypeInstance->mGenericTypeInfo->mIsUnspecializedVariation);
  6313. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  6314. doValidate = false;
  6315. if (mCurTypeInstance != NULL)
  6316. {
  6317. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  6318. doValidate = false;
  6319. if (auto curGenericTypeInstance = mCurTypeInstance->ToGenericTypeInstance())
  6320. {
  6321. if ((curGenericTypeInstance->mDependencyMap.mMinDependDepth > 32) &&
  6322. (genericTypeInstance->mDependencyMap.mMinDependDepth > 32))
  6323. {
  6324. Fail(StrFormat("Generic type dependency depth exceeded for type '{}'", TypeToString(genericTypeInstance).c_str()), typeRef);
  6325. return NULL;
  6326. }
  6327. if (curGenericTypeInstance->mGenericTypeInfo->mHadValidateErrors)
  6328. doValidate = false;
  6329. }
  6330. if ((mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mCurBaseTypeRef != NULL)) // We validate constraints for base types later
  6331. doValidate = false;
  6332. }
  6333. if (doValidate)
  6334. ValidateGenericConstraints(typeRef, genericTypeInstance, false);
  6335. }
  6336. if (populateType != BfPopulateType_IdentityNoRemapAlias)
  6337. {
  6338. while ((resolvedTypeRef != NULL) && (resolvedTypeRef->IsTypeAlias()))
  6339. {
  6340. if (mCurTypeInstance != NULL)
  6341. AddDependency(resolvedTypeRef, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  6342. if ((typeInstance->mCustomAttributes != NULL) && (!typeRef->IsTemporary()))
  6343. CheckErrorAttributes(typeInstance, NULL, typeInstance->mCustomAttributes, typeRef);
  6344. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  6345. if (resolvedTypeRef != NULL)
  6346. typeInstance = resolvedTypeRef->ToTypeInstance();
  6347. else
  6348. typeInstance = NULL;
  6349. }
  6350. }
  6351. if (typeInstance != NULL)
  6352. {
  6353. if ((typeInstance->mCustomAttributes != NULL) && (!typeRef->IsTemporary()))
  6354. CheckErrorAttributes(typeInstance, NULL, typeInstance->mCustomAttributes, typeRef);
  6355. if (typeInstance->IsTuple())
  6356. {
  6357. //TODO: This can cause circular reference issues. Is there a case this is needed?
  6358. //if (typeInstance->mDefineState < BfTypeDefineState_Defined)
  6359. // PopulateType(typeInstance);
  6360. if (typeInstance->mHasDeclError)
  6361. {
  6362. if (auto tupleTypeRef = BfNodeDynCast<BfTupleTypeRef>(typeRef))
  6363. {
  6364. HashSet<String> names;
  6365. for (auto nameIdentifier : tupleTypeRef->mFieldNames)
  6366. {
  6367. if (nameIdentifier == NULL)
  6368. continue;
  6369. StringT<64> fieldName;
  6370. nameIdentifier->ToString(fieldName);
  6371. if (!names.Add(fieldName))
  6372. {
  6373. Fail(StrFormat("A field named '%s' has already been declared", fieldName.c_str()), nameIdentifier);
  6374. }
  6375. }
  6376. }
  6377. }
  6378. }
  6379. }
  6380. return resolvedTypeRef;
  6381. }
  6382. void BfModule::ShowAmbiguousTypeError(BfAstNode* refNode, BfTypeDef* typeDef, BfTypeDef* otherTypeDef)
  6383. {
  6384. BfType* type = ResolveTypeDef(typeDef, BfPopulateType_Identity);
  6385. if (type == NULL)
  6386. return;
  6387. BfType* otherType = ResolveTypeDef(otherTypeDef, BfPopulateType_Identity);
  6388. if (otherType == NULL)
  6389. return;
  6390. auto error = Fail(StrFormat("'%s' is an ambiguous reference between '%s' and '%s'",
  6391. refNode->ToString().c_str(), TypeToString(type, BfTypeNameFlags_None).c_str(), TypeToString(otherType, BfTypeNameFlags_None).c_str()), refNode); // CS0104
  6392. if (error != NULL)
  6393. {
  6394. mCompiler->mPassInstance->MoreInfo("See first definition", typeDef->mTypeDeclaration->mNameNode);
  6395. mCompiler->mPassInstance->MoreInfo("See second definition", otherTypeDef->mTypeDeclaration->mNameNode);
  6396. }
  6397. }
  6398. void BfModule::ShowGenericArgCountError(BfTypeReference* typeRef, int wantedGenericParams)
  6399. {
  6400. BfGenericInstanceTypeRef* genericTypeInstRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef);
  6401. BfAstNode* lastNode = typeRef;
  6402. int genericArgDiffCount;
  6403. if (genericTypeInstRef != NULL)
  6404. {
  6405. genericArgDiffCount = (int)genericTypeInstRef->mGenericArguments.size() - wantedGenericParams;
  6406. lastNode = genericTypeInstRef->mOpenChevron;
  6407. if (genericTypeInstRef->mCloseChevron != NULL)
  6408. lastNode = genericTypeInstRef->mCloseChevron;
  6409. if (genericTypeInstRef->mGenericArguments.size() > wantedGenericParams)
  6410. {
  6411. lastNode = genericTypeInstRef->mGenericArguments[wantedGenericParams];
  6412. if (genericArgDiffCount == 1)
  6413. Fail("Too many generic parameters, expected one fewer", lastNode);
  6414. else
  6415. Fail(StrFormat("Too many generic parameters, expected %d fewer", genericArgDiffCount), lastNode);
  6416. return;
  6417. }
  6418. }
  6419. else
  6420. genericArgDiffCount = -wantedGenericParams;
  6421. if (wantedGenericParams == 1)
  6422. Fail("Too few generic parameters, expected one more", lastNode);
  6423. else
  6424. Fail(StrFormat("Too few generic parameters, expected %d more", -genericArgDiffCount), lastNode);
  6425. }
  6426. BfTypeDef* BfModule::GetActiveTypeDef(BfTypeInstance* typeInstanceOverride, bool useMixinDecl)
  6427. {
  6428. BfTypeDef* useTypeDef = NULL;
  6429. BfTypeInstance* typeInstance = (typeInstanceOverride != NULL) ? typeInstanceOverride : mCurTypeInstance;
  6430. if (typeInstance != NULL)
  6431. useTypeDef = typeInstance->mTypeDef;
  6432. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (useMixinDecl))
  6433. useTypeDef = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType;
  6434. else if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType != NULL))
  6435. useTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  6436. else if (mContext->mCurTypeState != NULL)
  6437. {
  6438. if ((mContext->mCurTypeState->mCurFieldDef != NULL) && (mContext->mCurTypeState->mCurFieldDef->mDeclaringType != NULL))
  6439. useTypeDef = mContext->mCurTypeState->mCurFieldDef->mDeclaringType;
  6440. else if (mContext->mCurTypeState->mCurTypeDef != NULL)
  6441. useTypeDef = mContext->mCurTypeState->mCurTypeDef;
  6442. }
  6443. return useTypeDef;
  6444. }
  6445. BfTypeDef* BfModule::FindTypeDefRaw(const BfAtomComposite& findName, int numGenericArgs, BfTypeInstance* typeInstance, BfTypeDef* useTypeDef, BfTypeLookupError* error)
  6446. {
  6447. if ((findName.mSize == 1) && (findName.mParts[0]->mIsSystemType))
  6448. {
  6449. //BP_ZONE("BfModule::FindTypeDefRaw_1");
  6450. return mSystem->FindTypeDef(findName, 0, useTypeDef->mProject);
  6451. }
  6452. BfTypeInstance* skipCheckBaseType = NULL;
  6453. if (mContext->mCurTypeState != NULL)
  6454. {
  6455. if (mContext->mCurTypeState->mCurBaseTypeRef != NULL)
  6456. skipCheckBaseType = mContext->mCurTypeState->mTypeInstance;
  6457. if (mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_BuildingGenericParams)
  6458. skipCheckBaseType = mContext->mCurTypeState->mTypeInstance;
  6459. }
  6460. BfTypeDefLookupContext lookupCtx;
  6461. bool allowPrivate = true;
  6462. int curPri = 1000;
  6463. auto checkTypeInst = typeInstance;
  6464. BfTypeDef* protErrorTypeDef = NULL;
  6465. BfTypeInstance* protErrorOuterType = NULL;
  6466. if (!lookupCtx.HasValidMatch())
  6467. {
  6468. std::function<bool(BfTypeInstance*)> _CheckType = [&](BfTypeInstance* typeInstance)
  6469. {
  6470. auto checkTypeInst = typeInstance;
  6471. allowPrivate = true;
  6472. while (checkTypeInst != NULL)
  6473. {
  6474. if (!checkTypeInst->mTypeDef->mNestedTypes.IsEmpty())
  6475. {
  6476. if (mSystem->FindTypeDef(findName, numGenericArgs, useTypeDef->mProject, checkTypeInst->mTypeDef->mFullNameEx, allowPrivate, &lookupCtx))
  6477. {
  6478. if (lookupCtx.HasValidMatch())
  6479. return true;
  6480. if ((lookupCtx.mBestTypeDef->mProtection == BfProtection_Private) && (!allowPrivate))
  6481. {
  6482. protErrorTypeDef = lookupCtx.mBestTypeDef;
  6483. protErrorOuterType = checkTypeInst;
  6484. }
  6485. }
  6486. }
  6487. if (checkTypeInst == skipCheckBaseType)
  6488. break;
  6489. checkTypeInst = GetBaseType(checkTypeInst);
  6490. allowPrivate = false;
  6491. }
  6492. checkTypeInst = typeInstance;
  6493. allowPrivate = true;
  6494. while (checkTypeInst != NULL)
  6495. {
  6496. auto outerTypeInst = GetOuterType(checkTypeInst);
  6497. if (outerTypeInst != NULL)
  6498. {
  6499. if (_CheckType(outerTypeInst))
  6500. return true;
  6501. }
  6502. if (checkTypeInst == skipCheckBaseType)
  6503. break;
  6504. checkTypeInst = GetBaseType(checkTypeInst);
  6505. allowPrivate = false;
  6506. }
  6507. return false;
  6508. };
  6509. _CheckType(typeInstance);
  6510. }
  6511. if (!lookupCtx.HasValidMatch())
  6512. {
  6513. if (mSystem->mTypeDefs.TryGet(findName, NULL))
  6514. mSystem->FindTypeDef(findName, numGenericArgs, useTypeDef->mProject, BfAtomComposite(), allowPrivate, &lookupCtx);
  6515. for (auto& checkNamespace : useTypeDef->mNamespaceSearch)
  6516. {
  6517. BfAtom* atom = findName.mParts[0];
  6518. BfAtom* prevAtom = checkNamespace.mParts[checkNamespace.mSize - 1];
  6519. if (atom->mPrevNamesMap.ContainsKey(prevAtom))
  6520. mSystem->FindTypeDef(findName, numGenericArgs, useTypeDef->mProject, checkNamespace, allowPrivate, &lookupCtx);
  6521. }
  6522. }
  6523. if (!lookupCtx.HasValidMatch())
  6524. {
  6525. auto staticSearch = GetStaticSearch();
  6526. if (staticSearch != NULL)
  6527. {
  6528. for (auto staticTypeInstance : staticSearch->mStaticTypes)
  6529. {
  6530. if (mSystem->FindTypeDef(findName, numGenericArgs, useTypeDef->mProject, staticTypeInstance->mTypeDef->mFullNameEx, false, &lookupCtx))
  6531. {
  6532. if (lookupCtx.HasValidMatch())
  6533. break;
  6534. if (lookupCtx.mBestTypeDef->mProtection < BfProtection_Public)
  6535. {
  6536. protErrorTypeDef = lookupCtx.mBestTypeDef;
  6537. protErrorOuterType = staticTypeInstance;
  6538. }
  6539. }
  6540. }
  6541. }
  6542. }
  6543. if ((error != NULL) && (lookupCtx.mAmbiguousTypeDef != NULL))
  6544. {
  6545. if (error->mErrorKind == BfTypeLookupError::BfErrorKind_None)
  6546. error->mErrorKind = BfTypeLookupError::BfErrorKind_Ambiguous;
  6547. error->mAmbiguousTypeDef = lookupCtx.mAmbiguousTypeDef;
  6548. if (error->mRefNode != NULL)
  6549. ShowAmbiguousTypeError(error->mRefNode, lookupCtx.mBestTypeDef, lookupCtx.mAmbiguousTypeDef);
  6550. }
  6551. if ((protErrorTypeDef != NULL) && (lookupCtx.mBestTypeDef == protErrorTypeDef) && (error != NULL) && (error->mRefNode != NULL))
  6552. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(protErrorOuterType).c_str(), findName.ToString().c_str()), error->mRefNode); // CS0122
  6553. return lookupCtx.mBestTypeDef;
  6554. }
  6555. BfTypeDef* BfModule::FindTypeDef(const BfAtomComposite& findName, int numGenericArgs, BfTypeInstance* typeInstanceOverride, BfTypeLookupError* error)
  6556. {
  6557. BP_ZONE("BfModule::FindTypeDef_1");
  6558. BfTypeInstance* typeInstance = (typeInstanceOverride != NULL) ? typeInstanceOverride : mCurTypeInstance;
  6559. if (typeInstance == NULL)
  6560. {
  6561. BfProject* project = NULL;
  6562. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mParser != NULL))
  6563. project = mCompiler->mResolvePassData->mParser->mProject;
  6564. BP_ZONE("System.FindTypeDef_2");
  6565. BfTypeDef* ambiguousTypeDef = NULL;
  6566. BfTypeDef *result = mSystem->FindTypeDef(findName, numGenericArgs, project, Array<BfAtomComposite>(), &ambiguousTypeDef);
  6567. if ((ambiguousTypeDef != NULL) && (error != NULL))
  6568. {
  6569. error->mErrorKind = BfTypeLookupError::BfErrorKind_Ambiguous;
  6570. error->mAmbiguousTypeDef = ambiguousTypeDef;
  6571. if (error->mRefNode != NULL)
  6572. ShowAmbiguousTypeError(error->mRefNode, result, ambiguousTypeDef);
  6573. }
  6574. return result;
  6575. }
  6576. auto useTypeDef = GetActiveTypeDef(typeInstanceOverride, true);
  6577. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  6578. {
  6579. if (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(useTypeDef))
  6580. return FindTypeDefRaw(findName, numGenericArgs, typeInstance, useTypeDef, error);
  6581. }
  6582. BfTypeLookupEntry typeLookupEntry;
  6583. typeLookupEntry.mName = findName;
  6584. typeLookupEntry.mNumGenericParams = numGenericArgs;
  6585. typeLookupEntry.mUseTypeDef = useTypeDef;
  6586. BfTypeLookupEntry* typeLookupEntryPtr = NULL;
  6587. BfTypeLookupResult* resultPtr = NULL;
  6588. if (typeInstance->mLookupResults.TryAdd(typeLookupEntry, &typeLookupEntryPtr, &resultPtr))
  6589. {
  6590. typeLookupEntryPtr->mAtomUpdateIdx = typeLookupEntry.mName.GetAtomUpdateIdx();
  6591. // FindTypeDefRaw may re-enter when finding base types, so we need to expect that resultPtr can change
  6592. resultPtr->mForceLookup = true;
  6593. resultPtr->mTypeDef = NULL;
  6594. int prevAllocSize = (int)typeInstance->mLookupResults.size();
  6595. BfTypeLookupError localError;
  6596. BfTypeLookupError* errorPtr = (error != NULL) ? error : &localError;
  6597. auto typeDef = FindTypeDefRaw(findName, numGenericArgs, typeInstance, useTypeDef, errorPtr);
  6598. if (prevAllocSize != typeInstance->mLookupResults.size())
  6599. {
  6600. bool found = typeInstance->mLookupResults.TryGetValue(typeLookupEntry, &resultPtr);
  6601. BF_ASSERT(found);
  6602. }
  6603. resultPtr->mTypeDef = typeDef;
  6604. resultPtr->mForceLookup = errorPtr->mErrorKind != BfTypeLookupError::BfErrorKind_None;
  6605. return typeDef;
  6606. }
  6607. else
  6608. {
  6609. if (resultPtr->mForceLookup)
  6610. return FindTypeDefRaw(findName, numGenericArgs, typeInstance, useTypeDef, error);
  6611. else
  6612. return resultPtr->mTypeDef;
  6613. }
  6614. }
  6615. BfTypeDef* BfModule::FindTypeDef(const StringImpl& typeName, int numGenericArgs, BfTypeInstance* typeInstanceOverride, BfTypeLookupError* error)
  6616. {
  6617. BP_ZONE("BfModule::FindTypeDef_4");
  6618. BfSizedAtomComposite findName;
  6619. if (!mSystem->ParseAtomComposite(typeName, findName))
  6620. return NULL;
  6621. auto result = FindTypeDef(findName, numGenericArgs, typeInstanceOverride, error);
  6622. // Don't allow just finding extensions here. This can happen in some 'using static' cases but generally shouldn't happen
  6623. if ((result != NULL) && (result->mTypeCode == BfTypeCode_Extension))
  6624. return NULL;
  6625. return result;
  6626. }
  6627. BfTypeDef* BfModule::FindTypeDef(BfTypeReference* typeRef, BfTypeInstance* typeInstanceOverride, BfTypeLookupError* error, int numGenericParams, BfResolveTypeRefFlags resolveFlags)
  6628. {
  6629. BP_ZONE("BfModule::FindTypeDef_5");
  6630. if (auto typeDefTypeRef = BfNodeDynCast<BfDirectTypeDefReference>(typeRef))
  6631. {
  6632. if (typeDefTypeRef->mTypeDef != NULL)
  6633. return mSystem->FilterDeletedTypeDef(typeDefTypeRef->mTypeDef);
  6634. }
  6635. //TODO: When does this get called?
  6636. if (auto elementedType = BfNodeDynCast<BfElementedTypeRef>(typeRef))
  6637. return FindTypeDef(elementedType->mElementType, typeInstanceOverride, error);
  6638. BF_ASSERT(typeRef->IsA<BfNamedTypeReference>() || typeRef->IsA<BfQualifiedTypeReference>() || typeRef->IsA<BfDirectStrTypeReference>());
  6639. auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef);
  6640. StringView findNameStr;
  6641. if (namedTypeRef != NULL)
  6642. findNameStr = namedTypeRef->mNameNode->ToStringView();
  6643. else
  6644. {
  6645. auto directStrTypeDef = BfNodeDynCastExact<BfDirectStrTypeReference>(typeRef);
  6646. if (directStrTypeDef != NULL)
  6647. findNameStr = directStrTypeDef->mTypeName;
  6648. else
  6649. BFMODULE_FATAL(this, "Error?");
  6650. }
  6651. if (findNameStr.mLength == 6)
  6652. {
  6653. if (findNameStr == "object")
  6654. {
  6655. findNameStr = "System.Object";
  6656. Fail("'object' alias not supported, use 'Object'", typeRef);
  6657. }
  6658. else if (findNameStr == "string")
  6659. {
  6660. findNameStr = "System.String";
  6661. Fail("'string' alias not supported, use 'String'", typeRef);
  6662. }
  6663. }
  6664. BfSizedAtomComposite findName;
  6665. if ((resolveFlags & BfResolveTypeRefFlag_Attribute) != 0)
  6666. {
  6667. String attributeName;
  6668. attributeName += findNameStr;
  6669. attributeName += "Attribute";
  6670. if (!mSystem->ParseAtomComposite(attributeName, findName))
  6671. return NULL;
  6672. }
  6673. else
  6674. {
  6675. if (!mSystem->ParseAtomComposite(findNameStr, findName))
  6676. return NULL;
  6677. }
  6678. #ifdef BF_AST_HAS_PARENT_MEMBER
  6679. if (auto parentGenericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef->mParent))
  6680. {
  6681. if (parentGenericTypeRef->mElementType == typeRef)
  6682. BF_ASSERT(numGenericParams == parentGenericTypeRef->GetGenericArgCount());
  6683. }
  6684. #endif
  6685. auto typeDef = FindTypeDef(findName, numGenericParams, typeInstanceOverride, error);
  6686. //TYPEDEF if (namedTypeRef != NULL)
  6687. // namedTypeRef->mTypeDef = typeDef;
  6688. return typeDef;
  6689. }
  6690. void BfModule::CheckTypeRefFixit(BfAstNode* typeRef, const char* appendName)
  6691. {
  6692. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((typeRef))))
  6693. {
  6694. String typeName = typeRef->ToString();
  6695. if (appendName != NULL)
  6696. typeName += appendName;
  6697. std::set<String> fixitNamespaces;
  6698. //TODO: Do proper value for numGenericArgs
  6699. mSystem->FindFixitNamespaces(typeName, -1, mCompiler->mResolvePassData->mParser->mProject, fixitNamespaces);
  6700. int insertLoc = 0;
  6701. BfUsingFinder usingFinder;
  6702. usingFinder.VisitMembers(typeRef->GetSourceData()->mRootNode);
  6703. for (auto& namespaceStr : fixitNamespaces)
  6704. {
  6705. BfParserData* parser = typeRef->GetSourceData()->ToParserData();
  6706. if (parser != NULL)
  6707. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("using %s;\t.using|%s|%d||using %s;", namespaceStr.c_str(), parser->mFileName.c_str(), usingFinder.mLastIdx, namespaceStr.c_str()).c_str()));
  6708. }
  6709. }
  6710. }
  6711. void BfModule::CheckIdentifierFixit(BfAstNode* node)
  6712. {
  6713. //TODO: Check globals, possibly spelling mistakes?
  6714. }
  6715. void BfModule::TypeRefNotFound(BfTypeReference* typeRef, const char* appendName)
  6716. {
  6717. if (typeRef->IsTemporary())
  6718. return;
  6719. Fail("Type could not be found (are you missing a using directive or library reference?)", typeRef);
  6720. if (!mIgnoreErrors)
  6721. {
  6722. while (auto elementedType = BfNodeDynCast<BfElementedTypeRef>(typeRef))
  6723. typeRef = elementedType->mElementType;
  6724. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef))
  6725. {
  6726. String findNameStr = namedTypeRef->mNameNode->ToString();
  6727. if (appendName != NULL)
  6728. findNameStr += appendName;
  6729. BfSizedAtomComposite findName;
  6730. if ((!mSystem->ParseAtomComposite(findNameStr, findName)) && (mCurTypeInstance != NULL))
  6731. {
  6732. //BfTypeInstance* typeInstance = (typeInstanceOverride != NULL) ? typeInstanceOverride : mCurTypeInstance;
  6733. // We don't need a typeInstanceOverride because that is used to lookup references
  6734. // from mixins, but it's the type using the mixin (mCurTypeInstance) that needs
  6735. // rebuilding if the lookup fails
  6736. BfTypeInstance* typeInstance = mCurTypeInstance;
  6737. BfTypeLookupEntry typeLookupEntry;
  6738. typeLookupEntry.mNumGenericParams = 0;
  6739. typeLookupEntry.mAtomUpdateIdx = mSystem->mAtomUpdateIdx;
  6740. typeInstance->mLookupResults.TryAdd(typeLookupEntry, BfTypeLookupResult());
  6741. }
  6742. }
  6743. }
  6744. CheckTypeRefFixit(typeRef, appendName);
  6745. }
  6746. bool BfModule::ValidateTypeWildcard(BfTypeReference* typeRef, bool isAttributeRef)
  6747. {
  6748. if (typeRef == NULL)
  6749. return false;
  6750. if (auto wildcardTypeRef = BfNodeDynCast<BfWildcardTypeReference>(typeRef))
  6751. return true;
  6752. StringT<128> nameStr;
  6753. typeRef->ToString(nameStr);
  6754. if (isAttributeRef)
  6755. nameStr.Append("Attribute");
  6756. auto typeDef = mSystem->FindTypeDef(nameStr, (BfProject*)NULL);
  6757. if ((typeDef != NULL) && (typeDef->mGenericParamDefs.IsEmpty()))
  6758. return true;
  6759. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  6760. {
  6761. if (qualifiedTypeRef->mLeft == NULL)
  6762. return false;
  6763. StringT<128> leftNameStr;
  6764. BfType* leftType = NULL;
  6765. BfAtomComposite leftComposite;
  6766. qualifiedTypeRef->mLeft->ToString(leftNameStr);
  6767. if (!mSystem->ParseAtomComposite(leftNameStr, leftComposite))
  6768. return false;
  6769. if (auto wildcardTypeRef = BfNodeDynCast<BfWildcardTypeReference>(qualifiedTypeRef->mRight))
  6770. {
  6771. if (mSystem->ContainsNamespace(leftComposite, NULL))
  6772. return true;
  6773. return ValidateTypeWildcard(qualifiedTypeRef->mLeft, false);
  6774. }
  6775. }
  6776. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  6777. {
  6778. StringT<128> nameStr;
  6779. genericTypeRef->mElementType->ToString(nameStr);
  6780. auto typeDef = mSystem->FindTypeDef(nameStr, (int)genericTypeRef->mGenericArguments.size(), NULL);
  6781. if (typeDef == NULL)
  6782. return false;
  6783. if (typeDef->mGenericParamDefs.size() != genericTypeRef->GetGenericArgCount())
  6784. return false;
  6785. for (auto genericArgTypeRef : genericTypeRef->mGenericArguments)
  6786. {
  6787. if ((genericTypeRef != NULL) && (!ValidateTypeWildcard(genericArgTypeRef, false)))
  6788. return false;
  6789. }
  6790. return true;
  6791. }
  6792. if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(typeRef))
  6793. {
  6794. return ValidateTypeWildcard(elementedTypeRef->mElementType, false);
  6795. }
  6796. return false;
  6797. }
  6798. //int sResolveTypeRefIdx = 0;
  6799. BfTypedValue BfModule::TryLookupGenericConstVaue(BfIdentifierNode* identifierNode, BfType* expectingType)
  6800. {
  6801. BfTypeInstance* contextTypeInstance = mCurTypeInstance;
  6802. BfMethodInstance* contextMethodInstance = mCurMethodInstance;
  6803. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  6804. {
  6805. contextTypeInstance = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  6806. contextMethodInstance = mCurMethodState->mMixinState->mMixinMethodInstance;
  6807. }
  6808. BfTypeDef* curTypeDef = NULL;
  6809. if (contextTypeInstance != NULL)
  6810. {
  6811. curTypeDef = contextTypeInstance->mTypeDef;
  6812. StringT<128> findName;
  6813. identifierNode->ToString(findName);
  6814. auto genericCheckTypeInstance = contextTypeInstance;
  6815. if (contextTypeInstance->IsBoxed())
  6816. genericCheckTypeInstance = contextTypeInstance->GetUnderlyingType()->ToTypeInstance();
  6817. bool doFakeVal = false;
  6818. if (genericCheckTypeInstance->IsUnspecializedTypeVariation())
  6819. {
  6820. genericCheckTypeInstance = GetUnspecializedTypeInstance(genericCheckTypeInstance);
  6821. doFakeVal = true;
  6822. }
  6823. BfGenericParamDef* genericParamDef = NULL;
  6824. BfGenericParamDef* origGenericParamDef = NULL;
  6825. BfType* genericParamResult = NULL;
  6826. BfType* genericTypeConstraint = NULL;
  6827. bool disallowConstExprValue = false;
  6828. if ((genericCheckTypeInstance != NULL) && (genericCheckTypeInstance->IsGenericTypeInstance()))
  6829. {
  6830. auto genericTypeInst = (BfTypeInstance*)genericCheckTypeInstance;
  6831. auto* genericParams = &curTypeDef->mGenericParamDefs;
  6832. auto* origGenericParams = &curTypeDef->mGenericParamDefs;
  6833. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  6834. {
  6835. auto activeTypeDef = GetActiveTypeDef(NULL, true);
  6836. genericParams = &activeTypeDef->mGenericParamDefs;
  6837. }
  6838. for (int genericParamIdx = (int)genericParams->size() - 1; genericParamIdx >= 0; genericParamIdx--)
  6839. {
  6840. auto checkGenericParamDef = (*genericParams)[genericParamIdx];
  6841. String genericName = checkGenericParamDef->mName;
  6842. if (genericName == findName)
  6843. {
  6844. genericParamDef = checkGenericParamDef;
  6845. origGenericParamDef = (*origGenericParams)[genericParamIdx];
  6846. genericParamResult = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[genericParamIdx];
  6847. genericTypeConstraint = genericTypeInst->mGenericTypeInfo->mGenericParams[genericParamIdx]->mTypeConstraint;
  6848. HandleTypeGenericParamRef(identifierNode, genericTypeInst->mTypeDef, genericParamIdx);
  6849. }
  6850. }
  6851. }
  6852. if ((contextMethodInstance != NULL) && (genericParamResult == NULL))
  6853. {
  6854. for (int genericParamIdx = (int)contextMethodInstance->mMethodDef->mGenericParams.size() - 1; genericParamIdx >= 0; genericParamIdx--)
  6855. {
  6856. auto checkGenericParamDef = contextMethodInstance->mMethodDef->mGenericParams[genericParamIdx];
  6857. String genericName = checkGenericParamDef->mName;
  6858. if (genericName == findName)
  6859. {
  6860. genericParamDef = checkGenericParamDef;
  6861. origGenericParamDef = checkGenericParamDef;
  6862. genericParamResult = contextMethodInstance->mMethodInfoEx->mMethodGenericArguments[genericParamIdx];
  6863. genericTypeConstraint = contextMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx]->mTypeConstraint;
  6864. HandleMethodGenericParamRef(identifierNode, contextMethodInstance->GetOwner()->mTypeDef, contextMethodInstance->mMethodDef, genericParamIdx);
  6865. }
  6866. }
  6867. }
  6868. if (genericParamResult != NULL)
  6869. {
  6870. auto typeRefSource = identifierNode->GetSourceData();
  6871. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mSourceClassifier != NULL) && (typeRefSource != NULL) && (typeRefSource == mCompiler->mResolvePassData->mParser->mSourceData))
  6872. mCompiler->mResolvePassData->mSourceClassifier->SetElementType(identifierNode, BfSourceElementType_Type);
  6873. if (genericParamResult->IsConstExprValue())
  6874. {
  6875. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericParamResult;
  6876. BfExprEvaluator exprEvaluator(this);
  6877. exprEvaluator.mExpectingType = genericTypeConstraint;
  6878. exprEvaluator.GetLiteral(identifierNode, constExprValueType->mValue);
  6879. if (exprEvaluator.mResult)
  6880. {
  6881. auto castedVal = CastToValue(identifierNode, exprEvaluator.mResult, genericTypeConstraint, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  6882. if (castedVal)
  6883. return BfTypedValue(castedVal, genericTypeConstraint);
  6884. }
  6885. return exprEvaluator.mResult;
  6886. }
  6887. else if (genericParamResult->IsGenericParam())
  6888. {
  6889. if ((doFakeVal) && (genericTypeConstraint != NULL))
  6890. {
  6891. return BfTypedValue(mBfIRBuilder->GetFakeVal(), genericTypeConstraint);
  6892. }
  6893. if (((genericParamDef->mGenericParamFlags | origGenericParamDef->mGenericParamFlags) & BfGenericParamFlag_Const) != 0)
  6894. {
  6895. BfTypedValue result;
  6896. result.mType = genericParamResult;
  6897. result.mKind = BfTypedValueKind_GenericConstValue;
  6898. return result;
  6899. }
  6900. }
  6901. }
  6902. }
  6903. return BfTypedValue();
  6904. }
  6905. BfType* BfModule::ResolveTypeRef(BfTypeReference* typeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags, int numGenericArgs)
  6906. {
  6907. BP_ZONE("BfModule::ResolveTypeRef");
  6908. if (typeRef == NULL)
  6909. {
  6910. AssertErrorState();
  6911. return NULL;
  6912. }
  6913. if (resolveFlags & BfResolveTypeRefFlag_AutoComplete)
  6914. {
  6915. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags & ~BfResolveTypeRefFlag_AutoComplete);
  6916. auto autoComplete = mCompiler->GetAutoComplete();
  6917. if (autoComplete != NULL)
  6918. autoComplete->CheckTypeRef(typeRef, false);
  6919. }
  6920. if ((resolveFlags & BfResolveTypeRefFlag_AllowRef) == 0)
  6921. {
  6922. if (auto refTypeRef = BfNodeDynCast<BfRefTypeRef>(typeRef))
  6923. {
  6924. const char* refTypeStr = BfTokenToString(refTypeRef->mRefToken->mToken);
  6925. Fail(StrFormat("Invalid use of '%s'. Only method parameters, return types, and local variables can be declared as %s types", refTypeStr, refTypeStr), refTypeRef->mRefToken);
  6926. return ResolveTypeRef(refTypeRef->mElementType);
  6927. }
  6928. }
  6929. if (auto directTypeRef = BfNodeDynCastExact<BfDirectTypeReference>(typeRef))
  6930. {
  6931. return directTypeRef->mType;
  6932. }
  6933. if (auto dotType = BfNodeDynCastExact<BfDotTypeReference>(typeRef))
  6934. {
  6935. Fail(StrFormat("Invalid use of '%s'", BfTokenToString(dotType->mDotToken->mToken)), typeRef);
  6936. return NULL;
  6937. }
  6938. if (auto varRefType = BfNodeDynCastExact<BfVarRefTypeReference>(typeRef))
  6939. {
  6940. Fail("Invalid use of 'var ref'. Generally references are generated with a 'var' declaration with 'ref' applied to the initializer", typeRef);
  6941. return NULL;
  6942. }
  6943. if (mNoResolveGenericParams)
  6944. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoResolveGenericParam);
  6945. SetAndRestoreValue<bool> prevNoResolveGenericParams(mNoResolveGenericParams, (resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0);
  6946. //
  6947. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags & ~BfResolveTypeRefFlag_NoResolveGenericParam);
  6948. BfTypeInstance* contextTypeInstance = mCurTypeInstance;
  6949. BfMethodInstance* contextMethodInstance = mCurMethodInstance;
  6950. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsForeignMethodDef))
  6951. contextTypeInstance = mCurMethodInstance->mMethodInfoEx->mForeignType;
  6952. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  6953. {
  6954. contextTypeInstance = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  6955. contextMethodInstance = mCurMethodState->mMixinState->mMixinMethodInstance;
  6956. }
  6957. BfTypeDef* curTypeDef = NULL;
  6958. if (contextTypeInstance != NULL)
  6959. {
  6960. curTypeDef = contextTypeInstance->mTypeDef;
  6961. // Check generics first
  6962. auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(typeRef);
  6963. auto directStrTypeRef = BfNodeDynCastExact<BfDirectStrTypeReference>(typeRef);
  6964. if (((namedTypeRef != NULL) && (namedTypeRef->mNameNode != NULL)) || (directStrTypeRef != NULL))
  6965. {
  6966. StringT<128> findName;
  6967. if (namedTypeRef != NULL)
  6968. namedTypeRef->mNameNode->ToString(findName);
  6969. else
  6970. findName = directStrTypeRef->mTypeName;
  6971. if (findName == "Self")
  6972. {
  6973. BfType* selfType = mCurTypeInstance;
  6974. if (selfType->IsInterface()) // For interfaces, 'Self' refers to the identity of the implementing type, so we use a placeholder
  6975. return GetPrimitiveType(BfTypeCode_Self);
  6976. else
  6977. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_FromIndirectSource);
  6978. if (selfType->IsBoxed())
  6979. selfType = selfType->GetUnderlyingType();
  6980. if ((resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0)
  6981. {
  6982. if ((selfType->IsSpecializedType()) || (selfType->IsUnspecializedTypeVariation()))
  6983. selfType = ResolveTypeDef(selfType->ToTypeInstance()->mTypeDef, populateType);
  6984. }
  6985. if (selfType == NULL)
  6986. {
  6987. Fail("'Self' type is not usable here", typeRef);
  6988. }
  6989. return ResolveTypeResult(typeRef, selfType, populateType, resolveFlags);
  6990. }
  6991. else if (findName == "SelfBase")
  6992. {
  6993. BfType* selfType = mCurTypeInstance;
  6994. if (selfType->IsInterface())
  6995. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_FromIndirectSource);
  6996. if (selfType->IsBoxed())
  6997. selfType = selfType->GetUnderlyingType();
  6998. if ((resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0)
  6999. {
  7000. if ((selfType->IsSpecializedType()) || (selfType->IsUnspecializedTypeVariation()))
  7001. selfType = ResolveTypeDef(selfType->ToTypeInstance()->mTypeDef, populateType);
  7002. }
  7003. BfType* baseType = NULL;
  7004. if (selfType != NULL)
  7005. {
  7006. if (selfType->IsTypedPrimitive())
  7007. baseType = selfType->GetUnderlyingType();
  7008. else
  7009. {
  7010. auto selfTypeInst = selfType->ToTypeInstance();
  7011. if (selfTypeInst != NULL)
  7012. {
  7013. baseType = selfTypeInst->mBaseType;
  7014. }
  7015. }
  7016. }
  7017. if (baseType == NULL)
  7018. {
  7019. Fail("'SelfBase' type is not usable here", typeRef);
  7020. }
  7021. return ResolveTypeResult(typeRef, baseType, populateType, resolveFlags);
  7022. }
  7023. else if (findName == "ExpectedType")
  7024. {
  7025. Fail("'ExpectedType' is not usable here", typeRef);
  7026. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7027. }
  7028. auto genericCheckTypeInstance = contextTypeInstance;
  7029. if (contextTypeInstance->IsBoxed())
  7030. genericCheckTypeInstance = contextTypeInstance->GetUnderlyingType()->ToTypeInstance();
  7031. BfGenericParamDef* genericParamDef = NULL;
  7032. BfType* genericParamResult = NULL;
  7033. bool disallowConstExprValue = false;
  7034. if ((genericCheckTypeInstance != NULL) && (genericCheckTypeInstance->IsGenericTypeInstance()))
  7035. {
  7036. auto genericTypeInst = (BfTypeInstance*)genericCheckTypeInstance;
  7037. auto* genericParams = &curTypeDef->mGenericParamDefs;
  7038. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  7039. {
  7040. auto activeTypeDef = GetActiveTypeDef(NULL, true);
  7041. genericParams = &activeTypeDef->mGenericParamDefs;
  7042. }
  7043. for (int genericParamIdx = (int)genericParams->size() - 1; genericParamIdx >= 0; genericParamIdx--)
  7044. {
  7045. auto checkGenericParamDef = (*genericParams)[genericParamIdx];
  7046. String genericName = checkGenericParamDef->mName;
  7047. if (genericName == findName)
  7048. {
  7049. genericParamDef = checkGenericParamDef;
  7050. if (((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  7051. ((resolveFlags & BfResolveTypeRefFlag_AllowGenericTypeParamConstValue) == 0))
  7052. disallowConstExprValue = true;
  7053. HandleTypeGenericParamRef(typeRef, curTypeDef, genericParamIdx);
  7054. if ((resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0)
  7055. return GetGenericParamType(BfGenericParamKind_Type, genericParamIdx);
  7056. else
  7057. {
  7058. SetAndRestoreValue<BfGetSymbolReferenceKind> prevSymbolRefKind;
  7059. if (mCompiler->mResolvePassData != NULL) // Don't add these typeRefs, they are indirect
  7060. prevSymbolRefKind.Init(mCompiler->mResolvePassData->mGetSymbolReferenceKind, BfGetSymbolReferenceKind_None);
  7061. genericParamResult = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[genericParamIdx];
  7062. if ((genericParamResult != NULL) &&
  7063. (genericParamResult->IsConstExprValue()) &&
  7064. ((resolveFlags & BfResolveTypeRefFlag_AllowGenericTypeParamConstValue) == 0))
  7065. disallowConstExprValue = true;
  7066. }
  7067. }
  7068. }
  7069. }
  7070. if ((contextMethodInstance != NULL) && (genericParamResult == NULL))
  7071. {
  7072. BfMethodInstance* prevMethodInstance = NULL;
  7073. // If we're in a closure then use the outside method generic arguments
  7074. auto checkMethodInstance = contextMethodInstance;
  7075. if ((mCurMethodState != NULL) && (checkMethodInstance->mIsClosure))
  7076. {
  7077. auto checkMethodState = mCurMethodState;
  7078. while (checkMethodState != NULL)
  7079. {
  7080. if ((checkMethodState->mMethodInstance != NULL) && (checkMethodState->mMethodInstance->mIsClosure))
  7081. {
  7082. checkMethodInstance = checkMethodState->mPrevMethodState->mMethodInstance;
  7083. }
  7084. checkMethodState = checkMethodState->mPrevMethodState;
  7085. }
  7086. }
  7087. for (int genericParamIdx = (int)checkMethodInstance->mMethodDef->mGenericParams.size() - 1; genericParamIdx >= 0; genericParamIdx--)
  7088. {
  7089. auto checkGenericParamDef = checkMethodInstance->mMethodDef->mGenericParams[genericParamIdx];
  7090. String genericName = checkGenericParamDef->mName;
  7091. if (genericName == findName)
  7092. {
  7093. genericParamDef = checkGenericParamDef;
  7094. if (((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  7095. ((resolveFlags & BfResolveTypeRefFlag_AllowGenericMethodParamConstValue) == 0))
  7096. disallowConstExprValue = true;
  7097. HandleMethodGenericParamRef(typeRef, checkMethodInstance->GetOwner()->mTypeDef, checkMethodInstance->mMethodDef, genericParamIdx);
  7098. if ((resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0)
  7099. return GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  7100. else
  7101. {
  7102. SetAndRestoreValue<BfGetSymbolReferenceKind> prevSymbolRefKind;
  7103. if (mCompiler->mResolvePassData != NULL) // Don't add these typeRefs, they are indirect
  7104. prevSymbolRefKind.Init(mCompiler->mResolvePassData->mGetSymbolReferenceKind, BfGetSymbolReferenceKind_None);
  7105. genericParamResult = checkMethodInstance->mMethodInfoEx->mMethodGenericArguments[genericParamIdx];
  7106. if ((genericParamResult != NULL) &&
  7107. (genericParamResult->IsConstExprValue()) &&
  7108. ((resolveFlags & BfResolveTypeRefFlag_AllowGenericMethodParamConstValue) == 0))
  7109. disallowConstExprValue = true;
  7110. }
  7111. }
  7112. }
  7113. }
  7114. if (genericParamResult != NULL)
  7115. {
  7116. if (disallowConstExprValue)
  7117. {
  7118. Fail("Invalid use of constant generic value", typeRef);
  7119. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7120. }
  7121. if (genericParamResult->IsRef())
  7122. {
  7123. if ((resolveFlags & BfResolveTypeRefFlag_AllowRefGeneric) == 0)
  7124. genericParamResult = genericParamResult->GetUnderlyingType();
  7125. }
  7126. return ResolveTypeResult(typeRef, genericParamResult, populateType, (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_FromIndirectSource));
  7127. }
  7128. }
  7129. }
  7130. BfTypeDef* typeDef = NULL;
  7131. if (typeRef->IsNamedTypeReference())
  7132. {
  7133. BfTypeLookupError error;
  7134. error.mRefNode = typeRef;
  7135. typeDef = FindTypeDef(typeRef, contextTypeInstance, &error, 0, resolveFlags);
  7136. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef))
  7137. {
  7138. if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(namedTypeRef->mNameNode))
  7139. {
  7140. // This handles the case where we have an "BaseClass.InnerClass", but the name is qualified as "DerivedClass.InnerClass"
  7141. auto leftType = ResolveTypeRef(qualifiedNameNode->mLeft, NULL, BfPopulateType_Identity, (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef));
  7142. if ((leftType != NULL) && (qualifiedNameNode->mRight != NULL))
  7143. {
  7144. // Try searching within inner type
  7145. auto resolvedType = ResolveInnerType(leftType, qualifiedNameNode->mRight, populateType, true);
  7146. if (resolvedType != NULL)
  7147. {
  7148. if (mCurTypeInstance != NULL)
  7149. AddDependency(leftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  7150. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  7151. }
  7152. }
  7153. }
  7154. }
  7155. if ((typeDef == NULL) && (mCurTypeInstance != NULL))
  7156. {
  7157. // Try searching within inner type
  7158. auto checkOuterType = mCurTypeInstance;
  7159. while (checkOuterType != NULL)
  7160. {
  7161. // We check for mBaseType to not be NULL because we can't inherit from an inner type, so don't even search there
  7162. // Causes reference cycles (bad).
  7163. if ((checkOuterType != mCurTypeInstance) || (checkOuterType->mBaseType != NULL))
  7164. {
  7165. auto resolvedType = ResolveInnerType(checkOuterType, typeRef, populateType, true);
  7166. if (resolvedType != NULL)
  7167. {
  7168. if (mCurTypeInstance != NULL)
  7169. AddDependency(checkOuterType, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  7170. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  7171. }
  7172. }
  7173. checkOuterType = GetOuterType(checkOuterType);
  7174. }
  7175. }
  7176. if (typeDef == NULL)
  7177. {
  7178. auto staticSearch = GetStaticSearch();
  7179. if (staticSearch != NULL)
  7180. {
  7181. for (auto staticTypeInst : staticSearch->mStaticTypes)
  7182. {
  7183. auto resolvedType = ResolveInnerType(staticTypeInst, typeRef, populateType, true);
  7184. if (resolvedType != NULL)
  7185. {
  7186. if (mCurTypeInstance != NULL)
  7187. AddDependency(staticTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  7188. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  7189. }
  7190. }
  7191. }
  7192. }
  7193. if (typeDef == NULL)
  7194. {
  7195. #ifdef BF_AST_HAS_PARENT_MEMBER
  7196. if (auto parentQualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef->mParent))
  7197. {
  7198. BF_ASSERT(typeRef->mParent == mParentNodeEntry->mNode);
  7199. }
  7200. #endif
  7201. if (mParentNodeEntry != NULL)
  7202. {
  7203. if (auto parentQualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(mParentNodeEntry->mNode))
  7204. {
  7205. if (typeRef == parentQualifiedTypeRef->mLeft)
  7206. {
  7207. if ((resolveFlags & BfResolveTypeRefFlag_IgnoreLookupError) == 0)
  7208. TypeRefNotFound(typeRef);
  7209. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7210. }
  7211. }
  7212. }
  7213. if ((resolveFlags & BfResolveTypeRefFlag_IgnoreLookupError) == 0)
  7214. {
  7215. TypeRefNotFound(typeRef, ((resolveFlags & Beefy::BfResolveTypeRefFlag_Attribute) != 0) ? "Attribute" : NULL);
  7216. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7217. }
  7218. return NULL;
  7219. }
  7220. }
  7221. else if (auto typeDefTypeRef = BfNodeDynCastExact<BfDirectTypeDefReference>(typeRef))
  7222. {
  7223. typeDef = typeDefTypeRef->mTypeDef;
  7224. }
  7225. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  7226. {
  7227. //TODO: Determine why we had this prevIgnoreErrors set here. It causes things like IEnumerator<Hey.Test<INVALIDNAME>> not fail
  7228. // properly on INVALIDNAME
  7229. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, /*true*/mIgnoreErrors);
  7230. StringView leftNameStr;
  7231. BfType* leftType = NULL;
  7232. BfSizedAtomComposite leftComposite;
  7233. bool leftIsValid = false;
  7234. //bool leftIsValid = (qualifiedTypeRef->mLeft != NULL) && mSystem->ParseAtomComposite(qualifiedTypeRef->mLeft->ToString(), leftComposite);
  7235. if (qualifiedTypeRef->mLeft != NULL)
  7236. {
  7237. leftNameStr = qualifiedTypeRef->mLeft->ToStringView();
  7238. if (mSystem->ParseAtomComposite(leftNameStr, leftComposite))
  7239. leftIsValid = true;
  7240. }
  7241. if ((leftIsValid) && (qualifiedTypeRef->mRight != NULL))
  7242. {
  7243. StringT<128> findName;
  7244. auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(qualifiedTypeRef->mRight);
  7245. auto activeTypeDef = GetActiveTypeDef();
  7246. BfProject* bfProject = NULL;
  7247. if (activeTypeDef != NULL)
  7248. bfProject = activeTypeDef->mProject;
  7249. if (mSystem->ContainsNamespace(leftComposite, bfProject))
  7250. {
  7251. qualifiedTypeRef->mLeft->ToString(findName);
  7252. findName.Append('.');
  7253. if (genericTypeRef != NULL)
  7254. genericTypeRef->mElementType->ToString(findName);
  7255. else
  7256. qualifiedTypeRef->mRight->ToString(findName);
  7257. }
  7258. else if ((activeTypeDef != NULL) && (activeTypeDef->mNamespace.EndsWith(leftComposite)))
  7259. {
  7260. // Partial namespace reference, extend to a full reference
  7261. findName += activeTypeDef->mNamespace.ToString();
  7262. findName.Append('.');
  7263. qualifiedTypeRef->mRight->ToString(findName);
  7264. }
  7265. if (!findName.IsEmpty())
  7266. {
  7267. int wantNumGenericArgs = 0;
  7268. #ifdef BF_AST_HAS_PARENT_MEMBER
  7269. if (auto genericTypeParent = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef->mParent))
  7270. {
  7271. BF_ASSERT(mParentNodeEntry->mNode == genericTypeParent);
  7272. //wantNumGenericArgs = (int)genericTypeParent->mGenericArguments.size();
  7273. //genericTypeRef = genericTypeParent;
  7274. }
  7275. #endif
  7276. if (mParentNodeEntry != NULL)
  7277. {
  7278. if (auto genericTypeParent = BfNodeDynCast<BfGenericInstanceTypeRef>(mParentNodeEntry->mNode))
  7279. {
  7280. wantNumGenericArgs = (int)genericTypeParent->mGenericArguments.size();
  7281. genericTypeRef = genericTypeParent;
  7282. }
  7283. }
  7284. BfTypeDef* ambiguousTypeDef = NULL;
  7285. //auto typeDef = mSystem->FindTypeDef(findName, wantNumGenericArgs, bfProject, {}, &ambiguousTypeDef);
  7286. //auto typeDef = mSystem->FindTypeDef(findName, wantNumGenericArgs, bfProject, {}, &ambiguousTypeDef);
  7287. BfTypeLookupError lookupError;
  7288. auto typeDef = FindTypeDef(findName, wantNumGenericArgs, NULL, &lookupError);
  7289. if (typeDef != NULL)
  7290. {
  7291. if (ambiguousTypeDef != NULL)
  7292. ShowAmbiguousTypeError(typeRef, typeDef, ambiguousTypeDef);
  7293. BfTypeVector genericArgs;
  7294. if (populateType != BfPopulateType_TypeDef)
  7295. {
  7296. if (genericTypeRef != NULL)
  7297. {
  7298. for (auto genericParamTypeRef : genericTypeRef->mGenericArguments)
  7299. {
  7300. auto genericParam = ResolveTypeRef(genericParamTypeRef, BfPopulateType_Declaration);
  7301. if (genericParam == NULL)
  7302. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7303. genericArgs.push_back(genericParam);
  7304. }
  7305. }
  7306. if (typeDef->mGenericParamDefs.size() != genericArgs.size())
  7307. {
  7308. prevIgnoreErrors.Restore();
  7309. BfAstNode* refNode = typeRef;
  7310. if (genericTypeRef != NULL)
  7311. refNode = genericTypeRef->mOpenChevron;
  7312. int wantedGenericParams = (int)typeDef->mGenericParamDefs.size();
  7313. if (wantedGenericParams == 1)
  7314. Fail("Expected one generic argument", refNode);
  7315. else
  7316. Fail(StrFormat("Expected %d generic arguments", wantedGenericParams), refNode);
  7317. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7318. }
  7319. }
  7320. return ResolveTypeResult(typeRef, ResolveTypeDef(typeDef, genericArgs, populateType), populateType, resolveFlags);
  7321. }
  7322. }
  7323. }
  7324. if (leftType == NULL)
  7325. {
  7326. BfAutoParentNodeEntry autoParentNodeEntry(this, qualifiedTypeRef);
  7327. leftType = ResolveTypeRef(qualifiedTypeRef->mLeft, BfPopulateType_Identity, (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_IgnoreLookupError)); // We throw an error below if we can't find the type
  7328. }
  7329. if (leftType == NULL)
  7330. {
  7331. mIgnoreErrors = prevIgnoreErrors.mPrevVal;
  7332. BfTypeReference* errorRefNode = qualifiedTypeRef->mLeft;
  7333. if ((leftIsValid) && (mCurTypeInstance != NULL) && (mSystem->ContainsNamespace(leftComposite, mCurTypeInstance->mTypeDef->mProject)))
  7334. {
  7335. // The left was a namespace name, so throw an error on the whole string
  7336. errorRefNode = qualifiedTypeRef;
  7337. }
  7338. TypeRefNotFound(errorRefNode);
  7339. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7340. }
  7341. prevIgnoreErrors.Restore();
  7342. if (qualifiedTypeRef->mRight == NULL)
  7343. {
  7344. FailAfter("Expected identifier", qualifiedTypeRef->mDot);
  7345. //AssertErrorState();
  7346. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7347. }
  7348. auto resolvedType = ResolveInnerType(leftType, qualifiedTypeRef->mRight, populateType, false, numGenericArgs);
  7349. if ((resolvedType != NULL) && (mCurTypeInstance != NULL))
  7350. AddDependency(leftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  7351. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  7352. // If we did a ResolveTypeResult, then that may process an alias as the alias-to type instead of the actual alias
  7353. //return ResolveInnerType(leftType, qualifiedTypeRef->mRight, populateType);
  7354. }
  7355. if (auto resolvedTypeRef = BfNodeDynCast<BfResolvedTypeReference>(typeRef))
  7356. {
  7357. return ResolveTypeResult(typeRef, resolvedTypeRef->mType, populateType, resolveFlags);
  7358. }
  7359. if (auto retTypeTypeRef = BfNodeDynCastExact<BfModifiedTypeRef>(typeRef))
  7360. {
  7361. if (retTypeTypeRef->mRetTypeToken->mToken == BfToken_RetType)
  7362. {
  7363. bool allowThrough = false;
  7364. BfType* resolvedType = NULL;
  7365. if (retTypeTypeRef->mElementType != NULL)
  7366. {
  7367. auto innerType = ResolveTypeRef(retTypeTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  7368. if (innerType != NULL)
  7369. {
  7370. if ((innerType->IsDelegate()) || (innerType->IsFunction()))
  7371. {
  7372. PopulateType(innerType, BfPopulateType_DataAndMethods);
  7373. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(innerType->ToTypeInstance(), 0, "Invoke");
  7374. if (invokeMethodInstance != NULL)
  7375. {
  7376. resolvedType = invokeMethodInstance->mReturnType;
  7377. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  7378. }
  7379. }
  7380. else if (innerType->IsGenericParam())
  7381. {
  7382. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  7383. {
  7384. // We could have case where we have "rettype(@T0)" and @T0 gets a type variation of @M0, but we can't do a
  7385. // GetGenericParamInstance on that
  7386. allowThrough = true;
  7387. }
  7388. else
  7389. {
  7390. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)innerType);
  7391. if (genericParamInstance->mTypeConstraint != NULL)
  7392. {
  7393. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()))
  7394. {
  7395. resolvedType = GetDelegateReturnType(genericParamInstance->mTypeConstraint);
  7396. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  7397. }
  7398. else if ((genericParamInstance->mTypeConstraint->IsTypeInstance()) &&
  7399. ((genericParamInstance->mTypeConstraint->ToTypeInstance()->mTypeDef == mCompiler->mDelegateTypeDef) ||
  7400. (genericParamInstance->mTypeConstraint->ToTypeInstance()->mTypeDef == mCompiler->mFunctionTypeDef)))
  7401. {
  7402. allowThrough = true;
  7403. }
  7404. }
  7405. }
  7406. }
  7407. else if (innerType->IsMethodRef())
  7408. {
  7409. auto methodRefType = (BfMethodRefType*)innerType;
  7410. resolvedType = methodRefType->mMethodRef->mReturnType;
  7411. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  7412. }
  7413. }
  7414. }
  7415. if (!allowThrough)
  7416. {
  7417. Fail("'rettype' can only be used on delegate or function types", retTypeTypeRef->mRetTypeToken);
  7418. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  7419. }
  7420. }
  7421. else if (retTypeTypeRef->mRetTypeToken->mToken == BfToken_AllocType)
  7422. {
  7423. BfType* resolvedType = NULL;
  7424. if (retTypeTypeRef->mElementType != NULL)
  7425. {
  7426. resolvedType = ResolveTypeRef(retTypeTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  7427. if (resolvedType != NULL)
  7428. {
  7429. if (resolvedType->IsGenericParam())
  7430. {
  7431. auto genericParam = GetGenericParamInstance((BfGenericParamType*)resolvedType);
  7432. if (((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsValueType())) ||
  7433. ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Enum)) != 0))
  7434. {
  7435. resolvedType = CreatePointerType(resolvedType);
  7436. }
  7437. else if (((genericParam->mTypeConstraint != NULL) && (!genericParam->mTypeConstraint->IsValueType())) ||
  7438. ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Class)) != 0))
  7439. {
  7440. // Leave as 'T'
  7441. }
  7442. else
  7443. resolvedType = CreateModifiedTypeType(resolvedType, BfToken_AllocType);
  7444. }
  7445. else if (resolvedType->IsValueType())
  7446. resolvedType = CreatePointerType(resolvedType);
  7447. }
  7448. }
  7449. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  7450. }
  7451. else if (retTypeTypeRef->mRetTypeToken->mToken == BfToken_Nullable)
  7452. {
  7453. bool allowThrough = false;
  7454. BfType* resolvedType = NULL;
  7455. if (retTypeTypeRef->mElementType != NULL)
  7456. {
  7457. resolvedType = ResolveTypeRef(retTypeTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  7458. }
  7459. if ((resolvedType != NULL) && (resolvedType->IsGenericParam()))
  7460. {
  7461. //resolvedType = CreateModifiedTypeType(resolvedType, BfToken_Nullable);
  7462. BfTypeVector typeVec;
  7463. typeVec.push_back(resolvedType);
  7464. resolvedType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec, BfPopulateType_Declaration);
  7465. }
  7466. else if (resolvedType != NULL)
  7467. {
  7468. if (resolvedType->IsValueType())
  7469. {
  7470. if (InDefinitionSection())
  7471. Warn(0, StrFormat("Consider using '%s?' instead of nullable modifier", TypeToString(resolvedType).c_str()), retTypeTypeRef);
  7472. BfTypeVector typeVec;
  7473. typeVec.push_back(resolvedType);
  7474. resolvedType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec, BfPopulateType_Declaration);
  7475. }
  7476. else
  7477. {
  7478. if (InDefinitionSection())
  7479. Warn(0, StrFormat("Unneeded nullable modifier, %s is already nullable", TypeToString(resolvedType).c_str()), retTypeTypeRef->mRetTypeToken);
  7480. }
  7481. }
  7482. if (resolvedType != NULL)
  7483. PopulateType(resolvedType, populateType);
  7484. return resolvedType;
  7485. }
  7486. else
  7487. BFMODULE_FATAL(this, "Unhandled");
  7488. }
  7489. if (auto refTypeRef = BfNodeDynCastExact<BfRefTypeRef>(typeRef))
  7490. {
  7491. if ((refTypeRef->mRefToken != NULL) && (refTypeRef->mRefToken->GetToken() == BfToken_Mut) && (refTypeRef->mElementType != NULL))
  7492. {
  7493. bool needsRefWrap = false;
  7494. auto resolvedType = ResolveTypeRef(refTypeRef->mElementType, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  7495. if (resolvedType != NULL)
  7496. {
  7497. if ((resolvedType->IsValueType()) || (resolvedType->IsGenericParam()))
  7498. needsRefWrap = true;
  7499. if ((InDefinitionSection()) && (!resolvedType->IsGenericParam()) && ((resolveFlags & BfResolveTypeRefFlag_NoWarnOnMut) == 0))
  7500. {
  7501. if (!resolvedType->IsValueType())
  7502. Warn(0, StrFormat("Specified 'mut' has no effect on '%s' since reference types are always mutable", TypeToString(resolvedType).c_str()), refTypeRef->mRefToken);
  7503. else
  7504. Warn(0, "Use 'mut' for generic arguments which may or may not be reference types. Consider using 'ref' here, instead.", refTypeRef->mRefToken);
  7505. }
  7506. }
  7507. if (!needsRefWrap)
  7508. {
  7509. // Non-composites (including pointers) don't actually need ref-wrapping for 'mut'
  7510. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  7511. }
  7512. }
  7513. }
  7514. BfResolvedTypeSet::LookupContext lookupCtx;
  7515. lookupCtx.mResolveFlags = (BfResolveTypeRefFlags)(resolveFlags & (BfResolveTypeRefFlag_NoCreate | BfResolveTypeRefFlag_IgnoreLookupError));
  7516. lookupCtx.mRootTypeRef = typeRef;
  7517. lookupCtx.mRootTypeDef = typeDef;
  7518. lookupCtx.mModule = this;
  7519. BfResolvedTypeSet::Entry* resolvedEntry = NULL;
  7520. auto inserted = mContext->mResolvedTypes.Insert(typeRef, &lookupCtx, &resolvedEntry);
  7521. if (resolvedEntry == NULL)
  7522. {
  7523. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7524. }
  7525. if (!inserted)
  7526. {
  7527. BF_ASSERT(resolvedEntry->mValue != NULL);
  7528. return ResolveTypeResult(typeRef, resolvedEntry->mValue, populateType, resolveFlags);
  7529. }
  7530. if ((resolveFlags & BfResolveTypeRefFlag_NoCreate) != 0)
  7531. {
  7532. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7533. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7534. }
  7535. BfModule* populateModule = this;
  7536. if ((resolveFlags & BfResolveTypeRefFlag_NoReify) != 0)
  7537. populateModule = mContext->mUnreifiedModule;
  7538. if (typeRef->IsTypeDefTypeReference())
  7539. {
  7540. //BF_ASSERT(typeDefTypeRef->mTypeDef != NULL); // Resolved higher up
  7541. //auto typeDef = typeDefTypeRef->mTypeDef;
  7542. if ((typeDef->mTypeCode >= BfTypeCode_None) && (typeDef->mTypeCode <= BfTypeCode_Double))
  7543. {
  7544. BfPrimitiveType* primType = new BfPrimitiveType();
  7545. primType->mTypeDef = typeDef;
  7546. resolvedEntry->mValue = primType;
  7547. BF_ASSERT(BfResolvedTypeSet::Hash(primType, &lookupCtx, false) == resolvedEntry->mHash);
  7548. populateModule->InitType(primType, populateType);
  7549. return ResolveTypeResult(typeRef, primType, populateType, resolveFlags);
  7550. }
  7551. BfTypeInstance* outerTypeInstance = lookupCtx.mRootOuterTypeInstance;
  7552. if (outerTypeInstance == NULL)
  7553. outerTypeInstance = mCurTypeInstance;
  7554. if ((outerTypeInstance != NULL) && (typeDef->mGenericParamDefs.size() != 0))
  7555. {
  7556. // Try to inherit generic params from current parent
  7557. BfTypeDef* outerType = mSystem->GetCombinedPartial(typeDef->mOuterType);
  7558. BF_ASSERT(!outerType->mIsPartial);
  7559. if (TypeHasParentOrEquals(outerTypeInstance->mTypeDef, outerType))
  7560. {
  7561. BfType* checkCurType = outerTypeInstance;
  7562. if (checkCurType->IsBoxed())
  7563. checkCurType = checkCurType->GetUnderlyingType();
  7564. if (checkCurType->IsTypeAlias())
  7565. checkCurType = GetOuterType(checkCurType);
  7566. BF_ASSERT(checkCurType->IsGenericTypeInstance());
  7567. int numParentGenericParams = (int)outerType->mGenericParamDefs.size();
  7568. int wantedGenericParams = (int)typeDef->mGenericParamDefs.size() - numParentGenericParams;
  7569. if (wantedGenericParams != 0)
  7570. {
  7571. if (wantedGenericParams == 1)
  7572. Fail("Expected generic argument", typeRef);
  7573. else
  7574. Fail(StrFormat("Expected %d generic arguments", wantedGenericParams), typeRef);
  7575. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7576. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7577. }
  7578. auto parentGenericTypeInstance = (BfTypeInstance*)checkCurType;
  7579. BfTypeInstance* genericTypeInst;
  7580. if (typeDef->mTypeCode == BfTypeCode_TypeAlias)
  7581. {
  7582. auto typeAliasType = new BfTypeAliasType();
  7583. genericTypeInst = typeAliasType;
  7584. }
  7585. else
  7586. genericTypeInst = new BfTypeInstance();
  7587. genericTypeInst->mGenericTypeInfo = new BfGenericTypeInfo();
  7588. genericTypeInst->mTypeDef = typeDef;
  7589. if (parentGenericTypeInstance->mGenericTypeInfo->mGenericParams.IsEmpty())
  7590. PopulateType(parentGenericTypeInstance, BfPopulateType_Declaration);
  7591. for (int i = 0; i < numParentGenericParams; i++)
  7592. {
  7593. genericTypeInst->mGenericTypeInfo->mGenericParams.push_back(parentGenericTypeInstance->mGenericTypeInfo->mGenericParams[i]->AddRef());
  7594. genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.push_back(parentGenericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[i]);
  7595. }
  7596. CheckUnspecializedGenericType(genericTypeInst, populateType);
  7597. resolvedEntry->mValue = genericTypeInst;
  7598. populateModule->InitType(genericTypeInst, populateType);
  7599. BF_ASSERT(BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx) == resolvedEntry->mHash);
  7600. return ResolveTypeResult(typeRef, genericTypeInst, populateType, resolveFlags);
  7601. }
  7602. }
  7603. BfTypeInstance* typeInst;
  7604. if (typeDef->mTypeCode == BfTypeCode_TypeAlias)
  7605. {
  7606. auto typeAliasType = new BfTypeAliasType();
  7607. typeInst = typeAliasType;
  7608. }
  7609. else
  7610. {
  7611. typeInst = new BfTypeInstance();
  7612. }
  7613. typeInst->mTypeDef = typeDef;
  7614. if (typeInst->mTypeDef->mGenericParamDefs.size() != 0)
  7615. {
  7616. Fail("Generic type arguments expected", typeRef);
  7617. delete typeInst;
  7618. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7619. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7620. }
  7621. resolvedEntry->mValue = typeInst;
  7622. #ifdef _DEBUG
  7623. int typeRefash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx);
  7624. #endif
  7625. populateModule->InitType(typeInst, populateType);
  7626. if (BfResolvedTypeSet::Hash(typeInst, &lookupCtx) != resolvedEntry->mHash)
  7627. {
  7628. int refHash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx);
  7629. int typeHash = BfResolvedTypeSet::Hash(typeInst, &lookupCtx);
  7630. BF_ASSERT(refHash == typeHash);
  7631. }
  7632. {
  7633. BF_ASSERT(BfResolvedTypeSet::Hash(typeInst, &lookupCtx) == resolvedEntry->mHash);
  7634. }
  7635. return ResolveTypeResult(typeRef, typeInst, populateType, resolveFlags);
  7636. }
  7637. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(typeRef))
  7638. {
  7639. if (arrayTypeRef->mDimensions > 4)
  7640. {
  7641. Fail("Too many array dimensions, consider using a jagged array.", arrayTypeRef);
  7642. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7643. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7644. }
  7645. auto elementType = ResolveTypeRef(arrayTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  7646. if (elementType == NULL)
  7647. {
  7648. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7649. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7650. }
  7651. if ((arrayTypeRef->mDimensions == 1) && (arrayTypeRef->mParams.size() == 1))
  7652. {
  7653. intptr elementCount = -1;
  7654. BfExpression* sizeExpr = BfNodeDynCast<BfExpression>(arrayTypeRef->mParams[0]);
  7655. BF_ASSERT(sizeExpr != NULL);
  7656. if (sizeExpr != NULL)
  7657. {
  7658. BfConstResolver constResolver(this);
  7659. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  7660. constResolver.mExpectingType = intType;
  7661. constResolver.mAllowGenericConstValue = true;
  7662. BfTypedValue typedVal;
  7663. {
  7664. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  7665. typedVal = constResolver.Resolve(sizeExpr, NULL, BfConstResolveFlag_ArrayInitSize);
  7666. }
  7667. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  7668. {
  7669. BfUnknownSizedArrayType* arrayType = new BfUnknownSizedArrayType();
  7670. arrayType->mContext = mContext;
  7671. arrayType->mElementType = elementType;
  7672. arrayType->mElementCount = -1;
  7673. arrayType->mElementCountSource = typedVal.mType;
  7674. resolvedEntry->mValue = arrayType;
  7675. BF_ASSERT(BfResolvedTypeSet::Hash(arrayType, &lookupCtx) == resolvedEntry->mHash);
  7676. populateModule->InitType(arrayType, populateType);
  7677. return ResolveTypeResult(typeRef, arrayType, populateType, resolveFlags);
  7678. }
  7679. if (typedVal)
  7680. typedVal = Cast(sizeExpr, typedVal, intType);
  7681. if (typedVal)
  7682. {
  7683. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  7684. if (constant != NULL)
  7685. {
  7686. if (constant->mConstType == BfConstType_Undef)
  7687. elementCount = -1; // Undef marker
  7688. else if (BfIRBuilder::IsInt(constant->mTypeCode))
  7689. elementCount = constant->mInt32;
  7690. }
  7691. }
  7692. }
  7693. /*if (elementCount < 0)
  7694. {
  7695. Fail(StrFormat("Array length '%d' is illegal", elementCount), arrayTypeRef->mParams[0]);
  7696. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7697. return CreateSizedArrayType(elementType, 0);
  7698. }*/
  7699. BfSizedArrayType* arrayType = new BfSizedArrayType();
  7700. arrayType->mContext = mContext;
  7701. arrayType->mElementType = elementType;
  7702. arrayType->mElementCount = elementCount;
  7703. arrayType->mWantsGCMarking = false; // Fill in in InitType
  7704. resolvedEntry->mValue = arrayType;
  7705. BF_ASSERT(BfResolvedTypeSet::Hash(arrayType, &lookupCtx) == resolvedEntry->mHash);
  7706. populateModule->InitType(arrayType, populateType);
  7707. return ResolveTypeResult(typeRef, arrayType, populateType, resolveFlags);
  7708. }
  7709. BfArrayType* arrayType = new BfArrayType();
  7710. arrayType->mGenericTypeInfo = new BfGenericTypeInfo();
  7711. arrayType->mContext = mContext;
  7712. arrayType->mDimensions = arrayTypeRef->mDimensions;
  7713. arrayType->mTypeDef = mCompiler->GetArrayTypeDef(arrayType->mDimensions);
  7714. arrayType->mGenericTypeInfo->mTypeGenericArguments.push_back(elementType);
  7715. resolvedEntry->mValue = arrayType;
  7716. CheckUnspecializedGenericType(arrayType, populateType);
  7717. BF_ASSERT(BfResolvedTypeSet::Hash(arrayType, &lookupCtx) == resolvedEntry->mHash);
  7718. populateModule->InitType(arrayType, populateType);
  7719. return ResolveTypeResult(typeRef, arrayType, populateType, resolveFlags);
  7720. }
  7721. else if (auto genericTypeInstRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  7722. {
  7723. int wantNumGenericParams = genericTypeInstRef->GetGenericArgCount();
  7724. BfTypeDef* ambiguousTypeDef = NULL;
  7725. Array<BfTypeReference*> genericArguments;
  7726. std::function<void(BfTypeReference*)> _GetTypeRefs = [&](BfTypeReference* typeRef)
  7727. {
  7728. if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(typeRef))
  7729. {
  7730. _GetTypeRefs(elementedTypeRef->mElementType);
  7731. }
  7732. else if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  7733. {
  7734. _GetTypeRefs(qualifiedTypeRef->mLeft);
  7735. }
  7736. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  7737. {
  7738. for (auto genericArg : genericTypeRef->mGenericArguments)
  7739. genericArguments.push_back(genericArg);
  7740. }
  7741. };
  7742. _GetTypeRefs(genericTypeInstRef);
  7743. BfTypeVector genericArgs;
  7744. BfType* type = NULL;
  7745. BfTypeDef* typeDef = ResolveGenericInstanceDef(genericTypeInstRef, &type);
  7746. if(ambiguousTypeDef != NULL)
  7747. ShowAmbiguousTypeError(typeRef, typeDef, ambiguousTypeDef);
  7748. if (typeDef == NULL)
  7749. {
  7750. Fail("Unable to resolve type", typeRef);
  7751. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7752. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7753. }
  7754. BfTypeInstance* outerTypeInstance = mCurTypeInstance;
  7755. auto outerType = typeDef->mOuterType;
  7756. BfTypeDef* commonOuterType = NULL;
  7757. int startDefGenericParamIdx = 0;
  7758. commonOuterType = BfResolvedTypeSet::FindRootCommonOuterType(outerType, &lookupCtx, outerTypeInstance);
  7759. if ((commonOuterType) && (outerTypeInstance->IsGenericTypeInstance()))
  7760. {
  7761. startDefGenericParamIdx = (int)commonOuterType->mGenericParamDefs.size();
  7762. auto parentTypeInstance = outerTypeInstance;
  7763. if (parentTypeInstance->IsTypeAlias())
  7764. parentTypeInstance = (BfTypeInstance*)GetOuterType(parentTypeInstance)->ToTypeInstance();
  7765. for (int i = 0; i < startDefGenericParamIdx; i++)
  7766. genericArgs.push_back(parentTypeInstance->mGenericTypeInfo->mTypeGenericArguments[i]);
  7767. }
  7768. for (auto genericArgRef : genericArguments)
  7769. {
  7770. auto genericArg = ResolveTypeRef(genericArgRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_AllowGenericTypeParamConstValue | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue));
  7771. if (genericArg == NULL)
  7772. {
  7773. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7774. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7775. }
  7776. genericArgs.Add(genericArg);
  7777. }
  7778. BfTypeInstance* genericTypeInst;
  7779. if ((type != NULL) &&
  7780. ((type->IsDelegateFromTypeRef()) || (type->IsFunctionFromTypeRef())))
  7781. {
  7782. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7783. return ResolveGenericType(type, &genericArgs, NULL);
  7784. }
  7785. else if ((type != NULL) && (type->IsTuple()))
  7786. {
  7787. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7788. return ResolveGenericType(type, &genericArgs, NULL);
  7789. }
  7790. else if ((typeDef != NULL) && (typeDef->mTypeCode == BfTypeCode_TypeAlias))
  7791. {
  7792. auto typeAliasType = new BfTypeAliasType();
  7793. genericTypeInst = typeAliasType;
  7794. }
  7795. else
  7796. genericTypeInst = new BfTypeInstance();
  7797. genericTypeInst->mContext = mContext;
  7798. genericTypeInst->mGenericTypeInfo = new BfGenericTypeInfo();
  7799. BF_ASSERT(typeDef->mDefState != BfTypeDef::DefState_Deleted);
  7800. int genericParamCount = (int)typeDef->mGenericParamDefs.size();
  7801. if ((type != NULL) && (type->IsGenericTypeInstance()))
  7802. {
  7803. // Is a generic type for sure...
  7804. // We need this case for generic methods
  7805. genericParamCount = (int)((BfTypeInstance*)type)->mGenericTypeInfo->mTypeGenericArguments.size();
  7806. }
  7807. else if (typeDef->mGenericParamDefs.size() == 0)
  7808. {
  7809. Fail("Not a generic type", typeRef);
  7810. delete genericTypeInst;
  7811. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7812. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7813. }
  7814. genericTypeInst->mTypeDef = typeDef;
  7815. if ((commonOuterType != NULL) && (outerTypeInstance->IsGenericTypeInstance()))
  7816. {
  7817. auto parentTypeInstance = outerTypeInstance;
  7818. if (parentTypeInstance->IsTypeAlias())
  7819. parentTypeInstance = (BfTypeInstance*)GetOuterType(parentTypeInstance)->ToTypeInstance();
  7820. for (int i = 0; i < startDefGenericParamIdx; i++)
  7821. {
  7822. genericTypeInst->mGenericTypeInfo->mGenericParams.push_back(parentTypeInstance->mGenericTypeInfo->mGenericParams[i]->AddRef());
  7823. genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.push_back(parentTypeInstance->mGenericTypeInfo->mTypeGenericArguments[i]);
  7824. auto typeGenericArg = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[i];
  7825. genericTypeInst->mGenericTypeInfo->mIsUnspecialized |= typeGenericArg->IsGenericParam() || typeGenericArg->IsUnspecializedType();
  7826. }
  7827. }
  7828. int wantedGenericParams = genericParamCount - startDefGenericParamIdx;
  7829. int genericArgDiffCount = (int)genericArguments.size() - wantedGenericParams;
  7830. if (genericArgDiffCount != 0)
  7831. {
  7832. int innerWantedGenericParams = genericParamCount;
  7833. if (typeDef->mOuterType != NULL)
  7834. innerWantedGenericParams -= (int)typeDef->mOuterType->mGenericParamDefs.size();
  7835. ShowGenericArgCountError(genericTypeInstRef, innerWantedGenericParams);
  7836. delete genericTypeInst;
  7837. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7838. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7839. }
  7840. int genericParamIdx = 0;
  7841. for (auto genericArgRef : genericArguments)
  7842. {
  7843. auto genericArg = genericArgs[genericParamIdx + startDefGenericParamIdx];
  7844. genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.push_back(genericArg);
  7845. genericTypeInst->mGenericTypeInfo->mTypeGenericArgumentRefs.push_back(genericArgRef);
  7846. if (genericArg->IsConstExprValue())
  7847. {
  7848. NOP;
  7849. }
  7850. genericParamIdx++;
  7851. }
  7852. resolvedEntry->mValue = genericTypeInst;
  7853. CheckUnspecializedGenericType(genericTypeInst, populateType);
  7854. populateModule->InitType(genericTypeInst, populateType);
  7855. #ifdef _DEBUG
  7856. if (BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx) != resolvedEntry->mHash)
  7857. {
  7858. int refHash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx);
  7859. int typeHash = BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx);
  7860. BF_ASSERT(refHash == typeHash);
  7861. }
  7862. if (!BfResolvedTypeSet::Equals(genericTypeInst, typeRef, &lookupCtx))
  7863. {
  7864. BF_ASSERT(BfResolvedTypeSet::Equals(genericTypeInst, typeRef, &lookupCtx));
  7865. }
  7866. #endif
  7867. BF_ASSERT(BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx) == resolvedEntry->mHash);
  7868. return ResolveTypeResult(typeRef, genericTypeInst, populateType, resolveFlags);
  7869. }
  7870. else if (auto tupleTypeRef = BfNodeDynCast<BfTupleTypeRef>(typeRef))
  7871. {
  7872. Array<BfType*> types;
  7873. Array<String> names;
  7874. bool wantGeneric = false;
  7875. bool isUnspecialized = false;
  7876. for (int fieldIdx = 0; fieldIdx < (int)tupleTypeRef->mFieldTypes.size(); fieldIdx++)
  7877. {
  7878. BfTypeReference* typeRef = tupleTypeRef->mFieldTypes[fieldIdx];
  7879. auto type = ResolveTypeRef(typeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  7880. if (type == NULL)
  7881. {
  7882. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7883. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7884. }
  7885. String fieldName;
  7886. BfIdentifierNode* identifierNode = NULL;
  7887. if (fieldIdx < (int)tupleTypeRef->mFieldNames.size())
  7888. identifierNode = tupleTypeRef->mFieldNames[fieldIdx];
  7889. if (identifierNode != NULL)
  7890. fieldName = identifierNode->ToString();
  7891. else
  7892. fieldName = StrFormat("%d", fieldIdx);
  7893. if (type->IsGenericParam())
  7894. wantGeneric = true;
  7895. if (type->IsUnspecializedType())
  7896. isUnspecialized = true;
  7897. BF_ASSERT(!type->IsVar());
  7898. // if (type->IsVar())
  7899. // isUnspecialized = true;
  7900. String typeName = TypeToString(type);
  7901. types.push_back(type);
  7902. names.push_back(fieldName);
  7903. }
  7904. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsGenericTypeInstance()))
  7905. wantGeneric = false;
  7906. auto baseType = (BfTypeInstance*)ResolveTypeDef(mContext->mCompiler->mValueTypeTypeDef, BfPopulateType_Identity);
  7907. BfTypeInstance* tupleType = NULL;
  7908. if (wantGeneric)
  7909. {
  7910. BfTupleType* actualTupleType = new BfTupleType();
  7911. actualTupleType->mGenericTypeInfo = new BfGenericTypeInfo();
  7912. actualTupleType->mGenericTypeInfo->mFinishedGenericParams = true;
  7913. actualTupleType->Init(baseType->mTypeDef->mProject, baseType);
  7914. for (int fieldIdx = 0; fieldIdx < (int)types.size(); fieldIdx++)
  7915. {
  7916. BfFieldDef* fieldDef = actualTupleType->AddField(names[fieldIdx]);
  7917. fieldDef->mProtection = (names[fieldIdx][0] == '_') ? BfProtection_Private : BfProtection_Public;
  7918. }
  7919. actualTupleType->Finish();
  7920. auto parentTypeInstance = (BfTypeInstance*)mCurTypeInstance;
  7921. for (int i = 0; i < parentTypeInstance->mGenericTypeInfo->mGenericParams.size(); i++)
  7922. {
  7923. actualTupleType->mGenericTypeInfo->mGenericParams.push_back(parentTypeInstance->mGenericTypeInfo->mGenericParams[i]->AddRef());
  7924. actualTupleType->mGenericTypeInfo->mTypeGenericArguments.push_back(parentTypeInstance->mGenericTypeInfo->mTypeGenericArguments[i]);
  7925. auto typeGenericArg = actualTupleType->mGenericTypeInfo->mTypeGenericArguments[i];
  7926. actualTupleType->mGenericTypeInfo->mIsUnspecialized |= typeGenericArg->IsGenericParam() || typeGenericArg->IsUnspecializedType();
  7927. }
  7928. CheckUnspecializedGenericType(actualTupleType, populateType);
  7929. if (isUnspecialized)
  7930. {
  7931. actualTupleType->mGenericTypeInfo->mIsUnspecialized = true;
  7932. actualTupleType->mGenericTypeInfo->mIsUnspecializedVariation = true;
  7933. }
  7934. actualTupleType->mIsUnspecializedType = actualTupleType->mGenericTypeInfo->mIsUnspecialized;
  7935. actualTupleType->mIsUnspecializedTypeVariation = actualTupleType->mGenericTypeInfo->mIsUnspecializedVariation;
  7936. tupleType = actualTupleType;
  7937. }
  7938. else
  7939. {
  7940. BfTupleType* actualTupleType = new BfTupleType();
  7941. actualTupleType->Init(baseType->mTypeDef->mProject, baseType);
  7942. for (int fieldIdx = 0; fieldIdx < (int)types.size(); fieldIdx++)
  7943. {
  7944. BfFieldDef* fieldDef = actualTupleType->AddField(names[fieldIdx]);
  7945. fieldDef->mProtection = (names[fieldIdx][0] == '_') ? BfProtection_Private : BfProtection_Public;
  7946. }
  7947. actualTupleType->Finish();
  7948. tupleType = actualTupleType;
  7949. actualTupleType->mIsUnspecializedType = isUnspecialized;
  7950. actualTupleType->mIsUnspecializedTypeVariation = isUnspecialized;
  7951. }
  7952. tupleType->mFieldInstances.Resize(types.size());
  7953. for (int fieldIdx = 0; fieldIdx < (int)types.size(); fieldIdx++)
  7954. {
  7955. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  7956. fieldInstance->mFieldIdx = fieldIdx;
  7957. fieldInstance->SetResolvedType(types[fieldIdx]);
  7958. BF_ASSERT(!types[fieldIdx]->IsVar());
  7959. fieldInstance->mOwner = tupleType;
  7960. }
  7961. resolvedEntry->mValue = tupleType;
  7962. BF_ASSERT(BfResolvedTypeSet::Hash(tupleType, &lookupCtx) == resolvedEntry->mHash);
  7963. populateModule->InitType(tupleType, populateType);
  7964. #ifdef _DEBUG
  7965. BF_ASSERT(ResolveType(tupleType, BfPopulateType_Identity) == tupleType);
  7966. #endif
  7967. return ResolveTypeResult(typeRef, tupleType, populateType, resolveFlags);
  7968. }
  7969. else if (auto nullableTypeRef = BfNodeDynCast<BfNullableTypeRef>(typeRef))
  7970. {
  7971. BfTypeReference* elementTypeRef = nullableTypeRef->mElementType;
  7972. auto typeDef = mCompiler->mNullableTypeDef;
  7973. auto elementType = ResolveTypeRef(elementTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  7974. if (elementType == NULL)
  7975. {
  7976. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  7977. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  7978. }
  7979. BfTypeInstance* genericTypeInst = new BfTypeInstance();
  7980. genericTypeInst->mGenericTypeInfo = new BfGenericTypeInfo();
  7981. genericTypeInst->mContext = mContext;
  7982. genericTypeInst->mTypeDef = typeDef;
  7983. auto genericParamInstance = new BfGenericTypeParamInstance(typeDef, 0);
  7984. genericTypeInst->mGenericTypeInfo->mGenericParams.push_back(genericParamInstance);
  7985. genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.push_back(elementType);
  7986. //genericTypeInst->mIsUnspecialized = elementType->IsGenericParam() || elementType->IsUnspecializedType();
  7987. CheckUnspecializedGenericType(genericTypeInst, populateType);
  7988. resolvedEntry->mValue = genericTypeInst;
  7989. BF_ASSERT(BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx) == resolvedEntry->mHash);
  7990. populateModule->InitType(genericTypeInst, populateType);
  7991. return ResolveTypeResult(typeRef, genericTypeInst, populateType, resolveFlags);
  7992. }
  7993. else if (auto pointerTypeRef = BfNodeDynCast<BfPointerTypeRef>(typeRef))
  7994. {
  7995. BfPointerType* pointerType = new BfPointerType();
  7996. pointerType->mElementType = ResolveTypeRef(pointerTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  7997. pointerType->mContext = mContext;
  7998. if (pointerType->mElementType == NULL)
  7999. {
  8000. delete pointerType;
  8001. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  8002. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  8003. }
  8004. resolvedEntry->mValue = pointerType;
  8005. //int hashVal = mContext->mResolvedTypes.Hash(typeRef, &lookupCtx);
  8006. BF_ASSERT(BfResolvedTypeSet::Hash(pointerType, &lookupCtx) == resolvedEntry->mHash);
  8007. populateModule->InitType(pointerType, populateType);
  8008. return ResolveTypeResult(typeRef, pointerType, populateType, resolveFlags);
  8009. }
  8010. else if (auto refTypeRef = BfNodeDynCast<BfRefTypeRef>(typeRef))
  8011. {
  8012. BfRefType* refType = new BfRefType();
  8013. refType->mRefKind = BfRefType::RefKind_Ref;
  8014. if (refTypeRef->mRefToken == NULL)
  8015. refType->mRefKind = BfRefType::RefKind_Ref;
  8016. else if (refTypeRef->mRefToken->GetToken() == BfToken_Out)
  8017. refType->mRefKind = BfRefType::RefKind_Out;
  8018. else if (refTypeRef->mRefToken->GetToken() == BfToken_Mut)
  8019. refType->mRefKind = BfRefType::RefKind_Mut;
  8020. refType->mElementType = ResolveTypeRef(refTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  8021. if (refType->mElementType == NULL)
  8022. {
  8023. delete refType;
  8024. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  8025. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  8026. }
  8027. resolvedEntry->mValue = refType;
  8028. BF_ASSERT(BfResolvedTypeSet::Hash(refType, &lookupCtx) == resolvedEntry->mHash);
  8029. populateModule->InitType(refType, populateType);
  8030. return ResolveTypeResult(typeRef, refType, populateType, resolveFlags);
  8031. }
  8032. else if (auto delegateTypeRef = BfNodeDynCast<BfDelegateTypeRef>(typeRef))
  8033. {
  8034. bool wantGeneric = false;
  8035. bool isUnspecialized = false;
  8036. auto _CheckType = [&](BfType* type)
  8037. {
  8038. if (type->IsGenericParam())
  8039. wantGeneric = true;
  8040. if (type->IsUnspecializedType())
  8041. isUnspecialized = true;
  8042. };
  8043. bool failed = false;
  8044. auto returnType = ResolveTypeRef(delegateTypeRef->mReturnType, NULL, BfPopulateType_Declaration);
  8045. if (returnType == NULL)
  8046. {
  8047. failed = true;
  8048. returnType = GetPrimitiveType(BfTypeCode_Var);
  8049. }
  8050. _CheckType(returnType);
  8051. BfType* functionThisType = NULL;
  8052. bool hasMutSpecifier = false;
  8053. bool isFirst = true;
  8054. bool isDelegate = delegateTypeRef->mTypeToken->GetToken() == BfToken_Delegate;
  8055. Array<BfType*> paramTypes;
  8056. for (auto param : delegateTypeRef->mParams)
  8057. {
  8058. BfResolveTypeRefFlags resolveTypeFlags = BfResolveTypeRefFlag_AllowRef;
  8059. if ((param->mNameNode != NULL) && (param->mNameNode->Equals("this")))
  8060. resolveTypeFlags = (BfResolveTypeRefFlags)(resolveTypeFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  8061. auto paramType = ResolveTypeRef(param->mTypeRef, BfPopulateType_Declaration, resolveTypeFlags);
  8062. if (paramType == NULL)
  8063. {
  8064. failed = true;
  8065. paramType = GetPrimitiveType(BfTypeCode_Var);
  8066. }
  8067. if ((!isDelegate) && (isFirst) && (param->mNameNode != NULL) && (param->mNameNode->Equals("this")))
  8068. {
  8069. functionThisType = paramType;
  8070. if (functionThisType->IsRef())
  8071. {
  8072. auto refType = (BfRefType*)functionThisType;
  8073. if (refType->mRefKind != BfRefType::RefKind_Mut)
  8074. {
  8075. if (auto refTypeRef = BfNodeDynCast<BfRefTypeRef>(param->mTypeRef))
  8076. {
  8077. failed = true;
  8078. Fail("Only 'mut' is allowed here", refTypeRef->mRefToken);
  8079. }
  8080. }
  8081. hasMutSpecifier = true;
  8082. functionThisType = refType->mElementType;
  8083. }
  8084. paramTypes.Add(functionThisType);
  8085. _CheckType(functionThisType);
  8086. }
  8087. else
  8088. {
  8089. paramTypes.Add(paramType);
  8090. _CheckType(paramType);
  8091. }
  8092. isFirst = false;
  8093. }
  8094. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsGenericTypeInstance()))
  8095. wantGeneric = false;
  8096. auto baseDelegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  8097. BfDelegateInfo* delegateInfo = NULL;
  8098. BfTypeInstance* delegateType = NULL;
  8099. if (wantGeneric)
  8100. {
  8101. BfDelegateType* genericTypeInst = new BfDelegateType();
  8102. genericTypeInst->mGenericTypeInfo = new BfGenericTypeInfo();
  8103. genericTypeInst->mGenericTypeInfo->mFinishedGenericParams = true;
  8104. delegateType = genericTypeInst;
  8105. delegateInfo = delegateType->GetDelegateInfo();
  8106. auto parentTypeInstance = (BfTypeInstance*)mCurTypeInstance;
  8107. for (int i = 0; i < parentTypeInstance->mGenericTypeInfo->mGenericParams.size(); i++)
  8108. {
  8109. genericTypeInst->mGenericTypeInfo->mGenericParams.push_back(parentTypeInstance->mGenericTypeInfo->mGenericParams[i]->AddRef());
  8110. genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.push_back(parentTypeInstance->mGenericTypeInfo->mTypeGenericArguments[i]);
  8111. auto typeGenericArg = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[i];
  8112. genericTypeInst->mGenericTypeInfo->mIsUnspecialized |= typeGenericArg->IsGenericParam() || typeGenericArg->IsUnspecializedType();
  8113. }
  8114. CheckUnspecializedGenericType(genericTypeInst, populateType);
  8115. // We don't ever need to do an actual pass over generic delegate methods, so it's safe to set the 'unspecialized variation' flag
  8116. if (isUnspecialized)
  8117. {
  8118. genericTypeInst->mGenericTypeInfo->mIsUnspecialized = true;
  8119. genericTypeInst->mGenericTypeInfo->mIsUnspecializedVariation = true;
  8120. }
  8121. genericTypeInst->mIsUnspecializedType = genericTypeInst->mGenericTypeInfo->mIsUnspecialized;
  8122. genericTypeInst->mIsUnspecializedTypeVariation = genericTypeInst->mGenericTypeInfo->mIsUnspecializedVariation;
  8123. }
  8124. else
  8125. {
  8126. auto dlgType = new BfDelegateType();
  8127. delegateInfo = dlgType->GetDelegateInfo();
  8128. dlgType->mIsUnspecializedType = isUnspecialized;
  8129. dlgType->mIsUnspecializedTypeVariation = isUnspecialized;
  8130. delegateType = dlgType;
  8131. }
  8132. Val128 hashContext;
  8133. BfTypeDef* typeDef = new BfTypeDef();
  8134. typeDef->mProject = baseDelegateType->mTypeDef->mProject;
  8135. typeDef->mSystem = mCompiler->mSystem;
  8136. typeDef->mName = mSystem->mEmptyAtom;
  8137. if (delegateTypeRef->mTypeToken->GetToken() == BfToken_Delegate)
  8138. {
  8139. typeDef->mIsDelegate = true;
  8140. typeDef->mTypeCode = BfTypeCode_Object;
  8141. }
  8142. else
  8143. {
  8144. typeDef->mIsFunction = true;
  8145. typeDef->mTypeCode = BfTypeCode_Struct;
  8146. }
  8147. BfMethodDef* methodDef = new BfMethodDef();
  8148. methodDef->mDeclaringType = typeDef;
  8149. methodDef->mName = "Invoke";
  8150. methodDef->mProtection = BfProtection_Public;
  8151. methodDef->mIdx = 0;
  8152. methodDef->mIsStatic = !typeDef->mIsDelegate && (functionThisType == NULL);
  8153. methodDef->mHasExplicitThis = functionThisType != NULL;
  8154. if ((functionThisType != NULL) && (hasMutSpecifier))
  8155. {
  8156. if ((functionThisType->IsValueType()) || (functionThisType->IsGenericParam()))
  8157. methodDef->mIsMutating = true;
  8158. }
  8159. auto directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  8160. delegateInfo->mDirectAllocNodes.push_back(directTypeRef);
  8161. if (typeDef->mIsDelegate)
  8162. directTypeRef->Init(delegateType);
  8163. else
  8164. directTypeRef->Init(ResolveTypeDef(mCompiler->mFunctionTypeDef));
  8165. typeDef->mBaseTypes.push_back(directTypeRef);
  8166. directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  8167. delegateInfo->mDirectAllocNodes.push_back(directTypeRef);
  8168. directTypeRef->Init(returnType);
  8169. methodDef->mReturnTypeRef = directTypeRef;
  8170. delegateInfo->mReturnType = returnType;
  8171. delegateInfo->mHasExplicitThis = functionThisType != NULL;
  8172. auto hashVal = mContext->mResolvedTypes.Hash(typeRef, &lookupCtx);
  8173. //int paramSrcOfs = (functionThisType != NULL) ? 1 : 0;
  8174. int paramSrcOfs = 0;
  8175. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  8176. {
  8177. auto param = delegateTypeRef->mParams[paramIdx + paramSrcOfs];
  8178. auto paramType = paramTypes[paramIdx];
  8179. if (paramType == NULL)
  8180. paramType = GetPrimitiveType(BfTypeCode_Var);
  8181. String paramName;
  8182. if (param->mNameNode != NULL)
  8183. paramName = param->mNameNode->ToString();
  8184. if (!paramType->IsReified())
  8185. delegateType->mIsReified = false;
  8186. auto directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  8187. delegateInfo->mDirectAllocNodes.push_back(directTypeRef);
  8188. directTypeRef->Init(paramType);
  8189. BfParameterDef* paramDef = new BfParameterDef();
  8190. paramDef->mTypeRef = directTypeRef;
  8191. paramDef->mName = paramName;
  8192. if ((paramIdx == 0) && (functionThisType != NULL))
  8193. paramDef->mParamKind = BfParamKind_ExplicitThis;
  8194. methodDef->mParams.push_back(paramDef);
  8195. delegateInfo->mParams.Add(paramType);
  8196. }
  8197. typeDef->mMethods.push_back(methodDef);
  8198. if (failed)
  8199. {
  8200. delete delegateType;
  8201. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  8202. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  8203. }
  8204. //
  8205. if (typeDef->mIsDelegate)
  8206. {
  8207. BfDefBuilder::AddMethod(typeDef, BfMethodType_Ctor, BfProtection_Public, false, "");
  8208. BfDefBuilder::AddDynamicCastMethods(typeDef);
  8209. }
  8210. delegateType->mContext = mContext;
  8211. delegateType->mTypeDef = typeDef;
  8212. populateModule->InitType(delegateType, populateType);
  8213. resolvedEntry->mValue = delegateType;
  8214. AddDependency(directTypeRef->mType, delegateType, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  8215. // if (delegateInfo->mFunctionThisType != NULL)
  8216. // AddDependency(delegateInfo->mFunctionThisType, delegateType, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  8217. for (auto paramType : paramTypes)
  8218. AddDependency(paramType, delegateType, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  8219. #ifdef _DEBUG
  8220. if (BfResolvedTypeSet::Hash(delegateType, &lookupCtx) != resolvedEntry->mHash)
  8221. {
  8222. int refHash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx);
  8223. int typeHash = BfResolvedTypeSet::Hash(delegateType, &lookupCtx);
  8224. BF_ASSERT(refHash == typeHash);
  8225. }
  8226. BF_ASSERT(BfResolvedTypeSet::Equals(delegateType, typeRef, &lookupCtx));
  8227. #endif
  8228. BF_ASSERT(BfResolvedTypeSet::Hash(delegateType, &lookupCtx) == resolvedEntry->mHash);
  8229. return ResolveTypeResult(typeRef, delegateType, populateType, resolveFlags);
  8230. }
  8231. else if (auto genericParamTypeRef = BfNodeDynCast<BfGenericParamTypeRef>(typeRef))
  8232. {
  8233. auto genericParamType = GetGenericParamType(genericParamTypeRef->mGenericParamKind, genericParamTypeRef->mGenericParamIdx);
  8234. resolvedEntry->mValue = genericParamType;
  8235. BF_ASSERT(BfResolvedTypeSet::Hash(genericParamType, &lookupCtx) == resolvedEntry->mHash);
  8236. return ResolveTypeResult(typeRef, genericParamType, populateType, resolveFlags);
  8237. }
  8238. else if (auto retTypeTypeRef = BfNodeDynCast<BfModifiedTypeRef>(typeRef))
  8239. {
  8240. auto retTypeType = new BfModifiedTypeType();
  8241. retTypeType->mModifiedKind = retTypeTypeRef->mRetTypeToken->mToken;
  8242. retTypeType->mElementType = ResolveTypeRef(retTypeTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  8243. // We know this is a generic param type, it can't fail to resolve
  8244. BF_ASSERT(retTypeType->mElementType);
  8245. resolvedEntry->mValue = retTypeType;
  8246. BF_ASSERT(BfResolvedTypeSet::Hash(retTypeType, &lookupCtx) == resolvedEntry->mHash);
  8247. populateModule->InitType(retTypeType, populateType);
  8248. return ResolveTypeResult(typeRef, retTypeType, populateType, resolveFlags);
  8249. }
  8250. else if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  8251. {
  8252. auto leftType = ResolveTypeRef(qualifiedTypeRef->mLeft, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  8253. if (leftType == NULL)
  8254. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  8255. return ResolveTypeResult(typeRef, ResolveInnerType(leftType, qualifiedTypeRef->mRight), populateType, resolveFlags);
  8256. }
  8257. else if (auto constTypeRef = BfNodeDynCastExact<BfConstTypeRef>(typeRef))
  8258. {
  8259. return ResolveTypeRef(constTypeRef->mElementType, populateType, (BfResolveTypeRefFlags)(resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam));
  8260. }
  8261. else if (auto constExprTypeRef = BfNodeDynCastExact<BfConstExprTypeRef>(typeRef))
  8262. {
  8263. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mDependencyMap.mMinDependDepth > 32))
  8264. {
  8265. Fail("Generic type dependency depth exceeded", typeRef);
  8266. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  8267. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  8268. }
  8269. BfVariant result;
  8270. BfType* resultType = NULL;
  8271. if (constExprTypeRef->mConstExpr != NULL)
  8272. {
  8273. result = mContext->mResolvedTypes.EvaluateToVariant(&lookupCtx, constExprTypeRef->mConstExpr, resultType);
  8274. BF_ASSERT(resultType != NULL);
  8275. }
  8276. auto constExprType = new BfConstExprValueType();
  8277. constExprType->mContext = mContext;
  8278. constExprType->mType = resultType;
  8279. BF_ASSERT(constExprType->mType != NULL);
  8280. if (constExprType->mType == NULL)
  8281. constExprType->mType = GetPrimitiveType(BfTypeCode_Let);
  8282. constExprType->mValue = result;
  8283. resolvedEntry->mValue = constExprType;
  8284. #ifdef _DEBUG
  8285. if (BfResolvedTypeSet::Hash(constExprType, &lookupCtx) != resolvedEntry->mHash)
  8286. {
  8287. int refHash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx);
  8288. int typeHash = BfResolvedTypeSet::Hash(constExprType, &lookupCtx);
  8289. BF_ASSERT(refHash == typeHash);
  8290. }
  8291. BF_ASSERT(BfResolvedTypeSet::Equals(constExprType, typeRef, &lookupCtx));
  8292. #endif
  8293. populateModule->InitType(constExprType, populateType);
  8294. return constExprType;
  8295. }
  8296. else
  8297. {
  8298. BFMODULE_FATAL(this, "Not implemented!");
  8299. NotImpl(typeRef);
  8300. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  8301. }
  8302. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  8303. }
  8304. BfType* BfModule::ResolveTypeRefAllowUnboundGenerics(BfTypeReference* typeRef, BfPopulateType populateType, bool resolveGenericParam)
  8305. {
  8306. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  8307. {
  8308. if (genericTypeRef->mGenericArguments.size() == 0)
  8309. {
  8310. auto genericTypeDef = ResolveGenericInstanceDef(genericTypeRef);
  8311. if (genericTypeDef == NULL)
  8312. return NULL;
  8313. BfTypeVector typeVector;
  8314. for (int i = 0; i < (int)genericTypeDef->mGenericParamDefs.size(); i++)
  8315. typeVector.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  8316. return ResolveTypeDef(genericTypeDef, typeVector, populateType);
  8317. }
  8318. }
  8319. return ResolveTypeRef(typeRef, populateType, resolveGenericParam ? (BfResolveTypeRefFlags)0 : BfResolveTypeRefFlag_NoResolveGenericParam);
  8320. }
  8321. // This finds non-default unspecialized generic type instances and converts them into a BfUnspecializedGenericTypeVariation
  8322. BfType* BfModule::CheckUnspecializedGenericType(BfTypeInstance* genericTypeInst, BfPopulateType populateType)
  8323. {
  8324. int argCount = (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size();
  8325. bool isDefaultUnspecialized = true;
  8326. for (int argIdx = 0; argIdx < argCount; argIdx++)
  8327. {
  8328. auto argType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[argIdx];
  8329. if (argType->IsGenericParam())
  8330. {
  8331. auto genericParamType = (BfGenericParamType*)argType;
  8332. if ((genericParamType->mGenericParamKind != BfGenericParamKind_Type) || (genericParamType->mGenericParamIdx != argIdx))
  8333. isDefaultUnspecialized = false;
  8334. genericTypeInst->mGenericTypeInfo->mIsUnspecialized = true;
  8335. }
  8336. else if (argType->IsUnspecializedType())
  8337. {
  8338. isDefaultUnspecialized = false;
  8339. genericTypeInst->mGenericTypeInfo->mIsUnspecialized = true;
  8340. }
  8341. else
  8342. isDefaultUnspecialized = false;
  8343. }
  8344. if (genericTypeInst->mGenericTypeInfo->mIsUnspecialized)
  8345. genericTypeInst->mGenericTypeInfo->mIsUnspecializedVariation = !isDefaultUnspecialized;
  8346. return genericTypeInst;
  8347. }
  8348. BfTypeInstance* BfModule::GetUnspecializedTypeInstance(BfTypeInstance* typeInst)
  8349. {
  8350. if (!typeInst->IsGenericTypeInstance())
  8351. return typeInst;
  8352. BF_ASSERT((!typeInst->IsDelegateFromTypeRef()) && (!typeInst->IsFunctionFromTypeRef()));
  8353. auto genericTypeInst = (BfTypeInstance*)typeInst;
  8354. auto result = ResolveTypeDef(genericTypeInst->mTypeDef, BfPopulateType_Declaration);
  8355. BF_ASSERT((result != NULL) && (result->IsUnspecializedType()));
  8356. if (result == NULL)
  8357. return NULL;
  8358. return result->ToTypeInstance();
  8359. }
  8360. BfType* BfModule::ResolveInnerType(BfType* outerType, BfIdentifierNode* identifier, BfPopulateType populateType, bool ignoreErrors)
  8361. {
  8362. BfDirectStrTypeReference typeRef;
  8363. typeRef.Init(identifier->ToString());
  8364. // There is no ref node so we ignore errors
  8365. auto type = ResolveInnerType(outerType, &typeRef, populateType, /*ignoreErrors*/true);
  8366. return type;
  8367. }
  8368. BfType* BfModule::ResolveTypeRef(BfAstNode* astNode, const BfSizedArray<BfTypeReference*>* genericArgs, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  8369. {
  8370. if ((genericArgs == NULL) || (genericArgs->size() == 0))
  8371. {
  8372. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(astNode))
  8373. {
  8374. BfNamedTypeReference typeRef;
  8375. typeRef.mNameNode = identifier;
  8376. typeRef.mSrcEnd = 0;
  8377. typeRef.mToken = BfToken_None;
  8378. auto type = ResolveTypeRef(&typeRef, populateType, resolveFlags);
  8379. return type;
  8380. }
  8381. }
  8382. BfAstAllocator alloc;
  8383. alloc.mSourceData = astNode->GetSourceData();
  8384. std::function<BfTypeReference*(BfAstNode*)> _ConvType = [&] (BfAstNode* astNode) -> BfTypeReference*
  8385. {
  8386. if (auto typeRef = BfNodeDynCast<BfTypeReference>(astNode))
  8387. return typeRef;
  8388. BfTypeReference* result = NULL;
  8389. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(astNode))
  8390. {
  8391. auto* typeRef = alloc.Alloc<BfNamedTypeReference>();
  8392. typeRef->mNameNode = identifier;
  8393. result = typeRef;
  8394. }
  8395. else if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(astNode))
  8396. {
  8397. auto qualifiedTypeRef = alloc.Alloc<BfQualifiedTypeReference>();
  8398. qualifiedTypeRef->mLeft = _ConvType(memberRefExpr->mTarget);
  8399. qualifiedTypeRef->mDot = memberRefExpr->mDotToken;
  8400. qualifiedTypeRef->mRight = _ConvType(memberRefExpr->mMemberName);
  8401. if ((qualifiedTypeRef->mLeft == NULL) || (qualifiedTypeRef->mRight == NULL))
  8402. return NULL;
  8403. result = qualifiedTypeRef;
  8404. }
  8405. if (result == NULL)
  8406. return NULL;
  8407. result->SetSrcStart(astNode->GetSrcStart());
  8408. result->SetSrcEnd(astNode->GetSrcEnd());
  8409. return result;
  8410. };
  8411. auto typeRef = _ConvType(astNode);
  8412. if (typeRef == NULL)
  8413. return NULL;
  8414. if ((genericArgs != NULL) && (genericArgs->size() != 0))
  8415. {
  8416. auto genericInstanceTypeRef = alloc.Alloc<BfGenericInstanceTypeRef>();
  8417. genericInstanceTypeRef->SetSrcStart(typeRef->GetSrcStart());
  8418. genericInstanceTypeRef->mElementType = typeRef;
  8419. #ifdef BF_AST_HAS_PARENT_MEMBER
  8420. typeRef->mParent = genericInstanceTypeRef;
  8421. #endif
  8422. BfDeferredAstSizedArray<BfTypeReference*> arguments(genericInstanceTypeRef->mGenericArguments, &alloc);
  8423. for (auto genericArg : *genericArgs)
  8424. {
  8425. if (genericArg != NULL)
  8426. {
  8427. arguments.push_back(genericArg);
  8428. genericInstanceTypeRef->SetSrcEnd(genericArg->GetSrcEnd());
  8429. }
  8430. }
  8431. typeRef = genericInstanceTypeRef;
  8432. }
  8433. return ResolveTypeRef(typeRef, populateType, resolveFlags);
  8434. }
  8435. // This flow should mirror CastToValue
  8436. bool BfModule::CanCast(BfTypedValue typedVal, BfType* toType, BfCastFlags castFlags)
  8437. {
  8438. BP_ZONE("BfModule::CanCast");
  8439. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  8440. return CastToValue(NULL, typedVal, toType, (BfCastFlags)(castFlags | BfCastFlags_SilentFail | BfCastFlags_IsCastCheck));
  8441. }
  8442. bool BfModule::AreSplatsCompatible(BfType* fromType, BfType* toType, bool* outNeedsMemberCasting)
  8443. {
  8444. if ((fromType->IsTypeInstance()) && (!fromType->IsSplattable()))
  8445. return false;
  8446. if ((toType->IsTypeInstance()) && (!toType->IsSplattable()))
  8447. return false;
  8448. auto _GetTypes = [&](BfType* type, Array<BfType*>& types)
  8449. {
  8450. BfTypeUtils::SplatIterate([&](BfType* memberType) { types.Add(memberType); }, type);
  8451. };
  8452. Array<BfType*> fromTypes;
  8453. _GetTypes(fromType, fromTypes);
  8454. Array<BfType*> toTypes;
  8455. _GetTypes(toType, toTypes);
  8456. if (toTypes.size() > fromTypes.size())
  8457. return false;
  8458. for (int i = 0; i < toTypes.size(); i++)
  8459. {
  8460. BfType* fromMemberType = fromTypes[i];
  8461. BfType* toMemberType = toTypes[i];
  8462. if (fromMemberType != toMemberType)
  8463. {
  8464. if ((outNeedsMemberCasting != NULL) &&
  8465. (fromMemberType->IsIntPtrable()) && (toMemberType->IsIntPtrable()))
  8466. *outNeedsMemberCasting = true;
  8467. else
  8468. return false;
  8469. }
  8470. }
  8471. return true;
  8472. }
  8473. BfIRValue BfModule::CastToFunction(BfAstNode* srcNode, const BfTypedValue& targetValue, BfMethodInstance* methodInstance, BfType* toType, BfCastFlags castFlags)
  8474. {
  8475. auto invokeMethodInstance = GetDelegateInvokeMethod(toType->ToTypeInstance());
  8476. if (invokeMethodInstance->IsExactMatch(methodInstance, false, true))
  8477. {
  8478. if (methodInstance->GetOwner()->IsFunction())
  8479. {
  8480. BF_ASSERT(targetValue);
  8481. return targetValue.mValue;
  8482. }
  8483. BfModuleMethodInstance methodRefMethod;
  8484. if (methodInstance->mDeclModule == this)
  8485. methodRefMethod = methodInstance;
  8486. else
  8487. methodRefMethod = ReferenceExternalMethodInstance(methodInstance);
  8488. auto dataType = GetPrimitiveType(BfTypeCode_IntPtr);
  8489. if (!methodRefMethod.mFunc)
  8490. {
  8491. if (HasCompiledOutput())
  8492. AssertErrorState();
  8493. return GetDefaultValue(dataType);
  8494. }
  8495. auto bindFuncVal = methodRefMethod.mFunc;
  8496. if (mCompiler->mOptions.mAllowHotSwapping)
  8497. bindFuncVal = mBfIRBuilder->RemapBindFunction(bindFuncVal);
  8498. return mBfIRBuilder->CreatePtrToInt(bindFuncVal, BfTypeCode_IntPtr);
  8499. }
  8500. if ((castFlags & BfCastFlags_SilentFail) == 0)
  8501. {
  8502. if (invokeMethodInstance->IsExactMatch(methodInstance, true, true))
  8503. {
  8504. 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);
  8505. }
  8506. else if (invokeMethodInstance->IsExactMatch(methodInstance, false, false))
  8507. {
  8508. bool handled = false;
  8509. if (methodInstance->HasThis())
  8510. {
  8511. auto thisType = methodInstance->GetThisType();
  8512. if (invokeMethodInstance->HasExplicitThis())
  8513. {
  8514. auto invokeThisType = invokeMethodInstance->GetThisType();
  8515. bool thisWasPtr = false;
  8516. if (thisType->IsPointer())
  8517. {
  8518. thisType = thisType->GetUnderlyingType();
  8519. thisWasPtr = true;
  8520. }
  8521. bool invokeThisWasPtr = false;
  8522. if (invokeThisType->IsPointer())
  8523. {
  8524. invokeThisType = invokeThisType->GetUnderlyingType();
  8525. invokeThisWasPtr = true;
  8526. }
  8527. if (invokeThisType == thisType)
  8528. {
  8529. if (invokeThisWasPtr != thisWasPtr)
  8530. {
  8531. if (invokeThisWasPtr)
  8532. Fail(StrFormat("Non-static method '%s' cannot match '%s', consider removing 'mut' from 'mut %s this' in the function parameters", MethodToString(methodInstance).c_str(), TypeToString(toType).c_str(), TypeToString(thisType).c_str()), srcNode);
  8533. else
  8534. Fail(StrFormat("Non-static method '%s' cannot match '%s', consider adding 'mut' specifier to '%s this' in the function parameters", MethodToString(methodInstance).c_str(), TypeToString(toType).c_str(), TypeToString(thisType).c_str()), srcNode);
  8535. handled = true;
  8536. }
  8537. }
  8538. }
  8539. }
  8540. if ((!methodInstance->mMethodDef->mIsStatic) && (!invokeMethodInstance->HasExplicitThis()))
  8541. {
  8542. handled = true;
  8543. auto thisType = methodInstance->GetParamType(-1);
  8544. 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(thisType).c_str()), srcNode);
  8545. }
  8546. if (!handled)
  8547. {
  8548. if (invokeMethodInstance->mMethodDef->mIsStatic)
  8549. Fail(StrFormat("Static method '%s' cannot match '%s'", MethodToString(methodInstance).c_str(), TypeToString(toType).c_str()).c_str(), srcNode);
  8550. else
  8551. Fail(StrFormat("Non-static method '%s' cannot match '%s'", MethodToString(methodInstance).c_str(), TypeToString(toType).c_str()).c_str(), srcNode);
  8552. }
  8553. }
  8554. }
  8555. return BfIRValue();
  8556. }
  8557. BfIRValue BfModule::CastToValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, BfCastFlags castFlags, BfCastResultFlags* resultFlags)
  8558. {
  8559. bool silentFail = ((castFlags & BfCastFlags_SilentFail) != 0);
  8560. bool explicitCast = (castFlags & BfCastFlags_Explicit) != 0;
  8561. bool ignoreErrors = mIgnoreErrors || ((castFlags & BfCastFlags_SilentFail) != 0);
  8562. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  8563. if (typedVal.mType == toType)
  8564. {
  8565. if (resultFlags != NULL)
  8566. {
  8567. if (typedVal.IsAddr())
  8568. *resultFlags = (BfCastResultFlags)(*resultFlags | BfCastResultFlags_IsAddr);
  8569. if (typedVal.mKind == BfTypedValueKind_TempAddr)
  8570. *resultFlags = (BfCastResultFlags)(*resultFlags | BfCastResultFlags_IsTemp);
  8571. }
  8572. else if (typedVal.IsAddr())
  8573. typedVal = LoadValue(typedVal);
  8574. return typedVal.mValue;
  8575. }
  8576. BF_ASSERT(typedVal.mType->mContext == mContext);
  8577. BF_ASSERT(toType->mContext == mContext);
  8578. if ((typedVal.IsAddr()) && (!typedVal.mType->IsValueType()))
  8579. typedVal = LoadValue(typedVal);
  8580. //BF_ASSERT(!typedVal.IsAddr() || typedVal.mType->IsGenericParam() || typedVal.mType->IsValueType());
  8581. // Ref X to Ref Y, X* to Y*
  8582. {
  8583. bool checkUnderlying = false;
  8584. if (((typedVal.mType->IsRef()) && (toType->IsRef())))
  8585. {
  8586. auto fromRefType = (BfRefType*)typedVal.mType;
  8587. auto toRefType = (BfRefType*)toType;
  8588. if (fromRefType->mRefKind == toRefType->mRefKind)
  8589. checkUnderlying = true;
  8590. else if ((fromRefType->mRefKind == BfRefType::RefKind_Ref) && (toRefType->mRefKind == BfRefType::RefKind_Mut))
  8591. checkUnderlying = true; // Allow a ref-to-mut implicit conversion
  8592. }
  8593. if ((typedVal.mType->IsPointer()) && (toType->IsPointer()))
  8594. checkUnderlying = true;
  8595. if (checkUnderlying)
  8596. {
  8597. auto fromInner = typedVal.mType->GetUnderlyingType();
  8598. auto toInner = toType->GetUnderlyingType();
  8599. if (fromInner == toInner)
  8600. {
  8601. return typedVal.mValue;
  8602. }
  8603. if ((fromInner->IsTuple()) && (toInner->IsTuple()))
  8604. {
  8605. auto fromTuple = (BfTupleType*)fromInner;
  8606. auto toTuple = (BfTupleType*)toInner;
  8607. if (fromTuple->mFieldInstances.size() == toTuple->mFieldInstances.size())
  8608. {
  8609. bool matches = true;
  8610. for (int fieldIdx = 0; fieldIdx < (int)fromTuple->mFieldInstances.size(); fieldIdx++)
  8611. {
  8612. if (fromTuple->mFieldInstances[fieldIdx].mResolvedType != toTuple->mFieldInstances[fieldIdx].mResolvedType)
  8613. {
  8614. matches = false;
  8615. break;
  8616. }
  8617. }
  8618. if (matches)
  8619. {
  8620. // This is either a ref or a ptr so we don't need to set the "IsAddr" flag
  8621. typedVal = MakeAddressable(typedVal);
  8622. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  8623. }
  8624. }
  8625. }
  8626. // ref int <-> ref int64/int32 (of same size)
  8627. if (((fromInner->IsInteger()) && (toInner->IsInteger())) &&
  8628. (fromInner->mSize == toInner->mSize) &&
  8629. (fromInner->IsSigned() == toInner->IsSigned()))
  8630. return typedVal.mValue;
  8631. }
  8632. }
  8633. // Null -> ObjectInst|IFace|ptr
  8634. if ((typedVal.mType->IsNull()) &&
  8635. ((toType->IsObjectOrInterface()) || (toType->IsPointer() || (toType->IsFunction()))))
  8636. {
  8637. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  8638. }
  8639. // Func -> void*
  8640. if ((typedVal.mType->IsFunction()) && (toType->IsVoidPtr()))
  8641. {
  8642. return mBfIRBuilder->CreateIntToPtr(typedVal.mValue, mBfIRBuilder->MapType(toType));
  8643. }
  8644. if (explicitCast)
  8645. {
  8646. // void* -> Func
  8647. if ((typedVal.mType->IsVoidPtr()) && (toType->IsFunction()))
  8648. {
  8649. return mBfIRBuilder->CreatePtrToInt(typedVal.mValue, BfTypeCode_IntPtr);
  8650. }
  8651. // * -> Valueless
  8652. if (toType->IsVoid())
  8653. return mBfIRBuilder->GetFakeVal();
  8654. // void* -> intptr
  8655. if ((typedVal.mType->IsPointer()) && (toType->IsIntPtr()))
  8656. {
  8657. if ((!typedVal.mType->GetUnderlyingType()->IsVoid()) && ((castFlags & BfCastFlags_FromCompiler) == 0))
  8658. {
  8659. if (!ignoreErrors)
  8660. Fail(StrFormat("Unable to cast directly from '%s' to '%s', consider casting to void* first", TypeToString(typedVal.mType).c_str(), TypeToString(toType).c_str()), srcNode);
  8661. else if (!silentFail)
  8662. SetFail();
  8663. }
  8664. auto toPrimitive = (BfPrimitiveType*)toType;
  8665. return mBfIRBuilder->CreatePtrToInt(typedVal.mValue, toPrimitive->mTypeDef->mTypeCode);
  8666. }
  8667. // intptr -> void*
  8668. if ((typedVal.mType->IsIntPtr()) && (toType->IsPointer()))
  8669. {
  8670. if ((!toType->GetUnderlyingType()->IsVoid()) && ((castFlags & BfCastFlags_FromCompiler) == 0))
  8671. {
  8672. if (!ignoreErrors)
  8673. Fail(StrFormat("Unable to cast directly from '%s' to '%s', consider casting to void* first", TypeToString(typedVal.mType).c_str(), TypeToString(toType).c_str()), srcNode);
  8674. else if (!silentFail)
  8675. SetFail();
  8676. }
  8677. return mBfIRBuilder->CreateIntToPtr(typedVal.mValue, mBfIRBuilder->MapType(toType));
  8678. }
  8679. }
  8680. // * <-> Var
  8681. if ((typedVal.mType->IsVar()) || (toType->IsVar()))
  8682. {
  8683. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(toType));
  8684. }
  8685. // Generic param -> *
  8686. if ((typedVal.mType->IsGenericParam()) && (!toType->IsGenericParam()))
  8687. {
  8688. if (toType == mContext->mBfObjectType)
  8689. {
  8690. // Always allow casting from generic to object
  8691. return typedVal.mValue;
  8692. }
  8693. auto _CheckGenericParamInstance = [&](BfGenericParamInstance* genericParamInst)
  8694. {
  8695. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  8696. {
  8697. return typedVal.mValue;
  8698. }
  8699. if (toType->IsInterface())
  8700. {
  8701. for (auto iface : genericParamInst->mInterfaceConstraints)
  8702. if (TypeIsSubTypeOf(iface, toType->ToTypeInstance()))
  8703. return mBfIRBuilder->GetFakeVal();
  8704. }
  8705. if (genericParamInst->mTypeConstraint != NULL)
  8706. {
  8707. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  8708. auto constraintTypeInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  8709. if ((constraintTypeInst != NULL) && (constraintTypeInst->mTypeDef == mCompiler->mEnumTypeDef))
  8710. {
  8711. // Enum->int
  8712. if ((explicitCast) && (toType->IsInteger()))
  8713. return typedVal.mValue;
  8714. }
  8715. BfTypedValue fromTypedValue;
  8716. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  8717. fromTypedValue = GetDefaultTypedValue(genericParamInst->mTypeConstraint);
  8718. else
  8719. fromTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), genericParamInst->mTypeConstraint, genericParamInst->mTypeConstraint->IsValueType());
  8720. auto result = CastToValue(srcNode, fromTypedValue, toType, (BfCastFlags)(castFlags | BfCastFlags_SilentFail));
  8721. if (result)
  8722. {
  8723. if ((genericParamInst->mTypeConstraint->IsDelegate()) && (toType->IsDelegate()))
  8724. {
  8725. // Don't allow cast when we are constrained by a delegate type, because BfMethodRefs can match and we require an actual alloc
  8726. 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);
  8727. return BfIRValue();
  8728. }
  8729. return result;
  8730. }
  8731. }
  8732. // Generic constrained with class or pointer type -> void*
  8733. if (toType->IsVoidPtr())
  8734. {
  8735. if (((genericParamInst->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Interface)) != 0) ||
  8736. ((genericParamInst->mTypeConstraint != NULL) &&
  8737. ((genericParamInst->mTypeConstraint->IsPointer()) ||
  8738. (genericParamInst->mTypeConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)) ||
  8739. (genericParamInst->mTypeConstraint->IsObjectOrInterface()))))
  8740. {
  8741. return typedVal.mValue;
  8742. }
  8743. }
  8744. if (toType->IsInteger())
  8745. {
  8746. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum) != 0)
  8747. {
  8748. return typedVal.mValue;
  8749. }
  8750. }
  8751. return BfIRValue();
  8752. };
  8753. BfIRValue retVal;
  8754. // For these casts, it's just important we get *A* value to work with here,
  8755. // as this is just use for unspecialized parsing. We don't use the generated code
  8756. {
  8757. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  8758. retVal = _CheckGenericParamInstance(genericParamInst);
  8759. if (retVal)
  8760. return retVal;
  8761. }
  8762. // Check method generic constraints
  8763. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mMethodInfoEx != NULL))
  8764. {
  8765. for (int genericParamIdx = (int)mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  8766. genericParamIdx < mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  8767. {
  8768. auto genericParamInst = mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  8769. if (genericParamInst->mExternType == typedVal.mType)
  8770. {
  8771. retVal = _CheckGenericParamInstance(genericParamInst);
  8772. if (retVal)
  8773. return retVal;
  8774. }
  8775. }
  8776. }
  8777. }
  8778. // * -> Generic param
  8779. if (toType->IsGenericParam())
  8780. {
  8781. if (explicitCast)
  8782. {
  8783. // Either an upcast or an unbox
  8784. if ((typedVal.mType == mContext->mBfObjectType) || (typedVal.mType->IsInterface()))
  8785. {
  8786. return GetDefaultValue(toType);
  8787. }
  8788. }
  8789. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)toType);
  8790. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var)
  8791. return GetDefaultValue(toType);
  8792. if (typedVal.mType->IsNull())
  8793. {
  8794. bool allowCast = (genericParamInst->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Interface)) != 0;
  8795. if ((!allowCast) && (genericParamInst->mTypeConstraint != NULL))
  8796. allowCast = genericParamInst->mTypeConstraint->IsObject() || genericParamInst->mTypeConstraint->IsPointer();
  8797. if (allowCast)
  8798. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  8799. }
  8800. if (genericParamInst->mTypeConstraint != NULL)
  8801. {
  8802. if (genericParamInst->mTypeConstraint->IsInstanceOf(mCompiler->mEnumTypeDef))
  8803. {
  8804. // int->Enum
  8805. if ((explicitCast) && (typedVal.mType->IsInteger()))
  8806. return mBfIRBuilder->GetFakeVal();
  8807. }
  8808. auto castedVal = CastToValue(srcNode, typedVal, genericParamInst->mTypeConstraint, (BfCastFlags)(castFlags | BfCastFlags_SilentFail));
  8809. if (castedVal)
  8810. return castedVal;
  8811. }
  8812. if (explicitCast)
  8813. {
  8814. if (((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) != 0) ||
  8815. ((genericParamInst->mTypeConstraint != NULL) && genericParamInst->mTypeConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))
  8816. {
  8817. auto voidPtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_None));
  8818. auto castedVal = CastToValue(srcNode, typedVal, voidPtrType, (BfCastFlags)(castFlags | BfCastFlags_SilentFail));
  8819. if (castedVal)
  8820. return castedVal;
  8821. }
  8822. }
  8823. if ((typedVal.mType->IsIntegral()) && ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum) != 0))
  8824. {
  8825. bool allowCast = explicitCast;
  8826. if ((!allowCast) && (typedVal.mType->IsIntegral()))
  8827. {
  8828. // Allow implicit cast of zero
  8829. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  8830. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  8831. {
  8832. allowCast = constant->mInt64 == 0;
  8833. }
  8834. }
  8835. if (allowCast)
  8836. {
  8837. return mBfIRBuilder->GetFakeVal();
  8838. }
  8839. }
  8840. }
  8841. if ((typedVal.mType->IsTypeInstance()) && (toType->IsTypeInstance()))
  8842. {
  8843. auto fromTypeInstance = typedVal.mType->ToTypeInstance();
  8844. auto toTypeInstance = toType->ToTypeInstance();
  8845. if ((typedVal.mType->IsValueType()) && (toType->IsValueType()))
  8846. {
  8847. bool allowCast = false;
  8848. if (TypeIsSubTypeOf(fromTypeInstance, toTypeInstance))
  8849. allowCast = true;
  8850. if (allowCast)
  8851. {
  8852. PopulateType(toType);
  8853. if (toType->IsValuelessType())
  8854. return BfIRValue::sValueless;
  8855. if (ignoreWrites)
  8856. return mBfIRBuilder->GetFakeVal();
  8857. if (resultFlags != NULL)
  8858. *resultFlags = (BfCastResultFlags)(BfCastResultFlags_IsAddr);
  8859. typedVal = MakeAddressable(typedVal);
  8860. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapTypeInstPtr(toTypeInstance));
  8861. }
  8862. }
  8863. // ObjectInst|IFace -> object|IFace
  8864. if ((typedVal.mType->IsObject() || (typedVal.mType->IsInterface())) && ((toType->IsObject() || (toType->IsInterface()))))
  8865. {
  8866. bool allowCast = false;
  8867. if (TypeIsSubTypeOf(fromTypeInstance, toTypeInstance))
  8868. allowCast = true;
  8869. else if ((explicitCast) &&
  8870. ((toType->IsInterface()) || (TypeIsSubTypeOf(toTypeInstance, fromTypeInstance))))
  8871. {
  8872. if (toType->IsObjectOrInterface())
  8873. {
  8874. if ((castFlags & BfCastFlags_Unchecked) == 0)
  8875. EmitDynamicCastCheck(typedVal, toType, true);
  8876. }
  8877. allowCast = true;
  8878. }
  8879. if (allowCast)
  8880. {
  8881. if (ignoreWrites)
  8882. return mBfIRBuilder->GetFakeVal();
  8883. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  8884. }
  8885. }
  8886. }
  8887. // MethodRef -> Function
  8888. if ((typedVal.mType->IsMethodRef()) && (toType->IsFunction()))
  8889. {
  8890. BfMethodInstance* methodInstance = ((BfMethodRefType*)typedVal.mType)->mMethodRef;
  8891. auto result = CastToFunction(srcNode, BfTypedValue(), methodInstance, toType, castFlags);
  8892. if (result)
  8893. return result;
  8894. }
  8895. // concrete IFace -> object|IFace
  8896. if ((typedVal.mType->IsConcreteInterfaceType()) && ((toType->IsObject() || (toType->IsInterface()))))
  8897. {
  8898. auto concreteInterfaceType = (BfConcreteInterfaceType*)typedVal.mType;
  8899. if ((toType->IsObject()) || (concreteInterfaceType->mInterface == toType))
  8900. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  8901. }
  8902. // IFace -> object
  8903. if ((typedVal.mType->IsInterface()) && (toType == mContext->mBfObjectType))
  8904. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  8905. // * -> Pointer
  8906. if (toType->IsPointer())
  8907. {
  8908. // Ptr -> Ptr
  8909. if (typedVal.mType->IsPointer())
  8910. {
  8911. bool allowCast = explicitCast;
  8912. auto fromPointerType = (BfPointerType*)typedVal.mType;
  8913. auto toPointerType = (BfPointerType*)toType;
  8914. auto fromUnderlying = fromPointerType->mElementType;
  8915. auto toUnderlying = toPointerType->mElementType;
  8916. // Allow cast from T[size]* to T* implicitly
  8917. // And from T* to T[size]* explicitly
  8918. while (fromUnderlying->IsSizedArray())
  8919. fromUnderlying = fromUnderlying->GetUnderlyingType();
  8920. while ((toUnderlying->IsSizedArray()) && (explicitCast))
  8921. toUnderlying = toUnderlying->GetUnderlyingType();
  8922. if ((fromUnderlying == toUnderlying) ||
  8923. (TypeIsSubTypeOf(fromUnderlying->ToTypeInstance(), toUnderlying->ToTypeInstance())) ||
  8924. (toUnderlying->IsVoid()))
  8925. allowCast = true;
  8926. if (allowCast)
  8927. {
  8928. if (ignoreWrites)
  8929. return mBfIRBuilder->GetFakeVal();
  8930. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  8931. }
  8932. }
  8933. else if (typedVal.mType->IsObject())
  8934. {
  8935. // ???
  8936. }
  8937. /*else if (typedVal.mType->IsSizedArray())
  8938. {
  8939. if (typedVal.IsAddr())
  8940. {
  8941. BfSizedArrayType* arrayType = (BfSizedArrayType*)typedVal.mType;
  8942. auto ptrType = CreatePointerType(arrayType->mElementType);
  8943. BfTypedValue returnPointer(mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(ptrType)), ptrType);
  8944. return CastToValue(srcNode, returnPointer, toType, castFlags, silentFail);
  8945. }
  8946. }*/
  8947. }
  8948. // Boxing?
  8949. bool mayBeBox = false;
  8950. if (((typedVal.mType->IsValueType()) || (typedVal.mType->IsPointer()) || (typedVal.mType->IsValuelessType())) &&
  8951. ((toType->IsInterface()) || (toType == mContext->mBfObjectType)))
  8952. {
  8953. // Make sure there's no conversion operator before we box
  8954. if ((!typedVal.mType->IsRef()) && (!typedVal.mType->IsModifiedTypeType()))
  8955. mayBeBox = true;
  8956. }
  8957. //TODO: the IsGenericParam is not valid - why did we have that? The generic param could be a struct for example...
  8958. if ((explicitCast) && ((typedVal.mType->IsInterface()) || (typedVal.mType == mContext->mBfObjectType) /*|| (typedVal.mType->IsGenericParam())*/) &&
  8959. ((toType->IsValueType()) || (toType->IsPointer())))
  8960. {
  8961. if (toType->IsValuelessType())
  8962. return BfIRValue::sValueless;
  8963. if (ignoreWrites)
  8964. return mBfIRBuilder->GetFakeVal();
  8965. // Unbox!
  8966. if ((castFlags & BfCastFlags_Unchecked) == 0)
  8967. {
  8968. EmitDynamicCastCheck(typedVal, toType, false);
  8969. EmitObjectAccessCheck(typedVal);
  8970. }
  8971. if (toType->IsNullable())
  8972. {
  8973. auto toTypeInst = toType->ToTypeInstance();
  8974. int valueIdx = toTypeInst->mFieldInstances[0].mDataIdx;
  8975. int hasValueIdx = toTypeInst->mFieldInstances[1].mDataIdx;
  8976. typedVal = MakeAddressable(typedVal);
  8977. auto elementType = toType->GetUnderlyingType();
  8978. auto ptrElementType = CreatePointerType(elementType);
  8979. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  8980. auto allocaInst = CreateAlloca(toType, true, "unboxN");
  8981. auto prevBB = mBfIRBuilder->GetInsertBlock();
  8982. auto nullBB = mBfIRBuilder->CreateBlock("unboxN.null");
  8983. auto notNullBB = mBfIRBuilder->CreateBlock("unboxN.notNull");
  8984. auto endBB = mBfIRBuilder->CreateBlock("unboxN.end");
  8985. auto isNull = mBfIRBuilder->CreateIsNull(typedVal.mValue);
  8986. mBfIRBuilder->CreateCondBr(isNull, nullBB, notNullBB);
  8987. int dataIdx = toTypeInst->mFieldInstances[1].mDataIdx;
  8988. mBfIRBuilder->AddBlock(nullBB);
  8989. mBfIRBuilder->SetInsertPoint(nullBB);
  8990. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, hasValueIdx); // has_value
  8991. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), hasValueAddr);
  8992. auto nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, valueIdx); // value
  8993. auto nullableValueBits = mBfIRBuilder->CreateBitCast(nullableValueAddr, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  8994. mBfIRBuilder->CreateMemSet(nullableValueBits, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)), GetConstValue(elementType->mSize), elementType->mAlign);
  8995. mBfIRBuilder->CreateBr(endBB);
  8996. mBfIRBuilder->AddBlock(notNullBB);
  8997. mBfIRBuilder->SetInsertPoint(notNullBB);
  8998. hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, hasValueIdx); // has_value
  8999. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), hasValueAddr);
  9000. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, valueIdx); // value
  9001. auto srcObjBits = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(ptrElementType));
  9002. auto boxedValueAddr = mBfIRBuilder->CreateInBoundsGEP(srcObjBits, 1); // Skip over vdata
  9003. auto boxedValue = mBfIRBuilder->CreateLoad(boxedValueAddr);
  9004. mBfIRBuilder->CreateStore(boxedValue, nullableValueAddr);
  9005. mBfIRBuilder->CreateBr(endBB);
  9006. mBfIRBuilder->AddBlock(endBB);
  9007. mBfIRBuilder->SetInsertPoint(endBB);
  9008. if (resultFlags != NULL)
  9009. *resultFlags = (BfCastResultFlags)(BfCastResultFlags_IsAddr | BfCastResultFlags_IsTemp);
  9010. return allocaInst;
  9011. }
  9012. auto boxedType = CreateBoxedType(toType);
  9013. mBfIRBuilder->PopulateType(boxedType);
  9014. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9015. auto boxedObj = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(boxedType));
  9016. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(boxedObj, 0, 1);
  9017. if ((toType->IsPrimitiveType()) || (toType->IsTypedPrimitive()) || (toType->IsPointer()) || (toType->IsSizedArray()) || (toType->IsMethodRef()))
  9018. {
  9019. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(toType)));
  9020. }
  9021. if ((toType->IsComposite()) && (resultFlags != NULL))
  9022. {
  9023. *resultFlags = BfCastResultFlags_IsAddr;
  9024. return valPtr;
  9025. }
  9026. else
  9027. return mBfIRBuilder->CreateLoad(valPtr, false);
  9028. }
  9029. // Null -> Nullable<T>
  9030. if ((typedVal.mType->IsNull()) && (toType->IsNullable()))
  9031. {
  9032. if (ignoreWrites)
  9033. return mBfIRBuilder->GetFakeVal();
  9034. if ((castFlags & BfCastFlags_PreferAddr) != 0)
  9035. {
  9036. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  9037. auto toTypeInst = toType->ToTypeInstance();
  9038. int hasValueIdx = toTypeInst->mFieldInstances[1].mDataIdx;
  9039. auto allocaInst = CreateAlloca(toType);
  9040. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, hasValueIdx); // has_value
  9041. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), hasValueAddr);
  9042. auto typedValue = BfTypedValue(allocaInst, toType, true);
  9043. if (resultFlags != NULL)
  9044. *resultFlags = (BfCastResultFlags)(BfCastResultFlags_IsAddr | BfCastResultFlags_IsTemp);
  9045. return allocaInst;
  9046. }
  9047. auto zeroNullable = mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(toType));
  9048. return zeroNullable;
  9049. }
  9050. // Nullable<A> -> Nullable<B>
  9051. if ((typedVal.mType->IsNullable()) && (toType->IsNullable()))
  9052. {
  9053. auto fromNullableType = (BfTypeInstance*)typedVal.mType;
  9054. auto toNullableType = (BfTypeInstance*)toType;
  9055. if (ignoreWrites)
  9056. {
  9057. auto toVal = CastToValue(srcNode, BfTypedValue(mBfIRBuilder->GetFakeVal(), fromNullableType->mGenericTypeInfo->mTypeGenericArguments[0]),
  9058. toNullableType->mGenericTypeInfo->mTypeGenericArguments[0], ignoreErrors ? BfCastFlags_SilentFail : BfCastFlags_None);
  9059. if (!toVal)
  9060. return BfIRValue();
  9061. return mBfIRBuilder->GetFakeVal();
  9062. }
  9063. BfIRValue srcPtr = typedVal.mValue;
  9064. if (!typedVal.IsAddr())
  9065. {
  9066. auto srcAlloca = CreateAllocaInst(fromNullableType);
  9067. mBfIRBuilder->CreateStore(typedVal.mValue, srcAlloca);
  9068. srcPtr = srcAlloca;
  9069. }
  9070. auto srcAddr = mBfIRBuilder->CreateInBoundsGEP(srcPtr, 0, 1); // mValue
  9071. auto srcVal = mBfIRBuilder->CreateLoad(srcAddr);
  9072. auto toVal = CastToValue(srcNode, BfTypedValue(srcVal, fromNullableType->mGenericTypeInfo->mTypeGenericArguments[0]),
  9073. toNullableType->mGenericTypeInfo->mTypeGenericArguments[0], ignoreErrors ? BfCastFlags_SilentFail : BfCastFlags_None);
  9074. if (!toVal)
  9075. return BfIRValue();
  9076. auto allocaInst = CreateAllocaInst(toNullableType);
  9077. auto destAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // mValue
  9078. mBfIRBuilder->CreateStore(toVal, destAddr);
  9079. srcAddr = mBfIRBuilder->CreateInBoundsGEP(srcPtr, 0, 2); // mHasValue
  9080. srcVal = mBfIRBuilder->CreateLoad(srcAddr);
  9081. destAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 2); // mHasValue
  9082. mBfIRBuilder->CreateStore(srcVal, destAddr);
  9083. if (resultFlags != NULL)
  9084. *resultFlags = (BfCastResultFlags)(BfCastResultFlags_IsAddr | BfCastResultFlags_IsTemp);
  9085. return allocaInst;
  9086. }
  9087. // Tuple -> Tuple
  9088. if ((typedVal.mType->IsTuple()) && (toType->IsTuple()))
  9089. {
  9090. auto fromTupleType = (BfTypeInstance*)typedVal.mType;
  9091. auto toTupleType = (BfTypeInstance*)toType;
  9092. PopulateType(fromTupleType);
  9093. PopulateType(toTupleType);
  9094. if (fromTupleType->mFieldInstances.size() == toTupleType->mFieldInstances.size())
  9095. {
  9096. typedVal = LoadValue(typedVal);
  9097. BfIRValue curTupleValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(toTupleType));
  9098. for (int valueIdx = 0; valueIdx < (int)fromTupleType->mFieldInstances.size(); valueIdx++)
  9099. {
  9100. BfFieldInstance* fromFieldInstance = &fromTupleType->mFieldInstances[valueIdx];
  9101. BfFieldInstance* toFieldInstance = &toTupleType->mFieldInstances[valueIdx];
  9102. if (!explicitCast)
  9103. {
  9104. BfFieldDef* fromFieldDef = fromFieldInstance->GetFieldDef();
  9105. BfFieldDef* toFieldDef = toFieldInstance->GetFieldDef();
  9106. // Either the names have to match or one has to be unnamed
  9107. if ((!fromFieldDef->IsUnnamedTupleField()) && (!toFieldDef->IsUnnamedTupleField()) &&
  9108. (fromFieldDef->mName != toFieldDef->mName))
  9109. {
  9110. curTupleValue = BfIRValue();
  9111. break;
  9112. }
  9113. }
  9114. auto fromFieldType = fromFieldInstance->GetResolvedType();
  9115. auto toFieldType = toFieldInstance->GetResolvedType();
  9116. if (toFieldType->IsVoid())
  9117. continue; // Allow sinking to void
  9118. BfIRValue fromFieldValue;
  9119. if (fromFieldInstance->mDataIdx >= 0)
  9120. fromFieldValue = mBfIRBuilder->CreateExtractValue(typedVal.mValue, fromFieldInstance->mDataIdx);
  9121. BfIRValue toFieldValue = CastToValue(srcNode, BfTypedValue(fromFieldValue, fromFieldType), toFieldType, (BfCastFlags)(castFlags | BfCastFlags_Explicit));
  9122. if (!toFieldValue)
  9123. {
  9124. curTupleValue = BfIRValue();
  9125. break;
  9126. }
  9127. if (toFieldInstance->mDataIdx >= 0)
  9128. curTupleValue = mBfIRBuilder->CreateInsertValue(curTupleValue, toFieldValue, toFieldInstance->mDataIdx);
  9129. }
  9130. if (curTupleValue)
  9131. return curTupleValue;
  9132. }
  9133. }
  9134. // -> const <value>
  9135. if (toType->IsConstExprValue())
  9136. {
  9137. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  9138. if (constant != NULL)
  9139. {
  9140. BfConstExprValueType* toConstExprValueType = (BfConstExprValueType*)toType;
  9141. auto variantVal = TypedValueToVariant(srcNode, typedVal);
  9142. if ((mBfIRBuilder->IsInt(variantVal.mTypeCode)) && (mBfIRBuilder->IsInt(toConstExprValueType->mValue.mTypeCode)))
  9143. {
  9144. if (variantVal.mInt64 == toConstExprValueType->mValue.mInt64)
  9145. return typedVal.mValue;
  9146. }
  9147. else if ((mBfIRBuilder->IsFloat(variantVal.mTypeCode)) && (mBfIRBuilder->IsFloat(toConstExprValueType->mValue.mTypeCode)))
  9148. {
  9149. if (variantVal.ToDouble() == toConstExprValueType->mValue.ToDouble())
  9150. return typedVal.mValue;
  9151. }
  9152. if (!ignoreErrors)
  9153. {
  9154. String valStr;
  9155. VariantToString(valStr, variantVal);
  9156. Fail(StrFormat("Unable to cast '%s %s' to '%s'", TypeToString(typedVal.mType).c_str(), valStr.c_str(), TypeToString(toType).c_str()), srcNode);
  9157. }
  9158. else if (!silentFail)
  9159. SetFail();
  9160. }
  9161. }
  9162. if ((typedVal.mType->IsPrimitiveType()) && (toType->IsPrimitiveType()))
  9163. {
  9164. auto fromPrimType = (BfPrimitiveType*)typedVal.mType;
  9165. auto toPrimType = (BfPrimitiveType*)toType;
  9166. BfTypeCode fromTypeCode = fromPrimType->mTypeDef->mTypeCode;
  9167. BfTypeCode toTypeCode = toPrimType->mTypeDef->mTypeCode;
  9168. if (toType->IsIntegral())
  9169. {
  9170. // Allow constant ints to be implicitly casted to a smaller type if they fit
  9171. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  9172. if (constant != NULL)
  9173. {
  9174. if (mBfIRBuilder->IsInt(constant->mTypeCode))
  9175. {
  9176. int64 srcVal = constant->mInt64;
  9177. if (toPrimType->IsChar())
  9178. {
  9179. if (srcVal == 0)
  9180. explicitCast = true;
  9181. }
  9182. else if ((fromPrimType->IsChar()) && (!toPrimType->IsChar()))
  9183. {
  9184. // Never allow this
  9185. }
  9186. else if ((constant->mTypeCode == BfTypeCode_UInt64) && (srcVal < 0))
  9187. {
  9188. // There's nothing that this could fit into
  9189. }
  9190. else if (toType->IsSigned())
  9191. {
  9192. if (toType->mSize == 8) // int64
  9193. explicitCast = true;
  9194. else
  9195. {
  9196. int64 minVal = -(1LL << (8 * toType->mSize - 1));
  9197. int64 maxVal = (1LL << (8 * toType->mSize - 1)) - 1;
  9198. if ((srcVal >= minVal) && (srcVal <= maxVal))
  9199. explicitCast = true;
  9200. }
  9201. }
  9202. else if (toType->mSize == 8) // uint64
  9203. {
  9204. if (srcVal >= 0)
  9205. explicitCast = true;
  9206. }
  9207. else
  9208. {
  9209. int64 minVal = 0;
  9210. int64 maxVal = (1LL << (8 * toType->mSize)) - 1;
  9211. if ((srcVal >= minVal) && (srcVal <= maxVal))
  9212. explicitCast = true;
  9213. }
  9214. }
  9215. else if (constant->mConstType == BfConstType_Undef)
  9216. {
  9217. BF_ASSERT(mBfIRBuilder->mIgnoreWrites);
  9218. auto undefConst = (BfConstantUndef*)constant;
  9219. auto fakeVal = GetFakeTypedValue(GetPrimitiveType(undefConst->mTypeCode));
  9220. // Why did we have this BfCastFlags_Explicit? It broke creating errors on things like "int16 val = TCount;"
  9221. //auto val = CastToValue(srcNode, fakeVal, toType, (BfCastFlags)(castFlags | BfCastFlags_Explicit));
  9222. auto val = CastToValue(srcNode, fakeVal, toType, castFlags);
  9223. if (val)
  9224. return val;
  9225. }
  9226. }
  9227. }
  9228. bool allowCast = false;
  9229. switch (toTypeCode)
  9230. {
  9231. case BfTypeCode_Char16:
  9232. switch (fromTypeCode)
  9233. {
  9234. case BfTypeCode_Char8:
  9235. allowCast = true; break;
  9236. default: break;
  9237. }
  9238. break;
  9239. case BfTypeCode_Int16:
  9240. switch (fromTypeCode)
  9241. {
  9242. case BfTypeCode_Int8:
  9243. allowCast = true; break;
  9244. case BfTypeCode_UInt8:
  9245. allowCast = true; break;
  9246. default: break;
  9247. }
  9248. break;
  9249. case BfTypeCode_UInt16:
  9250. switch (fromTypeCode)
  9251. {
  9252. case BfTypeCode_UInt8:
  9253. allowCast = true; break;
  9254. default: break;
  9255. }
  9256. break;
  9257. case BfTypeCode_Int32:
  9258. switch (fromTypeCode)
  9259. {
  9260. case BfTypeCode_Int8:
  9261. case BfTypeCode_Int16:
  9262. allowCast = true; break;
  9263. case BfTypeCode_IntPtr:
  9264. if (mCompiler->mSystem->mPtrSize == 4)
  9265. allowCast = true;
  9266. break;
  9267. case BfTypeCode_UInt8:
  9268. case BfTypeCode_UInt16:
  9269. allowCast = true; break;
  9270. default: break;
  9271. }
  9272. break;
  9273. case BfTypeCode_Char32:
  9274. switch (fromTypeCode)
  9275. {
  9276. case BfTypeCode_Char8:
  9277. case BfTypeCode_Char16:
  9278. allowCast = true; break;
  9279. default: break;
  9280. }
  9281. break;
  9282. case BfTypeCode_UInt32:
  9283. switch (fromTypeCode)
  9284. {
  9285. case BfTypeCode_UInt8:
  9286. case BfTypeCode_UInt16:
  9287. case BfTypeCode_UInt32:
  9288. allowCast = true; break;
  9289. case BfTypeCode_UIntPtr:
  9290. if (mCompiler->mSystem->mPtrSize == 4)
  9291. allowCast = true;
  9292. break;
  9293. default: break;
  9294. }
  9295. break;
  9296. case BfTypeCode_Int64:
  9297. switch (fromTypeCode)
  9298. {
  9299. case BfTypeCode_Int8:
  9300. case BfTypeCode_Int16:
  9301. case BfTypeCode_Int32:
  9302. case BfTypeCode_IntPtr:
  9303. allowCast = true; break;
  9304. case BfTypeCode_UInt8:
  9305. case BfTypeCode_UInt16:
  9306. case BfTypeCode_UInt32:
  9307. allowCast = true; break;
  9308. default: break;
  9309. }
  9310. break;
  9311. case BfTypeCode_UInt64:
  9312. switch (fromTypeCode)
  9313. {
  9314. case BfTypeCode_UInt8:
  9315. case BfTypeCode_UInt16:
  9316. case BfTypeCode_UInt32:
  9317. case BfTypeCode_UIntPtr:
  9318. allowCast = true; break;
  9319. default: break;
  9320. }
  9321. break;
  9322. case BfTypeCode_IntPtr:
  9323. switch (fromTypeCode)
  9324. {
  9325. case BfTypeCode_Int8:
  9326. case BfTypeCode_Int16:
  9327. case BfTypeCode_Int32:
  9328. allowCast = true; break;
  9329. case BfTypeCode_UInt8:
  9330. case BfTypeCode_UInt16:
  9331. allowCast = true; break;
  9332. case BfTypeCode_UInt32:
  9333. case BfTypeCode_Int64:
  9334. // It may seem that we want this to require an explicit cast,
  9335. // but consider the case of
  9336. // int val = Math.Max(intA, intB)
  9337. // Math.Max has an int32 and int64 override, so we want the correct one to be chosen and
  9338. // to be able to have the int64 return value implicitly used in a 64-bit build
  9339. if (mCompiler->mSystem->mPtrSize == 8)
  9340. allowCast = true;
  9341. break;
  9342. default: break;
  9343. }
  9344. break;
  9345. case BfTypeCode_UIntPtr:
  9346. switch (fromTypeCode)
  9347. {
  9348. case BfTypeCode_UInt8:
  9349. case BfTypeCode_UInt16:
  9350. case BfTypeCode_UInt32:
  9351. allowCast = true; break;
  9352. case BfTypeCode_UInt64:
  9353. if (mCompiler->mSystem->mPtrSize == 8)
  9354. allowCast = true;
  9355. break;
  9356. default: break;
  9357. }
  9358. break;
  9359. case BfTypeCode_Float:
  9360. switch (fromTypeCode)
  9361. {
  9362. case BfTypeCode_Int8:
  9363. case BfTypeCode_Int16:
  9364. case BfTypeCode_Int32:
  9365. case BfTypeCode_Int64:
  9366. case BfTypeCode_IntPtr:
  9367. case BfTypeCode_IntUnknown:
  9368. allowCast = true; break;
  9369. case BfTypeCode_UInt8:
  9370. case BfTypeCode_UInt16:
  9371. case BfTypeCode_UInt32:
  9372. case BfTypeCode_UInt64:
  9373. case BfTypeCode_UIntPtr:
  9374. case BfTypeCode_UIntUnknown:
  9375. allowCast = true; break;
  9376. default: break;
  9377. }
  9378. break;
  9379. case BfTypeCode_Double:
  9380. switch (fromTypeCode)
  9381. {
  9382. case BfTypeCode_Int8:
  9383. case BfTypeCode_Int16:
  9384. case BfTypeCode_Int32:
  9385. case BfTypeCode_Int64:
  9386. case BfTypeCode_IntPtr:
  9387. case BfTypeCode_IntUnknown:
  9388. allowCast = true; break;
  9389. case BfTypeCode_UInt8:
  9390. case BfTypeCode_UInt16:
  9391. case BfTypeCode_UInt32:
  9392. case BfTypeCode_UInt64:
  9393. case BfTypeCode_UIntPtr:
  9394. case BfTypeCode_UIntUnknown:
  9395. allowCast = true; break;
  9396. case BfTypeCode_Float:
  9397. allowCast = true; break;
  9398. default: break;
  9399. }
  9400. break;
  9401. default: break;
  9402. }
  9403. if (explicitCast)
  9404. {
  9405. if (((fromPrimType->IsIntegral()) || (fromPrimType->IsFloat()) || (fromPrimType->IsBoolean())) &&
  9406. ((toType->IsIntegral()) || (toType->IsFloat())))
  9407. allowCast = true;
  9408. }
  9409. if (allowCast)
  9410. {
  9411. return mBfIRBuilder->CreateNumericCast(typedVal.mValue, typedVal.mType->IsSigned(), toTypeCode);
  9412. }
  9413. }
  9414. if (typedVal.mValue.IsConst())
  9415. {
  9416. if ((toType->IsPointer()) && (toType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8)) && (typedVal.mType->IsInstanceOf(mCompiler->mStringTypeDef)))
  9417. {
  9418. int stringId = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  9419. if (stringId >= 0)
  9420. return GetStringCharPtr(stringId);
  9421. }
  9422. else if ((toType->IsInstanceOf(mCompiler->mStringViewTypeDef)))
  9423. {
  9424. int stringId = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  9425. if (stringId >= 0)
  9426. {
  9427. int strLen = 0;
  9428. String str;
  9429. BfStringPoolEntry* entry = NULL;
  9430. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  9431. {
  9432. auto svTypeInst = toType->ToTypeInstance();
  9433. mBfIRBuilder->PopulateType(svTypeInst);
  9434. auto stringCharPtr = GetStringCharPtr(stringId);
  9435. SizedArray<BfIRValue, 2> spanFieldVals;
  9436. spanFieldVals.Add(mBfIRBuilder->CreateConstStructZero(mBfIRBuilder->MapType(svTypeInst->mBaseType->mBaseType)));
  9437. spanFieldVals.Add(stringCharPtr);
  9438. spanFieldVals.Add(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, entry->mString.mLength));
  9439. SizedArray<BfIRValue, 2> svFieldVals;
  9440. svFieldVals.Add(mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(svTypeInst->mBaseType), spanFieldVals));
  9441. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(svTypeInst), svFieldVals);
  9442. }
  9443. }
  9444. }
  9445. }
  9446. // Check user-defined operators
  9447. if ((castFlags & BfCastFlags_NoConversionOperator) == 0)
  9448. {
  9449. auto fromType = typedVal.mType;
  9450. auto fromTypeInstance = typedVal.mType->ToTypeInstance();
  9451. auto toTypeInstance = toType->ToTypeInstance();
  9452. auto liftedFromType = ((fromTypeInstance != NULL) && fromTypeInstance->IsNullable()) ? fromTypeInstance->GetUnderlyingType() : NULL;
  9453. auto liftedToType = ((toTypeInstance != NULL) && toTypeInstance->IsNullable()) ? toTypeInstance->GetUnderlyingType() : NULL;
  9454. int bestFromDist = INT_MAX;
  9455. BfType* bestFromType = NULL;
  9456. int bestNegFromDist = INT_MAX;
  9457. BfType* bestNegFromType = NULL;
  9458. int bestToDist = INT_MAX;
  9459. BfType* bestToType = NULL;
  9460. int bestNegToDist = INT_MAX;
  9461. BfType* bestNegToType = NULL;
  9462. bool isAmbiguousCast = false;
  9463. BfIRValue conversionResult;
  9464. BfMethodInstance* opMethodInstance = NULL;
  9465. BfType* opMethodSrcType = NULL;
  9466. BfOperatorInfo* constraintOperatorInfo = NULL;
  9467. // Normal, lifted, execute
  9468. for (int pass = 0; pass < 3; pass++)
  9469. {
  9470. auto checkToType = toType;
  9471. auto checkFromType = fromType;
  9472. if (pass == 1)
  9473. {
  9474. if ((bestFromType != NULL) && (bestToType != NULL))
  9475. continue;
  9476. if (liftedFromType != NULL)
  9477. checkFromType = liftedFromType;
  9478. if (liftedToType != NULL)
  9479. checkToType = liftedToType;
  9480. }
  9481. else if (pass == 2)
  9482. {
  9483. if ((bestFromType == NULL) || (bestToType == NULL))
  9484. break;
  9485. }
  9486. bool isConstraintCheck = ((castFlags & BfCastFlags_IsConstraintCheck) != 0);
  9487. BfBaseClassWalker baseClassWalker(fromType, toType, this);
  9488. while (true)
  9489. {
  9490. auto entry = baseClassWalker.Next();
  9491. auto checkInstance = entry.mTypeInstance;
  9492. if (checkInstance == NULL)
  9493. break;
  9494. for (auto operatorDef : checkInstance->mTypeDef->mOperators)
  9495. {
  9496. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  9497. {
  9498. if ((!explicitCast) && (operatorDef->mOperatorDeclaration->mExplicitToken != NULL) &&
  9499. (operatorDef->mOperatorDeclaration->mExplicitToken->GetToken() == BfToken_Explicit))
  9500. continue;
  9501. BfType* methodFromType = NULL;
  9502. BfType* methodToType = NULL;
  9503. if (isConstraintCheck)
  9504. {
  9505. auto operatorInfo = GetOperatorInfo(checkInstance, operatorDef);
  9506. methodFromType = operatorInfo->mLHSType;
  9507. methodToType = operatorInfo->mReturnType;
  9508. if ((methodFromType == NULL) || (methodToType == NULL))
  9509. continue;
  9510. }
  9511. else
  9512. {
  9513. auto methodInst = GetRawMethodInstanceAtIdx(checkInstance, operatorDef->mIdx);
  9514. if (methodInst == NULL)
  9515. continue;
  9516. if (methodInst->GetParamCount() != 1)
  9517. {
  9518. AssertErrorState();
  9519. continue;
  9520. }
  9521. methodFromType = methodInst->GetParamType(0);
  9522. methodToType = methodInst->mReturnType;
  9523. }
  9524. if (methodFromType->IsSelf())
  9525. methodFromType = entry.mSrcType;
  9526. if (methodToType->IsSelf())
  9527. methodToType = entry.mSrcType;
  9528. // Selection pass
  9529. if (pass < 2)
  9530. {
  9531. auto methodCheckFromType = methodFromType;
  9532. auto methodCheckToType = methodToType;
  9533. if (pass == 1)
  9534. {
  9535. // Only check inner type on lifted types when we aren't checking conversions within lifted class
  9536. // This avoid some infinite conversions
  9537. if ((methodCheckFromType->IsNullable()) && (!checkInstance->IsNullable()))
  9538. methodCheckFromType = methodCheckFromType->GetUnderlyingType();
  9539. if ((methodCheckToType->IsNullable()) && (!checkInstance->IsNullable()))
  9540. methodCheckToType = methodCheckToType->GetUnderlyingType();
  9541. }
  9542. int fromDist = GetTypeDistance(methodCheckFromType, checkFromType);
  9543. if (fromDist < 0)
  9544. {
  9545. // Allow us to cast a constant int to a smaller type if it satisfies the cast operator
  9546. if ((typedVal.mValue.IsConst()) && (CanCast(typedVal, methodCheckFromType, BfCastFlags_NoConversionOperator)))
  9547. {
  9548. fromDist = 0;
  9549. }
  9550. }
  9551. int toDist = GetTypeDistance(methodCheckToType, checkToType);
  9552. if ((fromDist == INT_MAX) || (toDist == INT_MAX))
  9553. continue;
  9554. if (((fromDist >= 0) && (toDist >= 0)) || (explicitCast))
  9555. {
  9556. if ((fromDist >= 0) && (fromDist < bestFromDist))
  9557. {
  9558. bestFromDist = fromDist;
  9559. bestFromType = methodFromType;
  9560. }
  9561. if ((toDist >= 0) && (toDist < bestToDist))
  9562. {
  9563. bestToDist = toDist;
  9564. bestToType = methodToType;
  9565. }
  9566. }
  9567. if (explicitCast)
  9568. {
  9569. fromDist = abs(fromDist);
  9570. toDist = abs(toDist);
  9571. if ((fromDist >= 0) && (fromDist < bestNegFromDist))
  9572. {
  9573. bestNegFromDist = fromDist;
  9574. bestNegFromType = methodFromType;
  9575. }
  9576. if ((toDist >= 0) && (toDist < bestNegToDist))
  9577. {
  9578. bestNegToDist = toDist;
  9579. bestNegToType = methodToType;
  9580. }
  9581. }
  9582. }
  9583. else if (pass == 2) // Execution Pass
  9584. {
  9585. if ((methodFromType == bestFromType) && (methodToType == bestToType))
  9586. {
  9587. if (isConstraintCheck)
  9588. {
  9589. auto operatorInfo = GetOperatorInfo(checkInstance, operatorDef);
  9590. constraintOperatorInfo = operatorInfo;
  9591. }
  9592. else
  9593. {
  9594. // Get in native module so our module doesn't get a reference to it - we may not end up calling it at all!
  9595. BfMethodInstance* methodInstance = GetRawMethodInstanceAtIdx(checkInstance, operatorDef->mIdx);
  9596. if (opMethodInstance != NULL)
  9597. {
  9598. int prevGenericCount = GetGenericParamAndReturnCount(opMethodInstance);
  9599. int newGenericCount = GetGenericParamAndReturnCount(methodInstance);
  9600. if (newGenericCount > prevGenericCount)
  9601. {
  9602. // Prefer generic match
  9603. opMethodInstance = methodInstance;
  9604. opMethodSrcType = entry.mSrcType;
  9605. }
  9606. else if (newGenericCount < prevGenericCount)
  9607. {
  9608. // Previous was a generic match
  9609. continue;
  9610. }
  9611. else
  9612. {
  9613. isAmbiguousCast = true;
  9614. break;
  9615. }
  9616. }
  9617. else
  9618. {
  9619. opMethodInstance = methodInstance;
  9620. opMethodSrcType = entry.mSrcType;
  9621. }
  9622. }
  9623. }
  9624. }
  9625. }
  9626. }
  9627. if (isAmbiguousCast)
  9628. break;
  9629. if ((opMethodInstance != NULL) || (constraintOperatorInfo != NULL))
  9630. {
  9631. if (mayBeBox)
  9632. {
  9633. if (!ignoreErrors)
  9634. {
  9635. if (Fail("Ambiguous cast, may be conversion operator or may be boxing request", srcNode) != NULL)
  9636. mCompiler->mPassInstance->MoreInfo("See conversion operator", opMethodInstance->mMethodDef->GetRefNode());
  9637. }
  9638. else if (!silentFail)
  9639. SetFail();
  9640. }
  9641. BfType* returnType;
  9642. if (isConstraintCheck)
  9643. {
  9644. returnType = constraintOperatorInfo->mReturnType;
  9645. }
  9646. else
  9647. {
  9648. returnType = opMethodInstance->mReturnType;
  9649. BfMethodInstance* methodInstance = GetRawMethodInstance(opMethodInstance->GetOwner(), opMethodInstance->mMethodDef);
  9650. auto methodDeclaration = methodInstance->mMethodDef->GetMethodDeclaration();
  9651. if (methodDeclaration->mBody == NULL)
  9652. {
  9653. // Handle the typedPrim<->underlying part implicitly
  9654. if (fromType->IsTypedPrimitive())
  9655. {
  9656. auto convTypedValue = BfTypedValue(typedVal.mValue, fromType->GetUnderlyingType());
  9657. return CastToValue(srcNode, convTypedValue, toType, (BfCastFlags)(castFlags & ~BfCastFlags_Explicit), NULL);
  9658. }
  9659. else if (toType->IsTypedPrimitive())
  9660. {
  9661. auto castedVal = CastToValue(srcNode, typedVal, toType->GetUnderlyingType(), (BfCastFlags)(castFlags & ~BfCastFlags_Explicit), NULL);
  9662. return castedVal;
  9663. }
  9664. }
  9665. }
  9666. // Actually perform conversion
  9667. BfExprEvaluator exprEvaluator(this);
  9668. auto castedFromValue = Cast(srcNode, typedVal, bestFromType, castFlags);
  9669. if (!castedFromValue)
  9670. return BfIRValue();
  9671. BfTypedValue operatorOut;
  9672. if (ignoreWrites)
  9673. {
  9674. if (returnType == toType)
  9675. return mBfIRBuilder->GetFakeVal();
  9676. operatorOut = GetDefaultTypedValue(returnType);
  9677. }
  9678. else
  9679. {
  9680. BfModuleMethodInstance moduleMethodInstance = GetMethodInstance(opMethodInstance->GetOwner(), opMethodInstance->mMethodDef, BfTypeVector());
  9681. SizedArray<BfIRValue, 1> args;
  9682. exprEvaluator.PushArg(castedFromValue, args);
  9683. operatorOut = exprEvaluator.CreateCall(NULL, moduleMethodInstance.mMethodInstance, IsSkippingExtraResolveChecks() ? BfIRValue() : moduleMethodInstance.mFunc, false, args);
  9684. if ((operatorOut.mType != NULL) && (operatorOut.mType->IsSelf()))
  9685. {
  9686. BF_ASSERT(IsInGeneric());
  9687. operatorOut = GetDefaultTypedValue(opMethodSrcType);
  9688. }
  9689. }
  9690. return CastToValue(srcNode, operatorOut, toType, castFlags, resultFlags);
  9691. }
  9692. }
  9693. if (bestFromType == NULL)
  9694. bestFromType = bestNegFromType;
  9695. if (bestToType == NULL)
  9696. bestToType = bestNegToType;
  9697. }
  9698. isAmbiguousCast |= ((bestFromType != NULL) && (bestToType != NULL));
  9699. if (isAmbiguousCast)
  9700. {
  9701. if (!ignoreErrors)
  9702. {
  9703. const char* errStr = "Ambiguous conversion operators for casting from '%s' to '%s'";
  9704. Fail(StrFormat(errStr, TypeToString(typedVal.mType).c_str(), TypeToString(toType).c_str()), srcNode);
  9705. }
  9706. else if (!silentFail)
  9707. SetFail();
  9708. return BfIRValue();
  9709. }
  9710. // Check method generic constraints
  9711. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mMethodInfoEx != NULL))
  9712. {
  9713. for (int genericParamIdx = 0; genericParamIdx < mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  9714. {
  9715. auto genericParam = mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  9716. for (auto& opConstraint : genericParam->mOperatorConstraints)
  9717. {
  9718. if ((opConstraint.mCastToken == BfToken_Implicit) ||
  9719. ((explicitCast) && (opConstraint.mCastToken == BfToken_Explicit)))
  9720. {
  9721. // If we can convert OUR fromVal to the constraint's fromVal then we may match
  9722. if (CanCast(typedVal, opConstraint.mRightType, BfCastFlags_NoConversionOperator))
  9723. {
  9724. // .. and we can convert the constraint's toType to OUR toType then we're good
  9725. auto opToVal = genericParam->mExternType;
  9726. if (CanCast(BfTypedValue(BfIRValue::sValueless, opToVal), toType, BfCastFlags_NoConversionOperator))
  9727. return mBfIRBuilder->GetFakeVal();
  9728. }
  9729. }
  9730. }
  9731. }
  9732. }
  9733. // Check type generic constraints
  9734. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsGenericTypeInstance()) && (mCurTypeInstance->IsUnspecializedType()))
  9735. {
  9736. SizedArray<BfGenericParamInstance*, 4> genericParams;
  9737. GetActiveTypeGenericParamInstances(genericParams);
  9738. for (auto genericParam : genericParams)
  9739. {
  9740. for (auto& opConstraint : genericParam->mOperatorConstraints)
  9741. {
  9742. if ((opConstraint.mCastToken == BfToken_Implicit) ||
  9743. ((explicitCast) && (opConstraint.mCastToken == BfToken_Explicit)))
  9744. {
  9745. // If we can convert OUR fromVal to the constraint's fromVal then we may match
  9746. if (CanCast(typedVal, opConstraint.mRightType, BfCastFlags_NoConversionOperator))
  9747. {
  9748. // .. and we can convert the constraint's toType to OUR toType then we're good
  9749. auto opToVal = genericParam->mExternType;
  9750. if (CanCast(BfTypedValue(BfIRValue::sValueless, opToVal), toType, BfCastFlags_NoConversionOperator))
  9751. return mBfIRBuilder->GetFakeVal();
  9752. }
  9753. }
  9754. }
  9755. }
  9756. }
  9757. }
  9758. // Default typed primitive 'underlying casts' happen after checking cast operators
  9759. if (explicitCast)
  9760. {
  9761. // TypedPrimitive -> Primitive
  9762. if ((typedVal.mType->IsTypedPrimitive()) && (!typedVal.mType->IsFunction()) && (toType->IsPrimitiveType()))
  9763. {
  9764. auto fromTypedPrimitiveType = typedVal.mType->ToTypeInstance();
  9765. auto primTypedVal = BfTypedValue(typedVal.mValue, fromTypedPrimitiveType->mFieldInstances.back().mResolvedType, typedVal.IsAddr());
  9766. primTypedVal = LoadValue(primTypedVal);
  9767. return CastToValue(srcNode, primTypedVal, toType, castFlags);
  9768. }
  9769. // TypedPrimitive -> TypedPrimitive
  9770. if ((typedVal.mType->IsTypedPrimitive()) && (!typedVal.mType->IsFunction()) && (toType->IsTypedPrimitive()))
  9771. {
  9772. auto fromTypedPrimitiveType = typedVal.mType->ToTypeInstance();
  9773. auto toTypedPrimitiveType = toType->ToTypeInstance();
  9774. auto fromUnderlyingType = fromTypedPrimitiveType->GetUnderlyingType();
  9775. auto toUnderlyingType = toTypedPrimitiveType->GetUnderlyingType();
  9776. BfTypedValue underlyingTypedValue(typedVal.mValue, fromUnderlyingType, typedVal.IsAddr());
  9777. underlyingTypedValue = LoadValue(underlyingTypedValue);
  9778. BfIRValue castedToValue = CastToValue(srcNode, underlyingTypedValue, toUnderlyingType, (BfCastFlags)(castFlags | BfCastFlags_Explicit));
  9779. if (castedToValue)
  9780. return castedToValue;
  9781. }
  9782. }
  9783. else if ((typedVal.mType->IsTypedPrimitive()) && (toType->IsTypedPrimitive()))
  9784. {
  9785. if (TypeIsSubTypeOf(typedVal.mType->ToTypeInstance(), toType->ToTypeInstance()))
  9786. {
  9787. // These have the same underlying primitive type, just keep it all the same
  9788. if ((resultFlags != NULL) && (typedVal.IsAddr()))
  9789. *resultFlags = BfCastResultFlags_IsAddr;
  9790. return typedVal.mValue;
  9791. }
  9792. }
  9793. // Prim -> TypedPrimitive
  9794. if ((typedVal.mType->IsPrimitiveType()) && (toType->IsTypedPrimitive()))
  9795. {
  9796. bool allowCast = explicitCast;
  9797. if (toType == mCurTypeInstance)
  9798. allowCast = true;
  9799. if ((!allowCast) && (typedVal.mType->IsIntegral()) /*&& (!toType->IsEnum())*/)
  9800. {
  9801. // Allow implicit cast of zero
  9802. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  9803. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  9804. {
  9805. allowCast = constant->mInt64 == 0;
  9806. }
  9807. }
  9808. if (allowCast)
  9809. {
  9810. return CastToValue(srcNode, typedVal, toType->GetUnderlyingType(), castFlags);
  9811. }
  9812. }
  9813. if (typedVal.mType->IsBoxed())
  9814. {
  9815. BfBoxedType* boxedType = (BfBoxedType*)typedVal.mType;
  9816. if (boxedType->mElementType->IsGenericParam())
  9817. {
  9818. // If we have a boxed generic param, the actual available interfaces constraints won't be
  9819. // handled, so we need to pass through again as the root generic param
  9820. BfTypedValue unboxedValue = typedVal;
  9821. unboxedValue.mType = boxedType->mElementType;
  9822. auto result = CastToValue(srcNode, unboxedValue, toType, (BfCastFlags)(castFlags | BfCastFlags_SilentFail), resultFlags);
  9823. if (result)
  9824. return result;
  9825. }
  9826. }
  9827. if ((mayBeBox) && ((castFlags & BfCastFlags_NoBox) == 0))
  9828. {
  9829. BfScopeData* scopeData = NULL;
  9830. if (mCurMethodState != NULL)
  9831. {
  9832. if (mCurMethodState->mOverrideScope)
  9833. scopeData = mCurMethodState->mOverrideScope;
  9834. else
  9835. scopeData = mCurMethodState->mCurScope;
  9836. }
  9837. if ((castFlags & BfCastFlags_WarnOnBox) != 0)
  9838. {
  9839. Warn(0, "This implicit boxing will only be in scope during the constructor. Consider using a longer-term allocation such as 'box new'", srcNode);
  9840. }
  9841. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, ignoreWrites);
  9842. auto value = BoxValue(srcNode, typedVal, toType, scopeData, (castFlags & BfCastFlags_NoBoxDtor) == 0);
  9843. if (value)
  9844. return value.mValue;
  9845. }
  9846. if (!ignoreErrors)
  9847. {
  9848. const char* errStrF = explicitCast ?
  9849. "Unable to cast '%s' to '%s'" :
  9850. "Unable to implicitly cast '%s' to '%s'";
  9851. String errStr = StrFormat(errStrF, TypeToString(typedVal.mType).c_str(), TypeToString(toType).c_str());
  9852. auto error = Fail(errStr, srcNode);
  9853. if ((error != NULL) && (srcNode != NULL))
  9854. {
  9855. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((srcNode))))
  9856. {
  9857. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites);
  9858. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  9859. if (CastToValue(srcNode, typedVal, toType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail)))
  9860. {
  9861. bool doWrap = false;
  9862. if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(srcNode))
  9863. {
  9864. if ((unaryOpExpr->mOp != BfUnaryOp_AddressOf) && (unaryOpExpr->mOp != BfUnaryOp_Dereference))
  9865. doWrap = true;
  9866. }
  9867. if ((srcNode->IsA<BfCastExpression>()) ||
  9868. (srcNode->IsA<BfBinaryOperatorExpression>()) ||
  9869. (srcNode->IsA<BfConditionalExpression>()))
  9870. doWrap = true;
  9871. BfParserData* parser = srcNode->GetSourceData()->ToParserData();
  9872. String typeName = TypeToString(toType);
  9873. if (doWrap)
  9874. {
  9875. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit",
  9876. StrFormat("(%s)\tcast|%s|%d|(%s)(|`%d|)", typeName.c_str(), parser->mFileName.c_str(), srcNode->GetSrcStart(), typeName.c_str(), srcNode->GetSrcLength()).c_str()));
  9877. }
  9878. else
  9879. {
  9880. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit",
  9881. StrFormat("(%s)\tcast|%s|%d|(%s)", typeName.c_str(), parser->mFileName.c_str(), srcNode->GetSrcStart(), typeName.c_str()).c_str()));
  9882. }
  9883. }
  9884. }
  9885. }
  9886. }
  9887. else if (!silentFail)
  9888. SetFail();
  9889. return BfIRValue();
  9890. }
  9891. BfTypedValue BfModule::Cast(BfAstNode* srcNode, const BfTypedValue& typedVal, BfType* toType, BfCastFlags castFlags)
  9892. {
  9893. bool explicitCast = (castFlags & BfCastFlags_Explicit) != 0;
  9894. if (typedVal.mType == toType)
  9895. return typedVal;
  9896. PopulateType(toType, ((castFlags & BfCastFlags_NoConversionOperator) != 0) ? BfPopulateType_Data : BfPopulateType_DataAndMethods);
  9897. if ((toType->IsSizedArray()) && (typedVal.mType->IsSizedArray()))
  9898. {
  9899. // Retain our type if we're casting from a known-sized array to an unknown-sized arrays
  9900. if ((toType->IsUndefSizedArray()) && ((typedVal.mType->GetUnderlyingType()) == (toType->GetUnderlyingType())))
  9901. {
  9902. return typedVal;
  9903. }
  9904. }
  9905. if ((castFlags & BfCastFlags_Force) != 0)
  9906. {
  9907. if (toType->IsValuelessType())
  9908. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  9909. if ((typedVal.mType->IsValueType()) && (!typedVal.IsAddr()) && (typedVal.IsSplat()) && (toType->IsValueType()))
  9910. {
  9911. bool needsMemberCasting = false;
  9912. if (AreSplatsCompatible(typedVal.mType, toType, &needsMemberCasting))
  9913. {
  9914. return BfTypedValue(typedVal.mValue, toType, needsMemberCasting ? BfTypedValueKind_SplatHead_NeedsCasting : BfTypedValueKind_SplatHead);
  9915. }
  9916. }
  9917. if (typedVal.mType->IsValueType())
  9918. {
  9919. auto addrTypedValue = MakeAddressable(typedVal);
  9920. auto toPtrType = CreatePointerType(toType);
  9921. return BfTypedValue(mBfIRBuilder->CreateBitCast(addrTypedValue.mValue, mBfIRBuilder->MapType(toPtrType)), toType, BfTypedValueKind_Addr);
  9922. }
  9923. return BfTypedValue(mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType)), toType);
  9924. }
  9925. // This tuple cast may create a new type if the toType contains 'var' entries
  9926. if ((typedVal.mType->IsTuple()) && (toType->IsTuple()))
  9927. {
  9928. //auto loadedVal = LoadValue(typedVal);
  9929. PopulateType(toType);
  9930. auto fromTupleType = (BfTypeInstance*)typedVal.mType;
  9931. auto toTupleType = (BfTypeInstance*)toType;
  9932. if (fromTupleType == toTupleType)
  9933. return typedVal;
  9934. if (fromTupleType->mFieldInstances.size() == toTupleType->mFieldInstances.size())
  9935. {
  9936. BfTypeVector fieldTypes;
  9937. Array<String> fieldNames;
  9938. bool isCompatible = true;
  9939. bool isExactTypeMatch = true;
  9940. for (int fieldIdx = 0; fieldIdx < (int)fromTupleType->mFieldInstances.size(); fieldIdx++)
  9941. {
  9942. auto fromFieldInst = &fromTupleType->mFieldInstances[fieldIdx];
  9943. auto toFieldInst = &toTupleType->mFieldInstances[fieldIdx];
  9944. auto fromFieldDef = fromFieldInst->GetFieldDef();
  9945. auto toFieldDef = toFieldInst->GetFieldDef();
  9946. if (!toFieldDef->IsUnnamedTupleField())
  9947. {
  9948. if ((!explicitCast) &&
  9949. (!fromFieldDef->IsUnnamedTupleField()) &&
  9950. (fromFieldDef->mName != toFieldDef->mName))
  9951. isCompatible = false;
  9952. fieldNames.push_back(toFieldDef->mName);
  9953. }
  9954. else
  9955. fieldNames.push_back("");
  9956. if (toFieldInst->mResolvedType->IsVar())
  9957. fieldTypes.push_back(fromFieldInst->mResolvedType);
  9958. else
  9959. {
  9960. if (fromFieldInst->mResolvedType != toFieldInst->mResolvedType)
  9961. isExactTypeMatch = false;
  9962. BfCastFlags tryCastFlags = BfCastFlags_SilentFail;
  9963. if (explicitCast)
  9964. tryCastFlags = (BfCastFlags)(tryCastFlags | BfCastFlags_Explicit);
  9965. // 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
  9966. // so we can give normal implicit-cast-to-void errors
  9967. if ((fromFieldInst->mResolvedType != toFieldInst->mResolvedType) && (!toFieldInst->mResolvedType->IsVoid()) &&
  9968. (!CanCast(GetFakeTypedValue(fromFieldInst->mResolvedType), toFieldInst->mResolvedType, tryCastFlags)))
  9969. isCompatible = false;
  9970. fieldTypes.push_back(toFieldInst->mResolvedType);
  9971. }
  9972. }
  9973. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  9974. AddDependency(tupleType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  9975. mBfIRBuilder->PopulateType(tupleType);
  9976. if (isCompatible)
  9977. {
  9978. if (isExactTypeMatch)
  9979. {
  9980. if (typedVal.mKind == BfTypedValueKind_TempAddr)
  9981. {
  9982. return BfTypedValue(mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapTypeInstPtr(tupleType)), tupleType, BfTypedValueKind_TempAddr);
  9983. }
  9984. else if (typedVal.IsAddr())
  9985. {
  9986. return BfTypedValue(mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapTypeInstPtr(tupleType)), tupleType, BfTypedValueKind_ReadOnlyAddr);
  9987. }
  9988. else if (typedVal.IsSplat())
  9989. {
  9990. BfTypedValue retTypedValue = typedVal;
  9991. retTypedValue.mType = tupleType;
  9992. return retTypedValue;
  9993. }
  9994. BfIRValue curTupleValue = CreateAlloca(tupleType);
  9995. auto loadedVal = LoadValue(typedVal);
  9996. mBfIRBuilder->CreateStore(loadedVal.mValue, mBfIRBuilder->CreateBitCast(curTupleValue, mBfIRBuilder->MapTypeInstPtr(fromTupleType)));
  9997. return BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  9998. }
  9999. BfIRValue curTupleValue = CreateAlloca(tupleType);
  10000. for (int fieldIdx = 0; fieldIdx < (int)fromTupleType->mFieldInstances.size(); fieldIdx++)
  10001. {
  10002. BfFieldInstance* fromFieldInstance = &fromTupleType->mFieldInstances[fieldIdx];
  10003. BfFieldInstance* toFieldInstance = &tupleType->mFieldInstances[fieldIdx];
  10004. if (toFieldInstance->mDataIdx >= 0)
  10005. {
  10006. if (fromFieldInstance->mDataIdx >= 0)
  10007. {
  10008. auto elementVal = ExtractValue(typedVal, fromFieldInstance, fromFieldInstance->mDataIdx);
  10009. elementVal = LoadValue(elementVal);
  10010. auto castedElementVal = Cast(srcNode, elementVal, toFieldInstance->GetResolvedType(), castFlags);
  10011. if (!castedElementVal)
  10012. return BfTypedValue();
  10013. auto fieldRef = mBfIRBuilder->CreateInBoundsGEP(curTupleValue, 0, toFieldInstance->mDataIdx);
  10014. castedElementVal = LoadValue(castedElementVal);
  10015. mBfIRBuilder->CreateStore(castedElementVal.mValue, fieldRef);
  10016. }
  10017. else
  10018. isCompatible = false;
  10019. }
  10020. }
  10021. return BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  10022. }
  10023. }
  10024. const char* errStr = explicitCast ?
  10025. "Unable to cast '%s' to '%s'" :
  10026. "Unable to implicitly cast '%s' to '%s'";
  10027. Fail(StrFormat(errStr, TypeToString(typedVal.mType).c_str(), TypeToString(toType).c_str()), srcNode);
  10028. return BfTypedValue();
  10029. }
  10030. // Function->Function and Delegate->Delegate where type is compatible but not exact
  10031. if (((typedVal.mType->IsDelegate()) || (typedVal.mType->IsFunction())) &&
  10032. (typedVal.mType != toType) && // Don't bother to check for exact match, let CastToValue handle this
  10033. ((typedVal.mType->IsDelegate()) == (toType->IsDelegate())) &&
  10034. ((typedVal.mType->IsFunction()) == (toType->IsFunction())))
  10035. {
  10036. auto fromTypeInst = typedVal.mType->ToTypeInstance();
  10037. auto toTypeInst = toType->ToTypeInstance();
  10038. auto fromMethodInst = GetRawMethodByName(fromTypeInst, "Invoke", -1, true);
  10039. auto toMethodInst = GetRawMethodByName(toTypeInst, "Invoke", -1, true);
  10040. if ((fromMethodInst != NULL) && (toMethodInst != NULL) &&
  10041. (fromMethodInst->mMethodDef->mCallingConvention == toMethodInst->mMethodDef->mCallingConvention) &&
  10042. (fromMethodInst->mMethodDef->mIsMutating == toMethodInst->mMethodDef->mIsMutating) &&
  10043. (fromMethodInst->mReturnType == toMethodInst->mReturnType) &&
  10044. (fromMethodInst->GetParamCount() == toMethodInst->GetParamCount()))
  10045. {
  10046. bool matched = true;
  10047. StringT<64> fromParamName;
  10048. StringT<64> toParamName;
  10049. if (fromMethodInst->HasExplicitThis() != toMethodInst->HasExplicitThis())
  10050. {
  10051. matched = false;
  10052. }
  10053. else
  10054. {
  10055. for (int paramIdx = 0; paramIdx < (int)fromMethodInst->GetParamCount(); paramIdx++)
  10056. {
  10057. bool nameMatches = true;
  10058. if (!explicitCast)
  10059. {
  10060. fromMethodInst->GetParamName(paramIdx, fromParamName);
  10061. toMethodInst->GetParamName(paramIdx, toParamName);
  10062. if ((!fromParamName.IsEmpty()) && (!toParamName.IsEmpty()))
  10063. nameMatches = fromParamName == toParamName;
  10064. }
  10065. if ((fromMethodInst->GetParamKind(paramIdx) == toMethodInst->GetParamKind(paramIdx)) &&
  10066. (fromMethodInst->GetParamType(paramIdx) == toMethodInst->GetParamType(paramIdx)) &&
  10067. (nameMatches))
  10068. {
  10069. // Matched, required for implicit/explicit
  10070. }
  10071. else
  10072. {
  10073. matched = false;
  10074. break;
  10075. }
  10076. }
  10077. }
  10078. if (matched)
  10079. {
  10080. BfTypedValue loadedVal = LoadValue(typedVal);
  10081. return BfTypedValue(mBfIRBuilder->CreateBitCast(loadedVal.mValue, mBfIRBuilder->MapType(toType)), toType);
  10082. }
  10083. }
  10084. }
  10085. // Struct truncate
  10086. if ((typedVal.mType->IsStruct()) && (toType->IsStruct()))
  10087. {
  10088. auto fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  10089. auto toStructTypeInstance = toType->ToTypeInstance();
  10090. if (TypeIsSubTypeOf(fromStructTypeInstance, toStructTypeInstance))
  10091. {
  10092. if (typedVal.IsSplat())
  10093. {
  10094. BF_ASSERT(toStructTypeInstance->IsSplattable() || (toStructTypeInstance->mInstSize == 0));
  10095. return BfTypedValue(typedVal.mValue, toStructTypeInstance, typedVal.IsThis() ? BfTypedValueKind_ThisSplatHead : BfTypedValueKind_SplatHead);
  10096. }
  10097. if (typedVal.IsAddr())
  10098. {
  10099. BfIRValue castedIRValue;
  10100. if (typedVal.mValue.IsFake())
  10101. castedIRValue = typedVal.mValue;
  10102. else
  10103. castedIRValue = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapTypeInstPtr(toStructTypeInstance));
  10104. return BfTypedValue(castedIRValue, toType, typedVal.IsThis() ?
  10105. (typedVal.IsReadOnly() ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  10106. (typedVal.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  10107. }
  10108. BfTypedValue curTypedVal = typedVal;
  10109. while (curTypedVal.mType != toStructTypeInstance)
  10110. {
  10111. mBfIRBuilder->PopulateType(curTypedVal.mType);
  10112. auto curTypeInstance = curTypedVal.mType->ToTypeInstance();
  10113. BfIRValue extractedValue;
  10114. if (toStructTypeInstance->IsValuelessType())
  10115. extractedValue = mBfIRBuilder->GetFakeVal();
  10116. else
  10117. extractedValue = mBfIRBuilder->CreateExtractValue(curTypedVal.mValue, 0);
  10118. curTypedVal = BfTypedValue(extractedValue, curTypeInstance->mBaseType, typedVal.IsThis() ?
  10119. (typedVal.IsReadOnly() ? BfTypedValueKind_ReadOnlyThisValue : BfTypedValueKind_ThisValue) :
  10120. BfTypedValueKind_Value);
  10121. }
  10122. return curTypedVal;
  10123. }
  10124. }
  10125. /*if ((explicitCast) && (toType->IsValuelessType()))
  10126. {
  10127. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  10128. }*/
  10129. BfCastResultFlags castResultFlags = BfCastResultFlags_None;
  10130. auto castedValue = CastToValue(srcNode, typedVal, toType, castFlags, &castResultFlags);
  10131. if (!castedValue)
  10132. return BfTypedValue();
  10133. if ((castResultFlags & BfCastResultFlags_IsAddr) != 0)
  10134. {
  10135. if ((castResultFlags & BfCastResultFlags_IsTemp) != 0)
  10136. return BfTypedValue(castedValue, toType, BfTypedValueKind_TempAddr);
  10137. return BfTypedValue(castedValue, toType, BfTypedValueKind_Addr);
  10138. }
  10139. return BfTypedValue(castedValue, toType, BfTypedValueKind_Value);
  10140. }
  10141. BfPrimitiveType* BfModule::GetIntCoercibleType(BfType* type)
  10142. {
  10143. if (type->IsSizedArray())
  10144. {
  10145. auto sizedArray = (BfSizedArrayType*)type;
  10146. if ((sizedArray->mElementType->IsChar()) && (sizedArray->mElementType->mSize == 1))
  10147. {
  10148. auto primType = (BfPrimitiveType*)sizedArray->mElementType;
  10149. if (sizedArray->mElementCount == 1)
  10150. return GetPrimitiveType(BfTypeCode_UInt8);
  10151. if (sizedArray->mElementCount == 2)
  10152. return GetPrimitiveType(BfTypeCode_UInt16);
  10153. if (sizedArray->mElementCount == 4)
  10154. return GetPrimitiveType(BfTypeCode_UInt32);
  10155. if (sizedArray->mElementCount == 8)
  10156. return GetPrimitiveType(BfTypeCode_UInt64);
  10157. }
  10158. }
  10159. return NULL;
  10160. }
  10161. BfTypedValue BfModule::GetIntCoercible(const BfTypedValue& typedValue)
  10162. {
  10163. auto intType = GetIntCoercibleType(typedValue.mType);
  10164. if (intType == NULL)
  10165. return BfTypedValue();
  10166. if (typedValue.mValue.IsConst())
  10167. {
  10168. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  10169. if (constant->mConstType == BfConstType_Agg)
  10170. {
  10171. uint64 intVal = 0;
  10172. auto constantArray = (BfConstantAgg*)constant;
  10173. int memberIdx = 0;
  10174. for (int memberIdx = 0; memberIdx < (int)constantArray->mValues.size(); memberIdx++)
  10175. {
  10176. auto memberConstant = mBfIRBuilder->GetConstant(constantArray->mValues[memberIdx]);
  10177. if (memberConstant->mTypeCode == BfTypeCode_Char8)
  10178. {
  10179. intVal |= (uint64)(memberConstant->mUInt8) << (8 * memberIdx);
  10180. //intVal = (intVal << 8) | memberConstant->mUInt8;
  10181. }
  10182. }
  10183. return BfTypedValue(mBfIRBuilder->CreateConst(intType->mTypeDef->mTypeCode, intVal), intType);
  10184. }
  10185. }
  10186. auto convTypedValue = typedValue;
  10187. convTypedValue = MakeAddressable(convTypedValue);
  10188. auto intPtrType = CreatePointerType(intType);
  10189. auto addrVal = mBfIRBuilder->CreateBitCast(convTypedValue.mValue, mBfIRBuilder->MapType(intPtrType));
  10190. auto val = mBfIRBuilder->CreateLoad(addrVal);
  10191. return BfTypedValue(val, intType);
  10192. }
  10193. bool BfModule::TypeHasParentOrEquals(BfTypeDef* checkChildTypeDef, BfTypeDef* checkParentTypeDef)
  10194. {
  10195. BfTypeDef* checkType = checkChildTypeDef;
  10196. if (checkType->mNestDepth < checkParentTypeDef->mNestDepth)
  10197. return false;
  10198. while (checkType->mNestDepth > checkParentTypeDef->mNestDepth)
  10199. checkType = checkType->mOuterType;
  10200. if (checkType == checkParentTypeDef)
  10201. return true;
  10202. if (checkType->mNameEx != checkParentTypeDef->mNameEx)
  10203. return false;
  10204. if (checkType->mIsPartial)
  10205. {
  10206. for (auto partial : checkParentTypeDef->mPartials)
  10207. if (partial == checkType)
  10208. return true;
  10209. }
  10210. return false;
  10211. }
  10212. BfTypeDef* BfModule::FindCommonOuterType(BfTypeDef* type, BfTypeDef* type2)
  10213. {
  10214. if ((type == NULL) || (type2 == NULL))
  10215. return NULL;
  10216. int curNestDepth = std::min(type->mNestDepth, type2->mNestDepth);
  10217. while (type->mNestDepth > curNestDepth)
  10218. type = type->mOuterType;
  10219. while (type2->mNestDepth > curNestDepth)
  10220. type2 = type2->mOuterType;
  10221. while (curNestDepth >= 0)
  10222. {
  10223. if ((!type->mIsPartial) && (!type2->mIsPartial))
  10224. {
  10225. if (type == type2)
  10226. return type;
  10227. }
  10228. else
  10229. {
  10230. if (type->mFullNameEx == type2->mFullNameEx)
  10231. return type;
  10232. }
  10233. type = type->mOuterType;
  10234. type2 = type2->mOuterType;
  10235. curNestDepth--;
  10236. }
  10237. return NULL;
  10238. }
  10239. bool BfModule::TypeIsSubTypeOf(BfTypeInstance* srcType, BfTypeInstance* wantType, bool checkAccessibility)
  10240. {
  10241. if ((srcType == NULL) || (wantType == NULL))
  10242. return false;
  10243. if (srcType == wantType)
  10244. return true;
  10245. if (srcType->mDefineState < BfTypeDefineState_HasInterfaces)
  10246. {
  10247. // Type is incomplete. We don't do the IsIncomplete check here because of re-entry
  10248. // While handling 'var' resolution, we don't want to force a PopulateType reentry
  10249. // but we do have enough information for TypeIsSubTypeOf
  10250. PopulateType(srcType, BfPopulateType_Interfaces);
  10251. }
  10252. if (wantType->IsInterface())
  10253. {
  10254. BfTypeDef* checkActiveTypeDef = NULL;
  10255. bool checkAccessibility = true;
  10256. if (IsInSpecializedSection())
  10257. {
  10258. // When we have a specialized section, the generic params may not be considered "included"
  10259. // in the module that contains the generic type definition. We rely on any casting errors
  10260. // to be thrown on the unspecialized type pass. We have a similar issue with injecting mixins.
  10261. checkAccessibility = false;
  10262. }
  10263. auto checkType = srcType;
  10264. while (checkType != NULL)
  10265. {
  10266. for (auto ifaceInst : checkType->mInterfaces)
  10267. {
  10268. if (ifaceInst.mInterfaceType == wantType)
  10269. {
  10270. if (checkAccessibility)
  10271. {
  10272. if (checkActiveTypeDef == NULL)
  10273. checkActiveTypeDef = GetActiveTypeDef(NULL, false);
  10274. // We need to be lenient when validating generic constraints
  10275. // Otherwise "T<A> where T : IB" declared in a lib won't be able to match a type B in a using project 'C',
  10276. // because this check will see the lib using 'C', which it won't consider visible
  10277. if ((checkActiveTypeDef != NULL) &&
  10278. ((mCurMethodInstance != NULL) && (mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mResolveKind != BfTypeState::ResolveKind_BuildingGenericParams)))
  10279. {
  10280. if ((!srcType->IsTypeMemberAccessible(ifaceInst.mDeclaringType, checkActiveTypeDef)) ||
  10281. (!srcType->IsTypeMemberIncluded(ifaceInst.mDeclaringType, checkActiveTypeDef, this)))
  10282. {
  10283. continue;
  10284. }
  10285. }
  10286. }
  10287. return true;
  10288. }
  10289. }
  10290. checkType = checkType->GetImplBaseType();
  10291. if ((checkType != NULL) && (checkType->mDefineState < BfTypeDefineState_HasInterfaces))
  10292. {
  10293. PopulateType(checkType, BfPopulateType_Interfaces);
  10294. }
  10295. }
  10296. if (srcType->IsTypedPrimitive())
  10297. {
  10298. BfType* underlyingType = srcType->GetUnderlyingType();
  10299. if (underlyingType->IsWrappableType())
  10300. {
  10301. BfTypeInstance* wrappedType = GetWrappedStructType(underlyingType);
  10302. if ((wrappedType != NULL) && (wrappedType != srcType))
  10303. return TypeIsSubTypeOf(wrappedType, wantType, checkAccessibility);
  10304. }
  10305. }
  10306. return false;
  10307. }
  10308. auto srcBaseType = srcType->mBaseType;
  10309. return TypeIsSubTypeOf(srcBaseType, wantType);
  10310. }
  10311. // Positive value means that toType encompasses fromType, negative value means toType is encompassed by formType
  10312. // INT_MAX means the types are not related
  10313. int BfModule::GetTypeDistance(BfType* fromType, BfType* toType)
  10314. {
  10315. if (fromType == toType)
  10316. return 0;
  10317. if (fromType->IsPrimitiveType())
  10318. {
  10319. if (!toType->IsPrimitiveType())
  10320. return INT_MAX;
  10321. auto fromPrimType = (BfPrimitiveType*)fromType;
  10322. auto toPrimType = (BfPrimitiveType*)toType;
  10323. if ((fromPrimType->IsIntegral()) && (toPrimType->IsIntegral()))
  10324. {
  10325. int fromBitSize = fromPrimType->mSize * 8;
  10326. if (fromPrimType->IsSigned())
  10327. fromBitSize--;
  10328. int toBitSize = toPrimType->mSize * 8;
  10329. if (toPrimType->IsSigned())
  10330. toBitSize--;
  10331. return fromBitSize - toBitSize;
  10332. }
  10333. if ((fromPrimType->IsFloat()) && (toPrimType->IsFloat()))
  10334. {
  10335. return (fromPrimType->mSize * 8) - (toPrimType->mSize * 8);
  10336. }
  10337. if (((fromPrimType->IsIntegral()) || (fromPrimType->IsFloat())) &&
  10338. ((toPrimType->IsIntegral()) || (toPrimType->IsFloat())))
  10339. {
  10340. int sizeDiff = (fromPrimType->mSize * 8) - (toPrimType->mSize * 8);
  10341. if (sizeDiff < 0)
  10342. sizeDiff--;
  10343. else
  10344. sizeDiff++;
  10345. return sizeDiff;
  10346. }
  10347. return INT_MAX;
  10348. }
  10349. auto fromTypeInstance = fromType->ToTypeInstance();
  10350. auto toTypeInstance = toType->ToTypeInstance();
  10351. if ((fromTypeInstance != NULL) != (toTypeInstance != NULL))
  10352. return INT_MAX; // Ever valid?
  10353. if ((fromTypeInstance != NULL) && (toTypeInstance != NULL))
  10354. {
  10355. if ((fromTypeInstance->IsNullable()) && (toTypeInstance->IsNullable()))
  10356. return GetTypeDistance(fromTypeInstance->GetUnderlyingType(), toTypeInstance->GetUnderlyingType());
  10357. int inheritDistance = toTypeInstance->mInheritDepth - fromTypeInstance->mInheritDepth;
  10358. auto mostSpecificInstance = (inheritDistance < 0) ? fromTypeInstance : toTypeInstance;
  10359. auto leastSpecificInstance = (inheritDistance < 0) ? toTypeInstance : fromTypeInstance;
  10360. while (mostSpecificInstance != NULL)
  10361. {
  10362. if (mostSpecificInstance == leastSpecificInstance)
  10363. return inheritDistance;
  10364. mostSpecificInstance = mostSpecificInstance->mBaseType;
  10365. }
  10366. }
  10367. return INT_MAX;
  10368. }
  10369. bool BfModule::IsTypeMoreSpecific(BfType* leftType, BfType* rightType)
  10370. {
  10371. if (leftType->IsGenericTypeInstance())
  10372. {
  10373. if (!rightType->IsGenericTypeInstance())
  10374. return true;
  10375. auto leftGenericType = (BfTypeInstance*)leftType;
  10376. auto rightGenericType = (BfTypeInstance*)rightType;
  10377. if (leftGenericType->mTypeDef != rightGenericType->mTypeDef)
  10378. return false;
  10379. bool isBetter = false;
  10380. bool isWorse = false;
  10381. for (int argIdx = 0; argIdx < (int)leftGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); argIdx++)
  10382. {
  10383. if (IsTypeMoreSpecific(leftGenericType->mGenericTypeInfo->mTypeGenericArguments[argIdx], rightGenericType->mGenericTypeInfo->mTypeGenericArguments[argIdx]))
  10384. isBetter = true;
  10385. if (IsTypeMoreSpecific(rightGenericType->mGenericTypeInfo->mTypeGenericArguments[argIdx], leftGenericType->mGenericTypeInfo->mTypeGenericArguments[argIdx]))
  10386. isWorse = true;
  10387. }
  10388. return (isBetter) && (!isWorse);
  10389. }
  10390. return false;
  10391. }
  10392. StringT<128> BfModule::TypeToString(BfType* resolvedType, Array<String>* genericMethodParamNameOverrides)
  10393. {
  10394. BfTypeNameFlags flags = BfTypeNameFlags_None;
  10395. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  10396. flags = BfTypeNameFlag_ResolveGenericParamNames;
  10397. StringT<128> str;
  10398. DoTypeToString(str, resolvedType, flags, genericMethodParamNameOverrides);
  10399. return str;
  10400. }
  10401. StringT<128> BfModule::TypeToString(BfType* resolvedType, BfTypeNameFlags typeNameFlags, Array<String>* genericMethodParamNameOverrides)
  10402. {
  10403. StringT<128> str;
  10404. DoTypeToString(str, resolvedType, typeNameFlags, genericMethodParamNameOverrides);
  10405. return str;
  10406. }
  10407. void BfModule::VariantToString(StringImpl& str, const BfVariant& variant)
  10408. {
  10409. switch (variant.mTypeCode)
  10410. {
  10411. case BfTypeCode_Char8:
  10412. case BfTypeCode_Int8:
  10413. case BfTypeCode_UInt8:
  10414. case BfTypeCode_Int16:
  10415. case BfTypeCode_UInt16:
  10416. case BfTypeCode_Int32:
  10417. str += StrFormat("%d", variant.mInt32);
  10418. break;
  10419. case BfTypeCode_UInt32:
  10420. str += StrFormat("%lu", variant.mUInt32);
  10421. break;
  10422. case BfTypeCode_Int64:
  10423. str += StrFormat("%lld", variant.mInt64);
  10424. break;
  10425. case BfTypeCode_UInt64:
  10426. str += StrFormat("%llu", variant.mInt64);
  10427. break;
  10428. case BfTypeCode_Float:
  10429. {
  10430. char cstr[64];
  10431. ExactMinimalFloatToStr(variant.mSingle, cstr);
  10432. str += cstr;
  10433. if (strchr(cstr, '.') == NULL)
  10434. str += ".0f";
  10435. else
  10436. str += "f";
  10437. }
  10438. break;
  10439. case BfTypeCode_Double:
  10440. {
  10441. char cstr[64];
  10442. ExactMinimalDoubleToStr(variant.mDouble, cstr);
  10443. str += cstr;
  10444. if (strchr(cstr, '.') == NULL)
  10445. str += ".0";
  10446. }
  10447. break;
  10448. case BfTypeCode_Let:
  10449. str += "?";
  10450. break;
  10451. default: break;
  10452. }
  10453. }
  10454. void BfModule::DoTypeToString(StringImpl& str, BfType* resolvedType, BfTypeNameFlags typeNameFlags, Array<String>* genericMethodNameOverrides)
  10455. {
  10456. BP_ZONE("BfModule::DoTypeToString");
  10457. // This is clearly wrong. If we pass in @T0 from a generic type, this would immediately disable the ability to get its name
  10458. /*if (resolvedType->IsUnspecializedType())
  10459. typeNameFlags = (BfTypeNameFlags)(typeNameFlags & ~BfTypeNameFlag_ResolveGenericParamNames);*/
  10460. if (resolvedType->IsBoxed())
  10461. {
  10462. auto boxedType = (BfBoxedType*)resolvedType;
  10463. str += "boxed ";
  10464. DoTypeToString(str, boxedType->mElementType, typeNameFlags, genericMethodNameOverrides);
  10465. if (boxedType->mBoxedFlags == BfBoxedType::BoxedFlags_StructPtr)
  10466. str += "*";
  10467. return;
  10468. }
  10469. else if ((resolvedType->IsArray()) && ((typeNameFlags & BfTypeNameFlag_UseArrayImplType) == 0))
  10470. {
  10471. auto arrayType = (BfArrayType*)resolvedType;
  10472. DoTypeToString(str, arrayType->mGenericTypeInfo->mTypeGenericArguments[0], typeNameFlags, genericMethodNameOverrides);
  10473. str += "[";
  10474. for (int i = 1; i < arrayType->mDimensions; i++)
  10475. str += ",";
  10476. str += "]";
  10477. return;
  10478. }
  10479. else if (resolvedType->IsNullable())
  10480. {
  10481. auto genericType = (BfTypeInstance*)resolvedType;
  10482. auto elementType = genericType->mGenericTypeInfo->mTypeGenericArguments[0];
  10483. DoTypeToString(str, elementType, typeNameFlags, genericMethodNameOverrides);
  10484. str += "?";
  10485. return;
  10486. }
  10487. else if (resolvedType->IsTuple())
  10488. {
  10489. BfTypeInstance* tupleType = (BfTypeInstance*)resolvedType;
  10490. str += "(";
  10491. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  10492. {
  10493. if (fieldIdx > 0)
  10494. str += ", ";
  10495. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  10496. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  10497. BfTypeNameFlags innerFlags = (BfTypeNameFlags)(typeNameFlags & ~(BfTypeNameFlag_OmitNamespace | BfTypeNameFlag_OmitOuterType | BfTypeNameFlag_ExtendedInfo));
  10498. DoTypeToString(str, fieldInstance->GetResolvedType(), innerFlags, genericMethodNameOverrides);
  10499. char c = fieldDef->mName[0];
  10500. if ((c < '0') || (c > '9'))
  10501. {
  10502. str += " ";
  10503. str += fieldDef->mName;
  10504. }
  10505. }
  10506. str += ")";
  10507. return;
  10508. }
  10509. else if (resolvedType->IsDelegateFromTypeRef() || resolvedType->IsFunctionFromTypeRef())
  10510. {
  10511. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance);
  10512. auto delegateType = (BfTypeInstance*)resolvedType;
  10513. auto delegateInfo = resolvedType->GetDelegateInfo();
  10514. if (mCurTypeInstance == delegateType)
  10515. {
  10516. // Don't try to use ourselves for generic param resolution. This should only happen for debug printings from
  10517. // within InitType and such, not actual user-facing display
  10518. mCurTypeInstance = NULL;
  10519. }
  10520. auto methodDef = delegateType->mTypeDef->mMethods[0];
  10521. switch (methodDef->mCallingConvention)
  10522. {
  10523. case BfCallingConvention_Stdcall:
  10524. str += "[StdCall] ";
  10525. break;
  10526. case BfCallingConvention_Fastcall:
  10527. str += "[FastCall] ";
  10528. break;
  10529. default:
  10530. break;
  10531. }
  10532. if (resolvedType->IsDelegateFromTypeRef())
  10533. str += "delegate ";
  10534. else
  10535. str += "function ";
  10536. DoTypeToString(str, delegateInfo->mReturnType, typeNameFlags, genericMethodNameOverrides);
  10537. str += "(";
  10538. bool isFirstParam = true;//
  10539. for (int paramIdx = 0; paramIdx < methodDef->mParams.size(); paramIdx++)
  10540. {
  10541. if (!isFirstParam)
  10542. str += ", ";
  10543. auto paramDef = methodDef->mParams[paramIdx];
  10544. BfTypeNameFlags innerFlags = (BfTypeNameFlags)(typeNameFlags & ~(BfTypeNameFlag_OmitNamespace | BfTypeNameFlag_OmitOuterType | BfTypeNameFlag_ExtendedInfo));
  10545. auto paramType = delegateInfo->mParams[paramIdx];
  10546. if ((paramIdx == 0) && (delegateInfo->mHasExplicitThis))
  10547. {
  10548. if ((methodDef->mIsMutating) && (paramType->IsValueType()))
  10549. str += "mut ";
  10550. }
  10551. DoTypeToString(str, paramType, innerFlags, genericMethodNameOverrides);
  10552. if (!paramDef->mName.IsEmpty())
  10553. {
  10554. str += " ";
  10555. str += paramDef->mName;
  10556. }
  10557. isFirstParam = false;
  10558. }
  10559. str += ")";
  10560. return;
  10561. }
  10562. else if (resolvedType->IsMethodRef())
  10563. {
  10564. auto methodRefType = (BfMethodRefType*)resolvedType;
  10565. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  10566. if (methodRefType->IsDeleting())
  10567. {
  10568. str += "DELETED METHODREF";
  10569. return;
  10570. }
  10571. if (methodInstance == NULL)
  10572. {
  10573. str += "method reference NULL";
  10574. return;
  10575. }
  10576. str += "method reference ";
  10577. str += MethodToString(methodInstance);
  10578. return;
  10579. }
  10580. else if (resolvedType->IsTypeInstance())
  10581. {
  10582. BfTypeInstance* typeInstance = (BfTypeInstance*)resolvedType;
  10583. if ((typeNameFlags & BfTypeNameFlag_ExtendedInfo) != 0)
  10584. {
  10585. if (typeInstance->mTypeDef->mIsDelegate)
  10586. str += "delegate ";
  10587. else if (typeInstance->mTypeDef->mIsFunction)
  10588. str += "function ";
  10589. else if (typeInstance->mTypeDef->mTypeCode == BfTypeCode_Object)
  10590. str += "class ";
  10591. else if (typeInstance->mTypeDef->mTypeCode == BfTypeCode_Enum)
  10592. str += "enum ";
  10593. else if (typeInstance->mTypeDef->mTypeCode == BfTypeCode_Struct)
  10594. str += "struct ";
  10595. else if (typeInstance->mTypeDef->mTypeCode == BfTypeCode_TypeAlias)
  10596. str += "typealias ";
  10597. }
  10598. bool omitNamespace = (typeNameFlags & BfTypeNameFlag_OmitNamespace) != 0;
  10599. if ((typeNameFlags & BfTypeNameFlag_ReduceName) != 0)
  10600. {
  10601. for (auto& checkNamespace : mCurTypeInstance->mTypeDef->mNamespaceSearch)
  10602. {
  10603. if (checkNamespace == typeInstance->mTypeDef->mNamespace)
  10604. omitNamespace = true;
  10605. }
  10606. }
  10607. if ((!typeInstance->mTypeDef->mNamespace.IsEmpty()) && (!omitNamespace))
  10608. {
  10609. if (!typeInstance->mTypeDef->mNamespace.IsEmpty())
  10610. {
  10611. typeInstance->mTypeDef->mNamespace.ToString(str);
  10612. if (!typeInstance->mTypeDef->IsGlobalsContainer())
  10613. str += '.';
  10614. }
  10615. }
  10616. SizedArray<BfTypeDef*, 8> typeDefStack;
  10617. BfTypeDef* endTypeDef = NULL;
  10618. if (((typeNameFlags & BfTypeNameFlag_ReduceName) != 0) && (mCurTypeInstance != NULL))
  10619. {
  10620. auto checkTypeInst = typeInstance;
  10621. auto outerTypeInst = GetOuterType(checkTypeInst);
  10622. if (outerTypeInst != NULL)
  10623. {
  10624. checkTypeInst = outerTypeInst;
  10625. auto checkTypeDef = checkTypeInst->mTypeDef;
  10626. auto checkCurTypeInst = mCurTypeInstance; // Only used for ReduceName
  10627. BfTypeDef* checkCurTypeDef = NULL;
  10628. if (checkCurTypeInst != NULL)
  10629. checkCurTypeDef = checkCurTypeInst->mTypeDef;
  10630. while (checkCurTypeDef->mNestDepth > checkTypeDef->mNestDepth)
  10631. {
  10632. checkCurTypeInst = GetOuterType(checkCurTypeInst);
  10633. checkCurTypeDef = checkCurTypeInst->mTypeDef;
  10634. }
  10635. while (checkTypeDef != NULL)
  10636. {
  10637. if (TypeIsSubTypeOf(checkCurTypeInst, checkTypeInst))
  10638. {
  10639. endTypeDef = checkTypeDef;
  10640. break;
  10641. }
  10642. checkCurTypeInst = GetOuterType(checkCurTypeInst);
  10643. if (checkCurTypeInst == NULL)
  10644. break;
  10645. checkCurTypeDef = checkCurTypeInst->mTypeDef;
  10646. checkTypeInst = GetOuterType(checkTypeInst);
  10647. if (checkTypeInst == NULL)
  10648. break;
  10649. checkTypeDef = checkTypeInst->mTypeDef;
  10650. }
  10651. }
  10652. }
  10653. BfTypeDef* checkTypeDef = typeInstance->mTypeDef;
  10654. while (checkTypeDef != NULL)
  10655. {
  10656. typeDefStack.Add(checkTypeDef);
  10657. checkTypeDef = checkTypeDef->mOuterType;
  10658. if ((typeNameFlags & BfTypeNameFlag_OmitOuterType) != 0)
  10659. break;
  10660. if (checkTypeDef == endTypeDef)
  10661. break;
  10662. }
  10663. while (!typeDefStack.IsEmpty())
  10664. {
  10665. BfTypeDef* checkTypeDef = typeDefStack.back();
  10666. int depth = (int)typeDefStack.size() - 1;
  10667. typeDefStack.pop_back();
  10668. if (checkTypeDef->IsGlobalsContainer())
  10669. {
  10670. if ((typeNameFlags & BfTypeNameFlag_AddGlobalContainerName) != 0)
  10671. {
  10672. str += "G$";
  10673. str += checkTypeDef->mProject->mName;
  10674. }
  10675. }
  10676. else
  10677. {
  10678. checkTypeDef->mName->ToString(str);
  10679. if (!checkTypeDef->mGenericParamDefs.IsEmpty())
  10680. {
  10681. for (int ofs = 0; ofs < 3; ofs++)
  10682. {
  10683. int checkIdx = (int)str.length() - 1 - ofs;
  10684. if (checkIdx < 0)
  10685. break;
  10686. if (str[checkIdx] == '`')
  10687. {
  10688. str.RemoveToEnd(checkIdx);
  10689. break;
  10690. }
  10691. }
  10692. }
  10693. if (((typeNameFlags & BfTypeNameFlag_DisambiguateDups) != 0) && (checkTypeDef->mDupDetectedRevision != -1))
  10694. {
  10695. str += StrFormat("_%p", checkTypeDef);
  10696. }
  10697. }
  10698. int prevGenericParamCount = 0;
  10699. if (checkTypeDef->mOuterType != NULL)
  10700. {
  10701. prevGenericParamCount = (int)checkTypeDef->mOuterType->mGenericParamDefs.size();
  10702. }
  10703. if (resolvedType->IsGenericTypeInstance())
  10704. {
  10705. auto genericTypeInst = (BfTypeInstance*)resolvedType;
  10706. if (prevGenericParamCount != (int)checkTypeDef->mGenericParamDefs.size())
  10707. {
  10708. str += '<';
  10709. for (int i = prevGenericParamCount; i < (int)checkTypeDef->mGenericParamDefs.size(); i++)
  10710. {
  10711. BfType* typeGenericArg = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[i];
  10712. if (typeGenericArg->IsGenericParam())
  10713. {
  10714. if ((typeNameFlags & BfTypeNameFlag_ResolveGenericParamNames) == 0)
  10715. {
  10716. // We don't want the param names, just the commas (this is an unspecialized type reference)
  10717. if (i > prevGenericParamCount)
  10718. str += ',';
  10719. if ((typeNameFlags & BfTypeNameFlag_UseUnspecializedGenericParamNames) != 0)
  10720. {
  10721. str += checkTypeDef->mGenericParamDefs[i]->mName;
  10722. }
  10723. continue;
  10724. }
  10725. }
  10726. if (i > prevGenericParamCount)
  10727. str += ", ";
  10728. DoTypeToString(str, typeGenericArg, (BfTypeNameFlags)(typeNameFlags & ~(BfTypeNameFlag_OmitNamespace | BfTypeNameFlag_OmitOuterType | BfTypeNameFlag_ExtendedInfo)), genericMethodNameOverrides);
  10729. }
  10730. str += '>';
  10731. }
  10732. }
  10733. if (depth > 0)
  10734. str += '.';
  10735. };
  10736. if (typeInstance->IsTypeAlias())
  10737. {
  10738. if ((typeNameFlags & BfTypeNameFlag_ExtendedInfo) != 0)
  10739. {
  10740. auto underlyingType = typeInstance->GetUnderlyingType();
  10741. if (underlyingType != NULL)
  10742. {
  10743. str += " = ";
  10744. DoTypeToString(str, underlyingType, (BfTypeNameFlags)(typeNameFlags & ~(BfTypeNameFlag_OmitNamespace | BfTypeNameFlag_OmitOuterType | BfTypeNameFlag_ExtendedInfo)));
  10745. }
  10746. }
  10747. }
  10748. return;
  10749. }
  10750. else if (resolvedType->IsPrimitiveType())
  10751. {
  10752. auto primitiveType = (BfPrimitiveType*)resolvedType;
  10753. if (!primitiveType->mTypeDef->mNamespace.IsEmpty())
  10754. {
  10755. primitiveType->mTypeDef->mNamespace.ToString(str);
  10756. str += '.';
  10757. primitiveType->mTypeDef->mName->ToString(str);
  10758. return;
  10759. }
  10760. else
  10761. {
  10762. primitiveType->mTypeDef->mName->ToString(str);
  10763. return;
  10764. }
  10765. }
  10766. else if (resolvedType->IsPointer())
  10767. {
  10768. auto pointerType = (BfPointerType*)resolvedType;
  10769. DoTypeToString(str, pointerType->mElementType, typeNameFlags, genericMethodNameOverrides);
  10770. str += '*';
  10771. return;
  10772. }
  10773. else if (resolvedType->IsGenericParam())
  10774. {
  10775. bool doResolveGenericParams = (typeNameFlags & BfTypeNameFlag_ResolveGenericParamNames) != 0;
  10776. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  10777. doResolveGenericParams = false;
  10778. auto genericParam = (BfGenericParamType*)resolvedType;
  10779. if (genericParam->mGenericParamKind == BfGenericParamKind_Method)
  10780. {
  10781. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecializedVariation))
  10782. doResolveGenericParams = false;
  10783. }
  10784. if (!doResolveGenericParams)
  10785. {
  10786. if (genericParam->mGenericParamKind == BfGenericParamKind_Method)
  10787. {
  10788. if (genericMethodNameOverrides != NULL)
  10789. {
  10790. BF_ASSERT(genericParam->mGenericParamIdx < genericMethodNameOverrides->mSize);
  10791. if (genericParam->mGenericParamIdx < genericMethodNameOverrides->mSize)
  10792. {
  10793. str += (*genericMethodNameOverrides)[genericParam->mGenericParamIdx];
  10794. return;
  10795. }
  10796. }
  10797. str += StrFormat("@M%d", genericParam->mGenericParamIdx);
  10798. return;
  10799. }
  10800. str += StrFormat("@T%d", genericParam->mGenericParamIdx);
  10801. return;
  10802. }
  10803. if ((genericParam->mGenericParamKind == BfGenericParamKind_Type) && (mCurTypeInstance == NULL))
  10804. {
  10805. str += StrFormat("@T%d", genericParam->mGenericParamIdx);
  10806. return;
  10807. }
  10808. if (genericParam->mGenericParamKind == BfGenericParamKind_Method)
  10809. {
  10810. if (genericMethodNameOverrides != NULL)
  10811. {
  10812. str += (*genericMethodNameOverrides)[genericParam->mGenericParamIdx];
  10813. return;
  10814. }
  10815. if (mCurMethodInstance == NULL)
  10816. {
  10817. str += StrFormat("@M%d", genericParam->mGenericParamIdx);
  10818. return;
  10819. }
  10820. }
  10821. //TEMPORARY
  10822. if (genericParam->mGenericParamKind == BfGenericParamKind_Type)
  10823. {
  10824. auto curTypeInstance = mCurTypeInstance;
  10825. if (mCurMethodInstance != NULL)
  10826. curTypeInstance = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  10827. if ((curTypeInstance == NULL) || (!curTypeInstance->IsGenericTypeInstance()))
  10828. {
  10829. str += StrFormat("@T%d", genericParam->mGenericParamIdx);
  10830. return;
  10831. }
  10832. }
  10833. auto genericParamInstance = GetGenericParamInstance(genericParam);
  10834. auto genericParamDef = genericParamInstance->GetGenericParamDef();
  10835. if (genericParamDef != NULL)
  10836. str += genericParamInstance->GetGenericParamDef()->mName;
  10837. else
  10838. str += "external generic " + TypeToString(genericParamInstance->mExternType, typeNameFlags, genericMethodNameOverrides);
  10839. return;
  10840. }
  10841. else if (resolvedType->IsRef())
  10842. {
  10843. auto refType = (BfRefType*)resolvedType;
  10844. if (refType->mRefKind == BfRefType::RefKind_Ref)
  10845. {
  10846. str += "ref ";
  10847. DoTypeToString(str, refType->mElementType, typeNameFlags, genericMethodNameOverrides);
  10848. return;
  10849. }
  10850. else if (refType->mRefKind == BfRefType::RefKind_Out)
  10851. {
  10852. str += "out ";
  10853. DoTypeToString(str, refType->mElementType, typeNameFlags, genericMethodNameOverrides);
  10854. return;
  10855. }
  10856. else
  10857. {
  10858. str += "mut ";
  10859. DoTypeToString(str, refType->mElementType, typeNameFlags, genericMethodNameOverrides);
  10860. return;
  10861. }
  10862. }
  10863. else if (resolvedType->IsModifiedTypeType())
  10864. {
  10865. auto retTypeType = (BfModifiedTypeType*)resolvedType;
  10866. str += BfTokenToString(retTypeType->mModifiedKind);
  10867. str += "(";
  10868. DoTypeToString(str, retTypeType->mElementType, typeNameFlags, genericMethodNameOverrides);
  10869. str += ")";
  10870. return;
  10871. }
  10872. else if (resolvedType->IsConcreteInterfaceType())
  10873. {
  10874. auto concreteTypeType = (BfConcreteInterfaceType*)resolvedType;
  10875. str += "concrete ";
  10876. DoTypeToString(str, concreteTypeType->mInterface, typeNameFlags, genericMethodNameOverrides);
  10877. return;
  10878. }
  10879. else if (resolvedType->IsUnknownSizedArray())
  10880. {
  10881. auto arrayType = (BfUnknownSizedArrayType*)resolvedType;
  10882. DoTypeToString(str, arrayType->mElementType, typeNameFlags, genericMethodNameOverrides);
  10883. str += "[";
  10884. DoTypeToString(str, arrayType->mElementCountSource, typeNameFlags, genericMethodNameOverrides);
  10885. str += "]";
  10886. return;
  10887. }
  10888. else if (resolvedType->IsSizedArray())
  10889. {
  10890. auto arrayType = (BfSizedArrayType*)resolvedType;
  10891. if (arrayType->mElementCount == -1)
  10892. {
  10893. DoTypeToString(str, arrayType->mElementType, typeNameFlags, genericMethodNameOverrides);
  10894. str += "[?]";
  10895. return;
  10896. }
  10897. DoTypeToString(str, arrayType->mElementType, typeNameFlags, genericMethodNameOverrides);
  10898. str += StrFormat("[%d]", arrayType->mElementCount);
  10899. return;
  10900. }
  10901. else if (resolvedType->IsConstExprValue())
  10902. {
  10903. auto constExprValueType = (BfConstExprValueType*)resolvedType;
  10904. str += "const ";
  10905. DoTypeToString(str, constExprValueType->mType, typeNameFlags, genericMethodNameOverrides);
  10906. str += " ";
  10907. VariantToString(str, constExprValueType->mValue);
  10908. return;
  10909. }
  10910. BFMODULE_FATAL(this, "Not implemented");
  10911. str += "???";
  10912. return;
  10913. }