BfModuleTypeUtils.cpp 554 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374
  1. #include "BeefySysLib/util/AllocDebug.h"
  2. #include "BfCompiler.h"
  3. #include "BfSystem.h"
  4. #include "BfParser.h"
  5. #include "BfReducer.h"
  6. #include "BfCodeGen.h"
  7. #include "BfExprEvaluator.h"
  8. #include <fcntl.h>
  9. #include "BfConstResolver.h"
  10. #include "BfMangler.h"
  11. #include "BeefySysLib/util/PerfTimer.h"
  12. #include "BeefySysLib/util/BeefPerf.h"
  13. #include "BeefySysLib/util/StackHelper.h"
  14. #include "BfSourceClassifier.h"
  15. #include "BfAutoComplete.h"
  16. #include "BfDemangler.h"
  17. #include "BfResolvePass.h"
  18. #include "BfFixits.h"
  19. #include "BfIRCodeGen.h"
  20. #include "BfDefBuilder.h"
  21. #include "CeMachine.h"
  22. //////////////////////////////////////////////////////////////////////////
  23. int32 GetNumLowZeroBits(int32 n)
  24. {
  25. if (n == 0)
  26. return 32;
  27. int i = 0;
  28. while ((n & 1) == 0)
  29. {
  30. n = (int32)((uint32)n >> 1);
  31. i++;
  32. }
  33. return i;
  34. }
  35. //////////////////////////////////////////////////////////////////////////
  36. USING_NS_BF;
  37. BfGenericExtensionEntry* BfModule::BuildGenericExtensionInfo(BfTypeInstance* genericTypeInst, BfTypeDef* partialTypeDef)
  38. {
  39. if (!partialTypeDef->IsExtension())
  40. return NULL;
  41. if (partialTypeDef->mGenericParamDefs.size() != genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size())
  42. {
  43. AssertErrorState();
  44. return NULL;
  45. }
  46. BfGenericExtensionInfo* genericExtensionInfo = genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo;
  47. if (genericExtensionInfo == NULL)
  48. {
  49. genericExtensionInfo = new BfGenericExtensionInfo();
  50. genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo = genericExtensionInfo;
  51. }
  52. BfTypeState typeState;
  53. typeState.mPrevState = mContext->mCurTypeState;
  54. typeState.mType = genericTypeInst;
  55. typeState.mCurTypeDef = partialTypeDef;
  56. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  57. BfGenericExtensionEntry* genericExEntry;
  58. genericExtensionInfo->mExtensionMap.TryAdd(partialTypeDef, NULL, &genericExEntry);
  59. int startDefGenericParamIdx = (int)genericExEntry->mGenericParams.size();
  60. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size(); paramIdx++)
  61. {
  62. auto genericParamInstance = new BfGenericTypeParamInstance(partialTypeDef, paramIdx);
  63. genericParamInstance->mExternType = GetGenericParamType(BfGenericParamKind_Type, paramIdx);
  64. auto prevPtr = genericExEntry->mGenericParams.mVals;
  65. genericExEntry->mGenericParams.push_back(genericParamInstance);
  66. }
  67. for (int externConstraintIdx = 0; externConstraintIdx < (int)partialTypeDef->mExternalConstraints.size(); externConstraintIdx++)
  68. {
  69. auto& genericConstraint = partialTypeDef->mExternalConstraints[externConstraintIdx];
  70. auto genericParamInstance = new BfGenericTypeParamInstance(partialTypeDef, externConstraintIdx + (int)partialTypeDef->mGenericParamDefs.size());
  71. genericParamInstance->mExternType = ResolveTypeRef(genericConstraint.mTypeRef, BfPopulateType_Identity);
  72. auto autoComplete = mCompiler->GetAutoComplete();
  73. if (autoComplete != NULL)
  74. autoComplete->CheckTypeRef(genericConstraint.mTypeRef, false);
  75. if (genericParamInstance->mExternType == NULL)
  76. genericParamInstance->mExternType = GetPrimitiveType(BfTypeCode_Var);
  77. ResolveGenericParamConstraints(genericParamInstance, genericTypeInst->IsUnspecializedType());
  78. genericExEntry->mGenericParams.push_back(genericParamInstance);
  79. }
  80. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size(); paramIdx++)
  81. {
  82. auto genericParamInstance = genericExEntry->mGenericParams[paramIdx];
  83. auto rootGenericParamInstance = genericTypeInst->mGenericTypeInfo->mGenericParams[paramIdx];
  84. genericParamInstance->mTypeConstraint = rootGenericParamInstance->mTypeConstraint;
  85. genericParamInstance->mInterfaceConstraints = rootGenericParamInstance->mInterfaceConstraints;
  86. genericParamInstance->mGenericParamFlags = (BfGenericParamFlags)(genericParamInstance->mGenericParamFlags | rootGenericParamInstance->mGenericParamFlags);
  87. ResolveGenericParamConstraints(genericParamInstance, genericTypeInst->IsUnspecializedType());
  88. }
  89. for (auto genericParam : genericExEntry->mGenericParams)
  90. AddDependency(genericParam, mCurTypeInstance);
  91. ValidateGenericParams(BfGenericParamKind_Type,
  92. Span<BfGenericParamInstance*>((BfGenericParamInstance**)genericExEntry->mGenericParams.mVals,
  93. genericExEntry->mGenericParams.mSize));
  94. return genericExEntry;
  95. }
  96. bool BfModule::InitGenericParams(BfType* resolvedTypeRef)
  97. {
  98. BfTypeState typeState;
  99. typeState.mPrevState = mContext->mCurTypeState;
  100. typeState.mResolveKind = BfTypeState::ResolveKind_BuildingGenericParams;
  101. typeState.mType = resolvedTypeRef;
  102. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  103. BF_ASSERT(mCurMethodInstance == NULL);
  104. auto genericTypeInst = resolvedTypeRef->ToGenericTypeInstance();
  105. genericTypeInst->mGenericTypeInfo->mInitializedGenericParams = true;
  106. if (genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.IsEmpty())
  107. return true;
  108. if (genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0]->IsGenericParam())
  109. {
  110. BF_ASSERT(genericTypeInst->mGenericTypeInfo->mIsUnspecialized);
  111. }
  112. auto typeDef = genericTypeInst->mTypeDef;
  113. int startDefGenericParamIdx = (int)genericTypeInst->mGenericTypeInfo->mGenericParams.size();
  114. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size(); paramIdx++)
  115. {
  116. auto genericParamInstance = new BfGenericTypeParamInstance(typeDef, paramIdx);
  117. genericParamInstance->mExternType = GetGenericParamType(BfGenericParamKind_Type, paramIdx);
  118. genericTypeInst->mGenericTypeInfo->mGenericParams.push_back(genericParamInstance);
  119. }
  120. for (int externConstraintIdx = 0; externConstraintIdx < (int)typeDef->mExternalConstraints.size(); externConstraintIdx++)
  121. {
  122. auto genericParamInstance = new BfGenericTypeParamInstance(typeDef, externConstraintIdx + (int)typeDef->mGenericParamDefs.size());
  123. genericTypeInst->mGenericTypeInfo->mGenericParams.push_back(genericParamInstance);
  124. }
  125. return true;
  126. }
  127. bool BfModule::FinishGenericParams(BfType* resolvedTypeRef)
  128. {
  129. BfTypeState typeState;
  130. typeState.mPrevState = mContext->mCurTypeState;
  131. typeState.mResolveKind = BfTypeState::ResolveKind_BuildingGenericParams;
  132. typeState.mType = resolvedTypeRef;
  133. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  134. Array<BfTypeReference*> deferredResolveTypes;
  135. BF_ASSERT(mCurMethodInstance == NULL);
  136. auto genericTypeInst = resolvedTypeRef->ToGenericTypeInstance();
  137. genericTypeInst->mGenericTypeInfo->mFinishedGenericParams = true;
  138. if (genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0]->IsGenericParam())
  139. {
  140. BF_ASSERT(genericTypeInst->mGenericTypeInfo->mIsUnspecialized);
  141. }
  142. auto typeDef = genericTypeInst->mTypeDef;
  143. int startDefGenericParamIdx = (int)genericTypeInst->mGenericTypeInfo->mGenericParams.size();
  144. if ((!resolvedTypeRef->IsTuple()) && (!resolvedTypeRef->IsDelegateFromTypeRef()) && (!resolvedTypeRef->IsFunctionFromTypeRef()))
  145. {
  146. startDefGenericParamIdx = startDefGenericParamIdx -
  147. (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size() -
  148. (int)typeDef->mExternalConstraints.size();
  149. }
  150. BF_ASSERT(startDefGenericParamIdx >= 0);
  151. if (!typeDef->mPartials.empty())
  152. {
  153. BitSet prevConstraintsPassedSet;
  154. if (!genericTypeInst->IsUnspecializedType())
  155. {
  156. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  157. {
  158. auto genericExtensionInfo = genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo;
  159. prevConstraintsPassedSet = genericExtensionInfo->mConstraintsPassedSet;
  160. genericExtensionInfo->mConstraintsPassedSet.Clear();
  161. }
  162. }
  163. int extensionCount = 0;
  164. BfLogSysM("BfModule::FinishGenericParams %p\n", resolvedTypeRef);
  165. for (auto partialTypeDef : typeDef->mPartials)
  166. {
  167. if (!partialTypeDef->IsExtension())
  168. {
  169. typeState.mCurTypeDef = partialTypeDef;
  170. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mGenericTypeInfo->mGenericParams.size(); paramIdx++)
  171. {
  172. auto genericParamInstance = genericTypeInst->mGenericTypeInfo->mGenericParams[paramIdx];
  173. auto genericParamDef = genericParamInstance->GetGenericParamDef();
  174. if (paramIdx < (int)typeDef->mGenericParamDefs.size())
  175. {
  176. genericParamInstance->mExternType = GetGenericParamType(BfGenericParamKind_Type, paramIdx);
  177. }
  178. else
  179. {
  180. auto externConstraintDef = genericParamInstance->GetExternConstraintDef();
  181. genericParamInstance->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  182. if (genericParamInstance->mExternType == NULL)
  183. genericParamInstance->mExternType = GetPrimitiveType(BfTypeCode_Var);
  184. }
  185. ResolveGenericParamConstraints(genericParamInstance, genericTypeInst->IsUnspecializedType(), &deferredResolveTypes);
  186. if (genericParamDef != NULL)
  187. {
  188. for (auto nameNode : genericParamDef->mNameNodes)
  189. {
  190. HandleTypeGenericParamRef(nameNode, typeDef, paramIdx);
  191. }
  192. }
  193. }
  194. }
  195. else
  196. {
  197. auto genericExEntry = BuildGenericExtensionInfo(genericTypeInst, partialTypeDef);
  198. if (genericExEntry == NULL)
  199. continue;
  200. auto genericExtensionInfo = genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo;
  201. if (extensionCount == 0)
  202. genericExtensionInfo->mConstraintsPassedSet.Resize(typeDef->mPartials.mSize);
  203. extensionCount++;
  204. if (!genericTypeInst->IsUnspecializedType())
  205. {
  206. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  207. for (int paramIdx = 0; paramIdx < genericExEntry->mGenericParams.size(); paramIdx++)
  208. {
  209. auto genericParamInstance = genericExEntry->mGenericParams[paramIdx];
  210. BfGenericParamSource genericParamSource;
  211. genericParamSource.mCheckAccessibility = false;
  212. genericParamSource.mTypeInstance = genericTypeInst;
  213. BfError* error = NULL;
  214. BfType* genericArg;
  215. if (paramIdx < (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size())
  216. {
  217. genericArg = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[paramIdx];
  218. }
  219. else
  220. {
  221. genericArg = genericParamInstance->mExternType;
  222. }
  223. if ((genericArg == NULL) || (!CheckGenericConstraints(genericParamSource, genericArg, NULL, genericParamInstance, NULL, &error)))
  224. {
  225. genericExEntry->mConstraintsPassed = false;
  226. }
  227. }
  228. }
  229. if (genericExEntry->mConstraintsPassed)
  230. genericExtensionInfo->mConstraintsPassedSet.Set(partialTypeDef->mPartialIdx);
  231. BfLogSysM("BfModule::FinishGenericParams %p partialTypeDef:%p passed:%d\n", resolvedTypeRef, partialTypeDef, genericExEntry->mConstraintsPassed);
  232. }
  233. }
  234. auto genericExtensionInfo = genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo;
  235. if ((extensionCount > 0) && (!prevConstraintsPassedSet.IsEmpty()) && (genericExtensionInfo->mConstraintsPassedSet != prevConstraintsPassedSet))
  236. {
  237. mContext->QueueMidCompileRebuildDependentTypes(genericTypeInst, "mConstraintsPassedSet changed");
  238. }
  239. }
  240. else
  241. {
  242. for (int paramIdx = startDefGenericParamIdx; paramIdx < (int)genericTypeInst->mGenericTypeInfo->mGenericParams.size(); paramIdx++)
  243. {
  244. auto genericParamInstance = genericTypeInst->mGenericTypeInfo->mGenericParams[paramIdx];
  245. if (paramIdx < (int)typeDef->mGenericParamDefs.size())
  246. {
  247. genericParamInstance->mExternType = GetGenericParamType(BfGenericParamKind_Type, paramIdx);
  248. }
  249. else
  250. {
  251. auto externConstraintDef = genericParamInstance->GetExternConstraintDef();
  252. genericParamInstance->mExternType = ResolveTypeRef(externConstraintDef->mTypeRef);
  253. auto autoComplete = mCompiler->GetAutoComplete();
  254. if (autoComplete != NULL)
  255. autoComplete->CheckTypeRef(externConstraintDef->mTypeRef, false);
  256. if (genericParamInstance->mExternType != NULL)
  257. {
  258. //
  259. }
  260. else
  261. genericParamInstance->mExternType = GetPrimitiveType(BfTypeCode_Var);
  262. }
  263. ResolveGenericParamConstraints(genericParamInstance, genericTypeInst->IsUnspecializedType(), &deferredResolveTypes);
  264. auto genericParamDef = genericParamInstance->GetGenericParamDef();
  265. if (genericParamDef != NULL)
  266. {
  267. for (auto nameNode : genericParamDef->mNameNodes)
  268. {
  269. HandleTypeGenericParamRef(nameNode, typeDef, paramIdx);
  270. }
  271. }
  272. }
  273. }
  274. for (auto typeRef : deferredResolveTypes)
  275. auto constraintType = ResolveTypeRef(typeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_None);
  276. ValidateGenericParams(BfGenericParamKind_Type,
  277. Span<BfGenericParamInstance*>((BfGenericParamInstance**)genericTypeInst->mGenericTypeInfo->mGenericParams.mVals,
  278. genericTypeInst->mGenericTypeInfo->mGenericParams.mSize));
  279. for (auto genericParam : genericTypeInst->mGenericTypeInfo->mGenericParams)
  280. AddDependency(genericParam, mCurTypeInstance);
  281. return true;
  282. }
  283. void BfModule::ValidateGenericParams(BfGenericParamKind genericParamKind, Span<BfGenericParamInstance*> genericParams)
  284. {
  285. std::function<void(BfType*, Array<BfGenericParamType*>&)> _CheckType = [&](BfType* type, Array<BfGenericParamType*>& foundParams)
  286. {
  287. if (type == NULL)
  288. return;
  289. if (!type->IsGenericParam())
  290. return;
  291. auto genericParamType = (BfGenericParamType*)type;
  292. if (genericParamType->mGenericParamKind != genericParamKind)
  293. return;
  294. auto genericParam = genericParams[genericParamType->mGenericParamIdx];
  295. if (genericParam->mTypeConstraint == NULL)
  296. return;
  297. if (foundParams.Contains(genericParamType))
  298. {
  299. String error = "Circular constraint dependency between ";
  300. for (int i = 0; i < foundParams.mSize; i++)
  301. {
  302. auto foundParam = foundParams[i];
  303. if (i > 0)
  304. error += " and ";
  305. error += TypeToString(foundParam, BfTypeNameFlag_ResolveGenericParamNames);
  306. // Remove errored type constraint
  307. genericParams[foundParam->mGenericParamIdx]->mTypeConstraint = NULL;
  308. }
  309. if (foundParams.mSize == 1)
  310. error += " and itself";
  311. Fail(error, genericParams[genericParamType->mGenericParamIdx]->GetRefNode());
  312. return;
  313. }
  314. foundParams.Add(genericParamType);
  315. _CheckType(genericParam->mTypeConstraint, foundParams);
  316. foundParams.pop_back();
  317. };
  318. for (auto genericParam : genericParams)
  319. {
  320. if (genericParam->mTypeConstraint != NULL)
  321. {
  322. Array<BfGenericParamType*> foundParams;
  323. _CheckType(genericParam->mTypeConstraint, foundParams);
  324. }
  325. }
  326. }
  327. bool BfModule::ValidateGenericConstraints(BfAstNode* typeRef, BfTypeInstance* genericTypeInst, bool ignoreErrors)
  328. {
  329. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsTypeAlias()) && (mCurTypeInstance->IsGenericTypeInstance()))
  330. {
  331. // Don't validate constraints during the population of a concrete generic type alias instance, we want to
  332. // throw those errors at the usage sites
  333. return true;
  334. }
  335. // We don't validate constraints for things like Tuples/Delegates
  336. if (genericTypeInst->IsOnDemand())
  337. return true;
  338. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, mIgnoreErrors || ignoreErrors);
  339. genericTypeInst->mGenericTypeInfo->mValidatedGenericConstraints = true;
  340. if (!genericTypeInst->mGenericTypeInfo->mFinishedGenericParams)
  341. mContext->mUnreifiedModule->PopulateType(genericTypeInst, BfPopulateType_Interfaces_All);
  342. if (genericTypeInst->IsTypeAlias())
  343. {
  344. auto underlyingType = genericTypeInst->GetUnderlyingType();
  345. if ((underlyingType != NULL) && (underlyingType->IsGenericTypeInstance()))
  346. {
  347. auto underlyingGenericType = underlyingType->ToGenericTypeInstance();
  348. mContext->mUnreifiedModule->PopulateType(underlyingType, BfPopulateType_Declaration);
  349. bool result = ValidateGenericConstraints(typeRef, underlyingGenericType, ignoreErrors);
  350. if (underlyingGenericType->mGenericTypeInfo->mHadValidateErrors)
  351. genericTypeInst->mGenericTypeInfo->mHadValidateErrors = true;
  352. return result;
  353. }
  354. return true;
  355. }
  356. for (auto typeArg : genericTypeInst->mGenericTypeInfo->mTypeGenericArguments)
  357. {
  358. auto genericArg = typeArg->ToGenericTypeInstance();
  359. if (genericArg != NULL)
  360. genericTypeInst->mGenericTypeInfo->mMaxGenericDepth = BF_MAX(genericTypeInst->mGenericTypeInfo->mMaxGenericDepth, genericArg->mGenericTypeInfo->mMaxGenericDepth + 1);
  361. }
  362. auto typeDef = genericTypeInst->mTypeDef;
  363. int startGenericParamIdx = 0;
  364. if (typeDef->mOuterType != NULL)
  365. {
  366. startGenericParamIdx = typeDef->mOuterType->mGenericParamDefs.mSize + typeDef->mOuterType->mExternalConstraints.mSize;
  367. auto outerType = GetOuterType(genericTypeInst);
  368. mContext->mUnreifiedModule->PopulateType(outerType, BfPopulateType_Declaration);
  369. if ((outerType->mGenericTypeInfo != NULL) && (outerType->mGenericTypeInfo->mHadValidateErrors))
  370. genericTypeInst->mGenericTypeInfo->mHadValidateErrors = true;
  371. }
  372. for (int paramIdx = startGenericParamIdx; paramIdx < (int)genericTypeInst->mGenericTypeInfo->mGenericParams.size(); paramIdx++)
  373. {
  374. auto genericParamInstance = genericTypeInst->mGenericTypeInfo->mGenericParams[paramIdx];
  375. BfType* genericArg;
  376. if (paramIdx < (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size())
  377. {
  378. genericArg = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[paramIdx];
  379. }
  380. else
  381. {
  382. genericArg = genericParamInstance->mExternType;
  383. }
  384. BfError* error = NULL;
  385. if ((genericArg == NULL) || (!CheckGenericConstraints(BfGenericParamSource(genericTypeInst), genericArg, typeRef, genericParamInstance, NULL, &error)))
  386. {
  387. if (!genericTypeInst->IsUnspecializedTypeVariation())
  388. genericTypeInst->mGenericTypeInfo->mHadValidateErrors = true;
  389. return false;
  390. }
  391. }
  392. return true;
  393. }
  394. BfType* BfModule::ResolveGenericMethodTypeRef(BfTypeReference* typeRef, BfMethodInstance* methodInstance, BfGenericParamInstance* genericParamInstance, BfTypeVector* methodGenericArgsOverride)
  395. {
  396. BfConstraintState constraintSet;
  397. constraintSet.mPrevState = mContext->mCurConstraintState;
  398. constraintSet.mGenericParamInstance = genericParamInstance;
  399. constraintSet.mMethodInstance = methodInstance;
  400. constraintSet.mMethodGenericArgsOverride = methodGenericArgsOverride;
  401. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mContext->mCurConstraintState, &constraintSet);
  402. if (!CheckConstraintState(NULL))
  403. return NULL;
  404. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, methodInstance);
  405. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, methodInstance->GetOwner());
  406. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  407. BfType* type = ResolveTypeRef(typeRef);
  408. if (type == NULL)
  409. type = GetPrimitiveType(BfTypeCode_Var);
  410. return type;
  411. }
  412. bool BfModule::AreConstraintsSubset(BfGenericParamInstance* checkInner, BfGenericParamInstance* checkOuter)
  413. {
  414. if (checkOuter == NULL)
  415. return false;
  416. if (checkInner == NULL)
  417. return true;
  418. // Added new flags?
  419. if ((checkInner->mGenericParamFlags | checkOuter->mGenericParamFlags) != checkOuter->mGenericParamFlags)
  420. {
  421. // If the outer had a type flag and the inner has a specific type constraint, then see if those are compatible
  422. auto outerFlags = checkOuter->mGenericParamFlags;
  423. if ((outerFlags & BfGenericParamFlag_Enum) != 0)
  424. outerFlags = (BfGenericParamFlags)(outerFlags | BfGenericParamFlag_Struct);
  425. if (checkOuter->mTypeConstraint != NULL)
  426. {
  427. if (checkOuter->mTypeConstraint->IsStruct())
  428. outerFlags = (BfGenericParamFlags)(outerFlags | BfGenericParamFlag_Struct);
  429. else if (checkOuter->mTypeConstraint->IsStructOrStructPtr())
  430. outerFlags = (BfGenericParamFlags)(outerFlags | BfGenericParamFlag_StructPtr);
  431. else if ((checkOuter->mTypeConstraint->IsObject()) && (!checkOuter->mTypeConstraint->IsDelegate()))
  432. outerFlags = (BfGenericParamFlags)(outerFlags | BfGenericParamFlag_Class);
  433. else if (checkOuter->mTypeConstraint->IsEnum())
  434. outerFlags = (BfGenericParamFlags)(outerFlags | BfGenericParamFlag_Enum | BfGenericParamFlag_Struct);
  435. else if (checkOuter->mTypeConstraint->IsInterface())
  436. outerFlags = (BfGenericParamFlags)(outerFlags | BfGenericParamFlag_Interface);
  437. }
  438. auto innerFlags = checkInner->mGenericParamFlags;
  439. if ((innerFlags & BfGenericParamFlag_Enum) != 0)
  440. innerFlags = (BfGenericParamFlags)(innerFlags | BfGenericParamFlag_Struct);
  441. if (((innerFlags | outerFlags) & ~BfGenericParamFlag_Var) != (outerFlags & ~BfGenericParamFlag_Var))
  442. return false;
  443. }
  444. if (checkInner->mTypeConstraint != NULL)
  445. {
  446. if (checkOuter->mTypeConstraint == NULL)
  447. return false;
  448. if (!TypeIsSubTypeOf(checkOuter->mTypeConstraint->ToTypeInstance(), checkInner->mTypeConstraint->ToTypeInstance()))
  449. return false;
  450. }
  451. for (auto innerIFace : checkInner->mInterfaceConstraints)
  452. {
  453. if (checkOuter->mInterfaceConstraints.IsEmpty())
  454. return false;
  455. if (checkOuter->mInterfaceConstraintSet == NULL)
  456. {
  457. std::function<void(BfTypeInstance*)> _AddInterface = [&](BfTypeInstance* ifaceType)
  458. {
  459. if (!checkOuter->mInterfaceConstraintSet->Add(ifaceType))
  460. return;
  461. if (ifaceType->mDefineState < BfTypeDefineState_HasInterfaces_Direct)
  462. PopulateType(ifaceType, Beefy::BfPopulateType_Interfaces_Direct);
  463. for (auto& ifaceEntry : ifaceType->mInterfaces)
  464. _AddInterface(ifaceEntry.mInterfaceType);
  465. };
  466. checkOuter->mInterfaceConstraintSet = new HashSet<BfTypeInstance*>();
  467. for (auto outerIFace : checkOuter->mInterfaceConstraints)
  468. _AddInterface(outerIFace);
  469. }
  470. if (!checkOuter->mInterfaceConstraintSet->Contains(innerIFace))
  471. return false;
  472. }
  473. for (auto& innerOp : checkInner->mOperatorConstraints)
  474. {
  475. if (!checkOuter->mOperatorConstraints.Contains(innerOp))
  476. return false;
  477. }
  478. return true;
  479. }
  480. bool BfModule::CheckConstraintState(BfAstNode* refNode)
  481. {
  482. if (mContext->mCurConstraintState == NULL)
  483. return true;
  484. auto checkState = mContext->mCurConstraintState->mPrevState;
  485. while (checkState != NULL)
  486. {
  487. if (*checkState == *mContext->mCurConstraintState)
  488. {
  489. if (refNode != NULL)
  490. {
  491. Fail("Constraints cause circular operator invocations", refNode);
  492. }
  493. return false;
  494. }
  495. checkState = checkState->mPrevState;
  496. }
  497. return true;
  498. }
  499. bool BfModule::ShouldAllowMultipleDefinitions(BfTypeInstance* typeInst, BfTypeDef* firstDeclaringTypeDef, BfTypeDef* secondDeclaringTypeDef)
  500. {
  501. if (firstDeclaringTypeDef == secondDeclaringTypeDef)
  502. return false;
  503. // Since we will use shared debugging info, we won't be able to differentiate between these two fields.
  504. // If we created per-target debug info then we could "fix" this.
  505. // Can these projects even see each other?
  506. if ((!firstDeclaringTypeDef->mProject->ContainsReference(secondDeclaringTypeDef->mProject)) &&
  507. (!secondDeclaringTypeDef->mProject->ContainsReference(firstDeclaringTypeDef->mProject)))
  508. return true;
  509. if (typeInst->IsUnspecializedType())
  510. {
  511. bool alwaysCoincide = true;
  512. auto genericTypeInst = (BfTypeInstance*)typeInst;
  513. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  514. {
  515. auto firstConstraints = genericTypeInst->GetGenericParamsVector(firstDeclaringTypeDef);
  516. auto secondConstraints = genericTypeInst->GetGenericParamsVector(secondDeclaringTypeDef);
  517. for (int genericIdx = 0; genericIdx < (int)firstConstraints->size(); genericIdx++)
  518. {
  519. auto firstConstraint = (*firstConstraints)[genericIdx];
  520. auto secondConstraint = (*secondConstraints)[genericIdx];
  521. if ((!AreConstraintsSubset(firstConstraint, secondConstraint)) &&
  522. (!AreConstraintsSubset(secondConstraint, firstConstraint)))
  523. alwaysCoincide = false;
  524. }
  525. }
  526. // Only show an error if we are certain both members will always appear at the same time
  527. if (!alwaysCoincide)
  528. return true;
  529. }
  530. return false;
  531. }
  532. void BfModule::CheckInjectNewRevision(BfTypeInstance* typeInstance)
  533. {
  534. if ((typeInstance != NULL) && (typeInstance->mTypeDef != NULL))
  535. {
  536. auto typeDef = typeInstance->mTypeDef;
  537. if (typeDef->mEmitParent != NULL)
  538. typeDef = typeDef->mEmitParent;
  539. if (typeDef->mNextRevision != NULL)
  540. {
  541. // It's possible that our main compiler thread is generating a new typedef while we're autocompleting. This handles that case...
  542. if (typeInstance->mDefineState == BfTypeDefineState_Undefined)
  543. {
  544. if (typeInstance->IsBoxed())
  545. {
  546. BfBoxedType* boxedType = (BfBoxedType*)typeInstance;
  547. BfTypeInstance* innerType = boxedType->mElementType->ToTypeInstance();
  548. PopulateType(innerType, BfPopulateType_Data);
  549. }
  550. else
  551. {
  552. mContext->HandleChangedTypeDef(typeDef);
  553. mSystem->InjectNewRevision(typeDef);
  554. }
  555. }
  556. else
  557. {
  558. BF_ASSERT(mCompiler->IsAutocomplete());
  559. }
  560. }
  561. if ((!typeInstance->IsDeleting()) && (!mCompiler->IsAutocomplete()))
  562. BF_ASSERT((typeDef->mDefState == BfTypeDef::DefState_Defined) || (typeDef->mDefState == BfTypeDef::DefState_New));
  563. if ((typeInstance->mTypeDef->mDefState == BfTypeDef::DefState_EmittedDirty) && (typeInstance->mTypeDef->mEmitParent->mNextRevision == NULL))
  564. mSystem->UpdateEmittedTypeDef(typeInstance->mTypeDef);
  565. }
  566. }
  567. void BfModule::InitType(BfType* resolvedTypeRef, BfPopulateType populateType)
  568. {
  569. BP_ZONE("BfModule::InitType");
  570. if (auto depType = resolvedTypeRef->ToDependedType())
  571. {
  572. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodInfoEx != NULL))
  573. {
  574. depType->mDependencyMap.mMinDependDepth = mCurMethodInstance->mMethodInfoEx->mMinDependDepth + 1;
  575. }
  576. else if (mCurTypeInstance != NULL)
  577. {
  578. depType->mDependencyMap.mMinDependDepth = mCurTypeInstance->mDependencyMap.mMinDependDepth + 1;
  579. }
  580. }
  581. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, resolvedTypeRef->ToTypeInstance());
  582. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  583. if (mCompiler->mHotState != NULL)
  584. mCompiler->mHotState->mHasNewTypes = true;
  585. auto typeInst = resolvedTypeRef->ToTypeInstance();
  586. if (typeInst != NULL)
  587. {
  588. CheckInjectNewRevision(typeInst);
  589. BF_ASSERT(!typeInst->mTypeDef->IsEmitted());
  590. if (typeInst->mBaseType != NULL)
  591. BF_ASSERT((typeInst->mBaseType->mRebuildFlags & BfTypeRebuildFlag_Deleted) == 0);
  592. if ((typeInst->mTypeDef != NULL) && (typeInst->mTypeDef->mDefState == BfTypeDef::DefState_New) &&
  593. (typeInst->mTypeDef->mNextRevision == NULL))
  594. {
  595. mContext->HandleChangedTypeDef(typeInst->mTypeDef);
  596. typeInst->mTypeDef->mDefState = BfTypeDef::DefState_Defined;
  597. }
  598. typeInst->mIsReified = mIsReified;
  599. //BF_ASSERT(typeInst->mTypeDef->mTypeCode != BfTypeCode_Extension);
  600. typeInst->mRevision = mCompiler->mRevision;
  601. if (typeInst->mTypeDef != NULL)
  602. BF_ASSERT(typeInst->mTypeDef->mDefState != BfTypeDef::DefState_Deleted);
  603. if (resolvedTypeRef->IsTuple())
  604. {
  605. auto tupleType = (BfTypeInstance*)resolvedTypeRef;
  606. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  607. {
  608. auto fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  609. // We need to make sure dependencies get set immediately since we already resolved the types
  610. AddFieldDependency(typeInst, fieldInstance, fieldInstance->mResolvedType);
  611. }
  612. }
  613. }
  614. if (resolvedTypeRef->IsGenericTypeInstance())
  615. {
  616. auto genericTypeInst = (BfTypeInstance*)resolvedTypeRef;
  617. for (auto typeGenericArg : genericTypeInst->mGenericTypeInfo->mTypeGenericArguments)
  618. {
  619. BF_ASSERT((typeGenericArg->mRebuildFlags & BfTypeRebuildFlag_Deleted) == 0);
  620. if (mIsReified)
  621. {
  622. // Try to reify any generic args
  623. for (auto genericArg : typeInst->mGenericTypeInfo->mTypeGenericArguments)
  624. {
  625. if (!genericArg->IsReified())
  626. PopulateType(genericArg, BfPopulateType_Declaration);
  627. }
  628. }
  629. BF_ASSERT(!typeGenericArg->IsIntUnknown());
  630. }
  631. }
  632. if (!mContext->mSavedTypeDataMap.IsEmpty())
  633. {
  634. String typeName = BfSafeMangler::Mangle(resolvedTypeRef, this);
  635. BfSavedTypeData* savedTypeData;
  636. if (mContext->mSavedTypeDataMap.Remove(typeName, &savedTypeData))
  637. {
  638. mContext->mSavedTypeData[savedTypeData->mTypeId] = NULL;
  639. resolvedTypeRef->mTypeId = savedTypeData->mTypeId;
  640. BfLogSysM("Using mSavedTypeData for %p %s\n", resolvedTypeRef, typeName.c_str());
  641. if (typeInst != NULL)
  642. {
  643. if (IsHotCompile())
  644. {
  645. BfLogSysM("Using mSavedTypeData HotTypeData %p for %p\n", savedTypeData->mHotTypeData, resolvedTypeRef);
  646. typeInst->mHotTypeData = savedTypeData->mHotTypeData;
  647. savedTypeData->mHotTypeData = NULL;
  648. }
  649. }
  650. delete savedTypeData;
  651. mContext->mTypes[resolvedTypeRef->mTypeId] = resolvedTypeRef;
  652. }
  653. else
  654. {
  655. BfLogSysM("No mSavedTypeData entry for %p %s\n", resolvedTypeRef, typeName.c_str());
  656. }
  657. }
  658. resolvedTypeRef->mContext = mContext;
  659. if (resolvedTypeRef->IsGenericTypeInstance())
  660. {
  661. auto genericTypeInstance = (BfTypeInstance*)resolvedTypeRef;
  662. #ifdef _DEBUG
  663. for (auto genericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  664. BF_ASSERT(!genericArg->IsVar());
  665. #endif
  666. // We need to add generic dependencies here because when we are just doing an Identity population there may be
  667. // on-demand types that could get deleted before initializing the type
  668. DoPopulateType_SetGenericDependencies(genericTypeInstance);
  669. // Do it here so the location we attempted to specialize this type will throw the failure if there is one
  670. if (!InitGenericParams(resolvedTypeRef))
  671. return;
  672. }
  673. if ((typeInst != NULL) && (typeInst->mIsReified) && (!mCompiler->mIsResolveOnly))
  674. {
  675. BfLogSysM("REIFIED(InitType): %s Type:%p FromModule:%s FromMethod:%p\n", TypeToString(resolvedTypeRef).c_str(), resolvedTypeRef, mModuleName.c_str(), prevMethodInstance.mPrevVal);
  676. }
  677. BfLogSysM("%p InitType: %s Type: %p TypeDef: %p Revision:%d\n", mContext, TypeToString(resolvedTypeRef).c_str(), resolvedTypeRef, (typeInst != NULL) ? typeInst->mTypeDef : NULL, mCompiler->mRevision);
  678. // When we're autocomplete, we can't do the method processing so we have to add this type to the type work list
  679. if (((populateType < BfPopulateType_Full) || (mCompiler->IsAutocomplete())) /*&& (!resolvedTypeRef->IsUnspecializedTypeVariation())*/ && (resolvedTypeRef->IsTypeInstance()) &&
  680. (!resolvedTypeRef->IsTypeAlias()))
  681. {
  682. BfTypeProcessRequest* typeProcessRequest = mContext->mPopulateTypeWorkList.Alloc();
  683. typeProcessRequest->mType = resolvedTypeRef;
  684. BF_ASSERT(resolvedTypeRef->mContext == mContext);
  685. mCompiler->mStats.mTypesQueued++;
  686. mCompiler->UpdateCompletion();
  687. }
  688. PopulateType(resolvedTypeRef, populateType);
  689. }
  690. void BfModule::AddFieldDependency(BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfType* fieldType)
  691. {
  692. auto depFlag = fieldType->IsValueType() ? BfDependencyMap::DependencyFlag_ValueTypeMemberData : BfDependencyMap::DependencyFlag_PtrMemberData;
  693. if (fieldInstance->IsAppendedObject())
  694. depFlag = BfDependencyMap::DependencyFlag_ValueTypeMemberData;
  695. AddDependency(fieldType, typeInstance, depFlag);
  696. if ((fieldType->IsStruct()) && (fieldType->IsGenericTypeInstance()))
  697. {
  698. // When we're a generic struct, our data layout can depend on our generic parameters as well
  699. auto genericTypeInstance = (BfTypeInstance*)fieldType;
  700. for (auto typeGenericArg : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  701. AddFieldDependency(typeInstance, fieldInstance, typeGenericArg);
  702. }
  703. }
  704. BfFieldInstance* BfModule::GetFieldByName(BfTypeInstance* typeInstance, const StringImpl& fieldName, bool isRequired, BfAstNode* refNode)
  705. {
  706. PopulateType(typeInstance);
  707. typeInstance->mTypeDef->PopulateMemberSets();
  708. BfMemberSetEntry* entry = NULL;
  709. BfFieldDef* fieldDef = NULL;
  710. if (typeInstance->mTypeDef->mFieldSet.TryGetWith(fieldName, &entry))
  711. {
  712. fieldDef = (BfFieldDef*)entry->mMemberDef;
  713. return &typeInstance->mFieldInstances[fieldDef->mIdx];
  714. }
  715. if (isRequired)
  716. {
  717. FailInternal(StrFormat("Field '%s' not found in '%s'", fieldName.c_str(), TypeToString(typeInstance).c_str()), refNode);
  718. }
  719. return NULL;
  720. }
  721. void BfModule::CheckMemberNames(BfTypeInstance* typeInst)
  722. {
  723. struct MemberRef
  724. {
  725. BfMemberDef* mMemberDef;
  726. StringView mName;
  727. StringView mKindName;
  728. BfTypeInstance* mTypeInst;
  729. BfAstNode* mNameNode;
  730. BfProtection mProtection;
  731. BfTypeDef* mDeclaringType;
  732. bool mIsOverride;
  733. };
  734. SizedArray<MemberRef, 64> memberList;
  735. // Check base types first and then current type
  736. auto checkType = typeInst;
  737. while (checkType != NULL)
  738. {
  739. for (auto prop : checkType->mTypeDef->mProperties)
  740. {
  741. BfPropertyDeclaration* propDecl = (BfPropertyDeclaration*)prop->mFieldDeclaration;
  742. if ((propDecl != NULL) && (propDecl->mExplicitInterface != NULL))
  743. continue;
  744. if (!typeInst->IsTypeMemberIncluded(prop->mDeclaringType))
  745. continue;
  746. MemberRef memberRef = { 0 };
  747. memberRef.mMemberDef = prop;
  748. memberRef.mTypeInst = checkType;
  749. memberRef.mProtection = prop->mProtection;
  750. memberRef.mName = prop->mName;
  751. memberRef.mKindName = "property";
  752. auto fieldDecl = prop->GetFieldDeclaration();
  753. if (fieldDecl != NULL)
  754. memberRef.mNameNode = fieldDecl->mNameNode;
  755. memberRef.mDeclaringType = prop->mDeclaringType;
  756. auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(prop->mFieldDeclaration);
  757. if (propertyDeclaration != NULL)
  758. memberRef.mIsOverride = (propertyDeclaration->mNewSpecifier != NULL) ||
  759. ((propertyDeclaration->mVirtualSpecifier != NULL) && (propertyDeclaration->mVirtualSpecifier->GetToken() == BfToken_Override));
  760. memberList.push_back(memberRef);
  761. }
  762. for (auto field : checkType->mTypeDef->mFields)
  763. {
  764. if (!typeInst->IsTypeMemberIncluded(field->mDeclaringType))
  765. continue;
  766. MemberRef memberRef = { 0 };
  767. memberRef.mMemberDef = field;
  768. memberRef.mTypeInst = checkType;
  769. memberRef.mProtection = field->mProtection;
  770. memberRef.mName = field->mName;
  771. memberRef.mKindName = "field";
  772. memberRef.mDeclaringType = field->mDeclaringType;
  773. if (auto fieldDecl = field->GetFieldDeclaration())
  774. {
  775. memberRef.mNameNode = fieldDecl->mNameNode;
  776. memberRef.mIsOverride = fieldDecl->mNewSpecifier != NULL;
  777. }
  778. else if (auto paramDecl = field->GetParamDeclaration())
  779. {
  780. memberRef.mNameNode = paramDecl->mNameNode;
  781. }
  782. memberList.push_back(memberRef);
  783. }
  784. checkType = checkType->mBaseType;
  785. }
  786. Dictionary<StringView, MemberRef> memberMap;
  787. memberMap.Reserve(memberList.size());
  788. for (int i = (int)memberList.size() - 1; i >= 0; i--)
  789. {
  790. MemberRef& memberRef = memberList[i];
  791. if (memberRef.mName.IsEmpty())
  792. continue;
  793. if ((memberRef.mTypeInst == typeInst) && (!memberRef.mIsOverride))
  794. {
  795. MemberRef* prevMemberRef = NULL;
  796. if (memberMap.TryGetValue(memberRef.mName, &prevMemberRef))
  797. {
  798. if ((prevMemberRef->mDeclaringType->IsExtension()) && (!memberRef.mDeclaringType->IsExtension()))
  799. continue;
  800. MemberRef* firstMemberRef = &memberRef;
  801. MemberRef* secondMemberRef = prevMemberRef;
  802. bool showPrevious = false;
  803. BfError* error = NULL;
  804. if (prevMemberRef->mTypeInst != typeInst)
  805. {
  806. if ((prevMemberRef->mProtection != BfProtection_Private) && (memberRef.mNameNode != NULL))
  807. {
  808. error = Warn(BfWarning_CS0108_MemberHidesInherited, StrFormat("%s hides inherited member '%s'. Use the 'new' keyword if hiding was intentional.", String(prevMemberRef->mKindName).c_str(), String(memberRef.mName).c_str()), memberRef.mNameNode, true);
  809. showPrevious = true;
  810. }
  811. }
  812. else
  813. {
  814. if (ShouldAllowMultipleDefinitions(typeInst, firstMemberRef->mDeclaringType, secondMemberRef->mDeclaringType))
  815. {
  816. if (firstMemberRef->mMemberDef != NULL)
  817. {
  818. firstMemberRef->mMemberDef->mHasMultiDefs = true;
  819. secondMemberRef->mMemberDef->mHasMultiDefs = true;
  820. }
  821. continue;
  822. }
  823. bool wantsSwap = false;
  824. if ((secondMemberRef->mNameNode != NULL) && (firstMemberRef->mNameNode != NULL) &&
  825. (secondMemberRef->mNameNode->GetSourceData() == firstMemberRef->mNameNode->GetSourceData()) &&
  826. (secondMemberRef->mNameNode->GetSrcStart() < firstMemberRef->mNameNode->GetSrcStart()))
  827. {
  828. wantsSwap = true;
  829. }
  830. if (secondMemberRef->mDeclaringType->IsExtension() != firstMemberRef->mDeclaringType->IsExtension())
  831. {
  832. wantsSwap = firstMemberRef->mDeclaringType->IsExtension();
  833. }
  834. if (wantsSwap)
  835. {
  836. std::swap(firstMemberRef, secondMemberRef);
  837. }
  838. if (typeInst->mTypeDef->mIsCombinedPartial)
  839. {
  840. if ((firstMemberRef->mKindName == "property") && (secondMemberRef->mKindName == "property"))
  841. {
  842. auto firstPropertyDef = (BfPropertyDef*)firstMemberRef->mMemberDef;
  843. auto secondPropertyDef = (BfPropertyDef*)secondMemberRef->mMemberDef;
  844. if (auto secondPropertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(secondPropertyDef->mFieldDeclaration))
  845. {
  846. if ((secondPropertyDeclaration->mVirtualSpecifier != NULL) && (secondPropertyDeclaration->mVirtualSpecifier->mToken == BfToken_Override))
  847. continue;
  848. }
  849. }
  850. }
  851. if (secondMemberRef->mNameNode != NULL)
  852. error = Fail(StrFormat("A %s named '%s' has already been declared.", String(secondMemberRef->mKindName).c_str(), String(memberRef.mName).c_str()), secondMemberRef->mNameNode, true);
  853. showPrevious = true;
  854. typeInst->mHasDeclError = true;
  855. }
  856. if ((secondMemberRef->mNameNode != NULL) && (error != NULL))
  857. mCompiler->mPassInstance->MoreInfo("Previous declaration", firstMemberRef->mNameNode);
  858. }
  859. }
  860. memberMap.TryAdd(memberRef.mName, memberRef);
  861. }
  862. }
  863. void BfModule::TypeFailed(BfTypeInstance* typeInstance)
  864. {
  865. BfLogSysM("TypeFailed: %p\n", typeInstance);
  866. typeInstance->mTypeFailed = true;
  867. // Punt on field types - just substitute 'var' where we have NULLs
  868. for (auto& fieldInstance : typeInstance->mFieldInstances)
  869. {
  870. if ((fieldInstance.mResolvedType == NULL) || (fieldInstance.mResolvedType->IsNull()))
  871. {
  872. if (fieldInstance.mDataIdx >= 0)
  873. fieldInstance.mResolvedType = GetPrimitiveType(BfTypeCode_Var);
  874. }
  875. if (fieldInstance.mOwner == NULL)
  876. fieldInstance.mOwner = typeInstance;
  877. }
  878. if (typeInstance->mAlign == -1)
  879. typeInstance->mAlign = 1;
  880. if (typeInstance->mSize == -1)
  881. typeInstance->mSize = 1;
  882. mContext->mFailTypes.TryAdd(typeInstance, BfFailKind_Normal);
  883. mHadBuildError = true;
  884. }
  885. bool BfModule::CheckCircularDataError(bool failTypes)
  886. {
  887. // Find two loops of mCurTypeInstance. Just finding one loop can give some false errors.
  888. BfTypeState* circularTypeStateEnd = NULL;
  889. int checkIdx = 0;
  890. auto checkTypeState = mContext->mCurTypeState;
  891. bool isPreBaseCheck = checkTypeState->mPopulateType == BfPopulateType_Declaration;
  892. while (true)
  893. {
  894. if (checkTypeState == NULL)
  895. return false;
  896. if (checkTypeState->mResolveKind == BfTypeState::ResolveKind_UnionInnerType)
  897. {
  898. checkTypeState = checkTypeState->mPrevState;
  899. continue;
  900. }
  901. if (isPreBaseCheck)
  902. {
  903. if (checkTypeState->mPopulateType != BfPopulateType_Declaration)
  904. return false;
  905. }
  906. else
  907. {
  908. if (checkTypeState->mPopulateType == BfPopulateType_Declaration)
  909. return false;
  910. if ((checkIdx > 0) && (checkTypeState->mCurBaseTypeRef == NULL) && (checkTypeState->mCurAttributeTypeRef == NULL) && (checkTypeState->mCurFieldDef == NULL) &&
  911. ((checkTypeState->mType == NULL) || (checkTypeState->mType->IsTypeInstance())))
  912. return false;
  913. }
  914. if ((checkTypeState->mType == mCurTypeInstance) && (checkIdx > 1))
  915. {
  916. if (circularTypeStateEnd == NULL)
  917. circularTypeStateEnd = checkTypeState;
  918. else
  919. break;
  920. }
  921. checkTypeState = checkTypeState->mPrevState;
  922. checkIdx++;
  923. }
  924. bool hadError = false;
  925. checkTypeState = mContext->mCurTypeState->mPrevState;
  926. while (true)
  927. {
  928. if (checkTypeState == NULL)
  929. return hadError;
  930. if (checkTypeState == circularTypeStateEnd)
  931. return hadError;
  932. if (checkTypeState->mResolveKind == BfTypeState::ResolveKind_UnionInnerType)
  933. {
  934. // Skip over this to actual data references
  935. checkTypeState = checkTypeState->mPrevState;
  936. continue;
  937. }
  938. if ((checkTypeState->mCurAttributeTypeRef == NULL) && (checkTypeState->mCurBaseTypeRef == NULL) && (checkTypeState->mCurFieldDef == NULL) &&
  939. ((checkTypeState->mType == NULL) || (checkTypeState->mType->IsTypeInstance())))
  940. return hadError;
  941. hadError = true;
  942. if (!failTypes)
  943. return hadError;
  944. // We only get one chance to fire off these errors, they can't be ignored.
  945. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, false);
  946. if (checkTypeState->mCurAttributeTypeRef != NULL)
  947. {
  948. Fail(StrFormat("Attribute type '%s' causes a data cycle", BfTypeUtils::TypeToString(checkTypeState->mCurAttributeTypeRef).c_str()), checkTypeState->mCurAttributeTypeRef, true);
  949. }
  950. else if (checkTypeState->mCurBaseTypeRef != NULL)
  951. {
  952. Fail(StrFormat("Base type '%s' causes a data cycle", BfTypeUtils::TypeToString(checkTypeState->mCurBaseTypeRef).c_str()), checkTypeState->mCurBaseTypeRef, true);
  953. }
  954. else if ((checkTypeState->mCurFieldDef != NULL) && (checkTypeState->mCurFieldDef->mFieldDeclaration != NULL))
  955. {
  956. Fail(StrFormat("Field '%s.%s' causes a data cycle", TypeToString(checkTypeState->mType).c_str(), checkTypeState->mCurFieldDef->mName.c_str()),
  957. checkTypeState->mCurFieldDef->mTypeRef, true);
  958. }
  959. else if (checkTypeState->mCurFieldDef != NULL)
  960. {
  961. BfAstNode* refNode = checkTypeState->mCurFieldDef->GetRefNode();
  962. if (refNode == NULL)
  963. {
  964. if (checkTypeState->mCurTypeDef != NULL)
  965. refNode = checkTypeState->mCurTypeDef->GetRefNode();
  966. }
  967. auto checkSrcTypeState = checkTypeState;
  968. while ((refNode == NULL) && (checkSrcTypeState != NULL))
  969. {
  970. if (checkSrcTypeState->mCurFieldDef != NULL)
  971. refNode = checkSrcTypeState->mCurFieldDef->GetRefNode();
  972. checkSrcTypeState = checkSrcTypeState->mPrevState;
  973. }
  974. Fail(StrFormat("Field '%s.%s' causes a data cycle", TypeToString(checkTypeState->mType).c_str(), checkTypeState->mCurFieldDef->mName.c_str()), refNode, true);
  975. }
  976. else
  977. {
  978. BfAstNode* refNode = NULL;
  979. if (checkTypeState->mCurTypeDef != NULL)
  980. refNode = checkTypeState->mCurTypeDef->GetRefNode();
  981. Fail(StrFormat("Type '%s' causes a data cycle", TypeToString(checkTypeState->mType).c_str()), refNode, true);
  982. }
  983. auto typeInstance = checkTypeState->mType->ToTypeInstance();
  984. auto module = GetModuleFor(checkTypeState->mType);
  985. if (module != NULL)
  986. module->TypeFailed(typeInstance);
  987. else if (typeInstance != NULL)
  988. typeInstance->mTypeFailed = true;
  989. checkTypeState = checkTypeState->mPrevState;
  990. }
  991. }
  992. void BfModule::PopulateType(BfType* resolvedTypeRef, BfPopulateType populateType)
  993. {
  994. if ((populateType == BfPopulateType_Declaration) && (resolvedTypeRef->mDefineState >= BfTypeDefineState_Declared))
  995. return;
  996. if ((resolvedTypeRef->mRebuildFlags & BfTypeRebuildFlag_PendingGenericArgDep) != 0)
  997. {
  998. BfLogSysM("PopulateType handling BfTypeRebuildFlag_PendingGenericArgDep for type %p\n", resolvedTypeRef);
  999. // Reinit dependencies
  1000. resolvedTypeRef->mRebuildFlags = (BfTypeRebuildFlags)(resolvedTypeRef->mRebuildFlags & ~BfTypeRebuildFlag_PendingGenericArgDep);
  1001. DoPopulateType_SetGenericDependencies(resolvedTypeRef->ToTypeInstance());
  1002. }
  1003. // Are we "demanding" to reify a type that is currently resolve-only?
  1004. if ((mIsReified) && (populateType >= BfPopulateType_Declaration))
  1005. {
  1006. if (resolvedTypeRef->IsTypeInstance())
  1007. {
  1008. auto typeModule = resolvedTypeRef->GetModule();
  1009. if ((typeModule != NULL) && (typeModule->mIsSpecialModule))
  1010. {
  1011. auto typeInst = resolvedTypeRef->ToTypeInstance();
  1012. if (!typeInst->mIsReified)
  1013. {
  1014. BfLogSysM("Reifying type %p in scratch module in PopulateType\n", resolvedTypeRef);
  1015. // It's important for unspecialized types to be in the correct module --
  1016. // when we process their methods, new types will be determined as
  1017. // resolve-only or reified based on the module the unresolved type is in
  1018. BF_ASSERT(typeInst->mModule == mContext->mUnreifiedModule);
  1019. typeInst->mIsReified = true;
  1020. typeInst->mModule = mContext->mScratchModule;
  1021. // Why did we need to do this at all? Why is just marking the type as reified not enough?
  1022. // This causes issues where we may delete a method instance that is currently being used as the generic bindings for
  1023. // a method of a specialized generic type
  1024. // if (typeInst->IsOnDemand())
  1025. // {
  1026. // RebuildMethods(typeInst);
  1027. // }
  1028. // else
  1029. // mContext->RebuildType(typeInst, false, false);
  1030. if (typeInst->mGenericTypeInfo != NULL)
  1031. {
  1032. for (auto genericArg : typeInst->mGenericTypeInfo->mTypeGenericArguments)
  1033. {
  1034. if (!genericArg->IsReified())
  1035. PopulateType(genericArg, BfPopulateType_Declaration);
  1036. }
  1037. }
  1038. }
  1039. }
  1040. else
  1041. {
  1042. if ((typeModule != NULL) && (!typeModule->mIsReified) && (!typeModule->mReifyQueued))
  1043. {
  1044. bool canFastReify = false;
  1045. if (typeModule->mAwaitingInitFinish)
  1046. {
  1047. canFastReify = true;
  1048. for (auto ownedTypes : typeModule->mOwnedTypeInstances)
  1049. if (ownedTypes->mDefineState > BfTypeDefineState_HasInterfaces_Direct)
  1050. canFastReify = false;
  1051. }
  1052. if (!mCompiler->mIsResolveOnly)
  1053. {
  1054. for (auto ownedTypes : typeModule->mOwnedTypeInstances)
  1055. {
  1056. BfLogSysM("REIFIED(PopulateType-Reference): %s %p FromModule:%s FromMethod: %p\n", TypeToString(ownedTypes).c_str(), ownedTypes, mModuleName.c_str(), mCurMethodInstance);
  1057. }
  1058. }
  1059. if (canFastReify)
  1060. {
  1061. BfLogSysM("Setting reified type %p in module %p in PopulateType on module awaiting finish\n", resolvedTypeRef, typeModule);
  1062. typeModule->mIsReified = true;
  1063. typeModule->CalcGeneratesCode();
  1064. typeModule->mWantsIRIgnoreWrites = false;
  1065. for (auto ownedTypes : typeModule->mOwnedTypeInstances)
  1066. {
  1067. ownedTypes->mIsReified = true;
  1068. if (ownedTypes->mCustomAttributes != NULL)
  1069. {
  1070. for (auto& attr : ownedTypes->mCustomAttributes->mAttributes)
  1071. {
  1072. if ((attr.mType->mAttributeData != NULL) && ((attr.mType->mAttributeData->mFlags & BfCustomAttributeFlags_ReflectAttribute) != 0))
  1073. {
  1074. // Reify this attribute
  1075. typeModule->PopulateType(attr.mType);
  1076. }
  1077. }
  1078. }
  1079. }
  1080. mCompiler->mStats.mReifiedModuleCount++;
  1081. if (typeModule->mBfIRBuilder != NULL)
  1082. {
  1083. typeModule->mBfIRBuilder->ClearNonConstData();
  1084. typeModule->mBfIRBuilder->mIgnoreWrites = false;
  1085. typeModule->SetupIRBuilder(false);
  1086. }
  1087. else
  1088. typeModule->PrepareForIRWriting(resolvedTypeRef->ToTypeInstance());
  1089. }
  1090. else
  1091. {
  1092. if ((mCompiler->mCompileState == BfCompiler::CompileState_Unreified) || (mCompiler->mCompileState == BfCompiler::CompileState_VData))
  1093. {
  1094. FailInternal(StrFormat("Invalid late reification of type '%s'", TypeToString(resolvedTypeRef).c_str()));
  1095. }
  1096. else
  1097. {
  1098. BF_ASSERT((mCompiler->mCompileState != BfCompiler::CompileState_Unreified) && (mCompiler->mCompileState != BfCompiler::CompileState_VData));
  1099. BfLogSysM("Queued reification of type %p in module %p in PopulateType\n", resolvedTypeRef, typeModule);
  1100. BF_ASSERT((typeModule != mContext->mUnreifiedModule) && (typeModule != mContext->mScratchModule));
  1101. BF_ASSERT(!typeModule->mIsSpecialModule);
  1102. // This caused issues - we may need to reify a type and then request a method
  1103. typeModule->mReifyQueued = true;
  1104. mContext->mReifyModuleWorkList.Add(typeModule);
  1105. //typeModule->ReifyModule();
  1106. }
  1107. }
  1108. }
  1109. }
  1110. }
  1111. else
  1112. {
  1113. // If we're a type like "A*", make sure we reify "A" if necessary
  1114. auto checkUnderlying = resolvedTypeRef->GetUnderlyingType();
  1115. while (checkUnderlying != NULL)
  1116. {
  1117. auto checkTypeInst = checkUnderlying->ToTypeInstance();
  1118. if (checkTypeInst != NULL)
  1119. {
  1120. if (!checkTypeInst->mIsReified)
  1121. PopulateType(checkTypeInst, BfPopulateType_BaseType);
  1122. break;
  1123. }
  1124. checkUnderlying = checkUnderlying->GetUnderlyingType();
  1125. }
  1126. }
  1127. }
  1128. if (!resolvedTypeRef->IsIncomplete())
  1129. return;
  1130. if (populateType <= BfPopulateType_TypeDef)
  1131. return;
  1132. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  1133. CheckInjectNewRevision(typeInstance);
  1134. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  1135. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  1136. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  1137. if ((resolvedTypeRef->mRebuildFlags & (BfTypeRebuildFlag_Deleted | BfTypeRebuildFlag_DeleteQueued)) != 0)
  1138. {
  1139. if (mContext->mGhostDependencies.Contains(resolvedTypeRef))
  1140. {
  1141. // Not a nice state, but we should be able to recover
  1142. return;
  1143. }
  1144. InternalError("Attempting PopulateType on deleted type");
  1145. return;
  1146. }
  1147. bool isNew = resolvedTypeRef->mDefineState == BfTypeDefineState_Undefined;
  1148. if (isNew)
  1149. {
  1150. BP_ZONE("BfModule::PopulateType");
  1151. if (resolvedTypeRef->mTypeId == -1)
  1152. {
  1153. mCompiler->mTypeInitCount++;
  1154. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  1155. if (!mCompiler->mTypeIdFreeList.IsEmpty())
  1156. {
  1157. resolvedTypeRef->mTypeId = mCompiler->mTypeIdFreeList.back();
  1158. mCompiler->mTypeIdFreeList.pop_back();
  1159. }
  1160. else
  1161. resolvedTypeRef->mTypeId = mCompiler->mCurTypeId++;
  1162. while (resolvedTypeRef->mTypeId >= (int)mContext->mTypes.size())
  1163. mContext->mTypes.Add(NULL);
  1164. mContext->mTypes[resolvedTypeRef->mTypeId] = resolvedTypeRef;
  1165. if (typeInstance != NULL)
  1166. {
  1167. typeInstance->mSignatureRevision = mCompiler->mRevision;
  1168. typeInstance->mLastNonGenericUsedRevision = mCompiler->mRevision;
  1169. }
  1170. }
  1171. BfTypeDef* typeDef = NULL;
  1172. if (typeInstance != NULL)
  1173. typeDef = typeInstance->mTypeDef;
  1174. auto typeModule = resolvedTypeRef->GetModule();
  1175. if (typeModule != NULL)
  1176. BF_ASSERT(!typeModule->mAwaitingFinish);
  1177. BfLogSysM("PopulateType: %p %s populateType:%d ResolveOnly:%d Reified:%d AutoComplete:%d Ctx:%p Mod:%p TypeId:%d TypeDef:%p\n", resolvedTypeRef, TypeToString(resolvedTypeRef, BfTypeNameFlags_None).c_str(), populateType, mCompiler->mIsResolveOnly, mIsReified, mCompiler->IsAutocomplete(), mContext, resolvedTypeRef->GetModule(), resolvedTypeRef->mTypeId, typeDef);
  1178. BF_ASSERT(!resolvedTypeRef->IsDeleting());
  1179. }
  1180. if (resolvedTypeRef->IsRef())
  1181. {
  1182. BfRefType* refType = (BfRefType*)resolvedTypeRef;
  1183. if (refType->mElementType->IsValueType())
  1184. {
  1185. PopulateType(refType->mElementType, populateType);
  1186. resolvedTypeRef->mDefineState = refType->mElementType->mDefineState;
  1187. }
  1188. else
  1189. {
  1190. PopulateType(refType->mElementType, BfPopulateType_Identity);
  1191. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1192. }
  1193. refType->mSize = refType->mAlign = mSystem->mPtrSize;
  1194. return;
  1195. }
  1196. if (resolvedTypeRef->IsTypeAlias())
  1197. {
  1198. // Always populate these all the way
  1199. if (populateType != BfPopulateType_IdentityNoRemapAlias)
  1200. populateType = BfPopulateType_Data;
  1201. }
  1202. if (resolvedTypeRef->IsSizedArray())
  1203. {
  1204. resolvedTypeRef->mRevision = mRevision;
  1205. bool typeFailed = false;
  1206. BfSizedArrayType* arrayType = (BfSizedArrayType*)resolvedTypeRef;
  1207. auto elementType = arrayType->mElementType;
  1208. int elementSize = 0;
  1209. int elementAlign = 0;
  1210. int elementStride = 0;
  1211. if (elementType->IsValueType())
  1212. {
  1213. resolvedTypeRef->mDefineState = BfTypeDefineState_ResolvingBaseType;
  1214. BfTypeState typeState(arrayType, mContext->mCurTypeState);
  1215. typeState.mPopulateType = BfPopulateType_Data;
  1216. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  1217. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, NULL);
  1218. if (!CheckCircularDataError())
  1219. {
  1220. PopulateType(arrayType->mElementType, BfPopulateType_Data);
  1221. }
  1222. else
  1223. {
  1224. typeFailed = true;
  1225. PopulateType(arrayType->mElementType, BfPopulateType_Identity);
  1226. }
  1227. resolvedTypeRef->mDefineState = arrayType->mElementType->mDefineState;
  1228. AddDependency(elementType, resolvedTypeRef, BfDependencyMap::DependencyFlag_ValueTypeMemberData);
  1229. elementSize = arrayType->mElementType->mSize;
  1230. elementAlign = arrayType->mElementType->mAlign;
  1231. elementStride = arrayType->mElementType->GetStride();
  1232. }
  1233. else
  1234. {
  1235. PopulateType(arrayType->mElementType, BfPopulateType_Identity);
  1236. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1237. AddDependency(elementType, resolvedTypeRef, BfDependencyMap::DependencyFlag_PtrMemberData);
  1238. elementSize = mSystem->mPtrSize;
  1239. elementAlign = mSystem->mPtrSize;
  1240. elementStride = mSystem->mPtrSize;
  1241. }
  1242. if (arrayType->mElementCount > 0)
  1243. {
  1244. arrayType->mSize = (int)(elementStride * arrayType->mElementCount);
  1245. if (elementSize > 0)
  1246. {
  1247. int64 maxElements = 0x7FFFFFFF / elementStride;
  1248. if (arrayType->mElementCount > maxElements)
  1249. {
  1250. Fail(StrFormat("Array size overflow: %s", TypeToString(arrayType).c_str()));
  1251. arrayType->mSize = 0x7FFFFFFF;
  1252. }
  1253. }
  1254. arrayType->mAlign = std::max(elementAlign, 1);
  1255. }
  1256. else if (arrayType->mElementCount < 0)
  1257. {
  1258. // Unknown size, don't assume it's valueless
  1259. arrayType->mSize = 1;
  1260. arrayType->mAlign = 1;
  1261. }
  1262. else
  1263. {
  1264. arrayType->mSize = 0;
  1265. arrayType->mAlign = 1;
  1266. }
  1267. BF_ASSERT(arrayType->mSize >= 0);
  1268. if (!typeFailed)
  1269. arrayType->mWantsGCMarking = elementType->WantsGCMarking();
  1270. resolvedTypeRef->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  1271. resolvedTypeRef->mRebuildFlags = BfTypeRebuildFlag_None;
  1272. bool isValueless = arrayType->IsValuelessType();
  1273. return;
  1274. }
  1275. if (isNew)
  1276. {
  1277. BfTypeDef* typeDef = NULL;
  1278. if (typeInstance != NULL)
  1279. {
  1280. if ((populateType == BfPopulateType_Data) && (typeInstance->mNeedsMethodProcessing))
  1281. return;
  1282. typeDef = typeInstance->mTypeDef;
  1283. }
  1284. if (resolvedTypeRef->IsMethodRef())
  1285. return;
  1286. if (resolvedTypeRef->IsPointer())
  1287. {
  1288. BfPointerType* pointerType = (BfPointerType*)resolvedTypeRef;
  1289. if (pointerType->mElementType->IsIncomplete())
  1290. PopulateType(pointerType->mElementType, BfPopulateType_Declaration);
  1291. pointerType->mSize = pointerType->mAlign = mSystem->mPtrSize;
  1292. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1293. return;
  1294. }
  1295. if (resolvedTypeRef->IsGenericParam())
  1296. {
  1297. BfGenericParamType* genericParamType = (BfGenericParamType*)resolvedTypeRef;
  1298. PopulateType(mContext->mBfObjectType);
  1299. genericParamType->mSize = mContext->mBfObjectType->mSize;
  1300. genericParamType->mAlign = mContext->mBfObjectType->mAlign;
  1301. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1302. return;
  1303. }
  1304. if (resolvedTypeRef->IsModifiedTypeType())
  1305. {
  1306. BfModifiedTypeType* retTypeType = (BfModifiedTypeType*)resolvedTypeRef;
  1307. BF_ASSERT(retTypeType->mElementType->IsGenericParam());
  1308. resolvedTypeRef->mSize = mContext->mBfObjectType->mSize;
  1309. resolvedTypeRef->mAlign = mContext->mBfObjectType->mAlign;
  1310. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1311. return;
  1312. }
  1313. if (resolvedTypeRef->IsConcreteInterfaceType())
  1314. {
  1315. BfConcreteInterfaceType* concreteInterfaceType = (BfConcreteInterfaceType*)resolvedTypeRef;
  1316. BF_ASSERT(concreteInterfaceType->mInterface->IsInterface());
  1317. resolvedTypeRef->mSize = mContext->mBfObjectType->mSize;
  1318. resolvedTypeRef->mAlign = mContext->mBfObjectType->mAlign;
  1319. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1320. return;
  1321. }
  1322. if (resolvedTypeRef->IsConstExprValue())
  1323. {
  1324. BfConstExprValueType* constExprType = (BfConstExprValueType*)resolvedTypeRef;
  1325. resolvedTypeRef->mRevision = mRevision;
  1326. resolvedTypeRef->mSize = 0;
  1327. resolvedTypeRef->mAlign = 0;
  1328. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1329. if (constExprType->mType->IsTypeInstance())
  1330. AddDependency(constExprType->mType, resolvedTypeRef, BfDependencyMap::DependencyFlag_TypeGenericArg);
  1331. return;
  1332. }
  1333. // The autocomplete pass doesn't need to do the method processing, allow type to be (partially) incomplete
  1334. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL) &&
  1335. (typeInstance != NULL) && (typeInstance->mNeedsMethodProcessing) && (!typeInstance->IsDelegate()))
  1336. return;
  1337. BfPrimitiveType* primitiveType = NULL;
  1338. if (typeInstance == NULL)
  1339. {
  1340. BF_ASSERT(resolvedTypeRef->IsPrimitiveType());
  1341. primitiveType = (BfPrimitiveType*)resolvedTypeRef;
  1342. typeDef = primitiveType->mTypeDef;
  1343. }
  1344. #define PRIMITIVE_TYPE(name, llvmType, size, dType) \
  1345. primitiveType->mSize = primitiveType->mAlign = size; \
  1346. primitiveType->mDefineState = BfTypeDefineState_Defined;
  1347. switch (typeDef->mTypeCode)
  1348. {
  1349. case BfTypeCode_None:
  1350. primitiveType->mSize = primitiveType->mAlign = 0;
  1351. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1352. return;
  1353. case BfTypeCode_Self:
  1354. case BfTypeCode_Dot:
  1355. case BfTypeCode_Var:
  1356. case BfTypeCode_Let:
  1357. {
  1358. primitiveType->mSize = mSystem->mPtrSize;
  1359. primitiveType->mAlign = mSystem->mPtrSize;
  1360. resolvedTypeRef->mDefineState = BfTypeDefineState_Defined;
  1361. }
  1362. return;
  1363. case BfTypeCode_NullPtr:
  1364. primitiveType->mSize = primitiveType->mAlign = mSystem->mPtrSize;
  1365. primitiveType->mDefineState = BfTypeDefineState_Defined;
  1366. return;
  1367. case BfTypeCode_Boolean:
  1368. PRIMITIVE_TYPE("bool", Int1, 1, DW_ATE_boolean);
  1369. return;
  1370. case BfTypeCode_Int8:
  1371. PRIMITIVE_TYPE("sbyte", Int8, 1, DW_ATE_signed);
  1372. return;
  1373. case BfTypeCode_UInt8:
  1374. PRIMITIVE_TYPE("byte", Int8, 1, DW_ATE_unsigned);
  1375. return;
  1376. case BfTypeCode_Int16:
  1377. PRIMITIVE_TYPE("short", Int16, 2, DW_ATE_signed);
  1378. return;
  1379. case BfTypeCode_UInt16:
  1380. PRIMITIVE_TYPE("ushort", Int16, 2, DW_ATE_unsigned);
  1381. return;
  1382. case BfTypeCode_Int32:
  1383. PRIMITIVE_TYPE("int", Int32, 4, DW_ATE_signed);
  1384. return;
  1385. case BfTypeCode_UInt32:
  1386. PRIMITIVE_TYPE("uint", Int32, 4, DW_ATE_unsigned);
  1387. return;
  1388. case BfTypeCode_Int64:
  1389. PRIMITIVE_TYPE("long", Int64, 8, DW_ATE_signed);
  1390. return;
  1391. case BfTypeCode_UInt64:
  1392. PRIMITIVE_TYPE("ulong", Int64, 8, DW_ATE_unsigned);
  1393. return;
  1394. case BfTypeCode_IntPtr:
  1395. if (mSystem->mPtrSize == 4)
  1396. {
  1397. PRIMITIVE_TYPE("intptr", Int32, 4, DW_ATE_signed);
  1398. }
  1399. else
  1400. {
  1401. PRIMITIVE_TYPE("intptr", Int64, 8, DW_ATE_signed);
  1402. }
  1403. return;
  1404. case BfTypeCode_UIntPtr:
  1405. if (mSystem->mPtrSize == 4)
  1406. {
  1407. PRIMITIVE_TYPE("uintptr", Int32, 4, DW_ATE_unsigned);
  1408. }
  1409. else
  1410. {
  1411. PRIMITIVE_TYPE("uintptr", Int64, 8, DW_ATE_unsigned);
  1412. }
  1413. return;
  1414. case BfTypeCode_IntUnknown:
  1415. case BfTypeCode_UIntUnknown:
  1416. return;
  1417. case BfTypeCode_Char8:
  1418. PRIMITIVE_TYPE("char8", Int8, 1, DW_ATE_unsigned_char);
  1419. return;
  1420. case BfTypeCode_Char16:
  1421. PRIMITIVE_TYPE("char16", Int16, 2, DW_ATE_unsigned_char);
  1422. return;
  1423. case BfTypeCode_Char32:
  1424. PRIMITIVE_TYPE("char32", Int32, 4, DW_ATE_unsigned_char);
  1425. return;
  1426. case BfTypeCode_Float:
  1427. PRIMITIVE_TYPE("float", Float, 4, DW_ATE_float);
  1428. return;
  1429. case BfTypeCode_Double:
  1430. PRIMITIVE_TYPE("double", Double, 8, DW_ATE_float);
  1431. return;
  1432. case BfTypeCode_Object:
  1433. case BfTypeCode_Struct:
  1434. case BfTypeCode_Interface:
  1435. case BfTypeCode_Enum:
  1436. case BfTypeCode_TypeAlias:
  1437. // Implemented below
  1438. break;
  1439. case BfTypeCode_Extension:
  1440. // This can only happen if we didn't actually find the type the extension referred to
  1441. break;
  1442. default:
  1443. //NotImpl(resolvedTypeRef->mTypeRef);
  1444. BFMODULE_FATAL(this, "Invalid type");
  1445. return;
  1446. }
  1447. //////////////////////////////////////////////////////////////////////////
  1448. BF_ASSERT(typeInstance != NULL);
  1449. if (!typeInstance->IsArray())
  1450. {
  1451. BF_ASSERT(typeInstance->mTypeDef != mContext->mCompiler->mArray1TypeDef);
  1452. }
  1453. if (mContext->mBfObjectType == NULL)
  1454. {
  1455. if (typeInstance->IsInstanceOf(mCompiler->mBfObjectTypeDef))
  1456. mContext->mBfObjectType = typeInstance;
  1457. else if (mCompiler->mBfObjectTypeDef != NULL)
  1458. ResolveTypeDef(mCompiler->mBfObjectTypeDef);
  1459. }
  1460. if (typeInstance->mModule == NULL)
  1461. {
  1462. // Create a module for this type
  1463. mContext->HandleTypeWorkItem(resolvedTypeRef);
  1464. }
  1465. }
  1466. if (typeInstance == NULL)
  1467. return;
  1468. if (typeInstance->mModule == NULL)
  1469. {
  1470. BF_ASSERT(typeInstance->mTypeFailed);
  1471. return;
  1472. }
  1473. typeInstance->mModule->DoPopulateType(typeInstance, populateType);
  1474. }
  1475. BfTypeOptions* BfModule::GetTypeOptions(BfTypeDef* typeDef)
  1476. {
  1477. if (mContext->mSystem->mTypeOptions.size() == 0)
  1478. {
  1479. return NULL;
  1480. }
  1481. Array<int> matchedIndices;
  1482. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  1483. {
  1484. auto customAttributes = typeDef->mTypeDeclaration->mAttributes;
  1485. while (customAttributes != NULL)
  1486. {
  1487. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  1488. {
  1489. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  1490. auto typeRef = customAttributes->mAttributeTypeRef;
  1491. // StringT<128> attrName;
  1492. // for (auto& customAttrs : customAttributes->mAttributeTypeRef)
  1493. // {
  1494. // attrName.Clear();
  1495. // customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  1496. // Array<int>* arrPtr;
  1497. // if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  1498. // {
  1499. // for (auto optionsIdx : *arrPtr)
  1500. // {
  1501. // matchedIndices.Add(optionsIdx);
  1502. // }
  1503. // }
  1504. // }
  1505. }
  1506. customAttributes = customAttributes->mNextAttribute;
  1507. }
  1508. }
  1509. int typeOptionsCount = (int)mContext->mSystem->mTypeOptions.size();
  1510. auto _CheckTypeName = [&](const StringImpl& typeName)
  1511. {
  1512. for (int optionIdx = 0; optionIdx < (int)mContext->mSystem->mTypeOptions.size(); optionIdx++)
  1513. {
  1514. auto& typeOptions = mContext->mSystem->mTypeOptions[optionIdx];
  1515. bool matched = false;
  1516. for (auto& filter : typeOptions.mTypeFilters)
  1517. {
  1518. int filterIdx = 0;
  1519. int typeNameIdx = 0;
  1520. const char* filterPtr = filter.c_str();
  1521. const char* namePtr = typeName.c_str();
  1522. char prevFilterC = 0;
  1523. while (true)
  1524. {
  1525. char filterC;
  1526. while (true)
  1527. {
  1528. filterC = *(filterPtr++);
  1529. if (filterC != ' ')
  1530. break;
  1531. }
  1532. char nameC;
  1533. while (true)
  1534. {
  1535. nameC = *(namePtr++);
  1536. if (nameC != ' ')
  1537. break;
  1538. }
  1539. if ((filterC == 0) || (nameC == 0))
  1540. {
  1541. matched = (filterC == 0) && (nameC == 0);
  1542. break;
  1543. }
  1544. bool doWildcard = false;
  1545. if (nameC != filterC)
  1546. {
  1547. if (filterC == '*')
  1548. doWildcard = true;
  1549. else if (((filterC == ',') || (filterC == '>')) &&
  1550. ((prevFilterC == '<') || (prevFilterC == ',')))
  1551. {
  1552. doWildcard = true;
  1553. filterPtr--;
  1554. }
  1555. if (!doWildcard)
  1556. {
  1557. matched = false;
  1558. break;
  1559. }
  1560. }
  1561. if (doWildcard)
  1562. {
  1563. int openDepth = 0;
  1564. const char* startNamePtr = namePtr;
  1565. while (true)
  1566. {
  1567. nameC = *(namePtr++);
  1568. if (nameC == 0)
  1569. {
  1570. namePtr--;
  1571. if (openDepth != 0)
  1572. matched = false;
  1573. break;
  1574. }
  1575. if ((nameC == '>') && (openDepth == 0))
  1576. {
  1577. namePtr--;
  1578. break;
  1579. }
  1580. if (nameC == '<')
  1581. openDepth++;
  1582. else if (nameC == '>')
  1583. openDepth--;
  1584. else if ((nameC == ',') && (openDepth == 0))
  1585. {
  1586. namePtr--;
  1587. break;
  1588. }
  1589. }
  1590. if (!matched)
  1591. break;
  1592. }
  1593. prevFilterC = filterC;
  1594. }
  1595. }
  1596. if (matched)
  1597. matchedIndices.push_back(optionIdx);
  1598. }
  1599. };
  1600. // if (typeInstance->IsTypedPrimitive())
  1601. // {
  1602. // auto underlyingType = typeInstance->GetUnderlyingType();
  1603. // if (underlyingType != NULL)
  1604. // {
  1605. // String typeName = TypeToString(underlyingType);
  1606. // _CheckTypeName(typeName);
  1607. // }
  1608. // else
  1609. // {
  1610. // // Can this only happen for functions that are being extended?
  1611. // }
  1612. // }
  1613. //
  1614. // if ((!typeInstance->IsBoxed()) && (typeInstance->mTypeDef == mCompiler->mPointerTTypeDef))
  1615. // {
  1616. // BF_ASSERT(typeInstance->IsGenericTypeInstance());
  1617. // auto innerType = typeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  1618. // auto ptrType = CreatePointerType(innerType);
  1619. // String typeName = TypeToString(ptrType);
  1620. // _CheckTypeName(typeName);
  1621. // }
  1622. String typeName = BfTypeUtils::TypeToString(typeDef);
  1623. _CheckTypeName(typeName);
  1624. int matchedIdx = -1;
  1625. if (matchedIndices.size() == 1)
  1626. {
  1627. matchedIdx = matchedIndices[0];
  1628. }
  1629. else if (matchedIndices.size() > 1)
  1630. {
  1631. // Try to find a merged typeoptions with these indices
  1632. for (int mergedIdx = 0; mergedIdx < (int)mContext->mSystem->mMergedTypeOptions.size(); mergedIdx++)
  1633. {
  1634. auto& typeOptions = mContext->mSystem->mMergedTypeOptions[mergedIdx];
  1635. if (typeOptions.mMatchedIndices == matchedIndices)
  1636. {
  1637. matchedIdx = typeOptionsCount + mergedIdx;
  1638. break;
  1639. }
  1640. }
  1641. // Otherwise make one...
  1642. if (matchedIdx == -1)
  1643. {
  1644. auto& first = mContext->mSystem->mTypeOptions[matchedIndices[0]];
  1645. BfTypeOptions mergedTypeOptions;
  1646. mergedTypeOptions.mSIMDSetting = first.mSIMDSetting;
  1647. mergedTypeOptions.mOptimizationLevel = first.mOptimizationLevel;
  1648. mergedTypeOptions.mEmitDebugInfo = first.mEmitDebugInfo;
  1649. mergedTypeOptions.mAndFlags = first.mAndFlags;
  1650. mergedTypeOptions.mOrFlags = first.mOrFlags;
  1651. mergedTypeOptions.mAllocStackTraceDepth = first.mAllocStackTraceDepth;
  1652. mergedTypeOptions.mReflectMethodFilters = first.mReflectMethodFilters;
  1653. mergedTypeOptions.mReflectMethodAttributeFilters = first.mReflectMethodAttributeFilters;
  1654. mergedTypeOptions.mMatchedIndices = matchedIndices;
  1655. for (int idx = 1; idx < (int)matchedIndices.size(); idx++)
  1656. {
  1657. auto& typeOptions = mContext->mSystem->mTypeOptions[matchedIndices[idx]];
  1658. if (typeOptions.mSIMDSetting != -1)
  1659. mergedTypeOptions.mSIMDSetting = typeOptions.mSIMDSetting;
  1660. if (typeOptions.mOptimizationLevel != -1)
  1661. mergedTypeOptions.mOptimizationLevel = typeOptions.mOptimizationLevel;
  1662. if (typeOptions.mEmitDebugInfo != -1)
  1663. mergedTypeOptions.mEmitDebugInfo = typeOptions.mEmitDebugInfo;
  1664. mergedTypeOptions.mOrFlags = (BfOptionFlags)(mergedTypeOptions.mOrFlags | typeOptions.mOrFlags);
  1665. mergedTypeOptions.mAndFlags = (BfOptionFlags)(mergedTypeOptions.mAndFlags | typeOptions.mOrFlags);
  1666. mergedTypeOptions.mAndFlags = (BfOptionFlags)(mergedTypeOptions.mAndFlags & typeOptions.mAndFlags);
  1667. mergedTypeOptions.mOrFlags = (BfOptionFlags)(mergedTypeOptions.mOrFlags & typeOptions.mAndFlags);
  1668. if (mergedTypeOptions.HasReflectMethodFilters())
  1669. {
  1670. // If merging filter has non-default method flags but no filter then we need to append it as a filtered modification
  1671. if ((!typeOptions.HasReflectMethodFilters()) &&
  1672. (((typeOptions.mAndFlags & BfOptionFlags_Reflect_MethodMask) != BfOptionFlags_Reflect_MethodMask) ||
  1673. ((typeOptions.mOrFlags & BfOptionFlags_Reflect_MethodMask) != 0)))
  1674. {
  1675. mergedTypeOptions.mReflectMethodFilters.Add({"*", typeOptions.mAndFlags, typeOptions.mOrFlags});
  1676. }
  1677. mergedTypeOptions.mAndFlags = (BfOptionFlags)(mergedTypeOptions.mAndFlags | BfOptionFlags_Reflect_MethodMask);
  1678. mergedTypeOptions.mOrFlags = (BfOptionFlags)(mergedTypeOptions.mOrFlags & ~BfOptionFlags_Reflect_MethodMask);
  1679. }
  1680. if (typeOptions.mAllocStackTraceDepth != -1)
  1681. mergedTypeOptions.mAllocStackTraceDepth = typeOptions.mAllocStackTraceDepth;
  1682. for (auto filter : typeOptions.mReflectMethodFilters)
  1683. mergedTypeOptions.mReflectMethodFilters.Add(filter);
  1684. for (auto filter : typeOptions.mReflectMethodAttributeFilters)
  1685. mergedTypeOptions.mReflectMethodAttributeFilters.Add(filter);
  1686. }
  1687. matchedIdx = typeOptionsCount + (int)mContext->mSystem->mMergedTypeOptions.size();
  1688. mContext->mSystem->mMergedTypeOptions.push_back(mergedTypeOptions);
  1689. }
  1690. }
  1691. return mSystem->GetTypeOptions( matchedIdx);
  1692. }
  1693. bool BfModule::ApplyTypeOptionMethodFilters(bool includeMethod, BfMethodDef* methodDef, BfTypeOptions* typeOptions)
  1694. {
  1695. BfOptionFlags findFlag = BfOptionFlags_None;
  1696. if (methodDef->mMethodType == BfMethodType_Ctor)
  1697. findFlag = BfOptionFlags_ReflectConstructors;
  1698. else if (methodDef->mIsStatic)
  1699. findFlag = BfOptionFlags_ReflectStaticMethods;
  1700. else
  1701. findFlag = BfOptionFlags_ReflectNonStaticMethods;
  1702. if ((typeOptions->mAndFlags & findFlag) == 0)
  1703. includeMethod = false;
  1704. if ((typeOptions->mOrFlags & findFlag) != 0)
  1705. includeMethod = true;
  1706. if (!typeOptions->mReflectMethodFilters.IsEmpty())
  1707. {
  1708. for (auto& filter : typeOptions->mReflectMethodFilters)
  1709. {
  1710. if (BfCheckWildcard(filter.mFilter, methodDef->mName))
  1711. {
  1712. if ((filter.mAndFlags & findFlag) == 0)
  1713. includeMethod = false;
  1714. if ((filter.mAndFlags | findFlag) != 0)
  1715. includeMethod = true;
  1716. }
  1717. }
  1718. }
  1719. return includeMethod;
  1720. }
  1721. int BfModule::GenerateTypeOptions(BfCustomAttributes* customAttributes, BfTypeInstance* typeInstance, bool checkTypeName)
  1722. {
  1723. if (mContext->mSystem->mTypeOptions.size() == 0)
  1724. {
  1725. return -1;
  1726. }
  1727. Array<int> matchedIndices;
  1728. if ((!checkTypeName) && (typeInstance->mTypeOptionsIdx != -1))
  1729. {
  1730. // Methods should 'inherit' the owner's type options before applying type options from custom attributes
  1731. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  1732. if (typeOptions->mMatchedIndices.size() == 0)
  1733. matchedIndices.push_back(typeInstance->mTypeOptionsIdx);
  1734. else
  1735. matchedIndices = typeOptions->mMatchedIndices;
  1736. }
  1737. if (customAttributes != NULL)
  1738. {
  1739. if (!mCompiler->mAttributeTypeOptionMap.IsEmpty())
  1740. {
  1741. StringT<128> attrName;
  1742. for (auto& customAttrs : customAttributes->mAttributes)
  1743. {
  1744. attrName.Clear();
  1745. customAttrs.mType->mTypeDef->mFullName.ToString(attrName);
  1746. Array<int>* arrPtr;
  1747. if (mCompiler->mAttributeTypeOptionMap.TryGetValue(attrName, &arrPtr))
  1748. {
  1749. for (auto optionsIdx : *arrPtr)
  1750. {
  1751. matchedIndices.Add(optionsIdx);
  1752. }
  1753. }
  1754. }
  1755. }
  1756. }
  1757. int typeOptionsCount = (int)mContext->mSystem->mTypeOptions.size();
  1758. if (checkTypeName)
  1759. {
  1760. auto _CheckType = [&](BfType* type)
  1761. {
  1762. StringImpl typeName = TypeToString(type);
  1763. for (int optionIdx = 0; optionIdx < (int)mContext->mSystem->mTypeOptions.size(); optionIdx++)
  1764. {
  1765. auto& typeOptions = mContext->mSystem->mTypeOptions[optionIdx];
  1766. bool matched = false;
  1767. for (auto& filter : typeOptions.mTypeFilters)
  1768. {
  1769. int filterIdx = 0;
  1770. int typeNameIdx = 0;
  1771. if (filter.StartsWith(':'))
  1772. {
  1773. BfTypeInstance* typeInst = type->ToTypeInstance();
  1774. if (typeInst != NULL)
  1775. {
  1776. int startPos = 1;
  1777. for (; startPos < (int)filter.length(); startPos++)
  1778. if (filter[startPos] != ' ')
  1779. break;
  1780. String checkFilter;
  1781. checkFilter.Reference(filter.c_str() + startPos, filter.mLength - startPos);
  1782. BfTypeInstance* checkTypeInst = typeInst;
  1783. while (checkTypeInst != NULL)
  1784. {
  1785. for (auto& iface : checkTypeInst->mInterfaces)
  1786. {
  1787. StringT<128> ifaceName = TypeToString(iface.mInterfaceType);
  1788. if (BfCheckWildcard(checkFilter, ifaceName))
  1789. {
  1790. matched = true;
  1791. break;
  1792. }
  1793. }
  1794. checkTypeInst = checkTypeInst->mBaseType;
  1795. }
  1796. if (matched)
  1797. break;
  1798. }
  1799. }
  1800. else if (BfCheckWildcard(filter, typeName))
  1801. {
  1802. matched = true;
  1803. break;
  1804. }
  1805. }
  1806. if (matched)
  1807. matchedIndices.push_back(optionIdx);
  1808. }
  1809. };
  1810. if (typeInstance->IsTypedPrimitive())
  1811. {
  1812. auto underlyingType = typeInstance->GetUnderlyingType();
  1813. if (underlyingType != NULL)
  1814. {
  1815. _CheckType(underlyingType);
  1816. }
  1817. else
  1818. {
  1819. // Can this only happen for functions that are being extended?
  1820. }
  1821. }
  1822. if ((!typeInstance->IsBoxed()) && (typeInstance->IsInstanceOf(mCompiler->mPointerTTypeDef)))
  1823. {
  1824. BF_ASSERT(typeInstance->IsGenericTypeInstance());
  1825. auto innerType = typeInstance->mGenericTypeInfo->mTypeGenericArguments[0];
  1826. auto ptrType = CreatePointerType(innerType);
  1827. _CheckType(ptrType);
  1828. }
  1829. _CheckType(typeInstance);
  1830. }
  1831. int matchedIdx = -1;
  1832. if (matchedIndices.size() == 1)
  1833. {
  1834. matchedIdx = matchedIndices[0];
  1835. }
  1836. else if (matchedIndices.size() > 1)
  1837. {
  1838. // Try to find a merged typeoptions with these indices
  1839. for (int mergedIdx = 0; mergedIdx < (int)mContext->mSystem->mMergedTypeOptions.size(); mergedIdx++)
  1840. {
  1841. auto& typeOptions = mContext->mSystem->mMergedTypeOptions[mergedIdx];
  1842. if (typeOptions.mMatchedIndices == matchedIndices)
  1843. {
  1844. matchedIdx = typeOptionsCount + mergedIdx;
  1845. break;
  1846. }
  1847. }
  1848. // Otherwise make one...
  1849. if (matchedIdx == -1)
  1850. {
  1851. auto& first = mContext->mSystem->mTypeOptions[matchedIndices[0]];
  1852. BfTypeOptions mergedTypeOptions;
  1853. mergedTypeOptions.mSIMDSetting = first.mSIMDSetting;
  1854. mergedTypeOptions.mOptimizationLevel = first.mOptimizationLevel;
  1855. mergedTypeOptions.mEmitDebugInfo = first.mEmitDebugInfo;
  1856. mergedTypeOptions.mAndFlags = first.mAndFlags;
  1857. mergedTypeOptions.mOrFlags = first.mOrFlags;
  1858. mergedTypeOptions.mAllocStackTraceDepth = first.mAllocStackTraceDepth;
  1859. mergedTypeOptions.mReflectMethodFilters = first.mReflectMethodFilters;
  1860. mergedTypeOptions.mReflectMethodAttributeFilters = first.mReflectMethodAttributeFilters;
  1861. mergedTypeOptions.mMatchedIndices = matchedIndices;
  1862. for (int idx = 1; idx < (int)matchedIndices.size(); idx++)
  1863. {
  1864. auto& typeOptions = mContext->mSystem->mTypeOptions[matchedIndices[idx]];
  1865. if (typeOptions.mSIMDSetting != -1)
  1866. mergedTypeOptions.mSIMDSetting = typeOptions.mSIMDSetting;
  1867. if (typeOptions.mOptimizationLevel != -1)
  1868. mergedTypeOptions.mOptimizationLevel = typeOptions.mOptimizationLevel;
  1869. if (typeOptions.mEmitDebugInfo != -1)
  1870. mergedTypeOptions.mEmitDebugInfo = typeOptions.mEmitDebugInfo;
  1871. mergedTypeOptions.mOrFlags = (BfOptionFlags)(mergedTypeOptions.mOrFlags | typeOptions.mOrFlags);
  1872. mergedTypeOptions.mAndFlags = (BfOptionFlags)(mergedTypeOptions.mAndFlags | typeOptions.mOrFlags);
  1873. mergedTypeOptions.mAndFlags = (BfOptionFlags)(mergedTypeOptions.mAndFlags & typeOptions.mAndFlags);
  1874. mergedTypeOptions.mOrFlags = (BfOptionFlags)(mergedTypeOptions.mOrFlags & typeOptions.mAndFlags);
  1875. if (typeOptions.mAllocStackTraceDepth != -1)
  1876. mergedTypeOptions.mAllocStackTraceDepth = typeOptions.mAllocStackTraceDepth;
  1877. for (auto& filter : typeOptions.mReflectMethodFilters)
  1878. mergedTypeOptions.mReflectMethodFilters.Add(filter);
  1879. for (auto& filter : typeOptions.mReflectMethodAttributeFilters)
  1880. mergedTypeOptions.mReflectMethodAttributeFilters.Add(filter);
  1881. }
  1882. matchedIdx = typeOptionsCount + (int)mContext->mSystem->mMergedTypeOptions.size();
  1883. mContext->mSystem->mMergedTypeOptions.push_back(mergedTypeOptions);
  1884. }
  1885. }
  1886. return matchedIdx;
  1887. }
  1888. void BfModule::SetTypeOptions(BfTypeInstance* typeInstance)
  1889. {
  1890. typeInstance->mTypeOptionsIdx = GenerateTypeOptions(typeInstance->mCustomAttributes, typeInstance, true);
  1891. }
  1892. BfCEParseContext BfModule::CEEmitParse(BfTypeInstance* typeInstance, BfTypeDef* declaringType, const StringImpl& src, BfAstNode* refNode, BfCeTypeEmitSourceKind emitSourceKind)
  1893. {
  1894. if (mCompiler->mResolvePassData != NULL)
  1895. mCompiler->mResolvePassData->mHadEmits = true;
  1896. BfCEParseContext ceParseContext;
  1897. ceParseContext.mFailIdx = mCompiler->mPassInstance->mFailedIdx;
  1898. ceParseContext.mWarnIdx = mCompiler->mPassInstance->mWarnIdx;
  1899. if (typeInstance->mTypeDef->mEmitParent == NULL)
  1900. {
  1901. if (typeInstance->mTypeDef->mNextRevision != NULL)
  1902. {
  1903. InternalError("CEEmitParse preconditions failed");
  1904. return ceParseContext;
  1905. }
  1906. }
  1907. bool createdParser = false;
  1908. int startSrcIdx = 0;
  1909. BfParser* emitParser = NULL;
  1910. int64 emitSourceMapKey = ((int64)declaringType->mPartialIdx << 32) | refNode->mSrcStart;
  1911. if (typeInstance->mCeTypeInfo == NULL)
  1912. typeInstance->mCeTypeInfo = new BfCeTypeInfo();
  1913. auto ceTypeInfo = typeInstance->mCeTypeInfo;
  1914. if (ceTypeInfo->mNext != NULL)
  1915. ceTypeInfo = ceTypeInfo->mNext;
  1916. BfCeTypeEmitSource* ceEmitSource = NULL;
  1917. if ((mCurMethodState != NULL) && (mCurMethodState->mClosureState != NULL) && (mCurMethodState->mClosureState->mCapturing))
  1918. {
  1919. // Don't create emit sources when we're in a capture phase
  1920. }
  1921. else
  1922. {
  1923. auto refParser = refNode->GetParser();
  1924. if ((refParser != NULL) && (refParser->mIsEmitted))
  1925. {
  1926. // Default to type declaration
  1927. emitSourceMapKey = mCurTypeInstance->mTypeDef->GetRefNode()->mSrcStart;
  1928. for (auto& kv : ceTypeInfo->mEmitSourceMap)
  1929. {
  1930. if ((refNode->mSrcStart >= kv.mValue.mSrcStart) && (refNode->mSrcStart < kv.mValue.mSrcEnd))
  1931. {
  1932. // We found the initial emit source
  1933. emitSourceMapKey = kv.mKey;
  1934. break;
  1935. }
  1936. }
  1937. }
  1938. if (ceTypeInfo->mEmitSourceMap.TryAdd(emitSourceMapKey, NULL, &ceEmitSource))
  1939. {
  1940. if (typeInstance->IsSpecializedType())
  1941. {
  1942. auto unspecializedType = GetUnspecializedTypeInstance(typeInstance);
  1943. if ((unspecializedType->mCeTypeInfo == NULL) || (!unspecializedType->mCeTypeInfo->mEmitSourceMap.ContainsKey(emitSourceMapKey)))
  1944. ceTypeInfo->mMayHaveUniqueEmitLocations = true;
  1945. }
  1946. }
  1947. ceEmitSource->mKind = emitSourceKind;
  1948. }
  1949. BfLogSysM("CEEmitParse type %p ceTypeInfo %p\n", typeInstance, ceTypeInfo);
  1950. int emitSrcStart = 0;
  1951. BfEmitEmbedEntry* emitEmbedEntry = NULL;
  1952. if (typeInstance->mTypeDef->mEmitParent == NULL)
  1953. {
  1954. BF_ASSERT(typeInstance->mTypeDef->mNextRevision == NULL);
  1955. BfTypeDef* emitTypeDef = new BfTypeDef();
  1956. emitTypeDef->mEmitParent = typeInstance->mTypeDef;
  1957. mSystem->CopyTypeDef(emitTypeDef, typeInstance->mTypeDef);
  1958. emitTypeDef->mDefState = BfTypeDef::DefState_Emitted;
  1959. typeInstance->mTypeDef = emitTypeDef;
  1960. createdParser = true;
  1961. emitParser = new BfParser(mSystem, typeInstance->mTypeDef->mProject);
  1962. emitParser->mIsEmitted = true;
  1963. BfLogSys(mSystem, "Emit typeDef for type %p created %p parser %p typeDecl %p\n", typeInstance, emitTypeDef, emitParser, emitTypeDef->mTypeDeclaration);
  1964. String typeName = TypeToString(typeInstance, BfTypeNameFlag_AddProjectName);
  1965. if ((mCompiler->mResolvePassData != NULL) && (!mCompiler->mResolvePassData->mEmitEmbedEntries.IsEmpty()))
  1966. mCompiler->mResolvePassData->mEmitEmbedEntries.TryGetValue(typeName, &emitEmbedEntry);
  1967. emitParser->mFileName = "$Emit$";
  1968. emitParser->mFileName += typeName;
  1969. emitTypeDef->mSource = emitParser;
  1970. emitParser->mRefCount++;
  1971. emitParser->SetSource(src.c_str(), src.mLength);
  1972. if (emitEmbedEntry != NULL)
  1973. {
  1974. emitEmbedEntry->mRevision = typeInstance->mRevision;
  1975. emitEmbedEntry->mParser = emitParser;
  1976. emitEmbedEntry->mParser->mSourceClassifier = new BfSourceClassifier(emitEmbedEntry->mParser, NULL);
  1977. mCompiler->mPassInstance->mFilterErrorsTo.Add(emitEmbedEntry->mParser->mParserData);
  1978. if (emitEmbedEntry->mCursorIdx != -1)
  1979. {
  1980. emitParser->SetCursorIdx(emitEmbedEntry->mCursorIdx);
  1981. emitParser->mParserFlags = (BfParserFlag)(emitParser->mParserFlags | ParserFlag_Autocomplete | ParserFlag_Classifying);
  1982. }
  1983. }
  1984. // If we emit only from method attributes then we will already have method instances created
  1985. auto _FixMethod = [&](BfMethodInstance* methodInstance)
  1986. {
  1987. if (methodInstance == NULL)
  1988. return;
  1989. methodInstance->mMethodDef = emitTypeDef->mMethods[methodInstance->mMethodDef->mIdx];
  1990. };
  1991. for (auto& methodInstanceGroup : typeInstance->mMethodInstanceGroups)
  1992. {
  1993. _FixMethod(methodInstanceGroup.mDefault);
  1994. if (methodInstanceGroup.mMethodSpecializationMap != NULL)
  1995. {
  1996. for (auto& kv : *methodInstanceGroup.mMethodSpecializationMap)
  1997. _FixMethod(kv.mValue);
  1998. }
  1999. };
  2000. }
  2001. else
  2002. {
  2003. emitParser = typeInstance->mTypeDef->mSource->ToParser();
  2004. if ((mCompiler->mResolvePassData != NULL) && (!mCompiler->mResolvePassData->mEmitEmbedEntries.IsEmpty()))
  2005. {
  2006. int dollarPos = (int)emitParser->mFileName.LastIndexOf('$');
  2007. if (dollarPos != -1)
  2008. mCompiler->mResolvePassData->mEmitEmbedEntries.TryGetValue(emitParser->mFileName.Substring(dollarPos + 1), &emitEmbedEntry);
  2009. }
  2010. int idx = emitParser->AllocChars(2 + src.mLength + 1);
  2011. emitSrcStart = idx + 2;
  2012. memcpy((uint8*)emitParser->mSrc + idx, "\n\n", 2);
  2013. memcpy((uint8*)emitParser->mSrc + idx + 2, src.c_str(), src.mLength + 1);
  2014. emitParser->mSrcIdx = idx;
  2015. emitParser->mSrcLength = idx + src.mLength + 2;
  2016. emitParser->mParserData->mSrcLength = emitParser->mSrcLength;
  2017. emitParser->mOrigSrcLength = emitParser->mSrcLength;
  2018. }
  2019. if (ceEmitSource == NULL)
  2020. {
  2021. // Ignored
  2022. }
  2023. else if (ceEmitSource->mSrcStart == -1)
  2024. {
  2025. auto parserData = refNode->GetParserData();
  2026. if (parserData != NULL)
  2027. {
  2028. // Add the warning changes occur before the start of the buffer.
  2029. // We use this conservatively now - any temporary disabling will permanently disable
  2030. for (auto& warning : parserData->mWarningEnabledChanges)
  2031. {
  2032. if (!warning.mValue.mEnable)
  2033. emitParser->mParserData->mWarningEnabledChanges[-warning.mValue.mWarningNumber] = warning.mValue;
  2034. }
  2035. }
  2036. ceEmitSource->mSrcStart = emitSrcStart;
  2037. ceEmitSource->mSrcEnd = emitParser->mSrcLength;
  2038. }
  2039. else
  2040. {
  2041. ceEmitSource->mSrcStart = BF_MIN(ceEmitSource->mSrcStart, emitSrcStart);
  2042. ceEmitSource->mSrcEnd = BF_MAX(ceEmitSource->mSrcEnd, emitParser->mSrcLength);
  2043. }
  2044. emitParser->Parse(mCompiler->mPassInstance);
  2045. emitParser->FinishSideNodes();
  2046. if (emitEmbedEntry != NULL)
  2047. {
  2048. int prevStart = emitEmbedEntry->mCharData.mSize;
  2049. emitEmbedEntry->mCharData.GrowUninitialized(emitParser->mSrcLength - emitEmbedEntry->mCharData.mSize);
  2050. auto charDataPtr = emitEmbedEntry->mCharData.mVals;
  2051. for (int i = prevStart; i < emitParser->mSrcLength; i++)
  2052. {
  2053. charDataPtr[i].mChar = emitParser->mSrc[i];
  2054. charDataPtr[i].mDisplayPassId = 0;
  2055. charDataPtr[i].mDisplayTypeId = 0;
  2056. charDataPtr[i].mDisplayFlags = 0;
  2057. }
  2058. emitEmbedEntry->mParser->mSourceClassifier->mCharData = emitEmbedEntry->mCharData.mVals;
  2059. }
  2060. if (createdParser)
  2061. {
  2062. AutoCrit crit(mSystem->mDataLock);
  2063. mSystem->mParsers.Add(emitParser);
  2064. }
  2065. return ceParseContext;
  2066. }
  2067. void BfModule::FinishCEParseContext(BfAstNode* refNode, BfTypeInstance* typeInstance, BfCEParseContext* ceParseContext)
  2068. {
  2069. if ((ceParseContext->mFailIdx != mCompiler->mPassInstance->mFailedIdx) && (refNode != NULL))
  2070. Fail("Emitted code had errors", refNode);
  2071. else if ((ceParseContext->mWarnIdx != mCompiler->mPassInstance->mWarnIdx) && (refNode != NULL))
  2072. Warn(0, "Emitted code had warnings", refNode);
  2073. else if ((ceParseContext->mFailIdx != mCompiler->mPassInstance->mFailedIdx) ||
  2074. (ceParseContext->mWarnIdx != mCompiler->mPassInstance->mWarnIdx))
  2075. {
  2076. AddFailType(typeInstance);
  2077. }
  2078. }
  2079. void BfModule::UpdateCEEmit(CeEmitContext* ceEmitContext, BfTypeInstance* typeInstance, BfTypeDef* declaringType, const StringImpl& ctxString, BfAstNode* refNode, BfCeTypeEmitSourceKind emitSourceKind)
  2080. {
  2081. for (int ifaceTypeId : ceEmitContext->mInterfaces)
  2082. typeInstance->mCeTypeInfo->mPendingInterfaces.Add(ifaceTypeId);
  2083. if (ceEmitContext->mEmitData.IsEmpty())
  2084. return;
  2085. String src;
  2086. // if (typeInstance->mTypeDef->mEmitParent != NULL)
  2087. // src += "\n\n";
  2088. // src += "// Code emission in ";
  2089. // src += ctxString;
  2090. // src += "\n\n";
  2091. src += ceEmitContext->mEmitData;
  2092. ceEmitContext->mEmitData.Clear();
  2093. BfCEParseContext ceParseContext = CEEmitParse(typeInstance, declaringType, src, refNode, emitSourceKind);
  2094. auto emitParser = typeInstance->mTypeDef->mSource->ToParser();
  2095. auto typeDeclaration = emitParser->mAlloc->Alloc<BfTypeDeclaration>();
  2096. BfReducer bfReducer;
  2097. bfReducer.mSource = emitParser;
  2098. bfReducer.mPassInstance = mCompiler->mPassInstance;
  2099. bfReducer.mAlloc = emitParser->mAlloc;
  2100. bfReducer.mSystem = mSystem;
  2101. bfReducer.mCurTypeDecl = typeDeclaration;
  2102. typeDeclaration->mDefineNode = emitParser->mRootNode;
  2103. bfReducer.HandleTypeDeclaration(typeDeclaration, NULL);
  2104. BfDefBuilder defBuilder(mSystem);
  2105. defBuilder.mCurSource = emitParser;
  2106. defBuilder.mCurTypeDef = typeInstance->mTypeDef;
  2107. defBuilder.mCurDeclaringTypeDef = typeInstance->mTypeDef;
  2108. defBuilder.mPassInstance = mCompiler->mPassInstance;
  2109. defBuilder.mIsComptime = true;
  2110. defBuilder.DoVisitChild(typeDeclaration->mDefineNode);
  2111. defBuilder.FinishTypeDef(typeInstance->mTypeDef->mTypeCode == BfTypeCode_Enum);
  2112. FinishCEParseContext(refNode, typeInstance, &ceParseContext);
  2113. if (emitParser->mSourceClassifier != NULL)
  2114. {
  2115. emitParser->mSourceClassifier->VisitChild(emitParser->mRootNode);
  2116. emitParser->mSourceClassifier->DeferNodes(emitParser->mSidechannelRootNode);
  2117. emitParser->mSourceClassifier->DeferNodes(emitParser->mErrorRootNode);
  2118. }
  2119. if (typeInstance->mTypeDef->mEmitParent != NULL)
  2120. {
  2121. // Remove generated fields like the 'underlying type' enum field
  2122. typeInstance->mFieldInstances.Resize(typeInstance->mTypeDef->mEmitParent->mFields.mSize);
  2123. }
  2124. }
  2125. void BfModule::HandleCEAttributes(CeEmitContext* ceEmitContext, BfTypeInstance* typeInstance, BfFieldInstance* fieldInstance, BfCustomAttributes* customAttributes, Dictionary<BfTypeInstance*, BfIRValue>& prevAttrInstances, bool underlyingTypeDeferred)
  2126. {
  2127. for (auto& customAttribute : customAttributes->mAttributes)
  2128. {
  2129. if ((customAttribute.mDeclaringType->IsExtension()) && (typeInstance->IsGenericTypeInstance()) && (!typeInstance->IsUnspecializedTypeVariation()))
  2130. {
  2131. if (!typeInstance->IsTypeMemberIncluded(customAttribute.mDeclaringType, typeInstance->mTypeDef, this))
  2132. continue;
  2133. }
  2134. auto attrType = customAttribute.mType;
  2135. BfMethodInstance* methodInstance = NULL;
  2136. bool isFieldApply = false;
  2137. BfIRValue irValue;
  2138. int checkDepth = 0;
  2139. auto checkAttrType = attrType;
  2140. while (checkAttrType != NULL)
  2141. {
  2142. mContext->mUnreifiedModule->PopulateType(checkAttrType, BfPopulateType_DataAndMethods);
  2143. if (checkAttrType->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  2144. break;
  2145. for (auto& ifaceEntry : checkAttrType->mInterfaces)
  2146. {
  2147. isFieldApply = false;
  2148. isFieldApply = (ceEmitContext != NULL) && (fieldInstance != NULL) && (ifaceEntry.mInterfaceType->IsInstanceOf(mCompiler->mIOnFieldInitTypeDef));
  2149. if ((isFieldApply) ||
  2150. ((ceEmitContext != NULL) && (ifaceEntry.mInterfaceType->IsInstanceOf(mCompiler->mIComptimeTypeApply))) ||
  2151. ((ceEmitContext != NULL) && (ifaceEntry.mInterfaceType->IsInstanceOf(mCompiler->mIOnTypeInitTypeDef))) ||
  2152. ((ceEmitContext == NULL) && (ifaceEntry.mInterfaceType->IsInstanceOf(mCompiler->mIOnTypeDoneTypeDef))))
  2153. {
  2154. // Passes
  2155. }
  2156. else
  2157. continue;
  2158. prevAttrInstances.TryGetValue(checkAttrType, &irValue);
  2159. methodInstance = checkAttrType->mInterfaceMethodTable[ifaceEntry.mStartInterfaceTableIdx].mMethodRef;
  2160. break;
  2161. }
  2162. if (methodInstance != NULL)
  2163. break;
  2164. checkAttrType = checkAttrType->mBaseType;
  2165. checkDepth++;
  2166. }
  2167. if (methodInstance == NULL)
  2168. continue;
  2169. SetAndRestoreValue<CeEmitContext*> prevEmitContext(mCompiler->mCeMachine->mCurEmitContext, ceEmitContext);
  2170. auto ceContext = mCompiler->mCeMachine->AllocContext();
  2171. defer({ mCompiler->mCeMachine->ReleaseContext(ceContext); });
  2172. BfIRValue attrVal =ceContext->CreateAttribute(customAttribute.mRef, this, typeInstance->mConstHolder, &customAttribute);
  2173. for (int baseIdx = 0; baseIdx < checkDepth; baseIdx++)
  2174. attrVal = mBfIRBuilder->CreateExtractValue(attrVal, 0);
  2175. SizedArray<BfIRValue, 1> args;
  2176. if (!attrType->IsValuelessType())
  2177. args.Add(attrVal);
  2178. if (isFieldApply)
  2179. {
  2180. auto fieldInfoType = ResolveTypeDef(mCompiler->mReflectFieldInfoTypeDef);
  2181. if (fieldInfoType != NULL)
  2182. {
  2183. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  2184. SizedArray<BfIRValue, 9> fieldData =
  2185. {
  2186. mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(fieldInfoType->ToTypeInstance()->mBaseType, BfIRPopulateType_Identity)),
  2187. mBfIRBuilder->CreateTypeOf(mCurTypeInstance), // mTypeInstance
  2188. CreateFieldData(fieldInstance, -1)
  2189. };
  2190. FixConstValueParams(fieldInfoType->ToTypeInstance(), fieldData);
  2191. auto fieldDataAgg = mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(fieldInfoType, BfIRPopulateType_Identity), fieldData);
  2192. args.Add(fieldDataAgg);
  2193. }
  2194. }
  2195. else
  2196. args.Add(mBfIRBuilder->CreateTypeOf(typeInstance));
  2197. if (methodInstance->GetParamCount() > 1)
  2198. {
  2199. if (irValue)
  2200. args.Add(irValue);
  2201. else
  2202. args.Add(mBfIRBuilder->CreateConstNull());
  2203. }
  2204. else
  2205. {
  2206. // Only allow a single instance
  2207. if (irValue)
  2208. continue;
  2209. }
  2210. DoPopulateType_CeCheckEnum(typeInstance, underlyingTypeDeferred);
  2211. if (fieldInstance != NULL)
  2212. mCompiler->mCeMachine->mFieldInstanceSet.Add(fieldInstance);
  2213. BfTypedValue result;
  2214. ///
  2215. {
  2216. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  2217. CeCallSource callSource;
  2218. callSource.mRefNode = customAttribute.mRef;
  2219. if (isFieldApply)
  2220. {
  2221. callSource.mKind = CeCallSource::Kind_FieldInit;
  2222. callSource.mFieldInstance = fieldInstance;
  2223. }
  2224. else if (ceEmitContext != NULL)
  2225. {
  2226. callSource.mKind = CeCallSource::Kind_TypeInit;
  2227. }
  2228. else
  2229. {
  2230. callSource.mKind = CeCallSource::Kind_TypeDone;
  2231. }
  2232. result = ceContext->Call(callSource, this, methodInstance, args, (CeEvalFlags)(CeEvalFlags_ForceReturnThis | CeEvalFlags_IgnoreConstEncodeFailure), NULL);
  2233. }
  2234. if (fieldInstance != NULL)
  2235. mCompiler->mCeMachine->mFieldInstanceSet.Remove(fieldInstance);
  2236. if (result.mType == methodInstance->GetOwner())
  2237. prevAttrInstances[methodInstance->GetOwner()] = result.mValue;
  2238. if (ceEmitContext == NULL)
  2239. continue;
  2240. if (typeInstance->mDefineState == BfTypeDefineState_DefinedAndMethodsSlotted)
  2241. return;
  2242. if (typeInstance->mDefineState != BfTypeDefineState_CETypeInit)
  2243. {
  2244. // We populated before we could finish
  2245. AssertErrorState();
  2246. }
  2247. else
  2248. {
  2249. auto owner = methodInstance->GetOwner();
  2250. int typeId = owner->mTypeId;
  2251. if ((!result) && (mCompiler->mFastFinish))
  2252. {
  2253. if ((typeInstance->mCeTypeInfo != NULL) && (typeInstance->mCeTypeInfo->mNext == NULL))
  2254. typeInstance->mCeTypeInfo->mNext = new BfCeTypeInfo();
  2255. if ((typeInstance->mCeTypeInfo != NULL) && (typeInstance->mCeTypeInfo->mNext != NULL))
  2256. typeInstance->mCeTypeInfo->mNext->mFastFinished = true;
  2257. if (typeInstance->mCeTypeInfo != NULL)
  2258. {
  2259. BfCeTypeEmitEntry* entry = NULL;
  2260. if (typeInstance->mCeTypeInfo->mTypeIFaceMap.TryGetValue(typeId, &entry))
  2261. {
  2262. ceEmitContext->mEmitData = entry->mEmitData;
  2263. }
  2264. }
  2265. }
  2266. else
  2267. {
  2268. if (ceEmitContext->HasEmissions())
  2269. {
  2270. if (typeInstance->mCeTypeInfo == NULL)
  2271. typeInstance->mCeTypeInfo = new BfCeTypeInfo();
  2272. if (typeInstance->mCeTypeInfo->mNext == NULL)
  2273. typeInstance->mCeTypeInfo->mNext = new BfCeTypeInfo();
  2274. BfCeTypeEmitEntry entry;
  2275. entry.mEmitData = ceEmitContext->mEmitData;
  2276. typeInstance->mCeTypeInfo->mNext->mTypeIFaceMap[typeId] = entry;
  2277. typeInstance->mCeTypeInfo->mNext->mAlign = BF_MAX(typeInstance->mCeTypeInfo->mNext->mAlign, ceEmitContext->mAlign);
  2278. }
  2279. if ((ceEmitContext->mFailed) && (typeInstance->mCeTypeInfo != NULL))
  2280. typeInstance->mCeTypeInfo->mFailed = true;
  2281. }
  2282. if ((ceEmitContext->HasEmissions()) && (!mCompiler->mFastFinish))
  2283. {
  2284. String ctxStr = "comptime ";
  2285. ctxStr += methodInstance->mMethodDef->mName;
  2286. ctxStr += " of ";
  2287. ctxStr += TypeToString(attrType);
  2288. ctxStr += " to ";
  2289. ctxStr += TypeToString(typeInstance);
  2290. ctxStr += " ";
  2291. ctxStr += customAttribute.mRef->LocationToString();
  2292. UpdateCEEmit(ceEmitContext, typeInstance, customAttribute.mDeclaringType, ctxStr, customAttribute.mRef, BfCeTypeEmitSourceKind_Type);
  2293. }
  2294. }
  2295. }
  2296. }
  2297. void BfModule::CEMixin(BfAstNode* refNode, const StringImpl& code)
  2298. {
  2299. if (code.IsEmpty())
  2300. return;
  2301. if (mCurMethodInstance == NULL)
  2302. {
  2303. Fail("Invalid code mixin", refNode);
  2304. return;
  2305. }
  2306. auto activeTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  2307. //auto emitParser = activeTypeDef->mEmitParser;
  2308. String src;
  2309. // if (mCurTypeInstance->mTypeDef->mEmitParent != NULL)
  2310. // src += "\n\n";
  2311. // src += "// Code emission in ";
  2312. // src += MethodToString(mCurMethodInstance);
  2313. // src += "\n";
  2314. src += code;
  2315. BfReducer bfReducer;
  2316. bfReducer.mPassInstance = mCompiler->mPassInstance;
  2317. bfReducer.mSystem = mSystem;
  2318. bfReducer.mCurTypeDecl = activeTypeDef->mTypeDeclaration;
  2319. bfReducer.mCurMethodDecl = BfNodeDynCast<BfMethodDeclaration>(mCurMethodInstance->mMethodDef->mMethodDeclaration);
  2320. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, refNode);
  2321. EmitEnsureInstructionAt();
  2322. BfCEParseContext ceParseContext = CEEmitParse(mCurTypeInstance, activeTypeDef, src, refNode, BfCeTypeEmitSourceKind_Method);
  2323. auto emitParser = mCurTypeInstance->mTypeDef->mSource->ToParser();
  2324. bfReducer.mSource = emitParser;
  2325. bfReducer.mAlloc = emitParser->mAlloc;
  2326. bfReducer.HandleBlock(emitParser->mRootNode, false);
  2327. if (emitParser->mSourceClassifier != NULL)
  2328. {
  2329. emitParser->mSourceClassifier->VisitChild(emitParser->mRootNode);
  2330. emitParser->mSourceClassifier->VisitChild(emitParser->mSidechannelRootNode);
  2331. emitParser->mSourceClassifier->VisitChild(emitParser->mErrorRootNode);
  2332. }
  2333. Visit(emitParser->mRootNode);
  2334. prevCustomAttribute.Restore();
  2335. FinishCEParseContext(refNode, mCurTypeInstance, &ceParseContext);
  2336. }
  2337. void BfModule::ExecuteCEOnCompile(CeEmitContext* ceEmitContext, BfTypeInstance* typeInstance, BfCEOnCompileKind onCompileKind, bool underlyingTypeDeferred)
  2338. {
  2339. Dictionary<BfTypeInstance*, BfIRValue> prevAttrInstances;
  2340. if (typeInstance->mCustomAttributes != NULL)
  2341. HandleCEAttributes(ceEmitContext, typeInstance, NULL, typeInstance->mCustomAttributes, prevAttrInstances, underlyingTypeDeferred);
  2342. if (ceEmitContext != NULL)
  2343. {
  2344. for (auto& fieldInstance : typeInstance->mFieldInstances)
  2345. {
  2346. if (fieldInstance.mCustomAttributes != NULL)
  2347. HandleCEAttributes(ceEmitContext, typeInstance, &fieldInstance, fieldInstance.mCustomAttributes, prevAttrInstances, underlyingTypeDeferred);
  2348. }
  2349. for (auto methodDef : typeInstance->mTypeDef->mMethods)
  2350. {
  2351. auto methodDeclaration = methodDef->GetMethodDeclaration();
  2352. auto propertyMethodDeclaration = methodDef->GetPropertyMethodDeclaration();
  2353. BfAttributeTargets attrTarget = ((methodDef->mMethodType == BfMethodType_Ctor) || (methodDef->mMethodType == BfMethodType_CtorCalcAppend)) ? BfAttributeTargets_Constructor : BfAttributeTargets_Method;
  2354. BfAttributeDirective* attributeDirective = NULL;
  2355. if (methodDeclaration != NULL)
  2356. attributeDirective = methodDeclaration->mAttributes;
  2357. else if (propertyMethodDeclaration != NULL)
  2358. {
  2359. attributeDirective = propertyMethodDeclaration->mAttributes;
  2360. if (auto exprBody = BfNodeDynCast<BfPropertyBodyExpression>(propertyMethodDeclaration->mPropertyDeclaration->mDefinitionBlock))
  2361. {
  2362. attributeDirective = propertyMethodDeclaration->mPropertyDeclaration->mAttributes;
  2363. attrTarget = (BfAttributeTargets)(BfAttributeTargets_Property | BfAttributeTargets_Method);
  2364. }
  2365. }
  2366. if (attributeDirective == NULL)
  2367. continue;
  2368. // Corlib will never need to process
  2369. if (methodDef->mDeclaringType->mProject == mContext->mBfObjectType->mTypeDef->mProject)
  2370. continue;
  2371. if (methodDef->mDeclaringType != mCurTypeInstance->mTypeDef)
  2372. {
  2373. if (typeInstance->IsUnspecializedTypeVariation())
  2374. continue;
  2375. if (!typeInstance->IsTypeMemberIncluded(methodDef->mDeclaringType, mCurTypeInstance->mTypeDef, this))
  2376. continue;
  2377. }
  2378. if (methodDef->mIdx >= typeInstance->mMethodInstanceGroups.mSize)
  2379. continue;
  2380. auto& methodInstanceGroup = typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  2381. if (methodInstanceGroup.mDefaultCustomAttributes == NULL)
  2382. {
  2383. BfTypeState typeState;
  2384. typeState.mPrevState = mContext->mCurTypeState;
  2385. typeState.mForceActiveTypeDef = methodDef->mDeclaringType;
  2386. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  2387. methodInstanceGroup.mDefaultCustomAttributes = GetCustomAttributes(attributeDirective, attrTarget);
  2388. }
  2389. HandleCEAttributes(ceEmitContext, typeInstance, NULL, methodInstanceGroup.mDefaultCustomAttributes, prevAttrInstances, underlyingTypeDeferred);
  2390. }
  2391. }
  2392. int methodCount = (int)typeInstance->mTypeDef->mMethods.size();
  2393. for (int methodIdx = 0; methodIdx < methodCount; methodIdx++)
  2394. {
  2395. auto methodDef = typeInstance->mTypeDef->mMethods[methodIdx];
  2396. auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration);
  2397. if (methodDeclaration == NULL)
  2398. continue;
  2399. if (methodDeclaration->mAttributes == NULL)
  2400. continue;
  2401. BfTypeState typeState;
  2402. typeState.mPrevState = mContext->mCurTypeState;
  2403. typeState.mForceActiveTypeDef = methodDef->mDeclaringType;
  2404. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  2405. bool wantsAttributes = false;
  2406. BfAttributeDirective* checkAttributes = methodDeclaration->mAttributes;
  2407. while (checkAttributes != NULL)
  2408. {
  2409. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, true);
  2410. BfType* attrType = ResolveTypeRef(checkAttributes->mAttributeTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_NoReify));
  2411. if (attrType != NULL)
  2412. {
  2413. if (attrType->IsInstanceOf(mCompiler->mOnCompileAttributeTypeDef))
  2414. wantsAttributes = true;
  2415. auto attrTypeInstance = attrType->ToTypeInstance();
  2416. if ((attrTypeInstance != NULL) && (!attrTypeInstance->mInterfaces.IsEmpty()))
  2417. wantsAttributes = true;
  2418. }
  2419. checkAttributes = checkAttributes->mNextAttribute;
  2420. }
  2421. if (!wantsAttributes)
  2422. continue;
  2423. auto customAttributes = GetCustomAttributes(methodDeclaration->mAttributes, BfAttributeTargets_Method);
  2424. defer({ delete customAttributes; });
  2425. auto onCompileAttribute = customAttributes->Get(mCompiler->mOnCompileAttributeTypeDef);
  2426. if (onCompileAttribute == NULL)
  2427. continue;
  2428. HandleCEAttributes(ceEmitContext, typeInstance, NULL, customAttributes, prevAttrInstances, underlyingTypeDeferred);
  2429. if (onCompileAttribute->mCtorArgs.size() < 1)
  2430. continue;
  2431. auto constant = typeInstance->mConstHolder->GetConstant(onCompileAttribute->mCtorArgs[0]);
  2432. if (constant == NULL)
  2433. continue;
  2434. if (onCompileKind != (BfCEOnCompileKind)constant->mInt32)
  2435. continue;
  2436. if (!methodDef->mIsStatic)
  2437. {
  2438. Fail("OnCompile methods must be static", methodDeclaration);
  2439. continue;
  2440. }
  2441. if (!methodDef->mParams.IsEmpty())
  2442. {
  2443. Fail("OnCompile methods cannot declare parameters", methodDeclaration);
  2444. continue;
  2445. }
  2446. SetAndRestoreValue<CeEmitContext*> prevEmitContext(mCompiler->mCeMachine->mCurEmitContext);
  2447. if (onCompileKind == BfCEOnCompileKind_TypeInit)
  2448. {
  2449. mCompiler->mCeMachine->mCurEmitContext = ceEmitContext;
  2450. }
  2451. DoPopulateType_CeCheckEnum(typeInstance, underlyingTypeDeferred);
  2452. BfTypedValue result;
  2453. BfMethodInstance* methodInstance = NULL;
  2454. ///
  2455. {
  2456. auto useTypeInstance = typeInstance;
  2457. if (useTypeInstance->IsUnspecializedTypeVariation())
  2458. useTypeInstance = GetUnspecializedTypeInstance(useTypeInstance);
  2459. BfType* prevContextTypeInstance = NULL;
  2460. if (ceEmitContext != NULL)
  2461. {
  2462. prevContextTypeInstance = ceEmitContext->mType;
  2463. ceEmitContext->mType = useTypeInstance;
  2464. }
  2465. methodInstance = GetRawMethodInstanceAtIdx(useTypeInstance, methodDef->mIdx);
  2466. result = mCompiler->mCeMachine->Call(methodDef->GetRefNode(), this, methodInstance, {}, (CeEvalFlags)(CeEvalFlags_PersistantError | CeEvalFlags_DeferIfNotOnlyError), NULL);
  2467. if (ceEmitContext != NULL)
  2468. ceEmitContext->mType = prevContextTypeInstance;
  2469. }
  2470. if ((onCompileKind == BfCEOnCompileKind_TypeDone) && (typeInstance->mDefineState > BfTypeDefineState_CETypeInit))
  2471. {
  2472. // Type done, okay
  2473. }
  2474. else if (typeInstance->mDefineState != BfTypeDefineState_CETypeInit)
  2475. {
  2476. // We populated before we could finish
  2477. AssertErrorState();
  2478. }
  2479. else
  2480. {
  2481. if ((!result) && (mCompiler->mFastFinish))
  2482. {
  2483. if ((typeInstance->mCeTypeInfo != NULL) && (typeInstance->mCeTypeInfo->mNext == NULL))
  2484. typeInstance->mCeTypeInfo->mNext = new BfCeTypeInfo();
  2485. if ((typeInstance->mCeTypeInfo != NULL) && (typeInstance->mCeTypeInfo->mNext != NULL))
  2486. typeInstance->mCeTypeInfo->mNext->mFastFinished = true;
  2487. if (typeInstance->mCeTypeInfo != NULL)
  2488. {
  2489. BfCeTypeEmitEntry* entry = NULL;
  2490. if (typeInstance->mCeTypeInfo->mOnCompileMap.TryGetValue(methodDef->mIdx, &entry))
  2491. {
  2492. ceEmitContext->mEmitData = entry->mEmitData;
  2493. }
  2494. }
  2495. }
  2496. else if (!ceEmitContext->mEmitData.IsEmpty())
  2497. {
  2498. if (typeInstance->mCeTypeInfo == NULL)
  2499. typeInstance->mCeTypeInfo = new BfCeTypeInfo();
  2500. if (typeInstance->mCeTypeInfo->mNext == NULL)
  2501. typeInstance->mCeTypeInfo->mNext = new BfCeTypeInfo();
  2502. BfCeTypeEmitEntry entry;
  2503. entry.mEmitData = ceEmitContext->mEmitData;
  2504. typeInstance->mCeTypeInfo->mNext->mOnCompileMap[methodDef->mIdx] = entry;
  2505. }
  2506. else if ((ceEmitContext->mFailed) && (typeInstance->mCeTypeInfo != NULL))
  2507. typeInstance->mCeTypeInfo->mFailed = true;
  2508. if (!ceEmitContext->mEmitData.IsEmpty())
  2509. {
  2510. String ctxStr = "OnCompile execution of ";
  2511. ctxStr += MethodToString(methodInstance);
  2512. ctxStr += " ";
  2513. ctxStr += methodInstance->mMethodDef->GetRefNode()->LocationToString();
  2514. UpdateCEEmit(ceEmitContext, typeInstance, methodDef->mDeclaringType, ctxStr, methodInstance->mMethodDef->GetRefNode(), BfCeTypeEmitSourceKind_Type);
  2515. }
  2516. }
  2517. if (mCompiler->mCanceling)
  2518. {
  2519. DeferRebuildType(typeInstance);
  2520. }
  2521. }
  2522. // if ((!typeInstance->IsInstanceOf(mCompiler->mValueTypeTypeDef)) &&
  2523. // (!typeInstance->IsInstanceOf(mCompiler->mBfObjectTypeDef)) &&
  2524. // (!typeInstance->IsBoxed()) &&
  2525. // (!typeInstance->IsDelegate()) &&
  2526. // (!typeInstance->IsTuple()))
  2527. // {
  2528. // //zTODO: TESTING, remove!
  2529. // CEEmitParse(typeInstance, "// Testing");
  2530. // }
  2531. }
  2532. void BfModule::DoCEEmit(BfTypeInstance* typeInstance, bool& hadNewMembers, bool underlyingTypeDeferred)
  2533. {
  2534. BfLogSysM("BfModule::DoCEEmit %p\n", typeInstance);
  2535. if (((typeInstance->IsInstanceOf(mCompiler->mValueTypeTypeDef))) ||
  2536. ((typeInstance->IsInstanceOf(mCompiler->mEnumTypeDef))) ||
  2537. ((typeInstance->IsInstanceOf(mCompiler->mAttributeTypeDef))))
  2538. {
  2539. // These are not allowed to emit
  2540. return;
  2541. }
  2542. CeEmitContext ceEmitContext;
  2543. ceEmitContext.mType = typeInstance;
  2544. ExecuteCEOnCompile(&ceEmitContext, typeInstance, BfCEOnCompileKind_TypeInit, underlyingTypeDeferred);
  2545. hadNewMembers = (typeInstance->mTypeDef->mEmitParent != NULL);
  2546. if (ceEmitContext.mFailed)
  2547. TypeFailed(typeInstance);
  2548. }
  2549. void BfModule::DoCEEmit(BfMethodInstance* methodInstance)
  2550. {
  2551. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  2552. return;
  2553. auto customAttributes = methodInstance->GetCustomAttributes();
  2554. if (customAttributes == NULL)
  2555. return;
  2556. auto typeInstance = methodInstance->GetOwner();
  2557. CeEmitContext ceEmitContext;
  2558. ceEmitContext.mMethodInstance = methodInstance;
  2559. Dictionary<BfTypeInstance*, BfIRValue> prevAttrInstances;
  2560. for (auto& customAttribute : customAttributes->mAttributes)
  2561. {
  2562. auto attrType = customAttribute.mType;
  2563. BfMethodInstance* applyMethodInstance = NULL;
  2564. BfIRValue irValue;
  2565. int checkDepth = 0;
  2566. auto checkAttrType = attrType;
  2567. while (checkAttrType != NULL)
  2568. {
  2569. mContext->mUnreifiedModule->PopulateType(checkAttrType, BfPopulateType_DataAndMethods);
  2570. if (checkAttrType->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted)
  2571. break;
  2572. for (auto& ifaceEntry : checkAttrType->mInterfaces)
  2573. {
  2574. if ((!ifaceEntry.mInterfaceType->IsInstanceOf(mCompiler->mIComptimeMethodApply)) &&
  2575. (!ifaceEntry.mInterfaceType->IsInstanceOf(mCompiler->mIOnMethodInitTypeDef)))
  2576. continue;
  2577. prevAttrInstances.TryGetValue(checkAttrType, &irValue);
  2578. applyMethodInstance = checkAttrType->mInterfaceMethodTable[ifaceEntry.mStartInterfaceTableIdx].mMethodRef;
  2579. break;
  2580. }
  2581. if (applyMethodInstance != NULL)
  2582. break;
  2583. checkAttrType = checkAttrType->mBaseType;
  2584. checkDepth++;
  2585. }
  2586. if (applyMethodInstance == NULL)
  2587. continue;
  2588. SetAndRestoreValue<CeEmitContext*> prevEmitContext(mCompiler->mCeMachine->mCurEmitContext, &ceEmitContext);
  2589. auto ceContext = mCompiler->mCeMachine->AllocContext();
  2590. BfIRValue attrVal = ceContext->CreateAttribute(customAttribute.mRef, this, typeInstance->mConstHolder, &customAttribute);
  2591. for (int baseIdx = 0; baseIdx < checkDepth; baseIdx++)
  2592. attrVal = mBfIRBuilder->CreateExtractValue(attrVal, 0);
  2593. SizedArray<BfIRValue, 1> args;
  2594. if (!attrType->IsValuelessType())
  2595. args.Add(attrVal);
  2596. auto methodInfoType = ResolveTypeDef(mCompiler->mReflectMethodInfoTypeDef);
  2597. SizedArray<BfIRValue, 9> methodData =
  2598. {
  2599. mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(methodInfoType->ToTypeInstance()->mBaseType, BfIRPopulateType_Identity)),
  2600. mBfIRBuilder->CreateTypeOf(mCurTypeInstance), // mTypeInstance
  2601. GetConstValue((int64)methodInstance, GetPrimitiveType(BfTypeCode_Int64)), // mNativeMethodInstance
  2602. };
  2603. FixConstValueParams(methodInfoType->ToTypeInstance(), methodData, true);
  2604. auto fieldDataAgg = mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(methodInfoType, BfIRPopulateType_Identity), methodData);
  2605. args.Add(fieldDataAgg);
  2606. if (applyMethodInstance->GetParamCount() > 1)
  2607. {
  2608. if (irValue)
  2609. args.Add(irValue);
  2610. else
  2611. args.Add(mBfIRBuilder->CreateConstNull());
  2612. }
  2613. else
  2614. {
  2615. // Only allow a single instance
  2616. if (irValue)
  2617. continue;
  2618. }
  2619. mCompiler->mCeMachine->mMethodInstanceSet.Add(methodInstance);
  2620. auto activeTypeDef = typeInstance->mTypeDef;
  2621. BfTypedValue result;
  2622. ///
  2623. {
  2624. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  2625. CeCallSource callSource;
  2626. callSource.mRefNode = customAttribute.mRef;
  2627. callSource.mKind = CeCallSource::Kind_MethodInit;
  2628. result = ceContext->Call(callSource, this, applyMethodInstance, args, CeEvalFlags_ForceReturnThis, NULL);
  2629. }
  2630. if (result.mType == methodInstance->GetOwner())
  2631. prevAttrInstances[methodInstance->GetOwner()] = result.mValue;
  2632. if ((!result) && (mCompiler->mFastFinish))
  2633. {
  2634. methodInstance->mCeCancelled = true;
  2635. }
  2636. if ((!ceEmitContext.mEmitData.IsEmpty()) || (!ceEmitContext.mExitEmitData.IsEmpty()))
  2637. {
  2638. String src;
  2639. // src += "// Code emission in comptime ApplyToMethod of ";
  2640. // src += TypeToString(attrType);
  2641. // src += " to ";
  2642. // src += MethodToString(methodInstance);
  2643. // src += " ";
  2644. // src += customAttribute.mRef->LocationToString();
  2645. // src += "\n";
  2646. //auto emitTypeDef = typeInstance->mCeTypeInfo->mNext->mTypeDef;
  2647. //auto emitParser = emitTypeDef->mSource->ToParser();
  2648. //auto emitParser = activeTypeDef->mEmitParser;
  2649. BfReducer bfReducer;
  2650. //bfReducer.mSource = emitParser;
  2651. bfReducer.mPassInstance = mCompiler->mPassInstance;
  2652. bfReducer.mSystem = mSystem;
  2653. bfReducer.mCurTypeDecl = activeTypeDef->mTypeDeclaration;
  2654. bfReducer.mCurMethodDecl = BfNodeDynCast<BfMethodDeclaration>(methodInstance->mMethodDef->mMethodDeclaration);
  2655. BfAstNode* bodyNode = NULL;
  2656. if (auto methodDecl = BfNodeDynCast<BfMethodDeclaration>(methodInstance->mMethodDef->mMethodDeclaration))
  2657. bodyNode = methodDecl->mBody;
  2658. auto _Classify = [&](BfParser* emitParser)
  2659. {
  2660. if (emitParser->mSourceClassifier == NULL)
  2661. return;
  2662. emitParser->mSourceClassifier->VisitChild(emitParser->mRootNode);
  2663. emitParser->mSourceClassifier->VisitChild(emitParser->mSidechannelRootNode);
  2664. emitParser->mSourceClassifier->VisitChild(emitParser->mErrorRootNode);
  2665. };
  2666. if (!ceEmitContext.mEmitData.IsEmpty())
  2667. {
  2668. SetAndRestoreValue<BfAstNode*> prevCustomAttribute(mCurMethodState->mEmitRefNode, customAttribute.mRef);
  2669. String entrySrc = src;
  2670. // if (mCurTypeInstance->mTypeDef->mEmitParent != NULL)
  2671. // entrySrc += "\n\n";
  2672. entrySrc += src;
  2673. entrySrc += ceEmitContext.mEmitData;
  2674. BfAstNode* refNode = customAttribute.mRef;
  2675. if (bodyNode != NULL)
  2676. {
  2677. refNode = bodyNode;
  2678. if (auto blockNode = BfNodeDynCast<BfBlock>(bodyNode))
  2679. if (blockNode->mOpenBrace != NULL)
  2680. refNode = blockNode->mOpenBrace;
  2681. }
  2682. BfCEParseContext ceParseContext = CEEmitParse(typeInstance, methodInstance->mMethodDef->mDeclaringType, entrySrc, refNode, BfCeTypeEmitSourceKind_Type);
  2683. auto emitParser = mCurTypeInstance->mTypeDef->mSource->ToParser();
  2684. bfReducer.mSource = emitParser;
  2685. bfReducer.mAlloc = emitParser->mAlloc;
  2686. bfReducer.HandleBlock(emitParser->mRootNode, false);
  2687. _Classify(emitParser);
  2688. Visit(emitParser->mRootNode);
  2689. FinishCEParseContext(customAttribute.mRef, typeInstance, &ceParseContext);
  2690. }
  2691. if (!ceEmitContext.mExitEmitData.IsEmpty())
  2692. {
  2693. String exitSrc;
  2694. if (mCurTypeInstance->mTypeDef->mEmitParent != NULL)
  2695. exitSrc += "\n\n";
  2696. exitSrc += src;
  2697. exitSrc += ceEmitContext.mExitEmitData;
  2698. BfAstNode* refNode = customAttribute.mRef;
  2699. if (bodyNode != NULL)
  2700. {
  2701. refNode = bodyNode;
  2702. if (auto blockNode = BfNodeDynCast<BfBlock>(bodyNode))
  2703. if (blockNode->mCloseBrace != NULL)
  2704. refNode = blockNode->mCloseBrace;
  2705. }
  2706. BfCEParseContext ceParseContext = CEEmitParse(typeInstance, methodInstance->mMethodDef->mDeclaringType, exitSrc, refNode, BfCeTypeEmitSourceKind_Type);
  2707. auto emitParser = mCurTypeInstance->mTypeDef->mSource->ToParser();
  2708. bfReducer.mSource = emitParser;
  2709. bfReducer.mAlloc = emitParser->mAlloc;
  2710. bfReducer.HandleBlock(emitParser->mRootNode, false);
  2711. _Classify(emitParser);
  2712. auto deferredBlock = AddDeferredBlock(emitParser->mRootNode, &mCurMethodState->mHeadScope);
  2713. deferredBlock->mEmitRefNode = customAttribute.mRef;
  2714. FinishCEParseContext(customAttribute.mRef, typeInstance, &ceParseContext);
  2715. }
  2716. }
  2717. mCompiler->mCeMachine->ReleaseContext(ceContext);
  2718. }
  2719. }
  2720. void BfModule::PopulateUsingFieldData(BfTypeInstance* typeInstance)
  2721. {
  2722. if (typeInstance->mTypeInfoEx == NULL)
  2723. typeInstance->mTypeInfoEx = new BfTypeInfoEx();
  2724. BfUsingFieldData* usingFieldData;
  2725. if (typeInstance->mTypeInfoEx->mUsingFieldData != NULL)
  2726. {
  2727. usingFieldData = typeInstance->mTypeInfoEx->mUsingFieldData;
  2728. Array<BfTypeInstance*> populatedTypes;
  2729. for (auto checkType : usingFieldData->mAwaitingPopulateSet)
  2730. {
  2731. if (checkType->mDefineState >= BfTypeDefineState_Defined)
  2732. populatedTypes.Add(checkType);
  2733. }
  2734. if (populatedTypes.IsEmpty())
  2735. return;
  2736. for (auto type : populatedTypes)
  2737. usingFieldData->mAwaitingPopulateSet.Remove(type);
  2738. usingFieldData->mEntries.Clear();
  2739. usingFieldData->mMethods.Clear();
  2740. }
  2741. else
  2742. {
  2743. usingFieldData = new BfUsingFieldData();
  2744. typeInstance->mTypeInfoEx->mUsingFieldData = usingFieldData;
  2745. }
  2746. HashSet<BfTypeInstance*> checkedTypeSet;
  2747. Array<BfUsingFieldData::MemberRef> memberRefs;
  2748. std::function<void(BfTypeInstance*, bool)> _CheckType = [&](BfTypeInstance* usingType, bool staticOnly)
  2749. {
  2750. if (!checkedTypeSet.Add(usingType))
  2751. return;
  2752. defer(
  2753. {
  2754. checkedTypeSet.Remove(usingType);
  2755. });
  2756. for (auto fieldDef : usingType->mTypeDef->mFields)
  2757. {
  2758. if ((staticOnly) && (!fieldDef->mIsStatic))
  2759. continue;
  2760. memberRefs.Add(BfUsingFieldData::MemberRef(usingType, fieldDef));
  2761. defer(
  2762. {
  2763. memberRefs.pop_back();
  2764. });
  2765. if (memberRefs.Count() > 1)
  2766. {
  2767. BfUsingFieldData::Entry* entry = NULL;
  2768. usingFieldData->mEntries.TryAdd(fieldDef->mName, NULL, &entry);
  2769. SizedArray<BfUsingFieldData::MemberRef, 1> lookup;
  2770. for (auto entry : memberRefs)
  2771. lookup.Add(entry);
  2772. entry->mLookups.Add(lookup);
  2773. }
  2774. if (fieldDef->mUsingProtection == BfProtection_Hidden)
  2775. continue;
  2776. if (usingType->mDefineState < BfTypeDefineState_Defined)
  2777. {
  2778. bool isPopulatingType = false;
  2779. auto checkTypeState = mContext->mCurTypeState;
  2780. while (checkTypeState != NULL)
  2781. {
  2782. if ((checkTypeState->mType == usingType) && (checkTypeState->mPopulateType >= BfPopulateType_Data))
  2783. {
  2784. isPopulatingType = true;
  2785. break;
  2786. }
  2787. checkTypeState = checkTypeState->mPrevState;
  2788. }
  2789. if (!isPopulatingType)
  2790. {
  2791. // We need to populate this type now
  2792. PopulateType(usingType, BfPopulateType_Data_Soft);
  2793. }
  2794. if (usingType->mDefineState < BfTypeDefineState_Defined)
  2795. typeInstance->mTypeInfoEx->mUsingFieldData->mAwaitingPopulateSet.Add(usingType);
  2796. }
  2797. auto fieldInstance = &usingType->mFieldInstances[fieldDef->mIdx];
  2798. auto fieldTypeInst = fieldInstance->mResolvedType->ToTypeInstance();
  2799. if (fieldTypeInst != NULL)
  2800. _CheckType(fieldTypeInst, fieldDef->mIsStatic);
  2801. }
  2802. for (auto propDef : usingType->mTypeDef->mProperties)
  2803. {
  2804. if ((staticOnly) && (!propDef->mIsStatic))
  2805. continue;
  2806. memberRefs.Add(BfUsingFieldData::MemberRef(usingType, propDef));
  2807. defer(
  2808. {
  2809. memberRefs.pop_back();
  2810. });
  2811. if (memberRefs.Count() > 1)
  2812. {
  2813. BfUsingFieldData::Entry* entry = NULL;
  2814. usingFieldData->mEntries.TryAdd(propDef->mName, NULL, &entry);
  2815. SizedArray<BfUsingFieldData::MemberRef, 1> lookup;
  2816. for (auto entry : memberRefs)
  2817. lookup.Add(entry);
  2818. entry->mLookups.Add(lookup);
  2819. }
  2820. if (propDef->mUsingProtection == BfProtection_Hidden)
  2821. continue;
  2822. if (usingType->mDefineState < BfTypeDefineState_Defined)
  2823. {
  2824. // We need to populate this type now
  2825. PopulateType(usingType);
  2826. }
  2827. BfType* propType = NULL;
  2828. for (auto methodDef : propDef->mMethods)
  2829. {
  2830. auto methodInstance = GetRawMethodInstance(usingType, methodDef);
  2831. if (methodInstance == NULL)
  2832. continue;
  2833. if (methodDef->mMethodType == BfMethodType_PropertyGetter)
  2834. {
  2835. propType = methodInstance->mReturnType;
  2836. break;
  2837. }
  2838. if (methodDef->mMethodType == BfMethodType_PropertySetter)
  2839. {
  2840. if (methodInstance->GetParamCount() > 0)
  2841. {
  2842. propType = methodInstance->GetParamType(0);
  2843. break;
  2844. }
  2845. }
  2846. }
  2847. if ((propType != NULL) && (propType->IsTypeInstance()))
  2848. _CheckType(propType->ToTypeInstance(), propDef->mIsStatic);
  2849. }
  2850. for (auto methodDef : usingType->mTypeDef->mMethods)
  2851. {
  2852. if ((staticOnly) && (!methodDef->mIsStatic))
  2853. continue;
  2854. //TODO: Support mixins as well
  2855. if (methodDef->mMethodType != BfMethodType_Normal)
  2856. continue;
  2857. // No auto methods
  2858. if (methodDef->mMethodDeclaration == NULL)
  2859. continue;
  2860. memberRefs.Add(BfUsingFieldData::MemberRef(usingType, methodDef));
  2861. defer(
  2862. {
  2863. memberRefs.pop_back();
  2864. });
  2865. if (memberRefs.Count() > 1)
  2866. {
  2867. BfUsingFieldData::Entry* entry = NULL;
  2868. usingFieldData->mMethods.TryAdd(methodDef->mName, NULL, &entry);
  2869. SizedArray<BfUsingFieldData::MemberRef, 1> lookup;
  2870. for (auto entry : memberRefs)
  2871. lookup.Add(entry);
  2872. entry->mLookups.Add(lookup);
  2873. }
  2874. }
  2875. };
  2876. _CheckType(typeInstance, false);
  2877. }
  2878. void BfModule::DoPopulateType_SetGenericDependencies(BfTypeInstance* genericTypeInstance)
  2879. {
  2880. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, genericTypeInstance);
  2881. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  2882. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  2883. // Add generic dependencies if needed
  2884. for (auto genericArgType : genericTypeInstance->mGenericTypeInfo->mTypeGenericArguments)
  2885. {
  2886. if (genericArgType->IsPrimitiveType())
  2887. genericArgType = GetWrappedStructType(genericArgType);
  2888. if (genericArgType != NULL)
  2889. {
  2890. AddDependency(genericArgType, genericTypeInstance, BfDependencyMap::DependencyFlag_TypeGenericArg);
  2891. BfLogSysM("Adding generic dependency of %p for type %p revision %d\n", genericArgType, genericTypeInstance, genericTypeInstance->mRevision);
  2892. #ifdef _DEBUG
  2893. // auto argDepType = genericArgType->ToDependedType();
  2894. // if (argDepType != NULL)
  2895. // {
  2896. // BfDependencyMap::DependencyEntry* depEntry = NULL;
  2897. // argDepType->mDependencyMap.mTypeSet.TryGetValue(genericTypeInstance, &depEntry);
  2898. // BF_ASSERT(depEntry != NULL);
  2899. // BF_ASSERT(depEntry->mRevision == genericTypeInstance->mRevision);
  2900. // BF_ASSERT((depEntry->mFlags & BfDependencyMap::DependencyFlag_TypeGenericArg) != 0);
  2901. // }
  2902. #endif
  2903. }
  2904. }
  2905. if ((genericTypeInstance->IsSpecializedType()) &&
  2906. (!genericTypeInstance->IsDelegateFromTypeRef()) &&
  2907. (!genericTypeInstance->IsFunctionFromTypeRef()))
  2908. {
  2909. // This ensures we rebuild the unspecialized type whenever the specialized type rebuilds. This is important
  2910. // for generic type binding
  2911. auto unspecializedTypeInstance = GetUnspecializedTypeInstance(genericTypeInstance);
  2912. BF_ASSERT(!unspecializedTypeInstance->IsUnspecializedTypeVariation());
  2913. mContext->mScratchModule->AddDependency(genericTypeInstance, unspecializedTypeInstance, BfDependencyMap::DependencyFlag_UnspecializedType);
  2914. }
  2915. }
  2916. void BfModule::DoPopulateType_TypeAlias(BfTypeAliasType* typeAlias)
  2917. {
  2918. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeAlias);
  2919. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  2920. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  2921. BF_ASSERT(mCurMethodInstance == NULL);
  2922. auto typeDef = typeAlias->mTypeDef;
  2923. auto typeAliasDecl = (BfTypeAliasDeclaration*)typeDef->mTypeDeclaration;
  2924. BfType* aliasToType = NULL;
  2925. if (typeAlias->mBaseType == NULL)
  2926. typeAlias->mBaseType = ResolveTypeDef(mCompiler->mValueTypeTypeDef)->ToTypeInstance();
  2927. if ((typeAlias->mGenericTypeInfo != NULL) && (!typeAlias->mGenericTypeInfo->mFinishedGenericParams))
  2928. FinishGenericParams(typeAlias);
  2929. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  2930. typeState.mPopulateType = BfPopulateType_Data;
  2931. typeState.mCurBaseTypeRef = typeAliasDecl->mAliasToType;
  2932. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  2933. if (typeAlias->mDefineState < BfTypeDefineState_Declaring)
  2934. {
  2935. typeAlias->mDefineState = BfTypeDefineState_Declaring;
  2936. DoPopulateType_InitSearches(typeAlias);
  2937. }
  2938. typeAlias->mDefineState = BfTypeDefineState_ResolvingBaseType;
  2939. if (!CheckCircularDataError())
  2940. {
  2941. if (typeAliasDecl->mAliasToType != NULL)
  2942. aliasToType = ResolveTypeRef(typeAliasDecl->mAliasToType, BfPopulateType_IdentityNoRemapAlias,
  2943. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_AllowGenericParamConstValue | BfResolveTypeRefFlag_AllowImplicitConstExpr));
  2944. }
  2945. BfLogSysM("DoPopulateType_TypeAlias %p %s = %p %s\n", typeAlias, TypeToString(typeAlias).c_str(), aliasToType, (aliasToType != NULL) ? TypeToString(aliasToType).c_str() : NULL);
  2946. if (aliasToType != NULL)
  2947. {
  2948. if (aliasToType->IsConstExprValue())
  2949. {
  2950. Fail(StrFormat("Illegal alias to type '%s'", TypeToString(aliasToType).c_str()), typeAlias->mTypeDef->GetRefNode());
  2951. aliasToType = NULL;
  2952. }
  2953. }
  2954. if (aliasToType != NULL)
  2955. {
  2956. AddDependency(aliasToType, typeAlias, BfDependencyMap::DependencyFlag_DerivedFrom);
  2957. }
  2958. else
  2959. mContext->mFailTypes.TryAdd(typeAlias, BfFailKind_Normal);
  2960. if (typeAlias->mTypeFailed)
  2961. aliasToType = NULL;
  2962. if ((typeAlias->mAliasToType != NULL) && (typeAlias->mAliasToType != aliasToType) && (!typeAlias->mDependencyMap.IsEmpty()))
  2963. mContext->QueueMidCompileRebuildDependentTypes(typeAlias, "type alias remapped");
  2964. typeAlias->mAliasToType = aliasToType;
  2965. if (aliasToType != NULL)
  2966. {
  2967. typeAlias->mSize = 0;
  2968. typeAlias->mAlign = 1;
  2969. typeAlias->mInstSize = 0;
  2970. typeAlias->mInstAlign = 1;
  2971. }
  2972. typeAlias->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  2973. typeAlias->mRebuildFlags = BfTypeRebuildFlag_None;
  2974. if ((typeAlias->mCustomAttributes == NULL) && (typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mAttributes != NULL))
  2975. typeAlias->mCustomAttributes = GetCustomAttributes(typeDef->mTypeDeclaration->mAttributes, BfAttributeTargets_Alias);
  2976. if (typeAlias->mGenericTypeInfo != NULL)
  2977. {
  2978. DoPopulateType_SetGenericDependencies(typeAlias);
  2979. }
  2980. }
  2981. void BfModule::DoPopulateType_InitSearches(BfTypeInstance* typeInstance)
  2982. {
  2983. auto typeDef = typeInstance->mTypeDef;
  2984. auto _AddStaticSearch = [&](BfTypeDef* typeDef)
  2985. {
  2986. if (!typeDef->mStaticSearch.IsEmpty())
  2987. {
  2988. BfStaticSearch* staticSearch;
  2989. if (typeInstance->mStaticSearchMap.TryAdd(typeDef, NULL, &staticSearch))
  2990. {
  2991. SetAndRestoreValue<BfTypeDef*> prevTypeDef(mContext->mCurTypeState->mCurTypeDef, typeDef);
  2992. for (auto typeRef : typeDef->mStaticSearch)
  2993. {
  2994. auto staticType = ResolveTypeRef(typeRef, NULL, BfPopulateType_Identity);
  2995. if (staticType != NULL)
  2996. {
  2997. auto staticTypeInst = staticType->ToTypeInstance();
  2998. if (staticTypeInst == NULL)
  2999. {
  3000. Fail(StrFormat("Type '%s' cannot be used in a 'using static' declaration", TypeToString(staticType).c_str()), typeRef);
  3001. }
  3002. else
  3003. {
  3004. staticSearch->mStaticTypes.Add(staticTypeInst);
  3005. AddDependency(staticTypeInst, typeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  3006. }
  3007. }
  3008. }
  3009. }
  3010. }
  3011. if (!typeDef->mInternalAccessSet.IsEmpty())
  3012. {
  3013. BfInternalAccessSet* internalAccessSet;
  3014. BF_ASSERT(!typeDef->IsEmitted());
  3015. if (typeInstance->mInternalAccessMap.TryAdd(typeDef, NULL, &internalAccessSet))
  3016. {
  3017. for (auto typeRef : typeDef->mInternalAccessSet)
  3018. {
  3019. if ((typeRef->IsA<BfNamedTypeReference>()) ||
  3020. (typeRef->IsA<BfQualifiedTypeReference>()))
  3021. {
  3022. String checkNamespaceStr;
  3023. typeRef->ToString(checkNamespaceStr);
  3024. BfAtomCompositeT<16> checkNamespace;
  3025. if (mSystem->ParseAtomComposite(checkNamespaceStr, checkNamespace))
  3026. {
  3027. if (mSystem->ContainsNamespace(checkNamespace, typeDef->mProject))
  3028. {
  3029. mSystem->RefAtomComposite(checkNamespace);
  3030. internalAccessSet->mNamespaces.Add(checkNamespace);
  3031. continue;
  3032. }
  3033. }
  3034. }
  3035. BfType* internalType = NULL;
  3036. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  3037. internalType = mContext->mScratchModule->ResolveTypeRefAllowUnboundGenerics(typeRef, BfPopulateType_Identity);
  3038. else
  3039. internalType = ResolveTypeRef(typeRef, NULL, BfPopulateType_Identity);
  3040. if (internalType != NULL)
  3041. {
  3042. auto internalTypeInst = internalType->ToTypeInstance();
  3043. if (internalTypeInst == NULL)
  3044. {
  3045. Fail(StrFormat("Type '%s' cannot be used in a 'using internal' declaration", TypeToString(internalType).c_str()), typeRef);
  3046. }
  3047. else
  3048. {
  3049. internalAccessSet->mTypes.Add(internalTypeInst);
  3050. AddDependency(internalTypeInst, typeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  3051. }
  3052. }
  3053. }
  3054. }
  3055. }
  3056. };
  3057. if (typeDef->mIsCombinedPartial)
  3058. {
  3059. for (auto partialTypeDef : typeDef->mPartials)
  3060. _AddStaticSearch(partialTypeDef);
  3061. }
  3062. else
  3063. _AddStaticSearch(typeDef);
  3064. }
  3065. void BfModule::DoPopulateType_FinishEnum(BfTypeInstance* typeInstance, bool underlyingTypeDeferred, HashContext* dataMemberHashCtx, BfType* unionInnerType)
  3066. {
  3067. if (typeInstance->IsEnum())
  3068. {
  3069. int64 min = 0;
  3070. int64 max = 0;
  3071. bool isFirst = true;
  3072. if (typeInstance->mTypeInfoEx == NULL)
  3073. typeInstance->mTypeInfoEx = new BfTypeInfoEx();
  3074. bool isAllInt64 = true;
  3075. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  3076. {
  3077. auto fieldInstance = &fieldInstanceRef;
  3078. auto fieldDef = fieldInstance->GetFieldDef();
  3079. if (fieldDef != NULL)
  3080. {
  3081. if ((fieldInstance->mConstIdx == -1) || (fieldInstance->mResolvedType != typeInstance))
  3082. continue;
  3083. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  3084. if (constant->mTypeCode != BfTypeCode_Int64)
  3085. isAllInt64 = false;
  3086. if (isFirst)
  3087. {
  3088. min = constant->mInt64;
  3089. max = constant->mInt64;
  3090. isFirst = false;
  3091. }
  3092. else
  3093. {
  3094. min = BF_MIN(constant->mInt64, min);
  3095. max = BF_MAX(constant->mInt64, max);
  3096. }
  3097. }
  3098. }
  3099. typeInstance->mTypeInfoEx->mMinValue = min;
  3100. typeInstance->mTypeInfoEx->mMaxValue = max;
  3101. if (underlyingTypeDeferred)
  3102. {
  3103. BfTypeCode typeCode;
  3104. if ((min == 0) && (max == 0))
  3105. typeCode = BfTypeCode_None;
  3106. else if ((min >= -0x80) && (max <= 0x7F))
  3107. typeCode = BfTypeCode_Int8;
  3108. else if ((min >= 0) && (max <= 0xFF))
  3109. typeCode = BfTypeCode_UInt8;
  3110. else if ((min >= -0x8000) && (max <= 0x7FFF))
  3111. typeCode = BfTypeCode_Int16;
  3112. else if ((min >= 0) && (max <= 0xFFFF))
  3113. typeCode = BfTypeCode_UInt16;
  3114. else if ((min >= -0x80000000LL) && (max <= 0x7FFFFFFF))
  3115. typeCode = BfTypeCode_Int32;
  3116. else if ((min >= 0) && (max <= 0xFFFFFFFFLL))
  3117. typeCode = BfTypeCode_UInt32;
  3118. else
  3119. typeCode = BfTypeCode_Int64;
  3120. if (typeInstance->mIsCRepr)
  3121. typeCode = BfTypeCode_Int32;
  3122. if ((typeCode != BfTypeCode_Int64) || (!isAllInt64))
  3123. {
  3124. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  3125. {
  3126. auto fieldInstance = &fieldInstanceRef;
  3127. if ((fieldInstance->mConstIdx == -1) || (fieldInstance->mResolvedType != typeInstance))
  3128. continue;
  3129. auto constant = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  3130. if (constant->mTypeCode == typeCode)
  3131. continue;
  3132. BfIRValue newConstant = typeInstance->mConstHolder->CreateConst(typeCode, constant->mUInt64);
  3133. fieldInstance->mConstIdx = newConstant.mId;
  3134. }
  3135. }
  3136. BfType* underlyingType = GetPrimitiveType(typeCode);
  3137. auto fieldInstance = &typeInstance->mFieldInstances.back();
  3138. fieldInstance->mResolvedType = underlyingType;
  3139. fieldInstance->mDataSize = underlyingType->mSize;
  3140. typeInstance->mTypeInfoEx->mUnderlyingType = underlyingType;
  3141. typeInstance->mSize = underlyingType->mSize;
  3142. typeInstance->mAlign = underlyingType->mAlign;
  3143. typeInstance->mInstSize = underlyingType->mSize;
  3144. typeInstance->mInstAlign = underlyingType->mAlign;
  3145. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags & ~BfTypeRebuildFlag_UnderlyingTypeDeferred);
  3146. }
  3147. }
  3148. else
  3149. {
  3150. BF_ASSERT(!underlyingTypeDeferred);
  3151. }
  3152. if ((typeInstance->IsPayloadEnum()) && (!typeInstance->IsBoxed()))
  3153. {
  3154. typeInstance->mAlign = unionInnerType->mAlign;
  3155. int lastTagId = -1;
  3156. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  3157. {
  3158. auto fieldInstance = &fieldInstanceRef;
  3159. auto fieldDef = fieldInstance->GetFieldDef();
  3160. if ((fieldDef != NULL) && (fieldInstance->mDataIdx < 0))
  3161. {
  3162. BF_ASSERT(fieldInstance->mResolvedType->mAlign >= 1);
  3163. typeInstance->mAlign = BF_MAX(typeInstance->mAlign, fieldInstance->mResolvedType->mAlign);
  3164. lastTagId = -fieldInstance->mDataIdx - 1;
  3165. }
  3166. }
  3167. auto fieldInstance = &typeInstance->mFieldInstances.back();
  3168. //BF_ASSERT(fieldInstance->mResolvedType == NULL);
  3169. BfPrimitiveType* discriminatorType;
  3170. if (lastTagId > 0x7FFFFFFF) // HOW?
  3171. discriminatorType = GetPrimitiveType(BfTypeCode_Int64);
  3172. else if (lastTagId > 0x7FFF)
  3173. discriminatorType = GetPrimitiveType(BfTypeCode_Int32);
  3174. else if (lastTagId > 0x7F)
  3175. discriminatorType = GetPrimitiveType(BfTypeCode_Int16);
  3176. else
  3177. discriminatorType = GetPrimitiveType(BfTypeCode_Int8);
  3178. fieldInstance->mResolvedType = discriminatorType;
  3179. fieldInstance->mDataOffset = unionInnerType->mSize;
  3180. fieldInstance->mDataIdx = 2; // 0 = base, 1 = payload, 2 = discriminator
  3181. if (typeInstance->mPacking == 0)
  3182. {
  3183. if ((fieldInstance->mDataOffset % discriminatorType->mAlign) != 0)
  3184. {
  3185. fieldInstance->mDataOffset = BF_ALIGN(fieldInstance->mDataOffset, discriminatorType->mAlign);
  3186. fieldInstance->mDataIdx++; // Add room for explicit padding
  3187. }
  3188. }
  3189. typeInstance->mAlign = BF_MAX(typeInstance->mAlign, discriminatorType->mAlign);
  3190. typeInstance->mSize = fieldInstance->mDataOffset + discriminatorType->mSize;
  3191. typeInstance->mInstSize = typeInstance->mSize;
  3192. typeInstance->mInstAlign = typeInstance->mAlign;
  3193. if (dataMemberHashCtx != NULL)
  3194. {
  3195. dataMemberHashCtx->Mixin(unionInnerType->mTypeId);
  3196. dataMemberHashCtx->Mixin(discriminatorType->mTypeId);
  3197. }
  3198. typeInstance->mMergedFieldDataCount = 1; // Track it as a single entry
  3199. }
  3200. }
  3201. void BfModule::DoPopulateType_CeCheckEnum(BfTypeInstance* typeInstance, bool underlyingTypeDeferred)
  3202. {
  3203. if (!typeInstance->IsEnum())
  3204. return;
  3205. if (!typeInstance->IsPayloadEnum())
  3206. return;
  3207. if ((typeInstance->mCeTypeInfo != NULL) && (typeInstance->mCeTypeInfo->mNext != NULL))
  3208. return;
  3209. BfType* unionInnerType = NULL;
  3210. if (typeInstance->mIsUnion)
  3211. {
  3212. SetAndRestoreValue<BfTypeState::ResolveKind> prevResolveKind(mContext->mCurTypeState->mResolveKind, BfTypeState::ResolveKind_UnionInnerType);
  3213. unionInnerType = typeInstance->GetUnionInnerType();
  3214. }
  3215. DoPopulateType_FinishEnum(typeInstance, underlyingTypeDeferred, NULL, unionInnerType);
  3216. }
  3217. void BfModule::DoPopulateType(BfType* resolvedTypeRef, BfPopulateType populateType)
  3218. {
  3219. if (populateType == BfPopulateType_Identity)
  3220. return;
  3221. if ((populateType <= BfPopulateType_Data) && (resolvedTypeRef->mDefineState >= BfTypeDefineState_Defined))
  3222. return;
  3223. auto typeInstance = resolvedTypeRef->ToTypeInstance();
  3224. BfTypeInstance* boxedUnderlyingTypeInstance = NULL;
  3225. if (typeInstance->IsBoxed())
  3226. {
  3227. auto underlyingType = typeInstance->GetUnderlyingType();
  3228. if (underlyingType->IsPrimitiveType())
  3229. boxedUnderlyingTypeInstance = GetPrimitiveStructType(((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode);
  3230. else
  3231. boxedUnderlyingTypeInstance = underlyingType->ToTypeInstance();
  3232. typeInstance->mTypeDef = boxedUnderlyingTypeInstance->mTypeDef;
  3233. }
  3234. auto typeDef = typeInstance->mTypeDef;
  3235. BF_ASSERT((typeInstance->mTypeDef->mNextRevision == NULL) || (mCompiler->IsAutocomplete()));
  3236. // This is a special case where our base type has been rebuilt but we haven't
  3237. if ((typeInstance->mBaseTypeMayBeIncomplete) && (!typeInstance->mTypeIncomplete))
  3238. {
  3239. BfLogSysM("BaseTypeMayBeIncomplete processing. Type:%p -> Base:%p\n", typeInstance, typeInstance->mBaseType);
  3240. PopulateType(typeInstance->mBaseType, populateType);
  3241. if (!typeInstance->mBaseType->IsIncomplete())
  3242. typeInstance->mBaseTypeMayBeIncomplete = false;
  3243. if (!typeInstance->mTypeIncomplete)
  3244. return;
  3245. }
  3246. typeInstance->mBaseTypeMayBeIncomplete = false;
  3247. BF_ASSERT(mIsModuleMutable);
  3248. // Don't do type instance method processing for an autocomplete pass - this will get handled later on during
  3249. // the PopulateType worklist pass in the full resolver. We do need to handle the methods for delegates, though,
  3250. // since those can affect method declarations of other methods
  3251. // TODO: Investigate this "Delegate" claim
  3252. bool canDoMethodProcessing = ((mCompiler->mResolvePassData == NULL) || (mCompiler->mResolvePassData->mAutoComplete == NULL) /*|| (typeInstance->IsDelegate())*/);
  3253. if (populateType == BfPopulateType_Full_Force)
  3254. canDoMethodProcessing = true;
  3255. if (typeInstance->mResolvingConstField)
  3256. return;
  3257. // Partial population break out point
  3258. if ((populateType >= BfPopulateType_Identity) && (populateType <= BfPopulateType_IdentityNoRemapAlias))
  3259. return;
  3260. if ((populateType <= BfPopulateType_AllowStaticMethods) && (typeInstance->mDefineState >= BfTypeDefineState_HasInterfaces_Direct))
  3261. return;
  3262. // During CE init we need to avoid interface checking loops, so we only allow show direct interface declarations
  3263. if ((populateType == BfPopulateType_Interfaces_All) && (typeInstance->mDefineState >= Beefy::BfTypeDefineState_CETypeInit))
  3264. {
  3265. if ((typeInstance->mDefineState == Beefy::BfTypeDefineState_CEPostTypeInit) && (typeInstance->mCeTypeInfo != NULL) &&
  3266. (!typeInstance->mCeTypeInfo->mPendingInterfaces.IsEmpty()))
  3267. {
  3268. // We have finished CETypeInit and we have pending interfaces we need to apply
  3269. }
  3270. else
  3271. return;
  3272. }
  3273. if (!mCompiler->EnsureCeUnpaused(resolvedTypeRef))
  3274. {
  3275. // We need to avoid comptime reentry when the ceDebugger is paused
  3276. BfLogSysM("DoPopulateType %p bailing due to IsCePaused\n", resolvedTypeRef);
  3277. return;
  3278. }
  3279. auto _CheckTypeDone = [&]()
  3280. {
  3281. if (typeInstance->mNeedsMethodProcessing)
  3282. {
  3283. BF_ASSERT(typeInstance->mDefineState >= BfTypeDefineState_Defined);
  3284. if ((canDoMethodProcessing) && (populateType >= BfPopulateType_DataAndMethods))
  3285. DoTypeInstanceMethodProcessing(typeInstance);
  3286. return true;
  3287. }
  3288. if (typeInstance->mDefineState == BfTypeDefineState_DefinedAndMethodsSlotted)
  3289. return true;
  3290. return false;
  3291. };
  3292. if (_CheckTypeDone())
  3293. return;
  3294. if (!resolvedTypeRef->IsValueType())
  3295. {
  3296. resolvedTypeRef->mSize = typeInstance->mAlign = mSystem->mPtrSize;
  3297. }
  3298. BF_ASSERT((typeInstance->mMethodInstanceGroups.size() == 0) || (typeInstance->mMethodInstanceGroups.size() == typeDef->mMethods.size()) || (typeInstance->mCeTypeInfo != NULL) || (typeInstance->IsBoxed()));
  3299. typeInstance->mMethodInstanceGroups.Resize(typeDef->mMethods.size());
  3300. for (int i = 0; i < (int)typeInstance->mMethodInstanceGroups.size(); i++)
  3301. {
  3302. typeInstance->mMethodInstanceGroups[i].mOwner = typeInstance;
  3303. typeInstance->mMethodInstanceGroups[i].mMethodIdx = i;
  3304. }
  3305. AutoDisallowYield disableYield(mSystem);
  3306. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  3307. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  3308. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, NULL);
  3309. // WHY were we clearing these values?
  3310. //SetAndRestoreValue<bool> prevHadError(mHadBuildError, false);
  3311. //SetAndRestoreValue<bool> prevHadWarning(mHadBuildWarning, false);
  3312. BfTypeState typeState(mCurTypeInstance, mContext->mCurTypeState);
  3313. typeState.mPopulateType = populateType;
  3314. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  3315. if (typeInstance->IsGenericTypeInstance())
  3316. {
  3317. auto genericTypeInst = (BfTypeInstance*)typeInstance;
  3318. if (!genericTypeInst->mGenericTypeInfo->mInitializedGenericParams)
  3319. InitGenericParams(resolvedTypeRef);
  3320. }
  3321. if (resolvedTypeRef->IsTypeAlias())
  3322. {
  3323. prevTypeState.Restore();
  3324. DoPopulateType_TypeAlias((BfTypeAliasType*)typeInstance);
  3325. typeInstance->mTypeIncomplete = false;
  3326. resolvedTypeRef->mRebuildFlags = BfTypeRebuildFlag_None;
  3327. resolvedTypeRef->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  3328. return;
  3329. }
  3330. if (_CheckTypeDone())
  3331. return;
  3332. // Don't do TypeToString until down here. Otherwise we can infinitely loop on BuildGenericParams
  3333. bool isStruct = resolvedTypeRef->IsStruct();
  3334. bool reportErrors = true;
  3335. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  3336. reportErrors = true;
  3337. // If we're not the defining context then we don't report errors for this type, but errors will still put the system
  3338. // into an errored state
  3339. SetAndRestoreValue<bool> prevReportErrors(mReportErrors, reportErrors);
  3340. if (typeInstance->mIsFinishingType)
  3341. {
  3342. if (typeInstance->mTypeFailed)
  3343. return;
  3344. }
  3345. if (!typeInstance->mTypeFailed)
  3346. {
  3347. if (populateType == BfPopulateType_Data_Soft)
  3348. {
  3349. if (CheckCircularDataError(false))
  3350. return;
  3351. }
  3352. CheckCircularDataError();
  3353. }
  3354. if (typeInstance->mDefineState < BfTypeDefineState_Declaring)
  3355. {
  3356. typeInstance->mDefineState = BfTypeDefineState_Declaring;
  3357. DoPopulateType_InitSearches(typeInstance);
  3358. }
  3359. //
  3360. {
  3361. BP_ZONE("DoPopulateType:CheckStack");
  3362. StackHelper stackHelper;
  3363. if (!stackHelper.CanStackExpand(128 * 1024))
  3364. {
  3365. if (!stackHelper.Execute([&]()
  3366. {
  3367. DoPopulateType(resolvedTypeRef, populateType);
  3368. }))
  3369. {
  3370. Fail("Stack exhausted in DoPopulateType", typeDef->GetRefNode());
  3371. }
  3372. return;
  3373. }
  3374. }
  3375. bool underlyingTypeDeferred = false;
  3376. BfType* underlyingType = NULL;
  3377. if (typeInstance->mBaseType != NULL)
  3378. {
  3379. if (typeInstance->IsTypedPrimitive())
  3380. underlyingType = typeInstance->GetUnderlyingType();
  3381. if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_UnderlyingTypeDeferred) != 0)
  3382. underlyingTypeDeferred = true;
  3383. }
  3384. if ((typeInstance->IsEnum()) && (underlyingType == NULL) && (!underlyingTypeDeferred))
  3385. {
  3386. bool hasPayloads = false;
  3387. for (auto fieldDef : typeDef->mFields)
  3388. {
  3389. if ((fieldDef->IsEnumCaseEntry()) && (fieldDef->mTypeRef != NULL))
  3390. {
  3391. hasPayloads = true;
  3392. break;
  3393. }
  3394. }
  3395. if (!hasPayloads)
  3396. {
  3397. bool hadType = false;
  3398. BfAstNode* deferredErrorNode = NULL;
  3399. const char* deferredError = NULL;
  3400. for (auto baseTypeRef : typeDef->mBaseTypes)
  3401. {
  3402. auto declTypeDef = typeDef;
  3403. if (typeDef->mIsCombinedPartial)
  3404. declTypeDef = typeDef->mPartials.front();
  3405. SetAndRestoreValue<BfTypeDef*> prevTypeDef(mContext->mCurTypeState->mCurTypeDef, declTypeDef);
  3406. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurBaseTypeRef, baseTypeRef);
  3407. SetAndRestoreValue<BfTypeDefineState> prevDefineState(typeInstance->mDefineState, BfTypeDefineState_ResolvingBaseType);
  3408. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  3409. SetAndRestoreValue<bool> prevSkipTypeProtectionChecks(typeInstance->mSkipTypeProtectionChecks, true);
  3410. auto baseType = ResolveTypeRef(baseTypeRef, BfPopulateType_Declaration);
  3411. if (baseType != NULL)
  3412. {
  3413. if (baseType->IsIntegral())
  3414. {
  3415. if (!hadType)
  3416. {
  3417. hadType = true;
  3418. underlyingType = baseType;
  3419. }
  3420. else
  3421. {
  3422. deferredError = "Underlying enum type already specified";
  3423. deferredErrorNode = baseTypeRef;
  3424. }
  3425. }
  3426. else if (!baseType->IsInterface())
  3427. {
  3428. deferredError = "Invalid underlying enum type";
  3429. deferredErrorNode = baseTypeRef;
  3430. }
  3431. }
  3432. else
  3433. {
  3434. AssertErrorState();
  3435. TypeFailed(typeInstance);
  3436. }
  3437. }
  3438. if (deferredError != NULL)
  3439. Fail(deferredError, deferredErrorNode, true);
  3440. if (underlyingType == NULL)
  3441. {
  3442. underlyingType = GetPrimitiveType(BfTypeCode_Int64);
  3443. underlyingTypeDeferred = true;
  3444. }
  3445. }
  3446. }
  3447. // else if (typeInstance->IsFunction())
  3448. // {
  3449. // underlyingType = GetPrimitiveType(BfTypeCode_NullPtr);
  3450. // }
  3451. else if (((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive())) &&
  3452. (!typeInstance->mTypeFailed))
  3453. {
  3454. for (auto baseTypeRef : typeDef->mBaseTypes)
  3455. {
  3456. auto declTypeDef = typeDef;
  3457. if (typeDef->mIsCombinedPartial)
  3458. declTypeDef = typeDef->mPartials.front();
  3459. SetAndRestoreValue<BfTypeDef*> prevTypeDef(mContext->mCurTypeState->mCurTypeDef, declTypeDef);
  3460. SetAndRestoreValue<BfTypeDefineState> prevDefineState(typeInstance->mDefineState, BfTypeDefineState_ResolvingBaseType);
  3461. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurBaseTypeRef, baseTypeRef);
  3462. // We ignore errors here to avoid double-errors for type lookups, but this is where data cycles are detected
  3463. // but that type of error supersedes the mIgnoreErrors setting
  3464. SetAndRestoreValue<bool> prevIgnoreError(mIgnoreErrors, true);
  3465. // Temporarily allow us to derive from private classes, to avoid infinite loop from TypeIsSubTypeOf
  3466. SetAndRestoreValue<bool> prevSkipTypeProtectionChecks(typeInstance->mSkipTypeProtectionChecks, true);
  3467. auto baseType = ResolveTypeRef(baseTypeRef, BfPopulateType_Declaration);
  3468. if (baseType != NULL)
  3469. {
  3470. if (baseType->IsVar())
  3471. {
  3472. // Ignore
  3473. }
  3474. else if (baseType->IsPrimitiveType())
  3475. {
  3476. underlyingType = baseType;
  3477. }
  3478. else if (baseType->IsTypedPrimitive())
  3479. {
  3480. //PopulateType(baseType, true);
  3481. underlyingType = baseType->GetUnderlyingType();
  3482. BF_ASSERT(underlyingType != NULL);
  3483. }
  3484. }
  3485. else
  3486. {
  3487. AssertErrorState();
  3488. TypeFailed(typeInstance);
  3489. }
  3490. if (_CheckTypeDone())
  3491. {
  3492. prevDefineState.CancelRestore();
  3493. return;
  3494. }
  3495. }
  3496. // Incase we had re-entry, work this through ourselves again here
  3497. typeInstance->mIsTypedPrimitive = false;
  3498. }
  3499. if (underlyingTypeDeferred)
  3500. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_UnderlyingTypeDeferred);
  3501. typeInstance->mIsTypedPrimitive = underlyingType != NULL;
  3502. int wantFieldCount = (int)typeDef->mFields.size() + (((underlyingType != NULL) || (typeInstance->IsPayloadEnum())) ? 1 : 0);
  3503. if ((int)typeInstance->mFieldInstances.size() < wantFieldCount)
  3504. {
  3505. // Closures don't include the enclosed fields on their first pass through PopulateType, and they have no typeDef of their own
  3506. // so we need to take care not to truncate their fieldInstance vector here (thus the 'wantFieldCount' check above)
  3507. typeInstance->mFieldInstances.Resize(wantFieldCount);
  3508. }
  3509. if (underlyingType != NULL)
  3510. {
  3511. auto fieldInstance = &typeInstance->mFieldInstances.back();
  3512. fieldInstance->mDataOffset = 0;
  3513. fieldInstance->mDataSize = underlyingType->mSize;
  3514. fieldInstance->mOwner = typeInstance;
  3515. fieldInstance->mResolvedType = underlyingType;
  3516. typeInstance->mSize = underlyingType->mSize;
  3517. typeInstance->mAlign = underlyingType->mAlign;
  3518. typeInstance->mInstSize = underlyingType->mSize;
  3519. typeInstance->mInstAlign = underlyingType->mAlign;
  3520. typeInstance->mHasPackingHoles = underlyingType->HasPackingHoles();
  3521. }
  3522. // Partial population break out point
  3523. if (typeInstance->mDefineState < BfTypeDefineState_Declared)
  3524. typeInstance->mDefineState = BfTypeDefineState_Declared;
  3525. if (populateType == BfPopulateType_Declaration)
  3526. {
  3527. return;
  3528. }
  3529. if ((!mCompiler->mIsResolveOnly) && (!typeInstance->HasBeenInstantiated()))
  3530. {
  3531. for (auto& dep : typeInstance->mDependencyMap)
  3532. {
  3533. auto& depEntry = dep.mValue;
  3534. if ((depEntry.mFlags & BfDependencyMap::DependencyFlag_Allocates) != 0)
  3535. {
  3536. auto depType = dep.mKey;
  3537. if (depType->mRevision == depEntry.mRevision)
  3538. {
  3539. BfLogSysM("Setting mHasBeenInstantiated for %p instantiated from %p\n", typeInstance, depType);
  3540. typeInstance->mHasBeenInstantiated = true;
  3541. }
  3542. }
  3543. }
  3544. }
  3545. //BfLogSysM("Setting revision. Type: %p Revision: %d\n", typeInstance, mRevision);
  3546. //typeInstance->mRevision = mRevision;
  3547. // Temporarily allow us to derive from private classes, to avoid infinite loop from TypeIsSubTypeOf
  3548. SetAndRestoreValue<bool> prevSkipTypeProtectionChecks(typeInstance->mSkipTypeProtectionChecks, true);
  3549. if ((typeDef->mOuterType != NULL) && (typeDef->mOuterType->IsGlobalsContainer()))
  3550. {
  3551. if ((typeDef->mTypeDeclaration != NULL) && (typeDef->mTypeDeclaration->mTypeNode != NULL))
  3552. Fail("Global blocks cannot contain type declarations", typeDef->mTypeDeclaration->mTypeNode);
  3553. }
  3554. /// Create DI data
  3555. SizedArray<BfIRType, 8> llvmFieldTypes;
  3556. int curFieldDataIdx = 0;
  3557. typeInstance->mBaseType = NULL;
  3558. BfTypeInstance* defaultBaseTypeInst = NULL;
  3559. // Find base type
  3560. BfType* baseType = NULL;
  3561. struct BfInterfaceDecl
  3562. {
  3563. BfTypeInstance* mIFaceTypeInst;
  3564. BfTypeReference* mTypeRef;
  3565. BfTypeDef* mDeclaringType;
  3566. };
  3567. SizedArray<BfInterfaceDecl, 8> interfaces;
  3568. HashSet<BfTypeInstance*> ifaceSet;
  3569. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags | BfTypeRebuildFlag_ResolvingBase);
  3570. if (resolvedTypeRef == mContext->mBfObjectType)
  3571. {
  3572. baseType = NULL;
  3573. }
  3574. else if (typeInstance->IsEnum())
  3575. {
  3576. if (mCompiler->mEnumTypeDef == NULL)
  3577. {
  3578. Fail("Enum type required");
  3579. TypeFailed(typeInstance);
  3580. }
  3581. else
  3582. baseType = ResolveTypeDef(mCompiler->mEnumTypeDef)->ToTypeInstance();
  3583. }
  3584. else if (resolvedTypeRef->IsObject())
  3585. baseType = mContext->mBfObjectType;
  3586. else if (resolvedTypeRef->IsPointer())
  3587. {
  3588. baseType = ResolveTypeDef(mCompiler->mPointerTTypeDef, BfPopulateType_Data);
  3589. }
  3590. else if ((resolvedTypeRef->IsValueType()) && (typeDef != mCompiler->mValueTypeTypeDef))
  3591. {
  3592. baseType = ResolveTypeDef(mCompiler->mValueTypeTypeDef, BfPopulateType_Data)->ToTypeInstance();
  3593. }
  3594. if (baseType != NULL)
  3595. defaultBaseTypeInst = baseType->ToTypeInstance();
  3596. struct _DeferredValidate
  3597. {
  3598. BfTypeReference* mTypeRef;
  3599. BfTypeInstance* mGenericType;
  3600. bool mIgnoreErrors;
  3601. };
  3602. Array<_DeferredValidate> deferredTypeValidateList;
  3603. bool wantPopulateInterfaces = false;
  3604. BfTypeReference* baseTypeRef = NULL;
  3605. if ((typeDef->mIsDelegate) && (!typeInstance->IsClosure()))
  3606. {
  3607. if (mCompiler->mDelegateTypeDef == NULL)
  3608. {
  3609. Fail("Delegate type required");
  3610. TypeFailed(typeInstance);
  3611. }
  3612. else
  3613. baseType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  3614. }
  3615. else if (typeDef->mIsFunction)
  3616. {
  3617. if (mCompiler->mFunctionTypeDef == NULL)
  3618. {
  3619. Fail("Function type required");
  3620. TypeFailed(typeInstance);
  3621. }
  3622. else
  3623. baseType = ResolveTypeDef(mCompiler->mFunctionTypeDef)->ToTypeInstance();
  3624. }
  3625. else
  3626. {
  3627. for (auto checkTypeRef : typeDef->mBaseTypes)
  3628. {
  3629. if ((typeInstance->mDefineState == BfTypeDefineState_ResolvingBaseType) && (typeInstance->mTypeFailed))
  3630. break;
  3631. auto declTypeDef = typeDef;
  3632. if (typeDef->mIsCombinedPartial)
  3633. declTypeDef = typeDef->mPartials.front();
  3634. SetAndRestoreValue<BfTypeDef*> prevTypeDef(mContext->mCurTypeState->mCurTypeDef, declTypeDef);
  3635. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurBaseTypeRef, checkTypeRef);
  3636. SetAndRestoreValue<BfTypeDefineState> prevDefineState(typeInstance->mDefineState, BfTypeDefineState_ResolvingBaseType);
  3637. bool populateBase = !typeInstance->mTypeFailed;
  3638. BfType* checkType = checkType = ResolveTypeRef(checkTypeRef, BfPopulateType_Declaration);
  3639. if ((checkType != NULL) && (!checkType->IsInterface()) && (populateBase))
  3640. {
  3641. SetAndRestoreValue<BfTypeInstance*> prevBaseType(mContext->mCurTypeState->mCurBaseType, checkType->ToTypeInstance());
  3642. PopulateType(checkType, (populateType <= BfPopulateType_BaseType) ? BfPopulateType_BaseType : BfPopulateType_Data);
  3643. }
  3644. if (typeInstance->mDefineState >= BfTypeDefineState_Defined)
  3645. {
  3646. prevDefineState.CancelRestore();
  3647. return;
  3648. }
  3649. if (checkType != NULL)
  3650. {
  3651. if (auto genericTypeInst = checkType->ToGenericTypeInstance())
  3652. {
  3653. // Specialized type variations don't need to validate their constraints
  3654. if (!typeInstance->IsUnspecializedTypeVariation())
  3655. deferredTypeValidateList.Add({ checkTypeRef, genericTypeInst, false });
  3656. }
  3657. auto checkTypeInst = checkType->ToTypeInstance();
  3658. bool canDeriveFrom = checkTypeInst != NULL;
  3659. if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()) || (typeInstance->IsBoxed()))
  3660. canDeriveFrom |= checkType->IsPrimitiveType();
  3661. if ((typeInstance->IsEnum()) && (!checkType->IsInterface()))
  3662. {
  3663. if (typeInstance->IsTypedPrimitive())
  3664. continue;
  3665. if (checkType->IsPrimitiveType())
  3666. Fail(StrFormat("Enum '%s' cannot be specified as '%s' because it has a payload",
  3667. TypeToString(typeInstance).c_str(), TypeToString(checkType).c_str()),
  3668. checkTypeRef, true);
  3669. else
  3670. Fail("Enums cannot derive from other types", checkTypeRef);
  3671. continue;
  3672. }
  3673. if ((checkTypeInst != NULL) && (checkTypeInst->mTypeFailed))
  3674. {
  3675. // To keep circular references from breaking type invariants (ie: base type loops)
  3676. continue;
  3677. }
  3678. if (!canDeriveFrom)
  3679. {
  3680. Fail("Cannot derive from this type", checkTypeRef);
  3681. continue;
  3682. }
  3683. if (checkType->IsVar())
  3684. {
  3685. // This can't explicitly be specified, but can occur from comptime
  3686. continue;
  3687. }
  3688. if (checkType->IsInterface())
  3689. {
  3690. auto ifaceInst = checkType->ToTypeInstance();
  3691. if (ifaceSet.Add(ifaceInst))
  3692. {
  3693. // Not base type
  3694. BfInterfaceDecl ifaceDecl;
  3695. ifaceDecl.mIFaceTypeInst = ifaceInst;
  3696. ifaceDecl.mTypeRef = checkTypeRef;
  3697. ifaceDecl.mDeclaringType = typeDef->GetDefinition();
  3698. interfaces.push_back(ifaceDecl);
  3699. }
  3700. else
  3701. {
  3702. Fail(StrFormat("Interface '%s' is already specified", TypeToString(checkType).c_str()), checkTypeRef);
  3703. }
  3704. }
  3705. else if (resolvedTypeRef == mContext->mBfObjectType)
  3706. {
  3707. Fail(StrFormat("Type '%s' cannot define a base type", TypeToString(baseType).c_str()), checkTypeRef);
  3708. }
  3709. else
  3710. {
  3711. if (baseTypeRef != NULL)
  3712. {
  3713. Fail(StrFormat("Base type '%s' already declared", TypeToString(baseType).c_str()), checkTypeRef);
  3714. }
  3715. else
  3716. {
  3717. baseTypeRef = checkTypeRef;
  3718. if (checkTypeInst != NULL)
  3719. {
  3720. auto checkOuter = checkTypeInst;
  3721. while (checkOuter != NULL)
  3722. {
  3723. if (checkOuter == typeInstance)
  3724. {
  3725. Fail(StrFormat("Type '%s' cannot be declare inner type '%s' as a base type",
  3726. TypeToString(typeInstance).c_str(),
  3727. TypeToString(checkTypeInst).c_str()), checkTypeRef, true);
  3728. checkTypeInst = NULL;
  3729. break;
  3730. }
  3731. checkOuter = GetOuterType(checkOuter);
  3732. }
  3733. }
  3734. if (checkTypeInst != NULL)
  3735. {
  3736. baseType = checkTypeInst;
  3737. }
  3738. }
  3739. }
  3740. if (_CheckTypeDone())
  3741. {
  3742. prevDefineState.CancelRestore();
  3743. return;
  3744. }
  3745. }
  3746. else
  3747. {
  3748. AssertErrorState();
  3749. // Why did we go around setting mTypeFailed on all these things?
  3750. //typeInstance->mTypeFailed = true;
  3751. }
  3752. }
  3753. wantPopulateInterfaces = true;
  3754. }
  3755. // Handle CE interfaces
  3756. {
  3757. auto checkTypeInst = typeInstance;
  3758. if (boxedUnderlyingTypeInstance != NULL)
  3759. checkTypeInst = boxedUnderlyingTypeInstance;
  3760. if ((checkTypeInst->mCeTypeInfo != NULL) && (!checkTypeInst->mCeTypeInfo->mPendingInterfaces.IsEmpty()))
  3761. {
  3762. for (auto ifaceTypeId : checkTypeInst->mCeTypeInfo->mPendingInterfaces)
  3763. {
  3764. auto ifaceType = mContext->mTypes[ifaceTypeId];
  3765. if ((ifaceType == NULL) || (!ifaceType->IsInterface()))
  3766. continue;
  3767. auto ifaceInst = ifaceType->ToTypeInstance();
  3768. if (ifaceSet.Add(ifaceInst))
  3769. {
  3770. // Not base type
  3771. BfInterfaceDecl ifaceDecl;
  3772. ifaceDecl.mIFaceTypeInst = ifaceInst;
  3773. ifaceDecl.mTypeRef = NULL;
  3774. ifaceDecl.mDeclaringType = typeDef->GetDefinition();
  3775. interfaces.Add(ifaceDecl);
  3776. }
  3777. }
  3778. }
  3779. }
  3780. if (_CheckTypeDone())
  3781. return;
  3782. if (resolvedTypeRef->IsBoxed())
  3783. {
  3784. BfBoxedType* boxedType = (BfBoxedType*)resolvedTypeRef;
  3785. if ((baseType != NULL) && (baseType->IsStruct()))
  3786. {
  3787. BfType* modifiedBaseType = baseType;
  3788. if (boxedType->IsBoxedStructPtr())
  3789. modifiedBaseType = CreatePointerType(modifiedBaseType);
  3790. boxedType->mBoxedBaseType = CreateBoxedType(modifiedBaseType);
  3791. PopulateType(boxedType->mBoxedBaseType);
  3792. // Use derivedFrom for both the boxed base type and the unboxed type
  3793. AddDependency(boxedType->mBoxedBaseType, typeInstance, BfDependencyMap::DependencyFlag_DerivedFrom);
  3794. }
  3795. AddDependency(boxedType->mElementType, typeInstance, BfDependencyMap::DependencyFlag_ValueTypeMemberData);
  3796. baseType = mContext->mBfObjectType;
  3797. }
  3798. BfTypeInstance* baseTypeInst = NULL;
  3799. if (baseType != NULL)
  3800. {
  3801. baseTypeInst = baseType->ToTypeInstance();
  3802. }
  3803. if (typeInstance->mBaseType != NULL)
  3804. {
  3805. BF_ASSERT(typeInstance->mBaseType == baseTypeInst);
  3806. }
  3807. if (auto genericTypeInst = typeInstance->ToGenericTypeInstance())
  3808. {
  3809. if ((genericTypeInst->IsSpecializedType()) && (!genericTypeInst->mGenericTypeInfo->mValidatedGenericConstraints) && (!typeInstance->IsBoxed()))
  3810. {
  3811. deferredTypeValidateList.Add({ NULL, genericTypeInst, true });
  3812. }
  3813. }
  3814. if (!typeInstance->IsBoxed())
  3815. {
  3816. BfType* outerType = GetOuterType(typeInstance);
  3817. if (outerType != NULL)
  3818. {
  3819. PopulateType(outerType, BfPopulateType_Identity);
  3820. AddDependency(outerType, typeInstance, BfDependencyMap::DependencyFlag_OuterType);
  3821. }
  3822. }
  3823. if ((typeInstance->IsInterface()) && (baseTypeInst != NULL))
  3824. {
  3825. Fail("Interfaces cannot declare base types", baseTypeRef, true);
  3826. baseTypeInst = NULL;
  3827. }
  3828. if ((baseTypeInst != NULL) && (typeInstance->mBaseType == NULL))
  3829. {
  3830. if (typeInstance->mTypeFailed)
  3831. {
  3832. if (baseTypeInst->IsDataIncomplete())
  3833. {
  3834. if (baseTypeInst->IsStruct())
  3835. baseTypeInst = ResolveTypeDef(mCompiler->mValueTypeTypeDef)->ToTypeInstance();
  3836. else if (baseTypeInst->IsObject())
  3837. baseTypeInst = ResolveTypeDef(mCompiler->mBfObjectTypeDef)->ToTypeInstance();
  3838. }
  3839. }
  3840. PopulateType(baseTypeInst, BfPopulateType_Data);
  3841. typeInstance->mBaseTypeMayBeIncomplete = false;
  3842. typeInstance->mMergedFieldDataCount = baseTypeInst->mMergedFieldDataCount;
  3843. if ((resolvedTypeRef->IsObject()) && (!baseTypeInst->IsObject()))
  3844. {
  3845. Fail("Class can only derive from another class", baseTypeRef, true);
  3846. baseTypeInst = defaultBaseTypeInst;
  3847. typeInstance->mBaseType = baseTypeInst;
  3848. }
  3849. else if ((resolvedTypeRef->IsStruct()) && (!baseTypeInst->IsValueType()))
  3850. {
  3851. Fail("Struct can only derive from another struct", baseTypeRef, true);
  3852. baseTypeInst = defaultBaseTypeInst;
  3853. typeInstance->mBaseType = baseTypeInst;
  3854. }
  3855. if (!typeInstance->IsIncomplete())
  3856. {
  3857. // Re-entry may cause this type to be completed already
  3858. return;
  3859. }
  3860. //BfLogSysM("Adding DerivedFrom dependency. Used:%p Using:%p\n", baseType, typeInstance);
  3861. auto checkBaseType = baseTypeInst;
  3862. while (checkBaseType != NULL)
  3863. {
  3864. // Add 'DerivedFrom' dependency all the way up the inheritance chain
  3865. AddDependency(checkBaseType, typeInstance, BfDependencyMap::DependencyFlag_DerivedFrom);
  3866. checkBaseType = checkBaseType->mBaseType;
  3867. }
  3868. typeInstance->mBaseType = baseTypeInst;
  3869. typeInstance->mWantsGCMarking = baseTypeInst->mWantsGCMarking;
  3870. typeInstance->mInheritDepth = baseTypeInst->mInheritDepth + 1;
  3871. typeInstance->mHasParameterizedBase = baseTypeInst->mHasParameterizedBase;
  3872. if ((baseTypeInst->IsArray()) || (baseTypeInst->IsSizedArray()) || (baseTypeInst->IsGenericTypeInstance()))
  3873. typeInstance->mHasParameterizedBase = true;
  3874. if (underlyingType == NULL)
  3875. {
  3876. typeInstance->mInstSize = baseTypeInst->mInstSize;
  3877. typeInstance->mInstAlign = baseTypeInst->mInstAlign;
  3878. typeInstance->mAlign = baseTypeInst->mAlign;
  3879. typeInstance->mSize = baseTypeInst->mSize;
  3880. typeInstance->mHasPackingHoles = baseTypeInst->mHasPackingHoles;
  3881. if (baseTypeInst->mIsTypedPrimitive)
  3882. typeInstance->mIsTypedPrimitive = true;
  3883. }
  3884. }
  3885. typeInstance->mRebuildFlags = (BfTypeRebuildFlags)(typeInstance->mRebuildFlags & ~BfTypeRebuildFlag_ResolvingBase);
  3886. if (populateType <= BfPopulateType_BaseType)
  3887. return;
  3888. if (typeInstance->IsGenericTypeInstance())
  3889. {
  3890. auto genericTypeInst = (BfTypeInstance*)typeInstance;
  3891. // if (!genericTypeInst->mGenericTypeInfo->mInitializedGenericParams)
  3892. // InitGenericParams(resolvedTypeRef);
  3893. if (!genericTypeInst->mGenericTypeInfo->mFinishedGenericParams)
  3894. FinishGenericParams(resolvedTypeRef);
  3895. }
  3896. if (wantPopulateInterfaces)
  3897. {
  3898. for (auto partialTypeDef : typeDef->mPartials)
  3899. {
  3900. if (!typeInstance->IsTypeMemberIncluded(partialTypeDef))
  3901. continue;
  3902. if (partialTypeDef->mTypeDeclaration == typeInstance->mTypeDef->mTypeDeclaration)
  3903. continue;
  3904. for (auto checkTypeRef : partialTypeDef->mBaseTypes)
  3905. {
  3906. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurBaseTypeRef, checkTypeRef);
  3907. SetAndRestoreValue<BfTypeDef*> prevTypeDef(mContext->mCurTypeState->mCurTypeDef, partialTypeDef);
  3908. bool populateBase = !typeInstance->mTypeFailed;
  3909. auto checkType = ResolveTypeRef(checkTypeRef, BfPopulateType_Declaration);
  3910. if (checkType != NULL)
  3911. {
  3912. if (checkType->IsInterface())
  3913. {
  3914. BfInterfaceDecl ifaceDecl;
  3915. ifaceDecl.mIFaceTypeInst = checkType->ToTypeInstance();
  3916. ifaceDecl.mTypeRef = checkTypeRef;
  3917. ifaceDecl.mDeclaringType = partialTypeDef;
  3918. interfaces.push_back(ifaceDecl);
  3919. }
  3920. else
  3921. {
  3922. Fail(StrFormat("Extensions can only specify new interfaces, type '%s' is not a valid ", TypeToString(checkType).c_str()), checkTypeRef);
  3923. }
  3924. }
  3925. }
  3926. }
  3927. }
  3928. if ((typeInstance->mBaseType != NULL) && (!typeInstance->IsTypedPrimitive()))
  3929. {
  3930. curFieldDataIdx++;
  3931. }
  3932. if (!interfaces.empty())
  3933. {
  3934. for (int iFaceIdx = 0; iFaceIdx < (int)interfaces.size(); iFaceIdx++)
  3935. {
  3936. auto checkInterface = interfaces[iFaceIdx].mIFaceTypeInst;
  3937. SetAndRestoreValue<BfTypeDef*> prevTypeDef(mContext->mCurTypeState->mCurTypeDef, interfaces[iFaceIdx].mDeclaringType);
  3938. SetAndRestoreValue<BfTypeReference*> prevTypeRef(mContext->mCurTypeState->mCurBaseTypeRef, interfaces[iFaceIdx].mTypeRef);
  3939. PopulateType(checkInterface, BfPopulateType_Data);
  3940. BfTypeInterfaceEntry* found = NULL;
  3941. bool foundExact = false;
  3942. for (auto& typeInterfaceInst : typeInstance->mInterfaces)
  3943. {
  3944. if (typeInterfaceInst.mInterfaceType == checkInterface)
  3945. {
  3946. if (typeInterfaceInst.mDeclaringType == interfaces[iFaceIdx].mDeclaringType)
  3947. {
  3948. foundExact = true;
  3949. break;
  3950. }
  3951. found = &typeInterfaceInst;
  3952. }
  3953. }
  3954. if (foundExact)
  3955. continue;
  3956. BfTypeInterfaceEntry typeInterfaceInst;
  3957. typeInterfaceInst.mDeclaringType = interfaces[iFaceIdx].mDeclaringType;
  3958. typeInterfaceInst.mInterfaceType = checkInterface;
  3959. typeInterfaceInst.mStartInterfaceTableIdx = -1;
  3960. typeInterfaceInst.mStartVirtualIdx = -1;
  3961. typeInterfaceInst.mIsRedeclared = false;
  3962. typeInstance->mInterfaces.push_back(typeInterfaceInst);
  3963. AddDependency(checkInterface, typeInstance, BfDependencyMap::DependencyFlag_ImplementsInterface);
  3964. // Interfaces can list other interfaces in their declaration, so pull those in too
  3965. for (auto depIFace : checkInterface->mInterfaces)
  3966. {
  3967. auto depIFaceEntry = interfaces[iFaceIdx];
  3968. depIFaceEntry.mIFaceTypeInst = depIFace.mInterfaceType;
  3969. interfaces.push_back(depIFaceEntry);
  3970. }
  3971. }
  3972. if (typeInstance->mTypeFailed)
  3973. {
  3974. // Circular references in interfaces - just clear them all out
  3975. typeInstance->mInterfaces.Clear();
  3976. interfaces.Clear();
  3977. }
  3978. if (_CheckTypeDone())
  3979. return;
  3980. }
  3981. if (mCompiler->mOptions.mAllowHotSwapping)
  3982. {
  3983. if (typeInstance->mDefineState < BfTypeDefineState_HasInterfaces_Direct)
  3984. {
  3985. if (typeInstance->mHotTypeData == NULL)
  3986. {
  3987. typeInstance->mHotTypeData = new BfHotTypeData();
  3988. BfLogSysM("Created HotTypeData %p created for type %p in DoPopulateType\n", typeInstance->mHotTypeData, typeInstance);
  3989. }
  3990. // Clear any unused versions (if we have errors, etc)
  3991. if (mCompiler->mHotState != NULL)
  3992. typeInstance->mHotTypeData->ClearVersionsAfter(mCompiler->mHotState->mCommittedHotCompileIdx);
  3993. else
  3994. BF_ASSERT(typeInstance->mHotTypeData->mTypeVersions.IsEmpty()); // We should have created a new HotTypeData when rebuilding the type
  3995. BfHotTypeVersion* hotTypeVersion = new BfHotTypeVersion();
  3996. hotTypeVersion->mTypeId = typeInstance->mTypeId;
  3997. hotTypeVersion->mDeclHotCompileIdx = mCompiler->mOptions.mHotCompileIdx;
  3998. if (mCompiler->IsHotCompile())
  3999. hotTypeVersion->mCommittedHotCompileIdx = -1;
  4000. else
  4001. hotTypeVersion->mCommittedHotCompileIdx = 0;
  4002. hotTypeVersion->mRefCount++;
  4003. typeInstance->mHotTypeData->mTypeVersions.Add(hotTypeVersion);
  4004. BfLogSysM("BfHotTypeVersion %p created for type %p\n", hotTypeVersion, typeInstance);
  4005. }
  4006. auto hotTypeVersion = typeInstance->mHotTypeData->mTypeVersions.back();
  4007. if (typeInstance->mBaseType != NULL)
  4008. {
  4009. if (typeInstance->mBaseType->mHotTypeData != NULL)
  4010. hotTypeVersion->mBaseType = typeInstance->mBaseType->mHotTypeData->GetLatestVersion();
  4011. else if (populateType >= BfPopulateType_Interfaces_All)
  4012. {
  4013. AssertErrorState();
  4014. }
  4015. }
  4016. }
  4017. BF_ASSERT(!typeInstance->mNeedsMethodProcessing);
  4018. if (typeInstance->mDefineState < BfTypeDefineState_HasInterfaces_Direct)
  4019. typeInstance->mDefineState = BfTypeDefineState_HasInterfaces_Direct;
  4020. for (auto& validateEntry : deferredTypeValidateList)
  4021. {
  4022. SetAndRestoreValue<BfTypeReference*> prevAttributeTypeRef(typeState.mCurAttributeTypeRef, validateEntry.mTypeRef);
  4023. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, mIgnoreErrors | validateEntry.mIgnoreErrors);
  4024. ValidateGenericConstraints(validateEntry.mTypeRef, validateEntry.mGenericType, false);
  4025. }
  4026. bool isRootSystemType = typeInstance->IsInstanceOf(mCompiler->mValueTypeTypeDef) ||
  4027. typeInstance->IsInstanceOf(mCompiler->mAttributeTypeDef) ||
  4028. typeInstance->IsInstanceOf(mCompiler->mEnumTypeDef);
  4029. if (!typeInstance->IsBoxed())
  4030. {
  4031. if ((typeInstance->mCustomAttributes == NULL) && (typeDef->mTypeDeclaration != NULL) && (typeDef->HasCustomAttributes()))
  4032. {
  4033. BfAttributeTargets attrTarget;
  4034. if ((typeDef->mIsDelegate) || (typeDef->mIsFunction))
  4035. attrTarget = BfAttributeTargets_Delegate;
  4036. else if (typeInstance->IsEnum())
  4037. attrTarget = BfAttributeTargets_Enum;
  4038. else if (typeInstance->IsInterface())
  4039. attrTarget = BfAttributeTargets_Interface;
  4040. else if ((typeInstance->IsStruct()) || (typeInstance->IsTypedPrimitive()))
  4041. attrTarget = BfAttributeTargets_Struct;
  4042. else
  4043. attrTarget = BfAttributeTargets_Class;
  4044. if (!typeInstance->mTypeFailed)
  4045. {
  4046. BfTypeState typeState;
  4047. typeState.mPrevState = mContext->mCurTypeState;
  4048. typeState.mResolveKind = BfTypeState::ResolveKind_Attributes;
  4049. typeState.mType = typeInstance;
  4050. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  4051. // This allows us to avoid reentrancy when checking for inner types
  4052. SetAndRestoreValue<bool> prevSkipTypeProtectionChecks(typeInstance->mSkipTypeProtectionChecks, true);
  4053. if (typeDef->mIsCombinedPartial)
  4054. {
  4055. auto customAttributes = new BfCustomAttributes();
  4056. for (auto partialTypeDef : typeDef->mPartials)
  4057. {
  4058. if (partialTypeDef->mTypeDeclaration->mAttributes == NULL)
  4059. continue;
  4060. if (!typeInstance->IsTypeMemberIncluded(partialTypeDef))
  4061. continue;
  4062. typeState.mCurTypeDef = partialTypeDef;
  4063. GetCustomAttributes(customAttributes, partialTypeDef->mTypeDeclaration->mAttributes, attrTarget);
  4064. }
  4065. if (typeInstance->mCustomAttributes == NULL)
  4066. typeInstance->mCustomAttributes = customAttributes;
  4067. else
  4068. delete customAttributes;
  4069. }
  4070. else
  4071. {
  4072. auto customAttributes = new BfCustomAttributes();
  4073. GetCustomAttributes(customAttributes, typeDef->mTypeDeclaration->mAttributes, attrTarget);
  4074. if (typeInstance->mCustomAttributes == NULL)
  4075. typeInstance->mCustomAttributes = customAttributes;
  4076. else
  4077. delete customAttributes;
  4078. }
  4079. }
  4080. }
  4081. }
  4082. if (typeInstance->mTypeOptionsIdx == -2)
  4083. {
  4084. SetTypeOptions(typeInstance);
  4085. }
  4086. if (populateType <= BfPopulateType_AllowStaticMethods)
  4087. return;
  4088. prevSkipTypeProtectionChecks.Restore();
  4089. typeInstance->mInstSize = std::max(0, typeInstance->mInstSize);
  4090. typeInstance->mInstAlign = std::max(0, typeInstance->mInstAlign);
  4091. ProcessCustomAttributeData();
  4092. int packing = 0;
  4093. bool isUnion = false;
  4094. bool isCRepr = false;
  4095. bool isOrdered = false;
  4096. int alignOverride = 0;
  4097. BfType* underlyingArrayType = NULL;
  4098. int underlyingArraySize = -1;
  4099. ProcessTypeInstCustomAttributes(packing, isUnion, isCRepr, isOrdered, alignOverride, underlyingArrayType, underlyingArraySize);
  4100. if (underlyingArraySize > 0)
  4101. {
  4102. typeInstance->mHasUnderlyingArray = true;
  4103. curFieldDataIdx = 0;
  4104. }
  4105. if (packing > 0) // Packed infers ordered
  4106. isOrdered = true;
  4107. typeInstance->mIsUnion = isUnion;
  4108. if ((typeInstance->IsEnum()) && (typeInstance->IsStruct()))
  4109. typeInstance->mIsUnion = true;
  4110. typeInstance->mPacking = (uint8)packing;
  4111. typeInstance->mIsCRepr = isCRepr;
  4112. if (typeInstance->mTypeOptionsIdx >= 0)
  4113. {
  4114. auto typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  4115. if (typeOptions != NULL)
  4116. {
  4117. typeInstance->mHasBeenInstantiated = typeOptions->Apply(typeInstance->HasBeenInstantiated(), BfOptionFlags_ReflectAssumeInstantiated);
  4118. bool alwaysInclude = typeInstance->mAlwaysIncludeFlags != 0;
  4119. if ((typeOptions->Apply(alwaysInclude, BfOptionFlags_ReflectAlwaysIncludeType)) ||
  4120. (typeOptions->Apply(alwaysInclude, BfOptionFlags_ReflectAlwaysIncludeAll)))
  4121. {
  4122. typeInstance->mAlwaysIncludeFlags = (BfAlwaysIncludeFlags)(typeInstance->mAlwaysIncludeFlags | BfAlwaysIncludeFlag_Type);
  4123. }
  4124. else
  4125. {
  4126. typeInstance->mAlwaysIncludeFlags = BfAlwaysIncludeFlag_None;
  4127. }
  4128. }
  4129. }
  4130. BfType* unionInnerType = NULL;
  4131. bool hadDeferredVars = false;
  4132. int dataPos;
  4133. if (resolvedTypeRef->IsBoxed())
  4134. {
  4135. BfBoxedType* boxedType = (BfBoxedType*)resolvedTypeRef;
  4136. BfType* innerType = boxedType->mElementType;
  4137. if (boxedType->IsBoxedStructPtr())
  4138. innerType = CreatePointerType(innerType);
  4139. if (innerType->IsIncomplete())
  4140. PopulateType(innerType, BfPopulateType_Data);
  4141. auto innerTypeInst = innerType->ToTypeInstance();
  4142. if (innerTypeInst != NULL)
  4143. {
  4144. if (typeInstance->mTypeDef != innerTypeInst->mTypeDef)
  4145. {
  4146. // Rebuild with proper typedef (generally from inner type comptime emission)
  4147. BfLogSysM("Boxed type %p overriding typeDef to %p from inner type %p\n", typeInstance, innerTypeInst->mTypeDef, innerType);
  4148. typeInstance->mTypeDef = innerTypeInst->mTypeDef;
  4149. DoPopulateType(resolvedTypeRef, populateType);
  4150. return;
  4151. }
  4152. while (typeInstance->mInterfaces.mSize < innerTypeInst->mInterfaces.mSize)
  4153. {
  4154. auto ifaceEntry = innerTypeInst->mInterfaces[typeInstance->mInterfaces.mSize];
  4155. typeInstance->mInterfaces.Add(ifaceEntry);
  4156. AddDependency(ifaceEntry.mInterfaceType, typeInstance, BfDependencyMap::DependencyFlag_ImplementsInterface);
  4157. }
  4158. }
  4159. auto baseType = typeInstance->mBaseType;
  4160. dataPos = baseType->mInstSize;
  4161. int alignSize = BF_MAX(innerType->mAlign, baseType->mInstAlign);
  4162. if (alignSize > 1)
  4163. dataPos = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  4164. int dataSize = innerType->mSize;
  4165. typeInstance->mFieldInstances.push_back(BfFieldInstance());
  4166. BfFieldInstance* fieldInstance = &typeInstance->mFieldInstances.back();
  4167. fieldInstance->mDataOffset = dataPos;
  4168. fieldInstance->mDataSize = innerType->mSize;
  4169. fieldInstance->mOwner = typeInstance;
  4170. fieldInstance->mResolvedType = innerType;
  4171. if (!innerType->IsValuelessType())
  4172. {
  4173. curFieldDataIdx++;
  4174. }
  4175. dataPos += dataSize;
  4176. typeInstance->mInstAlign = std::max(baseType->mInstAlign, alignSize);
  4177. int instAlign = typeInstance->mInstAlign;
  4178. if (instAlign != 0)
  4179. {
  4180. int instSize = (dataPos + (instAlign - 1)) & ~(instAlign - 1);
  4181. if (instSize != typeInstance->mInstSize)
  4182. {
  4183. typeInstance->mInstSize = instSize;
  4184. typeInstance->mHasPackingHoles = true;
  4185. }
  4186. }
  4187. typeInstance->mInstSize = std::max(1, typeInstance->mInstSize);
  4188. }
  4189. else
  4190. {
  4191. dataPos = typeInstance->mInstSize;
  4192. if (underlyingType != NULL)
  4193. {
  4194. if (!underlyingType->IsValuelessType())
  4195. {
  4196. curFieldDataIdx++;
  4197. }
  4198. }
  4199. struct DeferredResolveEntry
  4200. {
  4201. BfFieldDef* mFieldDef;
  4202. int mTypeArrayIdx;
  4203. };
  4204. BfSizedVector<DeferredResolveEntry, 8> deferredVarResolves;
  4205. for (auto field : typeDef->mFields)
  4206. {
  4207. auto fieldInstance = &typeInstance->mFieldInstances[field->mIdx];
  4208. if (fieldInstance->mResolvedType != NULL)
  4209. continue;
  4210. if (!typeInstance->IsTypeMemberIncluded(field->mDeclaringType))
  4211. {
  4212. fieldInstance->mFieldIncluded = false;
  4213. continue;
  4214. }
  4215. fieldInstance->mOwner = typeInstance;
  4216. fieldInstance->mFieldIdx = field->mIdx;
  4217. if (typeInstance->IsInterface())
  4218. Fail("Interfaces cannot include fields. Consider making this a property", field->GetRefNode());
  4219. }
  4220. for (int pass = 0; pass < 2; pass++)
  4221. {
  4222. for (auto field : typeDef->mFields)
  4223. {
  4224. // Do consts then non-consts. Somewhat of a hack for using consts as sized array size
  4225. if (field->mIsConst != (pass == 0))
  4226. continue;
  4227. auto fieldInstance = &typeInstance->mFieldInstances[field->mIdx];
  4228. if ((fieldInstance->mResolvedType != NULL) || (!fieldInstance->mFieldIncluded))
  4229. continue;
  4230. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, field);
  4231. SetAndRestoreValue<BfTypeState::ResolveKind> prevResolveKind(mContext->mCurTypeState->mResolveKind, BfTypeState::ResolveKind_FieldType);
  4232. BfType* resolvedFieldType = NULL;
  4233. auto initializer = field->GetInitializer();
  4234. if ((field->mIsAppend) && (!resolvedTypeRef->IsObject()))
  4235. Fail("Appended objects can only be declared in class types", field->GetFieldDeclaration()->mExternSpecifier, true);
  4236. if ((field->mIsAppend) && (isUnion))
  4237. Fail("Appended objects cannot be declared in unions", field->GetFieldDeclaration()->mExternSpecifier, true);
  4238. if (field->IsEnumCaseEntry())
  4239. {
  4240. if (typeInstance->IsEnum())
  4241. {
  4242. resolvedFieldType = typeInstance;
  4243. BfType* payloadType = NULL;
  4244. if (field->mTypeRef != NULL)
  4245. payloadType = ResolveTypeRef(field->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_NoResolveGenericParam);
  4246. if (payloadType == NULL)
  4247. {
  4248. if (!typeInstance->IsTypedPrimitive())
  4249. payloadType = CreateTupleType(BfTypeVector(), Array<String>());
  4250. }
  4251. if (payloadType != NULL)
  4252. {
  4253. AddDependency(payloadType, typeInstance, BfDependencyMap::DependencyFlag_ValueTypeMemberData);
  4254. BF_ASSERT(payloadType->IsTuple());
  4255. resolvedFieldType = payloadType;
  4256. fieldInstance->mIsEnumPayloadCase = true;
  4257. }
  4258. }
  4259. else
  4260. {
  4261. Fail("Enum cases can only be declared within enum types", field->GetRefNode(), true);
  4262. resolvedFieldType = typeInstance;
  4263. }
  4264. }
  4265. else if ((field->mTypeRef != NULL) && ((field->mTypeRef->IsExact<BfVarTypeReference>()) || (field->mTypeRef->IsExact<BfLetTypeReference>()) || (field->mTypeRef->IsExact<BfExprModTypeRef>())))
  4266. {
  4267. resolvedFieldType = GetPrimitiveType(BfTypeCode_Var);
  4268. DeferredResolveEntry resolveEntry;
  4269. resolveEntry.mFieldDef = field;
  4270. resolveEntry.mTypeArrayIdx = (int)llvmFieldTypes.size();
  4271. deferredVarResolves.push_back(resolveEntry);
  4272. fieldInstance->mIsInferredType = true;
  4273. // For 'let', make read-only
  4274. }
  4275. else
  4276. {
  4277. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_NoResolveGenericParam;
  4278. if (initializer != NULL)
  4279. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_AllowInferredSizedArray);
  4280. resolvedFieldType = ResolveTypeRef(field->mTypeRef, BfPopulateType_Declaration, resolveFlags);
  4281. if (resolvedFieldType == NULL)
  4282. {
  4283. // Failed, just put in placeholder 'var'
  4284. AssertErrorState();
  4285. resolvedFieldType = GetPrimitiveType(BfTypeCode_Var);
  4286. }
  4287. }
  4288. if (resolvedFieldType->IsUndefSizedArray())
  4289. {
  4290. if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(field->mTypeRef))
  4291. {
  4292. if (arrayTypeRef->IsInferredSize())
  4293. {
  4294. if (initializer != NULL)
  4295. {
  4296. DeferredResolveEntry resolveEntry;
  4297. resolveEntry.mFieldDef = field;
  4298. resolveEntry.mTypeArrayIdx = (int)llvmFieldTypes.size();
  4299. deferredVarResolves.push_back(resolveEntry);
  4300. fieldInstance->mIsInferredType = true;
  4301. }
  4302. else
  4303. {
  4304. AssertErrorState();
  4305. }
  4306. }
  4307. }
  4308. }
  4309. if (resolvedFieldType->IsMethodRef())
  4310. {
  4311. auto methodRefType = (BfMethodRefType*)resolvedFieldType;
  4312. }
  4313. if (fieldInstance->mResolvedType == NULL)
  4314. fieldInstance->mResolvedType = resolvedFieldType;
  4315. if (field->mIsConst)
  4316. {
  4317. // Resolve in ResolveConstField after we finish populating entire FieldInstance list
  4318. }
  4319. else if (field->mIsStatic)
  4320. {
  4321. // Don't allocate this until after we're finished populating entire FieldInstance list,
  4322. // because we may have re-entry and create multiple instances of this static field
  4323. }
  4324. }
  4325. }
  4326. // Assign enum indices
  4327. int enumCaseEntryIdx = 0;
  4328. for (auto field : typeDef->mFields)
  4329. {
  4330. auto fieldInstance = &typeInstance->mFieldInstances[field->mIdx];
  4331. if (!fieldInstance->mFieldIncluded)
  4332. continue;
  4333. if (field->IsEnumCaseEntry())
  4334. {
  4335. if (typeInstance->IsEnum())
  4336. {
  4337. fieldInstance->mDataIdx = -(enumCaseEntryIdx++) - 1;
  4338. }
  4339. }
  4340. }
  4341. if (!resolvedTypeRef->IsIncomplete())
  4342. {
  4343. // We finished resolving ourselves through a re-entry, so we're actually done here
  4344. return;
  4345. }
  4346. for (auto& resolveEntry : deferredVarResolves)
  4347. {
  4348. hadDeferredVars = true;
  4349. auto fieldType = ResolveVarFieldType(typeInstance, &typeInstance->mFieldInstances[resolveEntry.mFieldDef->mIdx], resolveEntry.mFieldDef);
  4350. if (fieldType == NULL)
  4351. {
  4352. fieldType = mContext->mBfObjectType;
  4353. // We used to set mTypeFailed, but mHasBuildError is enough to cause a type rebuild properly
  4354. mHadBuildError = true;
  4355. //typeInstance->mTypeFailed = true;
  4356. }
  4357. auto fieldInstance = &typeInstance->mFieldInstances[resolveEntry.mFieldDef->mIdx];
  4358. fieldInstance->SetResolvedType(fieldType);
  4359. }
  4360. if (typeInstance->mResolvingConstField)
  4361. return;
  4362. bool hadSoftFail = false;
  4363. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  4364. {
  4365. auto fieldInstance = &fieldInstanceRef;
  4366. auto fieldDef = fieldInstance->GetFieldDef();
  4367. auto resolvedFieldType = fieldInstance->GetResolvedType();
  4368. if (!fieldInstance->mFieldIncluded)
  4369. continue;
  4370. if (fieldInstance->mCustomAttributes != NULL)
  4371. {
  4372. // Already handled
  4373. }
  4374. else if ((fieldDef != NULL) && (fieldDef->GetFieldDeclaration() != NULL) && (fieldDef->GetFieldDeclaration()->mAttributes != NULL) && (!typeInstance->mTypeFailed) && (!isRootSystemType))
  4375. {
  4376. if (auto propDecl = BfNodeDynCast<BfPropertyDeclaration>(fieldDef->mFieldDeclaration))
  4377. {
  4378. // Handled elsewhere
  4379. }
  4380. else
  4381. {
  4382. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, fieldDef);
  4383. fieldInstance->mCustomAttributes = GetCustomAttributes(fieldDef->GetFieldDeclaration()->mAttributes, fieldDef->mIsStatic ? BfAttributeTargets_StaticField : BfAttributeTargets_Field);
  4384. for (auto customAttr : fieldInstance->mCustomAttributes->mAttributes)
  4385. {
  4386. if (TypeToString(customAttr.mType) == "System.ThreadStaticAttribute")
  4387. {
  4388. if ((!fieldDef->mIsStatic) || (fieldDef->mIsConst))
  4389. {
  4390. Fail("ThreadStatic attribute can only be used on static fields", fieldDef->GetFieldDeclaration()->mAttributes);
  4391. }
  4392. }
  4393. }
  4394. }
  4395. }
  4396. if (resolvedFieldType == NULL)
  4397. {
  4398. if ((underlyingType != NULL) || (typeInstance->IsPayloadEnum()))
  4399. continue;
  4400. }
  4401. if (fieldDef == NULL)
  4402. continue;
  4403. if ((!fieldDef->mIsStatic) && (resolvedFieldType->IsValueType()))
  4404. {
  4405. // We need that type finished up for alignment and data size
  4406. // But if the type has failed then we need to avoid stack overflow so we don't finish it
  4407. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, fieldDef);
  4408. bool populateChildType = !typeInstance->mTypeFailed;
  4409. //bool populateChildType = true;
  4410. PopulateType(resolvedFieldType, populateChildType ? ((populateType == BfPopulateType_Data_Soft) ? BfPopulateType_Data_Soft : BfPopulateType_Data) : BfPopulateType_Declaration);
  4411. if (populateType == BfPopulateType_Data_Soft)
  4412. {
  4413. if (resolvedFieldType->IsDataIncomplete())
  4414. hadSoftFail = true;
  4415. }
  4416. else if (populateChildType)
  4417. {
  4418. if (resolvedFieldType->IsFinishingType())
  4419. {
  4420. AssertErrorState();
  4421. }
  4422. else
  4423. BF_ASSERT(!resolvedFieldType->IsDataIncomplete());
  4424. }
  4425. else
  4426. {
  4427. if (resolvedFieldType->IsDataIncomplete())
  4428. {
  4429. AssertErrorState();
  4430. resolvedFieldType = mContext->mBfObjectType;
  4431. fieldInstance->SetResolvedType(resolvedFieldType);
  4432. // We used to set mTypeFailed, but mHasBuildError is enough to cause a type rebuild properly
  4433. mHadBuildError = true;
  4434. }
  4435. }
  4436. }
  4437. }
  4438. if (hadSoftFail)
  4439. return;
  4440. bool tryCE = true;
  4441. if (typeInstance->mDefineState == BfTypeDefineState_CETypeInit)
  4442. {
  4443. if (populateType <= BfPopulateType_AllowStaticMethods)
  4444. return;
  4445. int foundTypeCount = 0;
  4446. auto typeState = mContext->mCurTypeState;
  4447. while (typeState != NULL)
  4448. {
  4449. if (typeState->mType == typeInstance)
  4450. {
  4451. foundTypeCount++;
  4452. if (foundTypeCount == 2)
  4453. break;
  4454. }
  4455. typeState = typeState->mPrevState;
  4456. }
  4457. if ((foundTypeCount >= 2) || (typeInstance->mTypeDef->IsEmitted()))
  4458. {
  4459. String error = "OnCompile const evaluation creates a data dependency during TypeInit";
  4460. if (mCompiler->mCeMachine->mCurBuilder != NULL)
  4461. {
  4462. error += StrFormat(" during const-eval generation of '%s'", MethodToString(mCompiler->mCeMachine->mCurBuilder->mCeFunction->mMethodInstance).c_str());
  4463. }
  4464. auto refNode = typeDef->GetRefNode();
  4465. Fail(error, refNode);
  4466. if ((mCompiler->mCeMachine->mCurContext != NULL) && (mCompiler->mCeMachine->mCurContext->mCurFrame != NULL))
  4467. mCompiler->mCeMachine->mCurContext->Fail(*mCompiler->mCeMachine->mCurContext->mCurFrame, error);
  4468. else if (mCompiler->mCeMachine->mCurContext != NULL)
  4469. mCompiler->mCeMachine->mCurContext->Fail(error);
  4470. tryCE = false;
  4471. }
  4472. }
  4473. if ((typeInstance->mDefineState < BfTypeDefineState_CEPostTypeInit) && (tryCE))
  4474. {
  4475. BF_ASSERT(!typeInstance->mTypeDef->IsEmitted());
  4476. if (typeInstance->mCeTypeInfo != NULL)
  4477. typeInstance->mCeTypeInfo->mPendingInterfaces.Clear();
  4478. typeInstance->mDefineState = BfTypeDefineState_CETypeInit;
  4479. bool hadNewMembers = false;
  4480. DoCEEmit(typeInstance, hadNewMembers, underlyingTypeDeferred);
  4481. if (typeInstance->mDefineState < BfTypeDefineState_CEPostTypeInit)
  4482. typeInstance->mDefineState = BfTypeDefineState_CEPostTypeInit;
  4483. if (typeInstance->mCeTypeInfo != NULL)
  4484. {
  4485. bool prevHadEmissions = !typeInstance->mCeTypeInfo->mEmitSourceMap.IsEmpty();
  4486. if (typeInstance->mCeTypeInfo->mNext != NULL)
  4487. {
  4488. BfLogSysM("Type %p injecting next ceTypeInfo %p into ceTypeInfo %p\n", typeInstance, typeInstance->mCeTypeInfo->mNext, typeInstance->mCeTypeInfo);
  4489. auto ceInfo = typeInstance->mCeTypeInfo->mNext;
  4490. HashContext hashCtx;
  4491. hashCtx.Mixin(ceInfo->mEmitSourceMap.mCount);
  4492. for (auto& kv : ceInfo->mEmitSourceMap)
  4493. {
  4494. hashCtx.Mixin(kv.mKey);
  4495. hashCtx.Mixin(kv.mValue.mKind);
  4496. hashCtx.Mixin(kv.mValue.mSrcStart);
  4497. hashCtx.Mixin(kv.mValue.mSrcEnd);
  4498. }
  4499. hashCtx.Mixin(ceInfo->mOnCompileMap.mCount);
  4500. for (auto& kv : ceInfo->mOnCompileMap)
  4501. {
  4502. hashCtx.Mixin(kv.mKey);
  4503. hashCtx.MixinStr(kv.mValue.mEmitData);
  4504. }
  4505. hashCtx.Mixin(ceInfo->mTypeIFaceMap.mCount);
  4506. for (auto& kv : ceInfo->mTypeIFaceMap)
  4507. {
  4508. hashCtx.Mixin(kv.mKey);
  4509. hashCtx.MixinStr(kv.mValue.mEmitData);
  4510. }
  4511. typeInstance->mCeTypeInfo->mNext->mHash = hashCtx.Finish128();
  4512. if (!typeInstance->mCeTypeInfo->mNext->mFastFinished)
  4513. {
  4514. if ((typeInstance->mCeTypeInfo->mHash != typeInstance->mCeTypeInfo->mNext->mHash) && (!typeInstance->mCeTypeInfo->mHash.IsZero()))
  4515. mContext->QueueMidCompileRebuildDependentTypes(typeInstance, "comptime hash changed");
  4516. typeInstance->mCeTypeInfo->mEmitSourceMap = typeInstance->mCeTypeInfo->mNext->mEmitSourceMap;
  4517. typeInstance->mCeTypeInfo->mOnCompileMap = typeInstance->mCeTypeInfo->mNext->mOnCompileMap;
  4518. typeInstance->mCeTypeInfo->mTypeIFaceMap = typeInstance->mCeTypeInfo->mNext->mTypeIFaceMap;
  4519. typeInstance->mCeTypeInfo->mHash = typeInstance->mCeTypeInfo->mNext->mHash;
  4520. typeInstance->mCeTypeInfo->mAlign = typeInstance->mCeTypeInfo->mNext->mAlign;
  4521. }
  4522. else
  4523. {
  4524. // This greatly increases dependent type rebuilds, which triggers other issues
  4525. /*if ((typeInstance->mCeTypeInfo->mHash != typeInstance->mCeTypeInfo->mNext->mHash) && (!typeInstance->mCeTypeInfo->mHash.IsZero()))
  4526. mContext->QueueMidCompileRebuildDependentTypes(typeInstance, "canceled comptime hash changed");*/
  4527. }
  4528. delete typeInstance->mCeTypeInfo->mNext;
  4529. typeInstance->mCeTypeInfo->mNext = NULL;
  4530. }
  4531. else
  4532. {
  4533. // Removed emissions
  4534. if (!typeInstance->mCeTypeInfo->mHash.IsZero())
  4535. mContext->QueueMidCompileRebuildDependentTypes(typeInstance, "removed comptime hash changed");
  4536. typeInstance->mCeTypeInfo->mEmitSourceMap.Clear();
  4537. typeInstance->mCeTypeInfo->mOnCompileMap.Clear();
  4538. typeInstance->mCeTypeInfo->mTypeIFaceMap.Clear();
  4539. typeInstance->mCeTypeInfo->mHash = Val128();
  4540. }
  4541. if (((typeInstance->mCeTypeInfo->mFailed) || (typeInstance->mTypeDef->HasParsingFailed())) &&
  4542. (prevHadEmissions))
  4543. {
  4544. // Just add a marker to retain the previous open emits
  4545. typeInstance->mCeTypeInfo->mEmitSourceMap[-1] = BfCeTypeEmitSource();
  4546. }
  4547. typeInstance->mCeTypeInfo->mFailed = false;
  4548. }
  4549. if (typeInstance->mCeTypeInfo != NULL)
  4550. {
  4551. if (!typeInstance->mCeTypeInfo->mPendingInterfaces.IsEmpty())
  4552. hadNewMembers = true;
  4553. }
  4554. if ((typeInstance->mTypeDef->IsEmitted()) && (typeInstance->mCeTypeInfo == NULL))
  4555. {
  4556. BF_ASSERT(mCompiler->mCanceling);
  4557. if (mCompiler->mCanceling)
  4558. {
  4559. TypeFailed(typeInstance);
  4560. auto prevTypeDef = typeInstance->mTypeDef->mEmitParent;
  4561. delete typeInstance->mTypeDef;
  4562. typeInstance->mTypeDef = prevTypeDef;
  4563. hadNewMembers = false;
  4564. }
  4565. }
  4566. if (hadNewMembers)
  4567. {
  4568. // Avoid getting stale cached comptime reflection info
  4569. mCompiler->mCeMachine->mCeModule->mTypeDataRefs.Remove(resolvedTypeRef);
  4570. // We need to avoid passing in BfPopulateType_Interfaces_All because it could cause us to miss out on new member processing,
  4571. // including resizing the method group table
  4572. DoPopulateType(resolvedTypeRef, BF_MAX(populateType, BfPopulateType_Data));
  4573. return;
  4574. }
  4575. if (_CheckTypeDone())
  4576. return;
  4577. }
  4578. }
  4579. // Type now has interfaces added from CEInit
  4580. if (typeInstance->mDefineState < BfTypeDefineState_HasInterfaces_All)
  4581. typeInstance->mDefineState = BfTypeDefineState_HasInterfaces_All;
  4582. if (_CheckTypeDone())
  4583. return;
  4584. BF_ASSERT(mContext->mCurTypeState == &typeState);
  4585. //BF_ASSERT(!typeInstance->mIsFinishingType);
  4586. typeInstance->mIsFinishingType = true;
  4587. // No re-entry is allowed below here -- we will run all the way to the end at this point
  4588. BfSizedVector<BfIRMDNode, 8> diFieldTypes;
  4589. HashContext dataMemberHashCtx;
  4590. if (!resolvedTypeRef->IsBoxed())
  4591. {
  4592. for (auto propDef : typeDef->mProperties)
  4593. {
  4594. if (!typeInstance->IsTypeMemberIncluded(propDef->mDeclaringType))
  4595. continue;
  4596. if (propDef->mFieldDeclaration != NULL)
  4597. {
  4598. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, propDef);
  4599. BfAttributeTargets target = BfAttributeTargets_Property;
  4600. if (propDef->IsExpressionBodied())
  4601. target = (BfAttributeTargets)(target | BfAttributeTargets_Method);
  4602. if ((propDef->GetFieldDeclaration()->mAttributes != NULL) && (!typeInstance->mTypeFailed) && (!isRootSystemType))
  4603. {
  4604. auto customAttrs = GetCustomAttributes(propDef->GetFieldDeclaration()->mAttributes, target);
  4605. delete customAttrs;
  4606. }
  4607. auto propDecl = (BfPropertyDeclaration*)propDef->mFieldDeclaration;
  4608. if (propDecl->mExplicitInterface != NULL)
  4609. {
  4610. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  4611. mCompiler->mResolvePassData->mAutoComplete->CheckTypeRef(propDecl->mExplicitInterface, false);
  4612. auto explicitInterface = ResolveTypeRef(propDecl->mExplicitInterface, BfPopulateType_Declaration);
  4613. if (explicitInterface != NULL)
  4614. {
  4615. bool interfaceFound = false;
  4616. for (auto ifaceInst : typeInstance->mInterfaces)
  4617. interfaceFound |= ifaceInst.mInterfaceType == explicitInterface;
  4618. if ((!interfaceFound) && (!typeInstance->mTypeFailed))
  4619. {
  4620. Fail("Containing class has not declared to implement this interface", propDecl->mExplicitInterface, true);
  4621. }
  4622. }
  4623. }
  4624. }
  4625. if (propDef->mMethods.IsEmpty())
  4626. {
  4627. auto nameNode = ((BfPropertyDeclaration*)propDef->mFieldDeclaration)->mNameNode;
  4628. if (nameNode != NULL)
  4629. {
  4630. Fail(StrFormat("Property or indexer '%s.%s' must have at least one accessor", TypeToString(typeInstance).c_str(), propDef->mName.c_str()),
  4631. nameNode, true); // CS0548
  4632. }
  4633. }
  4634. }
  4635. bool isGlobalContainer = typeDef->IsGlobalsContainer();
  4636. if (typeInstance->mBaseType != NULL)
  4637. {
  4638. dataMemberHashCtx.Mixin(typeInstance->mBaseType->mTypeId);
  4639. if (typeInstance->mBaseType->mHotTypeData != NULL)
  4640. {
  4641. BfHotTypeVersion* ver = typeInstance->mBaseType->mHotTypeData->GetLatestVersion();
  4642. dataMemberHashCtx.Mixin(ver->mDataHash);
  4643. }
  4644. }
  4645. dataMemberHashCtx.Mixin(typeInstance->mPacking);
  4646. dataMemberHashCtx.Mixin(typeInstance->mIsCRepr);
  4647. dataMemberHashCtx.Mixin(typeInstance->mIsUnion);
  4648. int startDataPos = dataPos;
  4649. int maxDataPos = dataPos;
  4650. BfSizedVector<BfFieldInstance*, 16> dataFieldVec;
  4651. bool allowInstanceFields = (underlyingType == NULL);
  4652. if (typeInstance->IsTypedPrimitive())
  4653. allowInstanceFields = false;
  4654. // We've resolved all the 'var' entries, so now build the actual composite type
  4655. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  4656. {
  4657. auto fieldInstance = &fieldInstanceRef;
  4658. if (!fieldInstance->mFieldIncluded)
  4659. continue;
  4660. auto resolvedFieldType = fieldInstance->GetResolvedType();
  4661. if (fieldInstance->mResolvedType == NULL)
  4662. {
  4663. if ((underlyingType == NULL) && (!typeInstance->IsPayloadEnum()))
  4664. BF_ASSERT(typeInstance->mTypeFailed);
  4665. continue;
  4666. }
  4667. if ((fieldInstance->GetFieldDef() != NULL) && (fieldInstance->GetFieldDef()->mIsConst))
  4668. {
  4669. // Resolve later
  4670. AddDependency(resolvedFieldType, typeInstance, BfDependencyMap::DependencyFlag_ConstValue);
  4671. }
  4672. else if (fieldInstance->GetFieldDef() != NULL)
  4673. {
  4674. if (!fieldInstance->GetFieldDef()->mIsStatic)
  4675. AddFieldDependency(typeInstance, fieldInstance, resolvedFieldType);
  4676. else
  4677. AddDependency(resolvedFieldType, typeInstance, BfDependencyMap::DependencyFlag_StaticValue);
  4678. }
  4679. auto fieldDef = fieldInstance->GetFieldDef();
  4680. if (fieldInstance->mResolvedType != NULL)
  4681. {
  4682. auto resolvedFieldType = fieldInstance->GetResolvedType();
  4683. if ((!typeInstance->IsBoxed()) && (fieldDef != NULL))
  4684. {
  4685. if ((fieldDef->mUsingProtection != BfProtection_Hidden) && (!resolvedFieldType->IsGenericParam()) && (!resolvedFieldType->IsObject()) && (!resolvedFieldType->IsStruct()))
  4686. Warn(0, StrFormat("Field type '%s' is not applicable for 'using'", TypeToString(resolvedFieldType).c_str()), fieldDef->GetFieldDeclaration()->mConstSpecifier);
  4687. if (fieldInstance->mIsEnumPayloadCase)
  4688. {
  4689. PopulateType(resolvedFieldType, BfPopulateType_Data);
  4690. if (resolvedFieldType->WantsGCMarking())
  4691. typeInstance->mWantsGCMarking = true;
  4692. }
  4693. if ((!fieldDef->mIsConst) && (!fieldDef->mIsStatic))
  4694. {
  4695. PopulateType(resolvedFieldType, resolvedFieldType->IsValueType() ? BfPopulateType_Data : BfPopulateType_Declaration);
  4696. if (resolvedFieldType->WantsGCMarking())
  4697. typeInstance->mWantsGCMarking = true;
  4698. fieldInstance->mMergedDataIdx = typeInstance->mMergedFieldDataCount;
  4699. if (resolvedFieldType->IsStruct())
  4700. {
  4701. auto resolvedFieldTypeInstance = resolvedFieldType->ToTypeInstance();
  4702. typeInstance->mMergedFieldDataCount += resolvedFieldTypeInstance->mMergedFieldDataCount;
  4703. }
  4704. else if (!resolvedFieldType->IsValuelessType())
  4705. typeInstance->mMergedFieldDataCount++;
  4706. if (fieldDef->mIsExtern)
  4707. {
  4708. Fail("Cannot declare instance member as 'extern'", fieldDef->GetFieldDeclaration()->mExternSpecifier, true);
  4709. }
  4710. BfAstNode* nameRefNode = NULL;
  4711. if (auto fieldDecl = fieldDef->GetFieldDeclaration())
  4712. nameRefNode = fieldDecl->mNameNode;
  4713. else if (auto paramDecl = fieldDef->GetParamDeclaration())
  4714. nameRefNode = paramDecl->mNameNode;
  4715. if (nameRefNode == NULL)
  4716. nameRefNode = fieldDef->mTypeRef;
  4717. if (!allowInstanceFields)
  4718. {
  4719. if (typeInstance->IsEnum())
  4720. Fail("Cannot declare instance members in an enum", nameRefNode, true);
  4721. else if (typeInstance->IsFunction())
  4722. Fail("Cannot declare instance members in a function", nameRefNode, true);
  4723. else
  4724. Fail("Cannot declare instance members in a typed primitive struct", nameRefNode, true);
  4725. TypeFailed(typeInstance);
  4726. fieldInstance->mDataIdx = -1;
  4727. continue;
  4728. }
  4729. if (typeDef->mIsStatic)
  4730. {
  4731. //CS0708
  4732. Fail("Cannot declare instance members in a static class", nameRefNode, true);
  4733. }
  4734. if (resolvedFieldType->IsValueType())
  4735. {
  4736. BF_ASSERT((!resolvedFieldType->IsDataIncomplete()) || (resolvedFieldType->HasTypeFailed()));
  4737. }
  4738. if (!mCompiler->mIsResolveOnly)
  4739. {
  4740. dataMemberHashCtx.MixinStr(fieldDef->mName);
  4741. dataMemberHashCtx.Mixin(resolvedFieldType->mTypeId);
  4742. }
  4743. int dataSize = resolvedFieldType->mSize;
  4744. int alignSize = resolvedFieldType->mAlign;
  4745. if (fieldInstance->IsAppendedObject())
  4746. {
  4747. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, fieldDef);
  4748. SetAndRestoreValue<BfTypeState::ResolveKind> prevResolveKind(mContext->mCurTypeState->mResolveKind, BfTypeState::ResolveKind_FieldType);
  4749. PopulateType(resolvedFieldType, BfPopulateType_Data);
  4750. auto fieldTypeInst = resolvedFieldType->ToTypeInstance();
  4751. dataSize = BF_MAX(fieldTypeInst->mInstSize, 0);
  4752. alignSize = BF_MAX(fieldTypeInst->mInstAlign, 1);
  4753. if (fieldTypeInst->mTypeFailed)
  4754. {
  4755. TypeFailed(fieldTypeInst);
  4756. fieldInstance->mResolvedType = GetPrimitiveType(BfTypeCode_Var);
  4757. continue;
  4758. }
  4759. if ((typeInstance != NULL) && (fieldTypeInst->mTypeDef->mIsAbstract))
  4760. {
  4761. Fail("Cannot create an instance of an abstract class", nameRefNode);
  4762. }
  4763. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  4764. BfMethodState methodState;
  4765. SetAndRestoreValue<BfMethodState*> prevMethodState(mCurMethodState, &methodState);
  4766. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  4767. BfTypedValue appendIndexValue;
  4768. BfExprEvaluator exprEvaluator(this);
  4769. BfResolvedArgs resolvedArgs;
  4770. auto fieldDecl = fieldDef->GetFieldDeclaration();
  4771. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(fieldDecl->mInitializer))
  4772. {
  4773. resolvedArgs.Init(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  4774. exprEvaluator.ResolveArgValues(resolvedArgs, BfResolveArgsFlag_DeferParamEval);
  4775. }
  4776. BfFunctionBindResult bindResult;
  4777. bindResult.mSkipThis = true;
  4778. bindResult.mWantsArgs = true;
  4779. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(exprEvaluator.mFunctionBindResult, &bindResult);
  4780. BfTypedValue emptyThis(mBfIRBuilder->GetFakeVal(), resolvedTypeRef, resolvedTypeRef->IsStruct());
  4781. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_Comptime;
  4782. auto ctorResult = exprEvaluator.MatchConstructor(nameRefNode, NULL, emptyThis, fieldTypeInst, resolvedArgs, false, BfMethodGenericArguments(), true);
  4783. if ((bindResult.mMethodInstance != NULL) && (bindResult.mMethodInstance->mMethodDef->mHasAppend))
  4784. {
  4785. auto calcAppendMethodModule = GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  4786. SizedArray<BfIRValue, 2> irArgs;
  4787. if (bindResult.mIRArgs.size() > 1)
  4788. irArgs.Insert(0, &bindResult.mIRArgs[1], bindResult.mIRArgs.size() - 1);
  4789. BfTypedValue appendSizeTypedValue = TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, irArgs, true);
  4790. if (appendSizeTypedValue)
  4791. {
  4792. int appendAlign = calcAppendMethodModule.mMethodInstance->mAppendAllocAlign;
  4793. dataSize = BF_ALIGN(dataSize, appendAlign);
  4794. alignSize = BF_MAX(alignSize, appendAlign);
  4795. auto constant = mBfIRBuilder->GetConstant(appendSizeTypedValue.mValue);
  4796. if (constant != NULL)
  4797. {
  4798. dataSize += constant->mInt32;
  4799. }
  4800. }
  4801. else
  4802. {
  4803. Fail(StrFormat("Append constructor '%s' does not result in a constant size", MethodToString(bindResult.mMethodInstance).c_str()), nameRefNode);
  4804. }
  4805. }
  4806. }
  4807. else if (fieldDef->mIsAppend)
  4808. {
  4809. if (!typeInstance->IsObject())
  4810. Fail("Append fields can only be declared in classes", nameRefNode, true);
  4811. else if (resolvedFieldType->IsGenericParam())
  4812. {
  4813. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, fieldDef);
  4814. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)resolvedFieldType, false, BfFailHandleKind_Soft);
  4815. if (genericParamInstance != NULL)
  4816. {
  4817. if (((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Class) == 0) &&
  4818. ((genericParamInstance->mTypeConstraint == NULL) || (!genericParamInstance->mTypeConstraint->IsObject())))
  4819. {
  4820. Fail(StrFormat("Append fields must be classes. Consider adding a 'where %s : class' constraint.", genericParamInstance->GetName().c_str()), nameRefNode, true);
  4821. }
  4822. }
  4823. }
  4824. else if (!resolvedFieldType->IsObject())
  4825. Fail("Append fields must be classes", nameRefNode, true);
  4826. }
  4827. BF_ASSERT(dataSize >= 0);
  4828. fieldInstance->mDataSize = dataSize;
  4829. if (!isUnion)
  4830. {
  4831. if (!resolvedFieldType->IsValuelessType())
  4832. {
  4833. dataFieldVec.push_back(fieldInstance);
  4834. }
  4835. }
  4836. else
  4837. {
  4838. BF_ASSERT(resolvedFieldType->mSize >= 0);
  4839. // if (alignSize > 1)
  4840. // dataPos = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  4841. fieldInstance->mDataOffset = dataPos;
  4842. typeInstance->mInstAlign = std::max(typeInstance->mInstAlign, alignSize);
  4843. dataPos += dataSize;
  4844. if (dataPos > maxDataPos)
  4845. {
  4846. maxDataPos = dataPos;
  4847. }
  4848. dataPos = startDataPos;
  4849. }
  4850. auto fieldTypeInst = resolvedFieldType->ToTypeInstance();
  4851. if (fieldTypeInst != NULL)
  4852. {
  4853. if ((fieldTypeInst->mRebuildFlags & BfTypeRebuildFlag_UnderlyingTypeDeferred) != 0)
  4854. {
  4855. if (populateType < BfPopulateType_Data)
  4856. {
  4857. // We don't actually need the data - bail out
  4858. return;
  4859. }
  4860. BfAstNode* refNode = fieldDef->mFieldDeclaration;
  4861. String failStr;
  4862. failStr = StrFormat("Circular data reference detected between '%s' and '%s'", TypeToString(mCurTypeInstance).c_str(), TypeToString(fieldTypeInst).c_str());
  4863. if (!mContext->mFieldResolveReentrys.IsEmpty())
  4864. {
  4865. failStr += StrFormat(" with the following fields:", TypeToString(mCurTypeInstance).c_str());
  4866. for (int i = 0; i < (int)mContext->mFieldResolveReentrys.size(); i++)
  4867. {
  4868. auto checkField = mContext->mFieldResolveReentrys[i];
  4869. if (i > 0)
  4870. failStr += ",";
  4871. failStr += "\n '" + TypeToString(typeInstance) + "." + checkField->GetFieldDef()->mName + "'";
  4872. if (checkField->mOwner == fieldTypeInst)
  4873. refNode = checkField->GetFieldDef()->mFieldDeclaration;
  4874. }
  4875. }
  4876. BfError* err = Fail(failStr, refNode);
  4877. if (err)
  4878. err->mIsPersistent = true;
  4879. }
  4880. }
  4881. }
  4882. bool useForUnion = false;
  4883. if (fieldInstance->mIsEnumPayloadCase)
  4884. {
  4885. if (!typeInstance->IsEnum())
  4886. {
  4887. Fail("Cases can only be used in enum types", fieldDef->mFieldDeclaration);
  4888. }
  4889. else
  4890. {
  4891. BF_ASSERT(typeInstance->mIsUnion);
  4892. }
  4893. }
  4894. if ((!fieldDef->mIsStatic) && (!resolvedFieldType->IsValuelessType()))
  4895. {
  4896. if (isUnion)
  4897. {
  4898. fieldInstance->mDataIdx = curFieldDataIdx;
  4899. }
  4900. }
  4901. }
  4902. if ((!typeInstance->IsSpecializedType()) && (!typeInstance->IsOnDemand()) && (fieldDef != NULL) && (!CheckDefineMemberProtection(fieldDef->mProtection, resolvedFieldType)))
  4903. {
  4904. //CS0052
  4905. Fail(StrFormat("Inconsistent accessibility: field type '%s' is less accessible than field '%s.%s'",
  4906. TypeToString(resolvedFieldType).c_str(), TypeToString(mCurTypeInstance).c_str(), fieldDef->mName.c_str()),
  4907. fieldDef->mTypeRef, true);
  4908. }
  4909. }
  4910. }
  4911. if (typeInstance->mIsUnion)
  4912. {
  4913. SetAndRestoreValue<BfTypeState::ResolveKind> prevResolveKind(typeState.mResolveKind, BfTypeState::ResolveKind_UnionInnerType);
  4914. unionInnerType = typeInstance->GetUnionInnerType();
  4915. }
  4916. if (!isOrdered)
  4917. {
  4918. int dataFieldCount = (int)dataFieldVec.size();
  4919. Array<Deque<BfFieldInstance*>> alignBuckets;
  4920. for (auto fieldInst : dataFieldVec)
  4921. {
  4922. int alignBits = GetHighestBitSet(fieldInst->GetAlign(packing));
  4923. while (alignBits >= alignBuckets.size())
  4924. alignBuckets.Add({});
  4925. alignBuckets[alignBits].Add(fieldInst);
  4926. }
  4927. dataFieldVec.clear();
  4928. int curSize = dataPos;
  4929. while (dataFieldVec.size() != dataFieldCount)
  4930. {
  4931. // Clear out completed buckets
  4932. while (alignBuckets[alignBuckets.size() - 1].IsEmpty())
  4933. {
  4934. alignBuckets.pop_back();
  4935. }
  4936. int alignBits = GetNumLowZeroBits(curSize) + 1;
  4937. alignBits = BF_MIN(alignBits, (int)alignBuckets.size() - 1);
  4938. bool foundEntry = false;
  4939. while (alignBits >= 0)
  4940. {
  4941. if (alignBuckets[alignBits].IsEmpty())
  4942. {
  4943. alignBits--;
  4944. continue;
  4945. }
  4946. bool isHighestBucket = alignBits == alignBuckets.size() - 1;
  4947. auto fieldInst = alignBuckets[alignBits][0];
  4948. alignBuckets[alignBits].RemoveAt(0);
  4949. dataFieldVec.push_back(fieldInst);
  4950. curSize = BF_ALIGN(curSize, fieldInst->GetAlign(packing));
  4951. curSize += fieldInst->mDataSize;
  4952. foundEntry = true;
  4953. if (!isHighestBucket)
  4954. {
  4955. // We may have a larger type that can fit now...
  4956. break;
  4957. }
  4958. }
  4959. if (!foundEntry)
  4960. {
  4961. // If no entries will fit, then force an entry of the smallest alignment
  4962. for (int alignBits = 0; alignBits < alignBuckets.size(); alignBits++)
  4963. {
  4964. if (!alignBuckets[alignBits].IsEmpty())
  4965. {
  4966. auto fieldInst = alignBuckets[alignBits][0];
  4967. alignBuckets[alignBits].RemoveAt(0);
  4968. dataFieldVec.push_back(fieldInst);
  4969. curSize = BF_ALIGN(curSize, fieldInst->GetAlign(packing));
  4970. curSize += fieldInst->mDataSize;
  4971. break;
  4972. }
  4973. }
  4974. }
  4975. }
  4976. }
  4977. bool needsExplicitAlignment = true;
  4978. if (typeInstance->mCeTypeInfo != NULL)
  4979. {
  4980. typeInstance->mInstAlign = BF_MAX(typeInstance->mInstAlign, typeInstance->mCeTypeInfo->mAlign);
  4981. }
  4982. for (int fieldIdx = 0; fieldIdx < (int)dataFieldVec.size(); fieldIdx++)
  4983. {
  4984. auto fieldInstance = dataFieldVec[fieldIdx];
  4985. auto resolvedFieldType = fieldInstance->GetResolvedType();
  4986. BF_ASSERT(resolvedFieldType->mSize >= 0);
  4987. if (fieldInstance->mDataSize == 0)
  4988. fieldInstance->mDataSize = resolvedFieldType->mSize;
  4989. int dataSize = fieldInstance->mDataSize;
  4990. int alignSize = fieldInstance->GetAlign(packing);
  4991. int nextDataPos = dataPos;
  4992. nextDataPos = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  4993. int padding = nextDataPos - dataPos;
  4994. if ((alignSize > 1) && (needsExplicitAlignment) && (padding > 0))
  4995. {
  4996. curFieldDataIdx++;
  4997. }
  4998. dataPos = nextDataPos;
  4999. fieldInstance->mDataOffset = dataPos;
  5000. fieldInstance->mDataIdx = curFieldDataIdx++;
  5001. typeInstance->mInstAlign = std::max(typeInstance->mInstAlign, alignSize);
  5002. dataPos += dataSize;
  5003. }
  5004. if (unionInnerType != NULL)
  5005. {
  5006. dataPos = startDataPos + unionInnerType->mSize;
  5007. typeInstance->mInstAlign = BF_MAX(unionInnerType->mAlign, typeInstance->mInstAlign);
  5008. }
  5009. // Old dataMemberHash location
  5010. CheckMemberNames(typeInstance);
  5011. if (alignOverride > 0)
  5012. typeInstance->mInstAlign = alignOverride;
  5013. else
  5014. typeInstance->mInstAlign = std::max(1, typeInstance->mInstAlign);
  5015. int alignSize = typeInstance->mInstAlign;
  5016. if (isCRepr)
  5017. {
  5018. // Align size to alignment
  5019. if (alignSize >= 1)
  5020. typeInstance->mInstSize = (dataPos + (alignSize - 1)) & ~(alignSize - 1);
  5021. typeInstance->mIsCRepr = true;
  5022. }
  5023. else
  5024. {
  5025. typeInstance->mInstSize = dataPos;
  5026. typeInstance->mIsCRepr = false;
  5027. }
  5028. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL))
  5029. {
  5030. for (auto propDef : typeInstance->mTypeDef->mProperties)
  5031. if (propDef->mFieldDeclaration != NULL)
  5032. mCompiler->mResolvePassData->mAutoComplete->CheckProperty(BfNodeDynCast<BfPropertyDeclaration>(propDef->mFieldDeclaration));
  5033. }
  5034. }
  5035. if (typeInstance->IsObjectOrInterface())
  5036. typeInstance->mWantsGCMarking = true;
  5037. if ((mCompiler->mOptions.mEnableRealtimeLeakCheck) && (!typeInstance->mWantsGCMarking))
  5038. {
  5039. typeInstance->mTypeDef->PopulateMemberSets();
  5040. BfMemberSetEntry* entry = NULL;
  5041. BfMethodDef* methodDef = NULL;
  5042. if (typeInstance->mTypeDef->mMethodSet.TryGetWith(String(BF_METHODNAME_MARKMEMBERS), &entry))
  5043. {
  5044. methodDef = (BfMethodDef*)entry->mMemberDef;
  5045. if (methodDef->HasBody())
  5046. typeInstance->mWantsGCMarking = true;
  5047. }
  5048. }
  5049. if (typeInstance->IsValueType())
  5050. {
  5051. typeInstance->mSize = typeInstance->mInstSize;
  5052. typeInstance->mAlign = typeInstance->mInstAlign;
  5053. }
  5054. if ((mCompiler->mOptions.mAllowHotSwapping) && (typeInstance->mDefineState < BfTypeDefineState_Defined))
  5055. {
  5056. if (typeInstance->mHotTypeData == NULL)
  5057. {
  5058. BF_ASSERT(typeInstance->mTypeFailed);
  5059. }
  5060. else
  5061. {
  5062. auto hotTypeVersion = typeInstance->mHotTypeData->mTypeVersions.back();
  5063. if ((typeInstance->mBaseType != NULL) && (typeInstance->mBaseType->mHotTypeData != NULL))
  5064. {
  5065. hotTypeVersion->mMembers.Add(typeInstance->mBaseType->mHotTypeData->GetLatestVersion());
  5066. }
  5067. for (auto& fieldInst : typeInstance->mFieldInstances)
  5068. {
  5069. auto fieldDef = fieldInst.GetFieldDef();
  5070. if ((fieldDef == NULL) || (fieldDef->mIsStatic))
  5071. continue;
  5072. auto depType = fieldInst.mResolvedType;
  5073. while (depType->IsSizedArray())
  5074. depType = ((BfSizedArrayType*)depType)->mElementType;
  5075. if (depType->IsStruct())
  5076. {
  5077. PopulateType(depType);
  5078. auto depTypeInst = depType->ToTypeInstance();
  5079. BF_ASSERT(depTypeInst->mHotTypeData != NULL);
  5080. if (depTypeInst->mHotTypeData != NULL)
  5081. hotTypeVersion->mMembers.Add(depTypeInst->mHotTypeData->GetLatestVersion());
  5082. }
  5083. }
  5084. for (auto member : hotTypeVersion->mMembers)
  5085. member->mRefCount++;
  5086. }
  5087. }
  5088. if (_CheckTypeDone())
  5089. return;
  5090. if (typeInstance->mDefineState < BfTypeDefineState_Defined)
  5091. {
  5092. typeInstance->mDefineState = BfTypeDefineState_Defined;
  5093. if (!typeInstance->IsBoxed())
  5094. {
  5095. ExecuteCEOnCompile(NULL, typeInstance, BfCEOnCompileKind_TypeDone, underlyingTypeDeferred);
  5096. if (typeInstance->mDefineState == BfTypeDefineState_DefinedAndMethodsSlotted)
  5097. return;
  5098. }
  5099. }
  5100. if (typeInstance->mTypeFailed)
  5101. mHadBuildError = true;
  5102. CheckAddFailType();
  5103. BF_ASSERT_REL(typeInstance->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting);
  5104. BF_ASSERT_REL(typeInstance->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotted);
  5105. BfLogSysM("Setting mNeedsMethodProcessing=true on %p\n", typeInstance);
  5106. typeInstance->mNeedsMethodProcessing = true;
  5107. typeInstance->mIsFinishingType = false;
  5108. ///
  5109. // 'Splattable' means that we can be passed via 3 or fewer primitive/pointer values
  5110. if (typeInstance->mHasUnderlyingArray)
  5111. {
  5112. // Never splat
  5113. }
  5114. else if (typeInstance->IsStruct())
  5115. {
  5116. bool hadNonSplattable = false;
  5117. if (typeInstance->mBaseType != NULL)
  5118. PopulateType(typeInstance->mBaseType, BfPopulateType_Data);
  5119. if ((typeInstance->mBaseType == NULL) || (typeInstance->mBaseType->IsSplattable()))
  5120. {
  5121. int dataCount = 0;
  5122. std::function<void(BfType*)> splatIterate;
  5123. splatIterate = [&](BfType* checkType)
  5124. {
  5125. if (checkType->IsValueType())
  5126. PopulateType(checkType, BfPopulateType_Data);
  5127. if (checkType->IsMethodRef())
  5128. {
  5129. // For simplicity, any methodRef inside a struct makes the struct non-splattable. This reduces cases of needing to
  5130. // handle embedded methodRefs
  5131. hadNonSplattable = true;
  5132. }
  5133. else if (checkType->IsOpaque())
  5134. {
  5135. hadNonSplattable = true;
  5136. }
  5137. else if (checkType->IsStruct())
  5138. {
  5139. auto checkTypeInstance = checkType->ToTypeInstance();
  5140. if (checkTypeInstance->mBaseType != NULL)
  5141. splatIterate(checkTypeInstance->mBaseType);
  5142. if (checkTypeInstance->mIsUnion)
  5143. {
  5144. bool wantSplat = false;
  5145. auto unionInnerType = checkTypeInstance->GetUnionInnerType(&wantSplat);
  5146. if (!wantSplat)
  5147. hadNonSplattable = true;
  5148. splatIterate(unionInnerType);
  5149. if (checkTypeInstance->IsEnum())
  5150. dataCount++; // Discriminator
  5151. }
  5152. else
  5153. {
  5154. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  5155. {
  5156. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  5157. if (fieldInstance->mDataIdx >= 0)
  5158. splatIterate(fieldInstance->GetResolvedType());
  5159. }
  5160. }
  5161. }
  5162. else if (!checkType->IsValuelessType())
  5163. {
  5164. if (checkType->IsSizedArray())
  5165. hadNonSplattable = true;
  5166. dataCount += checkType->GetSplatCount();
  5167. }
  5168. };
  5169. splatIterate(typeInstance);
  5170. if (isCRepr)
  5171. {
  5172. if ((mCompiler->mOptions.mMachineType == BfMachineType_x86) && (mCompiler->mOptions.mPlatformType == BfPlatformType_Windows))
  5173. {
  5174. typeInstance->mIsSplattable = (dataCount <= 4) && (!hadNonSplattable) && (dataPos > 4);
  5175. }
  5176. else
  5177. typeInstance->mIsSplattable = false;
  5178. }
  5179. else
  5180. typeInstance->mIsSplattable = (dataCount <= 3) && (!hadNonSplattable);
  5181. }
  5182. }
  5183. if (typeInstance->IsTypedPrimitive())
  5184. typeInstance->mIsSplattable = true;
  5185. if (typeInstance->mTypeDef->mIsOpaque)
  5186. typeInstance->mIsSplattable = false;
  5187. BF_ASSERT(mContext->mCurTypeState == &typeState);
  5188. // This is only required for autocomplete and finding type references
  5189. if (!typeInstance->IsSpecializedType())
  5190. {
  5191. for (auto propDef : typeDef->mProperties)
  5192. {
  5193. if (propDef->mTypeRef == NULL)
  5194. continue;
  5195. BfTypeState typeState;
  5196. typeState.mPrevState = mContext->mCurTypeState;
  5197. typeState.mCurTypeDef = propDef->mDeclaringType;
  5198. typeState.mType = typeInstance;
  5199. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  5200. if (BfNodeIsA<BfVarTypeReference>(propDef->mTypeRef))
  5201. {
  5202. // This is only valid for ConstEval properties
  5203. }
  5204. else
  5205. ResolveTypeRef(propDef->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowRef);
  5206. }
  5207. }
  5208. // Const handling
  5209. {
  5210. Dictionary<int64, BfFieldDef*> valueMap;
  5211. for (auto& fieldInstanceRef : typeInstance->mFieldInstances)
  5212. {
  5213. auto fieldInstance = &fieldInstanceRef;
  5214. if (!fieldInstance->mFieldIncluded)
  5215. continue;
  5216. auto fieldDef = fieldInstance->GetFieldDef();
  5217. if (fieldDef == NULL)
  5218. continue;
  5219. if ((fieldInstance->mConstIdx == -1) && (fieldDef->mIsConst))
  5220. {
  5221. SetAndRestoreValue<BfFieldDef*> prevTypeRef(mContext->mCurTypeState->mCurFieldDef, fieldDef);
  5222. typeInstance->mModule->ResolveConstField(typeInstance, fieldInstance, fieldDef);
  5223. // Check enum cases for duplicates
  5224. if (mCurTypeInstance->IsEnum())
  5225. {
  5226. auto underlyingType = fieldInstance->mResolvedType->GetUnderlyingType();
  5227. if ((fieldDef->IsEnumCaseEntry()) && (fieldInstance->mConstIdx != -1) && (underlyingType->IsIntegral()))
  5228. {
  5229. auto foreignConst = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  5230. BfFieldDef** fieldDefPtr;
  5231. if (valueMap.TryAdd(foreignConst->mInt64, NULL, &fieldDefPtr))
  5232. {
  5233. *fieldDefPtr = fieldDef;
  5234. }
  5235. else if ((typeInstance->mCustomAttributes == NULL) || (typeInstance->mCustomAttributes->Get(mCompiler->mAllowDuplicatesAttributeTypeDef) == NULL))
  5236. {
  5237. 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);
  5238. if (error != NULL)
  5239. mCompiler->mPassInstance->MoreInfo(StrFormat("This value was previously used for field '%s'", (*fieldDefPtr)->mName.c_str()), (*fieldDefPtr)->GetRefNode());
  5240. }
  5241. }
  5242. }
  5243. }
  5244. }
  5245. }
  5246. if ((typeInstance->IsEnum()) && (!typeInstance->IsPayloadEnum()))
  5247. {
  5248. BfLogSysM("Setting underlying type %p %d\n", typeInstance, underlyingTypeDeferred);
  5249. }
  5250. DoPopulateType_FinishEnum(typeInstance, underlyingTypeDeferred, &dataMemberHashCtx, unionInnerType);
  5251. if (!typeInstance->IsBoxed())
  5252. {
  5253. if (typeInstance->IsTypedPrimitive())
  5254. {
  5255. auto underlyingType = typeInstance->GetUnderlyingType();
  5256. dataMemberHashCtx.Mixin(underlyingType->mTypeId);
  5257. }
  5258. Val128 dataMemberHash = dataMemberHashCtx.Finish128();
  5259. if (typeInstance->mHotTypeData != NULL)
  5260. {
  5261. auto newHotTypeVersion = typeInstance->mHotTypeData->GetLatestVersion();
  5262. newHotTypeVersion->mDataHash = dataMemberHash;
  5263. if (mCompiler->mHotState != NULL)
  5264. {
  5265. auto committedHotTypeVersion = typeInstance->mHotTypeData->GetTypeVersion(mCompiler->mHotState->mCommittedHotCompileIdx);
  5266. if (committedHotTypeVersion != NULL)
  5267. {
  5268. if ((newHotTypeVersion->mDataHash != committedHotTypeVersion->mDataHash) && (typeInstance->mIsReified))
  5269. {
  5270. BfLogSysM("Hot compile detected data changes in %p '%s'\n", resolvedTypeRef, TypeToString(typeInstance).c_str());
  5271. if (!typeInstance->mHotTypeData->mPendingDataChange)
  5272. {
  5273. mCompiler->mHotState->mPendingDataChanges.Add(typeInstance->mTypeId);
  5274. typeInstance->mHotTypeData->mPendingDataChange = true;
  5275. }
  5276. else
  5277. {
  5278. BF_ASSERT(mCompiler->mHotState->mPendingDataChanges.Contains(typeInstance->mTypeId));
  5279. }
  5280. bool baseHadChanges = (typeInstance->mBaseType != NULL) && (typeInstance->mBaseType->mHotTypeData != NULL) && (typeInstance->mBaseType->mHotTypeData->mPendingDataChange);
  5281. if (!baseHadChanges)
  5282. Warn(0, StrFormat("Hot compile detected data changes in '%s'", TypeToString(typeInstance).c_str()), typeDef->GetRefNode());
  5283. }
  5284. else if (typeInstance->mHotTypeData->mPendingDataChange)
  5285. {
  5286. BfLogSysM("Hot compile removed pending data change for %p '%s'\n", resolvedTypeRef, TypeToString(typeInstance).c_str());
  5287. mCompiler->mHotState->RemovePendingChanges(typeInstance);
  5288. }
  5289. }
  5290. }
  5291. }
  5292. }
  5293. if (typeInstance == mContext->mBfObjectType)
  5294. typeInstance->mHasBeenInstantiated = true;
  5295. auto _HandleTypeDeclaration = [&](BfTypeDeclaration* typeDeclaration)
  5296. {
  5297. if ((typeDeclaration != NULL) && (typeDeclaration->mNameNode != NULL))
  5298. {
  5299. auto typeRefSource = typeDeclaration->mNameNode->GetParserData();
  5300. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mIsClassifying) && (typeRefSource != NULL))
  5301. {
  5302. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(typeDeclaration->mNameNode))
  5303. {
  5304. BfSourceElementType elemType = BfSourceElementType_Type;
  5305. if (typeInstance->IsInterface())
  5306. elemType = BfSourceElementType_Interface;
  5307. else if (typeInstance->IsObject())
  5308. elemType = BfSourceElementType_RefType;
  5309. else if (typeInstance->IsStruct() || (typeInstance->IsTypedPrimitive() && !typeInstance->IsEnum()))
  5310. elemType = BfSourceElementType_Struct;
  5311. sourceClassifier->SetElementType(typeDeclaration->mNameNode, elemType);
  5312. }
  5313. }
  5314. }
  5315. };
  5316. if (!typeInstance->IsBoxed())
  5317. {
  5318. _HandleTypeDeclaration(typeDef->mTypeDeclaration);
  5319. for (auto partial : typeDef->mPartials)
  5320. _HandleTypeDeclaration(partial->mTypeDeclaration);
  5321. }
  5322. if (typeInstance->IsGenericTypeInstance())
  5323. {
  5324. auto genericTypeInst = (BfTypeInstance*)typeInstance;
  5325. if (!genericTypeInst->mGenericTypeInfo->mFinishedGenericParams)
  5326. FinishGenericParams(resolvedTypeRef);
  5327. }
  5328. if (populateType <= BfPopulateType_Data)
  5329. return;
  5330. disableYield.Release();
  5331. prevTypeState.Restore();
  5332. if (canDoMethodProcessing)
  5333. {
  5334. if (typeInstance->mNeedsMethodProcessing) // May have been handled by GetRawMethodInstanceAtIdx above
  5335. DoTypeInstanceMethodProcessing(typeInstance);
  5336. }
  5337. }
  5338. void BfModule::DoTypeInstanceMethodProcessing(BfTypeInstance* typeInstance)
  5339. {
  5340. if (typeInstance->IsDeleting())
  5341. {
  5342. BF_ASSERT(typeInstance->IsOnDemand());
  5343. return;
  5344. }
  5345. if (typeInstance->IsSpecializedByAutoCompleteMethod())
  5346. return;
  5347. if (typeInstance->mDefineState == BfTypeDefineState_DefinedAndMethodsSlotting)
  5348. {
  5349. BfLogSysM("DoTypeInstanceMethodProcessing %p re-entrancy exit\n", typeInstance);
  5350. return;
  5351. }
  5352. //
  5353. {
  5354. BP_ZONE("DoTypeInstanceMethodProcessing:CheckStack");
  5355. StackHelper stackHelper;
  5356. if (!stackHelper.CanStackExpand(128 * 1024))
  5357. {
  5358. if (!stackHelper.Execute([&]()
  5359. {
  5360. DoTypeInstanceMethodProcessing(typeInstance);
  5361. }))
  5362. {
  5363. Fail("Stack exhausted in DoPopulateType", typeInstance->mTypeDef->GetRefNode());
  5364. }
  5365. return;
  5366. }
  5367. }
  5368. BF_ASSERT_REL(typeInstance->mNeedsMethodProcessing);
  5369. BF_ASSERT_REL(typeInstance->mDefineState == BfTypeDefineState_Defined);
  5370. typeInstance->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotting;
  5371. BF_ASSERT(typeInstance->mModule == this);
  5372. //TODO: This is new, make sure this is in the right place
  5373. /*if (mAwaitingInitFinish)
  5374. FinishInit();*/
  5375. AutoDisallowYield disableYield(mSystem);
  5376. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, typeInstance);
  5377. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  5378. BfLogSysM("DoTypeInstanceMethodProcessing: %p %s Revision:%d DefineState:%d\n", typeInstance, TypeToString(typeInstance).c_str(), typeInstance->mRevision, typeInstance->mDefineState);
  5379. auto typeDef = typeInstance->mTypeDef;
  5380. BfTypeOptions* typeOptions = NULL;
  5381. if (typeInstance->mTypeOptionsIdx >= 0)
  5382. typeOptions = mSystem->GetTypeOptions(typeInstance->mTypeOptionsIdx);
  5383. BfMethodDef* defaultCtor = NULL;
  5384. bool hasExplicitCtors = false;
  5385. // Generate all methods. Pass 0
  5386. for (auto methodDef : typeDef->mMethods)
  5387. {
  5388. if ((methodDef->mMethodType == BfMethodType_Ctor) && (!methodDef->mIsStatic) && (!methodDef->mDeclaringType->IsExtension()))
  5389. {
  5390. if (methodDef->mMethodDeclaration == NULL)
  5391. {
  5392. defaultCtor = methodDef;
  5393. }
  5394. else
  5395. {
  5396. hasExplicitCtors = true;
  5397. }
  5398. }
  5399. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  5400. // Don't set these pointers during resolve pass because they may become invalid if it's just a temporary autocomplete method
  5401. if (mCompiler->mResolvePassData == NULL)
  5402. {
  5403. if ((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mIsStatic))
  5404. {
  5405. typeInstance->mHasStaticInitMethod = true;
  5406. }
  5407. if ((methodDef->mMethodType == BfMethodType_Dtor) && (methodDef->mIsStatic))
  5408. {
  5409. typeInstance->mHasStaticDtorMethod = true;
  5410. }
  5411. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC))
  5412. {
  5413. typeInstance->mHasStaticMarkMethod = true;
  5414. }
  5415. if ((methodDef->mMethodType == BfMethodType_Normal) && (methodDef->mIsStatic) && (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS))
  5416. {
  5417. typeInstance->mHasTLSFindMethod = true;
  5418. }
  5419. }
  5420. // Thsi MAY be generated already
  5421. // This should still be set to the default value
  5422. //BF_ASSERT((methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet) || (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude));
  5423. }
  5424. if ((defaultCtor != NULL) && (hasExplicitCtors))
  5425. {
  5426. // This can happen if we emit another ctor
  5427. defaultCtor->mProtection = BfProtection_Hidden;
  5428. }
  5429. if (typeInstance == mContext->mBfObjectType)
  5430. {
  5431. BF_ASSERT(typeInstance->mInterfaceMethodTable.size() == 0);
  5432. }
  5433. int newIntefaceStartIdx = 0;
  5434. auto implBaseType = typeInstance->GetImplBaseType();
  5435. if (implBaseType != NULL)
  5436. {
  5437. auto baseTypeInst = implBaseType->ToTypeInstance();
  5438. if (implBaseType->IsIncomplete())
  5439. PopulateType(implBaseType, BfPopulateType_Full_Force);
  5440. typeInstance->mInterfaceMethodTable = baseTypeInst->mInterfaceMethodTable;
  5441. typeInstance->mVirtualMethodTable = implBaseType->mVirtualMethodTable;
  5442. typeInstance->mVirtualMethodTableSize = implBaseType->mVirtualMethodTableSize;
  5443. if ((!mCompiler->IsHotCompile()) && (!mCompiler->mPassInstance->HasFailed()) && ((mCompiler->mResolvePassData == NULL) || (mCompiler->mResolvePassData->mAutoComplete == NULL)))
  5444. {
  5445. BF_ASSERT(typeInstance->mVirtualMethodTable.size() == typeInstance->mVirtualMethodTableSize);
  5446. }
  5447. else
  5448. {
  5449. BF_ASSERT(typeInstance->mVirtualMethodTableSize >= (int)typeInstance->mVirtualMethodTable.size());
  5450. }
  5451. }
  5452. // Add new interfaces
  5453. for (int iFaceIdx = 0; iFaceIdx < (int)typeInstance->mInterfaces.size(); iFaceIdx++)
  5454. {
  5455. BfTypeInterfaceEntry& typeInterfaceInst = typeInstance->mInterfaces[iFaceIdx];
  5456. auto checkInterface = typeInterfaceInst.mInterfaceType;
  5457. if (checkInterface->IsIncomplete())
  5458. PopulateType(checkInterface, BfPopulateType_Full_Force);
  5459. typeInterfaceInst.mStartInterfaceTableIdx = (int)typeInstance->mInterfaceMethodTable.size();
  5460. // We don't add to the vtable for interface declarations, we just reference the listed interfaces
  5461. if (!typeInstance->IsInterface())
  5462. {
  5463. auto interfaceTypeDef = checkInterface->mTypeDef;
  5464. BF_ASSERT((interfaceTypeDef->mMethods.size() == checkInterface->mMethodInstanceGroups.size()) || (checkInterface->IsDeleting()));
  5465. // Reserve empty entries
  5466. for (int methodIdx = 0; methodIdx < (int)interfaceTypeDef->mMethods.size(); methodIdx++)
  5467. typeInstance->mInterfaceMethodTable.push_back(BfTypeInterfaceMethodEntry());
  5468. }
  5469. }
  5470. auto checkTypeInstance = typeInstance;
  5471. while (checkTypeInstance != NULL)
  5472. {
  5473. // These may have been already added
  5474. for (auto&& interfaceEntry : checkTypeInstance->mInterfaces)
  5475. AddDependency(interfaceEntry.mInterfaceType, typeInstance, BfDependencyMap::DependencyFlag_ImplementsInterface);
  5476. checkTypeInstance = checkTypeInstance->GetImplBaseType();
  5477. }
  5478. //for (auto& intefaceInst : typeInstance->mInterfaces)
  5479. if (typeInstance == mContext->mBfObjectType)
  5480. {
  5481. BF_ASSERT(typeInstance->mInterfaceMethodTable.size() == 1);
  5482. }
  5483. // Slot interfaces method blocks in vtable
  5484. {
  5485. int ifaceVirtIdx = 0;
  5486. std::unordered_map<BfTypeInstance*, BfTypeInterfaceEntry*> interfaceMap;
  5487. BfTypeInstance* checkType = typeInstance->GetImplBaseType();
  5488. while (checkType != NULL)
  5489. {
  5490. for (auto&& ifaceEntry : checkType->mInterfaces)
  5491. {
  5492. interfaceMap[ifaceEntry.mInterfaceType] = &ifaceEntry;
  5493. ifaceVirtIdx = std::max(ifaceVirtIdx, ifaceEntry.mStartVirtualIdx + ifaceEntry.mInterfaceType->mVirtualMethodTableSize);
  5494. }
  5495. checkType = checkType->GetImplBaseType();
  5496. }
  5497. for (int iFaceIdx = 0; iFaceIdx < (int)typeInstance->mInterfaces.size(); iFaceIdx++)
  5498. {
  5499. BfTypeInterfaceEntry& typeInterfaceInst = typeInstance->mInterfaces[iFaceIdx];
  5500. auto itr = interfaceMap.find(typeInterfaceInst.mInterfaceType);
  5501. if (itr != interfaceMap.end())
  5502. {
  5503. auto prevEntry = itr->second;
  5504. typeInterfaceInst.mStartVirtualIdx = prevEntry->mStartVirtualIdx;
  5505. }
  5506. else
  5507. {
  5508. typeInterfaceInst.mStartVirtualIdx = ifaceVirtIdx;
  5509. ifaceVirtIdx += typeInterfaceInst.mInterfaceType->mVirtualMethodTableSize;
  5510. interfaceMap[typeInterfaceInst.mInterfaceType] = &typeInterfaceInst;
  5511. }
  5512. }
  5513. }
  5514. auto isBoxed = typeInstance->IsBoxed();
  5515. BfLogSysM("Setting mTypeIncomplete = false on %p\n", typeInstance);
  5516. typeInstance->mNeedsMethodProcessing = false;
  5517. typeInstance->mTypeIncomplete = false;
  5518. auto checkBaseType = typeInstance->GetImplBaseType();
  5519. while (checkBaseType != NULL)
  5520. {
  5521. PopulateType(checkBaseType, BfPopulateType_Full_Force);
  5522. BF_ASSERT((!checkBaseType->IsIncomplete()) || (checkBaseType->mTypeFailed));
  5523. checkBaseType = checkBaseType->GetImplBaseType();
  5524. }
  5525. if ((mCompiler->mOptions.mHasVDataExtender) && (!typeInstance->IsInterface()))
  5526. {
  5527. // This is the vExt entry for this type instance
  5528. BfVirtualMethodEntry entry;
  5529. entry.mDeclaringMethod.mMethodNum = -1;
  5530. entry.mDeclaringMethod.mTypeInstance = typeInstance;
  5531. typeInstance->mVirtualMethodTable.push_back(entry);
  5532. typeInstance->mVirtualMethodTableSize++;
  5533. }
  5534. // Fill out to correct size
  5535. if (typeInstance->mHotTypeData != NULL)
  5536. {
  5537. //auto hotLatestVersionHead = typeInstance->mHotTypeData->GetLatestVersionHead();
  5538. int wantVTableSize = typeInstance->GetImplBaseVTableSize() + (int)typeInstance->mHotTypeData->mVTableEntries.size();
  5539. while ((int)typeInstance->mVirtualMethodTable.size() < wantVTableSize)
  5540. {
  5541. typeInstance->mVirtualMethodTable.push_back(BfVirtualMethodEntry());
  5542. typeInstance->mVirtualMethodTableSize++;
  5543. }
  5544. }
  5545. BfAmbiguityContext ambiguityContext;
  5546. ambiguityContext.mTypeInstance = typeInstance;
  5547. ambiguityContext.mModule = this;
  5548. ambiguityContext.mIsProjectSpecific = false;
  5549. bool wantsOnDemandMethods = false;
  5550. //TODO: Testing having interface methods be "on demand"...
  5551. //if (!typeInstance->IsInterface())
  5552. //
  5553. {
  5554. if ((typeInstance->IsSpecializedType()) || (typeInstance->IsUnspecializedTypeVariation()))
  5555. wantsOnDemandMethods = true;
  5556. else if ((mCompiler->mOptions.mCompileOnDemandKind != BfCompileOnDemandKind_AlwaysInclude) &&
  5557. (!typeInstance->IsUnspecializedTypeVariation()))
  5558. {
  5559. //if (typeDef->mName->ToString() != "AttributeUsageAttribute")
  5560. auto attributeDef = mCompiler->mAttributeTypeDef;
  5561. auto attributeType = mContext->mUnreifiedModule->ResolveTypeDef(attributeDef, BfPopulateType_Identity)->ToTypeInstance();
  5562. if (!TypeIsSubTypeOf(mCurTypeInstance, attributeType, false))
  5563. {
  5564. wantsOnDemandMethods = true;
  5565. }
  5566. }
  5567. }
  5568. if (TypeIsSubTypeOf(typeInstance, mCompiler->mAttributeTypeDef))
  5569. wantsOnDemandMethods = false;
  5570. if ((mCompiler->mResolvePassData != NULL) && (!mCompiler->mResolvePassData->mEmitEmbedEntries.IsEmpty()) && (typeInstance->IsSpecializedType()))
  5571. {
  5572. bool isCurrentEntry = false;
  5573. auto _CheckEntry = [&](BfTypeDef* typeDef)
  5574. {
  5575. auto parser = typeDef->mTypeDeclaration->GetParser();
  5576. if (parser != NULL)
  5577. if (mCompiler->mResolvePassData->GetSourceClassifier(parser) != NULL)
  5578. isCurrentEntry = true;
  5579. };
  5580. _CheckEntry(typeInstance->mTypeDef);
  5581. for (auto& partial : typeInstance->mTypeDef->mPartials)
  5582. _CheckEntry(partial);
  5583. if (isCurrentEntry)
  5584. {
  5585. String typeName = TypeToString(typeInstance, BfTypeNameFlag_AddProjectName);
  5586. if (mCompiler->mResolvePassData->mEmitEmbedEntries.ContainsKey(typeName))
  5587. {
  5588. wantsOnDemandMethods = false;
  5589. }
  5590. }
  5591. }
  5592. //bool allDeclsRequired = (mIsReified) && (mCompiler->mOptions.mEmitDebugInfo) && ();
  5593. bool allDeclsRequired = false;
  5594. //if ((mIsReified) && (mCompiler->mOptions.mEmitDebugInfo) && (!mCompiler->mWantsDeferMethodDecls))
  5595. // if ((mIsReified) && (mCompiler->mOptions.mEmitDebugInfo))
  5596. // {
  5597. // allDeclsRequired = true;
  5598. // }
  5599. HashSet<String> ifaceMethodNameSet;
  5600. if (wantsOnDemandMethods)
  5601. {
  5602. for (int iFaceIdx = newIntefaceStartIdx; iFaceIdx < (int)typeInstance->mInterfaces.size(); iFaceIdx++)
  5603. {
  5604. BfTypeInterfaceEntry& typeInterfaceInst = typeInstance->mInterfaces[iFaceIdx];
  5605. for (auto checkMethodDef : typeInterfaceInst.mInterfaceType->mTypeDef->mMethods)
  5606. {
  5607. ifaceMethodNameSet.Add(checkMethodDef->mName);
  5608. }
  5609. }
  5610. }
  5611. bool isFailedType = mCurTypeInstance->mTypeFailed;
  5612. if (auto genericTypeInst = mCurTypeInstance->ToGenericTypeInstance())
  5613. {
  5614. if (genericTypeInst->mGenericTypeInfo->mHadValidateErrors)
  5615. isFailedType = true;
  5616. }
  5617. bool typeOptionsIncludeAll = false;
  5618. bool typeOptionsIncludeFiltered = false;
  5619. if (typeOptions != NULL)
  5620. {
  5621. typeOptionsIncludeAll = typeOptions->Apply(typeOptionsIncludeAll, BfOptionFlags_ReflectAlwaysIncludeAll);
  5622. typeOptionsIncludeFiltered = typeOptions->Apply(typeOptionsIncludeAll, BfOptionFlags_ReflectAlwaysIncludeFiltered);
  5623. }
  5624. // Generate all methods. Pass 1
  5625. for (auto methodDef : typeDef->mMethods)
  5626. {
  5627. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  5628. if (typeOptions != NULL)
  5629. {
  5630. BfOptionFlags optionFlags = BfOptionFlags_ReflectNonStaticMethods;
  5631. if (methodDef->mMethodType == BfMethodType_Ctor)
  5632. optionFlags = BfOptionFlags_ReflectConstructors;
  5633. else if (methodDef->mIsStatic)
  5634. optionFlags = BfOptionFlags_ReflectStaticMethods;
  5635. methodInstanceGroup->mExplicitlyReflected = typeOptions->Apply(false, optionFlags);
  5636. methodInstanceGroup->mExplicitlyReflected = ApplyTypeOptionMethodFilters(methodInstanceGroup->mExplicitlyReflected, methodDef, typeOptions);
  5637. }
  5638. if ((typeInstance->mCustomAttributes != NULL) && (typeInstance->mCustomAttributes->Contains(mCompiler->mReflectAttributeTypeDef)))
  5639. methodInstanceGroup->mExplicitlyReflected = true;
  5640. if (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_AlwaysInclude)
  5641. continue;
  5642. if (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_InWorkList)
  5643. continue;
  5644. if (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Referenced)
  5645. continue;
  5646. if (isFailedType)
  5647. {
  5648. // We don't want method decls from failed generic types to clog up our type system
  5649. continue;
  5650. }
  5651. BF_ASSERT((methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet) ||
  5652. (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  5653. (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference));
  5654. if ((isBoxed) && (!methodDef->mIsVirtual))
  5655. {
  5656. if (methodDef->mIsStatic)
  5657. continue;
  5658. bool boxedRequired = false;
  5659. if (((methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mParams.size() == 0)) ||
  5660. (methodDef->mMethodType == BfMethodType_Dtor) ||
  5661. ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) || (methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) || (methodDef->mName == BF_METHODNAME_INVOKE) || (methodDef->mName == BF_METHODNAME_DYNAMICCAST)) ||
  5662. (methodDef->mGenericParams.size() != 0))
  5663. boxedRequired = true;
  5664. if (!boxedRequired)
  5665. {
  5666. if (wantsOnDemandMethods)
  5667. {
  5668. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  5669. mOnDemandMethodCount++;
  5670. }
  5671. continue;
  5672. }
  5673. }
  5674. if (methodDef->mMethodType == BfMethodType_Ignore)
  5675. continue;
  5676. if ((methodDef->mName == BF_METHODNAME_DYNAMICCAST) && (typeInstance->IsValueType()))
  5677. continue; // This is just a placeholder for boxed types
  5678. bool doAlwaysInclude = false;
  5679. if (wantsOnDemandMethods)
  5680. {
  5681. bool implRequired = false;
  5682. bool declRequired = false;
  5683. if ((!typeInstance->IsGenericTypeInstance()) && (methodDef->mGenericParams.IsEmpty()))
  5684. {
  5685. // For non-generic methods, declare all methods. This is useful for debug info.
  5686. declRequired = true;
  5687. }
  5688. if (methodDef->mMethodType == BfMethodType_CtorNoBody)
  5689. declRequired = true;
  5690. if ((methodDef->mIsStatic) &&
  5691. ((methodDef->mMethodType == BfMethodType_Dtor) || (methodDef->mMethodType == BfMethodType_Ctor)))
  5692. {
  5693. implRequired = true;
  5694. }
  5695. if (mCompiler->mOptions.mEnableRealtimeLeakCheck)
  5696. {
  5697. if ((methodDef->mName == BF_METHODNAME_MARKMEMBERS_STATIC) ||
  5698. (methodDef->mName == BF_METHODNAME_FIND_TLS_MEMBERS) ||
  5699. ((methodDef->mName == BF_METHODNAME_MARKMEMBERS) && (typeInstance->IsObject())))
  5700. implRequired = true;
  5701. }
  5702. BfAttributeDirective* attributes = NULL;
  5703. if (auto methodDeclaration = methodDef->GetMethodDeclaration())
  5704. attributes = methodDeclaration->mAttributes;
  5705. if (auto propertyDeclaration = methodDef->GetPropertyDeclaration())
  5706. attributes = propertyDeclaration->mAttributes;
  5707. while (attributes != NULL)
  5708. {
  5709. if (attributes->mAttributeTypeRef != NULL)
  5710. {
  5711. auto typeRefName = attributes->mAttributeTypeRef->ToCleanAttributeString();
  5712. if (typeRefName == "AlwaysInclude")
  5713. implRequired = true;
  5714. else if (typeRefName == "Export")
  5715. implRequired = true;
  5716. else if (typeRefName == "Test")
  5717. implRequired = true;
  5718. else
  5719. declRequired = true; // We need to create so we can check for AlwaysInclude in included attributes
  5720. }
  5721. attributes = attributes->mNextAttribute;
  5722. }
  5723. if ((mProject != NULL) && (mProject->mAlwaysIncludeAll) && (methodDef->mBody != NULL))
  5724. {
  5725. implRequired = true;
  5726. declRequired = true;
  5727. }
  5728. if (typeInstance->IncludeAllMethods())
  5729. implRequired = true;
  5730. // "AssumeInstantiated" also forces default ctor
  5731. if (((typeInstance->mAlwaysIncludeFlags & BfAlwaysIncludeFlag_AssumeInstantiated) != 0) &&
  5732. (methodDef->IsDefaultCtor()))
  5733. implRequired = true;
  5734. if ((typeOptionsIncludeAll || typeOptionsIncludeFiltered) && (ApplyTypeOptionMethodFilters(typeOptionsIncludeAll, methodDef, typeOptions)))
  5735. implRequired = true;
  5736. // if ((typeOptions != NULL) && (CheckTypeOptionMethodFilters(typeOptions, methodDef)))
  5737. // implRequired = true;
  5738. if (typeInstance->IsInterface())
  5739. declRequired = true;
  5740. if (methodDef->mIsVirtual)
  5741. declRequired = true;
  5742. if (!implRequired)
  5743. {
  5744. // Any interface with the same name causes us to not be on-demand
  5745. if (ifaceMethodNameSet.Contains(methodDef->mName))
  5746. declRequired = true;
  5747. }
  5748. // Is this strictly necessary? It will reduce our compilation speed in order to ensure methods are available for debug info
  5749. if (allDeclsRequired)
  5750. declRequired = true;
  5751. if (methodDef->mMethodDeclaration == NULL)
  5752. {
  5753. // Internal methods don't need decls
  5754. if ((methodDef->mName == BF_METHODNAME_DEFAULT_EQUALS) ||
  5755. (methodDef->mName == BF_METHODNAME_DEFAULT_STRICT_EQUALS))
  5756. declRequired = false;
  5757. }
  5758. if (methodDef->mMethodType == BfMethodType_Init)
  5759. {
  5760. declRequired = false;
  5761. implRequired = false;
  5762. }
  5763. if (!implRequired)
  5764. {
  5765. if (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  5766. {
  5767. if (!mIsScratchModule)
  5768. mOnDemandMethodCount++;
  5769. }
  5770. if (!declRequired)
  5771. {
  5772. if (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  5773. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_NoDecl_AwaitingReference;
  5774. continue;
  5775. }
  5776. else
  5777. {
  5778. if (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  5779. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  5780. }
  5781. VerifyOnDemandMethods();
  5782. }
  5783. else
  5784. {
  5785. doAlwaysInclude = true;
  5786. }
  5787. }
  5788. else
  5789. doAlwaysInclude = true;
  5790. if (doAlwaysInclude)
  5791. {
  5792. bool wasDeclared = (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingDecl) ||
  5793. (methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference);
  5794. methodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  5795. if (wasDeclared)
  5796. {
  5797. if (!mIsScratchModule)
  5798. mOnDemandMethodCount--;
  5799. if ((methodInstanceGroup->mDefault != NULL) && (!methodInstanceGroup->mDefault->mMethodDef->mIsAbstract))
  5800. AddMethodToWorkList(methodInstanceGroup->mDefault);
  5801. }
  5802. }
  5803. }
  5804. BF_ASSERT_REL(typeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted);
  5805. BfLogSysM("Starting DoTypeInstanceMethodProcessing %p GetMethodInstance pass. OnDemandMethods: %d\n", typeInstance, mOnDemandMethodCount);
  5806. // Def passes. First non-overrides then overrides (for in-place overrides in methods)
  5807. for (int pass = 0; pass < 2; pass++)
  5808. {
  5809. for (auto methodDef : typeDef->mMethods)
  5810. {
  5811. if ((pass == 1) != (methodDef->mIsOverride))
  5812. continue;
  5813. bool doGetMethodInstance = true;
  5814. auto methodInstanceGroup = &typeInstance->mMethodInstanceGroups[methodDef->mIdx];
  5815. if ((methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude) &&
  5816. (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Decl_AwaitingDecl))
  5817. {
  5818. BfLogSysM("Skipping GetMethodInstance on MethodDef: %p OnDemandKind: %d\n", methodDef, methodInstanceGroup->mOnDemandKind);
  5819. doGetMethodInstance = false;
  5820. }
  5821. if (methodDef->mMethodType == BfMethodType_Init)
  5822. doGetMethodInstance = false;
  5823. BfMethodInstance* methodInstance = NULL;
  5824. if (doGetMethodInstance)
  5825. {
  5826. int prevWorklistSize = (int)mContext->mMethodWorkList.size();
  5827. auto flags = ((methodDef->mGenericParams.size() != 0) || (typeInstance->IsUnspecializedType())) ? BfGetMethodInstanceFlag_UnspecializedPass : BfGetMethodInstanceFlag_None;
  5828. if (methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude)
  5829. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  5830. auto moduleMethodInstance = GetMethodInstance(typeInstance, methodDef, BfTypeVector(), flags);
  5831. methodInstance = moduleMethodInstance.mMethodInstance;
  5832. if (methodInstance == NULL)
  5833. {
  5834. BF_ASSERT(typeInstance->IsGenericTypeInstance() && (typeInstance->mTypeDef->mIsCombinedPartial));
  5835. continue;
  5836. }
  5837. if ((!mCompiler->mIsResolveOnly) &&
  5838. ((methodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference) || (!typeInstance->IsReified())))
  5839. {
  5840. bool forceMethodImpl = false;
  5841. BfCustomAttributes* customAttributes = methodInstance->GetCustomAttributes();
  5842. if ((customAttributes != NULL) && (typeInstance->IsReified()))
  5843. {
  5844. for (auto& attr : customAttributes->mAttributes)
  5845. {
  5846. auto attrTypeInst = attr.mType->ToTypeInstance();
  5847. auto attrCustomAttributes = attrTypeInst->mCustomAttributes;
  5848. if (attrCustomAttributes == NULL)
  5849. continue;
  5850. for (auto& attrAttr : attrCustomAttributes->mAttributes)
  5851. {
  5852. if (attrAttr.mType->ToTypeInstance()->IsInstanceOf(mCompiler->mAttributeUsageAttributeTypeDef))
  5853. {
  5854. // Check for Flags arg
  5855. if (attrAttr.mCtorArgs.size() < 2)
  5856. continue;
  5857. auto constant = attrTypeInst->mConstHolder->GetConstant(attrAttr.mCtorArgs[1]);
  5858. if (constant == NULL)
  5859. continue;
  5860. if (constant->mTypeCode == BfTypeCode_Boolean)
  5861. continue;
  5862. if ((constant->mInt8 & BfCustomAttributeFlags_AlwaysIncludeTarget) != 0)
  5863. forceMethodImpl = true;
  5864. if (attrTypeInst->mAttributeData == NULL)
  5865. PopulateType(attrTypeInst);
  5866. BF_ASSERT(attrTypeInst->mAttributeData != NULL);
  5867. if (attrTypeInst->mAttributeData != NULL)
  5868. {
  5869. if ((attrTypeInst->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_IncludeAllMethods) != 0)
  5870. forceMethodImpl = true;
  5871. // "AssumeInstantiated" also forces default ctor
  5872. if (((attrTypeInst->mAttributeData->mAlwaysIncludeUser & BfAlwaysIncludeFlag_AssumeInstantiated) != 0) &&
  5873. (methodDef->mMethodType == BfMethodType_Ctor) && (methodDef->mParams.IsEmpty()))
  5874. forceMethodImpl = true;
  5875. }
  5876. }
  5877. }
  5878. }
  5879. }
  5880. if (methodInstance->mMethodDef->mDeclaringType->mProject->mTargetType == BfTargetType_BeefTest)
  5881. {
  5882. if ((customAttributes != NULL) && (customAttributes->Contains(mCompiler->mTestAttributeTypeDef)))
  5883. {
  5884. forceMethodImpl = true;
  5885. }
  5886. }
  5887. if (forceMethodImpl)
  5888. {
  5889. if (!typeInstance->IsReified())
  5890. mContext->mScratchModule->PopulateType(typeInstance, BfPopulateType_Data);
  5891. // Reify method
  5892. mContext->mScratchModule->GetMethodInstance(typeInstance, methodDef, BfTypeVector());
  5893. BF_ASSERT(methodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Decl_AwaitingReference);
  5894. }
  5895. }
  5896. }
  5897. else
  5898. {
  5899. methodInstance = methodInstanceGroup->mDefault;
  5900. if (methodInstance == NULL)
  5901. continue;
  5902. }
  5903. bool methodUsedVirtually = false;
  5904. if (typeInstance->IsInterface())
  5905. {
  5906. if ((!methodDef->mIsConcrete) && (!methodDef->mIsStatic) && (!methodInstance->HasSelf()))
  5907. SlotInterfaceMethod(methodInstance);
  5908. }
  5909. else if (!methodDef->IsEmptyPartial())
  5910. {
  5911. methodUsedVirtually = SlotVirtualMethod(methodInstance, &ambiguityContext);
  5912. }
  5913. // This is important for reducing latency of autocomplete popup, but it's important we don't allow the autocomplete
  5914. // thread to cause any reentry issues by re-populating a type at an "inopportune time". We do allow certain
  5915. // reentries in PopulateType, but not when we're resolving fields (for example)
  5916. if ((mContext->mFieldResolveReentrys.size() == 0) && (!mContext->mResolvingVarField))
  5917. {
  5918. disableYield.Release();
  5919. mContext->CheckLockYield();
  5920. disableYield.Acquire();
  5921. }
  5922. }
  5923. }
  5924. BF_ASSERT(typeInstance->mVirtualMethodTable.size() == typeInstance->mVirtualMethodTableSize);
  5925. if ((isBoxed) && (!typeInstance->IsUnspecializedTypeVariation()))
  5926. {
  5927. // Any interface method that can be called virtually via an interface pointer needs to go into the boxed type
  5928. auto underlyingType = typeInstance->GetUnderlyingType();
  5929. BfTypeInstance* underlyingTypeInstance;
  5930. if (underlyingType->IsPrimitiveType())
  5931. underlyingTypeInstance = GetPrimitiveStructType(((BfPrimitiveType*)underlyingType)->mTypeDef->mTypeCode);
  5932. else
  5933. underlyingTypeInstance = underlyingType->ToTypeInstance();
  5934. if (underlyingTypeInstance != NULL)
  5935. {
  5936. PopulateType(underlyingTypeInstance, BfPopulateType_Full_Force);
  5937. for (int ifaceIdx = 0; ifaceIdx < (int)underlyingTypeInstance->mInterfaces.size(); ifaceIdx++)
  5938. {
  5939. auto& underlyingIFaceTypeInst = underlyingTypeInstance->mInterfaces[ifaceIdx];
  5940. auto& boxedIFaceTypeInst = typeInstance->mInterfaces[ifaceIdx];
  5941. BF_ASSERT(underlyingIFaceTypeInst.mInterfaceType == boxedIFaceTypeInst.mInterfaceType);
  5942. auto ifaceInst = underlyingIFaceTypeInst.mInterfaceType;
  5943. int startIdx = underlyingIFaceTypeInst.mStartInterfaceTableIdx;
  5944. int boxedStartIdx = boxedIFaceTypeInst.mStartInterfaceTableIdx;
  5945. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  5946. for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  5947. {
  5948. auto matchedMethodRef = &underlyingTypeInstance->mInterfaceMethodTable[iMethodIdx + startIdx].mMethodRef;
  5949. auto boxedMatchedMethodRef = &typeInstance->mInterfaceMethodTable[iMethodIdx + boxedStartIdx].mMethodRef;
  5950. BfMethodInstance* matchedMethod = *matchedMethodRef;
  5951. auto ifaceMethodInst = ifaceInst->mMethodInstanceGroups[iMethodIdx].mDefault;
  5952. if (ifaceMethodInst->mVirtualTableIdx != -1)
  5953. {
  5954. if (matchedMethod == NULL)
  5955. {
  5956. // Assert on base type?
  5957. //AssertErrorState();
  5958. }
  5959. else
  5960. {
  5961. auto matchedMethodDef = matchedMethod->mMethodDef;
  5962. if (!matchedMethod->mIsForeignMethodDef)
  5963. {
  5964. BfMethodInstanceGroup* boxedMethodInstanceGroup = &typeInstance->mMethodInstanceGroups[matchedMethod->mMethodDef->mIdx];
  5965. if (boxedMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NoDecl_AwaitingReference)
  5966. {
  5967. boxedMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_Decl_AwaitingDecl;
  5968. VerifyOnDemandMethods();
  5969. }
  5970. }
  5971. auto methodFlags = matchedMethod->mIsForeignMethodDef ? BfGetMethodInstanceFlag_ForeignMethodDef : BfGetMethodInstanceFlag_None;
  5972. methodFlags = (BfGetMethodInstanceFlags)(methodFlags | BfGetMethodInstanceFlag_MethodInstanceOnly);
  5973. auto moduleMethodInstance = GetMethodInstance(typeInstance, matchedMethodDef, BfTypeVector(),
  5974. methodFlags,
  5975. matchedMethod->GetForeignType());
  5976. auto methodInstance = moduleMethodInstance.mMethodInstance;
  5977. UniqueSlotVirtualMethod(methodInstance);
  5978. *boxedMatchedMethodRef = methodInstance;
  5979. }
  5980. }
  5981. }
  5982. }
  5983. }
  5984. }
  5985. if (typeInstance->mHotTypeData != NULL)
  5986. {
  5987. auto latestVersion = typeInstance->mHotTypeData->GetLatestVersion();
  5988. auto latestVersionHead = typeInstance->mHotTypeData->GetLatestVersionHead();
  5989. if (typeInstance->mHotTypeData->mVTableOrigLength != -1)
  5990. {
  5991. bool hasSlotError = false;
  5992. BF_ASSERT(mCompiler->IsHotCompile());
  5993. //typeInstance->mHotTypeData->mDirty = true;
  5994. //Val128 vtHash;
  5995. Array<int> ifaceMapping;
  5996. ifaceMapping.Resize(latestVersionHead->mInterfaceMapping.size());
  5997. typeInstance->CalcHotVirtualData(&ifaceMapping);
  5998. // Hot swapping allows for interfaces to be added to types or removed from types, but it doesn't allow
  5999. // interfaces to be added when the slot number has already been used -- even if the interface using
  6000. // that slot has been removed.
  6001. for (int slotIdx = 0; slotIdx < (int)ifaceMapping.size(); slotIdx++)
  6002. {
  6003. int newId = ifaceMapping[slotIdx];
  6004. int oldId = 0;
  6005. if (slotIdx < (int)latestVersionHead->mInterfaceMapping.size())
  6006. oldId = latestVersionHead->mInterfaceMapping[slotIdx];
  6007. if ((newId != oldId) && (newId != 0) && (oldId != 0))
  6008. {
  6009. String interfaceName;
  6010. for (auto iface : typeInstance->mInterfaces)
  6011. {
  6012. if (iface.mInterfaceType->mTypeId == newId)
  6013. interfaceName = TypeToString(iface.mInterfaceType);
  6014. }
  6015. Warn(0, StrFormat("Hot swap detected resolvable interface slot collision with '%s'.", interfaceName.c_str()), typeDef->mTypeDeclaration);
  6016. BF_ASSERT(latestVersion != latestVersionHead);
  6017. if (!hasSlotError)
  6018. {
  6019. latestVersion->mInterfaceMapping = ifaceMapping;
  6020. }
  6021. hasSlotError = true;
  6022. }
  6023. else if (hasSlotError)
  6024. {
  6025. if (oldId != 0)
  6026. latestVersion->mInterfaceMapping[slotIdx] = oldId;
  6027. }
  6028. if (oldId != 0)
  6029. ifaceMapping[slotIdx] = oldId;
  6030. }
  6031. latestVersionHead->mInterfaceMapping = ifaceMapping;
  6032. if (hasSlotError)
  6033. mCompiler->mHotState->mPendingFailedSlottings.Add(typeInstance->mTypeId);
  6034. else
  6035. mCompiler->mHotState->mPendingFailedSlottings.Remove(typeInstance->mTypeId);
  6036. }
  6037. }
  6038. if ((typeInstance->IsInterface()) && (!typeInstance->IsUnspecializedType()) && (typeInstance->mIsReified) && (typeInstance->mSlotNum == -1) && (mCompiler->IsHotCompile()))
  6039. {
  6040. mCompiler->mHotState->mHasNewInterfaceTypes = true;
  6041. }
  6042. if ((!typeInstance->IsInterface()) && (!typeInstance->IsUnspecializedTypeVariation()) && (!isBoxed) && (!isFailedType))
  6043. {
  6044. if (!typeInstance->mTypeDef->mIsAbstract)
  6045. {
  6046. for (int methodIdx = 0; methodIdx < (int) typeInstance->mVirtualMethodTable.size(); methodIdx++)
  6047. {
  6048. auto& methodRef = typeInstance->mVirtualMethodTable[methodIdx].mImplementingMethod;
  6049. if (methodRef.mMethodNum == -1)
  6050. {
  6051. BF_ASSERT(mCompiler->mOptions.mHasVDataExtender);
  6052. if (methodRef.mTypeInstance == typeInstance)
  6053. {
  6054. if (typeInstance->GetImplBaseType() != NULL)
  6055. BF_ASSERT(methodIdx == (int)typeInstance->GetImplBaseType()->mVirtualMethodTableSize);
  6056. }
  6057. continue;
  6058. }
  6059. auto methodInstance = (BfMethodInstance*)methodRef;
  6060. if ((methodInstance != NULL) && (methodInstance->mMethodDef->mIsAbstract))
  6061. {
  6062. if (methodInstance->mMethodDef->mIsAbstract)
  6063. {
  6064. if (typeInstance->mVirtualMethodTable[methodIdx].mDeclaringMethod.mTypeInstance == typeInstance)
  6065. {
  6066. Fail("Method is abstract but it is declared in non-abstract class", methodInstance->mMethodDef->GetRefNode());
  6067. }
  6068. else if (!typeInstance->IsUnspecializedTypeVariation())
  6069. {
  6070. if (Fail(StrFormat("'%s' does not implement inherited abstract method '%s'", TypeToString(typeInstance).c_str(), MethodToString(methodInstance).c_str()), typeDef->mTypeDeclaration->mNameNode, true) != NULL)
  6071. mCompiler->mPassInstance->MoreInfo("Abstract method declared", methodInstance->mMethodDef->GetRefNode());
  6072. }
  6073. }
  6074. else
  6075. {
  6076. if (!typeInstance->IsUnspecializedType())
  6077. AssertErrorState();
  6078. }
  6079. }
  6080. }
  6081. }
  6082. std::unordered_set<String> missingIFaceMethodNames;
  6083. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  6084. {
  6085. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  6086. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  6087. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  6088. auto declTypeDef = ifaceTypeInst.mDeclaringType;
  6089. for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  6090. {
  6091. auto matchedMethodRef = &typeInstance->mInterfaceMethodTable[iMethodIdx + startIdx].mMethodRef;
  6092. BfMethodInstance* matchedMethod = *matchedMethodRef;
  6093. auto ifaceMethodInst = ifaceInst->mMethodInstanceGroups[iMethodIdx].mDefault;
  6094. if ((matchedMethod == NULL) && (ifaceMethodInst != NULL))
  6095. {
  6096. missingIFaceMethodNames.insert(ifaceMethodInst->mMethodDef->mName);
  6097. }
  6098. }
  6099. }
  6100. if (!missingIFaceMethodNames.empty())
  6101. {
  6102. // Attempt to find matching entries in base types
  6103. ambiguityContext.mIsReslotting = true;
  6104. auto checkType = typeInstance->GetImplBaseType();
  6105. while (checkType != NULL)
  6106. {
  6107. for (auto& methodGroup : checkType->mMethodInstanceGroups)
  6108. {
  6109. auto methodInstance = methodGroup.mDefault;
  6110. if (methodInstance != NULL)
  6111. {
  6112. if ((methodInstance->mMethodDef->mProtection != BfProtection_Private) &&
  6113. (!methodInstance->mMethodDef->mIsOverride) &&
  6114. (missingIFaceMethodNames.find(methodInstance->mMethodDef->mName) != missingIFaceMethodNames.end()))
  6115. {
  6116. SlotVirtualMethod(methodInstance, &ambiguityContext);
  6117. }
  6118. }
  6119. }
  6120. checkType = checkType->GetImplBaseType();
  6121. }
  6122. }
  6123. for (auto& ifaceTypeInst : typeInstance->mInterfaces)
  6124. {
  6125. auto ifaceInst = ifaceTypeInst.mInterfaceType;
  6126. int startIdx = ifaceTypeInst.mStartInterfaceTableIdx;
  6127. int iMethodCount = (int)ifaceInst->mMethodInstanceGroups.size();
  6128. auto declTypeDef = ifaceTypeInst.mDeclaringType;
  6129. for (int iMethodIdx = 0; iMethodIdx < iMethodCount; iMethodIdx++)
  6130. {
  6131. auto matchedMethodRef = &typeInstance->mInterfaceMethodTable[iMethodIdx + startIdx].mMethodRef;
  6132. BfMethodInstance* matchedMethod = *matchedMethodRef;
  6133. auto ifaceMethodInst = ifaceInst->mMethodInstanceGroups[iMethodIdx].mDefault;
  6134. if (ifaceMethodInst == NULL)
  6135. continue;
  6136. auto iReturnType = ifaceMethodInst->mReturnType;
  6137. if (iReturnType->IsUnspecializedTypeVariation())
  6138. {
  6139. BfType* resolvedType = ResolveGenericType(iReturnType, NULL, NULL, mCurTypeInstance);
  6140. if (resolvedType != NULL)
  6141. iReturnType = resolvedType;
  6142. else
  6143. iReturnType = typeInstance;
  6144. }
  6145. if (ifaceMethodInst->mMethodDef->mIsOverride)
  6146. continue; // Don't consider overrides here
  6147. // If we have "ProjA depends on LibBase", "ProjB depends on LibBase", then a type ClassC in LibBase implementing IFaceD,
  6148. // where IFaceD gets extended with MethodE in ProjA, an implementing MethodE is still required to exist on ClassC --
  6149. // the visibility is bidirectional. A type ClassF implementing IFaceD inside ProjB will not be required to implement
  6150. // MethodE, however
  6151. if ((!ifaceInst->IsTypeMemberAccessible(ifaceMethodInst->mMethodDef->mDeclaringType, ifaceTypeInst.mDeclaringType)) &&
  6152. (!ifaceInst->IsTypeMemberAccessible(ifaceTypeInst.mDeclaringType, ifaceMethodInst->mMethodDef->mDeclaringType)))
  6153. continue;
  6154. if (!ifaceInst->IsTypeMemberIncluded(ifaceMethodInst->mMethodDef->mDeclaringType, ifaceTypeInst.mDeclaringType))
  6155. continue;
  6156. bool hadMatch = matchedMethod != NULL;
  6157. bool hadPubFailure = false;
  6158. bool hadStaticFailure = false;
  6159. bool hadMutFailure = false;
  6160. if (hadMatch)
  6161. {
  6162. if ((matchedMethod->GetExplicitInterface() == NULL) && (matchedMethod->mMethodDef->mProtection != BfProtection_Public))
  6163. {
  6164. hadMatch = false;
  6165. hadPubFailure = true;
  6166. }
  6167. if (matchedMethod->mMethodDef->mIsStatic != ifaceMethodInst->mMethodDef->mIsStatic)
  6168. {
  6169. hadMatch = false;
  6170. hadStaticFailure = true;
  6171. }
  6172. if (ifaceMethodInst->mVirtualTableIdx != -1)
  6173. {
  6174. if (matchedMethod->mReturnType != iReturnType)
  6175. hadMatch = false;
  6176. }
  6177. else
  6178. {
  6179. // Concrete/generic
  6180. if (!CanCast(GetFakeTypedValue(matchedMethod->mReturnType), iReturnType))
  6181. hadMatch = false;
  6182. }
  6183. // If we have mExplicitInterface set then we already gave a mut error (if needed)
  6184. if ((typeInstance->IsValueType()) && (matchedMethod->GetExplicitInterface() == NULL) &&
  6185. (matchedMethod->mMethodDef->mIsMutating) && (!ifaceMethodInst->mMethodDef->mIsMutating))
  6186. {
  6187. hadMutFailure = true;
  6188. hadMatch = false;
  6189. }
  6190. }
  6191. if (!hadMatch)
  6192. {
  6193. if (!typeInstance->IsUnspecializedTypeVariation())
  6194. {
  6195. auto bestMethodInst = ifaceMethodInst;
  6196. auto bestInterface = ifaceInst;
  6197. if (matchedMethod == NULL)
  6198. {
  6199. bool searchFailed = false;
  6200. for (auto& checkIFaceTypeInst : typeInstance->mInterfaces)
  6201. {
  6202. auto checkIFaceInst = checkIFaceTypeInst.mInterfaceType;
  6203. int checkStartIdx = checkIFaceTypeInst.mStartInterfaceTableIdx;
  6204. int checkIMethodCount = (int)checkIFaceInst->mMethodInstanceGroups.size();
  6205. for (int checkIMethodIdx = 0; checkIMethodIdx < checkIMethodCount; checkIMethodIdx++)
  6206. {
  6207. auto checkIFaceMethodInst = checkIFaceInst->mMethodInstanceGroups[checkIMethodIdx].mDefault;
  6208. if ((checkIFaceMethodInst != NULL) && (checkIFaceMethodInst->mMethodDef->mIsOverride))
  6209. {
  6210. bool cmpResult = CompareMethodSignatures(checkIFaceMethodInst, ifaceMethodInst);
  6211. if (cmpResult)
  6212. {
  6213. bool isBetter = TypeIsSubTypeOf(checkIFaceInst, bestInterface);
  6214. bool isWorse = TypeIsSubTypeOf(bestInterface, checkIFaceInst);
  6215. if (isBetter == isWorse)
  6216. {
  6217. CompareDeclTypes(NULL, checkIFaceMethodInst->mMethodDef->mDeclaringType, bestMethodInst->mMethodDef->mDeclaringType, isBetter, isWorse);
  6218. }
  6219. if ((isBetter) && (!isWorse))
  6220. {
  6221. bestInterface = checkIFaceInst;
  6222. bestMethodInst = checkIFaceMethodInst;
  6223. }
  6224. else if (isBetter == isWorse)
  6225. {
  6226. if (!searchFailed)
  6227. {
  6228. searchFailed = true;
  6229. auto error = Fail(StrFormat("There is no most-specific default implementation of '%s'", MethodToString(ifaceMethodInst).c_str()), declTypeDef->mTypeDeclaration->mNameNode);
  6230. if (error != NULL)
  6231. {
  6232. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  6233. MethodToString(bestMethodInst).c_str()), bestMethodInst->mMethodDef->GetRefNode());
  6234. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate",
  6235. MethodToString(checkIFaceMethodInst).c_str()), checkIFaceMethodInst->mMethodDef->GetRefNode());
  6236. }
  6237. //candidate implementations include '%s' and '%s'",
  6238. //TypeToString(checkIFaceInst).c_str(), TypeToString(bestInterface).c_str()), );
  6239. }
  6240. }
  6241. }
  6242. }
  6243. }
  6244. }
  6245. if (bestMethodInst->mReturnType != ifaceMethodInst->mReturnType)
  6246. {
  6247. auto error = Fail(StrFormat("Default interface method '%s' cannot be used because it doesn't have the return type '%s'",
  6248. MethodToString(bestMethodInst).c_str(), TypeToString(ifaceMethodInst->mReturnType).c_str()), declTypeDef->mTypeDeclaration->mNameNode);
  6249. if (error != NULL)
  6250. {
  6251. mCompiler->mPassInstance->MoreInfo("See original method declaration", ifaceMethodInst->mMethodDef->GetRefNode());
  6252. mCompiler->mPassInstance->MoreInfo("See override method declaration", bestMethodInst->mMethodDef->GetRefNode());
  6253. }
  6254. }
  6255. }
  6256. bool hasDefaultImpl = bestMethodInst->mMethodDef->HasBody() || bestMethodInst->mMethodDef->mIsAbstract;
  6257. if ((hasDefaultImpl) && (matchedMethod == NULL))
  6258. {
  6259. auto methodDef = bestMethodInst->mMethodDef;
  6260. BfGetMethodInstanceFlags flags = (BfGetMethodInstanceFlags)(BfGetMethodInstanceFlag_ForeignMethodDef | BfGetMethodInstanceFlag_MethodInstanceOnly);
  6261. if ((methodDef->mGenericParams.size() != 0) || (typeInstance->IsUnspecializedType()))
  6262. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_UnspecializedPass);
  6263. auto methodInst = GetMethodInstance(typeInstance, methodDef, BfTypeVector(), flags, ifaceInst);
  6264. if (methodInst)
  6265. {
  6266. *matchedMethodRef = methodInst.mMethodInstance;
  6267. BfMethodInstance* newMethodInstance = methodInst.mMethodInstance;
  6268. BF_ASSERT(newMethodInstance->mIsForeignMethodDef);
  6269. if (newMethodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  6270. {
  6271. if (!mIsScratchModule)
  6272. mOnDemandMethodCount++;
  6273. }
  6274. continue;
  6275. }
  6276. }
  6277. if (typeInstance->IsBoxed())
  6278. {
  6279. if (ifaceMethodInst->mMethodDef->mIsStatic)
  6280. {
  6281. // Skip the statics, those can't be invoked
  6282. }
  6283. else
  6284. {
  6285. // The unboxed version should have had the same error
  6286. if (!typeInstance->GetUnderlyingType()->IsIncomplete())
  6287. AssertErrorState();
  6288. }
  6289. }
  6290. else if ((typeInstance->mRebuildFlags & BfTypeRebuildFlag_ConstEvalCancelled) != 0)
  6291. {
  6292. // It's possible const eval was supposed to generate this method. We're rebuilding the type anyway.
  6293. }
  6294. else
  6295. {
  6296. String ifaceMethodString;
  6297. ///
  6298. {
  6299. BfTypeState typeState;
  6300. typeState.mPrevState = mContext->mCurTypeState;
  6301. typeState.mForceActiveTypeDef = declTypeDef;
  6302. SetAndRestoreValue<BfTypeState*> prevTypeState(mContext->mCurTypeState, &typeState);
  6303. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, ifaceMethodInst);
  6304. ifaceMethodString = MethodToString(ifaceMethodInst, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType));
  6305. }
  6306. BfTypeDeclaration* typeDecl = declTypeDef->mTypeDeclaration;
  6307. BfError* error = Fail(StrFormat("'%s' does not implement interface member '%s'", TypeToString(typeInstance).c_str(), ifaceMethodString.c_str()), typeDecl->mNameNode, true);
  6308. if ((matchedMethod != NULL) && (error != NULL))
  6309. {
  6310. String matchedMethodString = MethodToString(matchedMethod, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType));
  6311. if (hadStaticFailure)
  6312. {
  6313. auto staticNodeRef = matchedMethod->mMethodDef->GetRefNode();
  6314. if (auto methodDecl = BfNodeDynCast<BfMethodDeclaration>(matchedMethod->mMethodDef->mMethodDeclaration))
  6315. if (methodDecl->mStaticSpecifier != NULL)
  6316. staticNodeRef = methodDecl->mStaticSpecifier;
  6317. if (matchedMethod->mMethodDef->mIsStatic)
  6318. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because it's static",
  6319. matchedMethodString.c_str()), staticNodeRef);
  6320. else
  6321. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because it's not static",
  6322. matchedMethodString.c_str()), staticNodeRef);
  6323. }
  6324. else if (hadPubFailure)
  6325. {
  6326. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because it's not public",
  6327. matchedMethodString.c_str()), matchedMethod->mMethodDef->mReturnTypeRef);
  6328. }
  6329. else if (ifaceMethodInst->mReturnType->IsConcreteInterfaceType())
  6330. {
  6331. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because it does not have a concrete return type that implements '%s'",
  6332. matchedMethodString.c_str(), TypeToString(ifaceMethodInst->mReturnType).c_str()), matchedMethod->mMethodDef->mReturnTypeRef);
  6333. }
  6334. else if (hadMutFailure)
  6335. {
  6336. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because it's market as 'mut' but interface method does not allow it",
  6337. matchedMethodString.c_str()), matchedMethod->mMethodDef->GetMutNode());
  6338. mCompiler->mPassInstance->MoreInfo(StrFormat("Declare the interface method as 'mut' to allow matching 'mut' implementations"), ifaceMethodInst->mMethodDef->mMethodDeclaration);
  6339. }
  6340. else
  6341. {
  6342. mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' cannot match because it does not have the return type '%s'",
  6343. matchedMethodString.c_str(), TypeToString(ifaceMethodInst->mReturnType).c_str()), matchedMethod->mMethodDef->mReturnTypeRef);
  6344. if ((ifaceMethodInst->mVirtualTableIdx != -1) && (ifaceMethodInst->mReturnType->IsInterface()))
  6345. mCompiler->mPassInstance->MoreInfo("Declare the interface method as 'concrete' to allow matching concrete return values", ifaceMethodInst->mMethodDef->GetMethodDeclaration()->mVirtualSpecifier);
  6346. }
  6347. }
  6348. }
  6349. }
  6350. // Clear out the entry
  6351. *matchedMethodRef = BfMethodRef();
  6352. }
  6353. }
  6354. }
  6355. }
  6356. VerifyOnDemandMethods();
  6357. ambiguityContext.Finish();
  6358. CheckAddFailType();
  6359. typeInstance->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  6360. mCompiler->mStats.mTypesPopulated++;
  6361. mCompiler->UpdateCompletion();
  6362. BF_ASSERT_REL(!typeInstance->mNeedsMethodProcessing);
  6363. BfLogSysM("Finished DoTypeInstanceMethodProcessing %p. OnDemandMethods: %d Virtual Size: %d InterfaceMethodTableSize: %d\n", typeInstance, mOnDemandMethodCount, typeInstance->mVirtualMethodTable.size(), typeInstance->mInterfaceMethodTable.size());
  6364. }
  6365. void BfModule::RebuildMethods(BfTypeInstance* typeInstance)
  6366. {
  6367. if (typeInstance->IsIncomplete())
  6368. return;
  6369. BfLogSysM("RebuildMethods setting mNeedsMethodProcessing=true on %p\n", typeInstance);
  6370. BF_ASSERT_REL(typeInstance->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotting);
  6371. typeInstance->mNeedsMethodProcessing = true;
  6372. typeInstance->mDefineState = BfTypeDefineState_Defined;
  6373. typeInstance->mTypeIncomplete = true;
  6374. for (auto& methodInstanceGroup : typeInstance->mMethodInstanceGroups)
  6375. {
  6376. delete methodInstanceGroup.mDefault;
  6377. methodInstanceGroup.mDefault = NULL;
  6378. delete methodInstanceGroup.mMethodSpecializationMap;
  6379. methodInstanceGroup.mMethodSpecializationMap = NULL;
  6380. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_NotSet;
  6381. }
  6382. BfTypeProcessRequest* typeProcessRequest = mContext->mPopulateTypeWorkList.Alloc();
  6383. typeProcessRequest->mType = typeInstance;
  6384. BF_ASSERT(typeInstance->mContext == mContext);
  6385. mCompiler->mStats.mTypesQueued++;
  6386. mCompiler->UpdateCompletion();
  6387. }
  6388. BfModule* BfModule::GetModuleFor(BfType* type)
  6389. {
  6390. auto typeInst = type->ToTypeInstance();
  6391. if (typeInst == NULL)
  6392. return NULL;
  6393. return typeInst->mModule;
  6394. }
  6395. void BfModule::AddMethodToWorkList(BfMethodInstance* methodInstance)
  6396. {
  6397. BF_ASSERT(!methodInstance->mMethodDef->mIsAbstract);
  6398. if (methodInstance->IsSpecializedByAutoCompleteMethod())
  6399. return;
  6400. BF_ASSERT(mCompiler->mCompileState != BfCompiler::CompileState_VData);
  6401. if ((methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized))
  6402. {
  6403. BF_ASSERT(mCompiler->mCompileState != BfCompiler::CompileState_Unreified);
  6404. }
  6405. if (methodInstance->IsOrInUnspecializedVariation())
  6406. {
  6407. return;
  6408. }
  6409. BF_ASSERT(!methodInstance->GetOwner()->IsUnspecializedTypeVariation());
  6410. BF_ASSERT(methodInstance->mMethodProcessRequest == NULL);
  6411. auto defaultMethod = methodInstance->mMethodInstanceGroup->mDefault;
  6412. if (defaultMethod != methodInstance)
  6413. {
  6414. BF_ASSERT(defaultMethod != NULL);
  6415. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_Decl_AwaitingReference)
  6416. {
  6417. if ((defaultMethod->mIsReified) && (!defaultMethod->mDeclModule->mIsModuleMutable))
  6418. {
  6419. defaultMethod->mDeclModule->PrepareForIRWriting(methodInstance->GetOwner());
  6420. }
  6421. AddMethodToWorkList(defaultMethod);
  6422. // This should put all the specialized methods in the worklist, including us
  6423. return;
  6424. }
  6425. }
  6426. if (methodInstance->mDeclModule != NULL)
  6427. {
  6428. if (methodInstance->mDeclModule != this)
  6429. {
  6430. methodInstance->mDeclModule->AddMethodToWorkList(methodInstance);
  6431. return;
  6432. }
  6433. }
  6434. else
  6435. {
  6436. auto module = GetOrCreateMethodModule(methodInstance);
  6437. methodInstance->mDeclModule = module;
  6438. BfIRValue func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  6439. methodInstance->mIRFunction = func;
  6440. module->mFuncReferences[methodInstance] = func;
  6441. module->AddMethodToWorkList(methodInstance);
  6442. return;
  6443. }
  6444. if ((!methodInstance->mIRFunction) && (methodInstance->mIsReified) && (!methodInstance->mIsUnspecialized) &&
  6445. (methodInstance->GetImportCallKind() == BfImportCallKind_None))
  6446. {
  6447. if (!mIsModuleMutable)
  6448. PrepareForIRWriting(methodInstance->GetOwner());
  6449. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, mWantsIRIgnoreWrites);
  6450. BfIRValue func = CreateFunctionFrom(methodInstance, false, methodInstance->mAlwaysInline);
  6451. if (func)
  6452. {
  6453. methodInstance->mIRFunction = func;
  6454. mFuncReferences[methodInstance] = func;
  6455. }
  6456. }
  6457. BF_ASSERT(methodInstance->mDeclModule == this);
  6458. if (defaultMethod == methodInstance)
  6459. {
  6460. if (methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_AlwaysInclude)
  6461. {
  6462. auto owningModule = methodInstance->GetOwner()->GetModule();
  6463. BF_ASSERT(methodInstance->mMethodInstanceGroup->mOnDemandKind != BfMethodOnDemandKind_Referenced);
  6464. if (!mIsScratchModule)
  6465. {
  6466. auto onDemandModule = owningModule;
  6467. if (owningModule->mParentModule != NULL)
  6468. onDemandModule = owningModule->mParentModule;
  6469. owningModule->VerifyOnDemandMethods();
  6470. if (methodInstance->mMethodInstanceGroup->mOnDemandKind == BfMethodOnDemandKind_NotSet)
  6471. owningModule->mOnDemandMethodCount++;
  6472. BF_ASSERT(onDemandModule->mOnDemandMethodCount > 0);
  6473. VerifyOnDemandMethods();
  6474. }
  6475. methodInstance->mMethodInstanceGroup->mOnDemandKind = BfMethodOnDemandKind_InWorkList;
  6476. if (methodInstance->mMethodInstanceGroup->mMethodSpecializationMap != NULL)
  6477. {
  6478. for (auto& kv : *methodInstance->mMethodInstanceGroup->mMethodSpecializationMap)
  6479. {
  6480. auto specMethodInstance = kv.mValue;
  6481. if ((!specMethodInstance->mDeclModule->mIsModuleMutable) && (!specMethodInstance->mDeclModule->mReifyQueued))
  6482. {
  6483. specMethodInstance->mDeclModule->PrepareForIRWriting(specMethodInstance->GetOwner());
  6484. }
  6485. specMethodInstance->mDeclModule->AddMethodToWorkList(specMethodInstance);
  6486. }
  6487. }
  6488. }
  6489. }
  6490. else
  6491. {
  6492. BF_ASSERT(defaultMethod->mMethodInstanceGroup->IsImplemented());
  6493. }
  6494. BF_ASSERT(methodInstance->mDeclModule != NULL);
  6495. auto typeInstance = methodInstance->GetOwner();
  6496. BfMethodProcessRequest* methodProcessRequest = mContext->mMethodWorkList.Alloc();
  6497. if (mCompiler->mCompileState == BfCompiler::CompileState_Unreified)
  6498. {
  6499. if (methodInstance->mIsReified)
  6500. {
  6501. BfLogSysM("Marking method %d as unreified due to CompileState_Unreified\n", methodInstance);
  6502. methodInstance->mIsReified = false;
  6503. }
  6504. }
  6505. //BF_ASSERT(!methodInstance->mIsReified);
  6506. methodProcessRequest->mType = typeInstance;
  6507. methodProcessRequest->mMethodInstance = methodInstance;
  6508. methodProcessRequest->mRevision = typeInstance->mRevision;
  6509. methodProcessRequest->mFromModuleRebuildIdx = mRebuildIdx;
  6510. methodProcessRequest->mFromModule = this;
  6511. if ((!mCompiler->mIsResolveOnly) && (methodInstance->mIsReified))
  6512. {
  6513. if ((!mIsModuleMutable) && (!mIsScratchModule))
  6514. {
  6515. BF_ASSERT(!mGeneratesCode);
  6516. StartNewRevision(BfModule::RebuildKind_None);
  6517. }
  6518. BF_ASSERT(mIsModuleMutable || mReifyQueued);
  6519. }
  6520. BF_ASSERT((mBfIRBuilder != NULL) || (!methodInstance->mIsReified));
  6521. 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);
  6522. if (mAwaitingFinish)
  6523. {
  6524. BfLogSysM("Module: %p No longer awaiting finish\n", this);
  6525. mAwaitingFinish = false;
  6526. }
  6527. mCompiler->mStats.mMethodsQueued++;
  6528. mCompiler->UpdateCompletion();
  6529. mIncompleteMethodCount++;
  6530. if (methodInstance->GetNumGenericArguments() != 0)
  6531. mHasGenericMethods = true;
  6532. methodInstance->mMethodProcessRequest = methodProcessRequest;
  6533. }
  6534. BfArrayType* BfModule::CreateArrayType(BfType* resolvedType, int dimensions)
  6535. {
  6536. BF_ASSERT(!resolvedType->IsVar());
  6537. BF_ASSERT(!resolvedType->IsIntUnknown());
  6538. auto arrayTypeDef = mCompiler->GetArrayTypeDef(dimensions);
  6539. if (arrayTypeDef == NULL)
  6540. return NULL;
  6541. auto arrayType = mContext->mArrayTypePool.Get();
  6542. delete arrayType->mGenericTypeInfo;
  6543. arrayType->mGenericTypeInfo = new BfGenericTypeInfo();
  6544. arrayType->mContext = mContext;
  6545. arrayType->mTypeDef = arrayTypeDef;
  6546. arrayType->mDimensions = dimensions;
  6547. arrayType->mGenericTypeInfo->mTypeGenericArguments.clear();
  6548. arrayType->mGenericTypeInfo->mTypeGenericArguments.push_back(resolvedType);
  6549. auto resolvedArrayType = ResolveType(arrayType);
  6550. if (resolvedArrayType != arrayType)
  6551. {
  6552. arrayType->Dispose();
  6553. mContext->mArrayTypePool.GiveBack(arrayType);
  6554. }
  6555. return (BfArrayType*)resolvedArrayType;
  6556. }
  6557. BfSizedArrayType* BfModule::CreateSizedArrayType(BfType * resolvedType, int size)
  6558. {
  6559. BF_ASSERT(!resolvedType->IsVar());
  6560. auto arrayType = mContext->mSizedArrayTypePool.Get();
  6561. arrayType->mContext = mContext;
  6562. arrayType->mElementType = resolvedType;
  6563. arrayType->mElementCount = size;
  6564. auto resolvedArrayType = ResolveType(arrayType);
  6565. if (resolvedArrayType != arrayType)
  6566. mContext->mSizedArrayTypePool.GiveBack(arrayType);
  6567. return (BfSizedArrayType*)resolvedArrayType;
  6568. }
  6569. BfUnknownSizedArrayType* BfModule::CreateUnknownSizedArrayType(BfType* resolvedType, BfType* sizeParam)
  6570. {
  6571. BF_ASSERT(!resolvedType->IsVar());
  6572. BF_ASSERT(sizeParam->IsGenericParam());
  6573. auto arrayType = mContext->mUnknownSizedArrayTypePool.Get();
  6574. arrayType->mContext = mContext;
  6575. arrayType->mElementType = resolvedType;
  6576. arrayType->mElementCount = -1;
  6577. arrayType->mElementCountSource = sizeParam;
  6578. auto resolvedArrayType = ResolveType(arrayType);
  6579. if (resolvedArrayType != arrayType)
  6580. mContext->mUnknownSizedArrayTypePool.GiveBack(arrayType);
  6581. return (BfUnknownSizedArrayType*)resolvedArrayType;
  6582. }
  6583. BfPointerType* BfModule::CreatePointerType(BfType* resolvedType)
  6584. {
  6585. BF_ASSERT(!resolvedType->IsVar());
  6586. BF_ASSERT_REL(!resolvedType->IsDeleting());
  6587. auto pointerType = mContext->mPointerTypePool.Get();
  6588. pointerType->mContext = mContext;
  6589. pointerType->mElementType = resolvedType;
  6590. auto resolvedPointerType = (BfPointerType*)ResolveType(pointerType);
  6591. if (resolvedPointerType != pointerType)
  6592. mContext->mPointerTypePool.GiveBack(pointerType);
  6593. BF_ASSERT(resolvedPointerType->mElementType == resolvedType);
  6594. return resolvedPointerType;
  6595. }
  6596. BfConstExprValueType* BfModule::CreateConstExprValueType(const BfTypedValue& typedValue, bool allowCreate)
  6597. {
  6598. BfPopulateType populateType = allowCreate ? BfPopulateType_Data : BfPopulateType_Identity;
  6599. BfResolveTypeRefFlags resolveFlags = allowCreate ? BfResolveTypeRefFlag_None : BfResolveTypeRefFlag_NoCreate;
  6600. auto variant = TypedValueToVariant(NULL, typedValue);
  6601. if (variant.mTypeCode == BfTypeCode_None)
  6602. {
  6603. if (auto constant = mBfIRBuilder->GetConstant(typedValue.mValue))
  6604. {
  6605. if (constant->mConstType == BfConstType_Undef)
  6606. {
  6607. variant.mTypeCode = BfTypeCode_Let;
  6608. }
  6609. }
  6610. }
  6611. if (variant.mTypeCode == BfTypeCode_None)
  6612. return NULL;
  6613. auto constExprValueType = mContext->mConstExprValueTypePool.Get();
  6614. constExprValueType->mContext = mContext;
  6615. constExprValueType->mType = typedValue.mType;
  6616. constExprValueType->mValue = variant;
  6617. auto resolvedConstExprValueType = (BfConstExprValueType*)ResolveType(constExprValueType, populateType, resolveFlags);
  6618. if (resolvedConstExprValueType != constExprValueType)
  6619. mContext->mConstExprValueTypePool.GiveBack(constExprValueType);
  6620. if (resolvedConstExprValueType != NULL)
  6621. BF_ASSERT(resolvedConstExprValueType->mValue == constExprValueType->mValue);
  6622. return resolvedConstExprValueType;
  6623. }
  6624. BfConstExprValueType* BfModule::CreateConstExprValueType(const BfVariant& variant, BfType* type, bool allowCreate)
  6625. {
  6626. BfPopulateType populateType = allowCreate ? BfPopulateType_Data : BfPopulateType_Identity;
  6627. BfResolveTypeRefFlags resolveFlags = allowCreate ? BfResolveTypeRefFlag_None : BfResolveTypeRefFlag_NoCreate;
  6628. if (variant.mTypeCode == BfTypeCode_None)
  6629. return NULL;
  6630. auto constExprValueType = mContext->mConstExprValueTypePool.Get();
  6631. constExprValueType->mContext = mContext;
  6632. constExprValueType->mType = type;
  6633. constExprValueType->mValue = variant;
  6634. auto resolvedConstExprValueType = (BfConstExprValueType*)ResolveType(constExprValueType, populateType, resolveFlags);
  6635. if (resolvedConstExprValueType != constExprValueType)
  6636. mContext->mConstExprValueTypePool.GiveBack(constExprValueType);
  6637. if (resolvedConstExprValueType != NULL)
  6638. BF_ASSERT(resolvedConstExprValueType->mValue == constExprValueType->mValue);
  6639. return resolvedConstExprValueType;
  6640. }
  6641. BfTypeInstance* BfModule::GetWrappedStructType(BfType* type, bool allowSpecialized)
  6642. {
  6643. if (type->IsPointer())
  6644. {
  6645. if (allowSpecialized)
  6646. {
  6647. BfPointerType* pointerType = (BfPointerType*)type;
  6648. BfTypeVector typeVector;
  6649. typeVector.Add(pointerType->mElementType);
  6650. return ResolveTypeDef(mCompiler->mPointerTTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  6651. }
  6652. else
  6653. return ResolveTypeDef(mCompiler->mPointerTTypeDef, BfPopulateType_Data)->ToTypeInstance();
  6654. }
  6655. else if (type->IsMethodRef())
  6656. {
  6657. if (allowSpecialized)
  6658. {
  6659. BfMethodRefType* methodRefType = (BfMethodRefType*)type;
  6660. BfTypeVector typeVector;
  6661. typeVector.Add(methodRefType);
  6662. return ResolveTypeDef(mCompiler->mMethodRefTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  6663. }
  6664. else
  6665. return ResolveTypeDef(mCompiler->mMethodRefTypeDef, BfPopulateType_Data)->ToTypeInstance();
  6666. }
  6667. else if (type->IsSizedArray())
  6668. {
  6669. if (allowSpecialized)
  6670. {
  6671. if (type->IsUnknownSizedArrayType())
  6672. {
  6673. BfUnknownSizedArrayType* sizedArrayType = (BfUnknownSizedArrayType*)type;
  6674. BfTypeVector typeVector;
  6675. typeVector.Add(sizedArrayType->mElementType);
  6676. typeVector.Add(sizedArrayType->mElementCountSource);
  6677. return ResolveTypeDef(mCompiler->mSizedArrayTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  6678. }
  6679. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)type;
  6680. BfTypeVector typeVector;
  6681. typeVector.Add(sizedArrayType->mElementType);
  6682. auto sizeValue = BfTypedValue(GetConstValue(BF_MAX(sizedArrayType->mElementCount, 0)), GetPrimitiveType(BfTypeCode_IntPtr));
  6683. typeVector.Add(CreateConstExprValueType(sizeValue));
  6684. return ResolveTypeDef(mCompiler->mSizedArrayTypeDef, typeVector, BfPopulateType_Data)->ToTypeInstance();
  6685. }
  6686. else
  6687. return ResolveTypeDef(mCompiler->mSizedArrayTypeDef, BfPopulateType_Data)->ToTypeInstance();
  6688. }
  6689. BF_ASSERT(type->IsPrimitiveType());
  6690. return GetPrimitiveStructType(((BfPrimitiveType*)type)->mTypeDef->mTypeCode);
  6691. }
  6692. BfPrimitiveType* BfModule::GetPrimitiveType(BfTypeCode typeCode)
  6693. {
  6694. BfPrimitiveType* primType = mContext->mPrimitiveTypes[typeCode];
  6695. if (primType == NULL)
  6696. {
  6697. switch (typeCode)
  6698. {
  6699. case BfTypeCode_NullPtr:
  6700. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeNullPtr);
  6701. break;
  6702. case BfTypeCode_Self:
  6703. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeSelf);
  6704. break;
  6705. case BfTypeCode_Dot:
  6706. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeDot);
  6707. break;
  6708. case BfTypeCode_Var:
  6709. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeVar);
  6710. break;
  6711. case BfTypeCode_Let:
  6712. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeLet);
  6713. break;
  6714. case BfTypeCode_None:
  6715. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeVoid);
  6716. break;
  6717. case BfTypeCode_Boolean:
  6718. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeBool);
  6719. break;
  6720. case BfTypeCode_Int8:
  6721. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeInt8);
  6722. break;
  6723. case BfTypeCode_UInt8:
  6724. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUInt8);
  6725. break;
  6726. case BfTypeCode_Int16:
  6727. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeInt16);
  6728. break;
  6729. case BfTypeCode_UInt16:
  6730. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUInt16);
  6731. break;
  6732. case BfTypeCode_Int32:
  6733. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeInt32);
  6734. break;
  6735. case BfTypeCode_UInt32:
  6736. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUInt32);
  6737. break;
  6738. case BfTypeCode_Int64:
  6739. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeInt64);
  6740. break;
  6741. case BfTypeCode_UInt64:
  6742. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUInt64);
  6743. break;
  6744. case BfTypeCode_Char8:
  6745. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeChar8);
  6746. break;
  6747. case BfTypeCode_Char16:
  6748. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeChar16);
  6749. break;
  6750. case BfTypeCode_Char32:
  6751. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeChar32);
  6752. break;
  6753. case BfTypeCode_Float:
  6754. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeSingle);
  6755. break;
  6756. case BfTypeCode_Double:
  6757. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeDouble);
  6758. break;
  6759. case BfTypeCode_IntPtr:
  6760. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeIntPtr);
  6761. break;
  6762. case BfTypeCode_UIntPtr:
  6763. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUIntPtr);
  6764. break;
  6765. case BfTypeCode_IntUnknown:
  6766. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeIntUnknown);
  6767. break;
  6768. case BfTypeCode_UIntUnknown:
  6769. primType = (BfPrimitiveType*)ResolveTypeDef(mSystem->mTypeUIntUnknown);
  6770. break;
  6771. case BfTypeCode_StringId:
  6772. BFMODULE_FATAL(this, "Invalid use of StringId");
  6773. break;
  6774. default:
  6775. BF_DBG_FATAL("Invalid type");
  6776. break;
  6777. }
  6778. mContext->mPrimitiveTypes[typeCode] = primType;
  6779. }
  6780. return primType;
  6781. }
  6782. BfIRType BfModule::GetIRLoweredType(BfTypeCode loweredTypeCode, BfTypeCode loweredTypeCode2)
  6783. {
  6784. BF_ASSERT(!mIsComptimeModule);
  6785. BF_ASSERT(loweredTypeCode != BfTypeCode_None);
  6786. if (loweredTypeCode2 == BfTypeCode_None)
  6787. return mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  6788. SizedArray<BfIRType, 2> types;
  6789. types.push_back(mBfIRBuilder->GetPrimitiveType(loweredTypeCode));
  6790. types.push_back(mBfIRBuilder->GetPrimitiveType(loweredTypeCode2));
  6791. return mBfIRBuilder->CreateStructType(types);
  6792. }
  6793. BfMethodRefType* BfModule::CreateMethodRefType(BfMethodInstance* methodInstance, bool mustAlreadyExist)
  6794. {
  6795. // Make sure we don't have a partially-formed local method or lambda coming in, because those may be replaced
  6796. // after the capture phase
  6797. BF_ASSERT(!methodInstance->mDisallowCalling);
  6798. auto methodRefType = new BfMethodRefType();
  6799. methodRefType->mContext = mContext;
  6800. //methodRefType->mCaptureType = NULL;
  6801. methodRefType->mMethodRef = methodInstance;
  6802. methodRefType->mOwner = methodInstance->GetOwner();
  6803. methodRefType->mOwnerRevision = methodRefType->mOwner->mRevision;
  6804. //methodRefType->mMangledName = BfMangler::Mangle(mCompiler->GetMangleKind(), methodInstance);
  6805. methodRefType->mIsAutoCompleteMethod = methodInstance->mIsAutocompleteMethod;
  6806. methodRefType->mIsUnspecialized = methodInstance->mIsUnspecialized;
  6807. methodRefType->mIsUnspecializedVariation = methodInstance->mIsUnspecializedVariation;
  6808. methodRefType->mSize = 0;
  6809. BfResolvedTypeSet::LookupContext lookupCtx;
  6810. lookupCtx.mModule = this;
  6811. BfResolvedTypeSet::EntryRef typeEntry;
  6812. auto inserted = mContext->mResolvedTypes.Insert(methodRefType, &lookupCtx, &typeEntry);
  6813. if (typeEntry->mValue == NULL)
  6814. {
  6815. BF_ASSERT(!mustAlreadyExist);
  6816. BF_ASSERT(!methodInstance->mHasMethodRefType);
  6817. InitType(methodRefType, BfPopulateType_Identity);
  6818. methodRefType->mDefineState = BfTypeDefineState_DefinedAndMethodsSlotted;
  6819. methodInstance->mHasMethodRefType = true;
  6820. methodInstance->mMethodInstanceGroup->mRefCount++;
  6821. typeEntry->mValue = methodRefType;
  6822. BfLogSysM("Create MethodRefType %p MethodInstance: %p\n", methodRefType, methodInstance);
  6823. methodRefType->mRevision = 0;
  6824. AddDependency(methodInstance->GetOwner(), methodRefType, BfDependencyMap::DependencyFlag_Calls);
  6825. BfTypeVector tupleTypes;
  6826. Array<String> tupleNames;
  6827. int offset = 0;
  6828. methodRefType->mAlign = 1;
  6829. int dataIdx = 0;
  6830. // CRepr, just because we're lazy (for now)
  6831. int implicitParamCount = methodInstance->GetImplicitParamCount();
  6832. for (int implicitParamIdx = methodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  6833. {
  6834. auto paramType = methodInstance->GetParamType(implicitParamIdx);
  6835. if (!paramType->IsValuelessType())
  6836. {
  6837. methodRefType->mDataToParamIdx.Add(implicitParamIdx);
  6838. if (implicitParamIdx >= 0)
  6839. methodRefType->mParamToDataIdx.Add(dataIdx);
  6840. offset = BF_ALIGN(offset, paramType->mAlign);
  6841. offset += paramType->mSize;
  6842. methodRefType->mAlign = std::max(methodRefType->mAlign, paramType->mAlign);
  6843. dataIdx++;
  6844. }
  6845. else
  6846. {
  6847. methodRefType->mParamToDataIdx.Add(-1);
  6848. }
  6849. }
  6850. offset = BF_ALIGN(offset, methodRefType->mAlign);
  6851. methodRefType->mSize = offset;
  6852. // if (!tupleTypes.empty())
  6853. // {
  6854. // methodRefType->mCaptureType = CreateTupleType(tupleTypes, tupleNames);
  6855. // AddDependency(methodRefType->mCaptureType, methodRefType, BfDependencyMap::DependencyFlag_ReadFields);
  6856. //
  6857. // methodRefType->mSize = methodRefType->mCaptureType->mSize;
  6858. // methodRefType->mAlign = methodRefType->mCaptureType->mAlign;
  6859. // }
  6860. // else
  6861. // {
  6862. // methodRefType->mSize = 0;
  6863. // methodRefType->mAlign = 0;
  6864. // }
  6865. }
  6866. else
  6867. {
  6868. methodRefType->mMethodRef = NULL;
  6869. delete methodRefType;
  6870. methodRefType = (BfMethodRefType*)typeEntry->mValue;
  6871. }
  6872. return methodRefType;
  6873. }
  6874. BfType* BfModule::FixIntUnknown(BfType* type)
  6875. {
  6876. if ((type != NULL) && (type->IsPrimitiveType()))
  6877. {
  6878. auto primType = (BfPrimitiveType*)type;
  6879. if (primType->mTypeDef->mTypeCode == BfTypeCode_IntUnknown)
  6880. return GetPrimitiveType(BfTypeCode_IntPtr);
  6881. if (primType->mTypeDef->mTypeCode == BfTypeCode_UIntUnknown)
  6882. return GetPrimitiveType(BfTypeCode_UIntPtr);
  6883. }
  6884. return type;
  6885. }
  6886. void BfModule::FixIntUnknown(BfTypedValue& typedVal, BfType* matchType)
  6887. {
  6888. if (!typedVal.mValue.IsConst())
  6889. {
  6890. if ((typedVal.mType != NULL) && (typedVal.mType->IsPrimitiveType()))
  6891. {
  6892. auto primType = (BfPrimitiveType*)typedVal.mType;
  6893. BF_ASSERT((primType->mTypeDef->mTypeCode != BfTypeCode_IntUnknown) && (primType->mTypeDef->mTypeCode != BfTypeCode_UIntUnknown));
  6894. }
  6895. return;
  6896. }
  6897. if (!typedVal.mType->IsPrimitiveType())
  6898. return;
  6899. BfTypeCode wantTypeCode;
  6900. auto primType = (BfPrimitiveType*)typedVal.mType;
  6901. if (primType->mTypeDef->mTypeCode == BfTypeCode_IntUnknown)
  6902. wantTypeCode = BfTypeCode_IntPtr;
  6903. else if (primType->mTypeDef->mTypeCode == BfTypeCode_UIntUnknown)
  6904. wantTypeCode = BfTypeCode_UIntPtr;
  6905. else
  6906. return;
  6907. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  6908. if ((matchType != NULL) && (matchType->IsPrimitiveType()) && (mBfIRBuilder->IsInt(matchType->ToPrimitiveType()->mTypeDef->mTypeCode)))
  6909. {
  6910. auto wantTypeCode = matchType->ToPrimitiveType()->mTypeDef->mTypeCode;
  6911. if (matchType->mSize < 8)
  6912. {
  6913. int64 minVal = -(1LL << (8 * matchType->mSize - 1));
  6914. int64 maxVal = (1LL << (8 * matchType->mSize - 1)) - 1;
  6915. if ((constant->mInt64 >= minVal) && (constant->mInt64 <= maxVal))
  6916. {
  6917. typedVal.mValue = mBfIRBuilder->CreateNumericCast(typedVal.mValue, mBfIRBuilder->IsSigned(wantTypeCode), wantTypeCode);
  6918. typedVal.mType = GetPrimitiveType(wantTypeCode);
  6919. return;
  6920. }
  6921. }
  6922. }
  6923. if (mSystem->mPtrSize == 4)
  6924. {
  6925. if (primType->mTypeDef->mTypeCode == BfTypeCode_IntUnknown)
  6926. {
  6927. if ((constant->mInt64 >= -0x80000000LL) && (constant->mInt64 <= 0x7FFFFFFFLL))
  6928. {
  6929. typedVal.mValue = mBfIRBuilder->CreateNumericCast(typedVal.mValue, true, BfTypeCode_IntPtr);
  6930. typedVal.mType = GetPrimitiveType(BfTypeCode_IntPtr);
  6931. }
  6932. else
  6933. typedVal.mType = GetPrimitiveType(BfTypeCode_Int64);
  6934. return;
  6935. }
  6936. else
  6937. {
  6938. if ((constant->mInt64 >= 0) && (constant->mInt64 <= 0xFFFFFFFF))
  6939. {
  6940. typedVal.mValue = mBfIRBuilder->CreateNumericCast(typedVal.mValue, false, BfTypeCode_IntPtr);
  6941. typedVal.mType = GetPrimitiveType(BfTypeCode_UIntPtr);
  6942. }
  6943. else
  6944. typedVal.mType = GetPrimitiveType(BfTypeCode_UInt64);
  6945. return;
  6946. }
  6947. }
  6948. typedVal.mType = GetPrimitiveType(wantTypeCode);
  6949. }
  6950. void BfModule::FixIntUnknown(BfTypedValue& lhs, BfTypedValue& rhs)
  6951. {
  6952. if ((lhs.mType != NULL) && (lhs.mType->IsIntUnknown()) && (rhs.mType != NULL) &&
  6953. (rhs.mType->IsInteger()) && (!rhs.mType->IsIntUnknown()))
  6954. {
  6955. if (CanCast(lhs, rhs.mType))
  6956. {
  6957. lhs = Cast(NULL, lhs, rhs.mType, BfCastFlags_SilentFail);
  6958. if (!lhs)
  6959. lhs = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  6960. return;
  6961. }
  6962. }
  6963. if ((rhs.mType != NULL) && (rhs.mType->IsIntUnknown()) && (lhs.mType != NULL) &&
  6964. (lhs.mType->IsInteger()) && (!lhs.mType->IsIntUnknown()))
  6965. {
  6966. if (CanCast(rhs, lhs.mType))
  6967. {
  6968. rhs = Cast(NULL, rhs, lhs.mType, BfCastFlags_SilentFail);
  6969. if (!rhs)
  6970. rhs = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_IntPtr));
  6971. return;
  6972. }
  6973. }
  6974. FixIntUnknown(lhs);
  6975. FixIntUnknown(rhs);
  6976. }
  6977. void BfModule::FixValueActualization(BfTypedValue& typedVal, bool force)
  6978. {
  6979. if (!typedVal.mValue.IsConst())
  6980. return;
  6981. if ((mBfIRBuilder->mIgnoreWrites) && (!force))
  6982. return;
  6983. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  6984. if (!HasUnactializedConstant(constant, mBfIRBuilder))
  6985. return;
  6986. typedVal.mValue = ConstantToCurrent(constant, mBfIRBuilder, typedVal.mType, false);
  6987. }
  6988. BfTypeInstance* BfModule::GetPrimitiveStructType(BfTypeCode typeCode)
  6989. {
  6990. BfTypeInstance* typeInst = NULL;
  6991. switch (typeCode)
  6992. {
  6993. case BfTypeCode_None:
  6994. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Void"), BfPopulateType_Identity)->ToTypeInstance(); break;
  6995. case BfTypeCode_Boolean:
  6996. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Boolean"), BfPopulateType_Identity)->ToTypeInstance(); break;
  6997. case BfTypeCode_Int8:
  6998. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int8"), BfPopulateType_Identity)->ToTypeInstance(); break;
  6999. case BfTypeCode_UInt8:
  7000. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt8"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7001. case BfTypeCode_Int16:
  7002. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int16"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7003. case BfTypeCode_UInt16:
  7004. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt16"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7005. case BfTypeCode_Int32:
  7006. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int32"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7007. case BfTypeCode_UInt32:
  7008. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt32"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7009. case BfTypeCode_Int64:
  7010. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int64"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7011. case BfTypeCode_UInt64:
  7012. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt64"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7013. case BfTypeCode_IntPtr:
  7014. case BfTypeCode_IntUnknown:
  7015. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Int"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7016. case BfTypeCode_UIntPtr:
  7017. case BfTypeCode_UIntUnknown:
  7018. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.UInt"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7019. case BfTypeCode_Char8:
  7020. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Char8"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7021. case BfTypeCode_Char16:
  7022. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Char16"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7023. case BfTypeCode_Char32:
  7024. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Char32"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7025. case BfTypeCode_Float:
  7026. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Float"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7027. case BfTypeCode_Double:
  7028. typeInst = ResolveTypeDef(mSystem->FindTypeDef("System.Double"), BfPopulateType_Identity)->ToTypeInstance(); break;
  7029. default:
  7030. //BF_FATAL("not implemented");
  7031. break;
  7032. }
  7033. return typeInst;
  7034. }
  7035. BfBoxedType* BfModule::CreateBoxedType(BfType* resolvedTypeRef, bool allowCreate)
  7036. {
  7037. bool isStructPtr = false;
  7038. BfPopulateType populateType = allowCreate ? BfPopulateType_Data : BfPopulateType_Identity;
  7039. BfResolveTypeRefFlags resolveFlags = allowCreate ? BfResolveTypeRefFlag_None : BfResolveTypeRefFlag_NoCreate;
  7040. if (resolvedTypeRef->IsPrimitiveType())
  7041. {
  7042. auto primType = (BfPrimitiveType*)resolvedTypeRef;
  7043. resolvedTypeRef = GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  7044. if (resolvedTypeRef == NULL)
  7045. return NULL;
  7046. }
  7047. else if (resolvedTypeRef->IsPointer())
  7048. {
  7049. BfPointerType* pointerType = (BfPointerType*)resolvedTypeRef;
  7050. if (pointerType->mElementType->IsStruct())
  7051. {
  7052. resolvedTypeRef = pointerType->mElementType;
  7053. isStructPtr = true;
  7054. }
  7055. else
  7056. {
  7057. BfTypeVector typeVector;
  7058. typeVector.Add(pointerType->mElementType);
  7059. resolvedTypeRef = ResolveTypeDef(mCompiler->mPointerTTypeDef, typeVector, populateType, resolveFlags);
  7060. if (resolvedTypeRef == NULL)
  7061. return NULL;
  7062. }
  7063. }
  7064. else if (resolvedTypeRef->IsMethodRef())
  7065. {
  7066. BfMethodRefType* methodRefType = (BfMethodRefType*)resolvedTypeRef;
  7067. BfTypeVector typeVector;
  7068. typeVector.Add(methodRefType);
  7069. resolvedTypeRef = ResolveTypeDef(mCompiler->mMethodRefTypeDef, typeVector, populateType, resolveFlags);
  7070. if (resolvedTypeRef == NULL)
  7071. return NULL;
  7072. }
  7073. else if (resolvedTypeRef->IsSizedArray())
  7074. {
  7075. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)resolvedTypeRef;
  7076. BfTypeVector typeVector;
  7077. typeVector.Add(sizedArrayType->mElementType);
  7078. auto sizeValue = BfTypedValue(GetConstValue(sizedArrayType->mElementCount), GetPrimitiveType(BfTypeCode_IntPtr));
  7079. auto sizeValueType = CreateConstExprValueType(sizeValue, allowCreate);
  7080. if (sizeValueType == NULL)
  7081. return NULL;
  7082. typeVector.Add(sizeValueType);
  7083. resolvedTypeRef = ResolveTypeDef(mCompiler->mSizedArrayTypeDef, typeVector, populateType, resolveFlags);
  7084. if (resolvedTypeRef == NULL)
  7085. return NULL;
  7086. }
  7087. BfTypeInstance* typeInst = resolvedTypeRef->ToTypeInstance();
  7088. if ((typeInst == NULL) && (!resolvedTypeRef->IsGenericParam()))
  7089. return NULL;
  7090. auto boxedType = mContext->mBoxedTypePool.Get();
  7091. boxedType->mContext = mContext;
  7092. boxedType->mElementType = resolvedTypeRef;
  7093. if (typeInst != NULL)
  7094. boxedType->mTypeDef = typeInst->mTypeDef->GetDefinition();
  7095. else
  7096. boxedType->mTypeDef = mCompiler->mValueTypeTypeDef;
  7097. boxedType->mBoxedFlags = isStructPtr ? BfBoxedType::BoxedFlags_StructPtr : BfBoxedType::BoxedFlags_None;
  7098. auto resolvedBoxedType = ResolveType(boxedType, populateType, resolveFlags);
  7099. if (resolvedBoxedType != boxedType)
  7100. {
  7101. boxedType->Dispose();
  7102. mContext->mBoxedTypePool.GiveBack(boxedType);
  7103. }
  7104. return (BfBoxedType*)resolvedBoxedType;
  7105. }
  7106. BfTypeInstance* BfModule::CreateTupleType(const BfTypeVector& fieldTypes, const Array<String>& fieldNames, bool allowVar)
  7107. {
  7108. auto baseType = (BfTypeInstance*)ResolveTypeDef(mContext->mCompiler->mValueTypeTypeDef);
  7109. BfTupleType* tupleType = NULL;
  7110. auto actualTupleType = mContext->mTupleTypePool.Get();
  7111. actualTupleType->Init(baseType->mTypeDef->mProject, baseType);
  7112. bool isUnspecialzied = false;
  7113. for (int fieldIdx = 0; fieldIdx < (int)fieldTypes.size(); fieldIdx++)
  7114. {
  7115. String fieldName;
  7116. if (fieldIdx < (int)fieldNames.size())
  7117. fieldName = fieldNames[fieldIdx];
  7118. if (fieldName.empty())
  7119. fieldName = StrFormat("%d", fieldIdx);
  7120. BfFieldDef* fieldDef = actualTupleType->AddField(fieldName);
  7121. auto fieldType = fieldTypes[fieldIdx];
  7122. if ((fieldType->IsUnspecializedType()) || (fieldType->IsVar()))
  7123. isUnspecialzied = true;
  7124. }
  7125. tupleType = actualTupleType;
  7126. tupleType->mContext = mContext;
  7127. tupleType->mFieldInstances.Resize(fieldTypes.size());
  7128. for (int fieldIdx = 0; fieldIdx < (int)fieldTypes.size(); fieldIdx++)
  7129. {
  7130. BfFieldInstance* fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  7131. fieldInstance->mFieldIdx = fieldIdx;
  7132. BfType* fieldType = fieldTypes[fieldIdx];
  7133. if ((fieldType->IsVar()) && (!allowVar))
  7134. fieldType = mContext->mBfObjectType;
  7135. fieldInstance->SetResolvedType(fieldType);
  7136. fieldInstance->mOwner = tupleType;
  7137. }
  7138. tupleType->mIsUnspecializedType = false;
  7139. tupleType->mIsUnspecializedTypeVariation = false;
  7140. if (isUnspecialzied)
  7141. {
  7142. tupleType->mIsUnspecializedType = true;
  7143. tupleType->mIsUnspecializedTypeVariation = true;
  7144. }
  7145. auto resolvedTupleType = ResolveType(tupleType);
  7146. if (resolvedTupleType != tupleType)
  7147. {
  7148. BF_ASSERT(tupleType->mContext != NULL);
  7149. tupleType->Dispose();
  7150. mContext->mTupleTypePool.GiveBack((BfTupleType*)tupleType);
  7151. }
  7152. return (BfTupleType*)resolvedTupleType;
  7153. }
  7154. BfTypeInstance* BfModule::SantizeTupleType(BfTypeInstance* tupleType)
  7155. {
  7156. bool needsSanitize = false;
  7157. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  7158. {
  7159. BfFieldInstance* fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  7160. if ((fieldInstance->mResolvedType->IsVar()) || (fieldInstance->mResolvedType->IsLet()))
  7161. {
  7162. needsSanitize = true;
  7163. break;
  7164. }
  7165. }
  7166. if (!needsSanitize)
  7167. return tupleType;
  7168. BfTypeVector fieldTypes;
  7169. Array<String> fieldNames;
  7170. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  7171. {
  7172. BfFieldInstance* fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  7173. auto fieldDef = fieldInstance->GetFieldDef();
  7174. if ((fieldInstance->mResolvedType->IsVar()) || (fieldInstance->mResolvedType->IsLet()))
  7175. fieldTypes.Add(mContext->mBfObjectType);
  7176. else
  7177. fieldTypes.Add(fieldInstance->mResolvedType);
  7178. if (!fieldDef->IsUnnamedTupleField())
  7179. {
  7180. for (int i = 0; i < fieldIdx; i++)
  7181. fieldNames.Add(String());
  7182. fieldNames.Add(fieldDef->mName);
  7183. }
  7184. }
  7185. return CreateTupleType(fieldTypes, fieldNames);
  7186. }
  7187. BfRefType* BfModule::CreateRefType(BfType* resolvedTypeRef, BfRefType::RefKind refKind)
  7188. {
  7189. auto refType = mContext->mRefTypePool.Get();
  7190. refType->mContext = mContext;
  7191. refType->mElementType = resolvedTypeRef;
  7192. refType->mRefKind = refKind;
  7193. auto resolvedRefType = ResolveType(refType);
  7194. if (resolvedRefType != refType)
  7195. mContext->mRefTypePool.GiveBack(refType);
  7196. return (BfRefType*)resolvedRefType;
  7197. }
  7198. BfModifiedTypeType* BfModule::CreateModifiedTypeType(BfType* resolvedTypeRef, BfToken modifiedKind)
  7199. {
  7200. auto retTypeType = mContext->mModifiedTypeTypePool.Get();
  7201. retTypeType->mContext = mContext;
  7202. retTypeType->mModifiedKind = modifiedKind;
  7203. retTypeType->mElementType = resolvedTypeRef;
  7204. auto resolvedRetTypeType = ResolveType(retTypeType);
  7205. if (resolvedRetTypeType != retTypeType)
  7206. mContext->mModifiedTypeTypePool.GiveBack(retTypeType);
  7207. return (BfModifiedTypeType*)resolvedRetTypeType;
  7208. }
  7209. BfConcreteInterfaceType* BfModule::CreateConcreteInterfaceType(BfTypeInstance* interfaceType)
  7210. {
  7211. auto concreteInterfaceType = mContext->mConcreteInterfaceTypePool.Get();
  7212. concreteInterfaceType->mContext = mContext;
  7213. concreteInterfaceType->mInterface = interfaceType;
  7214. auto resolvedConcreteInterfaceType = ResolveType(concreteInterfaceType);
  7215. if (resolvedConcreteInterfaceType != concreteInterfaceType)
  7216. mContext->mConcreteInterfaceTypePool.GiveBack(concreteInterfaceType);
  7217. return (BfConcreteInterfaceType*)resolvedConcreteInterfaceType;
  7218. }
  7219. BfPointerType* BfModule::CreatePointerType(BfTypeReference* typeRef)
  7220. {
  7221. auto resolvedTypeRef = ResolveTypeRef(typeRef);
  7222. if (resolvedTypeRef == NULL)
  7223. return NULL;
  7224. return CreatePointerType(resolvedTypeRef);
  7225. }
  7226. BfType* BfModule::ResolveTypeDef(BfTypeDef* typeDef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  7227. {
  7228. BF_ASSERT(typeDef->mDefState != BfTypeDef::DefState_Emitted);
  7229. if (typeDef->mTypeDeclaration == NULL)
  7230. {
  7231. BF_ASSERT(!typeDef->mIsDelegate && !typeDef->mIsFunction);
  7232. }
  7233. //BF_ASSERT(typeDef->mTypeCode != BfTypeCode_Extension);
  7234. BF_ASSERT(!typeDef->mIsPartial || typeDef->mIsCombinedPartial);
  7235. BF_ASSERT(typeDef->mDefState != BfTypeDef::DefState_Deleted);
  7236. BF_ASSERT((typeDef->mOuterType == NULL) || (typeDef->mOuterType->mDefState != BfTypeDef::DefState_Deleted));
  7237. if (typeDef->mGenericParamDefs.size() != 0)
  7238. return ResolveTypeDef(typeDef, BfTypeVector(), populateType, resolveFlags);
  7239. auto typeDefTypeRef = mContext->mTypeDefTypeRefPool.Get();
  7240. typeDefTypeRef->mTypeDef = typeDef;
  7241. auto resolvedtypeDefType = ResolveTypeRef(typeDefTypeRef, populateType, resolveFlags);
  7242. if (resolvedtypeDefType == NULL)
  7243. {
  7244. mContext->mTypeDefTypeRefPool.GiveBack(typeDefTypeRef);
  7245. return NULL;
  7246. }
  7247. mContext->mTypeDefTypeRefPool.GiveBack(typeDefTypeRef);
  7248. //BF_ASSERT(resolvedtypeDefType->IsTypeInstance() || resolvedtypeDefType->IsPrimitiveType());
  7249. return resolvedtypeDefType;
  7250. }
  7251. // Get BaseClass even when we haven't populated the type yet
  7252. BfTypeInstance* BfModule::GetBaseType(BfTypeInstance* typeInst)
  7253. {
  7254. if (typeInst->mBaseType == NULL)
  7255. {
  7256. auto checkTypeState = mContext->mCurTypeState;
  7257. while (checkTypeState != NULL)
  7258. {
  7259. if (checkTypeState->mType == typeInst)
  7260. return NULL;
  7261. checkTypeState = checkTypeState->mPrevState;
  7262. }
  7263. }
  7264. if ((typeInst->mBaseType == NULL) && (typeInst != mContext->mBfObjectType))
  7265. PopulateType(typeInst, BfPopulateType_BaseType);
  7266. return typeInst->mBaseType;
  7267. }
  7268. void BfModule::HandleTypeGenericParamRef(BfAstNode* refNode, BfTypeDef* typeDef, int typeGenericParamIdx)
  7269. {
  7270. if (mCompiler->IsAutocomplete())
  7271. {
  7272. BfAutoComplete* autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  7273. if ((autoComplete != NULL) && (autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(refNode)))
  7274. {
  7275. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  7276. (autoComplete->mDefProp == NULL))
  7277. {
  7278. autoComplete->mDefType = typeDef;
  7279. autoComplete->mDefTypeGenericParamIdx = typeGenericParamIdx;
  7280. autoComplete->SetDefinitionLocation(refNode);
  7281. }
  7282. }
  7283. }
  7284. if (mCompiler->mResolvePassData != NULL)
  7285. mCompiler->mResolvePassData->HandleTypeGenericParam(refNode, typeDef, typeGenericParamIdx);
  7286. }
  7287. void BfModule::HandleMethodGenericParamRef(BfAstNode* refNode, BfTypeDef* typeDef, BfMethodDef* methodDef, int methodGenericParamIdx)
  7288. {
  7289. if (mCompiler->IsAutocomplete())
  7290. {
  7291. BfAutoComplete* autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  7292. if ((autoComplete != NULL) && (autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(refNode)))
  7293. {
  7294. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  7295. (autoComplete->mDefProp == NULL))
  7296. {
  7297. autoComplete->mDefType = typeDef;
  7298. autoComplete->mDefMethod = methodDef;
  7299. autoComplete->mDefMethodGenericParamIdx = methodGenericParamIdx;
  7300. autoComplete->SetDefinitionLocation(refNode);
  7301. }
  7302. }
  7303. }
  7304. if (mCompiler->mResolvePassData != NULL)
  7305. mCompiler->mResolvePassData->HandleMethodGenericParam(refNode, typeDef, methodDef, methodGenericParamIdx);
  7306. }
  7307. BfType* BfModule::ResolveInnerType(BfType* outerType, BfAstNode* typeRef, BfPopulateType populateType, bool ignoreErrors, int numGenericArgs, BfResolveTypeRefFlags resolveFlags)
  7308. {
  7309. BfTypeDef* nestedTypeDef = NULL;
  7310. if (outerType->IsBoxed())
  7311. outerType = outerType->GetUnderlyingType();
  7312. BfNamedTypeReference* namedTypeRef = NULL;
  7313. BfGenericInstanceTypeRef* genericTypeRef = NULL;
  7314. BfDirectStrTypeReference* directStrTypeRef = NULL;
  7315. BfIdentifierNode* identifierNode = NULL;
  7316. if ((namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef)))
  7317. {
  7318. //TYPEDEF nestedTypeDef = namedTypeRef->mTypeDef;
  7319. }
  7320. else if ((genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef)))
  7321. {
  7322. namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(genericTypeRef->mElementType);
  7323. //TYPEDEF nestedTypeDef = namedTypeRef->mTypeDef;
  7324. }
  7325. else if ((identifierNode = BfNodeDynCast<BfIdentifierNode>(typeRef)))
  7326. {
  7327. //TYPEDEF nestedTypeDef = namedTypeRef->mTypeDef;
  7328. }
  7329. else if ((directStrTypeRef = BfNodeDynCast<BfDirectStrTypeReference>(typeRef)))
  7330. {
  7331. //
  7332. }
  7333. BF_ASSERT((identifierNode != NULL) || (namedTypeRef != NULL) || (directStrTypeRef != NULL));
  7334. auto usedOuterType = outerType;
  7335. if (nestedTypeDef == NULL)
  7336. {
  7337. StringView findName;
  7338. if (namedTypeRef != NULL)
  7339. findName = namedTypeRef->mNameNode->ToStringView();
  7340. else if (identifierNode != NULL)
  7341. findName = identifierNode->ToStringView();
  7342. else
  7343. findName = directStrTypeRef->mTypeName;
  7344. if (!findName.Contains('.'))
  7345. {
  7346. if (outerType->IsTypeInstance())
  7347. {
  7348. auto outerTypeInstance = outerType->ToTypeInstance();
  7349. for (int pass = 0; pass < 2; pass++)
  7350. {
  7351. bool isFailurePass = pass == 1;
  7352. bool allowPrivate = (mCurTypeInstance != NULL) &&
  7353. ((mCurTypeInstance == outerTypeInstance) || TypeHasParentOrEquals(mCurTypeInstance->mTypeDef, outerTypeInstance->mTypeDef));
  7354. bool allowProtected = allowPrivate;/*(mCurTypeInstance != NULL) &&
  7355. (allowPrivate || (mCurTypeInstance->mSkipTypeProtectionChecks) || TypeIsSubTypeOf(mCurTypeInstance, outerTypeInstance));*/
  7356. auto checkOuterType = outerTypeInstance;
  7357. while (checkOuterType != NULL)
  7358. {
  7359. for (auto checkType : checkOuterType->mTypeDef->mNestedTypes)
  7360. {
  7361. auto latestCheckType = checkType->GetLatest();
  7362. if ((!isFailurePass) && ((resolveFlags & BfResolveTypeRefFlag_IgnoreProtection) == 0) &&
  7363. (!CheckProtection(latestCheckType->mProtection, latestCheckType, allowProtected, allowPrivate)))
  7364. continue;
  7365. if (checkType->mProject != checkOuterType->mTypeDef->mProject)
  7366. {
  7367. auto visibleProjectSet = GetVisibleProjectSet();
  7368. if ((visibleProjectSet == NULL) || (!visibleProjectSet->Contains(checkType->mProject)))
  7369. continue;
  7370. }
  7371. if ((checkType->mName->mString == findName) && (checkType->GetSelfGenericParamCount() == numGenericArgs))
  7372. {
  7373. if (isFailurePass)
  7374. {
  7375. // This is the one error we don't ignore when ignoreErrors is set
  7376. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(checkOuterType).c_str(), BfTypeUtils::TypeToString(typeRef).c_str()), typeRef); // CS0122
  7377. }
  7378. usedOuterType = checkOuterType;
  7379. nestedTypeDef = checkType;
  7380. break;
  7381. }
  7382. }
  7383. if (nestedTypeDef != NULL)
  7384. break;
  7385. allowPrivate = false;
  7386. checkOuterType = GetBaseType(checkOuterType);
  7387. }
  7388. if (nestedTypeDef != NULL)
  7389. break;
  7390. if ((outerTypeInstance->IsEnum()) && (findName == "UnderlyingType"))
  7391. {
  7392. if (outerTypeInstance->IsDataIncomplete())
  7393. PopulateType(outerTypeInstance);
  7394. auto underlyingType = outerTypeInstance->GetUnderlyingType();
  7395. if (underlyingType != NULL)
  7396. return underlyingType;
  7397. }
  7398. }
  7399. }
  7400. }
  7401. if (nestedTypeDef == NULL)
  7402. {
  7403. if ((!mIgnoreErrors) && (!ignoreErrors) && ((resolveFlags & BfResolveTypeRefFlag_IgnoreLookupError) == 0))
  7404. {
  7405. StringT<64> name;
  7406. name.Append(findName);
  7407. Fail(StrFormat("'%s' does not contain a definition for '%s'", TypeToString(outerType).c_str(), name.c_str()), typeRef);
  7408. }
  7409. return NULL;
  7410. }
  7411. }
  7412. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, ignoreErrors || mIgnoreErrors);
  7413. if ((genericTypeRef != NULL) || (usedOuterType->IsGenericTypeInstance()))
  7414. {
  7415. BfTypeVector genericArgs;
  7416. if (usedOuterType->IsGenericTypeInstance())
  7417. {
  7418. auto genericTypeInst = (BfTypeInstance*)usedOuterType;
  7419. genericArgs = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments;
  7420. }
  7421. if (genericTypeRef != NULL)
  7422. {
  7423. for (auto genericArgTypeRef : genericTypeRef->mGenericArguments)
  7424. {
  7425. auto genericArgType = ResolveTypeRef(genericArgTypeRef, NULL, BfPopulateType_IdentityNoRemapAlias);
  7426. if (genericArgType == NULL)
  7427. return NULL;
  7428. genericArgs.push_back(genericArgType);
  7429. }
  7430. }
  7431. if (genericArgs.size() != nestedTypeDef->mGenericParamDefs.size())
  7432. {
  7433. if (populateType == BfPopulateType_TypeDef)
  7434. {
  7435. // Probably from inside ResolveGenericInstanceDef, just return unresolved typedef
  7436. genericArgs.clear();
  7437. }
  7438. else
  7439. {
  7440. ShowGenericArgCountError(typeRef, (int)nestedTypeDef->mGenericParamDefs.size() - (int)nestedTypeDef->mOuterType->mGenericParamDefs.size());
  7441. return NULL;
  7442. }
  7443. }
  7444. if (nestedTypeDef->mIsPartial)
  7445. {
  7446. nestedTypeDef = GetCombinedPartialTypeDef(nestedTypeDef);
  7447. if (nestedTypeDef == NULL)
  7448. return NULL;
  7449. }
  7450. return ResolveTypeDef(nestedTypeDef, genericArgs, BfPopulateType_IdentityNoRemapAlias);
  7451. }
  7452. else
  7453. {
  7454. if (nestedTypeDef->mIsPartial)
  7455. {
  7456. nestedTypeDef = GetCombinedPartialTypeDef(nestedTypeDef);
  7457. if (nestedTypeDef == NULL)
  7458. return NULL;
  7459. }
  7460. return ResolveTypeDef(nestedTypeDef, BfPopulateType_IdentityNoRemapAlias);
  7461. }
  7462. return NULL;
  7463. }
  7464. BfTypeDef* BfModule::GetCombinedPartialTypeDef(BfTypeDef* typeDef)
  7465. {
  7466. BF_ASSERT(!typeDef->mIsExplicitPartial);
  7467. if (!typeDef->mIsPartial)
  7468. return typeDef;
  7469. auto result = mSystem->FindTypeDef(typeDef->mFullName, (int)typeDef->mGenericParamDefs.size(), NULL, {}, NULL, BfFindTypeDefFlag_None);
  7470. return result;
  7471. }
  7472. BfTypeInstance* BfModule::GetOuterType(BfType* type)
  7473. {
  7474. if (type == NULL)
  7475. return NULL;
  7476. if (type->IsBoxed())
  7477. return GetOuterType(((BfBoxedType*)type)->mElementType);
  7478. auto typeInst = type->ToTypeInstance();
  7479. if ((typeInst == NULL) || (typeInst->mTypeDef->mOuterType == NULL))
  7480. return NULL;
  7481. auto outerTypeDef = typeInst->mTypeDef->mOuterType;
  7482. if (outerTypeDef->mIsPartial)
  7483. {
  7484. outerTypeDef = GetCombinedPartialTypeDef(outerTypeDef);
  7485. if (outerTypeDef == NULL)
  7486. return NULL;
  7487. }
  7488. BfTypeVector typeGenericArguments;
  7489. if (type->IsGenericTypeInstance())
  7490. {
  7491. auto genericType = (BfTypeInstance*)type;
  7492. typeGenericArguments = genericType->mGenericTypeInfo->mTypeGenericArguments;
  7493. }
  7494. BF_ASSERT((intptr)typeGenericArguments.size() >= (intptr)outerTypeDef->mGenericParamDefs.size());
  7495. typeGenericArguments.resize(outerTypeDef->mGenericParamDefs.size());
  7496. //auto outerType = ResolveTypeDef(outerTypeDef, typeGenericArguments, BfPopulateType_Declaration);
  7497. auto outerType = ResolveTypeDef(outerTypeDef, typeGenericArguments, BfPopulateType_Identity);
  7498. if (outerType == NULL)
  7499. return NULL;
  7500. return outerType->ToTypeInstance();
  7501. }
  7502. bool BfModule::IsInnerType(BfType* checkInnerType, BfType* checkOuterType)
  7503. {
  7504. BfType* outerType = GetOuterType(checkInnerType);
  7505. if (outerType == NULL)
  7506. return false;
  7507. if (outerType == checkOuterType)
  7508. return true;
  7509. return IsInnerType(outerType, checkOuterType);
  7510. }
  7511. bool BfModule::IsInnerType(BfTypeDef* checkInnerType, BfTypeDef* checkOuterType)
  7512. {
  7513. BF_ASSERT(!checkOuterType->mIsPartial);
  7514. if (checkInnerType->mNestDepth <= checkOuterType->mNestDepth)
  7515. return false;
  7516. while (true)
  7517. {
  7518. BfTypeDef* outerType = checkInnerType->mOuterType;
  7519. if (outerType == NULL)
  7520. return false;
  7521. if (outerType->mIsPartial)
  7522. outerType = mSystem->GetCombinedPartial(outerType);
  7523. if (outerType->GetDefinition() == checkOuterType->GetDefinition())
  7524. return true;
  7525. checkInnerType = checkInnerType->mOuterType;
  7526. }
  7527. }
  7528. BfType* BfModule::ResolveTypeDef(BfTypeDef* typeDef, const BfTypeVector& genericArgs, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  7529. {
  7530. BF_ASSERT(typeDef->mDefState != BfTypeDef::DefState_Emitted);
  7531. if (typeDef->mGenericParamDefs.size() == 0)
  7532. return ResolveTypeDef(typeDef, populateType, resolveFlags);
  7533. if ((typeDef == mCompiler->mArray1TypeDef) || (typeDef == mCompiler->mArray2TypeDef))
  7534. {
  7535. auto arrayInstType = mContext->mArrayTypeInstancePool.Get();
  7536. arrayInstType->mContext = mContext;
  7537. if (typeDef == mCompiler->mArray1TypeDef)
  7538. arrayInstType->mDimensions = 1;
  7539. else
  7540. arrayInstType->mDimensions = 2;
  7541. auto typeRef = mContext->mTypeDefTypeRefPool.Get();
  7542. typeRef->mTypeDef = typeDef;
  7543. delete arrayInstType->mGenericTypeInfo;
  7544. arrayInstType->mGenericTypeInfo = new BfGenericTypeInfo();
  7545. arrayInstType->mTypeDef = typeDef;
  7546. arrayInstType->mGenericTypeInfo->mIsUnspecialized = false;
  7547. arrayInstType->mGenericTypeInfo->mTypeGenericArguments.clear();
  7548. for (auto genericArg : genericArgs)
  7549. {
  7550. arrayInstType->mGenericTypeInfo->mIsUnspecialized |= genericArg->IsGenericParam();
  7551. arrayInstType->mGenericTypeInfo->mTypeGenericArguments.push_back(genericArg);
  7552. }
  7553. if (genericArgs.size() == 0)
  7554. {
  7555. for (int i = 0; i < (int)typeDef->mGenericParamDefs.size(); i++)
  7556. {
  7557. auto genericParamTypeRef = GetGenericParamType(BfGenericParamKind_Type, i);
  7558. arrayInstType->mGenericTypeInfo->mTypeGenericArguments.push_back(genericParamTypeRef);
  7559. arrayInstType->mGenericTypeInfo->mIsUnspecialized = true;
  7560. }
  7561. }
  7562. auto resolvedType = ResolveType(arrayInstType, populateType, resolveFlags);
  7563. if (resolvedType != arrayInstType)
  7564. {
  7565. delete arrayInstType->mGenericTypeInfo;
  7566. arrayInstType->mGenericTypeInfo = NULL;
  7567. arrayInstType->Dispose();
  7568. mContext->mArrayTypeInstancePool.GiveBack(arrayInstType);
  7569. mContext->mTypeDefTypeRefPool.GiveBack(typeRef);
  7570. }
  7571. BF_ASSERT((resolvedType == NULL) || resolvedType->IsTypeInstance() || resolvedType->IsPrimitiveType());
  7572. return resolvedType;
  7573. }
  7574. BfTypeInstance* genericInstType;
  7575. if (typeDef->mTypeCode == BfTypeCode_TypeAlias)
  7576. genericInstType = mContext->mAliasTypePool.Get();
  7577. else
  7578. genericInstType = mContext->mGenericTypeInstancePool.Get();
  7579. delete genericInstType->mGenericTypeInfo;
  7580. genericInstType->mGenericTypeInfo = new BfGenericTypeInfo();
  7581. BF_ASSERT(genericInstType->mGenericTypeInfo->mGenericParams.size() == 0);
  7582. BF_ASSERT((genericInstType->mRebuildFlags & BfTypeRebuildFlag_AddedToWorkList) == 0);
  7583. genericInstType->mRebuildFlags = (BfTypeRebuildFlags)(genericInstType->mRebuildFlags & ~BfTypeRebuildFlag_InTempPool);
  7584. genericInstType->mContext = mContext;
  7585. auto typeRef = mContext->mTypeDefTypeRefPool.Get();
  7586. typeRef->mTypeDef = typeDef;
  7587. genericInstType->mTypeDef = typeDef;
  7588. genericInstType->mGenericTypeInfo->mIsUnspecialized = false;
  7589. genericInstType->mGenericTypeInfo->mTypeGenericArguments.clear();
  7590. genericInstType->mTypeFailed = false;
  7591. for (auto genericArg : genericArgs)
  7592. {
  7593. genericInstType->mGenericTypeInfo->mIsUnspecialized |= genericArg->IsGenericParam();
  7594. genericInstType->mGenericTypeInfo->mTypeGenericArguments.push_back(genericArg);
  7595. }
  7596. if (genericArgs.size() == 0)
  7597. {
  7598. for (int i = 0; i < (int)typeDef->mGenericParamDefs.size(); i++)
  7599. {
  7600. auto genericParamTypeRef = GetGenericParamType(BfGenericParamKind_Type, i);
  7601. genericInstType->mGenericTypeInfo->mTypeGenericArguments.push_back(genericParamTypeRef);
  7602. genericInstType->mGenericTypeInfo->mIsUnspecialized = true;
  7603. }
  7604. }
  7605. BfType* resolvedType = NULL;
  7606. bool failed = false;
  7607. resolvedType = ResolveType(genericInstType, populateType, resolveFlags);
  7608. if (resolvedType != genericInstType)
  7609. {
  7610. BF_ASSERT(genericInstType->mGenericTypeInfo->mGenericParams.size() == 0);
  7611. BF_ASSERT((genericInstType->mRebuildFlags & BfTypeRebuildFlag_AddedToWorkList) == 0);
  7612. genericInstType->mRebuildFlags = (BfTypeRebuildFlags)(genericInstType->mRebuildFlags | BfTypeRebuildFlag_InTempPool);
  7613. delete genericInstType->mGenericTypeInfo;
  7614. genericInstType->mGenericTypeInfo = NULL;
  7615. if (typeDef->mTypeCode == BfTypeCode_TypeAlias)
  7616. mContext->mAliasTypePool.GiveBack((BfTypeAliasType*)genericInstType);
  7617. else
  7618. {
  7619. genericInstType->Dispose();
  7620. mContext->mGenericTypeInstancePool.GiveBack(genericInstType);
  7621. }
  7622. mContext->mTypeDefTypeRefPool.GiveBack(typeRef);
  7623. }
  7624. BF_ASSERT((resolvedType == NULL) || resolvedType->IsTypeInstance() || resolvedType->IsPrimitiveType());
  7625. return resolvedType;
  7626. }
  7627. int checkIdx = 0;
  7628. BfTypeDef* BfModule::ResolveGenericInstanceDef(BfGenericInstanceTypeRef* genericTypeRef, BfType** outType, BfResolveTypeRefFlags resolveFlags)
  7629. {
  7630. if (outType != NULL)
  7631. *outType = NULL;
  7632. BfTypeReference* typeRef = genericTypeRef->mElementType;
  7633. int numGenericParams = genericTypeRef->GetGenericArgCount();
  7634. BfTypeDef* curTypeDef = NULL;
  7635. if (mCurTypeInstance != NULL)
  7636. curTypeDef = mCurTypeInstance->mTypeDef->GetDefinition();
  7637. if (auto directTypeDef = BfNodeDynCast<BfDirectTypeReference>(typeRef))
  7638. {
  7639. auto typeInst = directTypeDef->mType->ToTypeInstance();
  7640. return typeInst->mTypeDef->GetDefinition();
  7641. }
  7642. auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef);
  7643. auto directStrTypeDef = BfNodeDynCastExact<BfDirectStrTypeReference>(typeRef);
  7644. if ((namedTypeRef != NULL) || (directStrTypeDef != NULL))
  7645. {
  7646. BfTypeLookupError error;
  7647. error.mRefNode = typeRef;
  7648. BfTypeDef* typeDef = FindTypeDef(typeRef, NULL, &error, numGenericParams, resolveFlags);
  7649. if (typeDef != NULL)
  7650. {
  7651. BfAutoComplete* autoComplete = NULL;
  7652. if (mCompiler->IsAutocomplete())
  7653. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  7654. if ((autoComplete != NULL) && (autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(typeRef)))
  7655. {
  7656. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  7657. (autoComplete->mDefProp == NULL) && (typeDef->mTypeDeclaration != NULL))
  7658. {
  7659. autoComplete->mDefType = typeDef;
  7660. autoComplete->SetDefinitionLocation(typeDef->mTypeDeclaration->mNameNode);
  7661. }
  7662. }
  7663. if (mCompiler->mResolvePassData != NULL)
  7664. mCompiler->mResolvePassData->HandleTypeReference(typeRef, typeDef);
  7665. return typeDef;
  7666. }
  7667. if (mCurTypeInstance != NULL)
  7668. {
  7669. bool wasGenericParam = false;
  7670. // Check generics first
  7671. if (typeRef->IsA<BfNamedTypeReference>())
  7672. {
  7673. String findName = typeRef->ToString();
  7674. if ((resolveFlags & BfResolveTypeRefFlag_Attribute) != 0)
  7675. findName += "Attribute";
  7676. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsGenericTypeInstance()))
  7677. {
  7678. auto genericTypeInst = (BfTypeInstance*)mCurTypeInstance;
  7679. for (int genericParamIdx = 0; genericParamIdx < (int)curTypeDef->mGenericParamDefs.size(); genericParamIdx++)
  7680. {
  7681. String genericName = curTypeDef->mGenericParamDefs[genericParamIdx]->mName;
  7682. if (genericName == findName)
  7683. wasGenericParam = true;
  7684. }
  7685. }
  7686. if (mCurMethodInstance != NULL)
  7687. {
  7688. for (int genericParamIdx = 0; genericParamIdx < (int)mCurMethodInstance->mMethodDef->mGenericParams.size(); genericParamIdx++)
  7689. {
  7690. String genericName = mCurMethodInstance->mMethodDef->mGenericParams[genericParamIdx]->mName;
  7691. if (genericName == findName)
  7692. wasGenericParam = true;
  7693. }
  7694. }
  7695. }
  7696. if ((wasGenericParam) && ((resolveFlags & BfResolveTypeRefFlag_IgnoreLookupError) == 0))
  7697. Fail("Cannot use generic param as generic instance type", typeRef);
  7698. }
  7699. if (typeDef == NULL)
  7700. {
  7701. if ((resolveFlags & BfResolveTypeRefFlag_IgnoreLookupError) == 0)
  7702. TypeRefNotFound(typeRef);
  7703. return NULL;
  7704. }
  7705. }
  7706. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  7707. {
  7708. BfAutoParentNodeEntry autoParentNodeEntry(this, genericTypeRef);
  7709. auto type = ResolveTypeRef(qualifiedTypeRef, BfPopulateType_TypeDef, resolveFlags, numGenericParams);
  7710. if (type == NULL)
  7711. return NULL;
  7712. if (outType != NULL)
  7713. *outType = type;
  7714. auto typeInst = type->ToTypeInstance();
  7715. if (typeInst != NULL)
  7716. return typeInst->mTypeDef->GetDefinition();
  7717. }
  7718. if ((resolveFlags & BfResolveTypeRefFlag_IgnoreLookupError) == 0)
  7719. Fail("Invalid generic type", typeRef);
  7720. return NULL;
  7721. }
  7722. BfType* BfModule::ResolveGenericType(BfType* unspecializedType, BfTypeVector* typeGenericArguments, BfTypeVector* methodGenericArguments, BfType* selfType, bool allowFail)
  7723. {
  7724. if (unspecializedType->IsGenericParam())
  7725. {
  7726. auto genericParam = (BfGenericParamType*)unspecializedType;
  7727. if ((genericParam->mGenericParamKind == BfGenericParamKind_Type) && (typeGenericArguments != NULL))
  7728. {
  7729. if (genericParam->mGenericParamIdx < (int)typeGenericArguments->size())
  7730. return FixIntUnknown((*typeGenericArguments)[genericParam->mGenericParamIdx]);
  7731. BF_ASSERT(allowFail);
  7732. }
  7733. if ((genericParam->mGenericParamKind == BfGenericParamKind_Method) && (methodGenericArguments != NULL))
  7734. {
  7735. if (genericParam->mGenericParamIdx < (int)methodGenericArguments->size())
  7736. {
  7737. auto resolvedType = FixIntUnknown((*methodGenericArguments)[genericParam->mGenericParamIdx]);
  7738. if ((resolvedType != NULL) && (resolvedType->IsGenericParam()))
  7739. {
  7740. auto genericParamType = (BfGenericParamType*)resolvedType;
  7741. //BF_ASSERT(genericParamType->mGenericParamKind != BfGenericParamKind_Method);
  7742. }
  7743. return resolvedType;
  7744. }
  7745. BF_ASSERT(allowFail);
  7746. }
  7747. return unspecializedType;
  7748. }
  7749. if ((unspecializedType->IsSelf()) && (selfType != NULL))
  7750. return selfType;
  7751. if (!unspecializedType->IsUnspecializedType())
  7752. {
  7753. return unspecializedType;
  7754. }
  7755. if (unspecializedType->IsUnknownSizedArrayType())
  7756. {
  7757. auto* arrayType = (BfUnknownSizedArrayType*)unspecializedType;
  7758. auto elementType = ResolveGenericType(arrayType->mElementType, typeGenericArguments, methodGenericArguments, selfType, allowFail);
  7759. if (elementType == NULL)
  7760. return NULL;
  7761. if (elementType->IsVar())
  7762. return elementType;
  7763. auto sizeType = ResolveGenericType(arrayType->mElementCountSource, typeGenericArguments, methodGenericArguments, selfType, allowFail);
  7764. if (sizeType == NULL)
  7765. return NULL;
  7766. if (sizeType->IsConstExprValue())
  7767. {
  7768. return CreateSizedArrayType(elementType, ((BfConstExprValueType*)sizeType)->mValue.mInt32);
  7769. }
  7770. return CreateUnknownSizedArrayType(elementType, sizeType);
  7771. }
  7772. if (unspecializedType->IsSizedArray())
  7773. {
  7774. auto* arrayType = (BfSizedArrayType*)unspecializedType;
  7775. auto elementType = ResolveGenericType(arrayType->mElementType, typeGenericArguments, methodGenericArguments, selfType, allowFail);
  7776. if (elementType == NULL)
  7777. return NULL;
  7778. if (elementType->IsVar())
  7779. return elementType;
  7780. elementType = FixIntUnknown(elementType);
  7781. return CreateSizedArrayType(elementType, (int)arrayType->mElementCount);
  7782. }
  7783. if (unspecializedType->IsRef())
  7784. {
  7785. auto refType = (BfRefType*)unspecializedType;
  7786. auto elementType = ResolveGenericType(refType->GetUnderlyingType(), typeGenericArguments, methodGenericArguments, selfType, allowFail);
  7787. if (elementType == NULL)
  7788. return NULL;
  7789. if (elementType->IsVar())
  7790. return elementType;
  7791. elementType = FixIntUnknown(elementType);
  7792. return CreateRefType(elementType, refType->mRefKind);
  7793. }
  7794. if (unspecializedType->IsPointer())
  7795. {
  7796. auto ptrType = (BfPointerType*)unspecializedType;
  7797. auto elementType = ResolveGenericType(ptrType->GetUnderlyingType(), typeGenericArguments, methodGenericArguments, selfType, allowFail);
  7798. if (elementType == NULL)
  7799. return NULL;
  7800. if (elementType->IsVar())
  7801. return elementType;
  7802. elementType = FixIntUnknown(elementType);
  7803. return CreatePointerType(elementType);
  7804. }
  7805. if (unspecializedType->IsConcreteInterfaceType())
  7806. {
  7807. auto concreteType = (BfConcreteInterfaceType*)unspecializedType;
  7808. auto elementType = ResolveGenericType(concreteType->GetUnderlyingType(), typeGenericArguments, methodGenericArguments, selfType, allowFail);
  7809. if (elementType == NULL)
  7810. return NULL;
  7811. auto elementTypeInstance = elementType->ToTypeInstance();
  7812. if (elementTypeInstance == NULL)
  7813. return unspecializedType;
  7814. return CreateConcreteInterfaceType(elementTypeInstance);
  7815. }
  7816. if (unspecializedType->IsArray())
  7817. {
  7818. auto arrayType = (BfArrayType*)unspecializedType;
  7819. auto elementType = ResolveGenericType(arrayType->GetUnderlyingType(), typeGenericArguments, methodGenericArguments, selfType, allowFail);
  7820. if (elementType == NULL)
  7821. return NULL;
  7822. if (elementType->IsVar())
  7823. return elementType;
  7824. elementType = FixIntUnknown(elementType);
  7825. return CreateArrayType(elementType, arrayType->mDimensions);
  7826. }
  7827. if (unspecializedType->IsTuple())
  7828. {
  7829. bool wantGeneric = false;
  7830. bool isUnspecialized = false;
  7831. auto unspecializedTupleType = (BfTypeInstance*)unspecializedType;
  7832. auto unspecializedGenericTupleType = unspecializedTupleType->ToGenericTypeInstance();
  7833. Array<String> fieldNames;
  7834. BfTypeVector fieldTypes;
  7835. bool hadChange = false;
  7836. for (auto& fieldInstance : unspecializedTupleType->mFieldInstances)
  7837. {
  7838. fieldNames.push_back(fieldInstance.GetFieldDef()->mName);
  7839. auto origGenericArg = fieldInstance.mResolvedType;
  7840. auto newGenericArg = ResolveGenericType(origGenericArg, typeGenericArguments, methodGenericArguments, selfType, allowFail);
  7841. if (newGenericArg == NULL)
  7842. return NULL;
  7843. if (newGenericArg->IsVar())
  7844. return newGenericArg;
  7845. if (newGenericArg->IsTypeGenericParam())
  7846. wantGeneric = true;
  7847. if (newGenericArg->IsUnspecializedType())
  7848. isUnspecialized = true;
  7849. if (newGenericArg->IsVar())
  7850. wantGeneric = mContext->mBfObjectType;
  7851. //wantGeneric = true;
  7852. if (newGenericArg != origGenericArg)
  7853. hadChange = true;
  7854. fieldTypes.push_back(newGenericArg);
  7855. }
  7856. if (!hadChange)
  7857. return unspecializedType;
  7858. if (unspecializedGenericTupleType == NULL)
  7859. wantGeneric = false;
  7860. //TODO:
  7861. wantGeneric = false;
  7862. auto baseType = (BfTypeInstance*)ResolveTypeDef(mContext->mCompiler->mValueTypeTypeDef);
  7863. BfTupleType* tupleType = NULL;
  7864. if (wantGeneric)
  7865. {
  7866. Array<BfType*> genericArgs;
  7867. for (int genericArgIdx = 0; genericArgIdx < (int)unspecializedGenericTupleType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  7868. {
  7869. BfType* resolvedArg = unspecializedGenericTupleType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx];
  7870. if (resolvedArg->IsUnspecializedType())
  7871. {
  7872. resolvedArg = ResolveGenericType(resolvedArg, typeGenericArguments, methodGenericArguments, selfType, allowFail);
  7873. if (resolvedArg == NULL)
  7874. return NULL;
  7875. if (resolvedArg->IsVar())
  7876. return resolvedArg;
  7877. }
  7878. genericArgs.push_back(resolvedArg);
  7879. }
  7880. auto actualTupleType = mContext->mTupleTypePool.Get();
  7881. delete actualTupleType->mGenericTypeInfo;
  7882. actualTupleType->mGenericDepth = 0;
  7883. actualTupleType->mGenericTypeInfo = new BfGenericTypeInfo();
  7884. actualTupleType->mGenericTypeInfo->mIsUnspecialized = false;
  7885. actualTupleType->mGenericTypeInfo->mIsUnspecializedVariation = false;
  7886. actualTupleType->mGenericTypeInfo->mTypeGenericArguments = genericArgs;
  7887. for (int genericArgIdx = 0; genericArgIdx < (int)unspecializedGenericTupleType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  7888. {
  7889. auto typeGenericArg = genericArgs[genericArgIdx];
  7890. if ((typeGenericArg->IsGenericParam()) || (typeGenericArg->IsUnspecializedType()))
  7891. actualTupleType->mGenericTypeInfo->mIsUnspecialized = true;
  7892. actualTupleType->mGenericTypeInfo->mGenericParams.push_back(unspecializedGenericTupleType->mGenericTypeInfo->mGenericParams[genericArgIdx]->AddRef());
  7893. }
  7894. CheckUnspecializedGenericType(actualTupleType, BfPopulateType_Identity);
  7895. if (isUnspecialized)
  7896. {
  7897. actualTupleType->mGenericTypeInfo->mIsUnspecialized = true;
  7898. actualTupleType->mGenericTypeInfo->mIsUnspecializedVariation = true;
  7899. }
  7900. actualTupleType->mIsUnspecializedType = actualTupleType->mGenericTypeInfo->mIsUnspecialized;
  7901. actualTupleType->mIsUnspecializedTypeVariation = actualTupleType->mGenericTypeInfo->mIsUnspecializedVariation;
  7902. actualTupleType->Init(baseType->mTypeDef->mProject, baseType);
  7903. for (int fieldIdx = 0; fieldIdx < (int)fieldTypes.size(); fieldIdx++)
  7904. {
  7905. String fieldName = fieldNames[fieldIdx];
  7906. BfFieldDef* fieldDef = actualTupleType->AddField(fieldName);
  7907. }
  7908. tupleType = actualTupleType;
  7909. }
  7910. else
  7911. {
  7912. auto actualTupleType = new BfTupleType();
  7913. actualTupleType->mIsUnspecializedType = isUnspecialized;
  7914. actualTupleType->mIsUnspecializedTypeVariation = isUnspecialized;
  7915. actualTupleType->Init(baseType->mTypeDef->mProject, baseType);
  7916. for (int fieldIdx = 0; fieldIdx < (int)fieldTypes.size(); fieldIdx++)
  7917. {
  7918. String fieldName = fieldNames[fieldIdx];
  7919. BfFieldDef* fieldDef = actualTupleType->AddField(fieldName);
  7920. }
  7921. tupleType = actualTupleType;
  7922. }
  7923. tupleType->mContext = mContext;
  7924. tupleType->mFieldInstances.Resize(fieldTypes.size());
  7925. for (int fieldIdx = 0; fieldIdx < (int)fieldTypes.size(); fieldIdx++)
  7926. {
  7927. BfFieldInstance* fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[fieldIdx];
  7928. fieldInstance->mFieldIdx = fieldIdx;
  7929. fieldInstance->SetResolvedType(fieldTypes[fieldIdx]);
  7930. fieldInstance->mOwner = tupleType;
  7931. tupleType->mGenericDepth = BF_MAX(tupleType->mGenericDepth, fieldInstance->mResolvedType->GetGenericDepth() + 1);
  7932. }
  7933. bool failed = false;
  7934. BfType* resolvedType = NULL;
  7935. if (!failed)
  7936. resolvedType = ResolveType(tupleType, BfPopulateType_Identity);
  7937. if (resolvedType != tupleType)
  7938. {
  7939. delete tupleType->mGenericTypeInfo;
  7940. tupleType->mGenericTypeInfo = NULL;
  7941. tupleType->Dispose();
  7942. mContext->mTupleTypePool.GiveBack((BfTupleType*)tupleType);
  7943. }
  7944. BF_ASSERT((resolvedType == NULL) || resolvedType->IsTypeInstance() || resolvedType->IsPrimitiveType());
  7945. return resolvedType;
  7946. }
  7947. if ((unspecializedType->IsDelegateFromTypeRef()) || (unspecializedType->IsFunctionFromTypeRef()))
  7948. {
  7949. BfTypeInstance* unspecializedDelegateType = (BfTypeInstance*)unspecializedType;
  7950. BfTypeInstance* unspecializedGenericDelegateType = unspecializedType->ToGenericTypeInstance();
  7951. BfDelegateInfo* unspecializedDelegateInfo = unspecializedType->GetDelegateInfo();
  7952. bool wantGeneric = false;
  7953. bool isUnspecialized = false;
  7954. auto _CheckType = [&](BfType* type)
  7955. {
  7956. if (type->IsTypeGenericParam())
  7957. wantGeneric = true;
  7958. if (type->IsUnspecializedType())
  7959. isUnspecialized = true;
  7960. };
  7961. bool failed = false;
  7962. bool hasTypeGenerics = false;
  7963. auto returnType = ResolveGenericType(unspecializedDelegateInfo->mReturnType, typeGenericArguments, methodGenericArguments, selfType, allowFail);
  7964. if (returnType == NULL)
  7965. return NULL;
  7966. if (returnType->IsVar())
  7967. return returnType;
  7968. _CheckType(returnType);
  7969. if (returnType->IsGenericParam())
  7970. hasTypeGenerics |= ((BfGenericParamType*)returnType)->mGenericParamKind == BfGenericParamKind_Type;
  7971. Array<BfType*> paramTypes;
  7972. for (auto param : unspecializedDelegateInfo->mParams)
  7973. {
  7974. auto paramType = ResolveGenericType(param, typeGenericArguments, methodGenericArguments, selfType, allowFail);
  7975. if (paramType == NULL)
  7976. return NULL;
  7977. if (paramType->IsVar())
  7978. return paramType;
  7979. paramTypes.Add(paramType);
  7980. _CheckType(paramType);
  7981. }
  7982. if (unspecializedGenericDelegateType == NULL)
  7983. wantGeneric = false;
  7984. //TODO:
  7985. wantGeneric = false;
  7986. BfTypeInstance* delegateType = NULL;
  7987. auto baseDelegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  7988. if (wantGeneric)
  7989. {
  7990. Array<BfType*> genericArgs;
  7991. for (int genericArgIdx = 0; genericArgIdx < (int)unspecializedGenericDelegateType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  7992. {
  7993. BfType* resolvedArg = unspecializedGenericDelegateType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx];
  7994. if (resolvedArg->IsUnspecializedType())
  7995. {
  7996. resolvedArg = ResolveGenericType(resolvedArg, typeGenericArguments, methodGenericArguments, selfType, allowFail);
  7997. if (resolvedArg == NULL)
  7998. return NULL;
  7999. if (resolvedArg->IsVar())
  8000. return resolvedArg;
  8001. }
  8002. genericArgs.push_back(resolvedArg);
  8003. }
  8004. auto dlgType = mContext->mDelegateTypePool.Get();
  8005. delete dlgType->mGenericTypeInfo;
  8006. dlgType->mGenericTypeInfo = new BfGenericTypeInfo();
  8007. dlgType->mGenericTypeInfo->mFinishedGenericParams = true;
  8008. dlgType->mGenericTypeInfo->mIsUnspecialized = false;
  8009. dlgType->mGenericTypeInfo->mIsUnspecializedVariation = false;
  8010. dlgType->mGenericTypeInfo->mTypeGenericArguments = genericArgs;
  8011. for (int genericArgIdx = 0; genericArgIdx < (int)unspecializedGenericDelegateType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  8012. {
  8013. auto typeGenericArg = genericArgs[genericArgIdx];
  8014. if ((typeGenericArg->IsGenericParam()) || (typeGenericArg->IsUnspecializedType()))
  8015. dlgType->mGenericTypeInfo->mIsUnspecialized = true;
  8016. dlgType->mGenericTypeInfo->mGenericParams.push_back(unspecializedGenericDelegateType->mGenericTypeInfo->mGenericParams[genericArgIdx]->AddRef());
  8017. }
  8018. CheckUnspecializedGenericType(dlgType, BfPopulateType_Identity);
  8019. if (isUnspecialized)
  8020. {
  8021. dlgType->mGenericTypeInfo->mIsUnspecialized = true;
  8022. dlgType->mGenericTypeInfo->mIsUnspecializedVariation = true;
  8023. }
  8024. dlgType->mIsUnspecializedType = dlgType->mGenericTypeInfo->mIsUnspecialized;
  8025. dlgType->mIsUnspecializedTypeVariation = dlgType->mGenericTypeInfo->mIsUnspecializedVariation;
  8026. delegateType = dlgType;
  8027. }
  8028. else
  8029. {
  8030. auto dlgType = mContext->mDelegateTypePool.Get();
  8031. dlgType->mIsUnspecializedType = isUnspecialized;
  8032. dlgType->mIsUnspecializedTypeVariation = isUnspecialized;
  8033. delegateType = dlgType;
  8034. }
  8035. delete delegateType->mTypeDef;
  8036. delegateType->mTypeDef = NULL;
  8037. BfDelegateInfo* delegateInfo = delegateType->GetDelegateInfo();
  8038. delegateInfo->mParams.Clear();
  8039. BfTypeDef* typeDef = new BfTypeDef();
  8040. typeDef->mProject = baseDelegateType->mTypeDef->mProject;
  8041. typeDef->mSystem = mCompiler->mSystem;
  8042. typeDef->mName = mSystem->mEmptyAtom;
  8043. typeDef->mTypeCode = unspecializedDelegateType->mTypeDef->mTypeCode;
  8044. typeDef->mIsDelegate = unspecializedDelegateType->mTypeDef->mIsDelegate;
  8045. typeDef->mIsFunction = unspecializedDelegateType->mTypeDef->mIsFunction;
  8046. BfMethodDef* unspecializedInvokeMethodDef = unspecializedDelegateType->mTypeDef->GetMethodByName("Invoke");
  8047. BfMethodDef* methodDef = new BfMethodDef();
  8048. methodDef->mDeclaringType = typeDef;
  8049. methodDef->mName = "Invoke";
  8050. methodDef->mProtection = BfProtection_Public;
  8051. methodDef->mIdx = 0;
  8052. methodDef->mIsStatic = !typeDef->mIsDelegate && !unspecializedDelegateInfo->mHasExplicitThis;
  8053. methodDef->mHasExplicitThis = unspecializedDelegateInfo->mHasExplicitThis;
  8054. auto directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  8055. delegateInfo->mDirectAllocNodes.push_back(directTypeRef);
  8056. if (typeDef->mIsDelegate)
  8057. directTypeRef->Init(delegateType);
  8058. else
  8059. directTypeRef->Init(ResolveTypeDef(mCompiler->mFunctionTypeDef));
  8060. typeDef->mBaseTypes.push_back(directTypeRef);
  8061. directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  8062. delegateInfo->mDirectAllocNodes.push_back(directTypeRef);
  8063. directTypeRef->Init(returnType);
  8064. methodDef->mReturnTypeRef = directTypeRef;
  8065. delegateInfo->mReturnType = returnType;
  8066. delegateInfo->mHasExplicitThis = unspecializedDelegateInfo->mHasExplicitThis;
  8067. delegateInfo->mHasVarArgs = unspecializedDelegateInfo->mHasVarArgs;
  8068. int paramIdx = 0;
  8069. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  8070. {
  8071. auto paramType = paramTypes[paramIdx];
  8072. BfParameterDef* unspecializedParamDef = unspecializedInvokeMethodDef->mParams[paramIdx];
  8073. if (!paramType->IsReified())
  8074. delegateType->mIsReified = false;
  8075. auto directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  8076. delegateInfo->mDirectAllocNodes.push_back(directTypeRef);
  8077. directTypeRef->Init(paramType);
  8078. BfParameterDef* paramDef = new BfParameterDef();
  8079. paramDef->mParamKind = unspecializedParamDef->mParamKind;
  8080. paramDef->mTypeRef = directTypeRef;
  8081. paramDef->mName = unspecializedParamDef->mName;
  8082. methodDef->mParams.push_back(paramDef);
  8083. delegateInfo->mParams.Add(paramType);
  8084. }
  8085. typeDef->mMethods.push_back(methodDef);
  8086. if (unspecializedInvokeMethodDef->mIsMutating)
  8087. {
  8088. if ((delegateInfo->mParams[0]->IsValueType()) || (delegateInfo->mParams[0]->IsGenericParam()))
  8089. methodDef->mIsMutating = unspecializedInvokeMethodDef->mIsMutating;
  8090. }
  8091. //
  8092. if (typeDef->mIsDelegate)
  8093. {
  8094. BfDefBuilder::AddMethod(typeDef, BfMethodType_Ctor, BfProtection_Public, false, "");
  8095. BfDefBuilder::AddDynamicCastMethods(typeDef);
  8096. }
  8097. delegateType->mContext = mContext;
  8098. delegateType->mTypeDef = typeDef;
  8099. BfType* resolvedType = NULL;
  8100. if (!failed)
  8101. resolvedType = ResolveType(delegateType, BfPopulateType_Identity);
  8102. if (resolvedType == delegateType)
  8103. {
  8104. AddDependency(directTypeRef->mType, delegateType, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  8105. for (auto paramType : paramTypes)
  8106. AddDependency(paramType, delegateType, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  8107. }
  8108. else
  8109. {
  8110. delegateType->Dispose();
  8111. mContext->mDelegateTypePool.GiveBack((BfDelegateType*)delegateType);
  8112. }
  8113. BF_ASSERT((resolvedType == NULL) || resolvedType->IsTypeInstance() || resolvedType->IsPrimitiveType());
  8114. return resolvedType;
  8115. }
  8116. if (unspecializedType->IsGenericTypeInstance())
  8117. {
  8118. auto genericTypeInst = (BfTypeInstance*)unspecializedType;
  8119. BfTypeVector genericArgs;
  8120. for (auto genericArg : genericTypeInst->mGenericTypeInfo->mTypeGenericArguments)
  8121. {
  8122. if (genericArg->IsUnspecializedType())
  8123. {
  8124. auto resolvedArg = ResolveGenericType(genericArg, typeGenericArguments, methodGenericArguments, selfType, allowFail);
  8125. if (resolvedArg == NULL)
  8126. return NULL;
  8127. if (resolvedArg->IsVar())
  8128. return resolvedArg;
  8129. genericArgs.push_back(resolvedArg);
  8130. }
  8131. else
  8132. genericArgs.push_back(genericArg);
  8133. }
  8134. auto resolvedType = ResolveTypeDef(genericTypeInst->mTypeDef->GetDefinition(), genericArgs, BfPopulateType_BaseType);
  8135. BfTypeInstance* specializedType = NULL;
  8136. if (resolvedType != NULL)
  8137. specializedType = resolvedType->ToGenericTypeInstance();
  8138. if (specializedType != NULL)
  8139. {
  8140. if (specializedType->mGenericTypeInfo->mHadValidateErrors)
  8141. return NULL;
  8142. }
  8143. return specializedType;
  8144. }
  8145. return unspecializedType;
  8146. }
  8147. BfType* BfModule::ResolveSelfType(BfType* type, BfType* selfType)
  8148. {
  8149. if (!type->IsUnspecializedTypeVariation())
  8150. return type;
  8151. return ResolveGenericType(type, NULL, NULL, selfType);
  8152. }
  8153. BfType* BfModule::ResolveType(BfType* lookupType, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  8154. {
  8155. BfResolvedTypeSet::LookupContext lookupCtx;
  8156. lookupCtx.mModule = this;
  8157. lookupCtx.mResolveFlags = resolveFlags;
  8158. BfResolvedTypeSet::EntryRef resolvedEntry;
  8159. bool inserted = mContext->mResolvedTypes.Insert(lookupType, &lookupCtx, &resolvedEntry);
  8160. if (!resolvedEntry)
  8161. return NULL;
  8162. if (!inserted)
  8163. {
  8164. auto resolvedTypeRef = resolvedEntry->mValue;
  8165. PopulateType(resolvedTypeRef, populateType);
  8166. return resolvedTypeRef;
  8167. }
  8168. if (lookupType->IsGenericTypeInstance())
  8169. CheckUnspecializedGenericType((BfTypeInstance*)lookupType, populateType);
  8170. if (lookupType->IsTuple())
  8171. {
  8172. auto tupleType = (BfTupleType*)lookupType;
  8173. tupleType->Finish();
  8174. }
  8175. resolvedEntry->mValue = lookupType;
  8176. InitType(lookupType, populateType);
  8177. return lookupType;
  8178. }
  8179. bool BfModule::IsUnboundGeneric(BfType* type)
  8180. {
  8181. if (type->IsVar())
  8182. return true;
  8183. if (!type->IsGenericParam())
  8184. return false;
  8185. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)type);
  8186. return (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0;
  8187. }
  8188. BfGenericParamInstance* BfModule::GetGenericTypeParamInstance(int genericParamIdx)
  8189. {
  8190. // When we're evaluating a method, make sure the params refer back to that method context
  8191. auto curTypeInstance = mCurTypeInstance;
  8192. //TODO: This caused MethodToString issues with interface "implementation method not found" errors
  8193. // if (mCurMethodInstance != NULL)
  8194. // curTypeInstance = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  8195. BfTypeInstance* genericTypeInst = curTypeInstance->ToGenericTypeInstance();
  8196. if ((genericTypeInst->IsIncomplete()) && (genericTypeInst->mGenericTypeInfo->mGenericParams.size() == 0))
  8197. {
  8198. // Set this to NULL so we don't recurse infinitely
  8199. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, NULL);
  8200. PopulateType(genericTypeInst, BfPopulateType_Declaration);
  8201. }
  8202. if (genericParamIdx >= (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size())
  8203. {
  8204. if (genericParamIdx >= genericTypeInst->mGenericTypeInfo->mGenericParams.mSize)
  8205. FatalError("Invalid GetGenericTypeParamInstance");
  8206. // Extern constraints should always be directly used - they don't get extended
  8207. return genericTypeInst->mGenericTypeInfo->mGenericParams[genericParamIdx];
  8208. }
  8209. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  8210. {
  8211. bool isAutocomplete = (mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mAutoComplete != NULL);
  8212. auto activeTypeDef = GetActiveTypeDef(NULL, true);
  8213. if ((activeTypeDef->mTypeDeclaration != genericTypeInst->mTypeDef->mTypeDeclaration) && (activeTypeDef->IsExtension()) &&
  8214. ((genericTypeInst->mTypeDef->ContainsPartial(activeTypeDef)) || (isAutocomplete)))
  8215. {
  8216. BfTypeDef* lookupTypeDef = activeTypeDef;
  8217. while (lookupTypeDef->mNestDepth > genericTypeInst->mTypeDef->mNestDepth)
  8218. lookupTypeDef = lookupTypeDef->mOuterType;
  8219. BfGenericExtensionEntry* genericExEntry;
  8220. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.TryGetValue(lookupTypeDef, &genericExEntry))
  8221. {
  8222. return genericExEntry->mGenericParams[genericParamIdx];
  8223. }
  8224. else
  8225. {
  8226. if (!isAutocomplete)
  8227. {
  8228. FatalError("Invalid GetGenericParamInstance with extension");
  8229. }
  8230. }
  8231. }
  8232. }
  8233. BF_ASSERT(genericTypeInst != NULL);
  8234. return genericTypeInst->mGenericTypeInfo->mGenericParams[genericParamIdx];
  8235. }
  8236. void BfModule::GetActiveTypeGenericParamInstances(SizedArray<BfGenericParamInstance*, 4>& genericParamInstances)
  8237. {
  8238. // When we're evaluating a method, make sure the params refer back to that method context
  8239. auto curTypeInstance = mCurTypeInstance;
  8240. if (mCurMethodInstance != NULL)
  8241. curTypeInstance = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  8242. BfTypeInstance* genericTypeInst = curTypeInstance->ToGenericTypeInstance();
  8243. if ((genericTypeInst->IsIncomplete()) && (genericTypeInst->mGenericTypeInfo->mGenericParams.size() == 0))
  8244. {
  8245. // Set this to NULL so we don't recurse infinitely
  8246. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mCurTypeInstance, NULL);
  8247. PopulateType(genericTypeInst, BfPopulateType_Declaration);
  8248. }
  8249. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  8250. {
  8251. auto activeTypeDef = GetActiveTypeDef(NULL, true);
  8252. if ((activeTypeDef->mTypeDeclaration != genericTypeInst->mTypeDef->mTypeDeclaration) && (activeTypeDef->IsExtension()))
  8253. {
  8254. BfTypeDef* lookupTypeDef = activeTypeDef;
  8255. while (lookupTypeDef->mNestDepth > genericTypeInst->mTypeDef->mNestDepth)
  8256. lookupTypeDef = lookupTypeDef->mOuterType;
  8257. BfGenericExtensionEntry* genericExEntry;
  8258. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.TryGetValue(lookupTypeDef, &genericExEntry))
  8259. {
  8260. for (auto entry : genericExEntry->mGenericParams)
  8261. genericParamInstances.Add(entry);
  8262. auto genericTypeInfo = genericTypeInst->mGenericTypeInfo;
  8263. // Add root extern constraints - they don't get extended
  8264. for (int genericParamIdx = (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size(); genericParamIdx < genericTypeInst->mGenericTypeInfo->mGenericParams.size(); genericParamIdx++)
  8265. genericParamInstances.Add(genericTypeInst->mGenericTypeInfo->mGenericParams[genericParamIdx]);
  8266. return;
  8267. }
  8268. else
  8269. {
  8270. if ((mCompiler->mResolvePassData == NULL) || (mCompiler->mResolvePassData->mAutoComplete == NULL))
  8271. {
  8272. BFMODULE_FATAL(this, "Invalid GetGenericParamInstance with extension");
  8273. }
  8274. }
  8275. }
  8276. }
  8277. BF_ASSERT(genericTypeInst != NULL);
  8278. for (auto entry : genericTypeInst->mGenericTypeInfo->mGenericParams)
  8279. genericParamInstances.Add(entry);
  8280. }
  8281. BfGenericParamInstance* BfModule::GetMergedGenericParamData(BfGenericParamType* type, BfGenericParamFlags& outFlags, BfType*& outTypeConstraint)
  8282. {
  8283. BfGenericParamInstance* genericParam = GetGenericParamInstance(type);
  8284. outFlags = genericParam->mGenericParamFlags;
  8285. outTypeConstraint = genericParam->mTypeConstraint;
  8286. // Check method generic constraints
  8287. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mMethodInfoEx != NULL))
  8288. {
  8289. for (int genericParamIdx = (int)mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  8290. genericParamIdx < mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  8291. {
  8292. auto genericParam = mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  8293. if (genericParam->mExternType == type)
  8294. {
  8295. outFlags = (BfGenericParamFlags)(outFlags | genericParam->mGenericParamFlags);
  8296. if (genericParam->mTypeConstraint != NULL)
  8297. outTypeConstraint = genericParam->mTypeConstraint;
  8298. }
  8299. }
  8300. }
  8301. return genericParam;
  8302. }
  8303. BfGenericParamInstance* BfModule::GetGenericParamInstance(BfGenericParamType* type, bool checkMixinBind, BfFailHandleKind failHandleKind)
  8304. {
  8305. if (type->mGenericParamKind == BfGenericParamKind_Method)
  8306. {
  8307. auto curGenericMethodInstance = mCurMethodInstance;
  8308. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  8309. {
  8310. if ((checkMixinBind) || (mCurMethodState->mMixinState->mUseMixinGenerics))
  8311. curGenericMethodInstance = mCurMethodState->mMixinState->mMixinMethodInstance;
  8312. }
  8313. if ((curGenericMethodInstance == NULL) || (curGenericMethodInstance->mMethodInfoEx == NULL) || (type->mGenericParamIdx >= curGenericMethodInstance->mMethodInfoEx->mGenericParams.mSize))
  8314. {
  8315. if (failHandleKind == Beefy::BfFailHandleKind_Normal)
  8316. FatalError("Invalid GetGenericParamInstance method generic param");
  8317. else if (failHandleKind == Beefy::BfFailHandleKind_Soft)
  8318. InternalError("Invalid GetGenericParamInstance method generic param");
  8319. return NULL;
  8320. }
  8321. return curGenericMethodInstance->mMethodInfoEx->mGenericParams[type->mGenericParamIdx];
  8322. }
  8323. return GetGenericTypeParamInstance(type->mGenericParamIdx);
  8324. }
  8325. bool BfModule::ResolveTypeResult_Validate(BfAstNode* typeRef, BfType* resolvedTypeRef)
  8326. {
  8327. if ((typeRef == NULL) || (resolvedTypeRef == NULL))
  8328. return true;
  8329. BfTypeInstance* genericTypeInstance = resolvedTypeRef->ToGenericTypeInstance();
  8330. if ((genericTypeInstance != NULL) && (genericTypeInstance != mCurTypeInstance))
  8331. {
  8332. bool doValidate = (genericTypeInstance->mGenericTypeInfo->mHadValidateErrors) ||
  8333. (!genericTypeInstance->mGenericTypeInfo->mValidatedGenericConstraints) ||
  8334. (genericTypeInstance->mGenericTypeInfo->mIsUnspecializedVariation);
  8335. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->IsOrInUnspecializedVariation()))
  8336. doValidate = false;
  8337. if (mCurTypeInstance != NULL)
  8338. {
  8339. if (mCurTypeInstance->IsUnspecializedTypeVariation())
  8340. doValidate = false;
  8341. if (auto curGenericTypeInstance = mCurTypeInstance->ToGenericTypeInstance())
  8342. {
  8343. if ((curGenericTypeInstance->mDependencyMap.mMinDependDepth > 32) &&
  8344. (genericTypeInstance->mDependencyMap.mMinDependDepth > 32))
  8345. {
  8346. Fail(StrFormat("Generic type dependency depth exceeded for type '%s'", TypeToString(genericTypeInstance).c_str()), typeRef);
  8347. return false;
  8348. }
  8349. if (curGenericTypeInstance->mGenericTypeInfo->mHadValidateErrors)
  8350. doValidate = false;
  8351. }
  8352. if ((mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mCurBaseTypeRef != NULL) && (!mContext->mCurTypeState->mType->IsTypeAlias())) // We validate constraints for base types later
  8353. doValidate = false;
  8354. }
  8355. if (doValidate)
  8356. ValidateGenericConstraints(typeRef, genericTypeInstance, false);
  8357. }
  8358. if (auto genericInstanceTypeRef = BfNodeDynCastExact<BfGenericInstanceTypeRef>(typeRef))
  8359. {
  8360. if (genericTypeInstance != NULL)
  8361. {
  8362. auto genericTypeInfo = genericTypeInstance->GetGenericTypeInfo();
  8363. for (int argIdx = 0; argIdx < (int)genericInstanceTypeRef->mGenericArguments.size(); argIdx++)
  8364. {
  8365. ResolveTypeResult_Validate(genericInstanceTypeRef->mGenericArguments[argIdx], genericTypeInfo->mTypeGenericArguments[argIdx]);
  8366. }
  8367. }
  8368. }
  8369. else if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(typeRef))
  8370. {
  8371. return ResolveTypeResult_Validate(elementedTypeRef, resolvedTypeRef->GetUnderlyingType());
  8372. }
  8373. return true;
  8374. }
  8375. BfType* BfModule::SafeResolveAliasType(BfTypeAliasType* aliasType)
  8376. {
  8377. int aliasDepth = 0;
  8378. HashSet<BfType*> seenAliases;
  8379. BfType* type = aliasType;
  8380. while (type->IsTypeAlias())
  8381. {
  8382. aliasDepth++;
  8383. if (aliasDepth > 8)
  8384. {
  8385. if (!seenAliases.Add(type))
  8386. return NULL;
  8387. }
  8388. type = type->GetUnderlyingType();
  8389. if (type == NULL)
  8390. return NULL;
  8391. }
  8392. return type;
  8393. }
  8394. BfType* BfModule::ResolveTypeResult(BfTypeReference* typeRef, BfType* resolvedTypeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  8395. {
  8396. if ((mCompiler->mIsResolveOnly) && (!IsInSpecializedSection()))
  8397. {
  8398. bool isGetDefinition = false;
  8399. BfAutoComplete* autoComplete = NULL;
  8400. if (mCompiler->IsAutocomplete())
  8401. {
  8402. autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  8403. isGetDefinition = autoComplete->mIsGetDefinition || (autoComplete->mResolveType == BfResolveType_GetResultString);
  8404. }
  8405. BfSourceData* typeRefSource = NULL;
  8406. if (typeRef->IsTemporary())
  8407. {
  8408. BfTypeReference* checkTypeRef = typeRef;
  8409. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(checkTypeRef))
  8410. checkTypeRef = genericTypeRef->mElementType;
  8411. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(checkTypeRef))
  8412. typeRefSource = namedTypeRef->mNameNode->GetSourceData();
  8413. }
  8414. else
  8415. typeRefSource = typeRef->GetSourceData();
  8416. BfSourceClassifier* sourceClassifier = NULL;
  8417. if ((mCompiler->mResolvePassData->mIsClassifying) && (typeRefSource != NULL))
  8418. {
  8419. auto parser = typeRefSource->ToParser();
  8420. if (parser != NULL)
  8421. sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(parser);
  8422. }
  8423. bool wantsFileNamespaceInfo = ((sourceClassifier != NULL) || (isGetDefinition) || (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Namespace));
  8424. bool wantsAllNamespaceInfo = (mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Namespace) && (mCompiler->mResolvePassData->mParsers.IsEmpty());
  8425. if (wantsFileNamespaceInfo || wantsAllNamespaceInfo)
  8426. {
  8427. //TODO: By only breaking out for "mIgnoreErrors", we classified elements (below) even when a resolvedTypeRef was not found!
  8428. //Why did we have this mIgnoreErrors check in there?
  8429. // if ((resolvedTypeRef == NULL) && (mIgnoreErrors))
  8430. if (resolvedTypeRef == NULL)
  8431. {
  8432. return NULL;
  8433. }
  8434. BfTypeInstance* resolvedTypeInstance = NULL;
  8435. if (resolvedTypeRef != NULL)
  8436. resolvedTypeInstance = resolvedTypeRef->ToTypeInstance();
  8437. bool isNamespace = false;
  8438. auto checkTypeRef = typeRef;
  8439. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(checkTypeRef))
  8440. checkTypeRef = genericTypeRef->mElementType;
  8441. auto headTypeRef = checkTypeRef;
  8442. if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(checkTypeRef))
  8443. checkTypeRef = elementedTypeRef->mElementType;
  8444. if (!mIsInsideAutoComplete)
  8445. {
  8446. if ((resolvedTypeInstance != NULL) && (resolvedTypeInstance->mTypeDef->IsGlobalsContainer()))
  8447. {
  8448. isNamespace = true;
  8449. }
  8450. else
  8451. {
  8452. //TODO: This broke colorizing of inner expressions for things like "T2[T3]"
  8453. //mCompiler->mResolvePassData->mSourceClassifier->VisitChildNoRef(typeRef);
  8454. }
  8455. }
  8456. BfSourceElementType elemType = BfSourceElementType_Type;
  8457. {
  8458. auto type = resolvedTypeRef;
  8459. if (type->IsTypeAlias())
  8460. {
  8461. type = SafeResolveAliasType((BfTypeAliasType*)type);
  8462. if (type == NULL)
  8463. type = resolvedTypeRef;
  8464. }
  8465. if (type->IsInterface())
  8466. elemType = BfSourceElementType_Interface;
  8467. else if (type->IsObject())
  8468. elemType = BfSourceElementType_RefType;
  8469. else if (type->IsGenericParam())
  8470. elemType = BfSourceElementType_GenericParam;
  8471. else if (type->IsPrimitiveType())
  8472. elemType = BfSourceElementType_PrimitiveType;
  8473. else if (type->IsStruct() || (type->IsTypedPrimitive() && !type->IsEnum()))
  8474. elemType = BfSourceElementType_Struct;
  8475. }
  8476. while (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(checkTypeRef))
  8477. {
  8478. if ((sourceClassifier != NULL) && (checkTypeRef == headTypeRef) && (elemType != BfSourceElementType_Type))
  8479. sourceClassifier->SetElementType(qualifiedTypeRef->mRight, elemType);
  8480. StringView leftString = qualifiedTypeRef->mLeft->ToStringView();
  8481. BfSizedAtomComposite leftComposite;
  8482. bool isValid = mSystem->ParseAtomComposite(leftString, leftComposite);
  8483. if (sourceClassifier != NULL)
  8484. sourceClassifier->SetHighestElementType(qualifiedTypeRef->mRight, isNamespace ? BfSourceElementType_Namespace : BfSourceElementType_Type);
  8485. if (resolvedTypeInstance == NULL)
  8486. {
  8487. if ((isValid) && (mCompiler->mSystem->ContainsNamespace(leftComposite, mCurTypeInstance->mTypeDef->mProject)))
  8488. isNamespace = true;
  8489. }
  8490. else if ((isValid) && (resolvedTypeInstance->mTypeDef->mNamespace.EndsWith(leftComposite)) && (resolvedTypeInstance->mTypeDef->mOuterType == NULL))
  8491. {
  8492. if (autoComplete != NULL)
  8493. {
  8494. if (autoComplete->CheckFixit(typeRef))
  8495. autoComplete->FixitCheckNamespace(GetActiveTypeDef(), qualifiedTypeRef->mLeft, qualifiedTypeRef->mDot);
  8496. autoComplete->CheckNamespace(qualifiedTypeRef->mLeft, resolvedTypeInstance->mTypeDef->mNamespace);
  8497. }
  8498. mCompiler->mResolvePassData->HandleNamespaceReference(qualifiedTypeRef->mLeft, resolvedTypeInstance->mTypeDef->mNamespace);
  8499. isNamespace = true;
  8500. }
  8501. checkTypeRef = qualifiedTypeRef->mLeft;
  8502. }
  8503. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(checkTypeRef))
  8504. {
  8505. auto checkNameNode = namedTypeRef->mNameNode;
  8506. bool setType = false;
  8507. if ((sourceClassifier != NULL) && (checkTypeRef == headTypeRef) && (elemType != BfSourceElementType_Type))
  8508. {
  8509. if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(checkNameNode))
  8510. {
  8511. sourceClassifier->SetElementType(qualifiedNameNode->mRight, elemType);
  8512. }
  8513. else
  8514. {
  8515. setType = true;
  8516. sourceClassifier->SetElementType(checkNameNode, elemType);
  8517. }
  8518. }
  8519. while (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(checkNameNode))
  8520. {
  8521. StringView leftString = qualifiedNameNode->mLeft->ToStringView();
  8522. BfSizedAtomComposite leftComposite;
  8523. bool isValid = mSystem->ParseAtomComposite(leftString, leftComposite);
  8524. if (sourceClassifier != NULL)
  8525. sourceClassifier->SetHighestElementType(qualifiedNameNode->mRight, isNamespace ? BfSourceElementType_Namespace : BfSourceElementType_Type);
  8526. if (resolvedTypeInstance == NULL)
  8527. {
  8528. if ((isValid) && (mCompiler->mSystem->ContainsNamespace(leftComposite, mCurTypeInstance->mTypeDef->mProject)))
  8529. isNamespace = true;
  8530. }
  8531. else if ((isValid) && (resolvedTypeInstance->mTypeDef->mOuterType == NULL) && (resolvedTypeInstance->mTypeDef->mNamespace.EndsWith(leftComposite)))
  8532. {
  8533. if (autoComplete != NULL)
  8534. {
  8535. if (autoComplete->CheckFixit(typeRef))
  8536. autoComplete->FixitCheckNamespace(GetActiveTypeDef(), qualifiedNameNode->mLeft, qualifiedNameNode->mDot);
  8537. autoComplete->CheckNamespace(qualifiedNameNode->mLeft, resolvedTypeInstance->mTypeDef->mNamespace);
  8538. }
  8539. mCompiler->mResolvePassData->HandleNamespaceReference(qualifiedNameNode->mLeft, resolvedTypeInstance->mTypeDef->mNamespace);
  8540. isNamespace = true;
  8541. }
  8542. checkNameNode = qualifiedNameNode->mLeft;
  8543. }
  8544. if ((sourceClassifier != NULL) &&
  8545. ((!setType) || (checkNameNode != namedTypeRef->mNameNode)))
  8546. sourceClassifier->SetHighestElementType(checkNameNode, isNamespace ? BfSourceElementType_Namespace : BfSourceElementType_Type);
  8547. }
  8548. }
  8549. if (((mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Type) || (isGetDefinition)) &&
  8550. ((resolveFlags & BfResolveTypeRefFlag_FromIndirectSource) == 0) && (resolvedTypeRef != NULL) && (typeRefSource != NULL))
  8551. {
  8552. BfAstNode* elementTypeRef = typeRef;
  8553. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(elementTypeRef))
  8554. elementTypeRef = namedTypeRef->mNameNode;
  8555. if (elementTypeRef != NULL)
  8556. {
  8557. BfType* elementType = resolvedTypeRef;
  8558. if (BfTypeInstance* elementTypeInst = elementType->ToTypeInstance())
  8559. {
  8560. mCompiler->mResolvePassData->HandleTypeReference(elementTypeRef, elementTypeInst->mTypeDef);
  8561. if (mCompiler->IsAutocomplete())
  8562. {
  8563. BfAutoComplete* autoComplete = mCompiler->mResolvePassData->mAutoComplete;
  8564. if ((isGetDefinition) && (autoComplete->IsAutocompleteNode(elementTypeRef)))
  8565. {
  8566. BfAstNode* baseNode = elementTypeRef;
  8567. while (true)
  8568. {
  8569. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(baseNode))
  8570. {
  8571. baseNode = qualifiedTypeRef->mRight;
  8572. }
  8573. else if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(baseNode))
  8574. {
  8575. baseNode = elementedTypeRef->mElementType;
  8576. }
  8577. else if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(baseNode))
  8578. {
  8579. baseNode = namedTypeRef->mNameNode;
  8580. }
  8581. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(baseNode))
  8582. {
  8583. baseNode = qualifiedNameNode->mRight;
  8584. }
  8585. else if (auto declTypeRef = BfNodeDynCast<BfExprModTypeRef>(baseNode))
  8586. {
  8587. baseNode = NULL;
  8588. break;
  8589. }
  8590. else
  8591. break;
  8592. }
  8593. if ((baseNode != NULL) && (autoComplete->IsAutocompleteNode(baseNode)))
  8594. {
  8595. // We didn't have this mDefType check before - why? We always want to catch the FIRST definition,
  8596. // so 'Type?' will catch on 'Type' and not 'Type?'
  8597. if ((autoComplete->mDefType == NULL) &&
  8598. (autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  8599. (autoComplete->mDefProp == NULL) && (elementTypeInst->mTypeDef->mTypeDeclaration != NULL))
  8600. {
  8601. autoComplete->mDefType = elementTypeInst->mTypeDef;
  8602. autoComplete->SetDefinitionLocation(elementTypeInst->mTypeDef->mTypeDeclaration->mNameNode);
  8603. }
  8604. if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (resolvedTypeRef != NULL))
  8605. {
  8606. autoComplete->SetResultStringType(resolvedTypeRef);
  8607. }
  8608. }
  8609. }
  8610. }
  8611. }
  8612. }
  8613. }
  8614. }
  8615. if (resolvedTypeRef == NULL)
  8616. return NULL;
  8617. if (mCurTypeInstance == NULL)
  8618. {
  8619. // No deps
  8620. }
  8621. else if (resolvedTypeRef->IsTuple())
  8622. {
  8623. // Add the fields from the tuple as references since those inner fields types would have been explicitly stated, so we need
  8624. // to make sure to record the current type instance as a referring type. This mostly matters for symbol renaming.
  8625. BfTypeInstance* payloadTupleType = (BfTypeInstance*)resolvedTypeRef;
  8626. for (auto& payloadFieldInst : payloadTupleType->mFieldInstances)
  8627. {
  8628. auto payloadFieldType = payloadFieldInst.mResolvedType;
  8629. AddDependency(payloadFieldType, mCurTypeInstance, BfDependencyMap::DependencyFlag_TypeReference);
  8630. }
  8631. }
  8632. else if (resolvedTypeRef->IsDelegateFromTypeRef() || resolvedTypeRef->IsFunctionFromTypeRef())
  8633. {
  8634. auto delegateInfo = resolvedTypeRef->GetDelegateInfo();
  8635. // if (delegateInfo->mFunctionThisType != NULL)
  8636. // AddDependency(delegateInfo->mFunctionThisType, mCurTypeInstance, BfDependencyMap::DependencyFlag_TypeReference);
  8637. AddDependency(delegateInfo->mReturnType, mCurTypeInstance, BfDependencyMap::DependencyFlag_TypeReference);
  8638. for (auto& param : delegateInfo->mParams)
  8639. AddDependency(param, mCurTypeInstance, BfDependencyMap::DependencyFlag_TypeReference);
  8640. }
  8641. BfTypeInstance* typeInstance = resolvedTypeRef->ToTypeInstance();
  8642. BfTypeInstance* genericTypeInstance = resolvedTypeRef->ToGenericTypeInstance();
  8643. auto populateModule = this;
  8644. if ((resolveFlags & BfResolveTypeRefFlag_NoReify) != 0)
  8645. populateModule = mContext->mUnreifiedModule;
  8646. populateModule->PopulateType(resolvedTypeRef, populateType);
  8647. if ((typeInstance != NULL) && (typeInstance->mTypeDef != NULL) && (typeInstance->mTypeDef->mProtection == BfProtection_Internal) &&
  8648. (typeInstance != mCurTypeInstance) && (typeInstance->mTypeDef->mOuterType == NULL) && (!typeRef->IsTemporary()))
  8649. {
  8650. if (!CheckProtection(typeInstance->mTypeDef->mProtection, typeInstance->mTypeDef, false, false))
  8651. Fail(StrFormat("'%s' is inaccessible due to its protection level", TypeToString(typeInstance).c_str()), typeRef); // CS0122
  8652. }
  8653. // If the inner type is definted in an extension then we need to make sure the constraints are good
  8654. if ((typeInstance != NULL) && (typeInstance->mTypeDef != NULL) && (typeInstance->mTypeDef->mOuterType != NULL) &&
  8655. (typeInstance->mTypeDef->mOuterType->mTypeCode == BfTypeCode_Extension))
  8656. {
  8657. auto outerType = GetOuterType(typeInstance);
  8658. if ((outerType->mGenericTypeInfo != NULL) && (outerType->mGenericTypeInfo->mGenericExtensionInfo != NULL))
  8659. {
  8660. if (!outerType->mGenericTypeInfo->mGenericExtensionInfo->mConstraintsPassedSet.IsSet(typeInstance->mTypeDef->mOuterType->mPartialIdx))
  8661. {
  8662. Fail(StrFormat("'%s' is declared inside a type extension whose constraints were not met", TypeToString(typeInstance).c_str()), typeRef);
  8663. }
  8664. }
  8665. }
  8666. if (populateType > BfPopulateType_IdentityNoRemapAlias)
  8667. {
  8668. if (!ResolveTypeResult_Validate(typeRef, resolvedTypeRef))
  8669. return NULL;
  8670. }
  8671. if ((populateType != BfPopulateType_TypeDef) && (populateType != BfPopulateType_IdentityNoRemapAlias))
  8672. {
  8673. int aliasDepth = 0;
  8674. HashSet<BfType*> seenAliases;
  8675. while ((resolvedTypeRef != NULL) && (resolvedTypeRef->IsTypeAlias()))
  8676. {
  8677. aliasDepth++;
  8678. if (aliasDepth > 8)
  8679. {
  8680. if (!seenAliases.Add(resolvedTypeRef))
  8681. {
  8682. if ((typeRef != NULL) && (!typeRef->IsTemporary()))
  8683. Fail(StrFormat("Type alias '%s' has a recursive definition", TypeToString(resolvedTypeRef).c_str()), typeRef);
  8684. break;
  8685. }
  8686. }
  8687. if (mCurTypeInstance != NULL)
  8688. AddDependency(resolvedTypeRef, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  8689. if (resolvedTypeRef->mDefineState == BfTypeDefineState_Undefined)
  8690. PopulateType(resolvedTypeRef);
  8691. if ((typeInstance->mCustomAttributes != NULL) && (!typeRef->IsTemporary()))
  8692. CheckErrorAttributes(typeInstance, NULL, NULL, typeInstance->mCustomAttributes, typeRef);
  8693. resolvedTypeRef = resolvedTypeRef->GetUnderlyingType();
  8694. if (resolvedTypeRef != NULL)
  8695. typeInstance = resolvedTypeRef->ToTypeInstance();
  8696. else
  8697. typeInstance = NULL;
  8698. }
  8699. }
  8700. if (typeInstance != NULL)
  8701. {
  8702. if ((!typeRef->IsTemporary()) && ((resolveFlags & BfResolveTypeRefFlag_FromIndirectSource) == 0))
  8703. {
  8704. if (typeInstance->mCustomAttributes != NULL)
  8705. CheckErrorAttributes(typeInstance, NULL, NULL, typeInstance->mCustomAttributes, typeRef);
  8706. else if ((typeInstance->mTypeDef->mTypeDeclaration != NULL) && (typeInstance->mTypeDef->mTypeDeclaration->mAttributes != NULL))
  8707. {
  8708. auto typeRefVerifyRequest = mContext->mTypeRefVerifyWorkList.Alloc();
  8709. typeRefVerifyRequest->mCurTypeInstance = mCurTypeInstance;
  8710. typeRefVerifyRequest->mRefNode = typeRef;
  8711. typeRefVerifyRequest->mType = typeInstance;
  8712. typeRefVerifyRequest->mFromModule = this;
  8713. typeRefVerifyRequest->mFromModuleRevision = mRevision;
  8714. }
  8715. }
  8716. if (typeInstance->IsTuple())
  8717. {
  8718. //TODO: This can cause circular reference issues. Is there a case this is needed?
  8719. //if (typeInstance->mDefineState < BfTypeDefineState_Defined)
  8720. // PopulateType(typeInstance);
  8721. if (typeInstance->mHasDeclError)
  8722. {
  8723. if (auto tupleTypeRef = BfNodeDynCast<BfTupleTypeRef>(typeRef))
  8724. {
  8725. HashSet<String> names;
  8726. for (auto nameIdentifier : tupleTypeRef->mFieldNames)
  8727. {
  8728. if (nameIdentifier == NULL)
  8729. continue;
  8730. StringT<64> fieldName;
  8731. nameIdentifier->ToString(fieldName);
  8732. if (!names.Add(fieldName))
  8733. {
  8734. Fail(StrFormat("A field named '%s' has already been declared", fieldName.c_str()), nameIdentifier);
  8735. }
  8736. }
  8737. }
  8738. }
  8739. }
  8740. }
  8741. return resolvedTypeRef;
  8742. }
  8743. void BfModule::ShowAmbiguousTypeError(BfAstNode* refNode, BfTypeDef* typeDef, BfTypeDef* otherTypeDef)
  8744. {
  8745. BfType* type = ResolveTypeDef(typeDef, BfPopulateType_Identity);
  8746. if (type == NULL)
  8747. return;
  8748. BfType* otherType = ResolveTypeDef(otherTypeDef, BfPopulateType_Identity);
  8749. if (otherType == NULL)
  8750. return;
  8751. auto error = Fail(StrFormat("'%s' is an ambiguous reference between '%s' and '%s'",
  8752. refNode->ToString().c_str(), TypeToString(type, BfTypeNameFlags_None).c_str(), TypeToString(otherType, BfTypeNameFlags_None).c_str()), refNode); // CS0104
  8753. if (error != NULL)
  8754. {
  8755. mCompiler->mPassInstance->MoreInfo("See first definition", typeDef->mTypeDeclaration->mNameNode);
  8756. mCompiler->mPassInstance->MoreInfo("See second definition", otherTypeDef->mTypeDeclaration->mNameNode);
  8757. }
  8758. }
  8759. void BfModule::ShowGenericArgCountError(BfAstNode* typeRef, int wantedGenericParams)
  8760. {
  8761. BfGenericInstanceTypeRef* genericTypeInstRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef);
  8762. BfAstNode* lastNode = typeRef;
  8763. int genericArgDiffCount;
  8764. if (genericTypeInstRef != NULL)
  8765. {
  8766. genericArgDiffCount = (int)genericTypeInstRef->mGenericArguments.size() - wantedGenericParams;
  8767. lastNode = genericTypeInstRef->mOpenChevron;
  8768. if (genericTypeInstRef->mCloseChevron != NULL)
  8769. lastNode = genericTypeInstRef->mCloseChevron;
  8770. if (genericTypeInstRef->mGenericArguments.size() > wantedGenericParams)
  8771. {
  8772. lastNode = genericTypeInstRef->mGenericArguments[wantedGenericParams];
  8773. if (genericArgDiffCount == 1)
  8774. Fail("Too many generic parameters, expected one fewer", lastNode);
  8775. else
  8776. Fail(StrFormat("Too many generic parameters, expected %d fewer", genericArgDiffCount), lastNode);
  8777. return;
  8778. }
  8779. }
  8780. else
  8781. genericArgDiffCount = -wantedGenericParams;
  8782. if (wantedGenericParams == 1)
  8783. Fail("Too few generic parameters, expected one more", lastNode);
  8784. else
  8785. Fail(StrFormat("Too few generic parameters, expected %d more", -genericArgDiffCount), lastNode);
  8786. }
  8787. BfTypeDef* BfModule::GetActiveTypeDef(BfTypeInstance* typeInstanceOverride, bool useMixinDecl, bool useForeignImpl)
  8788. {
  8789. BfTypeDef* useTypeDef = NULL;
  8790. BfTypeInstance* typeInstance = (typeInstanceOverride != NULL) ? typeInstanceOverride : mCurTypeInstance;
  8791. if ((mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mForceActiveTypeDef != NULL))
  8792. return mContext->mCurTypeState->mForceActiveTypeDef;
  8793. if (typeInstance != NULL)
  8794. useTypeDef = typeInstance->mTypeDef->GetDefinition();
  8795. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL) && (useMixinDecl))
  8796. useTypeDef = mCurMethodState->mMixinState->mMixinMethodInstance->mMethodDef->mDeclaringType->GetDefinition();
  8797. else if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mMethodDef->mDeclaringType != NULL))
  8798. {
  8799. if ((mCurMethodInstance->mIsForeignMethodDef) && (useForeignImpl))
  8800. {
  8801. // Use the concrete impl typeDef, not the foreign method typedecl (the interface)
  8802. }
  8803. else
  8804. {
  8805. auto declTypeDef = mCurMethodInstance->mMethodDef->mDeclaringType;
  8806. useTypeDef = declTypeDef->GetDefinition(true);
  8807. if ((declTypeDef->IsEmitted()) && (useTypeDef->mIsCombinedPartial))
  8808. {
  8809. // Always consider methods to belong to the primary type declaration
  8810. useTypeDef = useTypeDef->mPartials[0];
  8811. }
  8812. }
  8813. }
  8814. else if (mContext->mCurTypeState != NULL)
  8815. {
  8816. if ((mContext->mCurTypeState->mCurFieldDef != NULL) && (mContext->mCurTypeState->mCurFieldDef->mDeclaringType != NULL))
  8817. useTypeDef = mContext->mCurTypeState->mCurFieldDef->mDeclaringType->GetDefinition(true);
  8818. else if (mContext->mCurTypeState->mCurTypeDef != NULL)
  8819. useTypeDef = mContext->mCurTypeState->mCurTypeDef->GetDefinition(true);
  8820. }
  8821. return useTypeDef;
  8822. }
  8823. BfTypeDef* BfModule::FindTypeDefRaw(const BfAtomComposite& findName, int numGenericArgs, BfTypeInstance* typeInstance, BfTypeDef* useTypeDef, BfTypeLookupError* error, BfTypeLookupResultCtx* lookupResultCtx, BfResolveTypeRefFlags resolveFlags)
  8824. {
  8825. if ((findName.mSize == 1) && (findName.mParts[0]->mIsSystemType))
  8826. {
  8827. //BP_ZONE("BfModule::FindTypeDefRaw_1");
  8828. return mSystem->FindTypeDef(findName, 0, useTypeDef->mProject);
  8829. }
  8830. BfTypeInstance* skipCheckBaseType = NULL;
  8831. if (mContext->mCurTypeState != NULL)
  8832. {
  8833. if (mContext->mCurTypeState->mCurBaseTypeRef != NULL)
  8834. skipCheckBaseType = mContext->mCurTypeState->mType->ToTypeInstance();
  8835. if (mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_BuildingGenericParams)
  8836. skipCheckBaseType = mContext->mCurTypeState->mType->ToTypeInstance();
  8837. }
  8838. BfProject* useProject = useTypeDef->mProject;
  8839. BfTypeDefLookupContext lookupCtx;
  8840. bool allowPrivate = true;
  8841. int curPri = 1000;
  8842. auto checkTypeInst = typeInstance;
  8843. BfTypeDef* protErrorTypeDef = NULL;
  8844. BfTypeInstance* protErrorOuterType = NULL;
  8845. BfTypeDef* foundInnerType = NULL;
  8846. if ((resolveFlags & BfResolveTypeRefFlag_SpecializedProject) != 0)
  8847. {
  8848. if (typeInstance->mGenericTypeInfo->mProjectsReferenced.empty())
  8849. typeInstance->GenerateProjectsReferenced();
  8850. lookupCtx.mCheckProjects = &typeInstance->mGenericTypeInfo->mProjectsReferenced;
  8851. }
  8852. if ((lookupResultCtx != NULL) && (lookupResultCtx->mIsVerify))
  8853. {
  8854. if (lookupResultCtx->mResult->mFoundInnerType)
  8855. return lookupCtx.mBestTypeDef;
  8856. }
  8857. else
  8858. {
  8859. if ((!lookupCtx.HasValidMatch()) && (typeInstance != NULL))
  8860. {
  8861. std::function<bool(BfTypeInstance*)> _CheckType = [&](BfTypeInstance* typeInstance)
  8862. {
  8863. auto checkTypeInst = typeInstance;
  8864. allowPrivate = true;
  8865. while (checkTypeInst != NULL)
  8866. {
  8867. if (!checkTypeInst->mTypeDef->mNestedTypes.IsEmpty())
  8868. {
  8869. if (mSystem->FindTypeDef(findName, numGenericArgs, useProject, checkTypeInst->mTypeDef->mFullNameEx, allowPrivate, &lookupCtx))
  8870. {
  8871. foundInnerType = lookupCtx.mBestTypeDef;
  8872. if (lookupCtx.HasValidMatch())
  8873. return true;
  8874. if ((lookupCtx.mBestTypeDef->mProtection == BfProtection_Private) && (!allowPrivate))
  8875. {
  8876. protErrorTypeDef = lookupCtx.mBestTypeDef;
  8877. protErrorOuterType = checkTypeInst;
  8878. }
  8879. }
  8880. }
  8881. if (checkTypeInst == skipCheckBaseType)
  8882. break;
  8883. checkTypeInst = GetBaseType(checkTypeInst);
  8884. allowPrivate = false;
  8885. }
  8886. checkTypeInst = typeInstance;
  8887. allowPrivate = true;
  8888. while (checkTypeInst != NULL)
  8889. {
  8890. auto outerTypeInst = GetOuterType(checkTypeInst);
  8891. if (outerTypeInst != NULL)
  8892. {
  8893. if (_CheckType(outerTypeInst))
  8894. return true;
  8895. }
  8896. if (checkTypeInst == skipCheckBaseType)
  8897. break;
  8898. checkTypeInst = GetBaseType(checkTypeInst);
  8899. allowPrivate = false;
  8900. }
  8901. return false;
  8902. };
  8903. _CheckType(typeInstance);
  8904. }
  8905. }
  8906. if (!lookupCtx.HasValidMatch())
  8907. {
  8908. if (mSystem->mTypeDefs.TryGet(findName, NULL))
  8909. mSystem->FindTypeDef(findName, numGenericArgs, useProject, BfAtomComposite(), allowPrivate, &lookupCtx);
  8910. for (auto& checkNamespace : useTypeDef->mNamespaceSearch)
  8911. {
  8912. BfAtom* atom = findName.mParts[0];
  8913. BfAtom* prevAtom = checkNamespace.mParts[checkNamespace.mSize - 1];
  8914. if (atom->mPrevNamesMap.ContainsKey(prevAtom))
  8915. mSystem->FindTypeDef(findName, numGenericArgs, useProject, checkNamespace, allowPrivate, &lookupCtx);
  8916. }
  8917. }
  8918. if (!lookupCtx.HasValidMatch())
  8919. {
  8920. auto staticSearch = GetStaticSearch();
  8921. if (staticSearch != NULL)
  8922. {
  8923. for (auto staticTypeInstance : staticSearch->mStaticTypes)
  8924. {
  8925. if (mSystem->FindTypeDef(findName, numGenericArgs, useProject, staticTypeInstance->mTypeDef->mFullNameEx, false, &lookupCtx))
  8926. {
  8927. if (lookupCtx.HasValidMatch())
  8928. break;
  8929. if (lookupCtx.mBestTypeDef->mProtection < BfProtection_Public)
  8930. {
  8931. protErrorTypeDef = lookupCtx.mBestTypeDef;
  8932. protErrorOuterType = staticTypeInstance;
  8933. }
  8934. }
  8935. }
  8936. }
  8937. }
  8938. if ((!lookupCtx.HasValidMatch()) && (typeInstance == NULL))
  8939. {
  8940. if (useTypeDef->mOuterType != NULL)
  8941. return FindTypeDefRaw(findName, numGenericArgs, typeInstance, useTypeDef->mOuterType, error);
  8942. }
  8943. if ((error != NULL) && (lookupCtx.mAmbiguousTypeDef != NULL))
  8944. {
  8945. if (error->mErrorKind == BfTypeLookupError::BfErrorKind_None)
  8946. error->mErrorKind = BfTypeLookupError::BfErrorKind_Ambiguous;
  8947. error->mAmbiguousTypeDef = lookupCtx.mAmbiguousTypeDef;
  8948. if (error->mRefNode != NULL)
  8949. ShowAmbiguousTypeError(error->mRefNode, lookupCtx.mBestTypeDef, lookupCtx.mAmbiguousTypeDef);
  8950. }
  8951. if ((protErrorTypeDef != NULL) && (lookupCtx.mBestTypeDef == protErrorTypeDef) && (error != NULL) && (error->mRefNode != NULL))
  8952. Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", TypeToString(protErrorOuterType).c_str(), findName.ToString().c_str()), error->mRefNode); // CS0122
  8953. if ((lookupResultCtx != NULL) && (lookupResultCtx->mResult != NULL) && (!lookupResultCtx->mIsVerify) && (foundInnerType != NULL) && (foundInnerType == lookupCtx.mBestTypeDef))
  8954. lookupResultCtx->mResult->mFoundInnerType = true;
  8955. if (((resolveFlags & BfResolveTypeRefFlag_AllowGlobalContainer) == 0) && (lookupCtx.mBestTypeDef != NULL) && (lookupCtx.mBestTypeDef->IsGlobalsContainer()))
  8956. return NULL;
  8957. return lookupCtx.mBestTypeDef;
  8958. }
  8959. BfTypeDef* BfModule::FindTypeDef(const BfAtomComposite& findName, int numGenericArgs, BfTypeInstance* typeInstanceOverride, BfTypeLookupError* error, BfResolveTypeRefFlags resolveFlags)
  8960. {
  8961. //BP_ZONE("BfModule::FindTypeDef_1");
  8962. BfTypeInstance* typeInstance = (typeInstanceOverride != NULL) ? typeInstanceOverride : mCurTypeInstance;
  8963. auto useTypeDef = GetActiveTypeDef(typeInstanceOverride, true);
  8964. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  8965. typeInstance = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  8966. if (useTypeDef != NULL)
  8967. useTypeDef = useTypeDef->GetDefinition();
  8968. if ((typeInstance == NULL) && (useTypeDef == NULL))
  8969. {
  8970. BfProject* project = NULL;
  8971. if ((mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mActiveProject != NULL))
  8972. project = mContext->mCurTypeState->mActiveProject;
  8973. else if ((mCompiler->mResolvePassData != NULL) && (!mCompiler->mResolvePassData->mParsers.IsEmpty()))
  8974. project = mCompiler->mResolvePassData->mParsers[0]->mProject;
  8975. //BP_ZONE("System.FindTypeDef_2");
  8976. Array<BfAtomComposite> namespaceSearch;
  8977. if (mContext->mCurNamespaceNodes != NULL)
  8978. {
  8979. String checkNamespace;
  8980. for (auto namespaceNode : *mContext->mCurNamespaceNodes)
  8981. {
  8982. if (namespaceNode->mNameNode != NULL)
  8983. {
  8984. if (!checkNamespace.IsEmpty())
  8985. checkNamespace += ".";
  8986. namespaceNode->mNameNode->ToString(checkNamespace);
  8987. }
  8988. }
  8989. if (!checkNamespace.IsEmpty())
  8990. {
  8991. BfAtomCompositeT<16> atomComposite;
  8992. if (mSystem->ParseAtomComposite(checkNamespace, atomComposite))
  8993. namespaceSearch.Add(atomComposite);
  8994. }
  8995. }
  8996. BfFindTypeDefFlags findDefFlags = BfFindTypeDefFlag_None;
  8997. if ((resolveFlags & BfResolveTypeRefFlag_AllowGlobalContainer) != 0)
  8998. findDefFlags = (BfFindTypeDefFlags)(findDefFlags | BfFindTypeDefFlag_AllowGlobal);
  8999. BfTypeDef* ambiguousTypeDef = NULL;
  9000. BfTypeDef *result = mSystem->FindTypeDef(findName, numGenericArgs, project, namespaceSearch, &ambiguousTypeDef, findDefFlags);
  9001. if ((ambiguousTypeDef != NULL) && (error != NULL))
  9002. {
  9003. error->mErrorKind = BfTypeLookupError::BfErrorKind_Ambiguous;
  9004. error->mAmbiguousTypeDef = ambiguousTypeDef;
  9005. if (error->mRefNode != NULL)
  9006. ShowAmbiguousTypeError(error->mRefNode, result, ambiguousTypeDef);
  9007. }
  9008. return result;
  9009. }
  9010. if ((mCompiler->mResolvePassData != NULL) && (typeInstance != NULL))
  9011. {
  9012. if (mCompiler->mResolvePassData->mAutoCompleteTempTypes.Contains(useTypeDef))
  9013. return FindTypeDefRaw(findName, numGenericArgs, typeInstance, useTypeDef, error, NULL, resolveFlags);
  9014. }
  9015. BfTypeLookupEntry typeLookupEntry;
  9016. typeLookupEntry.mName.Reference(findName);
  9017. typeLookupEntry.mNumGenericParams = numGenericArgs;
  9018. typeLookupEntry.mFlags = ((resolveFlags & BfResolveTypeRefFlag_SpecializedProject) != 0) ? BfTypeLookupEntry::Flags_SpecializedProject : BfTypeLookupEntry::Flags_None;
  9019. typeLookupEntry.mUseTypeDef = useTypeDef;
  9020. BfTypeLookupEntry* typeLookupEntryPtr = NULL;
  9021. BfTypeLookupResult* resultPtr = NULL;
  9022. if ((typeInstance != NULL) && (typeInstance->mLookupResults.TryAdd(typeLookupEntry, &typeLookupEntryPtr, &resultPtr)))
  9023. {
  9024. BF_ASSERT(!useTypeDef->IsEmitted());
  9025. bool isValid;
  9026. if (useTypeDef->mIsPartial)
  9027. isValid = typeInstance->mTypeDef->GetDefinition()->ContainsPartial(useTypeDef);
  9028. else
  9029. isValid = typeInstance->mTypeDef->GetDefinition() == useTypeDef;
  9030. if ((!isValid) && (mCurMethodInstance != NULL) && (mCurMethodInstance->mIsForeignMethodDef))
  9031. {
  9032. BF_ASSERT(mCurMethodInstance->mIsForeignMethodDef);
  9033. isValid = mCurMethodInstance->mMethodDef->mDeclaringType == useTypeDef;
  9034. }
  9035. BF_ASSERT(isValid);
  9036. typeLookupEntryPtr->mAtomUpdateIdx = typeLookupEntry.mName.GetAtomUpdateIdx();
  9037. // FindTypeDefRaw may re-enter when finding base types, so we need to expect that resultPtr can change
  9038. resultPtr->mForceLookup = true;
  9039. resultPtr->mTypeDef = NULL;
  9040. int prevAllocSize = (int)typeInstance->mLookupResults.size();
  9041. BfTypeLookupError localError;
  9042. BfTypeLookupError* errorPtr = (error != NULL) ? error : &localError;
  9043. BfTypeLookupResultCtx lookupResultCtx;
  9044. lookupResultCtx.mResult = resultPtr;
  9045. auto typeDef = FindTypeDefRaw(findName, numGenericArgs, typeInstance, useTypeDef, errorPtr, &lookupResultCtx, resolveFlags);
  9046. if (prevAllocSize != typeInstance->mLookupResults.size())
  9047. {
  9048. bool found = typeInstance->mLookupResults.TryGetValue(typeLookupEntry, &resultPtr);
  9049. BF_ASSERT(found);
  9050. }
  9051. resultPtr->mTypeDef = typeDef;
  9052. resultPtr->mForceLookup = errorPtr->mErrorKind != BfTypeLookupError::BfErrorKind_None;
  9053. return typeDef;
  9054. }
  9055. else
  9056. {
  9057. if ((resultPtr == NULL) || (resultPtr->mForceLookup))
  9058. return FindTypeDefRaw(findName, numGenericArgs, typeInstance, useTypeDef, error, NULL, resolveFlags);
  9059. else
  9060. return resultPtr->mTypeDef;
  9061. }
  9062. }
  9063. BfTypeDef* BfModule::FindTypeDef(const StringImpl& typeName, int numGenericArgs, BfTypeInstance* typeInstanceOverride, BfTypeLookupError* error, BfResolveTypeRefFlags resolveFlags)
  9064. {
  9065. //BP_ZONE("BfModule::FindTypeDef_4");
  9066. BfSizedAtomComposite findName;
  9067. if (!mSystem->ParseAtomComposite(typeName, findName))
  9068. return NULL;
  9069. auto result = FindTypeDef(findName, numGenericArgs, typeInstanceOverride, error, resolveFlags);
  9070. // Don't allow just finding extensions here. This can happen in some 'using static' cases but generally shouldn't happen
  9071. if ((result != NULL) && (result->mTypeCode == BfTypeCode_Extension))
  9072. return NULL;
  9073. return result;
  9074. }
  9075. BfTypeDef* BfModule::FindTypeDef(BfTypeReference* typeRef, BfTypeInstance* typeInstanceOverride, BfTypeLookupError* error, int numGenericParams, BfResolveTypeRefFlags resolveFlags)
  9076. {
  9077. //BP_ZONE("BfModule::FindTypeDef_5");
  9078. if (auto typeDefTypeRef = BfNodeDynCast<BfDirectTypeDefReference>(typeRef))
  9079. {
  9080. if (typeDefTypeRef->mTypeDef != NULL)
  9081. return mSystem->FilterDeletedTypeDef(typeDefTypeRef->mTypeDef);
  9082. }
  9083. //TODO: When does this get called?
  9084. if (auto elementedType = BfNodeDynCast<BfElementedTypeRef>(typeRef))
  9085. return FindTypeDef(elementedType->mElementType, typeInstanceOverride, error);
  9086. BF_ASSERT(typeRef->IsA<BfNamedTypeReference>() || typeRef->IsA<BfQualifiedTypeReference>() || typeRef->IsA<BfDirectStrTypeReference>());
  9087. auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef);
  9088. StringView findNameStr;
  9089. if (namedTypeRef != NULL)
  9090. findNameStr = namedTypeRef->mNameNode->ToStringView();
  9091. else
  9092. {
  9093. auto directStrTypeDef = BfNodeDynCastExact<BfDirectStrTypeReference>(typeRef);
  9094. if (directStrTypeDef != NULL)
  9095. findNameStr = directStrTypeDef->mTypeName;
  9096. else
  9097. BFMODULE_FATAL(this, "Error?");
  9098. }
  9099. if (findNameStr.mLength == 6)
  9100. {
  9101. if (findNameStr == "object")
  9102. {
  9103. findNameStr = "System.Object";
  9104. Fail("'object' alias not supported, use 'Object'", typeRef);
  9105. }
  9106. else if (findNameStr == "string")
  9107. {
  9108. findNameStr = "System.String";
  9109. Fail("'string' alias not supported, use 'String'", typeRef);
  9110. }
  9111. }
  9112. BfSizedAtomComposite findName;
  9113. if ((resolveFlags & BfResolveTypeRefFlag_Attribute) != 0)
  9114. {
  9115. String attributeName;
  9116. attributeName += findNameStr;
  9117. attributeName += "Attribute";
  9118. if (!mSystem->ParseAtomComposite(attributeName, findName))
  9119. return NULL;
  9120. }
  9121. else
  9122. {
  9123. if (!mSystem->ParseAtomComposite(findNameStr, findName))
  9124. return NULL;
  9125. }
  9126. #ifdef BF_AST_HAS_PARENT_MEMBER
  9127. if (auto parentGenericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef->mParent))
  9128. {
  9129. if (parentGenericTypeRef->mElementType == typeRef)
  9130. BF_ASSERT(numGenericParams == parentGenericTypeRef->GetGenericArgCount());
  9131. }
  9132. #endif
  9133. auto typeDef = FindTypeDef(findName, numGenericParams, typeInstanceOverride, error, resolveFlags);
  9134. //TYPEDEF if (namedTypeRef != NULL)
  9135. // namedTypeRef->mTypeDef = typeDef;
  9136. return typeDef;
  9137. }
  9138. void BfModule::CheckTypeRefFixit(BfAstNode* typeRef, const char* appendName)
  9139. {
  9140. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((typeRef))))
  9141. {
  9142. String typeName = typeRef->ToString();
  9143. if (appendName != NULL)
  9144. typeName += appendName;
  9145. std::set<String> fixitNamespaces;
  9146. //TODO: Do proper value for numGenericArgs
  9147. mSystem->FindFixitNamespaces(typeName, -1, mCompiler->mResolvePassData->mParsers[0]->mProject, fixitNamespaces);
  9148. int insertLoc = 0;
  9149. BfUsingFinder usingFinder;
  9150. usingFinder.mFromIdx = typeRef->mSrcStart;
  9151. usingFinder.VisitMembers(typeRef->GetSourceData()->mRootNode);
  9152. for (auto& namespaceStr : fixitNamespaces)
  9153. {
  9154. BfParserData* parser = typeRef->GetSourceData()->ToParserData();
  9155. if (parser != NULL)
  9156. 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()));
  9157. }
  9158. }
  9159. }
  9160. void BfModule::CheckIdentifierFixit(BfAstNode* node)
  9161. {
  9162. //TODO: Check globals, possibly spelling mistakes?
  9163. }
  9164. void BfModule::TypeRefNotFound(BfTypeReference* typeRef, const char* appendName)
  9165. {
  9166. if (typeRef->IsTemporary())
  9167. return;
  9168. if (PreFail())
  9169. Fail("Type could not be found (are you missing a using directive or library reference?)", typeRef);
  9170. if (!mIgnoreErrors)
  9171. {
  9172. while (auto elementedType = BfNodeDynCast<BfElementedTypeRef>(typeRef))
  9173. typeRef = elementedType->mElementType;
  9174. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef))
  9175. {
  9176. String findNameStr = namedTypeRef->mNameNode->ToString();
  9177. if (appendName != NULL)
  9178. findNameStr += appendName;
  9179. BfSizedAtomComposite findName;
  9180. if ((!mSystem->ParseAtomComposite(findNameStr, findName)) && (mCurTypeInstance != NULL))
  9181. {
  9182. //BfTypeInstance* typeInstance = (typeInstanceOverride != NULL) ? typeInstanceOverride : mCurTypeInstance;
  9183. // We don't need a typeInstanceOverride because that is used to lookup references
  9184. // from mixins, but it's the type using the mixin (mCurTypeInstance) that needs
  9185. // rebuilding if the lookup fails
  9186. BfTypeInstance* typeInstance = mCurTypeInstance;
  9187. BfTypeLookupEntry typeLookupEntry;
  9188. typeLookupEntry.mNumGenericParams = 0;
  9189. typeLookupEntry.mAtomUpdateIdx = mSystem->mAtomUpdateIdx;
  9190. typeInstance->mLookupResults.TryAdd(typeLookupEntry, BfTypeLookupResult());
  9191. }
  9192. }
  9193. }
  9194. CheckTypeRefFixit(typeRef, appendName);
  9195. }
  9196. bool BfModule::ValidateTypeWildcard(BfAstNode* typeRef, bool isAttributeRef)
  9197. {
  9198. if (typeRef == NULL)
  9199. return false;
  9200. if (auto wildcardTypeRef = BfNodeDynCast<BfWildcardTypeReference>(typeRef))
  9201. return true;
  9202. StringT<128> nameStr;
  9203. typeRef->ToString(nameStr);
  9204. if (isAttributeRef)
  9205. nameStr.Append("Attribute");
  9206. auto typeDef = mSystem->FindTypeDef(nameStr, (BfProject*)NULL);
  9207. if ((typeDef != NULL) && (typeDef->mGenericParamDefs.IsEmpty()))
  9208. return true;
  9209. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  9210. {
  9211. if (qualifiedTypeRef->mLeft == NULL)
  9212. return false;
  9213. if (auto wildcardTypeRef = BfNodeDynCast<BfWildcardTypeReference>(qualifiedTypeRef->mRight))
  9214. {
  9215. StringT<128> leftNameStr;
  9216. BfType* leftType = NULL;
  9217. BfAtomCompositeT<16> leftComposite;
  9218. qualifiedTypeRef->mLeft->ToString(leftNameStr);
  9219. if (!mSystem->ParseAtomComposite(leftNameStr, leftComposite))
  9220. return false;
  9221. if (mSystem->ContainsNamespace(leftComposite, NULL))
  9222. return true;
  9223. return ValidateTypeWildcard(qualifiedTypeRef->mLeft, false);
  9224. }
  9225. }
  9226. if (!BfNodeIsA<BfGenericInstanceTypeRef>(typeRef))
  9227. {
  9228. if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(typeRef))
  9229. {
  9230. return ValidateTypeWildcard(elementedTypeRef->mElementType, false);
  9231. }
  9232. }
  9233. BfAstNode* origTypeRef = typeRef;
  9234. String name;
  9235. String nameEx;
  9236. int genericCount = 0;
  9237. std::function<bool(BfAstNode*, bool)> _ToString = [&](BfAstNode* typeRef, bool isLast)
  9238. {
  9239. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  9240. {
  9241. _ToString(qualifiedTypeRef->mLeft, false);
  9242. name.Append(".");
  9243. nameEx.Append(".");
  9244. _ToString(qualifiedTypeRef->mRight, typeRef == origTypeRef);
  9245. return true;
  9246. }
  9247. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  9248. {
  9249. _ToString(genericTypeRef->mElementType, false);
  9250. genericCount += genericTypeRef->mCommas.mSize + 1;
  9251. for (auto genericArg : genericTypeRef->mGenericArguments)
  9252. if (!ValidateTypeWildcard(genericArg, false))
  9253. return false;
  9254. }
  9255. else
  9256. {
  9257. typeRef->ToString(name);
  9258. typeRef->ToString(nameEx);
  9259. }
  9260. if (genericCount > 0)
  9261. {
  9262. if (!isLast)
  9263. name += StrFormat("`%d", genericCount);
  9264. nameEx += StrFormat("`%d", genericCount);
  9265. }
  9266. return true;
  9267. };
  9268. if (!_ToString(typeRef, true))
  9269. return false;
  9270. BfAtomCompositeT<16> composite;
  9271. if (!mSystem->ParseAtomComposite(name, composite))
  9272. return false;
  9273. BfAtomCompositeT<16> compositeEx;
  9274. if (!mSystem->ParseAtomComposite(nameEx, compositeEx))
  9275. return false;
  9276. auto itr = mSystem->mTypeDefs.TryGet(composite);
  9277. while (itr != mSystem->mTypeDefs.end())
  9278. {
  9279. auto typeDef = *itr;
  9280. if (typeDef->mFullName != composite)
  9281. break;
  9282. if (typeDef->mFullNameEx == compositeEx)
  9283. return true;
  9284. ++itr;
  9285. }
  9286. return false;
  9287. }
  9288. //int sResolveTypeRefIdx = 0;
  9289. BfTypedValue BfModule::TryLookupGenericConstVaue(BfIdentifierNode* identifierNode, BfType* expectingType)
  9290. {
  9291. BfTypeInstance* contextTypeInstance = mCurTypeInstance;
  9292. BfMethodInstance* contextMethodInstance = mCurMethodInstance;
  9293. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  9294. {
  9295. contextTypeInstance = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  9296. contextMethodInstance = mCurMethodState->mMixinState->mMixinMethodInstance;
  9297. }
  9298. BfTypeDef* curTypeDef = NULL;
  9299. if (contextTypeInstance != NULL)
  9300. {
  9301. curTypeDef = contextTypeInstance->mTypeDef;
  9302. StringT<128> findName;
  9303. identifierNode->ToString(findName);
  9304. auto genericCheckTypeInstance = contextTypeInstance;
  9305. if (contextTypeInstance->IsBoxed())
  9306. genericCheckTypeInstance = contextTypeInstance->GetUnderlyingType()->ToTypeInstance();
  9307. bool doUndefVal = false;
  9308. if (genericCheckTypeInstance->IsUnspecializedTypeVariation())
  9309. {
  9310. genericCheckTypeInstance = GetUnspecializedTypeInstance(genericCheckTypeInstance);
  9311. doUndefVal = true;
  9312. }
  9313. BfGenericParamDef* genericParamDef = NULL;
  9314. BfGenericParamDef* origGenericParamDef = NULL;
  9315. BfType* genericParamResult = NULL;
  9316. BfType* genericTypeConstraint = NULL;
  9317. bool disallowConstExprValue = false;
  9318. if ((genericCheckTypeInstance != NULL) && (genericCheckTypeInstance->IsGenericTypeInstance()))
  9319. {
  9320. auto genericTypeInst = (BfTypeInstance*)genericCheckTypeInstance;
  9321. auto* genericParams = &curTypeDef->mGenericParamDefs;
  9322. auto* origGenericParams = &curTypeDef->mGenericParamDefs;
  9323. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  9324. {
  9325. auto activeTypeDef = GetActiveTypeDef(NULL, true);
  9326. genericParams = &activeTypeDef->mGenericParamDefs;
  9327. }
  9328. for (int genericParamIdx = (int)genericParams->size() - 1; genericParamIdx >= 0; genericParamIdx--)
  9329. {
  9330. auto checkGenericParamDef = (*genericParams)[genericParamIdx];
  9331. String genericName = checkGenericParamDef->mName;
  9332. if (genericName == findName)
  9333. {
  9334. genericParamDef = checkGenericParamDef;
  9335. origGenericParamDef = (*origGenericParams)[genericParamIdx];
  9336. genericParamResult = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[genericParamIdx];
  9337. genericTypeConstraint = genericTypeInst->mGenericTypeInfo->mGenericParams[genericParamIdx]->mTypeConstraint;
  9338. if (contextTypeInstance != genericCheckTypeInstance)
  9339. {
  9340. // Don't allow an 'unspecialized variation' generic param
  9341. auto checkResult = contextTypeInstance->mGenericTypeInfo->mTypeGenericArguments[genericParamIdx];
  9342. if (!checkResult->IsGenericParam())
  9343. genericParamResult = checkResult;
  9344. }
  9345. HandleTypeGenericParamRef(identifierNode, genericTypeInst->mTypeDef, genericParamIdx);
  9346. }
  9347. }
  9348. }
  9349. if ((contextMethodInstance != NULL) && (genericParamResult == NULL))
  9350. {
  9351. auto checkMethodInstance = contextMethodInstance;
  9352. if (checkMethodInstance->mIsUnspecializedVariation)
  9353. checkMethodInstance = GetUnspecializedMethodInstance(checkMethodInstance);
  9354. for (int genericParamIdx = (int)checkMethodInstance->mMethodDef->mGenericParams.size() - 1; genericParamIdx >= 0; genericParamIdx--)
  9355. {
  9356. auto checkGenericParamDef = checkMethodInstance->mMethodDef->mGenericParams[genericParamIdx];
  9357. String genericName = checkGenericParamDef->mName;
  9358. if (genericName == findName)
  9359. {
  9360. genericParamDef = checkGenericParamDef;
  9361. origGenericParamDef = checkGenericParamDef;
  9362. genericParamResult = checkMethodInstance->mMethodInfoEx->mMethodGenericArguments[genericParamIdx];
  9363. genericTypeConstraint = checkMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx]->mTypeConstraint;
  9364. if (contextMethodInstance != checkMethodInstance)
  9365. {
  9366. // Don't allow an 'unspecialized variation' generic param
  9367. auto checkResult = contextMethodInstance->mMethodInfoEx->mMethodGenericArguments[genericParamIdx];
  9368. if (!checkResult->IsGenericParam())
  9369. genericParamResult = checkResult;
  9370. }
  9371. HandleMethodGenericParamRef(identifierNode, contextMethodInstance->GetOwner()->mTypeDef, checkMethodInstance->mMethodDef, genericParamIdx);
  9372. }
  9373. }
  9374. }
  9375. if (genericParamResult != NULL)
  9376. {
  9377. auto typeRefSource = identifierNode->GetSourceData();
  9378. if ((mCompiler->mResolvePassData != NULL) && (mCompiler->mResolvePassData->mIsClassifying) && (typeRefSource != NULL))
  9379. {
  9380. if (auto sourceClassifier = mCompiler->mResolvePassData->GetSourceClassifier(identifierNode))
  9381. sourceClassifier->SetElementType(identifierNode, BfSourceElementType_GenericParam);
  9382. }
  9383. if (genericParamResult->IsConstExprValue())
  9384. {
  9385. BfConstExprValueType* constExprValueType = (BfConstExprValueType*)genericParamResult;
  9386. auto constType = genericTypeConstraint;
  9387. if (constType == NULL)
  9388. constType = GetPrimitiveType(BfTypeCode_IntPtr);
  9389. if (constType->IsVar())
  9390. {
  9391. BfExprEvaluator exprEvaluator(this);
  9392. exprEvaluator.GetLiteral(identifierNode, constExprValueType->mValue, constExprValueType->mType);
  9393. return exprEvaluator.mResult;
  9394. }
  9395. else
  9396. {
  9397. BfExprEvaluator exprEvaluator(this);
  9398. exprEvaluator.mExpectingType = constType;
  9399. exprEvaluator.GetLiteral(identifierNode, constExprValueType->mValue, constExprValueType->mType);
  9400. if (exprEvaluator.mResult)
  9401. {
  9402. auto castedVal = CastToValue(identifierNode, exprEvaluator.mResult, constType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  9403. if (castedVal)
  9404. return BfTypedValue(castedVal, constType);
  9405. }
  9406. return exprEvaluator.mResult;
  9407. }
  9408. }
  9409. else if (genericParamResult->IsGenericParam())
  9410. {
  9411. if ((doUndefVal) && (genericTypeConstraint != NULL))
  9412. {
  9413. return GetDefaultTypedValue(genericTypeConstraint, false, BfDefaultValueKind_Undef);
  9414. }
  9415. if (((genericParamDef->mGenericParamFlags | origGenericParamDef->mGenericParamFlags) & BfGenericParamFlag_Const) != 0)
  9416. {
  9417. BfTypedValue result;
  9418. result.mType = genericParamResult;
  9419. result.mKind = BfTypedValueKind_GenericConstValue;
  9420. return result;
  9421. }
  9422. }
  9423. }
  9424. }
  9425. return BfTypedValue();
  9426. }
  9427. void BfModule::GetDelegateTypeRefAttributes(BfDelegateTypeRef* delegateTypeRef, BfCallingConvention& callingConvention)
  9428. {
  9429. if (delegateTypeRef->mAttributes == NULL)
  9430. return;
  9431. BfCaptureInfo captureInfo;
  9432. auto customAttributes = GetCustomAttributes(delegateTypeRef->mAttributes, (BfAttributeTargets)(BfAttributeTargets_DelegateTypeRef | BfAttributeTargets_FunctionTypeRef), BfGetCustomAttributesFlags_KeepConstsInModule);
  9433. if (customAttributes != NULL)
  9434. {
  9435. auto linkNameAttr = customAttributes->Get(mCompiler->mCallingConventionAttributeTypeDef);
  9436. if (linkNameAttr != NULL)
  9437. {
  9438. if (linkNameAttr->mCtorArgs.size() == 1)
  9439. {
  9440. auto constant = mBfIRBuilder->GetConstant(linkNameAttr->mCtorArgs[0]);
  9441. if (constant != NULL)
  9442. callingConvention = (BfCallingConvention)constant->mInt32;
  9443. }
  9444. }
  9445. delete customAttributes;
  9446. }
  9447. }
  9448. BfType* BfModule::ResolveTypeRef(BfTypeReference* typeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags, int numGenericArgs)
  9449. {
  9450. return ResolveTypeRef_Ref(typeRef, populateType, resolveFlags, numGenericArgs);
  9451. }
  9452. BfType* BfModule::ResolveTypeRef_Ref(BfTypeReference* typeRef, BfPopulateType populateType, BfResolveTypeRefFlags& resolveFlags, int numGenericArgs)
  9453. {
  9454. //BP_ZONE("BfModule::ResolveTypeRef");
  9455. if (typeRef == NULL)
  9456. {
  9457. AssertErrorState();
  9458. return NULL;
  9459. }
  9460. if (resolveFlags & BfResolveTypeRefFlag_AutoComplete)
  9461. {
  9462. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags & ~BfResolveTypeRefFlag_AutoComplete);
  9463. auto autoComplete = mCompiler->GetAutoComplete();
  9464. if (autoComplete != NULL)
  9465. autoComplete->CheckTypeRef(typeRef, false);
  9466. }
  9467. if ((resolveFlags & BfResolveTypeRefFlag_AllowRef) == 0)
  9468. {
  9469. if (auto refTypeRef = BfNodeDynCast<BfRefTypeRef>(typeRef))
  9470. {
  9471. const char* refTypeStr = BfTokenToString(refTypeRef->mRefToken->mToken);
  9472. Fail(StrFormat("Invalid use of '%s'. Only method parameters, return types, and local variables can be declared as %s types", refTypeStr, refTypeStr), refTypeRef->mRefToken);
  9473. return ResolveTypeRef(refTypeRef->mElementType, populateType, resolveFlags, numGenericArgs);
  9474. }
  9475. }
  9476. if (auto directTypeRef = BfNodeDynCastExact<BfDirectTypeReference>(typeRef))
  9477. {
  9478. return directTypeRef->mType;
  9479. }
  9480. if (auto dotType = BfNodeDynCastExact<BfDotTypeReference>(typeRef))
  9481. {
  9482. Fail(StrFormat("Invalid use of '%s'", BfTokenToString(dotType->mDotToken->mToken)), typeRef);
  9483. return NULL;
  9484. }
  9485. if (auto varRefType = BfNodeDynCastExact<BfVarRefTypeReference>(typeRef))
  9486. {
  9487. Fail("Invalid use of 'var ref'. Generally references are generated with a 'var' declaration with 'ref' applied to the initializer", typeRef);
  9488. return NULL;
  9489. }
  9490. if (mNoResolveGenericParams)
  9491. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoResolveGenericParam);
  9492. SetAndRestoreValue<bool> prevNoResolveGenericParams(mNoResolveGenericParams, (resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0);
  9493. //
  9494. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags & ~BfResolveTypeRefFlag_NoResolveGenericParam);
  9495. BfTypeInstance* contextTypeInstance = mCurTypeInstance;
  9496. BfMethodInstance* contextMethodInstance = mCurMethodInstance;
  9497. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsForeignMethodDef))
  9498. contextTypeInstance = mCurMethodInstance->mMethodInfoEx->mForeignType;
  9499. if ((mCurMethodState != NULL) && (mCurMethodState->mMixinState != NULL))
  9500. {
  9501. contextTypeInstance = mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  9502. contextMethodInstance = mCurMethodState->mMixinState->mMixinMethodInstance;
  9503. }
  9504. BfTypeDef* curTypeDef = NULL;
  9505. Array<BfProject*>* checkProjects = NULL;
  9506. if (contextTypeInstance != NULL)
  9507. {
  9508. curTypeDef = contextTypeInstance->mTypeDef;
  9509. if ((curTypeDef->IsEmitted()) && (!typeRef->IsTemporary()))
  9510. {
  9511. auto parser = typeRef->GetParser();
  9512. if ((parser != NULL) && (parser->mIsEmitted))
  9513. {
  9514. if (contextTypeInstance->IsGenericTypeInstance())
  9515. {
  9516. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_SpecializedProject);
  9517. if (contextTypeInstance->mGenericTypeInfo->mProjectsReferenced.empty())
  9518. contextTypeInstance->GenerateProjectsReferenced();
  9519. checkProjects = &contextTypeInstance->mGenericTypeInfo->mProjectsReferenced;
  9520. }
  9521. }
  9522. }
  9523. // Check generics first
  9524. auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(typeRef);
  9525. auto directStrTypeRef = BfNodeDynCastExact<BfDirectStrTypeReference>(typeRef);
  9526. if (((namedTypeRef != NULL) && (namedTypeRef->mNameNode != NULL)) || (directStrTypeRef != NULL))
  9527. {
  9528. StringView findName;
  9529. if (namedTypeRef != NULL)
  9530. findName = namedTypeRef->mNameNode->ToStringView();
  9531. else
  9532. findName = directStrTypeRef->mTypeName;
  9533. if (findName == "Self")
  9534. {
  9535. BfType* selfType = mCurTypeInstance;
  9536. if (selfType->IsTypeAlias())
  9537. selfType = GetOuterType(selfType);
  9538. if (selfType != NULL)
  9539. {
  9540. if (selfType->IsInterface()) // For interfaces, 'Self' refers to the identity of the implementing type, so we use a placeholder
  9541. return GetPrimitiveType(BfTypeCode_Self);
  9542. else
  9543. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_FromIndirectSource);
  9544. if (selfType->IsBoxed())
  9545. selfType = selfType->GetUnderlyingType();
  9546. if ((resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0)
  9547. {
  9548. if ((selfType->IsSpecializedType()) || (selfType->IsUnspecializedTypeVariation()))
  9549. selfType = ResolveTypeDef(selfType->ToTypeInstance()->mTypeDef, populateType);
  9550. }
  9551. }
  9552. if (selfType != NULL)
  9553. {
  9554. auto selfTypeInst = selfType->ToTypeInstance();
  9555. if ((selfTypeInst != NULL) && (selfTypeInst->mTypeDef->IsGlobalsContainer()) && ((resolveFlags & BfResolveTypeRefFlag_AllowGlobalsSelf) == 0))
  9556. selfType = NULL;
  9557. }
  9558. if (selfType == NULL)
  9559. {
  9560. Fail("'Self' type is not usable here", typeRef);
  9561. }
  9562. return ResolveTypeResult(typeRef, selfType, populateType, resolveFlags);
  9563. }
  9564. else if (findName == "SelfBase")
  9565. {
  9566. BfType* selfType = mCurTypeInstance;
  9567. if (selfType->IsTypeAlias())
  9568. selfType = GetOuterType(selfType);
  9569. if (selfType != NULL)
  9570. {
  9571. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_FromIndirectSource);
  9572. if (selfType->IsBoxed())
  9573. selfType = selfType->GetUnderlyingType();
  9574. if ((resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0)
  9575. {
  9576. if ((selfType->IsSpecializedType()) || (selfType->IsUnspecializedTypeVariation()))
  9577. selfType = ResolveTypeDef(selfType->ToTypeInstance()->mTypeDef, populateType);
  9578. }
  9579. }
  9580. BfType* baseType = NULL;
  9581. if (selfType != NULL)
  9582. {
  9583. if (selfType->IsTypedPrimitive())
  9584. baseType = selfType->GetUnderlyingType();
  9585. else
  9586. {
  9587. auto selfTypeInst = selfType->ToTypeInstance();
  9588. if (selfTypeInst != NULL)
  9589. {
  9590. baseType = selfTypeInst->mBaseType;
  9591. }
  9592. }
  9593. }
  9594. if (baseType == NULL)
  9595. {
  9596. Fail("'SelfBase' type is not usable here", typeRef);
  9597. }
  9598. return ResolveTypeResult(typeRef, baseType, populateType, resolveFlags);
  9599. }
  9600. else if (findName == "SelfOuter")
  9601. {
  9602. BfType* selfType = mCurTypeInstance;
  9603. if (selfType->IsTypeAlias())
  9604. selfType = GetOuterType(selfType);
  9605. if (selfType != NULL)
  9606. {
  9607. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_FromIndirectSource);
  9608. if (selfType->IsBoxed())
  9609. selfType = selfType->GetUnderlyingType();
  9610. if ((resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0)
  9611. {
  9612. if ((selfType->IsSpecializedType()) || (selfType->IsUnspecializedTypeVariation()))
  9613. selfType = ResolveTypeDef(selfType->ToTypeInstance()->mTypeDef, populateType);
  9614. }
  9615. selfType = GetOuterType(selfType->ToTypeInstance());
  9616. }
  9617. if (selfType == NULL)
  9618. Fail("'SelfOuter' type is not usable here", typeRef);
  9619. return ResolveTypeResult(typeRef, selfType, populateType, resolveFlags);
  9620. }
  9621. else if (findName == "ExpectedType")
  9622. {
  9623. Fail("'ExpectedType' is not usable here", typeRef);
  9624. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  9625. }
  9626. auto genericCheckTypeInstance = contextTypeInstance;
  9627. if (contextTypeInstance->IsBoxed())
  9628. genericCheckTypeInstance = contextTypeInstance->GetUnderlyingType()->ToTypeInstance();
  9629. BfGenericParamDef* genericParamDef = NULL;
  9630. BfType* genericParamResult = NULL;
  9631. bool disallowConstExprValue = false;
  9632. if ((contextMethodInstance != NULL) && (genericParamResult == NULL))
  9633. {
  9634. BfMethodInstance* prevMethodInstance = NULL;
  9635. // If we're in a closure then use the outside method generic arguments
  9636. auto checkMethodInstance = contextMethodInstance;
  9637. if ((mCurMethodState != NULL) && (checkMethodInstance->mIsClosure))
  9638. {
  9639. auto checkMethodState = mCurMethodState;
  9640. while (checkMethodState != NULL)
  9641. {
  9642. if ((checkMethodState->mMethodInstance != NULL) && (checkMethodState->mMethodInstance->mIsClosure))
  9643. {
  9644. checkMethodInstance = checkMethodState->mPrevMethodState->mMethodInstance;
  9645. }
  9646. checkMethodState = checkMethodState->mPrevMethodState;
  9647. }
  9648. }
  9649. for (int genericParamIdx = (int)checkMethodInstance->mMethodDef->mGenericParams.size() - 1; genericParamIdx >= 0; genericParamIdx--)
  9650. {
  9651. auto checkGenericParamDef = checkMethodInstance->mMethodDef->mGenericParams[genericParamIdx];
  9652. String genericName = checkGenericParamDef->mName;
  9653. if (genericName == findName)
  9654. {
  9655. genericParamDef = checkGenericParamDef;
  9656. if (((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  9657. ((resolveFlags & BfResolveTypeRefFlag_AllowGenericMethodParamConstValue) == 0))
  9658. disallowConstExprValue = true;
  9659. HandleMethodGenericParamRef(typeRef, checkMethodInstance->GetOwner()->mTypeDef, checkMethodInstance->mMethodDef, genericParamIdx);
  9660. if ((resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0)
  9661. return GetGenericParamType(BfGenericParamKind_Method, genericParamIdx);
  9662. else
  9663. {
  9664. if ((mContext->mCurConstraintState != NULL) && (mContext->mCurConstraintState->mMethodInstance == checkMethodInstance) &&
  9665. (mContext->mCurConstraintState->mMethodGenericArgsOverride != NULL))
  9666. {
  9667. return ResolveTypeResult(typeRef, (*mContext->mCurConstraintState->mMethodGenericArgsOverride)[genericParamIdx], populateType, resolveFlags);
  9668. }
  9669. SetAndRestoreValue<BfGetSymbolReferenceKind> prevSymbolRefKind;
  9670. if (mCompiler->mResolvePassData != NULL) // Don't add these typeRefs, they are indirect
  9671. prevSymbolRefKind.Init(mCompiler->mResolvePassData->mGetSymbolReferenceKind, BfGetSymbolReferenceKind_None);
  9672. genericParamResult = checkMethodInstance->mMethodInfoEx->mMethodGenericArguments[genericParamIdx];
  9673. if ((genericParamResult != NULL) &&
  9674. (genericParamResult->IsConstExprValue()) &&
  9675. ((resolveFlags & BfResolveTypeRefFlag_AllowGenericMethodParamConstValue) == 0))
  9676. disallowConstExprValue = true;
  9677. }
  9678. }
  9679. }
  9680. }
  9681. if ((genericCheckTypeInstance != NULL) && (genericCheckTypeInstance->IsGenericTypeInstance()) && (genericParamResult == NULL))
  9682. {
  9683. auto genericTypeInst = (BfTypeInstance*)genericCheckTypeInstance;
  9684. auto* genericParams = &curTypeDef->mGenericParamDefs;
  9685. if (genericTypeInst->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  9686. {
  9687. auto activeTypeDef = GetActiveTypeDef(NULL, true);
  9688. genericParams = &activeTypeDef->mGenericParamDefs;
  9689. }
  9690. for (int genericParamIdx = (int)genericParams->size() - 1; genericParamIdx >= 0; genericParamIdx--)
  9691. {
  9692. auto checkGenericParamDef = (*genericParams)[genericParamIdx];
  9693. String genericName = checkGenericParamDef->mName;
  9694. if (genericName == findName)
  9695. {
  9696. genericParamDef = checkGenericParamDef;
  9697. if (((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0) &&
  9698. ((resolveFlags & BfResolveTypeRefFlag_AllowGenericTypeParamConstValue) == 0))
  9699. disallowConstExprValue = true;
  9700. HandleTypeGenericParamRef(typeRef, curTypeDef, genericParamIdx);
  9701. if ((resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam) != 0)
  9702. return GetGenericParamType(BfGenericParamKind_Type, genericParamIdx);
  9703. else
  9704. {
  9705. SetAndRestoreValue<BfGetSymbolReferenceKind> prevSymbolRefKind;
  9706. if (mCompiler->mResolvePassData != NULL) // Don't add these typeRefs, they are indirect
  9707. prevSymbolRefKind.Init(mCompiler->mResolvePassData->mGetSymbolReferenceKind, BfGetSymbolReferenceKind_None);
  9708. genericParamResult = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[genericParamIdx];
  9709. if ((genericParamResult != NULL) &&
  9710. (genericParamResult->IsConstExprValue()) &&
  9711. ((resolveFlags & BfResolveTypeRefFlag_AllowGenericTypeParamConstValue) == 0))
  9712. disallowConstExprValue = true;
  9713. }
  9714. }
  9715. }
  9716. }
  9717. if (genericParamResult != NULL)
  9718. {
  9719. if (disallowConstExprValue)
  9720. {
  9721. Fail("Invalid use of constant generic value", typeRef);
  9722. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  9723. }
  9724. if (genericParamResult->IsRef())
  9725. {
  9726. if ((resolveFlags & BfResolveTypeRefFlag_AllowRefGeneric) == 0)
  9727. genericParamResult = genericParamResult->GetUnderlyingType();
  9728. }
  9729. return ResolveTypeResult(typeRef, genericParamResult, populateType, (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_FromIndirectSource));
  9730. }
  9731. }
  9732. }
  9733. BfTypeDef* typeDef = NULL;
  9734. if (typeRef->IsNamedTypeReference())
  9735. {
  9736. BfTypeLookupError error;
  9737. error.mRefNode = typeRef;
  9738. typeDef = FindTypeDef(typeRef, contextTypeInstance, &error, 0, resolveFlags);
  9739. if (auto namedTypeRef = BfNodeDynCast<BfNamedTypeReference>(typeRef))
  9740. {
  9741. if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(namedTypeRef->mNameNode))
  9742. {
  9743. // This handles the case where we have an "BaseClass.InnerClass", but the name is qualified as "DerivedClass.InnerClass"
  9744. auto leftType = ResolveTypeRef(qualifiedNameNode->mLeft, NULL, BfPopulateType_Identity, (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowRef));
  9745. if ((leftType != NULL) && (qualifiedNameNode->mRight != NULL))
  9746. {
  9747. // Try searching within inner type
  9748. auto resolvedType = ResolveInnerType(leftType, qualifiedNameNode->mRight, populateType, true);
  9749. if (resolvedType != NULL)
  9750. {
  9751. if (mCurTypeInstance != NULL)
  9752. AddDependency(leftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  9753. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  9754. }
  9755. }
  9756. }
  9757. }
  9758. if ((typeDef == NULL) && (mCurTypeInstance != NULL))
  9759. {
  9760. // Try searching within inner type
  9761. auto checkOuterType = mCurTypeInstance;
  9762. while (checkOuterType != NULL)
  9763. {
  9764. // We check for mBaseType to not be NULL because we can't inherit from an inner type, so don't even search there
  9765. // Causes reference cycles (bad).
  9766. if ((checkOuterType != mCurTypeInstance) || (checkOuterType->mBaseType != NULL))
  9767. {
  9768. auto resolvedType = ResolveInnerType(checkOuterType, typeRef, populateType, true);
  9769. if (resolvedType != NULL)
  9770. {
  9771. if (mCurTypeInstance != NULL)
  9772. AddDependency(checkOuterType, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  9773. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  9774. }
  9775. }
  9776. checkOuterType = GetOuterType(checkOuterType);
  9777. }
  9778. }
  9779. if (typeDef == NULL)
  9780. {
  9781. auto staticSearch = GetStaticSearch();
  9782. if (staticSearch != NULL)
  9783. {
  9784. for (auto staticTypeInst : staticSearch->mStaticTypes)
  9785. {
  9786. auto resolvedType = ResolveInnerType(staticTypeInst, typeRef, populateType, true);
  9787. if (resolvedType != NULL)
  9788. {
  9789. if (mCurTypeInstance != NULL)
  9790. AddDependency(staticTypeInst, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  9791. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  9792. }
  9793. }
  9794. }
  9795. }
  9796. if (typeDef == NULL)
  9797. {
  9798. #ifdef BF_AST_HAS_PARENT_MEMBER
  9799. if (auto parentQualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef->mParent))
  9800. {
  9801. BF_ASSERT(typeRef->mParent == mParentNodeEntry->mNode);
  9802. }
  9803. #endif
  9804. if (mParentNodeEntry != NULL)
  9805. {
  9806. if (auto parentQualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(mParentNodeEntry->mNode))
  9807. {
  9808. if (typeRef == parentQualifiedTypeRef->mLeft)
  9809. {
  9810. if ((resolveFlags & BfResolveTypeRefFlag_IgnoreLookupError) == 0)
  9811. TypeRefNotFound(typeRef);
  9812. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  9813. }
  9814. }
  9815. }
  9816. if ((resolveFlags & BfResolveTypeRefFlag_IgnoreLookupError) == 0)
  9817. {
  9818. TypeRefNotFound(typeRef, ((resolveFlags & Beefy::BfResolveTypeRefFlag_Attribute) != 0) ? "Attribute" : NULL);
  9819. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  9820. }
  9821. return NULL;
  9822. }
  9823. }
  9824. else if (auto typeDefTypeRef = BfNodeDynCastExact<BfDirectTypeDefReference>(typeRef))
  9825. {
  9826. typeDef = typeDefTypeRef->mTypeDef;
  9827. }
  9828. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  9829. {
  9830. //TODO: Determine why we had this prevIgnoreErrors set here. It causes things like IEnumerator<Hey.Test<INVALIDNAME>> not fail
  9831. // properly on INVALIDNAME
  9832. SetAndRestoreValue<bool> prevIgnoreErrors(mIgnoreErrors, /*true*/mIgnoreErrors);
  9833. StringView leftNameStr;
  9834. BfType* leftType = NULL;
  9835. BfSizedAtomComposite leftComposite;
  9836. bool leftIsValid = false;
  9837. //bool leftIsValid = (qualifiedTypeRef->mLeft != NULL) && mSystem->ParseAtomComposite(qualifiedTypeRef->mLeft->ToString(), leftComposite);
  9838. if (qualifiedTypeRef->mLeft != NULL)
  9839. {
  9840. leftNameStr = qualifiedTypeRef->mLeft->ToStringView();
  9841. if (mSystem->ParseAtomComposite(leftNameStr, leftComposite))
  9842. leftIsValid = true;
  9843. }
  9844. if ((leftIsValid) && (qualifiedTypeRef->mRight != NULL))
  9845. {
  9846. StringT<128> findName;
  9847. auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(qualifiedTypeRef->mRight);
  9848. auto activeTypeDef = GetActiveTypeDef();
  9849. BfProject* bfProject = NULL;
  9850. if (activeTypeDef != NULL)
  9851. bfProject = activeTypeDef->mProject;
  9852. bool leftIsNamespace = false;
  9853. if (mSystem->ContainsNamespace(leftComposite, bfProject))
  9854. {
  9855. leftIsNamespace = true;
  9856. }
  9857. else if (checkProjects != NULL)
  9858. {
  9859. for (auto checkProject : *checkProjects)
  9860. {
  9861. if (mSystem->ContainsNamespace(leftComposite, checkProject))
  9862. {
  9863. leftIsNamespace = true;
  9864. break;
  9865. }
  9866. }
  9867. }
  9868. if (leftIsNamespace)
  9869. {
  9870. qualifiedTypeRef->mLeft->ToString(findName);
  9871. findName.Append('.');
  9872. if (genericTypeRef != NULL)
  9873. genericTypeRef->mElementType->ToString(findName);
  9874. else
  9875. qualifiedTypeRef->mRight->ToString(findName);
  9876. if ((resolveFlags & BfResolveTypeRefFlag_Attribute) != 0)
  9877. findName += "Attribute";
  9878. }
  9879. else if ((activeTypeDef != NULL) && (activeTypeDef->mNamespace.EndsWith(leftComposite)))
  9880. {
  9881. // Partial namespace reference, extend to a full reference
  9882. findName += activeTypeDef->mNamespace.ToString();
  9883. findName.Append('.');
  9884. qualifiedTypeRef->mRight->ToString(findName);
  9885. }
  9886. if (!findName.IsEmpty())
  9887. {
  9888. int wantNumGenericArgs = numGenericArgs;
  9889. #ifdef BF_AST_HAS_PARENT_MEMBER
  9890. if (auto genericTypeParent = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef->mParent))
  9891. {
  9892. BF_ASSERT(mParentNodeEntry->mNode == genericTypeParent);
  9893. //wantNumGenericArgs = (int)genericTypeParent->mGenericArguments.size();
  9894. //genericTypeRef = genericTypeParent;
  9895. }
  9896. #endif
  9897. if (mParentNodeEntry != NULL)
  9898. {
  9899. if (auto genericTypeParent = BfNodeDynCast<BfGenericInstanceTypeRef>(mParentNodeEntry->mNode))
  9900. {
  9901. wantNumGenericArgs = (int)genericTypeParent->mGenericArguments.size();
  9902. genericTypeRef = genericTypeParent;
  9903. }
  9904. }
  9905. BfTypeDef* ambiguousTypeDef = NULL;
  9906. BfTypeLookupError lookupError;
  9907. auto typeDef = FindTypeDef(findName, wantNumGenericArgs, NULL, &lookupError, resolveFlags);
  9908. if (typeDef != NULL)
  9909. {
  9910. if (ambiguousTypeDef != NULL)
  9911. ShowAmbiguousTypeError(typeRef, typeDef, ambiguousTypeDef);
  9912. BfTypeVector genericArgs;
  9913. if (populateType != BfPopulateType_TypeDef)
  9914. {
  9915. if (genericTypeRef != NULL)
  9916. {
  9917. for (auto genericParamTypeRef : genericTypeRef->mGenericArguments)
  9918. {
  9919. auto genericParam = ResolveTypeRef(genericParamTypeRef, NULL, BfPopulateType_Declaration);
  9920. if (genericParam == NULL)
  9921. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  9922. genericArgs.push_back(genericParam);
  9923. }
  9924. }
  9925. if (typeDef->mGenericParamDefs.size() != genericArgs.size())
  9926. {
  9927. prevIgnoreErrors.Restore();
  9928. BfAstNode* refNode = typeRef;
  9929. if (genericTypeRef != NULL)
  9930. refNode = genericTypeRef->mOpenChevron;
  9931. int wantedGenericParams = (int)typeDef->mGenericParamDefs.size();
  9932. if (wantedGenericParams == 1)
  9933. Fail("Expected one generic argument", refNode);
  9934. else
  9935. Fail(StrFormat("Expected %d generic arguments", wantedGenericParams), refNode);
  9936. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  9937. }
  9938. }
  9939. return ResolveTypeResult(typeRef, ResolveTypeDef(typeDef, genericArgs, populateType, resolveFlags), populateType, resolveFlags);
  9940. }
  9941. }
  9942. }
  9943. if (leftType == NULL)
  9944. {
  9945. BfAutoParentNodeEntry autoParentNodeEntry(this, qualifiedTypeRef);
  9946. auto leftPopulateType = BfPopulateType_Identity;
  9947. if ((resolveFlags & BfResolveTypeRefFlag_AllowUnboundGeneric) == 0)
  9948. {
  9949. // We can't just pass 'Identity' here because it won't validate a generic type ref on the left
  9950. leftPopulateType = BfPopulateType_Declaration;
  9951. }
  9952. leftType = ResolveTypeRef(qualifiedTypeRef->mLeft, leftPopulateType,
  9953. (BfResolveTypeRefFlags)((resolveFlags | BfResolveTypeRefFlag_IgnoreLookupError) & ~BfResolveTypeRefFlag_Attribute)); // We throw an error below if we can't find the type
  9954. }
  9955. if (leftType == NULL)
  9956. {
  9957. mIgnoreErrors = prevIgnoreErrors.mPrevVal;
  9958. BfTypeReference* errorRefNode = qualifiedTypeRef->mLeft;
  9959. if ((leftIsValid) && (mCurTypeInstance != NULL) && (mSystem->ContainsNamespace(leftComposite, curTypeDef->mProject)))
  9960. {
  9961. // The left was a namespace name, so throw an error on the whole string
  9962. errorRefNode = qualifiedTypeRef;
  9963. }
  9964. TypeRefNotFound(errorRefNode);
  9965. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  9966. }
  9967. prevIgnoreErrors.Restore();
  9968. if (qualifiedTypeRef->mRight == NULL)
  9969. {
  9970. FailAfter("Expected identifier", qualifiedTypeRef->mDot);
  9971. //AssertErrorState();
  9972. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  9973. }
  9974. if (leftType->IsGenericParam())
  9975. {
  9976. auto genericParam = GetGenericParamInstance((BfGenericParamType*)leftType);
  9977. if ((genericParam->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  9978. return ResolveTypeResult(typeRef, GetPrimitiveType(BfTypeCode_Var), populateType, resolveFlags);
  9979. if ((genericParam->IsEnum()) && (qualifiedTypeRef->mRight != NULL))
  9980. {
  9981. StringView findNameRight = qualifiedTypeRef->mRight->ToStringView();
  9982. if (findNameRight == "UnderlyingType")
  9983. return ResolveTypeResult(typeRef, GetPrimitiveType(BfTypeCode_Var), populateType, resolveFlags);
  9984. }
  9985. }
  9986. auto resolvedType = ResolveInnerType(leftType, qualifiedTypeRef->mRight, populateType, false, numGenericArgs, resolveFlags);
  9987. if ((resolvedType != NULL) && (mCurTypeInstance != NULL))
  9988. AddDependency(leftType, mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  9989. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  9990. // If we did a ResolveTypeResult, then that may process an alias as the alias-to type instead of the actual alias
  9991. //return ResolveInnerType(leftType, qualifiedTypeRef->mRight, populateType);
  9992. }
  9993. if (auto resolvedTypeRef = BfNodeDynCast<BfResolvedTypeReference>(typeRef))
  9994. {
  9995. return ResolveTypeResult(typeRef, resolvedTypeRef->mType, populateType, resolveFlags);
  9996. }
  9997. if (auto retTypeTypeRef = BfNodeDynCastExact<BfModifiedTypeRef>(typeRef))
  9998. {
  9999. if (retTypeTypeRef->mRetTypeToken->mToken == BfToken_RetType)
  10000. {
  10001. bool allowThrough = false;
  10002. BfType* resolvedType = NULL;
  10003. if (retTypeTypeRef->mElementType != NULL)
  10004. {
  10005. auto innerType = ResolveTypeRef(retTypeTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  10006. if (innerType != NULL)
  10007. {
  10008. if ((innerType->IsDelegate()) || (innerType->IsFunction()))
  10009. {
  10010. PopulateType(innerType, BfPopulateType_DataAndMethods);
  10011. BfMethodInstance* invokeMethodInstance = GetRawMethodInstanceAtIdx(innerType->ToTypeInstance(), 0, "Invoke");
  10012. if (invokeMethodInstance != NULL)
  10013. {
  10014. resolvedType = invokeMethodInstance->mReturnType;
  10015. if ((resolvedType != NULL) && (resolvedType->IsRef()))
  10016. resolvedType = resolvedType->GetUnderlyingType();
  10017. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  10018. }
  10019. }
  10020. else if (innerType->IsGenericParam())
  10021. {
  10022. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  10023. {
  10024. // We could have case where we have "rettype(@T0)" and @T0 gets a type variation of @M0, but we can't do a
  10025. // GetGenericParamInstance on that
  10026. allowThrough = true;
  10027. }
  10028. else
  10029. {
  10030. auto genericParamInstance = GetGenericParamInstance((BfGenericParamType*)innerType);
  10031. if (genericParamInstance->mTypeConstraint != NULL)
  10032. {
  10033. if ((genericParamInstance->mTypeConstraint->IsDelegate()) || (genericParamInstance->mTypeConstraint->IsFunction()))
  10034. {
  10035. resolvedType = GetDelegateReturnType(genericParamInstance->mTypeConstraint);
  10036. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  10037. }
  10038. else if ((genericParamInstance->mTypeConstraint->IsInstanceOf(mCompiler->mDelegateTypeDef)) ||
  10039. (genericParamInstance->mTypeConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))
  10040. {
  10041. allowThrough = true;
  10042. }
  10043. }
  10044. }
  10045. }
  10046. else if (innerType->IsMethodRef())
  10047. {
  10048. auto methodRefType = (BfMethodRefType*)innerType;
  10049. resolvedType = methodRefType->mMethodRef->mReturnType;
  10050. if ((resolvedType != NULL) && (resolvedType->IsRef()))
  10051. resolvedType = resolvedType->GetUnderlyingType();
  10052. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  10053. }
  10054. }
  10055. }
  10056. if (!allowThrough)
  10057. {
  10058. Fail("'rettype' can only be used on delegate or function types", retTypeTypeRef->mRetTypeToken);
  10059. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  10060. }
  10061. }
  10062. else if (retTypeTypeRef->mRetTypeToken->mToken == BfToken_AllocType)
  10063. {
  10064. BfType* resolvedType = NULL;
  10065. if (retTypeTypeRef->mElementType != NULL)
  10066. {
  10067. resolvedType = ResolveTypeRef(retTypeTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  10068. if (resolvedType != NULL)
  10069. {
  10070. if (resolvedType->IsGenericParam())
  10071. {
  10072. auto genericParam = GetGenericParamInstance((BfGenericParamType*)resolvedType);
  10073. if (((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsValueType())) ||
  10074. ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Enum)) != 0))
  10075. {
  10076. resolvedType = CreatePointerType(resolvedType);
  10077. }
  10078. else if (((genericParam->mTypeConstraint != NULL) && (!genericParam->mTypeConstraint->IsValueType())) ||
  10079. ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Class)) != 0))
  10080. {
  10081. // Leave as 'T'
  10082. }
  10083. else
  10084. resolvedType = CreateModifiedTypeType(resolvedType, BfToken_AllocType);
  10085. }
  10086. else if (resolvedType->IsValueType())
  10087. resolvedType = CreatePointerType(resolvedType);
  10088. }
  10089. }
  10090. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  10091. }
  10092. else if (retTypeTypeRef->mRetTypeToken->mToken == BfToken_Nullable)
  10093. {
  10094. bool allowThrough = false;
  10095. BfType* resolvedType = NULL;
  10096. if (retTypeTypeRef->mElementType != NULL)
  10097. {
  10098. resolvedType = ResolveTypeRef(retTypeTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  10099. }
  10100. if ((resolvedType != NULL) && (resolvedType->IsGenericParam()))
  10101. {
  10102. //resolvedType = CreateModifiedTypeType(resolvedType, BfToken_Nullable);
  10103. BfTypeVector typeVec;
  10104. typeVec.push_back(resolvedType);
  10105. resolvedType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec, BfPopulateType_Declaration);
  10106. }
  10107. else if (resolvedType != NULL)
  10108. {
  10109. if (resolvedType->IsValueType())
  10110. {
  10111. if (InDefinitionSection())
  10112. Warn(0, StrFormat("Consider using '%s?' instead of nullable modifier", TypeToString(resolvedType).c_str()), retTypeTypeRef);
  10113. BfTypeVector typeVec;
  10114. typeVec.push_back(resolvedType);
  10115. resolvedType = ResolveTypeDef(mCompiler->mNullableTypeDef, typeVec, BfPopulateType_Declaration);
  10116. }
  10117. else
  10118. {
  10119. if (InDefinitionSection())
  10120. Warn(0, StrFormat("Unneeded nullable modifier, %s is already nullable", TypeToString(resolvedType).c_str()), retTypeTypeRef->mRetTypeToken);
  10121. }
  10122. }
  10123. if (resolvedType != NULL)
  10124. PopulateType(resolvedType, populateType);
  10125. return resolvedType;
  10126. }
  10127. else
  10128. BFMODULE_FATAL(this, "Unhandled");
  10129. }
  10130. if (auto refTypeRef = BfNodeDynCastExact<BfRefTypeRef>(typeRef))
  10131. {
  10132. if ((refTypeRef->mRefToken != NULL) && (refTypeRef->mRefToken->GetToken() == BfToken_Mut) && (refTypeRef->mElementType != NULL))
  10133. {
  10134. bool needsRefWrap = false;
  10135. auto resolvedType = ResolveTypeRef(refTypeRef->mElementType, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  10136. if (resolvedType != NULL)
  10137. {
  10138. if ((resolvedType->IsValueType()) || (resolvedType->IsGenericParam()))
  10139. needsRefWrap = true;
  10140. if ((InDefinitionSection()) && (!resolvedType->IsGenericParam()) && ((resolveFlags & BfResolveTypeRefFlag_NoWarnOnMut) == 0))
  10141. {
  10142. if (!resolvedType->IsValueType())
  10143. Warn(0, StrFormat("Specified 'mut' has no effect on '%s' since reference types are always mutable", TypeToString(resolvedType).c_str()), refTypeRef->mRefToken);
  10144. else
  10145. Warn(0, "Use 'mut' for generic arguments which may or may not be reference types. Consider using 'ref' here, instead.", refTypeRef->mRefToken);
  10146. }
  10147. }
  10148. if (!needsRefWrap)
  10149. {
  10150. // Non-composites (including pointers) don't actually need ref-wrapping for 'mut'
  10151. return ResolveTypeResult(typeRef, resolvedType, populateType, resolveFlags);
  10152. }
  10153. }
  10154. }
  10155. static int sCallIdx = 0;
  10156. int callIdx = 0;
  10157. if (!mCompiler->mIsResolveOnly)
  10158. {
  10159. callIdx = sCallIdx++;
  10160. if (callIdx == 0x0000A224)
  10161. {
  10162. NOP;
  10163. }
  10164. }
  10165. BfResolvedTypeSet::LookupContext lookupCtx;
  10166. lookupCtx.mResolveFlags = (BfResolveTypeRefFlags)(resolveFlags &
  10167. (BfResolveTypeRefFlag_NoCreate | BfResolveTypeRefFlag_IgnoreLookupError | BfResolveTypeRefFlag_DisallowComptime |
  10168. BfResolveTypeRefFlag_AllowInferredSizedArray | BfResolveTypeRefFlag_Attribute | BfResolveTypeRefFlag_AllowUnboundGeneric |
  10169. BfResolveTypeRefFlag_ForceUnboundGeneric | BfResolveTypeRefFlag_AllowGenericParamConstValue |
  10170. BfResolveTypeRefFlag_AllowImplicitConstExpr | BfResolveTypeRefFlag_SpecializedProject));
  10171. lookupCtx.mRootTypeRef = typeRef;
  10172. lookupCtx.mRootTypeDef = typeDef;
  10173. lookupCtx.mModule = this;
  10174. BfResolvedTypeSet::EntryRef resolvedEntry;
  10175. if (auto delegateTypeRef = BfNodeDynCastExact<BfDelegateTypeRef>(typeRef))
  10176. GetDelegateTypeRefAttributes(delegateTypeRef, lookupCtx.mCallingConvention);
  10177. auto inserted = mContext->mResolvedTypes.Insert(typeRef, &lookupCtx, &resolvedEntry);
  10178. if (!resolvedEntry)
  10179. {
  10180. if (lookupCtx.mHadVar)
  10181. return ResolveTypeResult(typeRef, GetPrimitiveType(BfTypeCode_Var), populateType, resolveFlags);
  10182. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  10183. }
  10184. if (!inserted)
  10185. {
  10186. BF_ASSERT(resolvedEntry->mValue != NULL);
  10187. BF_ASSERT(!resolvedEntry->mValue->IsDeleting());
  10188. return ResolveTypeResult(typeRef, resolvedEntry->mValue, populateType, resolveFlags);
  10189. }
  10190. defer({
  10191. if (resolvedEntry->mValue == NULL)
  10192. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  10193. });
  10194. if ((lookupCtx.mIsUnboundGeneric) && (lookupCtx.mRootTypeDef != NULL))
  10195. {
  10196. return ResolveTypeResult(typeRef, ResolveTypeDef(lookupCtx.mRootTypeDef), populateType, resolveFlags);
  10197. }
  10198. if ((resolveFlags & BfResolveTypeRefFlag_NoCreate) != 0)
  10199. {
  10200. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  10201. }
  10202. BfModule* populateModule = this;
  10203. if ((resolveFlags & BfResolveTypeRefFlag_NoReify) != 0)
  10204. populateModule = mContext->mUnreifiedModule;
  10205. if (typeRef->IsTypeDefTypeReference())
  10206. {
  10207. //BF_ASSERT(typeDefTypeRef->mTypeDef != NULL); // Resolved higher up
  10208. //auto typeDef = typeDefTypeRef->mTypeDef;
  10209. if ((typeDef->mTypeCode >= BfTypeCode_None) && (typeDef->mTypeCode <= BfTypeCode_Double))
  10210. {
  10211. BfPrimitiveType* primType = new BfPrimitiveType();
  10212. primType->mTypeDef = typeDef;
  10213. resolvedEntry->mValue = primType;
  10214. BF_ASSERT(BfResolvedTypeSet::Hash(primType, &lookupCtx, false) == resolvedEntry->mHashCode);
  10215. populateModule->InitType(primType, populateType);
  10216. return ResolveTypeResult(typeRef, primType, populateType, resolveFlags);
  10217. }
  10218. BfTypeInstance* outerTypeInstance = lookupCtx.mRootOuterTypeInstance;
  10219. if (outerTypeInstance == NULL)
  10220. outerTypeInstance = mCurTypeInstance;
  10221. if ((outerTypeInstance != NULL) && (typeDef->mGenericParamDefs.size() != 0))
  10222. {
  10223. // Try to inherit generic params from current parent
  10224. BfTypeDef* outerType = mSystem->GetCombinedPartial(typeDef->mOuterType);
  10225. BF_ASSERT(!outerType->mIsPartial);
  10226. if (TypeHasParentOrEquals(outerTypeInstance->mTypeDef, outerType))
  10227. {
  10228. BfType* checkCurType = outerTypeInstance;
  10229. if (checkCurType->IsBoxed())
  10230. checkCurType = checkCurType->GetUnderlyingType();
  10231. if (checkCurType->IsTypeAlias())
  10232. checkCurType = GetOuterType(checkCurType);
  10233. BF_ASSERT(checkCurType->IsGenericTypeInstance());
  10234. int numParentGenericParams = (int)outerType->mGenericParamDefs.size();
  10235. int wantedGenericParams = (int)typeDef->mGenericParamDefs.size() - numParentGenericParams;
  10236. if (wantedGenericParams != 0)
  10237. {
  10238. if (wantedGenericParams == 1)
  10239. Fail("Expected generic argument", typeRef);
  10240. else
  10241. Fail(StrFormat("Expected %d generic arguments", wantedGenericParams), typeRef);
  10242. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  10243. }
  10244. auto parentGenericTypeInstance = (BfTypeInstance*)checkCurType;
  10245. BfTypeInstance* genericTypeInst;
  10246. if (typeDef->mTypeCode == BfTypeCode_TypeAlias)
  10247. {
  10248. auto typeAliasType = new BfTypeAliasType();
  10249. genericTypeInst = typeAliasType;
  10250. }
  10251. else
  10252. genericTypeInst = new BfTypeInstance();
  10253. genericTypeInst->mGenericTypeInfo = new BfGenericTypeInfo();
  10254. genericTypeInst->mTypeDef = typeDef;
  10255. if (parentGenericTypeInstance->mGenericTypeInfo->mGenericParams.IsEmpty())
  10256. PopulateType(parentGenericTypeInstance, BfPopulateType_Declaration);
  10257. for (int i = 0; i < numParentGenericParams; i++)
  10258. {
  10259. genericTypeInst->mGenericTypeInfo->mGenericParams.push_back(parentGenericTypeInstance->mGenericTypeInfo->mGenericParams[i]->AddRef());
  10260. genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.push_back(parentGenericTypeInstance->mGenericTypeInfo->mTypeGenericArguments[i]);
  10261. }
  10262. CheckUnspecializedGenericType(genericTypeInst, populateType);
  10263. resolvedEntry->mValue = genericTypeInst;
  10264. populateModule->InitType(genericTypeInst, populateType);
  10265. #ifdef _DEBUG
  10266. if (BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx) != resolvedEntry->mHashCode)
  10267. {
  10268. int refHash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx);
  10269. int typeHash = BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx);
  10270. BF_ASSERT(refHash == typeHash);
  10271. }
  10272. #endif
  10273. return ResolveTypeResult(typeRef, genericTypeInst, populateType, resolveFlags);
  10274. }
  10275. }
  10276. BfTypeInstance* typeInst;
  10277. if (typeDef->mTypeCode == BfTypeCode_TypeAlias)
  10278. {
  10279. auto typeAliasType = new BfTypeAliasType();
  10280. typeInst = typeAliasType;
  10281. }
  10282. else
  10283. {
  10284. typeInst = new BfTypeInstance();
  10285. }
  10286. typeInst->mTypeDef = typeDef;
  10287. if (((resolveFlags & BfResolveTypeRefFlag_NoReify) != 0) && (mCompiler->mOptions.mCompileOnDemandKind != BfCompileOnDemandKind_AlwaysInclude))
  10288. {
  10289. typeInst->mIsReified = false;
  10290. }
  10291. if (typeInst->mTypeDef->mGenericParamDefs.size() != 0)
  10292. {
  10293. Fail("Generic type arguments expected", typeRef);
  10294. delete typeInst;
  10295. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  10296. }
  10297. resolvedEntry->mValue = typeInst;
  10298. #ifdef _DEBUG
  10299. int typeRefash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx);
  10300. #endif
  10301. populateModule->InitType(typeInst, populateType);
  10302. if (BfResolvedTypeSet::Hash(typeInst, &lookupCtx) != resolvedEntry->mHashCode)
  10303. {
  10304. int refHash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx);
  10305. int typeHash = BfResolvedTypeSet::Hash(typeInst, &lookupCtx);
  10306. BF_ASSERT(refHash == typeHash);
  10307. }
  10308. {
  10309. BF_ASSERT(BfResolvedTypeSet::Hash(typeInst, &lookupCtx) == resolvedEntry->mHashCode);
  10310. }
  10311. return ResolveTypeResult(typeRef, typeInst, populateType, resolveFlags);
  10312. }
  10313. else if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(typeRef))
  10314. {
  10315. if (arrayTypeRef->mDimensions > 4)
  10316. {
  10317. Fail("Too many array dimensions, consider using a jagged array.", arrayTypeRef);
  10318. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  10319. }
  10320. auto elementType = ResolveTypeRef(arrayTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  10321. auto arrayTypeDef = mCompiler->GetArrayTypeDef(arrayTypeRef->mDimensions);
  10322. if ((elementType == NULL) || (arrayTypeDef == NULL))
  10323. {
  10324. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  10325. }
  10326. if ((arrayTypeRef->mDimensions == 1) && (arrayTypeRef->mParams.size() == 1))
  10327. {
  10328. intptr elementCount = -1;
  10329. BfExpression* sizeExpr = BfNodeDynCast<BfExpression>(arrayTypeRef->mParams[0]);
  10330. BF_ASSERT(sizeExpr != NULL);
  10331. if (sizeExpr != NULL)
  10332. {
  10333. BfType* intType = GetPrimitiveType(BfTypeCode_IntPtr);
  10334. BfTypedValue typedVal;
  10335. lookupCtx.mResolvedValueMap.TryGetValue(sizeExpr, &typedVal);
  10336. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  10337. {
  10338. BfUnknownSizedArrayType* arrayType = new BfUnknownSizedArrayType();
  10339. arrayType->mContext = mContext;
  10340. arrayType->mElementType = elementType;
  10341. arrayType->mElementCount = -1;
  10342. arrayType->mElementCountSource = typedVal.mType;
  10343. resolvedEntry->mValue = arrayType;
  10344. BF_ASSERT(BfResolvedTypeSet::Hash(arrayType, &lookupCtx) == resolvedEntry->mHashCode);
  10345. populateModule->InitType(arrayType, populateType);
  10346. return ResolveTypeResult(typeRef, arrayType, populateType, resolveFlags);
  10347. }
  10348. if (typedVal)
  10349. typedVal = Cast(sizeExpr, typedVal, intType);
  10350. if (typedVal)
  10351. {
  10352. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  10353. if (constant != NULL)
  10354. {
  10355. if (constant->mConstType == BfConstType_Undef)
  10356. elementCount = -1; // Undef marker
  10357. else if (BfIRBuilder::IsInt(constant->mTypeCode))
  10358. elementCount = (intptr)constant->mInt64;
  10359. }
  10360. }
  10361. }
  10362. /*if (elementCount < 0)
  10363. {
  10364. Fail(StrFormat("Array length '%d' is illegal", elementCount), arrayTypeRef->mParams[0]);
  10365. mContext->mResolvedTypes.RemoveEntry(resolvedEntry);
  10366. return CreateSizedArrayType(elementType, 0);
  10367. }*/
  10368. BfSizedArrayType* arrayType = new BfSizedArrayType();
  10369. arrayType->mContext = mContext;
  10370. arrayType->mElementType = elementType;
  10371. arrayType->mElementCount = elementCount;
  10372. arrayType->mWantsGCMarking = false; // Fill in in InitType
  10373. arrayType->mGenericDepth = elementType->GetGenericDepth() + 1;
  10374. resolvedEntry->mValue = arrayType;
  10375. BF_ASSERT(BfResolvedTypeSet::Hash(arrayType, &lookupCtx) == resolvedEntry->mHashCode);
  10376. populateModule->InitType(arrayType, populateType);
  10377. return ResolveTypeResult(typeRef, arrayType, populateType, resolveFlags);
  10378. }
  10379. BfArrayType* arrayType = new BfArrayType();
  10380. arrayType->mGenericTypeInfo = new BfGenericTypeInfo();
  10381. arrayType->mContext = mContext;
  10382. arrayType->mDimensions = arrayTypeRef->mDimensions;
  10383. arrayType->mTypeDef = arrayTypeDef;
  10384. arrayType->mGenericTypeInfo->mTypeGenericArguments.push_back(elementType);
  10385. resolvedEntry->mValue = arrayType;
  10386. CheckUnspecializedGenericType(arrayType, populateType);
  10387. BF_ASSERT(BfResolvedTypeSet::Hash(arrayType, &lookupCtx) == resolvedEntry->mHashCode);
  10388. populateModule->InitType(arrayType, populateType);
  10389. return ResolveTypeResult(typeRef, arrayType, populateType, resolveFlags);
  10390. }
  10391. else if (auto genericTypeInstRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  10392. {
  10393. BfTypeReference* outerTypeRef = NULL;
  10394. Array<BfAstNode*> genericArguments;
  10395. BfTypeReference* checkTypeRef = genericTypeInstRef;
  10396. int checkIdx = 0;
  10397. while (checkTypeRef != NULL)
  10398. {
  10399. checkIdx++;
  10400. if (checkIdx >= 3)
  10401. {
  10402. outerTypeRef = checkTypeRef;
  10403. break;
  10404. }
  10405. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(checkTypeRef))
  10406. {
  10407. for (auto genericArg : genericTypeRef->mGenericArguments)
  10408. genericArguments.push_back(genericArg);
  10409. checkTypeRef = genericTypeRef->mElementType;
  10410. continue;
  10411. }
  10412. if (auto elementedTypeRef = BfNodeDynCast<BfElementedTypeRef>(checkTypeRef))
  10413. {
  10414. checkTypeRef = elementedTypeRef->mElementType;
  10415. continue;
  10416. }
  10417. if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(checkTypeRef))
  10418. {
  10419. checkTypeRef = qualifiedTypeRef->mLeft;
  10420. continue;
  10421. }
  10422. break;
  10423. }
  10424. BfTypeVector genericArgs;
  10425. BfType* type = NULL;
  10426. BfTypeDef* typeDef = ResolveGenericInstanceDef(genericTypeInstRef, &type, resolveFlags);
  10427. if (typeDef == NULL)
  10428. {
  10429. Fail("Unable to resolve type", typeRef);
  10430. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  10431. }
  10432. BfTypeInstance* outerTypeInstance = NULL;
  10433. BfTypeDef* commonOuterType = NULL;
  10434. int startDefGenericParamIdx = 0;
  10435. if (outerTypeRef != NULL)
  10436. {
  10437. BfType* outerType = lookupCtx.GetCachedResolvedType(outerTypeRef);
  10438. if (outerType != NULL)
  10439. {
  10440. outerTypeInstance = outerType->ToTypeInstance();
  10441. commonOuterType = outerTypeInstance->mTypeDef;
  10442. }
  10443. }
  10444. else
  10445. {
  10446. outerTypeInstance = mCurTypeInstance;
  10447. auto outerType = typeDef->mOuterType;
  10448. commonOuterType = BfResolvedTypeSet::FindRootCommonOuterType(outerType, &lookupCtx, outerTypeInstance);
  10449. }
  10450. if ((commonOuterType) && (outerTypeInstance->IsGenericTypeInstance()))
  10451. {
  10452. startDefGenericParamIdx = (int)commonOuterType->mGenericParamDefs.size();
  10453. auto parentTypeInstance = outerTypeInstance;
  10454. if (parentTypeInstance->IsTypeAlias())
  10455. parentTypeInstance = (BfTypeInstance*)GetOuterType(parentTypeInstance)->ToTypeInstance();
  10456. for (int i = 0; i < startDefGenericParamIdx; i++)
  10457. genericArgs.push_back(parentTypeInstance->mGenericTypeInfo->mTypeGenericArguments[i]);
  10458. }
  10459. for (auto genericArgRef : genericArguments)
  10460. {
  10461. BfType* genericArg = NULL;
  10462. lookupCtx.mResolvedTypeMap.TryGetValue(genericArgRef, &genericArg);
  10463. if (genericArg == NULL)
  10464. genericArg = ResolveTypeRef(genericArgRef, NULL, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_AllowGenericTypeParamConstValue | BfResolveTypeRefFlag_AllowGenericMethodParamConstValue));
  10465. if ((genericArg == NULL) || (genericArg->IsVar()))
  10466. {
  10467. return ResolveTypeResult(typeRef, ((genericArg != NULL) && (genericArg->IsVar())) ? genericArg : NULL, populateType, resolveFlags);
  10468. }
  10469. genericArgs.Add(genericArg);
  10470. }
  10471. BfTypeInstance* genericTypeInst;
  10472. if ((type != NULL) &&
  10473. ((type->IsDelegateFromTypeRef()) || (type->IsFunctionFromTypeRef())))
  10474. {
  10475. return ResolveGenericType(type, &genericArgs, NULL, mCurTypeInstance);
  10476. }
  10477. else if ((type != NULL) && (type->IsTuple()))
  10478. {
  10479. return ResolveGenericType(type, &genericArgs, NULL, mCurTypeInstance);
  10480. }
  10481. else if ((typeDef != NULL) && (typeDef->mTypeCode == BfTypeCode_TypeAlias))
  10482. {
  10483. auto typeAliasType = new BfTypeAliasType();
  10484. genericTypeInst = typeAliasType;
  10485. }
  10486. else
  10487. genericTypeInst = new BfTypeInstance();
  10488. genericTypeInst->mContext = mContext;
  10489. genericTypeInst->mGenericTypeInfo = new BfGenericTypeInfo();
  10490. BF_ASSERT(typeDef->mDefState != BfTypeDef::DefState_Deleted);
  10491. int genericParamCount = (int)typeDef->mGenericParamDefs.size();
  10492. if ((type != NULL) && (type->IsGenericTypeInstance()))
  10493. {
  10494. // Is a generic type for sure...
  10495. // We need this case for generic methods
  10496. genericParamCount = (int)((BfTypeInstance*)type)->mGenericTypeInfo->mTypeGenericArguments.size();
  10497. }
  10498. else if (typeDef->mGenericParamDefs.size() == 0)
  10499. {
  10500. Fail("Not a generic type", typeRef);
  10501. delete genericTypeInst;
  10502. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  10503. }
  10504. genericTypeInst->mTypeDef = typeDef;
  10505. if (commonOuterType != NULL)
  10506. {
  10507. auto parentTypeInstance = outerTypeInstance;
  10508. if ((parentTypeInstance != NULL) && (parentTypeInstance->IsTypeAlias()))
  10509. parentTypeInstance = (BfTypeInstance*)GetOuterType(parentTypeInstance)->ToTypeInstance();
  10510. if (parentTypeInstance->mDefineState < BfTypeDefineState_Declared)
  10511. PopulateType(parentTypeInstance, BfPopulateType_Declaration);
  10512. if ((parentTypeInstance != NULL) && (parentTypeInstance->IsGenericTypeInstance()))
  10513. {
  10514. genericTypeInst->mGenericTypeInfo->mMaxGenericDepth = BF_MAX(genericTypeInst->mGenericTypeInfo->mMaxGenericDepth, parentTypeInstance->mGenericTypeInfo->mMaxGenericDepth);
  10515. for (int i = 0; i < startDefGenericParamIdx; i++)
  10516. {
  10517. genericTypeInst->mGenericTypeInfo->mGenericParams.push_back(parentTypeInstance->mGenericTypeInfo->mGenericParams[i]->AddRef());
  10518. genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.push_back(parentTypeInstance->mGenericTypeInfo->mTypeGenericArguments[i]);
  10519. auto typeGenericArg = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[i];
  10520. genericTypeInst->mGenericTypeInfo->mIsUnspecialized |= typeGenericArg->IsGenericParam() || typeGenericArg->IsUnspecializedType();
  10521. }
  10522. }
  10523. }
  10524. int wantedGenericParams = genericParamCount - startDefGenericParamIdx;
  10525. int genericArgDiffCount = (int)genericArguments.size() - wantedGenericParams;
  10526. if (genericArgDiffCount != 0)
  10527. {
  10528. int innerWantedGenericParams = genericParamCount;
  10529. if (typeDef->mOuterType != NULL)
  10530. innerWantedGenericParams -= (int)typeDef->mOuterType->mGenericParamDefs.size();
  10531. ShowGenericArgCountError(genericTypeInstRef, innerWantedGenericParams);
  10532. delete genericTypeInst;
  10533. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  10534. }
  10535. int genericParamIdx = 0;
  10536. for (auto genericArgRef : genericArguments)
  10537. {
  10538. auto genericArg = genericArgs[genericParamIdx + startDefGenericParamIdx];
  10539. genericTypeInst->mGenericTypeInfo->mMaxGenericDepth = BF_MAX(genericTypeInst->mGenericTypeInfo->mMaxGenericDepth, genericArg->GetGenericDepth() + 1);
  10540. genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.push_back(genericArg);
  10541. genericParamIdx++;
  10542. }
  10543. if (genericTypeInst->mGenericTypeInfo->mMaxGenericDepth > 64)
  10544. {
  10545. Fail("Maximum generic depth exceeded", typeRef);
  10546. delete genericTypeInst;
  10547. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  10548. }
  10549. resolvedEntry->mValue = genericTypeInst;
  10550. CheckUnspecializedGenericType(genericTypeInst, populateType);
  10551. populateModule->InitType(genericTypeInst, populateType);
  10552. #ifdef _DEBUG
  10553. if (BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx) != resolvedEntry->mHashCode)
  10554. {
  10555. int refHash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx);
  10556. int typeHash = BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx);
  10557. BF_ASSERT(refHash == typeHash);
  10558. BF_ASSERT(refHash == resolvedEntry->mHashCode);
  10559. }
  10560. if (!BfResolvedTypeSet::Equals(genericTypeInst, typeRef, &lookupCtx))
  10561. {
  10562. BF_ASSERT(BfResolvedTypeSet::Equals(genericTypeInst, typeRef, &lookupCtx) || (mCompiler->mCanceling));
  10563. }
  10564. BfLogSysM("Generic type %p typeHash: %8X\n", genericTypeInst, resolvedEntry->mHashCode);
  10565. #endif
  10566. BF_ASSERT(BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx) == resolvedEntry->mHashCode);
  10567. return ResolveTypeResult(typeRef, genericTypeInst, populateType, resolveFlags);
  10568. }
  10569. else if (auto tupleTypeRef = BfNodeDynCast<BfTupleTypeRef>(typeRef))
  10570. {
  10571. Array<BfType*> types;
  10572. Array<String> names;
  10573. bool wantGeneric = false;
  10574. bool isUnspecialized = false;
  10575. for (int fieldIdx = 0; fieldIdx < (int)tupleTypeRef->mFieldTypes.size(); fieldIdx++)
  10576. {
  10577. BfTypeReference* typeRef = tupleTypeRef->mFieldTypes[fieldIdx];
  10578. auto type = ResolveTypeRef(typeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  10579. if (type == NULL)
  10580. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  10581. String fieldName;
  10582. BfIdentifierNode* identifierNode = NULL;
  10583. if (fieldIdx < (int)tupleTypeRef->mFieldNames.size())
  10584. identifierNode = tupleTypeRef->mFieldNames[fieldIdx];
  10585. if (identifierNode != NULL)
  10586. fieldName = identifierNode->ToString();
  10587. else
  10588. fieldName = StrFormat("%d", fieldIdx);
  10589. if (type->IsTypeGenericParam())
  10590. wantGeneric = true;
  10591. if (type->IsUnspecializedType())
  10592. isUnspecialized = true;
  10593. if (type->IsVar())
  10594. {
  10595. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  10596. }
  10597. types.push_back(type);
  10598. names.push_back(fieldName);
  10599. }
  10600. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsGenericTypeInstance()))
  10601. wantGeneric = false;
  10602. //TODO:
  10603. wantGeneric = false;
  10604. auto baseType = (BfTypeInstance*)ResolveTypeDef(mContext->mCompiler->mValueTypeTypeDef, BfPopulateType_Identity);
  10605. BfTupleType* tupleType = NULL;
  10606. if (wantGeneric)
  10607. {
  10608. BfTupleType* actualTupleType = new BfTupleType();
  10609. actualTupleType->mGenericTypeInfo = new BfGenericTypeInfo();
  10610. actualTupleType->mGenericTypeInfo->mFinishedGenericParams = true;
  10611. actualTupleType->Init(baseType->mTypeDef->mProject, baseType);
  10612. for (int fieldIdx = 0; fieldIdx < (int)types.size(); fieldIdx++)
  10613. {
  10614. BfFieldDef* fieldDef = actualTupleType->AddField(names[fieldIdx]);
  10615. fieldDef->mProtection = (names[fieldIdx][0] == '_') ? BfProtection_Private : BfProtection_Public;
  10616. }
  10617. actualTupleType->Finish();
  10618. auto parentTypeInstance = (BfTypeInstance*)mCurTypeInstance;
  10619. for (int i = 0; i < parentTypeInstance->mGenericTypeInfo->mGenericParams.size(); i++)
  10620. {
  10621. actualTupleType->mGenericTypeInfo->mGenericParams.push_back(parentTypeInstance->mGenericTypeInfo->mGenericParams[i]->AddRef());
  10622. }
  10623. for (int i = 0; i < parentTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(); i++)
  10624. {
  10625. actualTupleType->mGenericTypeInfo->mTypeGenericArguments.push_back(parentTypeInstance->mGenericTypeInfo->mTypeGenericArguments[i]);
  10626. auto typeGenericArg = actualTupleType->mGenericTypeInfo->mTypeGenericArguments[i];
  10627. actualTupleType->mGenericTypeInfo->mIsUnspecialized |= typeGenericArg->IsGenericParam() || typeGenericArg->IsUnspecializedType();
  10628. }
  10629. CheckUnspecializedGenericType(actualTupleType, populateType);
  10630. if (isUnspecialized)
  10631. {
  10632. actualTupleType->mGenericTypeInfo->mIsUnspecialized = true;
  10633. actualTupleType->mGenericTypeInfo->mIsUnspecializedVariation = true;
  10634. }
  10635. actualTupleType->mIsUnspecializedType = actualTupleType->mGenericTypeInfo->mIsUnspecialized;
  10636. actualTupleType->mIsUnspecializedTypeVariation = actualTupleType->mGenericTypeInfo->mIsUnspecializedVariation;
  10637. tupleType = actualTupleType;
  10638. }
  10639. else
  10640. {
  10641. BfTupleType* actualTupleType = new BfTupleType();
  10642. actualTupleType->Init(baseType->mTypeDef->mProject, baseType);
  10643. for (int fieldIdx = 0; fieldIdx < (int)types.size(); fieldIdx++)
  10644. {
  10645. BfFieldDef* fieldDef = actualTupleType->AddField(names[fieldIdx]);
  10646. fieldDef->mProtection = (names[fieldIdx][0] == '_') ? BfProtection_Private : BfProtection_Public;
  10647. }
  10648. actualTupleType->Finish();
  10649. tupleType = actualTupleType;
  10650. actualTupleType->mIsUnspecializedType = isUnspecialized;
  10651. actualTupleType->mIsUnspecializedTypeVariation = isUnspecialized;
  10652. }
  10653. tupleType->mFieldInstances.Resize(types.size());
  10654. for (int fieldIdx = 0; fieldIdx < (int)types.size(); fieldIdx++)
  10655. {
  10656. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  10657. fieldInstance->mFieldIdx = fieldIdx;
  10658. fieldInstance->SetResolvedType(types[fieldIdx]);
  10659. BF_ASSERT(!types[fieldIdx]->IsVar());
  10660. fieldInstance->mOwner = tupleType;
  10661. tupleType->mGenericDepth = BF_MAX(tupleType->mGenericDepth, fieldInstance->mResolvedType->GetGenericDepth() + 1);
  10662. }
  10663. resolvedEntry->mValue = tupleType;
  10664. BF_ASSERT(BfResolvedTypeSet::Hash(tupleType, &lookupCtx) == resolvedEntry->mHashCode);
  10665. populateModule->InitType(tupleType, populateType);
  10666. return ResolveTypeResult(typeRef, tupleType, populateType, resolveFlags);
  10667. }
  10668. else if (auto tagTypeRef = BfNodeDynCast<BfTagTypeRef>(typeRef))
  10669. {
  10670. auto baseType = (BfTypeInstance*)ResolveTypeDef(mContext->mCompiler->mEnumTypeDef, BfPopulateType_Identity);
  10671. BfTagType* tagType = new BfTagType();
  10672. tagType->Init(baseType->mTypeDef->mProject, baseType, tagTypeRef->mNameNode->ToString());
  10673. resolvedEntry->mValue = tagType;
  10674. BF_ASSERT(BfResolvedTypeSet::Hash(tagType, &lookupCtx) == resolvedEntry->mHashCode);
  10675. populateModule->InitType(tagType, populateType);
  10676. return ResolveTypeResult(typeRef, tagType, populateType, resolveFlags);
  10677. }
  10678. else if (auto nullableTypeRef = BfNodeDynCast<BfNullableTypeRef>(typeRef))
  10679. {
  10680. BfTypeReference* elementTypeRef = nullableTypeRef->mElementType;
  10681. auto typeDef = mCompiler->mNullableTypeDef;
  10682. auto elementType = ResolveTypeRef(elementTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  10683. if ((elementType == NULL) || (elementType->IsVar()))
  10684. return ResolveTypeResult(typeRef, elementType, populateType, resolveFlags);
  10685. BfTypeInstance* genericTypeInst = new BfTypeInstance();
  10686. genericTypeInst->mGenericTypeInfo = new BfGenericTypeInfo();
  10687. genericTypeInst->mContext = mContext;
  10688. genericTypeInst->mTypeDef = typeDef;
  10689. auto genericParamInstance = new BfGenericTypeParamInstance(typeDef, 0);
  10690. genericTypeInst->mGenericTypeInfo->mGenericParams.push_back(genericParamInstance);
  10691. genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.push_back(elementType);
  10692. //genericTypeInst->mIsUnspecialized = elementType->IsGenericParam() || elementType->IsUnspecializedType();
  10693. CheckUnspecializedGenericType(genericTypeInst, populateType);
  10694. resolvedEntry->mValue = genericTypeInst;
  10695. #ifdef _DEBUG
  10696. if (BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx) != resolvedEntry->mHashCode)
  10697. {
  10698. int refHash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx);
  10699. int typeHash = BfResolvedTypeSet::Hash(genericTypeInst, &lookupCtx);
  10700. BF_ASSERT(refHash == typeHash);
  10701. }
  10702. #endif
  10703. populateModule->InitType(genericTypeInst, populateType);
  10704. return ResolveTypeResult(typeRef, genericTypeInst, populateType, resolveFlags);
  10705. }
  10706. else if (auto pointerTypeRef = BfNodeDynCast<BfPointerTypeRef>(typeRef))
  10707. {
  10708. BfPointerType* pointerType = new BfPointerType();
  10709. auto elementType = ResolveTypeRef(pointerTypeRef->mElementType, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  10710. if ((elementType == NULL) || (elementType->IsVar()))
  10711. {
  10712. delete pointerType;
  10713. return ResolveTypeResult(typeRef, elementType, populateType, resolveFlags);
  10714. }
  10715. pointerType->mGenericDepth = elementType->GetGenericDepth() + 1;
  10716. pointerType->mElementType = elementType;
  10717. pointerType->mContext = mContext;
  10718. resolvedEntry->mValue = pointerType;
  10719. //int hashVal = mContext->mResolvedTypes.Hash(typeRef, &lookupCtx);
  10720. BF_ASSERT(BfResolvedTypeSet::Hash(pointerType, &lookupCtx) == resolvedEntry->mHashCode);
  10721. populateModule->InitType(pointerType, populateType);
  10722. return ResolveTypeResult(typeRef, pointerType, populateType, resolveFlags);
  10723. }
  10724. else if (auto refTypeRef = BfNodeDynCast<BfRefTypeRef>(typeRef))
  10725. {
  10726. BfRefType* refType = new BfRefType();
  10727. refType->mRefKind = BfRefType::RefKind_Ref;
  10728. if (refTypeRef->mRefToken == NULL)
  10729. refType->mRefKind = BfRefType::RefKind_Ref;
  10730. else if (refTypeRef->mRefToken->GetToken() == BfToken_In)
  10731. refType->mRefKind = BfRefType::RefKind_In;
  10732. else if (refTypeRef->mRefToken->GetToken() == BfToken_Out)
  10733. refType->mRefKind = BfRefType::RefKind_Out;
  10734. else if (refTypeRef->mRefToken->GetToken() == BfToken_Mut)
  10735. refType->mRefKind = BfRefType::RefKind_Mut;
  10736. auto elementType = ResolveTypeRef(refTypeRef->mElementType, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  10737. if ((elementType == NULL) || (elementType->IsVar()))
  10738. {
  10739. delete refType;
  10740. return ResolveTypeResult(typeRef, elementType, populateType, resolveFlags);
  10741. }
  10742. refType->mElementType = elementType;
  10743. resolvedEntry->mValue = refType;
  10744. #ifdef _DEBUG
  10745. if (BfResolvedTypeSet::Hash(refType, &lookupCtx) != resolvedEntry->mHashCode)
  10746. {
  10747. int refHash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx, BfResolvedTypeSet::BfHashFlag_AllowRef);
  10748. int typeHash = BfResolvedTypeSet::Hash(refType, &lookupCtx);
  10749. BF_ASSERT(refHash == typeHash);
  10750. }
  10751. BF_ASSERT(BfResolvedTypeSet::Equals(refType, typeRef, &lookupCtx));
  10752. #endif
  10753. populateModule->InitType(refType, populateType);
  10754. return ResolveTypeResult(typeRef, refType, populateType, resolveFlags);
  10755. }
  10756. else if (auto delegateTypeRef = BfNodeDynCast<BfDelegateTypeRef>(typeRef))
  10757. {
  10758. bool wantGeneric = false;
  10759. bool isUnspecialized = false;
  10760. auto _CheckType = [&](BfType* type)
  10761. {
  10762. if (type->IsTypeGenericParam())
  10763. wantGeneric = true;
  10764. if (type->IsUnspecializedType())
  10765. isUnspecialized = true;
  10766. };
  10767. bool failed = false;
  10768. auto returnType = ResolveTypeRef(delegateTypeRef->mReturnType, NULL, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowRef);
  10769. if (returnType == NULL)
  10770. {
  10771. failed = true;
  10772. returnType = GetPrimitiveType(BfTypeCode_Var);
  10773. }
  10774. _CheckType(returnType);
  10775. BfType* functionThisType = NULL;
  10776. bool hasMutSpecifier = false;
  10777. bool isFirst = true;
  10778. bool isDelegate = delegateTypeRef->mTypeToken->GetToken() == BfToken_Delegate;
  10779. bool hasVarArgs = false;
  10780. Array<BfType*> paramTypes;
  10781. for (int paramIdx = 0; paramIdx < delegateTypeRef->mParams.size(); paramIdx++)
  10782. {
  10783. auto param = delegateTypeRef->mParams[paramIdx];
  10784. BfResolveTypeRefFlags resolveTypeFlags = BfResolveTypeRefFlag_AllowRef;
  10785. if ((param->mNameNode != NULL) && (param->mNameNode->Equals("this")))
  10786. resolveTypeFlags = (BfResolveTypeRefFlags)(resolveTypeFlags | BfResolveTypeRefFlag_NoWarnOnMut);
  10787. if (paramIdx == delegateTypeRef->mParams.size() - 1)
  10788. {
  10789. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(param->mTypeRef))
  10790. {
  10791. if (dotTypeRef->mDotToken->mToken == BfToken_DotDotDot)
  10792. {
  10793. hasVarArgs = true;
  10794. continue;
  10795. }
  10796. }
  10797. }
  10798. auto paramType = ResolveTypeRef(param->mTypeRef, BfPopulateType_Declaration, resolveTypeFlags);
  10799. if (paramType == NULL)
  10800. {
  10801. failed = true;
  10802. paramType = GetPrimitiveType(BfTypeCode_Var);
  10803. }
  10804. if ((!isDelegate) && (isFirst) && (param->mNameNode != NULL) && (param->mNameNode->Equals("this")))
  10805. {
  10806. functionThisType = paramType;
  10807. if (functionThisType->IsRef())
  10808. {
  10809. auto refType = (BfRefType*)functionThisType;
  10810. if (refType->mRefKind != BfRefType::RefKind_Mut)
  10811. {
  10812. if (auto refTypeRef = BfNodeDynCast<BfRefTypeRef>(param->mTypeRef))
  10813. {
  10814. failed = true;
  10815. Fail("Only 'mut' is allowed here", refTypeRef->mRefToken);
  10816. }
  10817. }
  10818. hasMutSpecifier = true;
  10819. functionThisType = refType->mElementType;
  10820. }
  10821. paramTypes.Add(functionThisType);
  10822. _CheckType(functionThisType);
  10823. }
  10824. else
  10825. {
  10826. paramTypes.Add(paramType);
  10827. _CheckType(paramType);
  10828. }
  10829. isFirst = false;
  10830. }
  10831. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsGenericTypeInstance()))
  10832. wantGeneric = false;
  10833. //TODO:
  10834. wantGeneric = false;
  10835. BfTypeInstance* baseDelegateType = NULL;
  10836. if (mCompiler->mDelegateTypeDef != NULL)
  10837. baseDelegateType = ResolveTypeDef(mCompiler->mDelegateTypeDef)->ToTypeInstance();
  10838. else
  10839. failed = true;
  10840. BfDelegateInfo* delegateInfo = NULL;
  10841. BfDelegateType* delegateType = NULL;
  10842. if (wantGeneric)
  10843. {
  10844. BfDelegateType* genericTypeInst = new BfDelegateType();
  10845. genericTypeInst->mGenericTypeInfo = new BfGenericTypeInfo();
  10846. genericTypeInst->mGenericTypeInfo->mFinishedGenericParams = true;
  10847. delegateType = genericTypeInst;
  10848. delegateInfo = delegateType->GetDelegateInfo();
  10849. auto parentTypeInstance = (BfTypeInstance*)mCurTypeInstance;
  10850. for (int i = 0; i < parentTypeInstance->mGenericTypeInfo->mGenericParams.size(); i++)
  10851. {
  10852. genericTypeInst->mGenericTypeInfo->mGenericParams.push_back(parentTypeInstance->mGenericTypeInfo->mGenericParams[i]->AddRef());
  10853. }
  10854. for (int i = 0; i < parentTypeInstance->mGenericTypeInfo->mTypeGenericArguments.size(); i++)
  10855. {
  10856. genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.push_back(parentTypeInstance->mGenericTypeInfo->mTypeGenericArguments[i]);
  10857. auto typeGenericArg = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[i];
  10858. genericTypeInst->mGenericTypeInfo->mIsUnspecialized |= typeGenericArg->IsGenericParam() || typeGenericArg->IsUnspecializedType();
  10859. }
  10860. CheckUnspecializedGenericType(genericTypeInst, populateType);
  10861. // We don't ever need to do an actual pass over generic delegate methods, so it's safe to set the 'unspecialized variation' flag
  10862. if (isUnspecialized)
  10863. {
  10864. genericTypeInst->mGenericTypeInfo->mIsUnspecialized = true;
  10865. genericTypeInst->mGenericTypeInfo->mIsUnspecializedVariation = true;
  10866. }
  10867. genericTypeInst->mIsUnspecializedType = genericTypeInst->mGenericTypeInfo->mIsUnspecialized;
  10868. genericTypeInst->mIsUnspecializedTypeVariation = genericTypeInst->mGenericTypeInfo->mIsUnspecializedVariation;
  10869. }
  10870. else
  10871. {
  10872. auto dlgType = new BfDelegateType();
  10873. delegateInfo = dlgType->GetDelegateInfo();
  10874. dlgType->mIsUnspecializedType = isUnspecialized;
  10875. dlgType->mIsUnspecializedTypeVariation = isUnspecialized;
  10876. delegateType = dlgType;
  10877. }
  10878. delegateInfo->mCallingConvention = lookupCtx.mCallingConvention;
  10879. Val128 hashContext;
  10880. BfTypeDef* typeDef = new BfTypeDef();
  10881. if (baseDelegateType != NULL)
  10882. typeDef->mProject = baseDelegateType->mTypeDef->mProject;
  10883. typeDef->mSystem = mCompiler->mSystem;
  10884. typeDef->mName = mSystem->mEmptyAtom;
  10885. if (delegateTypeRef->mTypeToken->GetToken() == BfToken_Delegate)
  10886. {
  10887. typeDef->mIsDelegate = true;
  10888. typeDef->mTypeCode = BfTypeCode_Object;
  10889. }
  10890. else
  10891. {
  10892. typeDef->mIsFunction = true;
  10893. typeDef->mTypeCode = BfTypeCode_Struct;
  10894. }
  10895. BfMethodDef* methodDef = new BfMethodDef();
  10896. methodDef->mDeclaringType = typeDef;
  10897. methodDef->mName = "Invoke";
  10898. methodDef->mProtection = BfProtection_Public;
  10899. methodDef->mIdx = 0;
  10900. methodDef->mIsStatic = !typeDef->mIsDelegate && (functionThisType == NULL);
  10901. methodDef->mHasExplicitThis = functionThisType != NULL;
  10902. if ((functionThisType != NULL) && (hasMutSpecifier))
  10903. {
  10904. if ((functionThisType->IsValueType()) || (functionThisType->IsGenericParam()))
  10905. methodDef->mIsMutating = true;
  10906. }
  10907. auto directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  10908. delegateInfo->mDirectAllocNodes.push_back(directTypeRef);
  10909. if (typeDef->mIsDelegate)
  10910. directTypeRef->Init(delegateType);
  10911. else if (mCompiler->mFunctionTypeDef == NULL)
  10912. failed = true;
  10913. else
  10914. directTypeRef->Init(ResolveTypeDef(mCompiler->mFunctionTypeDef));
  10915. if (!failed)
  10916. typeDef->mBaseTypes.push_back(directTypeRef);
  10917. directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  10918. delegateInfo->mDirectAllocNodes.push_back(directTypeRef);
  10919. directTypeRef->Init(returnType);
  10920. methodDef->mReturnTypeRef = directTypeRef;
  10921. delegateInfo->mReturnType = returnType;
  10922. delegateInfo->mHasExplicitThis = functionThisType != NULL;
  10923. delegateInfo->mHasVarArgs = hasVarArgs;
  10924. delegateType->mGenericDepth = BF_MAX(delegateType->mGenericDepth, returnType->GetGenericDepth() + 1);
  10925. auto hashVal = mContext->mResolvedTypes.Hash(typeRef, &lookupCtx);
  10926. //int paramSrcOfs = (functionThisType != NULL) ? 1 : 0;
  10927. int paramSrcOfs = 0;
  10928. for (int paramIdx = 0; paramIdx < (int)paramTypes.size(); paramIdx++)
  10929. {
  10930. auto param = delegateTypeRef->mParams[paramIdx + paramSrcOfs];
  10931. auto paramType = paramTypes[paramIdx];
  10932. if (paramType == NULL)
  10933. paramType = GetPrimitiveType(BfTypeCode_Var);
  10934. String paramName;
  10935. if (param->mNameNode != NULL)
  10936. paramName = param->mNameNode->ToString();
  10937. if (!paramType->IsReified())
  10938. delegateType->mIsReified = false;
  10939. auto directTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeReference>();
  10940. delegateInfo->mDirectAllocNodes.push_back(directTypeRef);
  10941. directTypeRef->Init(paramType);
  10942. BfParameterDef* paramDef = new BfParameterDef();
  10943. paramDef->mTypeRef = directTypeRef;
  10944. paramDef->mName = paramName;
  10945. if ((paramIdx == 0) && (functionThisType != NULL))
  10946. paramDef->mParamKind = BfParamKind_ExplicitThis;
  10947. methodDef->mParams.push_back(paramDef);
  10948. if ((param->mModToken != NULL) && (param->mModToken->mToken == BfToken_Params))
  10949. {
  10950. if (paramIdx == (int)paramTypes.size() - 1)
  10951. paramDef->mParamKind = BfParamKind_Params;
  10952. else
  10953. {
  10954. failed = true;
  10955. Fail("Params parameter must be the last parameter", param);
  10956. }
  10957. }
  10958. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(paramDef->mTypeRef))
  10959. {
  10960. if (dotTypeRef->mDotToken->mToken == BfToken_DotDotDot)
  10961. {
  10962. if (paramIdx == (int)paramTypes.size() - 1)
  10963. paramDef->mParamKind = BfParamKind_VarArgs;
  10964. else
  10965. {
  10966. failed = true;
  10967. Fail("Varargs specifier must be the last parameter", param);
  10968. }
  10969. }
  10970. }
  10971. delegateInfo->mParams.Add(paramType);
  10972. delegateType->mGenericDepth = BF_MAX(delegateType->mGenericDepth, paramType->GetGenericDepth() + 1);
  10973. }
  10974. if (delegateInfo->mHasVarArgs)
  10975. {
  10976. BfParameterDef* paramDef = new BfParameterDef();
  10977. paramDef->mParamKind = BfParamKind_VarArgs;
  10978. methodDef->mParams.push_back(paramDef);
  10979. }
  10980. typeDef->mMethods.push_back(methodDef);
  10981. if (failed)
  10982. {
  10983. delete delegateType;
  10984. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  10985. }
  10986. //
  10987. if (typeDef->mIsDelegate)
  10988. {
  10989. BfDefBuilder::AddMethod(typeDef, BfMethodType_Ctor, BfProtection_Public, false, "");
  10990. BfDefBuilder::AddDynamicCastMethods(typeDef);
  10991. }
  10992. delegateType->mContext = mContext;
  10993. delegateType->mTypeDef = typeDef;
  10994. populateModule->InitType(delegateType, populateType);
  10995. resolvedEntry->mValue = delegateType;
  10996. AddDependency(directTypeRef->mType, delegateType, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  10997. // if (delegateInfo->mFunctionThisType != NULL)
  10998. // AddDependency(delegateInfo->mFunctionThisType, delegateType, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  10999. for (auto paramType : paramTypes)
  11000. AddDependency(paramType, delegateType, BfDependencyMap::DependencyFlag_ParamOrReturnValue);
  11001. #ifdef _DEBUG
  11002. if (BfResolvedTypeSet::Hash(delegateType, &lookupCtx) != resolvedEntry->mHashCode)
  11003. {
  11004. int refHash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx);
  11005. int typeHash = BfResolvedTypeSet::Hash(delegateType, &lookupCtx);
  11006. BF_ASSERT(refHash == typeHash);
  11007. }
  11008. BF_ASSERT(BfResolvedTypeSet::Equals(delegateType, typeRef, &lookupCtx));
  11009. #endif
  11010. BF_ASSERT(BfResolvedTypeSet::Hash(delegateType, &lookupCtx) == resolvedEntry->mHashCode);
  11011. return ResolveTypeResult(typeRef, delegateType, populateType, resolveFlags);
  11012. }
  11013. else if (auto genericParamTypeRef = BfNodeDynCast<BfGenericParamTypeRef>(typeRef))
  11014. {
  11015. auto genericParamType = GetGenericParamType(genericParamTypeRef->mGenericParamKind, genericParamTypeRef->mGenericParamIdx);
  11016. resolvedEntry->mValue = genericParamType;
  11017. BF_ASSERT(BfResolvedTypeSet::Hash(genericParamType, &lookupCtx) == resolvedEntry->mHashCode);
  11018. return ResolveTypeResult(typeRef, genericParamType, populateType, resolveFlags);
  11019. }
  11020. else if (auto retTypeTypeRef = BfNodeDynCast<BfModifiedTypeRef>(typeRef))
  11021. {
  11022. auto retTypeType = new BfModifiedTypeType();
  11023. retTypeType->mModifiedKind = retTypeTypeRef->mRetTypeToken->mToken;
  11024. retTypeType->mElementType = ResolveTypeRef(retTypeTypeRef->mElementType, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  11025. // We know this is a generic param type, it can't fail to resolve
  11026. BF_ASSERT(retTypeType->mElementType);
  11027. resolvedEntry->mValue = retTypeType;
  11028. BF_ASSERT(BfResolvedTypeSet::Hash(retTypeType, &lookupCtx) == resolvedEntry->mHashCode);
  11029. populateModule->InitType(retTypeType, populateType);
  11030. return ResolveTypeResult(typeRef, retTypeType, populateType, resolveFlags);
  11031. }
  11032. else if (auto qualifiedTypeRef = BfNodeDynCast<BfQualifiedTypeReference>(typeRef))
  11033. {
  11034. auto leftType = ResolveTypeRef(qualifiedTypeRef->mLeft, BfPopulateType_Declaration, BfResolveTypeRefFlag_AllowGenericParamConstValue);
  11035. if (leftType == NULL)
  11036. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  11037. return ResolveTypeResult(typeRef, ResolveInnerType(leftType, qualifiedTypeRef->mRight), populateType, resolveFlags);
  11038. }
  11039. else if (auto constTypeRef = BfNodeDynCastExact<BfConstTypeRef>(typeRef))
  11040. {
  11041. return ResolveTypeRef(constTypeRef->mElementType, populateType, (BfResolveTypeRefFlags)(resolveFlags & BfResolveTypeRefFlag_NoResolveGenericParam));
  11042. }
  11043. else if (auto constExprTypeRef = BfNodeDynCastExact<BfConstExprTypeRef>(typeRef))
  11044. {
  11045. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->mDependencyMap.mMinDependDepth > 32))
  11046. {
  11047. Fail("Generic type dependency depth exceeded", typeRef);
  11048. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  11049. }
  11050. BfVariant result;
  11051. BfType* resultType = NULL;
  11052. if (constExprTypeRef->mConstExpr != NULL)
  11053. {
  11054. result = mContext->mResolvedTypes.EvaluateToVariant(&lookupCtx, constExprTypeRef->mConstExpr, resultType);
  11055. BF_ASSERT(resultType != NULL);
  11056. }
  11057. auto constExprType = new BfConstExprValueType();
  11058. constExprType->mContext = mContext;
  11059. constExprType->mType = resultType;
  11060. BF_ASSERT(constExprType->mType != NULL);
  11061. if (constExprType->mType == NULL)
  11062. constExprType->mType = GetPrimitiveType(BfTypeCode_Let);
  11063. constExprType->mValue = result;
  11064. resolvedEntry->mValue = constExprType;
  11065. #ifdef _DEBUG
  11066. if (BfResolvedTypeSet::Hash(constExprType, &lookupCtx) != resolvedEntry->mHashCode)
  11067. {
  11068. int refHash = BfResolvedTypeSet::Hash(typeRef, &lookupCtx);
  11069. int typeHash = BfResolvedTypeSet::Hash(constExprType, &lookupCtx);
  11070. BF_ASSERT(refHash == typeHash);
  11071. }
  11072. BF_ASSERT(BfResolvedTypeSet::Equals(constExprType, typeRef, &lookupCtx));
  11073. #endif
  11074. populateModule->InitType(constExprType, populateType);
  11075. return constExprType;
  11076. }
  11077. else
  11078. {
  11079. BFMODULE_FATAL(this, "Not implemented!");
  11080. NotImpl(typeRef);
  11081. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  11082. }
  11083. return ResolveTypeResult(typeRef, NULL, populateType, resolveFlags);
  11084. }
  11085. BfType* BfModule::ResolveTypeRefAllowUnboundGenerics(BfTypeReference* typeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags, bool resolveGenericParam)
  11086. {
  11087. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeRef))
  11088. {
  11089. if (genericTypeRef->mGenericArguments.size() == 0)
  11090. {
  11091. auto genericTypeDef = ResolveGenericInstanceDef(genericTypeRef);
  11092. if (genericTypeDef == NULL)
  11093. return NULL;
  11094. BfTypeVector typeVector;
  11095. for (int i = 0; i < (int)genericTypeDef->mGenericParamDefs.size(); i++)
  11096. typeVector.push_back(GetGenericParamType(BfGenericParamKind_Type, i));
  11097. auto result = ResolveTypeDef(genericTypeDef, typeVector, populateType, resolveFlags);
  11098. if ((result != NULL) && (genericTypeRef->mCommas.size() + 1 != genericTypeDef->mGenericParamDefs.size()))
  11099. {
  11100. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance, result->ToTypeInstance());
  11101. SetAndRestoreValue<BfMethodInstance*> prevMethodInstance(mCurMethodInstance, NULL);
  11102. Fail(StrFormat("Type '%s' requires %d generic arguments", TypeToString(result).c_str(), genericTypeDef->mGenericParamDefs.size()), typeRef);
  11103. }
  11104. return result;
  11105. }
  11106. }
  11107. return ResolveTypeRef(typeRef, populateType, resolveGenericParam ? (BfResolveTypeRefFlags)0 : BfResolveTypeRefFlag_NoResolveGenericParam);
  11108. }
  11109. // This finds non-default unspecialized generic type instances and converts them into a BfUnspecializedGenericTypeVariation
  11110. BfType* BfModule::CheckUnspecializedGenericType(BfTypeInstance* genericTypeInst, BfPopulateType populateType)
  11111. {
  11112. int argCount = (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size();
  11113. bool isDefaultUnspecialized = true;
  11114. for (int argIdx = 0; argIdx < argCount; argIdx++)
  11115. {
  11116. auto argType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[argIdx];
  11117. if (argType->IsGenericParam())
  11118. {
  11119. auto genericParamType = (BfGenericParamType*)argType;
  11120. if ((genericParamType->mGenericParamKind != BfGenericParamKind_Type) || (genericParamType->mGenericParamIdx != argIdx))
  11121. isDefaultUnspecialized = false;
  11122. genericTypeInst->mGenericTypeInfo->mIsUnspecialized = true;
  11123. }
  11124. else if (argType->IsUnspecializedType())
  11125. {
  11126. isDefaultUnspecialized = false;
  11127. genericTypeInst->mGenericTypeInfo->mIsUnspecialized = true;
  11128. }
  11129. else
  11130. isDefaultUnspecialized = false;
  11131. }
  11132. if (genericTypeInst->mGenericTypeInfo->mIsUnspecialized)
  11133. genericTypeInst->mGenericTypeInfo->mIsUnspecializedVariation = !isDefaultUnspecialized;
  11134. return genericTypeInst;
  11135. }
  11136. BfTypeInstance* BfModule::GetUnspecializedTypeInstance(BfTypeInstance* typeInst)
  11137. {
  11138. if (!typeInst->IsGenericTypeInstance())
  11139. return typeInst;
  11140. BF_ASSERT((!typeInst->IsDelegateFromTypeRef()) && (!typeInst->IsFunctionFromTypeRef()));
  11141. auto genericTypeInst = (BfTypeInstance*)typeInst;
  11142. auto result = ResolveTypeDef(genericTypeInst->mTypeDef->GetDefinition(), BfPopulateType_Declaration);
  11143. BF_ASSERT((result != NULL) && (result->IsUnspecializedType()));
  11144. if (result == NULL)
  11145. return NULL;
  11146. return result->ToTypeInstance();
  11147. }
  11148. BfType* BfModule::ResolveTypeRef_Type(BfAstNode* astNode, const BfSizedArray<BfAstNode*>* genericArgs, BfPopulateType populateType, BfResolveTypeRefFlags& resolveFlags)
  11149. {
  11150. if ((genericArgs == NULL) || (genericArgs->size() == 0))
  11151. {
  11152. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(astNode))
  11153. {
  11154. BfNamedTypeReference typeRef;
  11155. typeRef.mNameNode = identifier;
  11156. typeRef.mSrcEnd = 0;
  11157. typeRef.mToken = BfToken_None;
  11158. auto type = ResolveTypeRef_Ref(&typeRef, populateType, resolveFlags, 0);
  11159. return type;
  11160. }
  11161. }
  11162. BfAstAllocator alloc;
  11163. alloc.mSourceData = astNode->GetSourceData();
  11164. std::function<BfTypeReference* (BfAstNode*)> _ConvType = [&](BfAstNode* astNode) -> BfTypeReference*
  11165. {
  11166. if (auto typeRef = BfNodeDynCast<BfTypeReference>(astNode))
  11167. return typeRef;
  11168. BfTypeReference* result = NULL;
  11169. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(astNode))
  11170. {
  11171. auto* typeRef = alloc.Alloc<BfNamedTypeReference>();
  11172. typeRef->mNameNode = identifier;
  11173. result = typeRef;
  11174. }
  11175. else if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(astNode))
  11176. {
  11177. auto qualifiedTypeRef = alloc.Alloc<BfQualifiedTypeReference>();
  11178. qualifiedTypeRef->mLeft = _ConvType(memberRefExpr->mTarget);
  11179. qualifiedTypeRef->mDot = memberRefExpr->mDotToken;
  11180. qualifiedTypeRef->mRight = _ConvType(memberRefExpr->mMemberName);
  11181. if ((qualifiedTypeRef->mLeft == NULL) || (qualifiedTypeRef->mRight == NULL))
  11182. return NULL;
  11183. result = qualifiedTypeRef;
  11184. }
  11185. if (result == NULL)
  11186. return NULL;
  11187. result->SetSrcStart(astNode->GetSrcStart());
  11188. result->SetSrcEnd(astNode->GetSrcEnd());
  11189. return result;
  11190. };
  11191. auto typeRef = _ConvType(astNode);
  11192. if (typeRef == NULL)
  11193. return NULL;
  11194. if ((genericArgs != NULL) && (genericArgs->size() != 0))
  11195. {
  11196. auto genericInstanceTypeRef = alloc.Alloc<BfGenericInstanceTypeRef>();
  11197. genericInstanceTypeRef->SetSrcStart(typeRef->GetSrcStart());
  11198. genericInstanceTypeRef->mElementType = typeRef;
  11199. #ifdef BF_AST_HAS_PARENT_MEMBER
  11200. typeRef->mParent = genericInstanceTypeRef;
  11201. #endif
  11202. BfDeferredAstSizedArray<BfAstNode*> arguments(genericInstanceTypeRef->mGenericArguments, &alloc);
  11203. for (auto genericArg : *genericArgs)
  11204. {
  11205. if (genericArg != NULL)
  11206. {
  11207. arguments.push_back(genericArg);
  11208. genericInstanceTypeRef->SetSrcEnd(genericArg->GetSrcEnd());
  11209. }
  11210. }
  11211. typeRef = genericInstanceTypeRef;
  11212. }
  11213. return ResolveTypeRef_Ref(typeRef, populateType, resolveFlags, 0);
  11214. }
  11215. BfType* BfModule::ResolveTypeRef(BfAstNode* astNode, const BfSizedArray<BfAstNode*>* genericArgs, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  11216. {
  11217. return ResolveTypeRef_Ref(astNode, genericArgs, populateType, resolveFlags);
  11218. }
  11219. BfType* BfModule::ResolveTypeRef_Ref(BfAstNode* astNode, const BfSizedArray<BfAstNode*>* genericArgs, BfPopulateType populateType, BfResolveTypeRefFlags& resolveFlags)
  11220. {
  11221. if (astNode == NULL)
  11222. {
  11223. AssertErrorState();
  11224. return NULL;
  11225. }
  11226. if (auto typeRef = BfNodeDynCast<BfTypeReference>(astNode))
  11227. return ResolveTypeRef_Ref(typeRef, populateType, resolveFlags, 0);
  11228. if ((resolveFlags & BfResolveTypeRefFlag_AllowImplicitConstExpr) != 0)
  11229. {
  11230. if (auto expr = BfNodeDynCast<BfExpression>(astNode))
  11231. {
  11232. resolveFlags = (BfResolveTypeRefFlags)(resolveFlags | BfResolveTypeRefFlag_IgnoreLookupError);
  11233. auto checkType = ResolveTypeRef_Type(astNode, genericArgs, populateType, resolveFlags);
  11234. if (checkType != NULL)
  11235. return checkType;
  11236. BfResolvedTypeSet::LookupContext lookupCtx;
  11237. lookupCtx.mModule = this;
  11238. BfResolvedTypeSet::Entry* typeEntry = NULL;
  11239. BfType* resultType = NULL;
  11240. auto result = mContext->mResolvedTypes.EvaluateToVariant(&lookupCtx, expr, resultType);
  11241. if (resultType != NULL)
  11242. {
  11243. auto constExprValue = CreateConstExprValueType(result, resultType);
  11244. return constExprValue;
  11245. }
  11246. }
  11247. }
  11248. return ResolveTypeRef_Type(astNode, genericArgs, populateType, resolveFlags);
  11249. }
  11250. // This flow should mirror CastToValue
  11251. bool BfModule::CanCast(BfTypedValue typedVal, BfType* toType, BfCastFlags castFlags)
  11252. {
  11253. BP_ZONE("BfModule::CanCast");
  11254. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11255. return CastToValue(NULL, typedVal, toType, (BfCastFlags)(castFlags | BfCastFlags_SilentFail | BfCastFlags_IsCastCheck));
  11256. }
  11257. bool BfModule::AreSplatsCompatible(BfType* fromType, BfType* toType, bool* outNeedsMemberCasting)
  11258. {
  11259. if ((fromType->IsTypeInstance()) && (!fromType->IsSplattable()))
  11260. return false;
  11261. if ((toType->IsTypeInstance()) && (!toType->IsSplattable()))
  11262. return false;
  11263. auto _GetTypes = [&](BfType* type, Array<BfType*>& types)
  11264. {
  11265. BfTypeUtils::SplatIterate([&](BfType* memberType) { types.Add(memberType); }, type);
  11266. };
  11267. Array<BfType*> fromTypes;
  11268. _GetTypes(fromType, fromTypes);
  11269. Array<BfType*> toTypes;
  11270. _GetTypes(toType, toTypes);
  11271. if (toTypes.size() > fromTypes.size())
  11272. return false;
  11273. for (int i = 0; i < toTypes.size(); i++)
  11274. {
  11275. BfType* fromMemberType = fromTypes[i];
  11276. BfType* toMemberType = toTypes[i];
  11277. if (fromMemberType != toMemberType)
  11278. {
  11279. if ((outNeedsMemberCasting != NULL) &&
  11280. (fromMemberType->IsIntPtrable()) && (toMemberType->IsIntPtrable()))
  11281. *outNeedsMemberCasting = true;
  11282. else
  11283. return false;
  11284. }
  11285. }
  11286. return true;
  11287. }
  11288. BfType* BfModule::GetClosestNumericCastType(const BfTypedValue& typedVal, BfType* wantType)
  11289. {
  11290. BfType* toType = wantType;
  11291. if ((toType == NULL) ||
  11292. ((!toType->IsFloat()) && (!toType->IsIntegral())))
  11293. toType = NULL;
  11294. BfType* bestReturnType = NULL;
  11295. if (typedVal.mType->IsTypedPrimitive())
  11296. return NULL;
  11297. auto checkType = typedVal.mType->ToTypeInstance();
  11298. while (checkType != NULL)
  11299. {
  11300. for (auto operatorDef : checkType->mTypeDef->mOperators)
  11301. {
  11302. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  11303. {
  11304. if (operatorDef->IsExplicit())
  11305. continue;
  11306. auto returnType = CheckOperator(checkType, operatorDef, typedVal, BfTypedValue());
  11307. if ((returnType != NULL) &&
  11308. ((returnType->IsIntegral()) || (returnType->IsFloat())))
  11309. {
  11310. bool canCastTo = true;
  11311. if ((toType != NULL) && (!CanCast(GetFakeTypedValue(returnType), toType)))
  11312. canCastTo = false;
  11313. if (canCastTo)
  11314. {
  11315. if (bestReturnType == NULL)
  11316. {
  11317. bestReturnType = returnType;
  11318. }
  11319. else
  11320. {
  11321. if (CanCast(GetFakeTypedValue(bestReturnType), returnType))
  11322. {
  11323. bestReturnType = returnType;
  11324. }
  11325. }
  11326. }
  11327. }
  11328. }
  11329. }
  11330. checkType = checkType->mBaseType;
  11331. }
  11332. if ((toType == NULL) && (bestReturnType != NULL))
  11333. {
  11334. auto intPtrType = GetPrimitiveType(BfTypeCode_IntPtr);
  11335. if (!CanCast(GetFakeTypedValue(bestReturnType), intPtrType))
  11336. {
  11337. // If no 'wantType' is specified, try to get closest one to an intptr
  11338. auto otherType = GetClosestNumericCastType(typedVal, intPtrType);
  11339. if (otherType != NULL)
  11340. return otherType;
  11341. }
  11342. }
  11343. return bestReturnType;
  11344. }
  11345. BfIRValue BfModule::CastToFunction(BfAstNode* srcNode, const BfTypedValue& targetValue, BfMethodInstance* methodInstance, BfType* toType, BfCastFlags castFlags, BfIRValue irFunc)
  11346. {
  11347. auto invokeMethodInstance = GetDelegateInvokeMethod(toType->ToTypeInstance());
  11348. bool methodsThisMatch = true;
  11349. if (invokeMethodInstance->mMethodDef->mIsStatic != methodInstance->mMethodDef->mIsStatic)
  11350. methodsThisMatch = false;
  11351. else
  11352. {
  11353. if (!methodInstance->mMethodDef->mIsStatic)
  11354. {
  11355. BfType* thisType = methodInstance->GetThisType();
  11356. if (thisType->IsPointer())
  11357. thisType = thisType->GetUnderlyingType();
  11358. BfType* invokeThisType = invokeMethodInstance->GetThisType();
  11359. if (invokeThisType->IsPointer())
  11360. invokeThisType = invokeThisType->GetUnderlyingType();
  11361. if (!TypeIsSubTypeOf(thisType->ToTypeInstance(), invokeThisType->ToTypeInstance()))
  11362. methodsThisMatch = false;
  11363. }
  11364. }
  11365. bool methodMatches = methodsThisMatch;
  11366. if (methodMatches)
  11367. methodMatches = invokeMethodInstance->IsExactMatch(methodInstance, false, false);
  11368. if (methodMatches)
  11369. {
  11370. if (methodInstance->GetOwner()->IsFunction())
  11371. {
  11372. BF_ASSERT(targetValue);
  11373. return targetValue.mValue;
  11374. }
  11375. BfIRFunction bindFuncVal = irFunc;
  11376. if (!bindFuncVal)
  11377. {
  11378. BfModuleMethodInstance methodRefMethod;
  11379. if (methodInstance->mDeclModule == this)
  11380. methodRefMethod = methodInstance;
  11381. else
  11382. methodRefMethod = ReferenceExternalMethodInstance(methodInstance);
  11383. auto dataType = GetPrimitiveType(BfTypeCode_IntPtr);
  11384. if (!methodRefMethod.mFunc)
  11385. {
  11386. if ((!methodInstance->mIsUnspecialized) && (HasCompiledOutput()))
  11387. AssertErrorState();
  11388. return GetDefaultTypedValue(dataType, false, BfDefaultValueKind_Value).mValue;
  11389. }
  11390. bindFuncVal = methodRefMethod.mFunc;
  11391. }
  11392. if ((mCompiler->mOptions.mAllowHotSwapping) && (!mIsComptimeModule))
  11393. bindFuncVal = mBfIRBuilder->RemapBindFunction(bindFuncVal);
  11394. return mBfIRBuilder->CreatePtrToInt(bindFuncVal, BfTypeCode_IntPtr);
  11395. }
  11396. if ((castFlags & BfCastFlags_SilentFail) == 0)
  11397. {
  11398. if ((methodsThisMatch) && (invokeMethodInstance->IsExactMatch(methodInstance, true, false)))
  11399. {
  11400. 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);
  11401. }
  11402. else if (invokeMethodInstance->IsExactMatch(methodInstance, false, false))
  11403. {
  11404. bool handled = false;
  11405. if (methodInstance->HasThis())
  11406. {
  11407. auto thisType = methodInstance->GetThisType();
  11408. if (invokeMethodInstance->HasExplicitThis())
  11409. {
  11410. auto invokeThisType = invokeMethodInstance->GetThisType();
  11411. bool thisWasPtr = false;
  11412. if (thisType->IsPointer())
  11413. {
  11414. thisType = thisType->GetUnderlyingType();
  11415. thisWasPtr = true;
  11416. }
  11417. bool invokeThisWasPtr = false;
  11418. if (invokeThisType->IsPointer())
  11419. {
  11420. invokeThisType = invokeThisType->GetUnderlyingType();
  11421. invokeThisWasPtr = true;
  11422. }
  11423. if (TypeIsSubTypeOf(thisType->ToTypeInstance(), invokeThisType->ToTypeInstance()))
  11424. {
  11425. if (invokeThisWasPtr != thisWasPtr)
  11426. {
  11427. if (invokeThisWasPtr)
  11428. 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);
  11429. else
  11430. 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);
  11431. handled = true;
  11432. }
  11433. }
  11434. }
  11435. }
  11436. if ((!methodInstance->mMethodDef->mIsStatic) && (!invokeMethodInstance->HasExplicitThis()))
  11437. {
  11438. handled = true;
  11439. auto thisType = methodInstance->GetParamType(-1);
  11440. 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);
  11441. }
  11442. if (!handled)
  11443. {
  11444. if (invokeMethodInstance->mMethodDef->mIsStatic)
  11445. Fail(StrFormat("Static method '%s' cannot match '%s'", MethodToString(methodInstance).c_str(), TypeToString(toType).c_str()).c_str(), srcNode);
  11446. else
  11447. Fail(StrFormat("Non-static method '%s' cannot match '%s'", MethodToString(methodInstance).c_str(), TypeToString(toType).c_str()).c_str(), srcNode);
  11448. }
  11449. }
  11450. }
  11451. return BfIRValue();
  11452. }
  11453. BfIRValue BfModule::CastToValue(BfAstNode* srcNode, BfTypedValue typedVal, BfType* toType, BfCastFlags castFlags, BfCastResultFlags* resultFlags)
  11454. {
  11455. bool silentFail = ((castFlags & BfCastFlags_SilentFail) != 0);
  11456. bool explicitCast = (castFlags & BfCastFlags_Explicit) != 0;
  11457. bool ignoreErrors = mIgnoreErrors || ((castFlags & BfCastFlags_SilentFail) != 0);
  11458. bool ignoreWrites = mBfIRBuilder->mIgnoreWrites;
  11459. if (typedVal.mType == toType)
  11460. {
  11461. if (resultFlags != NULL)
  11462. {
  11463. if (typedVal.IsAddr())
  11464. *resultFlags = (BfCastResultFlags)(*resultFlags | BfCastResultFlags_IsAddr);
  11465. if (typedVal.mKind == BfTypedValueKind_TempAddr)
  11466. *resultFlags = (BfCastResultFlags)(*resultFlags | BfCastResultFlags_IsTemp);
  11467. }
  11468. else if (typedVal.IsAddr())
  11469. typedVal = LoadValue(typedVal);
  11470. return typedVal.mValue;
  11471. }
  11472. BF_ASSERT(typedVal.mType->mContext == mContext);
  11473. BF_ASSERT(toType->mContext == mContext);
  11474. if ((typedVal.IsAddr()) && (!typedVal.mType->IsValueType()))
  11475. typedVal = LoadValue(typedVal);
  11476. //BF_ASSERT(!typedVal.IsAddr() || typedVal.mType->IsGenericParam() || typedVal.mType->IsValueType());
  11477. // Ref X to Ref Y, X* to Y*
  11478. {
  11479. bool checkUnderlying = false;
  11480. bool isRef = false;
  11481. if (((typedVal.mType->IsRef()) && (toType->IsRef())))
  11482. {
  11483. isRef = true;
  11484. auto fromRefType = (BfRefType*)typedVal.mType;
  11485. auto toRefType = (BfRefType*)toType;
  11486. if (fromRefType->mRefKind == toRefType->mRefKind)
  11487. checkUnderlying = true;
  11488. else if ((fromRefType->mRefKind == BfRefType::RefKind_Ref) && (toRefType->mRefKind == BfRefType::RefKind_Mut))
  11489. checkUnderlying = true; // Allow a ref-to-mut implicit conversion
  11490. }
  11491. if ((typedVal.mType->IsPointer()) && (toType->IsPointer()))
  11492. checkUnderlying = true;
  11493. if (checkUnderlying)
  11494. {
  11495. auto fromInner = typedVal.mType->GetUnderlyingType();
  11496. auto toInner = toType->GetUnderlyingType();
  11497. if (fromInner == toInner)
  11498. {
  11499. return typedVal.mValue;
  11500. }
  11501. if ((fromInner->IsTuple()) && (toInner->IsTuple()))
  11502. {
  11503. auto fromTuple = (BfTupleType*)fromInner;
  11504. auto toTuple = (BfTupleType*)toInner;
  11505. if (fromTuple->mFieldInstances.size() == toTuple->mFieldInstances.size())
  11506. {
  11507. bool matches = true;
  11508. for (int fieldIdx = 0; fieldIdx < (int)fromTuple->mFieldInstances.size(); fieldIdx++)
  11509. {
  11510. if (fromTuple->mFieldInstances[fieldIdx].mResolvedType != toTuple->mFieldInstances[fieldIdx].mResolvedType)
  11511. {
  11512. matches = false;
  11513. break;
  11514. }
  11515. }
  11516. if (matches)
  11517. {
  11518. // This is either a ref or a ptr so we don't need to set the "IsAddr" flag
  11519. typedVal = MakeAddressable(typedVal);
  11520. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  11521. }
  11522. }
  11523. }
  11524. if ((isRef) && (fromInner->IsStruct()) && (toInner->IsStruct()))
  11525. {
  11526. if (TypeIsSubTypeOf(fromInner->ToTypeInstance(), toInner->ToTypeInstance()))
  11527. {
  11528. if (toInner->IsValuelessType())
  11529. return mBfIRBuilder->GetFakeVal();
  11530. // Is this valid?
  11531. typedVal = MakeAddressable(typedVal);
  11532. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  11533. }
  11534. }
  11535. // ref int <-> ref int64/int32 (of same size)
  11536. if (((fromInner->IsInteger()) && (toInner->IsInteger())) &&
  11537. (fromInner->mSize == toInner->mSize) &&
  11538. (fromInner->IsSigned() == toInner->IsSigned()))
  11539. return typedVal.mValue;
  11540. }
  11541. }
  11542. // Null -> ObjectInst|IFace|ptr
  11543. if ((typedVal.mType->IsNull()) &&
  11544. ((toType->IsObjectOrInterface()) || (toType->IsPointer() || (toType->IsFunction()) || (toType->IsAllocType()))))
  11545. {
  11546. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  11547. }
  11548. // Func -> void*
  11549. if ((typedVal.mType->IsFunction()) && (toType->IsVoidPtr()))
  11550. {
  11551. typedVal = LoadValue(typedVal);
  11552. return mBfIRBuilder->CreateIntToPtr(typedVal.mValue, mBfIRBuilder->MapType(toType));
  11553. }
  11554. if (explicitCast)
  11555. {
  11556. // void* -> Func
  11557. if ((typedVal.mType->IsVoidPtr()) && (toType->IsFunction()))
  11558. {
  11559. typedVal = LoadValue(typedVal);
  11560. return mBfIRBuilder->CreatePtrToInt(typedVal.mValue, BfTypeCode_IntPtr);
  11561. }
  11562. // * -> Valueless
  11563. if (toType->IsVoid())
  11564. return mBfIRBuilder->GetFakeVal();
  11565. // void* -> intptr
  11566. if ((typedVal.mType->IsPointer()) && (toType->IsIntPtr()))
  11567. {
  11568. if ((!typedVal.mType->GetUnderlyingType()->IsVoid()) && ((castFlags & BfCastFlags_FromCompiler) == 0))
  11569. {
  11570. if (!ignoreErrors)
  11571. 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);
  11572. else if (!silentFail)
  11573. SetFail();
  11574. }
  11575. auto toPrimitive = (BfPrimitiveType*)toType;
  11576. return mBfIRBuilder->CreatePtrToInt(typedVal.mValue, toPrimitive->mTypeDef->mTypeCode);
  11577. }
  11578. // intptr -> void*
  11579. if ((typedVal.mType->IsIntPtr()) && (toType->IsPointer()))
  11580. {
  11581. if ((!toType->GetUnderlyingType()->IsVoid()) && ((castFlags & BfCastFlags_FromCompiler) == 0))
  11582. {
  11583. if (!ignoreErrors)
  11584. 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);
  11585. else if (!silentFail)
  11586. SetFail();
  11587. }
  11588. return mBfIRBuilder->CreateIntToPtr(typedVal.mValue, mBfIRBuilder->MapType(toType));
  11589. }
  11590. }
  11591. // * <-> Var
  11592. if ((typedVal.mType->IsVar()) || (toType->IsVar()))
  11593. {
  11594. return mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(toType));
  11595. }
  11596. // Generic param -> *
  11597. if (typedVal.mType->IsGenericParam())
  11598. {
  11599. if (toType->IsGenericParam())
  11600. {
  11601. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  11602. if (genericParamInst->mTypeConstraint == toType)
  11603. return typedVal.mValue;
  11604. }
  11605. else
  11606. {
  11607. if ((typedVal.mKind != Beefy::BfTypedValueKind_GenericConstValue) && (toType == mContext->mBfObjectType))
  11608. {
  11609. // Always allow casting from generic to object
  11610. return typedVal.mValue;
  11611. }
  11612. auto _CheckGenericParamInstance = [&](BfGenericParamInstance* genericParamInst)
  11613. {
  11614. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  11615. {
  11616. return typedVal.mValue;
  11617. }
  11618. if (toType->IsInterface())
  11619. {
  11620. for (auto iface : genericParamInst->mInterfaceConstraints)
  11621. if (TypeIsSubTypeOf(iface, toType->ToTypeInstance()))
  11622. return mBfIRBuilder->GetFakeVal();
  11623. }
  11624. if (genericParamInst->mTypeConstraint != NULL)
  11625. {
  11626. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, true);
  11627. auto constraintTypeInst = genericParamInst->mTypeConstraint->ToTypeInstance();
  11628. if ((constraintTypeInst != NULL) && (constraintTypeInst->IsDelegateOrFunction()))
  11629. {
  11630. // Could be a methodref - can't cast to anything else
  11631. }
  11632. else
  11633. {
  11634. if ((constraintTypeInst != NULL) && (constraintTypeInst->IsInstanceOf(mCompiler->mEnumTypeDef)) && (explicitCast))
  11635. {
  11636. // Enum->int
  11637. if ((explicitCast) && (toType->IsInteger()))
  11638. return typedVal.mValue;
  11639. }
  11640. BfTypedValue fromTypedValue;
  11641. if (typedVal.mKind == BfTypedValueKind_GenericConstValue)
  11642. {
  11643. if (genericParamInst->mTypeConstraint->IsVar())
  11644. fromTypedValue = GetDefaultTypedValue(genericParamInst->mTypeConstraint);
  11645. else
  11646. fromTypedValue = GetDefaultTypedValue(genericParamInst->mTypeConstraint, false, BfDefaultValueKind_Undef);
  11647. }
  11648. else
  11649. fromTypedValue = BfTypedValue(mBfIRBuilder->GetFakeVal(), genericParamInst->mTypeConstraint, genericParamInst->mTypeConstraint->IsValueType());
  11650. auto result = CastToValue(srcNode, fromTypedValue, toType, (BfCastFlags)(castFlags | BfCastFlags_SilentFail));
  11651. if (result)
  11652. {
  11653. if ((genericParamInst->mTypeConstraint->IsDelegate()) && (toType->IsDelegate()))
  11654. {
  11655. // Don't allow cast when we are constrained by a delegate type, because BfMethodRefs can match and we require an actual alloc
  11656. 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);
  11657. return BfIRValue();
  11658. }
  11659. return result;
  11660. }
  11661. }
  11662. }
  11663. // Generic constrained with class or pointer type -> void*
  11664. if (toType->IsVoidPtr())
  11665. {
  11666. if (((genericParamInst->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Interface)) != 0) ||
  11667. ((genericParamInst->mTypeConstraint != NULL) &&
  11668. ((genericParamInst->mTypeConstraint->IsPointer()) ||
  11669. (genericParamInst->mTypeConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)) ||
  11670. (genericParamInst->mTypeConstraint->IsObjectOrInterface()))))
  11671. {
  11672. return typedVal.mValue;
  11673. }
  11674. }
  11675. if ((toType->IsInteger()) && (explicitCast))
  11676. {
  11677. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum) != 0)
  11678. {
  11679. return typedVal.mValue;
  11680. }
  11681. }
  11682. return BfIRValue();
  11683. };
  11684. BfIRValue retVal;
  11685. // For these casts, it's just important we get *A* value to work with here,
  11686. // as this is just use for unspecialized parsing. We don't use the generated code
  11687. {
  11688. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)typedVal.mType);
  11689. retVal = _CheckGenericParamInstance(genericParamInst);
  11690. if (retVal)
  11691. return retVal;
  11692. }
  11693. // Check method generic constraints
  11694. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mMethodInfoEx != NULL))
  11695. {
  11696. for (int genericParamIdx = (int)mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  11697. genericParamIdx < mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  11698. {
  11699. auto genericParamInst = mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  11700. if (genericParamInst->mExternType == typedVal.mType)
  11701. {
  11702. retVal = _CheckGenericParamInstance(genericParamInst);
  11703. if (retVal)
  11704. return retVal;
  11705. }
  11706. }
  11707. }
  11708. }
  11709. }
  11710. // * -> Generic param
  11711. if (toType->IsGenericParam())
  11712. {
  11713. if (explicitCast)
  11714. {
  11715. // Either an upcast or an unbox
  11716. if ((typedVal.mType == mContext->mBfObjectType) || (typedVal.mType->IsInterface()))
  11717. {
  11718. return GetDefaultValue(toType);
  11719. }
  11720. }
  11721. auto genericParamInst = GetGenericParamInstance((BfGenericParamType*)toType);
  11722. if (genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var)
  11723. return GetDefaultValue(toType);
  11724. if (typedVal.mType->IsNull())
  11725. {
  11726. bool allowCast = (genericParamInst->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Interface)) != 0;
  11727. if ((!allowCast) && (genericParamInst->mTypeConstraint != NULL))
  11728. allowCast = genericParamInst->mTypeConstraint->IsObject() || genericParamInst->mTypeConstraint->IsPointer();
  11729. if (allowCast)
  11730. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  11731. }
  11732. if (genericParamInst->mTypeConstraint != NULL)
  11733. {
  11734. if (genericParamInst->mTypeConstraint->IsInstanceOf(mCompiler->mEnumTypeDef))
  11735. {
  11736. // int->Enum
  11737. if ((explicitCast) && (typedVal.mType->IsInteger()))
  11738. return mBfIRBuilder->GetFakeVal();
  11739. }
  11740. if ((genericParamInst->mTypeConstraint == toType) && (toType->IsUnspecializedType()))
  11741. return mBfIRBuilder->GetFakeVal();
  11742. auto castedVal = CastToValue(srcNode, typedVal, genericParamInst->mTypeConstraint, (BfCastFlags)(castFlags | BfCastFlags_SilentFail));
  11743. if (castedVal)
  11744. return castedVal;
  11745. }
  11746. if (explicitCast)
  11747. {
  11748. if (((genericParamInst->mGenericParamFlags & BfGenericParamFlag_StructPtr) != 0) ||
  11749. ((genericParamInst->mTypeConstraint != NULL) && genericParamInst->mTypeConstraint->IsInstanceOf(mCompiler->mFunctionTypeDef)))
  11750. {
  11751. auto voidPtrType = CreatePointerType(GetPrimitiveType(BfTypeCode_None));
  11752. auto castedVal = CastToValue(srcNode, typedVal, voidPtrType, (BfCastFlags)(castFlags | BfCastFlags_SilentFail));
  11753. if (castedVal)
  11754. return castedVal;
  11755. }
  11756. }
  11757. if ((typedVal.mType->IsIntegral()) && ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Enum) != 0))
  11758. {
  11759. bool allowCast = explicitCast;
  11760. if ((!allowCast) && (typedVal.mType->IsIntegral()))
  11761. {
  11762. // Allow implicit cast of zero
  11763. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  11764. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  11765. {
  11766. allowCast = constant->mInt64 == 0;
  11767. }
  11768. }
  11769. if (allowCast)
  11770. {
  11771. return mBfIRBuilder->GetFakeVal();
  11772. }
  11773. }
  11774. }
  11775. if ((typedVal.mType->IsTypeInstance()) && (toType->IsTypeInstance()))
  11776. {
  11777. auto fromTypeInstance = typedVal.mType->ToTypeInstance();
  11778. auto toTypeInstance = toType->ToTypeInstance();
  11779. if ((typedVal.mType->IsValueType()) && (toType->IsValueType()))
  11780. {
  11781. bool allowCast = false;
  11782. if (TypeIsSubTypeOf(fromTypeInstance, toTypeInstance))
  11783. allowCast = true;
  11784. if (allowCast)
  11785. {
  11786. PopulateType(toType);
  11787. if (toType->IsValuelessType())
  11788. return BfIRValue::sValueless;
  11789. if (ignoreWrites)
  11790. return mBfIRBuilder->GetFakeVal();
  11791. if (resultFlags != NULL)
  11792. *resultFlags = (BfCastResultFlags)(BfCastResultFlags_IsAddr);
  11793. typedVal = MakeAddressable(typedVal);
  11794. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapTypeInstPtr(toTypeInstance));
  11795. }
  11796. }
  11797. // ObjectInst|IFace -> object|IFace
  11798. if ((typedVal.mType->IsObject() || (typedVal.mType->IsInterface())) && ((toType->IsObject() || (toType->IsInterface()))))
  11799. {
  11800. bool allowCast = false;
  11801. if (((castFlags & BfCastFlags_NoInterfaceImpl) != 0) && (toTypeInstance->IsInterface()))
  11802. {
  11803. // Don't allow
  11804. }
  11805. else if (TypeIsSubTypeOf(fromTypeInstance, toTypeInstance))
  11806. allowCast = true;
  11807. else if ((explicitCast) &&
  11808. ((toType->IsInterface()) || (TypeIsSubTypeOf(toTypeInstance, fromTypeInstance))))
  11809. {
  11810. if (toType->IsObjectOrInterface())
  11811. {
  11812. if ((castFlags & BfCastFlags_Unchecked) == 0)
  11813. EmitDynamicCastCheck(typedVal, toType, true);
  11814. }
  11815. allowCast = true;
  11816. }
  11817. if (allowCast)
  11818. {
  11819. if ((ignoreWrites) && (!typedVal.mValue.IsConst()))
  11820. return mBfIRBuilder->GetFakeVal();
  11821. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  11822. }
  11823. }
  11824. }
  11825. // MethodRef -> Function
  11826. if ((typedVal.mType->IsMethodRef()) && (toType->IsFunction()))
  11827. {
  11828. BfMethodInstance* methodInstance = ((BfMethodRefType*)typedVal.mType)->mMethodRef;
  11829. auto result = CastToFunction(srcNode, BfTypedValue(), methodInstance, toType, castFlags);
  11830. if (result)
  11831. return result;
  11832. }
  11833. // concrete IFace -> object|IFace
  11834. if ((typedVal.mType->IsConcreteInterfaceType()) && ((toType->IsObject() || (toType->IsInterface()))))
  11835. {
  11836. auto concreteInterfaceType = (BfConcreteInterfaceType*)typedVal.mType;
  11837. if ((toType->IsObject()) || (concreteInterfaceType->mInterface == toType))
  11838. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  11839. }
  11840. // IFace -> object
  11841. if ((typedVal.mType->IsInterface()) && (toType == mContext->mBfObjectType))
  11842. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  11843. // * -> Pointer
  11844. if (toType->IsPointer())
  11845. {
  11846. // Ptr -> Ptr
  11847. if (typedVal.mType->IsPointer())
  11848. {
  11849. bool allowCast = explicitCast;
  11850. auto fromPointerType = (BfPointerType*)typedVal.mType;
  11851. auto toPointerType = (BfPointerType*)toType;
  11852. auto fromUnderlying = fromPointerType->mElementType;
  11853. auto toUnderlying = toPointerType->mElementType;
  11854. // Allow cast from T[size]* to T* implicitly
  11855. // And from T* to T[size]* explicitly
  11856. while (fromUnderlying->IsSizedArray())
  11857. fromUnderlying = fromUnderlying->GetUnderlyingType();
  11858. while ((toUnderlying->IsSizedArray()) && (explicitCast))
  11859. toUnderlying = toUnderlying->GetUnderlyingType();
  11860. if ((fromUnderlying == toUnderlying) ||
  11861. (TypeIsSubTypeOf(fromUnderlying->ToTypeInstance(), toUnderlying->ToTypeInstance())) ||
  11862. (toUnderlying->IsVoid()))
  11863. allowCast = true;
  11864. if (allowCast)
  11865. {
  11866. if ((ignoreWrites) && (!typedVal.mValue.IsConst()))
  11867. return mBfIRBuilder->GetFakeVal();
  11868. return mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType));
  11869. }
  11870. }
  11871. else if (typedVal.mType->IsObject())
  11872. {
  11873. // ???
  11874. }
  11875. /*else if (typedVal.mType->IsSizedArray())
  11876. {
  11877. if (typedVal.IsAddr())
  11878. {
  11879. BfSizedArrayType* arrayType = (BfSizedArrayType*)typedVal.mType;
  11880. auto ptrType = CreatePointerType(arrayType->mElementType);
  11881. BfTypedValue returnPointer(mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(ptrType)), ptrType);
  11882. return CastToValue(srcNode, returnPointer, toType, castFlags, silentFail);
  11883. }
  11884. }*/
  11885. }
  11886. // Boxing?
  11887. bool mayBeBox = false;
  11888. if (((typedVal.mType->IsValueType()) || (typedVal.mType->IsPointer()) || (typedVal.mType->IsValuelessType())) &&
  11889. ((toType->IsInterface()) || (toType == mContext->mBfObjectType)))
  11890. {
  11891. // Make sure there's no conversion operator before we box
  11892. if ((!typedVal.mType->IsRef()) && (!typedVal.mType->IsModifiedTypeType()))
  11893. mayBeBox = true;
  11894. }
  11895. //TODO: the IsGenericParam is not valid - why did we have that? The generic param could be a struct for example...
  11896. if ((explicitCast) && ((typedVal.mType->IsInterface()) || (typedVal.mType == mContext->mBfObjectType) /*|| (typedVal.mType->IsGenericParam())*/) &&
  11897. ((toType->IsValueType()) || (toType->IsPointer())))
  11898. {
  11899. if (toType->IsValuelessType())
  11900. return BfIRValue::sValueless;
  11901. if (ignoreWrites)
  11902. return mBfIRBuilder->GetFakeVal();
  11903. // Unbox!
  11904. if ((castFlags & BfCastFlags_Unchecked) == 0)
  11905. {
  11906. EmitDynamicCastCheck(typedVal, toType, false);
  11907. EmitObjectAccessCheck(typedVal);
  11908. }
  11909. if (toType->IsNullable())
  11910. {
  11911. auto toTypeInst = toType->ToTypeInstance();
  11912. int valueIdx = toTypeInst->mFieldInstances[0].mDataIdx;
  11913. int hasValueIdx = toTypeInst->mFieldInstances[1].mDataIdx;
  11914. typedVal = MakeAddressable(typedVal);
  11915. auto elementType = toType->GetUnderlyingType();
  11916. auto ptrElementType = CreatePointerType(elementType);
  11917. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  11918. auto allocaInst = CreateAlloca(toType, true, "unboxN");
  11919. auto prevBB = mBfIRBuilder->GetInsertBlock();
  11920. auto nullBB = mBfIRBuilder->CreateBlock("unboxN.null");
  11921. auto notNullBB = mBfIRBuilder->CreateBlock("unboxN.notNull");
  11922. auto endBB = mBfIRBuilder->CreateBlock("unboxN.end");
  11923. auto isNull = mBfIRBuilder->CreateIsNull(typedVal.mValue);
  11924. mBfIRBuilder->CreateCondBr(isNull, nullBB, notNullBB);
  11925. int dataIdx = toTypeInst->mFieldInstances[1].mDataIdx;
  11926. mBfIRBuilder->AddBlock(nullBB);
  11927. mBfIRBuilder->SetInsertPoint(nullBB);
  11928. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, hasValueIdx); // has_value
  11929. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), hasValueAddr);
  11930. auto nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, valueIdx); // value
  11931. auto nullableValueBits = mBfIRBuilder->CreateBitCast(nullableValueAddr, mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  11932. mBfIRBuilder->CreateMemSet(nullableValueBits, GetConstValue(0, GetPrimitiveType(BfTypeCode_Int8)), GetConstValue(elementType->mSize), elementType->mAlign);
  11933. mBfIRBuilder->CreateBr(endBB);
  11934. mBfIRBuilder->AddBlock(notNullBB);
  11935. mBfIRBuilder->SetInsertPoint(notNullBB);
  11936. hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, hasValueIdx); // has_value
  11937. mBfIRBuilder->CreateStore(GetConstValue(1, boolType), hasValueAddr);
  11938. nullableValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, valueIdx); // value
  11939. auto srcObjBits = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(ptrElementType));
  11940. auto boxedValueAddr = mBfIRBuilder->CreateInBoundsGEP(srcObjBits, 1); // Skip over vdata
  11941. auto boxedValue = mBfIRBuilder->CreateLoad(boxedValueAddr);
  11942. mBfIRBuilder->CreateStore(boxedValue, nullableValueAddr);
  11943. mBfIRBuilder->CreateBr(endBB);
  11944. mBfIRBuilder->AddBlock(endBB);
  11945. mBfIRBuilder->SetInsertPoint(endBB);
  11946. if (resultFlags != NULL)
  11947. *resultFlags = (BfCastResultFlags)(BfCastResultFlags_IsAddr | BfCastResultFlags_IsTemp);
  11948. return allocaInst;
  11949. }
  11950. auto boxedType = CreateBoxedType(toType);
  11951. mBfIRBuilder->PopulateType(boxedType);
  11952. AddDependency(boxedType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  11953. auto boxedObj = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(boxedType));
  11954. auto valPtr = mBfIRBuilder->CreateInBoundsGEP(boxedObj, 0, 1);
  11955. if ((toType->IsPrimitiveType()) || (toType->IsTypedPrimitive()) || (toType->IsPointer()) || (toType->IsSizedArray()) || (toType->IsMethodRef()))
  11956. {
  11957. valPtr = mBfIRBuilder->CreateBitCast(valPtr, mBfIRBuilder->GetPointerTo(mBfIRBuilder->MapType(toType)));
  11958. }
  11959. if ((toType->IsComposite()) && (resultFlags != NULL))
  11960. {
  11961. *resultFlags = BfCastResultFlags_IsAddr;
  11962. return valPtr;
  11963. }
  11964. else
  11965. return mBfIRBuilder->CreateLoad(valPtr, false);
  11966. }
  11967. // Null -> Nullable<T>
  11968. if ((typedVal.mType->IsNull()) && (toType->IsNullable()))
  11969. {
  11970. if (ignoreWrites)
  11971. return mBfIRBuilder->GetFakeVal();
  11972. if ((castFlags & BfCastFlags_PreferAddr) != 0)
  11973. {
  11974. auto boolType = GetPrimitiveType(BfTypeCode_Boolean);
  11975. auto toTypeInst = toType->ToTypeInstance();
  11976. int hasValueIdx = toTypeInst->mFieldInstances[1].mDataIdx;
  11977. auto allocaInst = CreateAlloca(toType);
  11978. auto hasValueAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, hasValueIdx); // has_value
  11979. mBfIRBuilder->CreateStore(GetConstValue(0, boolType), hasValueAddr);
  11980. auto typedValue = BfTypedValue(allocaInst, toType, true);
  11981. if (resultFlags != NULL)
  11982. *resultFlags = (BfCastResultFlags)(BfCastResultFlags_IsAddr | BfCastResultFlags_IsTemp);
  11983. return allocaInst;
  11984. }
  11985. auto zeroNullable = mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(toType));
  11986. return zeroNullable;
  11987. }
  11988. // Nullable<A> -> Nullable<B>
  11989. if ((typedVal.mType->IsNullable()) && (toType->IsNullable()))
  11990. {
  11991. auto fromNullableType = (BfTypeInstance*)typedVal.mType;
  11992. auto toNullableType = (BfTypeInstance*)toType;
  11993. if (ignoreWrites)
  11994. {
  11995. auto toVal = CastToValue(srcNode, BfTypedValue(mBfIRBuilder->GetFakeVal(), fromNullableType->mGenericTypeInfo->mTypeGenericArguments[0]),
  11996. toNullableType->mGenericTypeInfo->mTypeGenericArguments[0], ignoreErrors ? BfCastFlags_SilentFail : BfCastFlags_None);
  11997. if (!toVal)
  11998. return BfIRValue();
  11999. return mBfIRBuilder->GetFakeVal();
  12000. }
  12001. BfIRValue srcPtr = typedVal.mValue;
  12002. if (!typedVal.IsAddr())
  12003. {
  12004. auto srcAlloca = CreateAllocaInst(fromNullableType);
  12005. mBfIRBuilder->CreateStore(typedVal.mValue, srcAlloca);
  12006. srcPtr = srcAlloca;
  12007. }
  12008. auto srcAddr = mBfIRBuilder->CreateInBoundsGEP(srcPtr, 0, 1); // mValue
  12009. auto srcVal = mBfIRBuilder->CreateLoad(srcAddr);
  12010. auto toVal = CastToValue(srcNode, BfTypedValue(srcVal, fromNullableType->mGenericTypeInfo->mTypeGenericArguments[0]),
  12011. toNullableType->mGenericTypeInfo->mTypeGenericArguments[0], ignoreErrors ? BfCastFlags_SilentFail : BfCastFlags_None);
  12012. if (!toVal)
  12013. return BfIRValue();
  12014. auto allocaInst = CreateAllocaInst(toNullableType);
  12015. auto destAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // mValue
  12016. mBfIRBuilder->CreateStore(toVal, destAddr);
  12017. srcAddr = mBfIRBuilder->CreateInBoundsGEP(srcPtr, 0, 2); // mHasValue
  12018. srcVal = mBfIRBuilder->CreateLoad(srcAddr);
  12019. destAddr = mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 2); // mHasValue
  12020. mBfIRBuilder->CreateStore(srcVal, destAddr);
  12021. if (resultFlags != NULL)
  12022. *resultFlags = (BfCastResultFlags)(BfCastResultFlags_IsAddr | BfCastResultFlags_IsTemp);
  12023. return allocaInst;
  12024. }
  12025. // Tuple -> Tuple
  12026. if ((typedVal.mType->IsTuple()) && (toType->IsTuple()))
  12027. {
  12028. auto fromTupleType = (BfTypeInstance*)typedVal.mType;
  12029. auto toTupleType = (BfTypeInstance*)toType;
  12030. PopulateType(fromTupleType);
  12031. PopulateType(toTupleType);
  12032. if (fromTupleType->mFieldInstances.size() == toTupleType->mFieldInstances.size())
  12033. {
  12034. typedVal = LoadValue(typedVal);
  12035. BfIRValue curTupleValue = mBfIRBuilder->CreateUndefValue(mBfIRBuilder->MapType(toTupleType));
  12036. for (int valueIdx = 0; valueIdx < (int)fromTupleType->mFieldInstances.size(); valueIdx++)
  12037. {
  12038. BfFieldInstance* fromFieldInstance = &fromTupleType->mFieldInstances[valueIdx];
  12039. BfFieldInstance* toFieldInstance = &toTupleType->mFieldInstances[valueIdx];
  12040. if (!explicitCast)
  12041. {
  12042. BfFieldDef* fromFieldDef = fromFieldInstance->GetFieldDef();
  12043. BfFieldDef* toFieldDef = toFieldInstance->GetFieldDef();
  12044. // Either the names have to match or one has to be unnamed
  12045. if ((!fromFieldDef->IsUnnamedTupleField()) && (!toFieldDef->IsUnnamedTupleField()) &&
  12046. (fromFieldDef->mName != toFieldDef->mName))
  12047. {
  12048. curTupleValue = BfIRValue();
  12049. break;
  12050. }
  12051. }
  12052. auto fromFieldType = fromFieldInstance->GetResolvedType();
  12053. auto toFieldType = toFieldInstance->GetResolvedType();
  12054. if (toFieldType->IsVoid())
  12055. continue; // Allow sinking to void
  12056. BfIRValue fromFieldValue;
  12057. if (fromFieldInstance->mDataIdx >= 0)
  12058. fromFieldValue = mBfIRBuilder->CreateExtractValue(typedVal.mValue, fromFieldInstance->mDataIdx);
  12059. BfIRValue toFieldValue = CastToValue(srcNode, BfTypedValue(fromFieldValue, fromFieldType), toFieldType, (BfCastFlags)(castFlags | BfCastFlags_Explicit));
  12060. if (!toFieldValue)
  12061. {
  12062. curTupleValue = BfIRValue();
  12063. break;
  12064. }
  12065. if (toFieldInstance->mDataIdx >= 0)
  12066. curTupleValue = mBfIRBuilder->CreateInsertValue(curTupleValue, toFieldValue, toFieldInstance->mDataIdx);
  12067. }
  12068. if (curTupleValue)
  12069. return curTupleValue;
  12070. }
  12071. }
  12072. // -> const <value>
  12073. if (toType->IsConstExprValue())
  12074. {
  12075. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  12076. if (constant != NULL)
  12077. {
  12078. BfConstExprValueType* toConstExprValueType = (BfConstExprValueType*)toType;
  12079. auto variantVal = TypedValueToVariant(srcNode, typedVal, true);
  12080. if ((mBfIRBuilder->IsIntable(variantVal.mTypeCode)) && (mBfIRBuilder->IsIntable(toConstExprValueType->mValue.mTypeCode)))
  12081. {
  12082. if (variantVal.mUInt64 == toConstExprValueType->mValue.mUInt64)
  12083. return typedVal.mValue;
  12084. }
  12085. else if ((mBfIRBuilder->IsFloat(variantVal.mTypeCode)) && (mBfIRBuilder->IsFloat(toConstExprValueType->mValue.mTypeCode)))
  12086. {
  12087. if (variantVal.ToDouble() == toConstExprValueType->mValue.ToDouble())
  12088. return typedVal.mValue;
  12089. }
  12090. if (toConstExprValueType->mValue.mTypeCode == BfTypeCode_StringId)
  12091. {
  12092. int stringIdx = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  12093. if ((stringIdx != -1) && (stringIdx == toConstExprValueType->mValue.mInt32))
  12094. return typedVal.mValue;
  12095. }
  12096. if ((toConstExprValueType->mValue.mTypeCode == BfTypeCode_Let) && (constant->mConstType == BfConstType_Undef))
  12097. {
  12098. return typedVal.mValue;
  12099. }
  12100. if (!ignoreErrors)
  12101. {
  12102. String valStr;
  12103. VariantToString(valStr, variantVal);
  12104. Fail(StrFormat("Unable to cast '%s %s' to '%s'", TypeToString(typedVal.mType).c_str(), valStr.c_str(), TypeToString(toType).c_str()), srcNode);
  12105. }
  12106. else if (!silentFail)
  12107. SetFail();
  12108. }
  12109. }
  12110. if ((typedVal.mType->IsPrimitiveType()) && (toType->IsPrimitiveType()))
  12111. {
  12112. auto fromPrimType = (BfPrimitiveType*)typedVal.mType;
  12113. auto toPrimType = (BfPrimitiveType*)toType;
  12114. BfTypeCode fromTypeCode = fromPrimType->mTypeDef->mTypeCode;
  12115. BfTypeCode toTypeCode = toPrimType->mTypeDef->mTypeCode;
  12116. if (toType->IsIntegral())
  12117. {
  12118. // Allow constant ints to be implicitly casted to a smaller type if they fit
  12119. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  12120. if (constant != NULL)
  12121. {
  12122. if (mBfIRBuilder->IsInt(constant->mTypeCode))
  12123. {
  12124. int64 srcVal = constant->mInt64;
  12125. if (toPrimType->IsChar())
  12126. {
  12127. if (srcVal == 0)
  12128. explicitCast = true;
  12129. }
  12130. else if ((fromPrimType->IsChar()) && (!toPrimType->IsChar()))
  12131. {
  12132. // Never allow this
  12133. }
  12134. else if ((constant->mTypeCode == BfTypeCode_UInt64) && (srcVal < 0))
  12135. {
  12136. // There's nothing that this could fit into
  12137. }
  12138. else if (toType->IsSigned())
  12139. {
  12140. if (toType->mSize == 8) // int64
  12141. explicitCast = true;
  12142. else
  12143. {
  12144. int64 minVal = -(1LL << (8 * toType->mSize - 1));
  12145. int64 maxVal = (1LL << (8 * toType->mSize - 1)) - 1;
  12146. if ((srcVal >= minVal) && (srcVal <= maxVal))
  12147. explicitCast = true;
  12148. }
  12149. }
  12150. else if (toType->mSize == 8) // uint64
  12151. {
  12152. if (srcVal >= 0)
  12153. explicitCast = true;
  12154. }
  12155. else
  12156. {
  12157. int64 minVal = 0;
  12158. int64 maxVal = (1LL << (8 * toType->mSize)) - 1;
  12159. if ((srcVal >= minVal) && (srcVal <= maxVal))
  12160. explicitCast = true;
  12161. }
  12162. }
  12163. else if (constant->mConstType == BfConstType_Undef)
  12164. {
  12165. if (mIsComptimeModule)
  12166. return mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(toType));
  12167. auto undefConst = (BfConstantUndef*)constant;
  12168. BfType* bfType = NULL;
  12169. if (undefConst->mType.mKind == BfIRTypeData::TypeKind_TypeCode)
  12170. {
  12171. bfType = GetPrimitiveType((BfTypeCode)undefConst->mType.mId);
  12172. }
  12173. else
  12174. {
  12175. BF_ASSERT(undefConst->mType.mKind == BfIRTypeData::TypeKind_TypeId);
  12176. if (undefConst->mType.mKind == BfIRTypeData::TypeKind_TypeId)
  12177. bfType = mContext->FindTypeById(undefConst->mType.mId);
  12178. }
  12179. if (bfType == NULL)
  12180. return BfIRValue();
  12181. auto fakeVal = GetFakeTypedValue(bfType);
  12182. auto val = CastToValue(srcNode, fakeVal, toType, castFlags);
  12183. if (val)
  12184. return mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(toType));
  12185. }
  12186. }
  12187. }
  12188. bool allowCast = false;
  12189. switch (toTypeCode)
  12190. {
  12191. case BfTypeCode_Char16:
  12192. switch (fromTypeCode)
  12193. {
  12194. case BfTypeCode_Char8:
  12195. allowCast = true; break;
  12196. default: break;
  12197. }
  12198. break;
  12199. case BfTypeCode_Int16:
  12200. switch (fromTypeCode)
  12201. {
  12202. case BfTypeCode_Int8:
  12203. allowCast = true; break;
  12204. case BfTypeCode_UInt8:
  12205. allowCast = true; break;
  12206. default: break;
  12207. }
  12208. break;
  12209. case BfTypeCode_UInt16:
  12210. switch (fromTypeCode)
  12211. {
  12212. case BfTypeCode_UInt8:
  12213. allowCast = true; break;
  12214. default: break;
  12215. }
  12216. break;
  12217. case BfTypeCode_Int32:
  12218. switch (fromTypeCode)
  12219. {
  12220. case BfTypeCode_Int8:
  12221. case BfTypeCode_Int16:
  12222. allowCast = true; break;
  12223. case BfTypeCode_IntPtr:
  12224. if (mCompiler->mSystem->mPtrSize == 4)
  12225. allowCast = true;
  12226. break;
  12227. case BfTypeCode_UInt8:
  12228. case BfTypeCode_UInt16:
  12229. allowCast = true; break;
  12230. default: break;
  12231. }
  12232. break;
  12233. case BfTypeCode_Char32:
  12234. switch (fromTypeCode)
  12235. {
  12236. case BfTypeCode_Char8:
  12237. case BfTypeCode_Char16:
  12238. allowCast = true; break;
  12239. default: break;
  12240. }
  12241. break;
  12242. case BfTypeCode_UInt32:
  12243. switch (fromTypeCode)
  12244. {
  12245. case BfTypeCode_UInt8:
  12246. case BfTypeCode_UInt16:
  12247. case BfTypeCode_UInt32:
  12248. allowCast = true; break;
  12249. case BfTypeCode_UIntPtr:
  12250. if (mCompiler->mSystem->mPtrSize == 4)
  12251. allowCast = true;
  12252. break;
  12253. default: break;
  12254. }
  12255. break;
  12256. case BfTypeCode_Int64:
  12257. switch (fromTypeCode)
  12258. {
  12259. case BfTypeCode_Int8:
  12260. case BfTypeCode_Int16:
  12261. case BfTypeCode_Int32:
  12262. case BfTypeCode_IntPtr:
  12263. allowCast = true; break;
  12264. case BfTypeCode_UInt8:
  12265. case BfTypeCode_UInt16:
  12266. case BfTypeCode_UInt32:
  12267. allowCast = true; break;
  12268. default: break;
  12269. }
  12270. break;
  12271. case BfTypeCode_UInt64:
  12272. switch (fromTypeCode)
  12273. {
  12274. case BfTypeCode_UInt8:
  12275. case BfTypeCode_UInt16:
  12276. case BfTypeCode_UInt32:
  12277. case BfTypeCode_UIntPtr:
  12278. allowCast = true; break;
  12279. default: break;
  12280. }
  12281. break;
  12282. case BfTypeCode_IntPtr:
  12283. switch (fromTypeCode)
  12284. {
  12285. case BfTypeCode_Int8:
  12286. case BfTypeCode_Int16:
  12287. case BfTypeCode_Int32:
  12288. allowCast = true; break;
  12289. case BfTypeCode_UInt8:
  12290. case BfTypeCode_UInt16:
  12291. allowCast = true; break;
  12292. case BfTypeCode_UInt32:
  12293. case BfTypeCode_Int64:
  12294. // It may seem that we want this to require an explicit cast,
  12295. // but consider the case of
  12296. // int val = Math.Max(intA, intB)
  12297. // Math.Max has an int32 and int64 override, so we want the correct one to be chosen and
  12298. // to be able to have the int64 return value implicitly used in a 64-bit build
  12299. if (mCompiler->mSystem->mPtrSize == 8)
  12300. allowCast = true;
  12301. break;
  12302. default: break;
  12303. }
  12304. break;
  12305. case BfTypeCode_UIntPtr:
  12306. switch (fromTypeCode)
  12307. {
  12308. case BfTypeCode_UInt8:
  12309. case BfTypeCode_UInt16:
  12310. case BfTypeCode_UInt32:
  12311. allowCast = true; break;
  12312. case BfTypeCode_UInt64:
  12313. if (mCompiler->mSystem->mPtrSize == 8)
  12314. allowCast = true;
  12315. break;
  12316. default: break;
  12317. }
  12318. break;
  12319. case BfTypeCode_Float:
  12320. switch (fromTypeCode)
  12321. {
  12322. case BfTypeCode_Int8:
  12323. case BfTypeCode_Int16:
  12324. case BfTypeCode_Int32:
  12325. case BfTypeCode_Int64:
  12326. case BfTypeCode_IntPtr:
  12327. case BfTypeCode_IntUnknown:
  12328. allowCast = true; break;
  12329. case BfTypeCode_UInt8:
  12330. case BfTypeCode_UInt16:
  12331. case BfTypeCode_UInt32:
  12332. case BfTypeCode_UInt64:
  12333. case BfTypeCode_UIntPtr:
  12334. case BfTypeCode_UIntUnknown:
  12335. allowCast = true; break;
  12336. default: break;
  12337. }
  12338. break;
  12339. case BfTypeCode_Double:
  12340. switch (fromTypeCode)
  12341. {
  12342. case BfTypeCode_Int8:
  12343. case BfTypeCode_Int16:
  12344. case BfTypeCode_Int32:
  12345. case BfTypeCode_Int64:
  12346. case BfTypeCode_IntPtr:
  12347. case BfTypeCode_IntUnknown:
  12348. allowCast = true; break;
  12349. case BfTypeCode_UInt8:
  12350. case BfTypeCode_UInt16:
  12351. case BfTypeCode_UInt32:
  12352. case BfTypeCode_UInt64:
  12353. case BfTypeCode_UIntPtr:
  12354. case BfTypeCode_UIntUnknown:
  12355. allowCast = true; break;
  12356. case BfTypeCode_Float:
  12357. allowCast = true; break;
  12358. default: break;
  12359. }
  12360. break;
  12361. default: break;
  12362. }
  12363. if (explicitCast)
  12364. {
  12365. if (((fromPrimType->IsIntegral()) || (fromPrimType->IsFloat())) &&
  12366. ((toType->IsIntegral()) || (toType->IsFloat())))
  12367. allowCast = true;
  12368. }
  12369. if (allowCast)
  12370. {
  12371. if (typedVal.IsAddr())
  12372. typedVal = LoadValue(typedVal);
  12373. return mBfIRBuilder->CreateNumericCast(typedVal.mValue, typedVal.mType->IsSigned(), toTypeCode);
  12374. }
  12375. }
  12376. if (typedVal.mValue.IsConst())
  12377. {
  12378. if ((toType->IsPointer()) && (toType->GetUnderlyingType() == GetPrimitiveType(BfTypeCode_Char8)) && (typedVal.mType->IsInstanceOf(mCompiler->mStringTypeDef)))
  12379. {
  12380. int stringId = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  12381. if (stringId >= 0)
  12382. return GetStringCharPtr(stringId);
  12383. }
  12384. else if ((toType->IsInstanceOf(mCompiler->mStringViewTypeDef)))
  12385. {
  12386. int stringId = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  12387. bool isNull = false;
  12388. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  12389. if (constant->mTypeCode == BfTypeCode_NullPtr)
  12390. isNull = true;
  12391. if ((stringId >= 0) || (isNull))
  12392. {
  12393. int strLen = 0;
  12394. String str;
  12395. BfStringPoolEntry* entry = NULL;
  12396. if ((isNull) || (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry)))
  12397. {
  12398. auto svTypeInst = toType->ToTypeInstance();
  12399. PopulateType(svTypeInst);
  12400. PopulateType(svTypeInst->mBaseType);
  12401. mBfIRBuilder->PopulateType(svTypeInst);
  12402. // Sanity check
  12403. if (svTypeInst->mMergedFieldDataCount == 2)
  12404. {
  12405. SizedArray<BfIRValue, 2> spanFieldVals;
  12406. spanFieldVals.Add(mBfIRBuilder->CreateConstAggZero(mBfIRBuilder->MapType(svTypeInst->mBaseType->mBaseType)));
  12407. if (isNull)
  12408. {
  12409. spanFieldVals.Add(mBfIRBuilder->CreateConstNull(mBfIRBuilder->MapType(CreatePointerType(GetPrimitiveType(BfTypeCode_Char8)))));
  12410. spanFieldVals.Add(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  12411. }
  12412. else
  12413. {
  12414. auto stringCharPtr = GetStringCharPtr(stringId);
  12415. spanFieldVals.Add(stringCharPtr);
  12416. spanFieldVals.Add(mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, entry->mString.mLength));
  12417. }
  12418. SizedArray<BfIRValue, 2> svFieldVals;
  12419. svFieldVals.Add(mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(svTypeInst->mBaseType), spanFieldVals));
  12420. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(svTypeInst), svFieldVals);
  12421. }
  12422. }
  12423. }
  12424. }
  12425. else if (toType->IsSizedArray())
  12426. {
  12427. auto sizedArray = (BfSizedArrayType*)toType;
  12428. if (sizedArray->mElementType == GetPrimitiveType(BfTypeCode_Char8))
  12429. {
  12430. int stringId = GetStringPoolIdx(typedVal.mValue, mBfIRBuilder);
  12431. if (stringId >= 0)
  12432. {
  12433. BfStringPoolEntry* entry = NULL;
  12434. if (mContext->mStringObjectIdMap.TryGetValue(stringId, &entry))
  12435. {
  12436. String& string = entry->mString;
  12437. if (string.GetLength() > sizedArray->mElementCount)
  12438. {
  12439. if (!ignoreErrors)
  12440. Fail(StrFormat("String literal is too long to fit into '%s'", TypeToString(sizedArray).c_str()), srcNode);
  12441. }
  12442. Array<BfIRValue> charValues;
  12443. for (int i = 0; i < (int)BF_MIN(string.GetLength(), sizedArray->mElementCount); i++)
  12444. {
  12445. char c = string[i];
  12446. charValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)(uint8)c));
  12447. }
  12448. if (sizedArray->mElementCount > charValues.size())
  12449. charValues.Add(mBfIRBuilder->CreateConst(BfTypeCode_Char8, 0));
  12450. return mBfIRBuilder->CreateConstAgg(mBfIRBuilder->MapType(sizedArray), charValues);
  12451. }
  12452. }
  12453. }
  12454. }
  12455. }
  12456. // Check user-defined operators
  12457. if (((castFlags & BfCastFlags_NoConversionOperator) == 0) && (toType != mContext->mBfObjectType))
  12458. {
  12459. BfType* walkFromType = typedVal.mType;
  12460. if (walkFromType->IsWrappableType())
  12461. walkFromType = GetWrappedStructType(walkFromType);
  12462. BfType* walkToType = toType;
  12463. if (walkToType->IsWrappableType())
  12464. walkToType = GetWrappedStructType(walkToType);
  12465. SizedArray<BfResolvedArg, 1> args;
  12466. BfResolvedArg resolvedArg;
  12467. resolvedArg.mTypedValue = typedVal;
  12468. if (resolvedArg.mTypedValue.IsParams())
  12469. {
  12470. resolvedArg.mTypedValue = LoadOrAggregateValue(resolvedArg.mTypedValue);
  12471. resolvedArg.mTypedValue.mKind = BfTypedValueKind_Value;
  12472. }
  12473. args.push_back(resolvedArg);
  12474. BfMethodMatcher methodMatcher(srcNode, this, "", args, BfMethodGenericArguments());
  12475. methodMatcher.mCheckReturnType = toType;
  12476. methodMatcher.mBfEvalExprFlags = (BfEvalExprFlags)(BfEvalExprFlags_NoAutoComplete | BfEvalExprFlags_FromConversionOp);
  12477. if ((castFlags & BfCastFlags_Explicit) != 0)
  12478. methodMatcher.mBfEvalExprFlags = (BfEvalExprFlags)(methodMatcher.mBfEvalExprFlags | BfEvalExprFlags_FromConversionOp_Explicit);
  12479. methodMatcher.mAllowImplicitRef = true;
  12480. methodMatcher.mAllowImplicitWrap = true;
  12481. BfBaseClassWalker baseClassWalker(walkFromType, walkToType, this);
  12482. bool isConstraintCheck = ((castFlags & BfCastFlags_IsConstraintCheck) != 0);
  12483. BfType* bestSelfType = NULL;
  12484. while (true)
  12485. {
  12486. auto entry = baseClassWalker.Next();
  12487. auto checkType = entry.mTypeInstance;
  12488. if (checkType == NULL)
  12489. break;
  12490. for (auto operatorDef : checkType->mTypeDef->mOperators)
  12491. {
  12492. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  12493. {
  12494. if ((!explicitCast) && (operatorDef->IsExplicit()))
  12495. continue;
  12496. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  12497. continue;
  12498. int prevArgSize = (int)args.mSize;
  12499. if (!operatorDef->mIsStatic)
  12500. {
  12501. // Try without arg
  12502. args.mSize = 0;
  12503. }
  12504. if (isConstraintCheck)
  12505. {
  12506. auto returnType = CheckOperator(checkType, operatorDef, typedVal, BfTypedValue());
  12507. if (returnType != NULL)
  12508. {
  12509. auto result = BfTypedValue(mBfIRBuilder->GetFakeVal(), returnType);
  12510. if (result)
  12511. {
  12512. if (result.mType != toType)
  12513. {
  12514. auto castedResult = CastToValue(srcNode, result, toType, (BfCastFlags)(castFlags | BfCastFlags_Explicit | BfCastFlags_NoConversionOperator), resultFlags);
  12515. if (castedResult)
  12516. return castedResult;
  12517. }
  12518. else
  12519. return result.mValue;
  12520. }
  12521. }
  12522. }
  12523. else
  12524. {
  12525. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  12526. methodMatcher.mSelfType = entry.mSrcType;
  12527. }
  12528. args.mSize = prevArgSize;
  12529. }
  12530. }
  12531. }
  12532. if (methodMatcher.mBestMethodDef != NULL)
  12533. {
  12534. if (mayBeBox)
  12535. {
  12536. if (!ignoreErrors)
  12537. {
  12538. if (Fail("Ambiguous cast, may be conversion operator or may be boxing request", srcNode) != NULL)
  12539. mCompiler->mPassInstance->MoreInfo("See conversion operator", methodMatcher.mBestMethodDef->GetRefNode());
  12540. }
  12541. else if (!silentFail)
  12542. SetFail();
  12543. }
  12544. }
  12545. if (methodMatcher.mBestMethodDef == NULL)
  12546. {
  12547. // Check method generic constraints
  12548. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecialized) && (mCurMethodInstance->mMethodInfoEx != NULL))
  12549. {
  12550. for (int genericParamIdx = 0; genericParamIdx < mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  12551. {
  12552. auto genericParam = mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  12553. for (auto& opConstraint : genericParam->mOperatorConstraints)
  12554. {
  12555. if ((opConstraint.mCastToken == BfToken_Implicit) ||
  12556. ((explicitCast) && (opConstraint.mCastToken == BfToken_Explicit)))
  12557. {
  12558. // If we can convert OUR fromVal to the constraint's fromVal then we may match
  12559. if (CanCast(typedVal, opConstraint.mRightType, BfCastFlags_NoConversionOperator))
  12560. {
  12561. // .. and we can convert the constraint's toType to OUR toType then we're good
  12562. auto opToVal = genericParam->mExternType;
  12563. if (CanCast(BfTypedValue(BfIRValue::sValueless, opToVal), toType, BfCastFlags_NoConversionOperator))
  12564. {
  12565. if (mBfIRBuilder->IsConstValue(typedVal.mValue))
  12566. {
  12567. // Retain constness
  12568. return mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(toType));
  12569. }
  12570. else
  12571. return mBfIRBuilder->GetFakeVal();
  12572. }
  12573. }
  12574. }
  12575. }
  12576. }
  12577. }
  12578. // Check type generic constraints
  12579. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsGenericTypeInstance()) && (mCurTypeInstance->IsUnspecializedType()))
  12580. {
  12581. SizedArray<BfGenericParamInstance*, 4> genericParams;
  12582. GetActiveTypeGenericParamInstances(genericParams);
  12583. for (auto genericParam : genericParams)
  12584. {
  12585. for (auto& opConstraint : genericParam->mOperatorConstraints)
  12586. {
  12587. if ((opConstraint.mCastToken == BfToken_Implicit) ||
  12588. ((explicitCast) && (opConstraint.mCastToken == BfToken_Explicit)))
  12589. {
  12590. // If we can convert OUR fromVal to the constraint's fromVal then we may match
  12591. if (CanCast(typedVal, opConstraint.mRightType, BfCastFlags_NoConversionOperator))
  12592. {
  12593. // .. and we can convert the constraint's toType to OUR toType then we're good
  12594. auto opToVal = genericParam->mExternType;
  12595. if (CanCast(BfTypedValue(BfIRValue::sValueless, opToVal), toType, BfCastFlags_NoConversionOperator))
  12596. {
  12597. if (mBfIRBuilder->IsConstValue(typedVal.mValue))
  12598. {
  12599. // Retain constness
  12600. return mBfIRBuilder->GetUndefConstValue(mBfIRBuilder->MapType(toType));
  12601. }
  12602. else
  12603. return mBfIRBuilder->GetFakeVal();
  12604. }
  12605. }
  12606. }
  12607. }
  12608. }
  12609. }
  12610. }
  12611. else
  12612. {
  12613. BfTypedValue result;
  12614. BfExprEvaluator exprEvaluator(this);
  12615. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_FromConversionOp;
  12616. if ((castFlags & BfCastFlags_WantsConst) != 0)
  12617. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  12618. auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodMatcher.mBestMethodDef->mMethodDeclaration);
  12619. if ((methodDeclaration != NULL) && (methodDeclaration->mBody == NULL))
  12620. {
  12621. auto fromType = typedVal.mType;
  12622. // Handle the typedPrim<->underlying part implicitly
  12623. if (fromType->IsTypedPrimitive())
  12624. {
  12625. typedVal = LoadValue(typedVal);
  12626. auto convTypedValue = BfTypedValue(typedVal.mValue, fromType->GetUnderlyingType());
  12627. return CastToValue(srcNode, convTypedValue, toType, (BfCastFlags)(castFlags & ~BfCastFlags_Explicit), NULL);
  12628. }
  12629. else if (toType->IsTypedPrimitive())
  12630. {
  12631. auto castedVal = CastToValue(srcNode, typedVal, toType->GetUnderlyingType(), (BfCastFlags)(castFlags & ~BfCastFlags_Explicit), NULL);
  12632. return castedVal;
  12633. }
  12634. }
  12635. bool doCall = true;
  12636. auto moduleMethodInstance = exprEvaluator.GetSelectedMethod(methodMatcher);
  12637. if (moduleMethodInstance.mMethodInstance != NULL)
  12638. {
  12639. auto returnType = moduleMethodInstance.mMethodInstance->mReturnType;
  12640. auto paramType = moduleMethodInstance.mMethodInstance->GetParamType(0);
  12641. BfCastFlags implicitCastFlags = (BfCastFlags)(castFlags & ~BfCastFlags_Explicit | BfCastFlags_NoConversionOperator);
  12642. // Check typedPrimitive->underlying cast
  12643. if ((explicitCast) && (typedVal.mType->IsTypedPrimitive()))
  12644. {
  12645. auto underlyingType = typedVal.mType->GetUnderlyingType();
  12646. if ((returnType == underlyingType) && (explicitCast))
  12647. {
  12648. doCall = false;
  12649. }
  12650. else if ((CanCast(GetFakeTypedValue(underlyingType), toType, (BfCastFlags)(castFlags | BfCastFlags_NoConversionOperator))))
  12651. {
  12652. float underlyingCanCast = CanCast(GetFakeTypedValue(underlyingType), toType, implicitCastFlags);
  12653. float returnCanCast = CanCast(GetFakeTypedValue(returnType), toType, implicitCastFlags);
  12654. if ((underlyingCanCast) &&
  12655. (!returnCanCast))
  12656. {
  12657. doCall = false;
  12658. }
  12659. else if ((returnCanCast) &&
  12660. (!underlyingCanCast))
  12661. {
  12662. // Can do
  12663. }
  12664. else if ((CanCast(GetFakeTypedValue(underlyingType), returnType, implicitCastFlags)) &&
  12665. (!CanCast(GetFakeTypedValue(returnType), underlyingType, implicitCastFlags)))
  12666. {
  12667. // Can do
  12668. }
  12669. else
  12670. doCall = false;
  12671. }
  12672. }
  12673. // Check underlying->typedPrimitive cast
  12674. if ((explicitCast) && (toType->IsTypedPrimitive()))
  12675. {
  12676. auto underlyingType = toType->GetUnderlyingType();
  12677. if ((paramType == underlyingType) && (explicitCast))
  12678. {
  12679. doCall = false;
  12680. }
  12681. else if (CanCast(typedVal, underlyingType, (BfCastFlags)(castFlags | BfCastFlags_NoConversionOperator)))
  12682. {
  12683. float underlyingCanCast = CanCast(typedVal, underlyingType, implicitCastFlags);
  12684. float paramCanCast = CanCast(typedVal, paramType, implicitCastFlags);
  12685. if ((underlyingType) &&
  12686. (!paramCanCast))
  12687. {
  12688. doCall = false;
  12689. }
  12690. else if ((paramCanCast) &&
  12691. (!underlyingCanCast))
  12692. {
  12693. // Can do
  12694. }
  12695. else if ((CanCast(GetFakeTypedValue(underlyingType), paramType, implicitCastFlags)) &&
  12696. (!CanCast(GetFakeTypedValue(paramType), underlyingType, implicitCastFlags)))
  12697. {
  12698. // Can do
  12699. }
  12700. else
  12701. doCall = false;
  12702. }
  12703. }
  12704. if (doCall)
  12705. {
  12706. if (!silentFail)
  12707. methodMatcher.FlushAmbiguityError();
  12708. auto wantType = paramType;
  12709. if (wantType->IsRef())
  12710. wantType = wantType->GetUnderlyingType();
  12711. auto convTypedVal = methodMatcher.mArguments[0].mTypedValue;
  12712. if (wantType != convTypedVal.mType)
  12713. {
  12714. if ((convTypedVal.mType->IsWrappableType()) && (wantType == GetWrappedStructType(convTypedVal.mType)))
  12715. {
  12716. convTypedVal = MakeAddressable(convTypedVal);
  12717. if (convTypedVal.mType->IsValuelessType())
  12718. {
  12719. methodMatcher.mArguments[0].mTypedValue = GetDefaultTypedValue(paramType, false, paramType->IsRef() ? BfDefaultValueKind_Value : BfDefaultValueKind_Addr);
  12720. }
  12721. else
  12722. {
  12723. methodMatcher.mArguments[0].mTypedValue = BfTypedValue(mBfIRBuilder->CreateBitCast(convTypedVal.mValue, mBfIRBuilder->MapTypeInstPtr(wantType->ToTypeInstance())),
  12724. paramType, paramType->IsRef() ? BfTypedValueKind_Value : BfTypedValueKind_Addr);
  12725. }
  12726. }
  12727. else
  12728. {
  12729. methodMatcher.mArguments[0].mTypedValue = Cast(srcNode, convTypedVal, wantType, (BfCastFlags)(castFlags | BfCastFlags_Explicit | BfCastFlags_NoConversionOperator));
  12730. if (paramType->IsRef())
  12731. {
  12732. convTypedVal = MakeAddressable(convTypedVal);
  12733. convTypedVal.mKind = BfTypedValueKind_Addr;
  12734. }
  12735. }
  12736. }
  12737. }
  12738. }
  12739. if (doCall)
  12740. {
  12741. if ((castFlags & BfCastFlags_IsCastCheck) != 0)
  12742. {
  12743. // We've already verified that we can cast from the return type to toType in MethodMatcher.CheckMethod
  12744. return mBfIRBuilder->GetFakeVal();
  12745. }
  12746. result = exprEvaluator.CreateCall(&methodMatcher, BfTypedValue());
  12747. if (result.mType != toType)
  12748. return CastToValue(srcNode, result, toType, (BfCastFlags)(castFlags | BfCastFlags_Explicit | BfCastFlags_NoConversionOperator), resultFlags);
  12749. if (result)
  12750. {
  12751. if (resultFlags != NULL)
  12752. {
  12753. if (result.IsAddr())
  12754. *resultFlags = (BfCastResultFlags)(*resultFlags | BfCastResultFlags_IsAddr);
  12755. if (result.mKind == BfTypedValueKind_TempAddr)
  12756. *resultFlags = (BfCastResultFlags)(*resultFlags | BfCastResultFlags_IsTemp);
  12757. }
  12758. else if (result.IsAddr())
  12759. result = LoadValue(result);
  12760. return result.mValue;
  12761. }
  12762. }
  12763. }
  12764. }
  12765. // Default typed primitive 'underlying casts' happen after checking cast operators
  12766. if (explicitCast)
  12767. {
  12768. // TypedPrimitive -> Primitive
  12769. if ((typedVal.mType->IsTypedPrimitive()) && (!typedVal.mType->IsFunction()) && (toType->IsPrimitiveType()))
  12770. {
  12771. auto fromTypedPrimitiveType = typedVal.mType->ToTypeInstance();
  12772. auto primTypedVal = BfTypedValue(typedVal.mValue, fromTypedPrimitiveType->mFieldInstances.back().mResolvedType, typedVal.IsAddr());
  12773. primTypedVal = LoadValue(primTypedVal);
  12774. if ((typedVal.mType->IsEnum()) && (primTypedVal.IsValuelessType()))
  12775. {
  12776. // For enums with <= 1 member, fake an int8(0) instead of a void
  12777. primTypedVal = GetDefaultTypedValue(GetPrimitiveType(BfTypeCode_Int8));
  12778. }
  12779. return CastToValue(srcNode, primTypedVal, toType, castFlags);
  12780. }
  12781. // TypedPrimitive -> TypedPrimitive
  12782. if ((typedVal.mType->IsTypedPrimitive()) && (!typedVal.mType->IsFunction()) && (toType->IsTypedPrimitive()))
  12783. {
  12784. auto fromTypedPrimitiveType = typedVal.mType->ToTypeInstance();
  12785. auto toTypedPrimitiveType = toType->ToTypeInstance();
  12786. auto fromUnderlyingType = fromTypedPrimitiveType->GetUnderlyingType();
  12787. auto toUnderlyingType = toTypedPrimitiveType->GetUnderlyingType();
  12788. BfTypedValue underlyingTypedValue(typedVal.mValue, fromUnderlyingType, typedVal.IsAddr());
  12789. underlyingTypedValue = LoadValue(underlyingTypedValue);
  12790. BfIRValue castedToValue = CastToValue(srcNode, underlyingTypedValue, toUnderlyingType, (BfCastFlags)(castFlags | BfCastFlags_Explicit));
  12791. if (castedToValue)
  12792. return castedToValue;
  12793. }
  12794. }
  12795. else if ((typedVal.mType->IsTypedPrimitive()) && (toType->IsTypedPrimitive()))
  12796. {
  12797. if (TypeIsSubTypeOf(typedVal.mType->ToTypeInstance(), toType->ToTypeInstance()))
  12798. {
  12799. // These have the same underlying primitive type, just keep it all the same
  12800. if ((resultFlags != NULL) && (typedVal.IsAddr()))
  12801. *resultFlags = BfCastResultFlags_IsAddr;
  12802. return typedVal.mValue;
  12803. }
  12804. }
  12805. // Prim -> TypedPrimitive
  12806. if ((typedVal.mType->IsPrimitiveType()) && (toType->IsTypedPrimitive()))
  12807. {
  12808. bool allowCast = explicitCast;
  12809. if (toType == mCurTypeInstance)
  12810. allowCast = true;
  12811. if ((!allowCast) && (typedVal.mType->IsIntegral()) /*&& (!toType->IsEnum())*/)
  12812. {
  12813. // Allow implicit cast of zero
  12814. auto constant = mBfIRBuilder->GetConstant(typedVal.mValue);
  12815. if ((constant != NULL) && (mBfIRBuilder->IsInt(constant->mTypeCode)))
  12816. {
  12817. allowCast = constant->mInt64 == 0;
  12818. }
  12819. }
  12820. if (allowCast)
  12821. {
  12822. return CastToValue(srcNode, typedVal, toType->GetUnderlyingType(), castFlags);
  12823. }
  12824. }
  12825. if (typedVal.mType->IsBoxed())
  12826. {
  12827. BfBoxedType* boxedType = (BfBoxedType*)typedVal.mType;
  12828. if (boxedType->mElementType->IsGenericParam())
  12829. {
  12830. // If we have a boxed generic param, the actual available interfaces constraints won't be
  12831. // handled, so we need to pass through again as the root generic param
  12832. BfTypedValue unboxedValue = typedVal;
  12833. unboxedValue.mType = boxedType->mElementType;
  12834. auto result = CastToValue(srcNode, unboxedValue, toType, (BfCastFlags)(castFlags | BfCastFlags_SilentFail), resultFlags);
  12835. if (result)
  12836. return result;
  12837. }
  12838. }
  12839. if ((mayBeBox) && ((castFlags & BfCastFlags_NoBox) == 0))
  12840. {
  12841. BfScopeData* scopeData = NULL;
  12842. if (mCurMethodState != NULL)
  12843. {
  12844. if (mCurMethodState->mOverrideScope)
  12845. scopeData = mCurMethodState->mOverrideScope;
  12846. else
  12847. scopeData = mCurMethodState->mCurScope;
  12848. }
  12849. if ((castFlags & BfCastFlags_WarnOnBox) != 0)
  12850. {
  12851. Warn(0, "This implicit boxing will only be in scope during the constructor. Consider using a longer-term allocation such as 'box new'", srcNode);
  12852. }
  12853. SetAndRestoreValue<bool> prevIgnoreWrites(mBfIRBuilder->mIgnoreWrites, ignoreWrites);
  12854. auto value = BoxValue(srcNode, typedVal, toType, scopeData, castFlags);
  12855. if (value)
  12856. return value.mValue;
  12857. }
  12858. if (!ignoreErrors)
  12859. {
  12860. const char* errStrF = explicitCast ?
  12861. "Unable to cast '%s' to '%s'" :
  12862. "Unable to implicitly cast '%s' to '%s'";
  12863. if ((castFlags & BfCastFlags_FromComptimeReturn) != 0)
  12864. errStrF = "Comptime return unable to cast '%s' to '%s'";
  12865. String errStr = StrFormat(errStrF, TypeToString(typedVal.mType).c_str(), TypeToString(toType).c_str());
  12866. auto error = Fail(errStr, srcNode);
  12867. if ((error != NULL) && (srcNode != NULL))
  12868. {
  12869. if ((mCompiler->IsAutocomplete()) && (mCompiler->mResolvePassData->mAutoComplete->CheckFixit((srcNode))))
  12870. {
  12871. SetAndRestoreValue<bool> ignoreWrites(mBfIRBuilder->mIgnoreWrites);
  12872. SetAndRestoreValue<bool> ignoreErrors(mIgnoreErrors, true);
  12873. if (CastToValue(srcNode, typedVal, toType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail)))
  12874. {
  12875. bool doWrap = false;
  12876. if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(srcNode))
  12877. {
  12878. if ((unaryOpExpr->mOp != BfUnaryOp_AddressOf) && (unaryOpExpr->mOp != BfUnaryOp_Dereference))
  12879. doWrap = true;
  12880. }
  12881. if ((srcNode->IsA<BfCastExpression>()) ||
  12882. (srcNode->IsA<BfBinaryOperatorExpression>()) ||
  12883. (srcNode->IsA<BfConditionalExpression>()))
  12884. doWrap = true;
  12885. BfParserData* parser = srcNode->GetSourceData()->ToParserData();
  12886. String typeName = TypeToString(toType);
  12887. if (doWrap)
  12888. {
  12889. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit",
  12890. StrFormat("(%s)\tcast|%s|%d|(%s)(|`%d|)", typeName.c_str(), parser->mFileName.c_str(), srcNode->GetSrcStart(), typeName.c_str(), srcNode->GetSrcLength()).c_str()));
  12891. }
  12892. else
  12893. {
  12894. mCompiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit",
  12895. StrFormat("(%s)\tcast|%s|%d|(%s)", typeName.c_str(), parser->mFileName.c_str(), srcNode->GetSrcStart(), typeName.c_str()).c_str()));
  12896. }
  12897. }
  12898. }
  12899. }
  12900. }
  12901. else if (!silentFail)
  12902. SetFail();
  12903. return BfIRValue();
  12904. }
  12905. BfTypedValue BfModule::Cast(BfAstNode* srcNode, const BfTypedValue& typedVal, BfType* toType, BfCastFlags castFlags)
  12906. {
  12907. bool explicitCast = (castFlags & BfCastFlags_Explicit) != 0;
  12908. if (typedVal.mType == toType)
  12909. return typedVal;
  12910. if ((toType->IsSizedArray()) && (typedVal.mType->IsSizedArray()))
  12911. {
  12912. // Retain our type if we're casting from a known-sized array to an unknown-sized arrays
  12913. if ((toType->IsUndefSizedArray()) && ((typedVal.mType->GetUnderlyingType()) == (toType->GetUnderlyingType())))
  12914. {
  12915. return typedVal;
  12916. }
  12917. }
  12918. if ((castFlags & BfCastFlags_Force) != 0)
  12919. {
  12920. PopulateType(toType, BfPopulateType_Data);
  12921. if (toType->IsValuelessType())
  12922. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  12923. if ((typedVal.mType->IsValueType()) && (!typedVal.IsAddr()) && (typedVal.IsSplat()) && (toType->IsValueType()))
  12924. {
  12925. bool needsMemberCasting = false;
  12926. if (AreSplatsCompatible(typedVal.mType, toType, &needsMemberCasting))
  12927. {
  12928. return BfTypedValue(typedVal.mValue, toType, needsMemberCasting ? BfTypedValueKind_SplatHead_NeedsCasting : BfTypedValueKind_SplatHead);
  12929. }
  12930. }
  12931. if (typedVal.mType->IsValueType())
  12932. {
  12933. auto addrTypedValue = MakeAddressable(typedVal);
  12934. auto toPtrType = CreatePointerType(toType);
  12935. return BfTypedValue(mBfIRBuilder->CreateBitCast(addrTypedValue.mValue, mBfIRBuilder->MapType(toPtrType)), toType, BfTypedValueKind_Addr);
  12936. }
  12937. return BfTypedValue(mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapType(toType)), toType);
  12938. }
  12939. // This tuple cast may create a new type if the toType contains 'var' entries
  12940. if ((typedVal.mType->IsTuple()) && (toType->IsTuple()))
  12941. {
  12942. PopulateType(toType);
  12943. auto fromTupleType = (BfTypeInstance*)typedVal.mType;
  12944. auto toTupleType = (BfTypeInstance*)toType;
  12945. if (fromTupleType == toTupleType)
  12946. return typedVal;
  12947. if (fromTupleType->mFieldInstances.size() == toTupleType->mFieldInstances.size())
  12948. {
  12949. BfTypeVector fieldTypes;
  12950. Array<String> fieldNames;
  12951. bool isCompatible = true;
  12952. bool isExactTypeMatch = true;
  12953. for (int fieldIdx = 0; fieldIdx < (int)fromTupleType->mFieldInstances.size(); fieldIdx++)
  12954. {
  12955. auto fromFieldInst = &fromTupleType->mFieldInstances[fieldIdx];
  12956. auto toFieldInst = &toTupleType->mFieldInstances[fieldIdx];
  12957. auto fromFieldDef = fromFieldInst->GetFieldDef();
  12958. auto toFieldDef = toFieldInst->GetFieldDef();
  12959. if (!toFieldDef->IsUnnamedTupleField())
  12960. {
  12961. if ((!explicitCast) &&
  12962. (!fromFieldDef->IsUnnamedTupleField()) &&
  12963. (fromFieldDef->mName != toFieldDef->mName))
  12964. isCompatible = false;
  12965. fieldNames.push_back(toFieldDef->mName);
  12966. }
  12967. else
  12968. fieldNames.push_back("");
  12969. if (toFieldInst->mResolvedType->IsVar())
  12970. fieldTypes.push_back(fromFieldInst->mResolvedType);
  12971. else
  12972. {
  12973. if (fromFieldInst->mResolvedType != toFieldInst->mResolvedType)
  12974. isExactTypeMatch = false;
  12975. BfCastFlags tryCastFlags = BfCastFlags_SilentFail;
  12976. if (explicitCast)
  12977. tryCastFlags = (BfCastFlags)(tryCastFlags | BfCastFlags_Explicit);
  12978. // 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
  12979. // so we can give normal implicit-cast-to-void errors
  12980. if ((fromFieldInst->mResolvedType != toFieldInst->mResolvedType) && (!toFieldInst->mResolvedType->IsVoid()) &&
  12981. (!CanCast(GetFakeTypedValue(fromFieldInst->mResolvedType), toFieldInst->mResolvedType, tryCastFlags)))
  12982. isCompatible = false;
  12983. fieldTypes.push_back(toFieldInst->mResolvedType);
  12984. }
  12985. }
  12986. auto tupleType = CreateTupleType(fieldTypes, fieldNames);
  12987. AddDependency(tupleType, mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  12988. mBfIRBuilder->PopulateType(tupleType);
  12989. if (isCompatible)
  12990. {
  12991. if (isExactTypeMatch)
  12992. {
  12993. if (typedVal.mKind == BfTypedValueKind_TempAddr)
  12994. {
  12995. return BfTypedValue(mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapTypeInstPtr(tupleType)), tupleType, BfTypedValueKind_TempAddr);
  12996. }
  12997. else if (typedVal.IsAddr())
  12998. {
  12999. return BfTypedValue(mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapTypeInstPtr(tupleType)), tupleType, BfTypedValueKind_ReadOnlyAddr);
  13000. }
  13001. else if (typedVal.IsSplat())
  13002. {
  13003. BfTypedValue retTypedValue = typedVal;
  13004. retTypedValue.mType = tupleType;
  13005. return retTypedValue;
  13006. }
  13007. BfIRValue curTupleValue = CreateAlloca(tupleType);
  13008. auto loadedVal = LoadValue(typedVal);
  13009. mBfIRBuilder->CreateStore(loadedVal.mValue, mBfIRBuilder->CreateBitCast(curTupleValue, mBfIRBuilder->MapTypeInstPtr(fromTupleType)));
  13010. return BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  13011. }
  13012. BfIRValue curTupleValue = CreateAlloca(tupleType);
  13013. for (int fieldIdx = 0; fieldIdx < (int)fromTupleType->mFieldInstances.size(); fieldIdx++)
  13014. {
  13015. BfFieldInstance* fromFieldInstance = &fromTupleType->mFieldInstances[fieldIdx];
  13016. BfFieldInstance* toFieldInstance = &tupleType->mFieldInstances[fieldIdx];
  13017. if (toFieldInstance->mDataIdx >= 0)
  13018. {
  13019. if (fromFieldInstance->mDataIdx >= 0)
  13020. {
  13021. auto elementVal = ExtractValue(typedVal, fromFieldInstance, fromFieldInstance->mDataIdx);
  13022. elementVal = LoadValue(elementVal);
  13023. auto castedElementVal = Cast(srcNode, elementVal, toFieldInstance->GetResolvedType(), castFlags);
  13024. if (!castedElementVal)
  13025. return BfTypedValue();
  13026. auto fieldRef = mBfIRBuilder->CreateInBoundsGEP(curTupleValue, 0, toFieldInstance->mDataIdx);
  13027. castedElementVal = LoadValue(castedElementVal);
  13028. mBfIRBuilder->CreateStore(castedElementVal.mValue, fieldRef);
  13029. }
  13030. else
  13031. isCompatible = false;
  13032. }
  13033. }
  13034. return BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  13035. }
  13036. }
  13037. const char* errStr = explicitCast ?
  13038. "Unable to cast '%s' to '%s'" :
  13039. "Unable to implicitly cast '%s' to '%s'";
  13040. Fail(StrFormat(errStr, TypeToString(typedVal.mType).c_str(), TypeToString(toType).c_str()), srcNode);
  13041. return BfTypedValue();
  13042. }
  13043. // Function->Function and Delegate->Delegate where type is compatible but not exact
  13044. if (((typedVal.mType->IsDelegate()) || (typedVal.mType->IsFunction())) &&
  13045. (typedVal.mType != toType) && // Don't bother to check for exact match, let CastToValue handle this
  13046. ((typedVal.mType->IsDelegate()) == (toType->IsDelegate())) &&
  13047. ((typedVal.mType->IsFunction()) == (toType->IsFunction())))
  13048. {
  13049. auto fromTypeInst = typedVal.mType->ToTypeInstance();
  13050. auto toTypeInst = toType->ToTypeInstance();
  13051. auto fromMethodInst = GetRawMethodByName(fromTypeInst, "Invoke", -1, true);
  13052. auto toMethodInst = GetRawMethodByName(toTypeInst, "Invoke", -1, true);
  13053. auto toDelegateInfo = toTypeInst->GetDelegateInfo();
  13054. if ((fromMethodInst != NULL) && (toMethodInst != NULL) &&
  13055. (fromMethodInst->mCallingConvention == toMethodInst->mCallingConvention) &&
  13056. (fromMethodInst->mMethodDef->mIsMutating == toMethodInst->mMethodDef->mIsMutating) &&
  13057. (fromMethodInst->mReturnType == toMethodInst->mReturnType) &&
  13058. (fromMethodInst->GetParamCount() == toMethodInst->GetParamCount()))
  13059. {
  13060. bool matched = true;
  13061. StringT<64> fromParamName;
  13062. StringT<64> toParamName;
  13063. if (fromMethodInst->HasExplicitThis() != toMethodInst->HasExplicitThis())
  13064. {
  13065. matched = false;
  13066. }
  13067. else
  13068. {
  13069. for (int paramIdx = 0; paramIdx < (int)fromMethodInst->GetParamCount(); paramIdx++)
  13070. {
  13071. bool nameMatches = true;
  13072. if (!explicitCast)
  13073. {
  13074. int fromNamePrefixCount = 0;
  13075. int toNamePrefixCount = 0;
  13076. fromMethodInst->GetParamName(paramIdx, fromParamName, fromNamePrefixCount);
  13077. toMethodInst->GetParamName(paramIdx, toParamName, toNamePrefixCount);
  13078. if ((!fromParamName.IsEmpty()) && (!toParamName.IsEmpty()))
  13079. nameMatches = fromParamName == toParamName;
  13080. }
  13081. if ((fromMethodInst->GetParamKind(paramIdx) == toMethodInst->GetParamKind(paramIdx)) &&
  13082. (fromMethodInst->GetParamType(paramIdx) == toMethodInst->GetParamType(paramIdx)) &&
  13083. (nameMatches))
  13084. {
  13085. // Matched, required for implicit/explicit
  13086. }
  13087. else
  13088. {
  13089. matched = false;
  13090. break;
  13091. }
  13092. }
  13093. }
  13094. if (matched)
  13095. {
  13096. BfTypedValue loadedVal = LoadValue(typedVal);
  13097. return BfTypedValue(mBfIRBuilder->CreateBitCast(loadedVal.mValue, mBfIRBuilder->MapType(toType)), toType);
  13098. }
  13099. }
  13100. }
  13101. // Struct truncate
  13102. if ((typedVal.mType->IsStruct()) && (toType->IsStruct()))
  13103. {
  13104. auto fromStructTypeInstance = typedVal.mType->ToTypeInstance();
  13105. auto toStructTypeInstance = toType->ToTypeInstance();
  13106. if (TypeIsSubTypeOf(fromStructTypeInstance, toStructTypeInstance))
  13107. {
  13108. if (typedVal.IsSplat())
  13109. {
  13110. if ((!toStructTypeInstance->IsSplattable()) && (toStructTypeInstance->mInstSize != 0))
  13111. return Cast(srcNode, MakeAddressable(typedVal), toType, castFlags);
  13112. BF_ASSERT(toStructTypeInstance->IsSplattable() || (toStructTypeInstance->mInstSize == 0));
  13113. return BfTypedValue(typedVal.mValue, toStructTypeInstance, typedVal.IsThis() ? BfTypedValueKind_ThisSplatHead : BfTypedValueKind_SplatHead);
  13114. }
  13115. if (typedVal.IsAddr())
  13116. {
  13117. BfIRValue castedIRValue;
  13118. if (typedVal.mValue.IsFake())
  13119. castedIRValue = typedVal.mValue;
  13120. else
  13121. castedIRValue = mBfIRBuilder->CreateBitCast(typedVal.mValue, mBfIRBuilder->MapTypeInstPtr(toStructTypeInstance));
  13122. return BfTypedValue(castedIRValue, toType, typedVal.IsThis() ?
  13123. (typedVal.IsReadOnly() ? BfTypedValueKind_ReadOnlyThisAddr : BfTypedValueKind_ThisAddr) :
  13124. (typedVal.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr));
  13125. }
  13126. BfTypedValue curTypedVal = typedVal;
  13127. while (curTypedVal.mType != toStructTypeInstance)
  13128. {
  13129. mBfIRBuilder->PopulateType(curTypedVal.mType);
  13130. auto curTypeInstance = curTypedVal.mType->ToTypeInstance();
  13131. BfIRValue extractedValue;
  13132. if (toStructTypeInstance->IsValuelessType())
  13133. extractedValue = mBfIRBuilder->GetFakeVal();
  13134. else
  13135. extractedValue = mBfIRBuilder->CreateExtractValue(curTypedVal.mValue, 0);
  13136. curTypedVal = BfTypedValue(extractedValue, curTypeInstance->mBaseType, typedVal.IsThis() ?
  13137. (typedVal.IsReadOnly() ? BfTypedValueKind_ReadOnlyThisValue : BfTypedValueKind_ThisValue) :
  13138. BfTypedValueKind_Value);
  13139. }
  13140. return curTypedVal;
  13141. }
  13142. }
  13143. /*if ((explicitCast) && (toType->IsValuelessType()))
  13144. {
  13145. return BfTypedValue(mBfIRBuilder->GetFakeVal(), toType);
  13146. }*/
  13147. BfCastResultFlags castResultFlags = BfCastResultFlags_None;
  13148. auto castedValue = CastToValue(srcNode, typedVal, toType, castFlags, &castResultFlags);
  13149. if (!castedValue)
  13150. return BfTypedValue();
  13151. if ((castResultFlags & BfCastResultFlags_IsAddr) != 0)
  13152. {
  13153. if ((castResultFlags & BfCastResultFlags_IsTemp) != 0)
  13154. return BfTypedValue(castedValue, toType, BfTypedValueKind_TempAddr);
  13155. return BfTypedValue(castedValue, toType, BfTypedValueKind_Addr);
  13156. }
  13157. return BfTypedValue(castedValue, toType, BfTypedValueKind_Value);
  13158. }
  13159. BfPrimitiveType* BfModule::GetIntCoercibleType(BfType* type)
  13160. {
  13161. if (type->IsSizedArray())
  13162. {
  13163. auto sizedArray = (BfSizedArrayType*)type;
  13164. if ((sizedArray->mElementType->IsChar()) && (sizedArray->mElementType->mSize == 1))
  13165. {
  13166. auto primType = (BfPrimitiveType*)sizedArray->mElementType;
  13167. if (sizedArray->mElementCount == 1)
  13168. return GetPrimitiveType(BfTypeCode_UInt8);
  13169. if (sizedArray->mElementCount == 2)
  13170. return GetPrimitiveType(BfTypeCode_UInt16);
  13171. if (sizedArray->mElementCount == 4)
  13172. return GetPrimitiveType(BfTypeCode_UInt32);
  13173. if (sizedArray->mElementCount == 8)
  13174. return GetPrimitiveType(BfTypeCode_UInt64);
  13175. }
  13176. }
  13177. return NULL;
  13178. }
  13179. BfTypedValue BfModule::GetIntCoercible(const BfTypedValue& typedValue)
  13180. {
  13181. auto intType = GetIntCoercibleType(typedValue.mType);
  13182. if (intType == NULL)
  13183. return BfTypedValue();
  13184. if (typedValue.mValue.IsConst())
  13185. {
  13186. auto constant = mBfIRBuilder->GetConstant(typedValue.mValue);
  13187. if (constant->mConstType == BfConstType_Agg)
  13188. {
  13189. uint64 intVal = 0;
  13190. auto constantArray = (BfConstantAgg*)constant;
  13191. int memberIdx = 0;
  13192. for (int memberIdx = 0; memberIdx < (int)constantArray->mValues.size(); memberIdx++)
  13193. {
  13194. auto memberConstant = mBfIRBuilder->GetConstant(constantArray->mValues[memberIdx]);
  13195. if (memberConstant->mTypeCode == BfTypeCode_Char8)
  13196. {
  13197. intVal |= (uint64)(memberConstant->mUInt8) << (8 * memberIdx);
  13198. //intVal = (intVal << 8) | memberConstant->mUInt8;
  13199. }
  13200. }
  13201. return BfTypedValue(mBfIRBuilder->CreateConst(intType->mTypeDef->mTypeCode, intVal), intType);
  13202. }
  13203. }
  13204. auto convTypedValue = typedValue;
  13205. convTypedValue = MakeAddressable(convTypedValue);
  13206. auto intPtrType = CreatePointerType(intType);
  13207. auto addrVal = mBfIRBuilder->CreateBitCast(convTypedValue.mValue, mBfIRBuilder->MapType(intPtrType));
  13208. auto val = mBfIRBuilder->CreateLoad(addrVal);
  13209. return BfTypedValue(val, intType);
  13210. }
  13211. bool BfModule::TypeHasParentOrEquals(BfTypeDef* checkChildTypeDef, BfTypeDef* checkParentTypeDef)
  13212. {
  13213. BfTypeDef* checkType = checkChildTypeDef;
  13214. if (checkType->mNestDepth < checkParentTypeDef->mNestDepth)
  13215. return false;
  13216. while (checkType->mNestDepth > checkParentTypeDef->mNestDepth)
  13217. checkType = checkType->mOuterType;
  13218. if (checkType->GetDefinition() == checkParentTypeDef->GetDefinition())
  13219. return true;
  13220. if (checkType->mNameEx != checkParentTypeDef->mNameEx)
  13221. return false;
  13222. if (checkType->mIsPartial)
  13223. {
  13224. for (auto partial : checkParentTypeDef->mPartials)
  13225. if (partial == checkType)
  13226. return true;
  13227. }
  13228. return false;
  13229. }
  13230. BfTypeDef* BfModule::FindCommonOuterType(BfTypeDef* type, BfTypeDef* type2)
  13231. {
  13232. if ((type == NULL) || (type2 == NULL))
  13233. return NULL;
  13234. int curNestDepth = BF_MIN(type->mNestDepth, type2->mNestDepth);
  13235. while (type->mNestDepth > curNestDepth)
  13236. type = type->mOuterType;
  13237. while (type2->mNestDepth > curNestDepth)
  13238. type2 = type2->mOuterType;
  13239. while (curNestDepth >= 0)
  13240. {
  13241. if ((!type->mIsPartial) && (!type2->mIsPartial))
  13242. {
  13243. if (type->GetDefinition() == type2->GetDefinition())
  13244. return type;
  13245. }
  13246. else
  13247. {
  13248. if (type->mFullNameEx == type2->mFullNameEx)
  13249. return type;
  13250. }
  13251. type = type->mOuterType;
  13252. type2 = type2->mOuterType;
  13253. curNestDepth--;
  13254. }
  13255. return NULL;
  13256. }
  13257. bool BfModule::TypeIsSubTypeOf(BfTypeInstance* srcType, BfTypeInstance* wantType, bool checkAccessibility)
  13258. {
  13259. if ((srcType == NULL) || (wantType == NULL))
  13260. return false;
  13261. if (srcType == wantType)
  13262. return true;
  13263. if (srcType->mDefineState < BfTypeDefineState_HasInterfaces_Direct)
  13264. {
  13265. if (srcType->mDefineState == BfTypeDefineState_ResolvingBaseType)
  13266. {
  13267. auto typeState = mContext->mCurTypeState;
  13268. while (typeState != NULL)
  13269. {
  13270. if ((typeState->mType == srcType) && (typeState->mCurBaseType != NULL))
  13271. {
  13272. return TypeIsSubTypeOf(typeState->mCurBaseType, wantType, checkAccessibility);
  13273. }
  13274. typeState = typeState->mPrevState;
  13275. }
  13276. }
  13277. // Type is incomplete. We don't do the IsIncomplete check here because of re-entry
  13278. // While handling 'var' resolution, we don't want to force a PopulateType reentry
  13279. // but we do have enough information for TypeIsSubTypeOf
  13280. PopulateType(srcType, BfPopulateType_Interfaces_Direct);
  13281. }
  13282. if (wantType->IsInterface())
  13283. {
  13284. if (wantType->mDefineState < BfTypeDefineState_HasInterfaces_All)
  13285. PopulateType(srcType, BfPopulateType_Interfaces_All);
  13286. BfTypeDef* checkActiveTypeDef = NULL;
  13287. bool checkAccessibility = true;
  13288. if (IsInSpecializedSection())
  13289. {
  13290. // When we have a specialized section, the generic params may not be considered "included"
  13291. // in the module that contains the generic type definition. We rely on any casting errors
  13292. // to be thrown on the unspecialized type pass. We have a similar issue with injecting mixins.
  13293. checkAccessibility = false;
  13294. }
  13295. auto checkType = srcType;
  13296. while (checkType != NULL)
  13297. {
  13298. for (auto ifaceInst : checkType->mInterfaces)
  13299. {
  13300. if (ifaceInst.mInterfaceType == wantType)
  13301. {
  13302. if (checkAccessibility)
  13303. {
  13304. if (checkActiveTypeDef == NULL)
  13305. checkActiveTypeDef = GetActiveTypeDef(NULL, false, true);
  13306. // We need to be lenient when validating generic constraints
  13307. // Otherwise "T<A> where T : IB" declared in a lib won't be able to match a type B in a using project 'C',
  13308. // because this check will see the lib using 'C', which it won't consider visible
  13309. if ((checkActiveTypeDef != NULL) &&
  13310. ((mCurMethodInstance != NULL) && (mContext->mCurTypeState != NULL) && (mContext->mCurTypeState->mResolveKind != BfTypeState::ResolveKind_BuildingGenericParams)))
  13311. {
  13312. if ((!srcType->IsTypeMemberAccessible(ifaceInst.mDeclaringType, checkActiveTypeDef)) ||
  13313. (!srcType->IsTypeMemberIncluded(ifaceInst.mDeclaringType, checkActiveTypeDef, this)))
  13314. {
  13315. continue;
  13316. }
  13317. }
  13318. }
  13319. return true;
  13320. }
  13321. }
  13322. checkType = checkType->GetImplBaseType();
  13323. if ((checkType != NULL) && (checkType->mDefineState < BfTypeDefineState_CETypeInit))
  13324. {
  13325. // We check BfTypeDefineState_CETypeInit so we don't cause a populate loop during interface checking during CETypeInit
  13326. PopulateType(checkType, BfPopulateType_Interfaces_All);
  13327. }
  13328. }
  13329. if (srcType->IsTypedPrimitive())
  13330. {
  13331. BfType* underlyingType = srcType->GetUnderlyingType();
  13332. if (underlyingType->IsWrappableType())
  13333. {
  13334. BfTypeInstance* wrappedType = GetWrappedStructType(underlyingType);
  13335. if ((wrappedType != NULL) && (wrappedType != srcType))
  13336. return TypeIsSubTypeOf(wrappedType, wantType, checkAccessibility);
  13337. }
  13338. }
  13339. return false;
  13340. }
  13341. auto srcBaseType = srcType->mBaseType;
  13342. return TypeIsSubTypeOf(srcBaseType, wantType);
  13343. }
  13344. bool BfModule::TypeIsSubTypeOf(BfTypeInstance* srcType, BfTypeDef* wantType)
  13345. {
  13346. if ((srcType == NULL) || (wantType == NULL))
  13347. return false;
  13348. if (srcType->IsInstanceOf(wantType))
  13349. return true;
  13350. if (srcType->mDefineState < BfTypeDefineState_HasInterfaces_Direct)
  13351. {
  13352. if (srcType->mDefineState == BfTypeDefineState_ResolvingBaseType)
  13353. {
  13354. auto typeState = mContext->mCurTypeState;
  13355. while (typeState != NULL)
  13356. {
  13357. if ((typeState->mType == srcType) && (typeState->mCurBaseType != NULL))
  13358. {
  13359. return TypeIsSubTypeOf(typeState->mCurBaseType, wantType);
  13360. }
  13361. typeState = typeState->mPrevState;
  13362. }
  13363. }
  13364. // Type is incomplete. We don't do the IsIncomplete check here because of re-entry
  13365. // While handling 'var' resolution, we don't want to force a PopulateType reentry
  13366. // but we do have enough information for TypeIsSubTypeOf
  13367. PopulateType(srcType, BfPopulateType_Interfaces_Direct);
  13368. }
  13369. if (wantType->mTypeCode == BfTypeCode_Interface)
  13370. {
  13371. if (srcType->mDefineState < BfTypeDefineState_HasInterfaces_All)
  13372. PopulateType(srcType, BfPopulateType_Interfaces_All);
  13373. BfTypeDef* checkActiveTypeDef = NULL;
  13374. auto checkType = srcType;
  13375. while (checkType != NULL)
  13376. {
  13377. for (auto ifaceInst : checkType->mInterfaces)
  13378. {
  13379. if (ifaceInst.mInterfaceType->IsInstanceOf(wantType))
  13380. return true;
  13381. }
  13382. checkType = checkType->GetImplBaseType();
  13383. if ((checkType != NULL) && (checkType->mDefineState < BfTypeDefineState_HasInterfaces_All))
  13384. {
  13385. PopulateType(checkType, BfPopulateType_Interfaces_All);
  13386. }
  13387. }
  13388. if (srcType->IsTypedPrimitive())
  13389. {
  13390. BfType* underlyingType = srcType->GetUnderlyingType();
  13391. if (underlyingType->IsWrappableType())
  13392. {
  13393. BfTypeInstance* wrappedType = GetWrappedStructType(underlyingType);
  13394. if ((wrappedType != NULL) && (wrappedType != srcType))
  13395. return TypeIsSubTypeOf(wrappedType, wantType);
  13396. }
  13397. }
  13398. return false;
  13399. }
  13400. auto srcBaseType = srcType->mBaseType;
  13401. return TypeIsSubTypeOf(srcBaseType, wantType);
  13402. }
  13403. // Positive value means that toType encompasses fromType, negative value means toType is encompassed by formType
  13404. // INT_MAX means the types are not related
  13405. int BfModule::GetTypeDistance(BfType* fromType, BfType* toType)
  13406. {
  13407. if (fromType == toType)
  13408. return 0;
  13409. if (fromType->IsPrimitiveType())
  13410. {
  13411. if (!toType->IsPrimitiveType())
  13412. return INT_MAX;
  13413. auto fromPrimType = (BfPrimitiveType*)fromType;
  13414. auto toPrimType = (BfPrimitiveType*)toType;
  13415. if ((fromPrimType->IsIntegral()) && (toPrimType->IsIntegral()))
  13416. {
  13417. int fromBitSize = fromPrimType->mSize * 8;
  13418. if (fromPrimType->IsSigned())
  13419. fromBitSize--;
  13420. int toBitSize = toPrimType->mSize * 8;
  13421. if (toPrimType->IsSigned())
  13422. toBitSize--;
  13423. return fromBitSize - toBitSize;
  13424. }
  13425. if ((fromPrimType->IsFloat()) && (toPrimType->IsFloat()))
  13426. {
  13427. return (fromPrimType->mSize * 8) - (toPrimType->mSize * 8);
  13428. }
  13429. if (((fromPrimType->IsIntegral()) || (fromPrimType->IsFloat())) &&
  13430. ((toPrimType->IsIntegral()) || (toPrimType->IsFloat())))
  13431. {
  13432. int sizeDiff = (fromPrimType->mSize * 8) - (toPrimType->mSize * 8);
  13433. if (sizeDiff < 0)
  13434. sizeDiff--;
  13435. else
  13436. sizeDiff++;
  13437. return sizeDiff;
  13438. }
  13439. return INT_MAX;
  13440. }
  13441. auto fromTypeInstance = fromType->ToTypeInstance();
  13442. auto toTypeInstance = toType->ToTypeInstance();
  13443. if ((fromTypeInstance != NULL) != (toTypeInstance != NULL))
  13444. return INT_MAX; // Ever valid?
  13445. if ((fromTypeInstance != NULL) && (toTypeInstance != NULL))
  13446. {
  13447. if ((fromTypeInstance->IsNullable()) && (toTypeInstance->IsNullable()))
  13448. return GetTypeDistance(fromTypeInstance->GetUnderlyingType(), toTypeInstance->GetUnderlyingType());
  13449. int inheritDistance = toTypeInstance->mInheritDepth - fromTypeInstance->mInheritDepth;
  13450. auto mostSpecificInstance = (inheritDistance < 0) ? fromTypeInstance : toTypeInstance;
  13451. auto leastSpecificInstance = (inheritDistance < 0) ? toTypeInstance : fromTypeInstance;
  13452. while (mostSpecificInstance != NULL)
  13453. {
  13454. if (mostSpecificInstance == leastSpecificInstance)
  13455. return inheritDistance;
  13456. mostSpecificInstance = mostSpecificInstance->mBaseType;
  13457. }
  13458. }
  13459. return INT_MAX;
  13460. }
  13461. bool BfModule::IsTypeMoreSpecific(BfType* leftType, BfType* rightType)
  13462. {
  13463. if (leftType->IsGenericTypeInstance())
  13464. {
  13465. if (!rightType->IsGenericTypeInstance())
  13466. return true;
  13467. auto leftGenericType = (BfTypeInstance*)leftType;
  13468. auto rightGenericType = (BfTypeInstance*)rightType;
  13469. if (leftGenericType->mTypeDef != rightGenericType->mTypeDef)
  13470. return false;
  13471. bool isBetter = false;
  13472. bool isWorse = false;
  13473. for (int argIdx = 0; argIdx < (int)leftGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); argIdx++)
  13474. {
  13475. if (IsTypeMoreSpecific(leftGenericType->mGenericTypeInfo->mTypeGenericArguments[argIdx], rightGenericType->mGenericTypeInfo->mTypeGenericArguments[argIdx]))
  13476. isBetter = true;
  13477. if (IsTypeMoreSpecific(rightGenericType->mGenericTypeInfo->mTypeGenericArguments[argIdx], leftGenericType->mGenericTypeInfo->mTypeGenericArguments[argIdx]))
  13478. isWorse = true;
  13479. }
  13480. return (isBetter) && (!isWorse);
  13481. }
  13482. return false;
  13483. }
  13484. StringT<128> BfModule::TypeToString(BfType* resolvedType, Array<String>* genericMethodParamNameOverrides)
  13485. {
  13486. BfTypeNameFlags flags = BfTypeNameFlags_None;
  13487. if ((mCurTypeInstance == NULL) || (!mCurTypeInstance->IsUnspecializedTypeVariation()))
  13488. flags = BfTypeNameFlag_ResolveGenericParamNames;
  13489. StringT<128> str;
  13490. DoTypeToString(str, resolvedType, flags, genericMethodParamNameOverrides);
  13491. return str;
  13492. }
  13493. StringT<128> BfModule::TypeToString(BfType* resolvedType, BfTypeNameFlags typeNameFlags, Array<String>* genericMethodParamNameOverrides)
  13494. {
  13495. StringT<128> str;
  13496. DoTypeToString(str, resolvedType, typeNameFlags, genericMethodParamNameOverrides);
  13497. return str;
  13498. }
  13499. void BfModule::DataToString(StringImpl& str, void* ptr, BfType* type)
  13500. {
  13501. if (type->IsPrimitiveType())
  13502. {
  13503. BfPrimitiveType* primType = (BfPrimitiveType*)type;
  13504. BfTypeCode typeCode = primType->GetTypeCode();
  13505. if (typeCode == BfTypeCode_IntPtr)
  13506. {
  13507. if (mSystem->mPtrSize == 8)
  13508. typeCode = BfTypeCode_Int64;
  13509. else
  13510. typeCode = BfTypeCode_Int32;
  13511. }
  13512. else if (typeCode == BfTypeCode_UIntPtr)
  13513. {
  13514. if (mSystem->mPtrSize == 8)
  13515. typeCode = BfTypeCode_UInt64;
  13516. else
  13517. typeCode = BfTypeCode_UInt32;
  13518. }
  13519. switch (typeCode)
  13520. {
  13521. case BfTypeCode_Boolean:
  13522. if (*(uint8*)ptr == 0)
  13523. str += "false";
  13524. else if (*(uint8*)ptr == 1)
  13525. str += "true";
  13526. else
  13527. str += StrFormat("%d", *(uint8*)ptr);
  13528. break;
  13529. case BfTypeCode_Int8:
  13530. str += StrFormat("%d", *(int8*)ptr);
  13531. break;
  13532. case BfTypeCode_UInt8:
  13533. str += StrFormat("%d", *(uint8*)ptr);
  13534. break;
  13535. case BfTypeCode_Int16:
  13536. str += StrFormat("%d", *(int16*)ptr);
  13537. break;
  13538. case BfTypeCode_UInt16:
  13539. str += StrFormat("%d", *(uint16*)ptr);
  13540. break;
  13541. case BfTypeCode_Int32:
  13542. str += StrFormat("%d", *(int32*)ptr);
  13543. break;
  13544. case BfTypeCode_Char8:
  13545. case BfTypeCode_Char16:
  13546. case BfTypeCode_Char32:
  13547. {
  13548. uint32 c = 0;
  13549. if (typeCode == BfTypeCode_Char8)
  13550. c = *(uint8*)ptr;
  13551. else if (typeCode == BfTypeCode_Char16)
  13552. c = *(uint16*)ptr;
  13553. else if (typeCode == BfTypeCode_Char32)
  13554. c = *(uint32*)ptr;
  13555. if ((c >= 32) && (c <= 0x7E))
  13556. str += StrFormat("'%c'", (char)c);
  13557. else if (c <= 0xFF)
  13558. str += StrFormat("'\\x%2X'", c);
  13559. else
  13560. str += StrFormat("'\\u{%X}'", c);
  13561. }
  13562. break;
  13563. case BfTypeCode_UInt32:
  13564. str += StrFormat("%lu", *(uint32*)ptr);
  13565. break;
  13566. case BfTypeCode_Int64:
  13567. str += StrFormat("%lld", *(int64*)ptr);
  13568. break;
  13569. case BfTypeCode_UInt64:
  13570. str += StrFormat("%llu", *(uint64*)ptr);
  13571. break;
  13572. case BfTypeCode_Float:
  13573. {
  13574. char cstr[64];
  13575. ExactMinimalFloatToStr(*(float*)ptr, cstr);
  13576. str += cstr;
  13577. if (strchr(cstr, '.') == NULL)
  13578. str += ".0f";
  13579. else
  13580. str += "f";
  13581. }
  13582. break;
  13583. case BfTypeCode_Double:
  13584. {
  13585. char cstr[64];
  13586. ExactMinimalDoubleToStr(*(double*)ptr, cstr);
  13587. str += cstr;
  13588. if (strchr(cstr, '.') == NULL)
  13589. str += ".0";
  13590. }
  13591. break;
  13592. case BfTypeCode_StringId:
  13593. {
  13594. int stringId = *(int32*)ptr;
  13595. auto stringPoolEntry = mContext->mStringObjectIdMap[stringId];
  13596. str += '"';
  13597. str += SlashString(stringPoolEntry.mString, false, false, true);
  13598. str += '"';
  13599. }
  13600. break;
  13601. case BfTypeCode_Let:
  13602. str += "?";
  13603. break;
  13604. default: break;
  13605. }
  13606. }
  13607. else
  13608. {
  13609. if (type->IsInstanceOf(mCompiler->mClosedRangeTypeDef))
  13610. {
  13611. if (type->mSize == 16)
  13612. str += StrFormat("%d...%d", ((int64*)ptr)[0], ((int64*)ptr)[1]);
  13613. else
  13614. str += StrFormat("%d...%d", ((int32*)ptr)[0], ((int32*)ptr)[1]);
  13615. return;
  13616. }
  13617. if (type->IsInstanceOf(mCompiler->mRangeTypeDef))
  13618. {
  13619. if (type->mSize == 16)
  13620. str += StrFormat("%d..<%d", ((int64*)ptr)[0], ((int64*)ptr)[1]);
  13621. else
  13622. str += StrFormat("%d..<%d", ((int32*)ptr)[0], ((int32*)ptr)[1]);
  13623. return;
  13624. }
  13625. BfTypeInstance* typeInstance = type->ToTypeInstance();
  13626. if (typeInstance != NULL)
  13627. {
  13628. str += "(";
  13629. DoPopulateType(typeInstance);
  13630. int showIdx = 0;
  13631. if ((typeInstance->mBaseType != NULL) && (!typeInstance->mBaseType->IsInstanceOf(mCompiler->mValueTypeTypeDef)))
  13632. {
  13633. DataToString(str, ptr, typeInstance->mBaseType);
  13634. showIdx++;
  13635. }
  13636. for (auto& fieldInstance : typeInstance->mFieldInstances)
  13637. {
  13638. if (fieldInstance.mDataOffset >= 0)
  13639. {
  13640. if (showIdx > 0)
  13641. str += ", ";
  13642. DataToString(str, (uint8*)ptr + fieldInstance.mDataOffset, fieldInstance.mResolvedType);
  13643. showIdx++;
  13644. }
  13645. }
  13646. str += ")";
  13647. }
  13648. else if (type->IsPointer())
  13649. str += "null";
  13650. else
  13651. {
  13652. str += "uint8[](";
  13653. for (int i = 0; i < type->mSize; i++)
  13654. {
  13655. if (i > 0)
  13656. str += ", ";
  13657. str += StrFormat("%d", ((uint8_t*)ptr)[i]);
  13658. }
  13659. str += ")";
  13660. }
  13661. }
  13662. }
  13663. void BfModule::VariantToString(StringImpl& str, const BfVariant& variant, BfType* type)
  13664. {
  13665. switch (variant.mTypeCode)
  13666. {
  13667. case BfTypeCode_Boolean:
  13668. if (variant.mUInt64 == 0)
  13669. str += "false";
  13670. else if (variant.mUInt64 == 1)
  13671. str += "true";
  13672. else
  13673. str += StrFormat("%lld", variant.mInt64);
  13674. break;
  13675. case BfTypeCode_Int8:
  13676. case BfTypeCode_UInt8:
  13677. case BfTypeCode_Int16:
  13678. case BfTypeCode_UInt16:
  13679. case BfTypeCode_Int32:
  13680. str += StrFormat("%d", variant.mInt32);
  13681. break;
  13682. case BfTypeCode_Char8:
  13683. case BfTypeCode_Char16:
  13684. case BfTypeCode_Char32:
  13685. if ((variant.mUInt32 >= 32) && (variant.mUInt32 <= 0x7E))
  13686. str += StrFormat("'%c'", (char)variant.mUInt32);
  13687. else if (variant.mUInt32 <= 0xFF)
  13688. str += StrFormat("'\\x%2X'", variant.mUInt32);
  13689. else
  13690. str += StrFormat("'\\u{%X}'", variant.mUInt32);
  13691. break;
  13692. case BfTypeCode_UInt32:
  13693. str += StrFormat("%lu", variant.mUInt32);
  13694. break;
  13695. case BfTypeCode_Int64:
  13696. str += StrFormat("%lld", variant.mInt64);
  13697. break;
  13698. case BfTypeCode_UInt64:
  13699. str += StrFormat("%llu", variant.mInt64);
  13700. break;
  13701. case BfTypeCode_Float:
  13702. {
  13703. char cstr[64];
  13704. ExactMinimalFloatToStr(variant.mSingle, cstr);
  13705. str += cstr;
  13706. if (strchr(cstr, '.') == NULL)
  13707. str += ".0f";
  13708. else
  13709. str += "f";
  13710. }
  13711. break;
  13712. case BfTypeCode_Double:
  13713. {
  13714. char cstr[64];
  13715. ExactMinimalDoubleToStr(variant.mDouble, cstr);
  13716. str += cstr;
  13717. if (strchr(cstr, '.') == NULL)
  13718. str += ".0";
  13719. }
  13720. break;
  13721. case BfTypeCode_StringId:
  13722. {
  13723. int stringId = variant.mInt32;
  13724. auto stringPoolEntry = mContext->mStringObjectIdMap[stringId];
  13725. str += '"';
  13726. str += SlashString(stringPoolEntry.mString, false, false, true);
  13727. str += '"';
  13728. }
  13729. break;
  13730. case BfTypeCode_Let:
  13731. str += "?";
  13732. break;
  13733. case BfTypeCode_Struct:
  13734. {
  13735. BfVariant::StructData* structData = (BfVariant::StructData*)variant.mPtr;
  13736. if (type == NULL)
  13737. {
  13738. str += "uint8[](";
  13739. for (int i = 0; i < structData->mSize; i++)
  13740. {
  13741. if (i > 0)
  13742. str += ", ";
  13743. str += StrFormat("%d", structData->mData[i]);
  13744. }
  13745. str += ")";
  13746. break;
  13747. }
  13748. DataToString(str, structData->mData, type);
  13749. }
  13750. break;
  13751. default: break;
  13752. }
  13753. }
  13754. void BfModule::DoTypeToString(StringImpl& str, BfType* resolvedType, BfTypeNameFlags typeNameFlags, Array<String>* genericMethodNameOverrides)
  13755. {
  13756. BP_ZONE("BfModule::DoTypeToString");
  13757. if ((typeNameFlags & BfTypeNameFlag_AddProjectName) != 0)
  13758. {
  13759. BfProject* defProject = NULL;
  13760. auto typeInst = resolvedType->ToTypeInstance();
  13761. if (typeInst != NULL)
  13762. {
  13763. defProject = typeInst->mTypeDef->mProject;
  13764. str += defProject->mName;
  13765. str += ":";
  13766. }
  13767. SizedArray<BfProject*, 4> projectList;
  13768. BfTypeUtils::GetProjectList(resolvedType, &projectList, 0);
  13769. if (!projectList.IsEmpty())
  13770. {
  13771. if (defProject != projectList[0])
  13772. {
  13773. str += projectList[0]->mName;
  13774. str += ":";
  13775. }
  13776. }
  13777. typeNameFlags = (BfTypeNameFlags)(typeNameFlags & ~BfTypeNameFlag_AddProjectName);
  13778. }
  13779. // This is clearly wrong. If we pass in @T0 from a generic type, this would immediately disable the ability to get its name
  13780. /*if (resolvedType->IsUnspecializedType())
  13781. typeNameFlags = (BfTypeNameFlags)(typeNameFlags & ~BfTypeNameFlag_ResolveGenericParamNames);*/
  13782. if (resolvedType->IsBoxed())
  13783. {
  13784. auto boxedType = (BfBoxedType*)resolvedType;
  13785. str += "boxed ";
  13786. DoTypeToString(str, boxedType->mElementType, typeNameFlags, genericMethodNameOverrides);
  13787. if (boxedType->mBoxedFlags == BfBoxedType::BoxedFlags_StructPtr)
  13788. str += "*";
  13789. return;
  13790. }
  13791. else if ((resolvedType->IsArray()) && ((typeNameFlags & BfTypeNameFlag_UseArrayImplType) == 0))
  13792. {
  13793. auto arrayType = (BfArrayType*)resolvedType;
  13794. DoTypeToString(str, arrayType->mGenericTypeInfo->mTypeGenericArguments[0], typeNameFlags, genericMethodNameOverrides);
  13795. str += "[";
  13796. for (int i = 1; i < arrayType->mDimensions; i++)
  13797. str += ",";
  13798. str += "]";
  13799. return;
  13800. }
  13801. else if (resolvedType->IsNullable())
  13802. {
  13803. auto genericType = (BfTypeInstance*)resolvedType;
  13804. auto elementType = genericType->mGenericTypeInfo->mTypeGenericArguments[0];
  13805. DoTypeToString(str, elementType, typeNameFlags, genericMethodNameOverrides);
  13806. str += "?";
  13807. return;
  13808. }
  13809. else if (resolvedType->IsTuple())
  13810. {
  13811. BfTypeInstance* tupleType = (BfTypeInstance*)resolvedType;
  13812. str += "(";
  13813. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  13814. {
  13815. if (fieldIdx > 0)
  13816. str += ", ";
  13817. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  13818. BfFieldDef* fieldDef = fieldInstance->GetFieldDef();
  13819. BfTypeNameFlags innerFlags = (BfTypeNameFlags)(typeNameFlags & ~(BfTypeNameFlag_OmitNamespace | BfTypeNameFlag_OmitOuterType | BfTypeNameFlag_ExtendedInfo));
  13820. DoTypeToString(str, fieldInstance->GetResolvedType(), innerFlags, genericMethodNameOverrides);
  13821. char c = fieldDef->mName[0];
  13822. if ((c < '0') || (c > '9'))
  13823. {
  13824. str += " ";
  13825. str += fieldDef->mName;
  13826. }
  13827. }
  13828. str += ")";
  13829. return;
  13830. }
  13831. else if ((resolvedType->IsOnDemand()) && (resolvedType->IsEnum()))
  13832. {
  13833. auto typeInst = resolvedType->ToTypeInstance();
  13834. str += "tag ";
  13835. str += typeInst->mTypeDef->mFields[0]->mName;
  13836. return;
  13837. }
  13838. else if (resolvedType->IsDelegateFromTypeRef() || resolvedType->IsFunctionFromTypeRef())
  13839. {
  13840. SetAndRestoreValue<BfTypeInstance*> prevTypeInstance(mCurTypeInstance);
  13841. auto delegateType = (BfTypeInstance*)resolvedType;
  13842. auto delegateInfo = resolvedType->GetDelegateInfo();
  13843. if (mCurTypeInstance == delegateType)
  13844. {
  13845. // Don't try to use ourselves for generic param resolution. This should only happen for debug printings from
  13846. // within InitType and such, not actual user-facing display
  13847. mCurTypeInstance = NULL;
  13848. }
  13849. auto methodDef = delegateType->mTypeDef->mMethods[0];
  13850. switch (methodDef->mCallingConvention)
  13851. {
  13852. case BfCallingConvention_Stdcall:
  13853. str += "[StdCall] ";
  13854. break;
  13855. case BfCallingConvention_Fastcall:
  13856. str += "[FastCall] ";
  13857. break;
  13858. default:
  13859. break;
  13860. }
  13861. if (resolvedType->IsDelegateFromTypeRef())
  13862. str += "delegate ";
  13863. else
  13864. str += "function ";
  13865. if (delegateInfo->mCallingConvention != BfCallingConvention_Unspecified)
  13866. {
  13867. str += "[CallingConvention(";
  13868. switch (delegateInfo->mCallingConvention)
  13869. {
  13870. case BfCallingConvention_Cdecl:
  13871. str += ".Cdecl";
  13872. break;
  13873. case BfCallingConvention_Stdcall:
  13874. str += ".Stdcall";
  13875. break;
  13876. case BfCallingConvention_Fastcall:
  13877. str += ".Fastcall";
  13878. break;
  13879. }
  13880. str += ")] ";
  13881. }
  13882. DoTypeToString(str, delegateInfo->mReturnType, typeNameFlags, genericMethodNameOverrides);
  13883. str += "(";
  13884. bool isFirstParam = true;//
  13885. for (int paramIdx = 0; paramIdx < methodDef->mParams.size(); paramIdx++)
  13886. {
  13887. if (!isFirstParam)
  13888. str += ", ";
  13889. auto paramDef = methodDef->mParams[paramIdx];
  13890. BfTypeNameFlags innerFlags = (BfTypeNameFlags)(typeNameFlags & ~(BfTypeNameFlag_OmitNamespace | BfTypeNameFlag_OmitOuterType | BfTypeNameFlag_ExtendedInfo));
  13891. if (paramDef->mParamKind == BfParamKind_VarArgs)
  13892. {
  13893. str += "...";
  13894. continue;
  13895. }
  13896. auto paramType = delegateInfo->mParams[paramIdx];
  13897. if ((paramIdx == 0) && (delegateInfo->mHasExplicitThis))
  13898. {
  13899. if ((methodDef->mIsMutating) && (paramType->IsValueType()))
  13900. str += "mut ";
  13901. }
  13902. DoTypeToString(str, paramType, innerFlags, genericMethodNameOverrides);
  13903. if (!paramDef->mName.IsEmpty())
  13904. {
  13905. str += " ";
  13906. str += paramDef->mName;
  13907. }
  13908. isFirstParam = false;
  13909. }
  13910. str += ")";
  13911. return;
  13912. }
  13913. else if (resolvedType->IsMethodRef())
  13914. {
  13915. auto methodRefType = (BfMethodRefType*)resolvedType;
  13916. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  13917. if (methodRefType->IsDeleting())
  13918. {
  13919. str += "DELETED METHODREF";
  13920. return;
  13921. }
  13922. if (methodInstance == NULL)
  13923. {
  13924. str += "method reference NULL";
  13925. return;
  13926. }
  13927. str += "method reference ";
  13928. str += MethodToString(methodInstance, BfMethodNameFlag_NoAst);
  13929. return;
  13930. }
  13931. else if (resolvedType->IsTypeInstance())
  13932. {
  13933. BfTypeInstance* typeInstance = (BfTypeInstance*)resolvedType;
  13934. if ((typeNameFlags & BfTypeNameFlag_ExtendedInfo) != 0)
  13935. {
  13936. if (typeInstance->mTypeDef->IsGlobalsContainer())
  13937. str += "static ";
  13938. else if (typeInstance->mTypeDef->mIsDelegate)
  13939. str += "delegate ";
  13940. else if (typeInstance->mTypeDef->mIsFunction)
  13941. str += "function ";
  13942. else if (typeInstance->mTypeDef->mTypeCode == BfTypeCode_Object)
  13943. str += "class ";
  13944. else if (typeInstance->mTypeDef->mTypeCode == BfTypeCode_Enum)
  13945. str += "enum ";
  13946. else if (typeInstance->mTypeDef->mTypeCode == BfTypeCode_Struct)
  13947. str += "struct ";
  13948. else if (typeInstance->mTypeDef->mTypeCode == BfTypeCode_TypeAlias)
  13949. str += "typealias ";
  13950. }
  13951. bool omitNamespace = (typeNameFlags & BfTypeNameFlag_OmitNamespace) != 0;
  13952. if ((typeNameFlags & BfTypeNameFlag_ReduceName) != 0)
  13953. {
  13954. for (auto& checkNamespace : mCurTypeInstance->mTypeDef->mNamespaceSearch)
  13955. {
  13956. if (checkNamespace == typeInstance->mTypeDef->mNamespace)
  13957. omitNamespace = true;
  13958. }
  13959. }
  13960. if ((!typeInstance->mTypeDef->mNamespace.IsEmpty()) && (!omitNamespace))
  13961. {
  13962. if (!typeInstance->mTypeDef->mNamespace.IsEmpty())
  13963. {
  13964. typeInstance->mTypeDef->mNamespace.ToString(str);
  13965. if (!typeInstance->mTypeDef->IsGlobalsContainer())
  13966. str += '.';
  13967. }
  13968. }
  13969. SizedArray<BfTypeDef*, 8> typeDefStack;
  13970. BfTypeDef* endTypeDef = NULL;
  13971. if (((typeNameFlags & BfTypeNameFlag_ReduceName) != 0) && (mCurTypeInstance != NULL))
  13972. {
  13973. auto checkTypeInst = typeInstance;
  13974. auto outerTypeInst = GetOuterType(checkTypeInst);
  13975. if (outerTypeInst != NULL)
  13976. {
  13977. checkTypeInst = outerTypeInst;
  13978. auto checkTypeDef = checkTypeInst->mTypeDef;
  13979. auto checkCurTypeInst = mCurTypeInstance; // Only used for ReduceName
  13980. BfTypeDef* checkCurTypeDef = NULL;
  13981. if (checkCurTypeInst != NULL)
  13982. checkCurTypeDef = checkCurTypeInst->mTypeDef;
  13983. while (checkCurTypeDef->mNestDepth > checkTypeDef->mNestDepth)
  13984. {
  13985. checkCurTypeInst = GetOuterType(checkCurTypeInst);
  13986. checkCurTypeDef = checkCurTypeInst->mTypeDef;
  13987. }
  13988. while (checkTypeDef != NULL)
  13989. {
  13990. if (TypeIsSubTypeOf(checkCurTypeInst, checkTypeInst))
  13991. {
  13992. endTypeDef = checkTypeDef;
  13993. break;
  13994. }
  13995. checkCurTypeInst = GetOuterType(checkCurTypeInst);
  13996. if (checkCurTypeInst == NULL)
  13997. break;
  13998. checkCurTypeDef = checkCurTypeInst->mTypeDef;
  13999. checkTypeInst = GetOuterType(checkTypeInst);
  14000. if (checkTypeInst == NULL)
  14001. break;
  14002. checkTypeDef = checkTypeInst->mTypeDef;
  14003. }
  14004. }
  14005. }
  14006. BfTypeDef* checkTypeDef = typeInstance->mTypeDef;
  14007. while (checkTypeDef != NULL)
  14008. {
  14009. typeDefStack.Add(checkTypeDef);
  14010. checkTypeDef = checkTypeDef->mOuterType;
  14011. if ((typeNameFlags & BfTypeNameFlag_OmitOuterType) != 0)
  14012. break;
  14013. if (checkTypeDef == endTypeDef)
  14014. break;
  14015. }
  14016. while (!typeDefStack.IsEmpty())
  14017. {
  14018. BfTypeDef* checkTypeDef = typeDefStack.back();
  14019. int depth = (int)typeDefStack.size() - 1;
  14020. typeDefStack.pop_back();
  14021. if (checkTypeDef->IsGlobalsContainer())
  14022. {
  14023. if ((typeNameFlags & BfTypeNameFlag_AddGlobalContainerName) != 0)
  14024. {
  14025. str += "G$";
  14026. str += checkTypeDef->mProject->mName;
  14027. }
  14028. }
  14029. else
  14030. {
  14031. checkTypeDef->mName->ToString(str);
  14032. if (!checkTypeDef->mGenericParamDefs.IsEmpty())
  14033. {
  14034. for (int ofs = 0; ofs < 3; ofs++)
  14035. {
  14036. int checkIdx = (int)str.length() - 1 - ofs;
  14037. if (checkIdx < 0)
  14038. break;
  14039. if (str[checkIdx] == '`')
  14040. {
  14041. str.RemoveToEnd(checkIdx);
  14042. break;
  14043. }
  14044. }
  14045. }
  14046. if (((typeNameFlags & BfTypeNameFlag_DisambiguateDups) != 0) && (checkTypeDef->mDupDetectedRevision != -1))
  14047. {
  14048. str += StrFormat("_%p", checkTypeDef);
  14049. }
  14050. }
  14051. int prevGenericParamCount = 0;
  14052. if (checkTypeDef->mOuterType != NULL)
  14053. {
  14054. prevGenericParamCount = (int)checkTypeDef->mOuterType->mGenericParamDefs.size();
  14055. }
  14056. if (resolvedType->IsGenericTypeInstance())
  14057. {
  14058. auto genericTypeInst = (BfTypeInstance*)resolvedType;
  14059. if (prevGenericParamCount != (int)checkTypeDef->mGenericParamDefs.size())
  14060. {
  14061. str += '<';
  14062. for (int i = prevGenericParamCount; i < (int)checkTypeDef->mGenericParamDefs.size(); i++)
  14063. {
  14064. BfType* typeGenericArg = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[i];
  14065. if (typeGenericArg->IsGenericParam())
  14066. {
  14067. if ((typeNameFlags & BfTypeNameFlag_ResolveGenericParamNames) == 0)
  14068. {
  14069. // We don't want the param names, just the commas (this is an unspecialized type reference)
  14070. if (i > prevGenericParamCount)
  14071. str += ',';
  14072. if ((typeNameFlags & BfTypeNameFlag_UseUnspecializedGenericParamNames) != 0)
  14073. {
  14074. str += checkTypeDef->mGenericParamDefs[i]->mName;
  14075. }
  14076. continue;
  14077. }
  14078. }
  14079. if (i > prevGenericParamCount)
  14080. str += ", ";
  14081. DoTypeToString(str, typeGenericArg, (BfTypeNameFlags)((typeNameFlags | BfTypeNameFlag_ShortConst) & ~(BfTypeNameFlag_OmitNamespace | BfTypeNameFlag_OmitOuterType | BfTypeNameFlag_ExtendedInfo)), genericMethodNameOverrides);
  14082. }
  14083. str += '>';
  14084. }
  14085. }
  14086. if (depth > 0)
  14087. str += '.';
  14088. };
  14089. if (typeInstance->IsTypeAlias())
  14090. {
  14091. if ((typeNameFlags & BfTypeNameFlag_ExtendedInfo) != 0)
  14092. {
  14093. auto underlyingType = typeInstance->GetUnderlyingType();
  14094. if (underlyingType != NULL)
  14095. {
  14096. str += " = ";
  14097. DoTypeToString(str, underlyingType, (BfTypeNameFlags)(typeNameFlags & ~(BfTypeNameFlag_OmitNamespace | BfTypeNameFlag_OmitOuterType | BfTypeNameFlag_ExtendedInfo)));
  14098. }
  14099. }
  14100. }
  14101. return;
  14102. }
  14103. else if (resolvedType->IsPrimitiveType())
  14104. {
  14105. auto primitiveType = (BfPrimitiveType*)resolvedType;
  14106. if (!primitiveType->mTypeDef->mNamespace.IsEmpty())
  14107. {
  14108. primitiveType->mTypeDef->mNamespace.ToString(str);
  14109. str += '.';
  14110. primitiveType->mTypeDef->mName->ToString(str);
  14111. return;
  14112. }
  14113. else
  14114. {
  14115. primitiveType->mTypeDef->mName->ToString(str);
  14116. return;
  14117. }
  14118. }
  14119. else if (resolvedType->IsPointer())
  14120. {
  14121. auto pointerType = (BfPointerType*)resolvedType;
  14122. DoTypeToString(str, pointerType->mElementType, typeNameFlags, genericMethodNameOverrides);
  14123. str += '*';
  14124. return;
  14125. }
  14126. else if (resolvedType->IsGenericParam())
  14127. {
  14128. bool doResolveGenericParams = (typeNameFlags & BfTypeNameFlag_ResolveGenericParamNames) != 0;
  14129. if ((mCurTypeInstance != NULL) && (mCurTypeInstance->IsUnspecializedTypeVariation()))
  14130. doResolveGenericParams = false;
  14131. auto genericParam = (BfGenericParamType*)resolvedType;
  14132. if (genericParam->mGenericParamKind == BfGenericParamKind_Method)
  14133. {
  14134. if ((mCurMethodInstance != NULL) && (mCurMethodInstance->mIsUnspecializedVariation))
  14135. doResolveGenericParams = false;
  14136. }
  14137. if (!doResolveGenericParams)
  14138. {
  14139. if (genericParam->mGenericParamKind == BfGenericParamKind_Method)
  14140. {
  14141. if (genericMethodNameOverrides != NULL)
  14142. {
  14143. BF_ASSERT(genericParam->mGenericParamIdx < genericMethodNameOverrides->mSize);
  14144. if (genericParam->mGenericParamIdx < genericMethodNameOverrides->mSize)
  14145. {
  14146. str += (*genericMethodNameOverrides)[genericParam->mGenericParamIdx];
  14147. return;
  14148. }
  14149. }
  14150. str += StrFormat("@M%d", genericParam->mGenericParamIdx);
  14151. return;
  14152. }
  14153. str += StrFormat("@T%d", genericParam->mGenericParamIdx);
  14154. return;
  14155. }
  14156. if ((genericParam->mGenericParamKind == BfGenericParamKind_Type) && (mCurTypeInstance == NULL))
  14157. {
  14158. str += StrFormat("@T%d", genericParam->mGenericParamIdx);
  14159. return;
  14160. }
  14161. if (genericParam->mGenericParamKind == BfGenericParamKind_Method)
  14162. {
  14163. if (genericMethodNameOverrides != NULL)
  14164. {
  14165. str += (*genericMethodNameOverrides)[genericParam->mGenericParamIdx];
  14166. return;
  14167. }
  14168. if (mCurMethodInstance == NULL)
  14169. {
  14170. str += StrFormat("@M%d", genericParam->mGenericParamIdx);
  14171. return;
  14172. }
  14173. }
  14174. if (genericParam->mGenericParamKind == BfGenericParamKind_Type)
  14175. {
  14176. auto curTypeInstance = mCurTypeInstance;
  14177. if (mCurMethodInstance != NULL)
  14178. curTypeInstance = mCurMethodInstance->mMethodInstanceGroup->mOwner;
  14179. if ((curTypeInstance == NULL) || (!curTypeInstance->IsGenericTypeInstance()))
  14180. {
  14181. str += StrFormat("@T%d", genericParam->mGenericParamIdx);
  14182. return;
  14183. }
  14184. }
  14185. auto genericParamInstance = GetGenericParamInstance(genericParam, false, BfFailHandleKind_Soft);
  14186. if (genericParamInstance == NULL)
  14187. {
  14188. str += StrFormat("@M%d", genericParam->mGenericParamIdx);
  14189. return;
  14190. }
  14191. auto genericParamDef = genericParamInstance->GetGenericParamDef();
  14192. if (genericParamDef != NULL)
  14193. str += genericParamInstance->GetGenericParamDef()->mName;
  14194. else
  14195. str += "external generic " + TypeToString(genericParamInstance->mExternType, typeNameFlags, genericMethodNameOverrides);
  14196. return;
  14197. }
  14198. else if (resolvedType->IsRef())
  14199. {
  14200. auto refType = (BfRefType*)resolvedType;
  14201. if (refType->mRefKind == BfRefType::RefKind_Ref)
  14202. {
  14203. str += "ref ";
  14204. DoTypeToString(str, refType->mElementType, typeNameFlags, genericMethodNameOverrides);
  14205. return;
  14206. }
  14207. else if (refType->mRefKind == BfRefType::RefKind_In)
  14208. {
  14209. str += "in ";
  14210. DoTypeToString(str, refType->mElementType, typeNameFlags, genericMethodNameOverrides);
  14211. return;
  14212. }
  14213. else if (refType->mRefKind == BfRefType::RefKind_Out)
  14214. {
  14215. str += "out ";
  14216. DoTypeToString(str, refType->mElementType, typeNameFlags, genericMethodNameOverrides);
  14217. return;
  14218. }
  14219. else
  14220. {
  14221. str += "mut ";
  14222. DoTypeToString(str, refType->mElementType, typeNameFlags, genericMethodNameOverrides);
  14223. return;
  14224. }
  14225. }
  14226. else if (resolvedType->IsModifiedTypeType())
  14227. {
  14228. auto retTypeType = (BfModifiedTypeType*)resolvedType;
  14229. str += BfTokenToString(retTypeType->mModifiedKind);
  14230. str += "(";
  14231. DoTypeToString(str, retTypeType->mElementType, typeNameFlags, genericMethodNameOverrides);
  14232. str += ")";
  14233. return;
  14234. }
  14235. else if (resolvedType->IsConcreteInterfaceType())
  14236. {
  14237. auto concreteTypeType = (BfConcreteInterfaceType*)resolvedType;
  14238. str += "concrete ";
  14239. DoTypeToString(str, concreteTypeType->mInterface, typeNameFlags, genericMethodNameOverrides);
  14240. return;
  14241. }
  14242. else if (resolvedType->IsUnknownSizedArrayType())
  14243. {
  14244. auto arrayType = (BfUnknownSizedArrayType*)resolvedType;
  14245. DoTypeToString(str, arrayType->mElementType, typeNameFlags, genericMethodNameOverrides);
  14246. str += "[";
  14247. DoTypeToString(str, arrayType->mElementCountSource, typeNameFlags, genericMethodNameOverrides);
  14248. str += "]";
  14249. return;
  14250. }
  14251. else if (resolvedType->IsSizedArray())
  14252. {
  14253. SizedArray<intptr, 4> sizes;
  14254. auto checkType = resolvedType;
  14255. while (true)
  14256. {
  14257. if (checkType->IsSizedArray())
  14258. {
  14259. auto arrayType = (BfSizedArrayType*)checkType;
  14260. sizes.Add(arrayType->mElementCount);
  14261. checkType = arrayType->mElementType;
  14262. continue;
  14263. }
  14264. DoTypeToString(str, checkType, typeNameFlags, genericMethodNameOverrides);
  14265. break;
  14266. }
  14267. for (int i = 0; i < (int)sizes.mSize; i++)
  14268. {
  14269. if (sizes[i] == -1)
  14270. str += "[?]";
  14271. else
  14272. str += StrFormat("[%d]", sizes[i]);
  14273. }
  14274. return;
  14275. }
  14276. else if (resolvedType->IsConstExprValue())
  14277. {
  14278. auto constExprValueType = (BfConstExprValueType*)resolvedType;
  14279. if ((typeNameFlags & BfTypeNameFlag_ShortConst) == 0)
  14280. {
  14281. str += "const ";
  14282. if ((!constExprValueType->mType->IsInstanceOf(mCompiler->mRangeTypeDef)) &&
  14283. (!constExprValueType->mType->IsInstanceOf(mCompiler->mClosedRangeTypeDef)))
  14284. {
  14285. DoTypeToString(str, constExprValueType->mType, typeNameFlags, genericMethodNameOverrides);
  14286. if (constExprValueType->mValue.mTypeCode != BfTypeCode_Boolean)
  14287. str += " ";
  14288. }
  14289. }
  14290. if (constExprValueType->mValueString.IsEmpty())
  14291. VariantToString(constExprValueType->mValueString, constExprValueType->mValue, constExprValueType->mType);
  14292. str += constExprValueType->mValueString;
  14293. return;
  14294. }
  14295. BFMODULE_FATAL(this, "Not implemented");
  14296. str += "???";
  14297. return;
  14298. }