2
0

BfExprEvaluator.cpp 894 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268
  1. #pragma warning(push)
  2. #pragma warning(disable:4800)
  3. #pragma warning(disable:4244)
  4. #pragma warning(disable:4141)
  5. #pragma warning(disable:4624)
  6. #pragma warning(disable:4146)
  7. #pragma warning(disable:4267)
  8. #pragma warning(disable:4291)
  9. #include "BfExprEvaluator.h"
  10. #include "BfConstResolver.h"
  11. #include "BfAutoComplete.h"
  12. #include "BeefySysLib/util/PerfTimer.h"
  13. #include "BeefySysLib/util/BeefPerf.h"
  14. #include "BfParser.h"
  15. #include "BfMangler.h"
  16. #include "BfDemangler.h"
  17. #include "BfResolvePass.h"
  18. #include "BfUtil.h"
  19. #include "BfDeferEvalChecker.h"
  20. #include "BfVarDeclChecker.h"
  21. #include "BfFixits.h"
  22. #include "CeMachine.h"
  23. #include "BfDefBuilder.h"
  24. #include "CeMachine.h"
  25. #include "CeDebugger.h"
  26. #pragma warning(pop)
  27. #pragma warning(disable:4996)
  28. #include "BeefySysLib/util/AllocDebug.h"
  29. USING_NS_BF;
  30. using namespace llvm;
  31. //////////////////////////////////////////////////////////////////////////
  32. DeferredTupleAssignData::~DeferredTupleAssignData()
  33. {
  34. for (auto entry : mChildren)
  35. {
  36. delete entry.mExprEvaluator;
  37. delete entry.mInnerTuple;
  38. }
  39. }
  40. //////////////////////////////////////////////////////////////////////////
  41. BfBaseClassWalker::BfBaseClassWalker(BfType* typeA, BfType* typeB, BfModule* module, bool allowInterfaces)
  42. {
  43. mMayBeFromInterface = false;
  44. if (typeB == typeA)
  45. typeB = NULL;
  46. if ((typeA != NULL) &&
  47. ((!typeA->IsInterface()) || (allowInterfaces)))
  48. mTypes[0] = typeA->ToTypeInstance();
  49. else
  50. mTypes[0] = NULL;
  51. if ((typeB != NULL) &&
  52. ((!typeB->IsInterface()) || (allowInterfaces)))
  53. mTypes[1] = typeB->ToTypeInstance();
  54. else
  55. mTypes[1] = NULL;
  56. if ((typeA != NULL) && (typeA->IsGenericParam()))
  57. {
  58. mMayBeFromInterface = true;
  59. AddConstraints(typeA, module->GetGenericParamInstance((BfGenericParamType*)typeA));
  60. }
  61. if ((typeA != NULL) && (typeA->IsInterface()))
  62. {
  63. AddInterfaces(typeA, typeA->ToTypeInstance());
  64. }
  65. if ((typeB != NULL) && (typeB->IsGenericParam()))
  66. {
  67. mMayBeFromInterface = true;
  68. AddConstraints(typeB, module->GetGenericParamInstance((BfGenericParamType*)typeB));
  69. }
  70. if ((typeB != NULL) && (typeB->IsInterface()))
  71. {
  72. AddInterfaces(typeB, typeB->ToTypeInstance());
  73. }
  74. }
  75. /*BfBaseClassWalker::BfBaseClassWalker(BfTypeInstance* typeA, BfTypeInstance* typeB)
  76. {
  77. mTypes[0] = typeA;
  78. mTypes[1] = typeB;
  79. }*/
  80. BfBaseClassWalker::BfBaseClassWalker()
  81. {
  82. mMayBeFromInterface = false;
  83. mTypes[0] = NULL;
  84. mTypes[1] = NULL;
  85. }
  86. void BfBaseClassWalker::AddConstraints(BfType* srcType, BfGenericParamInstance* genericParam)
  87. {
  88. if (genericParam->mTypeConstraint != NULL)
  89. {
  90. auto typeInst = genericParam->mTypeConstraint->ToTypeInstance();
  91. if (typeInst != NULL)
  92. {
  93. if (typeInst->IsInterface())
  94. AddInterfaces(srcType, typeInst->ToTypeInstance());
  95. Entry entry(srcType, typeInst);
  96. if (!mManualList.Contains(entry))
  97. mManualList.Add(entry);
  98. }
  99. }
  100. for (auto typeInst : genericParam->mInterfaceConstraints)
  101. {
  102. if (typeInst != NULL)
  103. {
  104. if (typeInst->IsInterface())
  105. AddInterfaces(srcType, typeInst->ToTypeInstance());
  106. Entry entry(srcType, typeInst);
  107. if (!mManualList.Contains(entry))
  108. mManualList.Add(entry);
  109. }
  110. }
  111. }
  112. void BfBaseClassWalker::AddInterfaces(BfType* srcType, BfTypeInstance* typeInst)
  113. {
  114. for (auto ifaceEntry : typeInst->mInterfaces)
  115. {
  116. Entry entry(srcType, ifaceEntry.mInterfaceType);
  117. if ((typeInst != NULL) && (!mManualList.Contains(entry)))
  118. mManualList.Add(entry);
  119. }
  120. }
  121. BfBaseClassWalker::Entry BfBaseClassWalker::Next()
  122. {
  123. if (!mManualList.IsEmpty())
  124. {
  125. auto entry = mManualList.back();
  126. mManualList.pop_back();
  127. return entry;
  128. }
  129. // Check the most specific type instance first (highest inheritance level)
  130. auto checkInstance = mTypes[0];
  131. if (mTypes[0] == NULL)
  132. checkInstance = mTypes[1];
  133. else if ((mTypes[1] != NULL) && (mTypes[1]->mInheritDepth > mTypes[0]->mInheritDepth))
  134. checkInstance = mTypes[1];
  135. if (checkInstance == NULL)
  136. return Entry();
  137. // Do it this was so if we reach the same base class for both types that we only handle each base type once
  138. if (checkInstance == mTypes[0])
  139. mTypes[0] = checkInstance->mBaseType;
  140. if (checkInstance == mTypes[1])
  141. mTypes[1] = checkInstance->mBaseType;
  142. Entry entry;
  143. entry.mSrcType = checkInstance;
  144. entry.mTypeInstance = checkInstance;
  145. return entry;
  146. }
  147. //////////////////////////////////////////////////////////////////////////
  148. BfMethodMatcher::BfMethodMatcher(BfAstNode* targetSrc, BfModule* module, const StringImpl& methodName, SizedArrayImpl<BfResolvedArg>& arguments, const BfMethodGenericArguments& methodGenericArguments) :
  149. mArguments(arguments)
  150. {
  151. mTargetSrc = targetSrc;
  152. mModule = module;
  153. mMethodName = methodName;
  154. Init(/*arguments, */methodGenericArguments);
  155. }
  156. BfMethodMatcher::BfMethodMatcher(BfAstNode* targetSrc, BfModule* module, BfMethodInstance* interfaceMethodInstance, SizedArrayImpl<BfResolvedArg>& arguments, const BfMethodGenericArguments& methodGenericArguments) :
  157. mArguments(arguments)
  158. {
  159. mTargetSrc = targetSrc;
  160. mModule = module;
  161. Init(/*arguments, */methodGenericArguments);
  162. mInterfaceMethodInstance = interfaceMethodInstance;
  163. mMethodName = mInterfaceMethodInstance->mMethodDef->mName;
  164. }
  165. void BfMethodMatcher::Init(const BfMethodGenericArguments& methodGenericArguments)
  166. {
  167. //mArguments = arguments;
  168. mUsingLists = NULL;
  169. mActiveTypeDef = NULL;
  170. mBestMethodDef = NULL;
  171. mBackupMethodDef = NULL;
  172. mBackupMatchKind = BackupMatchKind_None;
  173. mBestRawMethodInstance = NULL;
  174. mBestMethodTypeInstance = NULL;
  175. mExplicitInterfaceCheck = NULL;
  176. mSelfType = NULL;
  177. mMethodType = BfMethodType_Normal;
  178. mCheckReturnType = NULL;
  179. mHasArgNames = false;
  180. mHadExplicitGenericArguments = false;
  181. mHadOpenGenericArguments = methodGenericArguments.mIsOpen;
  182. mHadPartialGenericArguments = methodGenericArguments.mIsPartial;
  183. mHasVarArguments = false;
  184. mInterfaceMethodInstance = NULL;
  185. mFakeConcreteTarget = false;
  186. mBypassVirtual = false;
  187. mAllowStatic = true;
  188. mAllowNonStatic = true;
  189. mSkipImplicitParams = false;
  190. mAllowImplicitThis = false;
  191. mAllowImplicitRef = false;
  192. mAllowImplicitWrap = false;
  193. mHadVarConflictingReturnType = false;
  194. mAutoFlushAmbiguityErrors = true;
  195. mMethodCheckCount = 0;
  196. mCheckedKind = BfCheckedKind_NotSet;
  197. mAllowAppendKind = BfAllowAppendKind_No;
  198. mMatchFailKind = MatchFailKind_None;
  199. mBfEvalExprFlags = BfEvalExprFlags_None;
  200. for (auto& arg : mArguments)
  201. {
  202. auto bfType = arg.mTypedValue.mType;
  203. if (bfType != NULL)
  204. {
  205. mHasVarArguments |= bfType->IsVar();
  206. if (bfType->IsGenericParam())
  207. {
  208. BfType* typeConstraint = NULL;
  209. BfGenericParamFlags flags = BfGenericParamFlag_None;
  210. mModule->GetMergedGenericParamData(bfType, flags, typeConstraint);
  211. if ((flags & BfGenericParamFlag_Var) != 0)
  212. mHasVarArguments = true;
  213. }
  214. }
  215. if (arg.mNameNode != NULL)
  216. mHasArgNames = true;
  217. }
  218. if (methodGenericArguments.mArguments != NULL)
  219. {
  220. for (BfAstNode* genericArg : *(methodGenericArguments.mArguments))
  221. {
  222. BfType* genericArgType = NULL;
  223. if (BfNodeIsA<BfUninitializedExpression>(genericArg))
  224. {
  225. // Allow a null here
  226. BF_ASSERT(mHadPartialGenericArguments);
  227. }
  228. else
  229. {
  230. genericArgType = mModule->ResolveTypeRef(genericArg, NULL, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowImplicitConstExpr);
  231. if ((genericArgType != NULL) && (genericArgType->IsGenericParam()))
  232. {
  233. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)genericArgType);
  234. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  235. mHasVarArguments = true;
  236. }
  237. }
  238. mExplicitMethodGenericArguments.push_back(genericArgType);
  239. }
  240. mHadExplicitGenericArguments = true;
  241. }
  242. }
  243. bool BfMethodMatcher::IsMemberAccessible(BfTypeInstance* typeInst, BfTypeDef* declaringType)
  244. {
  245. if (!declaringType->mIsPartial)
  246. return true;
  247. if (mActiveTypeDef == NULL)
  248. mActiveTypeDef = mModule->GetActiveTypeDef();
  249. // Note that mActiveTypeDef does not pose a constraint here
  250. if (!typeInst->IsTypeMemberIncluded(declaringType, mActiveTypeDef, mModule))
  251. return false;
  252. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  253. if ((visibleProjectSet != NULL) && (!typeInst->IsTypeMemberAccessible(declaringType, visibleProjectSet)))
  254. {
  255. return false;
  256. }
  257. return true;
  258. }
  259. bool BfGenericInferContext::AddToCheckedSet(BfType* argType, BfType* wantType)
  260. {
  261. int64 idPair = ((int64)argType->mTypeId << 32) | (wantType->mTypeId);
  262. return mCheckedTypeSet.Add(idPair);
  263. }
  264. bool BfGenericInferContext::InferGenericArgument(BfMethodInstance* methodInstance, BfType* argType, BfType* wantType, BfIRValue argValue, bool checkCheckedSet)
  265. {
  266. if (argType == NULL)
  267. return false;
  268. if (!wantType->IsUnspecializedType())
  269. return true;
  270. if (checkCheckedSet)
  271. {
  272. if (!AddToCheckedSet(argType, wantType))
  273. return true;
  274. }
  275. if (wantType->IsGenericParam())
  276. {
  277. auto wantGenericParam = (BfGenericParamType*)wantType;
  278. BfType* methodGenericTypeConstraint = NULL;
  279. auto _SetGeneric = [&]()
  280. {
  281. if (argType != NULL)
  282. {
  283. // Disallow illegal types
  284. if (argType->IsRef())
  285. return;
  286. if (argType->IsNull())
  287. return;
  288. }
  289. if ((*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] != argType)
  290. {
  291. if (methodGenericTypeConstraint != NULL)
  292. {
  293. if (methodGenericTypeConstraint->IsGenericTypeInstance())
  294. {
  295. auto wantGenericType = (BfTypeInstance*)methodGenericTypeConstraint;
  296. auto checkArgType = argType;
  297. while (checkArgType != NULL)
  298. {
  299. if (checkArgType->IsGenericTypeInstance())
  300. {
  301. auto argGenericType = (BfTypeInstance*)checkArgType;
  302. if (argGenericType->mTypeDef->GetLatest() == wantGenericType->mTypeDef->GetLatest())
  303. {
  304. for (int genericArgIdx = 0; genericArgIdx < (int)argGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  305. InferGenericArgument(methodInstance, argGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], wantGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], BfIRValue(), true);
  306. }
  307. }
  308. else if (checkArgType->IsSizedArray())
  309. {
  310. auto sizedArrayType = (BfSizedArrayType*)checkArgType;
  311. if (wantGenericType->IsInstanceOf(mModule->mCompiler->mSizedArrayTypeDef))
  312. {
  313. InferGenericArgument(methodInstance, sizedArrayType->mElementType, wantGenericType->mGenericTypeInfo->mTypeGenericArguments[0], BfIRValue());
  314. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  315. BfTypedValue arraySize = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), intType);
  316. InferGenericArgument(methodInstance, mModule->CreateConstExprValueType(arraySize), wantGenericType->mGenericTypeInfo->mTypeGenericArguments[1], BfIRValue(), true);
  317. }
  318. }
  319. else if (checkArgType->IsPointer())
  320. {
  321. auto pointerType = (BfPointerType*)checkArgType;
  322. if (wantGenericType->IsInstanceOf(mModule->mCompiler->mPointerTTypeDef))
  323. {
  324. InferGenericArgument(methodInstance, pointerType->mElementType, wantGenericType->mGenericTypeInfo->mTypeGenericArguments[0], BfIRValue(), true);
  325. }
  326. }
  327. auto checkTypeInst = checkArgType->ToTypeInstance();
  328. if ((checkTypeInst == NULL) || (!checkTypeInst->mHasParameterizedBase))
  329. break;
  330. checkArgType = checkTypeInst->mBaseType;
  331. }
  332. }
  333. }
  334. }
  335. if ((*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] == NULL)
  336. mInferredCount++;
  337. (*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] = argType;
  338. if (!mPrevArgValues.IsEmpty())
  339. mPrevArgValues[wantGenericParam->mGenericParamIdx] = argValue;
  340. };
  341. if (argType->IsVar())
  342. {
  343. _SetGeneric();
  344. return true;
  345. }
  346. if (wantGenericParam->mGenericParamKind == BfGenericParamKind_Method)
  347. {
  348. auto genericParamInst = methodInstance->mMethodInfoEx->mGenericParams[wantGenericParam->mGenericParamIdx];
  349. methodGenericTypeConstraint = genericParamInst->mTypeConstraint;
  350. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  351. {
  352. if (argValue.IsConst())
  353. {
  354. argType = mModule->CreateConstExprValueType(BfTypedValue(argValue, argType));
  355. }
  356. else if (!argType->IsConstExprValue())
  357. {
  358. return false;
  359. }
  360. }
  361. if (argType == mModule->mContext->mBfObjectType)
  362. {
  363. if ((genericParamInst->mTypeConstraint != NULL) && (genericParamInst->mTypeConstraint->IsDelegate()))
  364. {
  365. argType = mModule->ResolveGenericType(genericParamInst->mTypeConstraint, NULL, mCheckMethodGenericArguments, mModule->mCurTypeInstance);
  366. if (argType == NULL)
  367. return true;
  368. }
  369. }
  370. if (mPrevArgValues.IsEmpty())
  371. {
  372. _SetGeneric();
  373. return true;
  374. }
  375. auto prevGenericMethodArg = (*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx];
  376. auto prevArgValue = mPrevArgValues[wantGenericParam->mGenericParamIdx];
  377. if (prevGenericMethodArg == NULL)
  378. {
  379. _SetGeneric();
  380. return true;
  381. }
  382. if ((prevGenericMethodArg->IsIntUnknown()) && (!argType->IsIntUnknown()))
  383. {
  384. // Old int fits into new argType, that's good
  385. if (mModule->CanCast(BfTypedValue(prevArgValue, prevGenericMethodArg), argType))
  386. {
  387. _SetGeneric();
  388. return true;
  389. }
  390. // Doesn't fit, upgrade type to 'int'
  391. argType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  392. if (mModule->CanCast(BfTypedValue(prevArgValue, prevGenericMethodArg), argType))
  393. {
  394. _SetGeneric();
  395. return true;
  396. }
  397. }
  398. if (argType->IsIntUnknown())
  399. {
  400. // New int fits into previous arg type, that's good
  401. if (mModule->CanCast(BfTypedValue(argValue, argType), prevGenericMethodArg))
  402. return true;
  403. // Doesn't fit, upgrade type to 'int'
  404. argType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  405. }
  406. else
  407. {
  408. // Prev is already best
  409. if (mModule->CanCast(mModule->GetFakeTypedValue(argType), prevGenericMethodArg))
  410. return true;
  411. }
  412. // New best?
  413. if (mModule->CanCast(mModule->GetFakeTypedValue(prevGenericMethodArg), argType))
  414. {
  415. _SetGeneric();
  416. return true;
  417. }
  418. // No implicit conversion, FAIL!
  419. (*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] = NULL;
  420. return false;
  421. }
  422. return true;
  423. }
  424. if (wantType->IsTuple())
  425. {
  426. if (argType->IsTuple())
  427. {
  428. auto wantTupleType = (BfTupleType*)wantType;
  429. auto argTupleType = (BfTupleType*)argType;
  430. if (wantTupleType->mFieldInstances.size() == argTupleType->mFieldInstances.size())
  431. {
  432. for (int fieldIdx = 0; fieldIdx < (int)wantTupleType->mFieldInstances.size(); fieldIdx++)
  433. {
  434. InferGenericArgument(methodInstance, argTupleType->mFieldInstances[fieldIdx].mResolvedType,
  435. wantTupleType->mFieldInstances[fieldIdx].mResolvedType, BfIRValue());
  436. }
  437. }
  438. }
  439. }
  440. if ((wantType->IsGenericTypeInstance()) && (wantType->IsUnspecializedTypeVariation()))
  441. {
  442. auto wantGenericType = (BfTypeInstance*)wantType;
  443. if (argType->IsGenericParam())
  444. {
  445. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)argType);
  446. if ((genericParam->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  447. {
  448. InferGenericArgument(methodInstance, mModule->GetPrimitiveType(BfTypeCode_Var), wantType, BfIRValue());
  449. return true;
  450. }
  451. if ((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsGenericTypeInstance()))
  452. InferGenericArgument(methodInstance, genericParam->mTypeConstraint, wantType, BfIRValue());
  453. }
  454. if (argType->IsVar())
  455. {
  456. for (int genericArgIdx = 0; genericArgIdx < (int)wantGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  457. {
  458. BfType* wantGenericArgument = wantGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx];
  459. if (!wantGenericArgument->IsUnspecializedType())
  460. continue;
  461. InferGenericArgument(methodInstance, mModule->GetPrimitiveType(BfTypeCode_Var), wantGenericArgument, BfIRValue());
  462. }
  463. return true;
  464. }
  465. auto typeInstance = argType->ToTypeInstance();
  466. if (typeInstance == NULL)
  467. return true;
  468. if (wantGenericType->IsInterface())
  469. {
  470. for (auto& ifaceEntry : typeInstance->mInterfaces)
  471. InferGenericArgument(methodInstance, ifaceEntry.mInterfaceType, wantType, BfIRValue());
  472. }
  473. else if (typeInstance->mBaseType != NULL)
  474. InferGenericArgument(methodInstance, typeInstance->mBaseType, wantType, BfIRValue());
  475. if (!argType->IsGenericTypeInstance())
  476. return true;
  477. auto argGenericType = (BfTypeInstance*)argType;
  478. if (argGenericType->mTypeDef->GetDefinition() != wantGenericType->mTypeDef->GetDefinition())
  479. return true;
  480. for (int genericArgIdx = 0; genericArgIdx < (int)argGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  481. {
  482. BfType* wantGenericArgument = wantGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx];
  483. if (!wantGenericArgument->IsUnspecializedType())
  484. continue;
  485. InferGenericArgument(methodInstance, argGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], wantGenericArgument, BfIRValue(), true);
  486. }
  487. return true;
  488. }
  489. if (wantType->IsRef())
  490. {
  491. auto wantRefType = (BfRefType*)wantType;
  492. if (!argType->IsRef())
  493. {
  494. // Match to non-ref
  495. InferGenericArgument(methodInstance, argType, wantRefType->mElementType, BfIRValue());
  496. return true;
  497. }
  498. auto argRefType = (BfRefType*)argType;
  499. //TODO: We removed this check so we still infer even if we have the wrong ref kind
  500. //if (wantRefType->mRefKind != argRefType->mRefKind)
  501. //return true;
  502. return InferGenericArgument(methodInstance, argRefType->mElementType, wantRefType->mElementType, BfIRValue());
  503. }
  504. if (wantType->IsPointer())
  505. {
  506. if (!argType->IsPointer())
  507. return true;
  508. auto wantPointerType = (BfPointerType*) wantType;
  509. auto argPointerType = (BfPointerType*) argType;
  510. return InferGenericArgument(methodInstance, argPointerType->mElementType, wantPointerType->mElementType, BfIRValue());
  511. }
  512. if (wantType->IsUnknownSizedArrayType())
  513. {
  514. auto wantArrayType = (BfUnknownSizedArrayType*)wantType;
  515. if (argType->IsUnknownSizedArrayType())
  516. {
  517. auto argArrayType = (BfUnknownSizedArrayType*)argType;
  518. InferGenericArgument(methodInstance, argArrayType->mElementCountSource, wantArrayType->mElementCountSource, BfIRValue());
  519. }
  520. else if (argType->IsSizedArray())
  521. {
  522. auto argArrayType = (BfSizedArrayType*)argType;
  523. BfTypedValue sizeValue(mModule->GetConstValue(argArrayType->mElementCount), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  524. auto sizedType = mModule->CreateConstExprValueType(sizeValue);
  525. InferGenericArgument(methodInstance, sizedType, wantArrayType->mElementCountSource, BfIRValue());
  526. }
  527. }
  528. if (wantType->IsSizedArray())
  529. {
  530. if (argType->IsSizedArray())
  531. {
  532. auto wantArrayType = (BfSizedArrayType*)wantType;
  533. auto argArrayType = (BfSizedArrayType*)argType;
  534. InferGenericArgument(methodInstance, argArrayType->mElementType, wantArrayType->mElementType, BfIRValue());
  535. }
  536. }
  537. if ((wantType->IsDelegate()) || (wantType->IsFunction()))
  538. {
  539. if (((argType->IsDelegate()) || (argType->IsFunction())) &&
  540. (wantType->IsDelegate() == argType->IsDelegate()))
  541. {
  542. if (!AddToCheckedSet(argType, wantType))
  543. return true;
  544. auto argInvokeMethod = mModule->GetRawMethodByName(argType->ToTypeInstance(), "Invoke");
  545. auto wantInvokeMethod = mModule->GetRawMethodByName(wantType->ToTypeInstance(), "Invoke");
  546. if ((argInvokeMethod != NULL) && (wantInvokeMethod != NULL) && (argInvokeMethod->GetParamCount() == wantInvokeMethod->GetParamCount()))
  547. {
  548. InferGenericArgument(methodInstance, argInvokeMethod->mReturnType, wantInvokeMethod->mReturnType, BfIRValue());
  549. for (int argIdx = 0; argIdx < (int)argInvokeMethod->GetParamCount(); argIdx++)
  550. InferGenericArgument(methodInstance, argInvokeMethod->GetParamType(argIdx), wantInvokeMethod->GetParamType(argIdx), BfIRValue());
  551. }
  552. }
  553. else if (argType->IsMethodRef())
  554. {
  555. auto methodTypeRef = (BfMethodRefType*)argType;
  556. if (!AddToCheckedSet(argType, wantType))
  557. return true;
  558. auto argInvokeMethod = methodTypeRef->mMethodRef;
  559. auto delegateInfo = wantType->GetDelegateInfo();
  560. auto wantInvokeMethod = mModule->GetRawMethodByName(wantType->ToTypeInstance(), "Invoke");
  561. if ((delegateInfo->mHasExplicitThis) && (argInvokeMethod->HasThis()))
  562. InferGenericArgument(methodInstance, argInvokeMethod->GetParamType(-1), delegateInfo->mParams[0], BfIRValue());
  563. int wantInvokeOffset = delegateInfo->mHasExplicitThis ? 1 : 0;
  564. if ((argInvokeMethod != NULL) && (wantInvokeMethod != NULL) && (argInvokeMethod->GetParamCount() == wantInvokeMethod->GetParamCount() - wantInvokeOffset))
  565. {
  566. InferGenericArgument(methodInstance, argInvokeMethod->mReturnType, wantInvokeMethod->mReturnType, BfIRValue());
  567. for (int argIdx = 0; argIdx < (int)argInvokeMethod->GetParamCount(); argIdx++)
  568. InferGenericArgument(methodInstance, argInvokeMethod->GetParamType(argIdx), wantInvokeMethod->GetParamType(argIdx + wantInvokeOffset), BfIRValue());
  569. }
  570. }
  571. }
  572. return true;
  573. }
  574. bool BfGenericInferContext::InferGenericArguments(BfMethodInstance* methodInstance, int srcGenericIdx)
  575. {
  576. auto& srcGenericArg = (*mCheckMethodGenericArguments)[srcGenericIdx];
  577. if (srcGenericArg == NULL)
  578. return false;
  579. int startInferCount = mInferredCount;
  580. auto srcGenericParam = methodInstance->mMethodInfoEx->mGenericParams[srcGenericIdx];
  581. for (auto ifaceConstraint : srcGenericParam->mInterfaceConstraints)
  582. {
  583. if ((ifaceConstraint->IsUnspecializedTypeVariation()) && (ifaceConstraint->IsGenericTypeInstance()))
  584. {
  585. InferGenericArgument(methodInstance, srcGenericArg, ifaceConstraint, BfIRValue());
  586. auto typeInstance = srcGenericArg->ToTypeInstance();
  587. if ((typeInstance == NULL) && (srcGenericArg->IsWrappableType()))
  588. typeInstance = mModule->GetWrappedStructType(srcGenericArg);
  589. if (typeInstance != NULL)
  590. {
  591. for (auto ifaceEntry : typeInstance->mInterfaces)
  592. InferGenericArgument(methodInstance, ifaceEntry.mInterfaceType, ifaceConstraint, BfIRValue());
  593. }
  594. if (srcGenericArg->IsGenericParam())
  595. {
  596. auto genericParamType = (BfGenericParamType*)srcGenericArg;
  597. BfGenericParamInstance* genericParam = NULL;
  598. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  599. genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  600. else
  601. genericParam = mModule->GetGenericParamInstance(genericParamType);
  602. if (genericParam->mTypeConstraint != NULL)
  603. InferGenericArgument(methodInstance, genericParam->mTypeConstraint, ifaceConstraint, BfIRValue());
  604. for (auto argIfaceConstraint : genericParam->mInterfaceConstraints)
  605. InferGenericArgument(methodInstance, argIfaceConstraint, ifaceConstraint, BfIRValue());
  606. }
  607. }
  608. }
  609. return mInferredCount != startInferCount;
  610. }
  611. void BfGenericInferContext::InferGenericArguments(BfMethodInstance* methodInstance)
  612. {
  613. // Attempt to infer from other generic args
  614. for (int srcGenericIdx = 0; srcGenericIdx < (int)mCheckMethodGenericArguments->size(); srcGenericIdx++)
  615. {
  616. InferGenericArguments(methodInstance, srcGenericIdx);
  617. }
  618. }
  619. int BfMethodMatcher::GetMostSpecificType(BfType* lhs, BfType* rhs)
  620. {
  621. if ((lhs->IsRef()) && (rhs->IsRef()))
  622. return GetMostSpecificType(lhs->GetUnderlyingType(), rhs->GetUnderlyingType());
  623. if ((lhs->IsPointer()) && (rhs->IsPointer()))
  624. return GetMostSpecificType(lhs->GetUnderlyingType(), rhs->GetUnderlyingType());
  625. if ((lhs->IsSizedArray()) && (rhs->IsSizedArray()))
  626. return GetMostSpecificType(lhs->GetUnderlyingType(), rhs->GetUnderlyingType());
  627. if (lhs->IsGenericParam())
  628. return rhs->IsGenericParam() ? -1 : 1;
  629. if (rhs->IsGenericParam())
  630. return 0;
  631. if ((lhs->IsUnspecializedType()) && (lhs->IsGenericTypeInstance()))
  632. {
  633. if ((!rhs->IsUnspecializedType()) || (!rhs->IsGenericTypeInstance()))
  634. return 1;
  635. auto lhsTypeInst = lhs->ToTypeInstance();
  636. auto rhsTypeInst = rhs->ToTypeInstance();
  637. if ((rhsTypeInst == NULL) || (lhsTypeInst == NULL) || (lhsTypeInst->mTypeDef != rhsTypeInst->mTypeDef))
  638. return -1;
  639. bool hadLHSMoreSpecific = false;
  640. bool hadRHSMoreSpecific = false;
  641. for (int generigArgIdx = 0; generigArgIdx < (int)lhsTypeInst->mGenericTypeInfo->mTypeGenericArguments.size(); generigArgIdx++)
  642. {
  643. int argMoreSpecific = GetMostSpecificType(lhsTypeInst->mGenericTypeInfo->mTypeGenericArguments[generigArgIdx],
  644. rhsTypeInst->mGenericTypeInfo->mTypeGenericArguments[generigArgIdx]);
  645. if (argMoreSpecific == 0)
  646. hadLHSMoreSpecific = true;
  647. else if (argMoreSpecific == 1)
  648. hadRHSMoreSpecific = true;
  649. }
  650. if ((hadLHSMoreSpecific) && (!hadRHSMoreSpecific))
  651. return 0;
  652. if ((hadRHSMoreSpecific) && (!hadLHSMoreSpecific))
  653. return 1;
  654. return -1;
  655. }
  656. if (rhs->IsUnspecializedType())
  657. return 0;
  658. return -1;
  659. }
  660. void BfMethodMatcher::CompareMethods(BfMethodInstance* prevMethodInstance, BfTypeVector* prevGenericArgumentsSubstitute,
  661. BfMethodInstance* newMethodInstance, BfTypeVector* genericArgumentsSubstitute,
  662. bool* outNewIsBetter, bool* outNewIsWorse, bool allowSpecializeFail)
  663. {
  664. if (prevMethodInstance == newMethodInstance)
  665. {
  666. *outNewIsBetter = false;
  667. *outNewIsWorse = true;
  668. return;
  669. }
  670. #define SET_BETTER_OR_WORSE(lhs, rhs) \
  671. if ((!isBetter) && (lhs) && !(rhs)) isBetter = true; \
  672. if ((!isWorse) && !(lhs) && (rhs)) isWorse = true;
  673. #define RETURN_BETTER_OR_WORSE(lhs, rhs) \
  674. if ((!isBetter) && (lhs) && !(rhs)) { *outNewIsBetter = true; *outNewIsWorse = false; return; } \
  675. if ((!isWorse) && !(lhs) && (rhs)) { *outNewIsBetter = false; *outNewIsWorse = true; return; };
  676. #define RETURN_RESULTS \
  677. *outNewIsBetter = isBetter; \
  678. *outNewIsWorse = isWorse; \
  679. return;
  680. int numUsedParams = 0;
  681. int prevNumUsedParams = 0;
  682. bool usedExtendedForm = false;
  683. bool prevUsedExtendedForm = false;
  684. bool isBetter = false;
  685. bool isWorse = false;
  686. int argIdx;
  687. BfMethodDef* prevMethodDef = prevMethodInstance->mMethodDef;
  688. BfMethodDef* newMethodDef = newMethodInstance->mMethodDef;
  689. if (prevMethodDef == mBackupMethodDef)
  690. {
  691. // This can happen for extension methods and such
  692. *outNewIsBetter = true;
  693. *outNewIsWorse = false;
  694. return;
  695. }
  696. if (newMethodDef->mExplicitInterface != prevMethodDef->mExplicitInterface)
  697. {
  698. if (mModule->CompareMethodSignatures(newMethodInstance, prevMethodInstance))
  699. {
  700. SET_BETTER_OR_WORSE(newMethodDef->mExplicitInterface != NULL, prevMethodDef->mExplicitInterface != NULL);
  701. *outNewIsBetter = isBetter;
  702. *outNewIsWorse = isWorse;
  703. return;
  704. }
  705. }
  706. bool anyIsExtension = false;
  707. int newImplicitParamCount = newMethodInstance->GetImplicitParamCount();
  708. if (newMethodInstance->mMethodDef->HasAppend())
  709. newImplicitParamCount++;
  710. if (newMethodInstance->mMethodDef->mMethodType == BfMethodType_Extension)
  711. {
  712. newImplicitParamCount++;
  713. anyIsExtension = true;
  714. }
  715. int prevImplicitParamCount = prevMethodInstance->GetImplicitParamCount();
  716. if (prevMethodInstance->mMethodDef->HasAppend())
  717. prevImplicitParamCount++;
  718. if (prevMethodInstance->mMethodDef->mMethodType == BfMethodType_Extension)
  719. {
  720. prevImplicitParamCount++;
  721. anyIsExtension = true;
  722. }
  723. BfCastFlags implicitCastFlags = ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp) != 0) ? BfCastFlags_NoConversionOperator : BfCastFlags_None;
  724. int newMethodParamCount = newMethodInstance->GetParamCount();
  725. int prevMethodParamCount = prevMethodInstance->GetParamCount();
  726. bool hadEnoughArgs = newMethodParamCount - newImplicitParamCount < (int)mArguments.size();
  727. bool prevHadEnoughArgs = prevMethodParamCount - prevImplicitParamCount < (int)mArguments.size();
  728. RETURN_BETTER_OR_WORSE(hadEnoughArgs, prevHadEnoughArgs);
  729. bool chainSkip = (newMethodInstance->mChainType == BfMethodChainType_ChainMember) || (newMethodInstance->mChainType == BfMethodChainType_ChainSkip);
  730. bool prevChainSkip = (prevMethodInstance->mChainType == BfMethodChainType_ChainMember) || (prevMethodInstance->mChainType == BfMethodChainType_ChainSkip);
  731. RETURN_BETTER_OR_WORSE(!chainSkip, !prevChainSkip);
  732. if ((!isBetter) && (!isWorse))
  733. {
  734. bool betterByGenericParam = false;
  735. bool worseByGenericParam = false;
  736. bool betterByConstExprParam = false;
  737. bool worseByConstExprParam = false;
  738. bool someArgWasBetter = false;
  739. bool someArgWasWorse = false;
  740. for (argIdx = anyIsExtension ? -1 : 0; argIdx < (int)mArguments.size(); argIdx++)
  741. {
  742. BfTypedValue arg;
  743. BfResolvedArg* resolvedArg = NULL;
  744. bool wasArgDeferred = false;
  745. if (argIdx == -1)
  746. {
  747. arg = mTarget;
  748. }
  749. else
  750. {
  751. resolvedArg = &mArguments[argIdx];
  752. wasArgDeferred = resolvedArg->mArgFlags != 0;
  753. arg = resolvedArg->mTypedValue;
  754. }
  755. int newArgIdx = argIdx + newImplicitParamCount;
  756. int prevArgIdx = argIdx + prevImplicitParamCount;
  757. if (newArgIdx >= newMethodParamCount)
  758. break;
  759. if (prevArgIdx >= prevMethodParamCount)
  760. break;
  761. bool wasGenericParam = (newArgIdx >= 0) && newMethodInstance->WasGenericParam(newArgIdx);
  762. bool prevWasGenericParam = (prevArgIdx >= 0) && prevMethodInstance->WasGenericParam(prevArgIdx);
  763. BfType* paramType = newMethodInstance->GetParamType(newArgIdx, true);
  764. BfType* prevParamType = prevMethodInstance->GetParamType(prevArgIdx, true);
  765. numUsedParams++;
  766. prevNumUsedParams++;
  767. BfType* origParamType = paramType;
  768. BfType* origPrevParamType = prevParamType;
  769. bool paramWasConstExpr = false;
  770. bool prevParamWasConstExpr = false;
  771. bool paramWasUnspecialized = paramType->IsUnspecializedType();
  772. if ((genericArgumentsSubstitute != NULL) && (paramWasUnspecialized))
  773. {
  774. paramType = mModule->ResolveGenericType(paramType, NULL, genericArgumentsSubstitute, mModule->mCurTypeInstance, allowSpecializeFail);
  775. paramType = mModule->FixIntUnknown(paramType);
  776. }
  777. if ((paramType != NULL) && (paramType->IsConstExprValue()))
  778. {
  779. paramWasConstExpr = true;
  780. paramType = ((BfConstExprValueType*)paramType)->mType;
  781. }
  782. bool prevParamWasUnspecialized = prevParamType->IsUnspecializedType();
  783. if ((prevGenericArgumentsSubstitute != NULL) && (prevParamWasUnspecialized))
  784. {
  785. prevParamType = mModule->ResolveGenericType(prevParamType, NULL, prevGenericArgumentsSubstitute, mModule->mCurTypeInstance, allowSpecializeFail);
  786. prevParamType = mModule->FixIntUnknown(prevParamType);
  787. }
  788. if ((prevParamType != NULL) && (prevParamType->IsConstExprValue()))
  789. {
  790. prevParamWasConstExpr = true;
  791. prevParamType = ((BfConstExprValueType*)prevParamType)->mType;
  792. }
  793. bool paramsEquivalent = paramType == prevParamType;
  794. if ((prevParamType == NULL) || (paramType == NULL))
  795. {
  796. SET_BETTER_OR_WORSE(paramType != NULL, prevParamType != NULL);
  797. }
  798. else if (paramType != prevParamType)
  799. {
  800. bool isUnspecializedParam = paramType->IsUnspecializedType();
  801. bool isPrevUnspecializedParam = prevParamType->IsUnspecializedType();
  802. SET_BETTER_OR_WORSE((!isUnspecializedParam) && (!paramType->IsVar()),
  803. (!isPrevUnspecializedParam) && (!prevParamType->IsVar()));
  804. if ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp_Explicit) != 0)
  805. {
  806. // Pick the one that can implicitly cast
  807. SET_BETTER_OR_WORSE(
  808. mModule->CanCast(arg, paramType, implicitCastFlags),
  809. mModule->CanCast(arg, prevParamType, implicitCastFlags));
  810. }
  811. // Why did we have this !isUnspecializedParam check? We need the 'canCast' logic still
  812. if ((!isBetter) && (!isWorse) /*&& (!isUnspecializedParam) && (!isPrevUnspecializedParam)*/)
  813. {
  814. SET_BETTER_OR_WORSE((paramType != NULL) && (!paramType->IsUnspecializedType()),
  815. (prevParamType != NULL) && (!prevParamType->IsUnspecializedType()));
  816. if ((!isBetter) && (!isWorse))
  817. {
  818. // The resolved argument type may actually match for both considered functions. IE:
  819. // Method(int8 val) and Method(int16 val) called with Method(0) will create arguments that match their param types
  820. if ((!wasArgDeferred) && (!wasGenericParam) && (IsType(arg, paramType)) && ((resolvedArg == NULL) || (prevParamType != resolvedArg->mBestBoundType)))
  821. isBetter = true;
  822. //else if ((!prevWasGenericParam) && (IsType(arg, prevParamType)) && (!IsType(arg, paramType)))
  823. else if ((!wasArgDeferred) && (!prevWasGenericParam) && (IsType(arg, prevParamType)) && ((resolvedArg == NULL) || (paramType != resolvedArg->mBestBoundType)))
  824. isWorse = true;
  825. else
  826. {
  827. bool canCastFromCurToPrev = mModule->CanCast(mModule->GetFakeTypedValue(paramType), prevParamType, implicitCastFlags);
  828. bool canCastFromPrevToCur = mModule->CanCast(mModule->GetFakeTypedValue(prevParamType), paramType, implicitCastFlags);
  829. if ((canCastFromCurToPrev) && (canCastFromPrevToCur))
  830. paramsEquivalent = true;
  831. if ((canCastFromCurToPrev) && (!canCastFromPrevToCur))
  832. isBetter = true;
  833. else if ((canCastFromPrevToCur) && (!canCastFromCurToPrev))
  834. isWorse = true;
  835. else if ((paramType->IsIntegral()) && (prevParamType->IsIntegral()))
  836. {
  837. if (paramType == arg.mType)
  838. isBetter = true;
  839. else if (prevParamType == arg.mType)
  840. isWorse = true;
  841. else
  842. {
  843. if (paramType->mSize < prevParamType->mSize)
  844. isBetter = true;
  845. else if (paramType->mSize > prevParamType->mSize)
  846. isWorse = true;
  847. else if (paramType->IsSigned())
  848. isBetter = true;
  849. else
  850. isWorse = true;
  851. }
  852. }
  853. else if ((wasArgDeferred) && ((paramType->IsIntegral()) || (prevParamType->IsIntegral())))
  854. {
  855. SET_BETTER_OR_WORSE(paramType->IsIntegral(), prevParamType->IsIntegral());
  856. }
  857. }
  858. }
  859. }
  860. }
  861. if ((!isBetter) && (!isWorse) && (paramsEquivalent))
  862. {
  863. if ((origParamType != origPrevParamType) && (paramWasConstExpr) && (!prevParamWasConstExpr))
  864. betterByConstExprParam = true;
  865. else if ((origParamType != origPrevParamType) && (!paramWasConstExpr) && (prevParamWasConstExpr))
  866. worseByConstExprParam = true;
  867. else if (((paramWasUnspecialized) || (prevParamWasUnspecialized)))
  868. {
  869. int origTypeMoreSpecific = GetMostSpecificType(origParamType, origPrevParamType);
  870. if (origTypeMoreSpecific == 0)
  871. betterByGenericParam = true;
  872. else if (origTypeMoreSpecific == 1)
  873. worseByGenericParam = true;
  874. }
  875. }
  876. if ((!isBetter) && (!isWorse) && (paramType->IsRef()) && (prevParamType->IsRef()))
  877. {
  878. auto refType = (BfRefType*)paramType;
  879. auto prevRefType = (BfRefType*)prevParamType;
  880. // Prefer 'out' to 'ref'
  881. SET_BETTER_OR_WORSE(
  882. (refType->mRefKind == BfRefType::RefKind_Out) && (prevRefType->mRefKind == BfRefType::RefKind_Ref),
  883. (refType->mRefKind == BfRefType::RefKind_Ref) && (prevRefType->mRefKind == BfRefType::RefKind_Out));
  884. }
  885. if ((newArgIdx >= 0) && (newMethodInstance->GetParamKind(newArgIdx) == BfParamKind_Params))
  886. usedExtendedForm = true;
  887. if ((prevArgIdx >= 0) && (prevMethodInstance->GetParamKind(prevArgIdx) == BfParamKind_Params))
  888. prevUsedExtendedForm = true;
  889. if ((usedExtendedForm) || (prevUsedExtendedForm))
  890. break;
  891. someArgWasBetter |= isBetter;
  892. someArgWasWorse |= isWorse;
  893. isBetter = false;
  894. isWorse = false;
  895. }
  896. isBetter |= someArgWasBetter;
  897. isWorse |= someArgWasWorse;
  898. if ((!isBetter) && (!isWorse))
  899. {
  900. // Don't allow ambiguity
  901. if ((betterByGenericParam && !worseByGenericParam) ||
  902. (!betterByGenericParam && worseByGenericParam))
  903. {
  904. isBetter = betterByGenericParam;
  905. isWorse = worseByGenericParam;
  906. }
  907. }
  908. if ((!isBetter) && (!isWorse))
  909. {
  910. // Don't allow ambiguity
  911. if ((betterByConstExprParam && !worseByConstExprParam) ||
  912. (!betterByConstExprParam && worseByConstExprParam))
  913. {
  914. isBetter = betterByConstExprParam;
  915. isWorse = worseByConstExprParam;
  916. }
  917. }
  918. if ((isBetter) || (isWorse))
  919. {
  920. RETURN_RESULTS;
  921. }
  922. }
  923. // Choose by return type for conversion operators
  924. if (((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp) != 0) && (!isBetter) && (!isWorse))
  925. {
  926. auto returnType = newMethodInstance->mReturnType;
  927. auto prevReturnType = prevMethodInstance->mReturnType;
  928. if ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp_Explicit) != 0)
  929. {
  930. // Pick the one that can implicitly cast
  931. SET_BETTER_OR_WORSE(
  932. mModule->CanCast(mModule->GetFakeTypedValue(returnType), mCheckReturnType, implicitCastFlags),
  933. mModule->CanCast(mModule->GetFakeTypedValue(prevReturnType), mCheckReturnType, implicitCastFlags));
  934. }
  935. if ((!isBetter) && (!isWorse))
  936. {
  937. bool canCastFromCurToPrev = mModule->CanCast(mModule->GetFakeTypedValue(returnType), prevReturnType, implicitCastFlags);
  938. bool canCastFromPrevToCur = mModule->CanCast(mModule->GetFakeTypedValue(prevReturnType), returnType, implicitCastFlags);
  939. if ((canCastFromCurToPrev) && (!canCastFromPrevToCur))
  940. isWorse = true;
  941. else if ((canCastFromPrevToCur) && (!canCastFromCurToPrev))
  942. isBetter = true;
  943. }
  944. if ((isBetter) || (isWorse))
  945. {
  946. RETURN_RESULTS;
  947. }
  948. }
  949. // Check for unused extended params as next param - that still counts as using extended form
  950. usedExtendedForm = newMethodInstance->HasParamsArray();
  951. prevUsedExtendedForm = prevMethodInstance->HasParamsArray();
  952. RETURN_BETTER_OR_WORSE(newMethodInstance->GetNumGenericArguments() == 0, prevMethodInstance->GetNumGenericArguments() == 0);
  953. // Not using generic delegate params is better
  954. RETURN_BETTER_OR_WORSE(!newMethodInstance->mHadGenericDelegateParams, !prevMethodInstance->mHadGenericDelegateParams);
  955. // Normal form trumps extended form
  956. RETURN_BETTER_OR_WORSE(!usedExtendedForm, !prevUsedExtendedForm);
  957. // More used params trumps less params
  958. int paramDiff = (int) numUsedParams - (int) prevNumUsedParams;
  959. RETURN_BETTER_OR_WORSE(paramDiff > 0, paramDiff < 0);
  960. // Fewer defaults trumps more defaults
  961. // Since we know the number of used params is the same (previous check), we infer that the rest are defaults
  962. paramDiff = (int) newMethodInstance->GetParamCount() - (int) prevMethodInstance->GetParamCount();
  963. RETURN_BETTER_OR_WORSE(paramDiff < 0, paramDiff > 0);
  964. BfMethodInstance* typeUnspecNewMethodInstance = mModule->GetUnspecializedMethodInstance(newMethodInstance, true);
  965. BfMethodInstance* typeUnspecPrevMethodInstance = mModule->GetUnspecializedMethodInstance(prevMethodInstance, true);
  966. // Check specificity of args
  967. std::function<void(BfType*, BfType*)> _CompareParamTypes = [&](BfType* newType, BfType* prevType)
  968. {
  969. if ((newType->IsGenericParam()) && (prevType->IsGenericParam()))
  970. {
  971. auto newGenericParamType = (BfGenericParamType*)newType;
  972. auto prevGenericParamType = (BfGenericParamType*)prevType;
  973. if ((newGenericParamType->mGenericParamKind == BfGenericParamKind_Method) && (prevGenericParamType->mGenericParamKind == BfGenericParamKind_Method))
  974. {
  975. auto newMethodGenericParam = typeUnspecNewMethodInstance->mMethodInfoEx->mGenericParams[newGenericParamType->mGenericParamIdx];
  976. auto prevMethodGenericParam = typeUnspecPrevMethodInstance->mMethodInfoEx->mGenericParams[prevGenericParamType->mGenericParamIdx];
  977. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  978. }
  979. }
  980. else if (newType == prevType)
  981. {
  982. if ((newType->IsUnspecializedType()) && (newType->IsGenericTypeInstance()))
  983. {
  984. BfTypeInstance* newGenericType = (BfTypeInstance*)newType;
  985. BfTypeInstance* prevGenericType = (BfTypeInstance*)prevType;
  986. for (int genericArgIdx = 0; genericArgIdx < (int)newGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  987. {
  988. _CompareParamTypes(newGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], prevGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx]);
  989. }
  990. }
  991. }
  992. else
  993. {
  994. //TODO: Why did we need this?
  995. //isBetter |= mModule->IsTypeMoreSpecific(newType, prevType);
  996. //isWorse |= mModule->IsTypeMoreSpecific(prevType, newType);
  997. }
  998. };
  999. int paramCheckCount = (int)BF_MIN(newMethodInstance->GetParamCount() - newImplicitParamCount, prevMethodInstance->GetParamCount() - prevImplicitParamCount);
  1000. for (argIdx = 0; argIdx < (int)paramCheckCount/*mArguments.size()*/; argIdx++)
  1001. {
  1002. int newArgIdx = argIdx + newImplicitParamCount;
  1003. int prevArgIdx = argIdx + prevImplicitParamCount;
  1004. _CompareParamTypes(typeUnspecNewMethodInstance->GetParamType(newArgIdx), typeUnspecPrevMethodInstance->GetParamType(prevArgIdx));
  1005. }
  1006. // Do generic constraint subset test directly to handle cases like "NotDisposed<T>()" vs "NotDisposed<T>() where T : IDisposable"
  1007. if ((newMethodInstance->GetNumGenericArguments() > 0) && (newMethodInstance->GetNumGenericArguments() == prevMethodInstance->GetNumGenericArguments()))
  1008. {
  1009. for (int genericParamIdx = 0; genericParamIdx < (int)newMethodInstance->GetNumGenericArguments(); genericParamIdx++)
  1010. {
  1011. auto newMethodGenericParam = newMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  1012. auto prevMethodGenericParam = prevMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  1013. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  1014. }
  1015. if ((!isBetter) && (!isWorse))
  1016. {
  1017. SET_BETTER_OR_WORSE(newMethodInstance->HasExternConstraints(), prevMethodInstance->HasExternConstraints());
  1018. }
  1019. }
  1020. if ((isBetter) || (isWorse))
  1021. {
  1022. RETURN_RESULTS;
  1023. }
  1024. // For operators, prefer explicit comparison over '<=>' comparison operator
  1025. if ((!isBetter) && (!isWorse))
  1026. {
  1027. if ((prevMethodDef->mIsOperator) && (newMethodDef->mIsOperator))
  1028. {
  1029. bool newIsComparison = ((BfOperatorDeclaration*)newMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  1030. bool prevIsComparison = ((BfOperatorDeclaration*)prevMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  1031. RETURN_BETTER_OR_WORSE(!newIsComparison, !prevIsComparison);
  1032. }
  1033. }
  1034. if ((newMethodInstance->mMethodDef->mExternalConstraints.size() != 0) || (prevMethodInstance->mMethodDef->mExternalConstraints.size() != 0))
  1035. {
  1036. struct GenericParamPair
  1037. {
  1038. BfGenericMethodParamInstance* mParams[2];
  1039. GenericParamPair()
  1040. {
  1041. mParams[0] = NULL;
  1042. mParams[1] = NULL;
  1043. }
  1044. };
  1045. Dictionary<BfType*, GenericParamPair> externConstraints;
  1046. auto _GetParams = [&](int idx, BfMethodInstance* methodInstance)
  1047. {
  1048. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodInstance->mMethodDef->mExternalConstraints.size(); externConstraintIdx++)
  1049. {
  1050. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[methodInstance->mMethodDef->mGenericParams.size() + externConstraintIdx];
  1051. BF_ASSERT(genericParam->mExternType != NULL);
  1052. GenericParamPair* pairPtr = NULL;
  1053. externConstraints.TryAdd(genericParam->mExternType, NULL, &pairPtr);
  1054. pairPtr->mParams[idx] = genericParam;
  1055. }
  1056. };
  1057. _GetParams(0, newMethodInstance);
  1058. _GetParams(1, prevMethodInstance);
  1059. for (auto kv : externConstraints)
  1060. {
  1061. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(kv.mValue.mParams[1], kv.mValue.mParams[0]), mModule->AreConstraintsSubset(kv.mValue.mParams[0], kv.mValue.mParams[1]));
  1062. }
  1063. if ((isBetter) || (isWorse))
  1064. {
  1065. RETURN_RESULTS;
  1066. }
  1067. }
  1068. // Does one have a body and one doesn't? Obvious!
  1069. isBetter = prevMethodDef->IsEmptyPartial();
  1070. isWorse = newMethodDef->IsEmptyPartial();
  1071. if ((isBetter) && (isWorse))
  1072. {
  1073. // If both are empty partials then just bind to either
  1074. isWorse = true;
  1075. RETURN_RESULTS;
  1076. }
  1077. // For extensions, select the version in the most-specific project (only applicable for ctors)
  1078. if ((!isBetter) && (!isWorse))
  1079. {
  1080. auto newProject = newMethodDef->mDeclaringType->mProject;
  1081. auto prevProject = prevMethodDef->mDeclaringType->mProject;
  1082. if (newProject != prevProject)
  1083. {
  1084. RETURN_BETTER_OR_WORSE(newProject->ContainsReference(prevProject), prevProject->ContainsReference(newProject));
  1085. }
  1086. }
  1087. // If we have conditional type extensions that both define an implementation for a method, use the most-specific conditional extension constraints
  1088. auto owner = newMethodInstance->GetOwner();
  1089. if ((newMethodDef->mDeclaringType != prevMethodDef->mDeclaringType) && (owner->IsGenericTypeInstance()))
  1090. {
  1091. auto genericOwner = (BfTypeInstance*)owner;
  1092. if (genericOwner->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  1093. {
  1094. BfGenericExtensionEntry* newGenericExtesionEntry = NULL;
  1095. BfGenericExtensionEntry* prevGenericExtesionEntry = NULL;
  1096. if ((genericOwner->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.TryGetValue(newMethodDef->mDeclaringType, &newGenericExtesionEntry)) &&
  1097. (genericOwner->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.TryGetValue(prevMethodDef->mDeclaringType, &prevGenericExtesionEntry)))
  1098. {
  1099. if ((newGenericExtesionEntry->mGenericParams.size() == prevGenericExtesionEntry->mGenericParams.size()))
  1100. {
  1101. for (int genericParamIdx = 0; genericParamIdx < (int)newGenericExtesionEntry->mGenericParams.size(); genericParamIdx++)
  1102. {
  1103. auto newMethodGenericParam = newGenericExtesionEntry->mGenericParams[genericParamIdx];
  1104. auto prevMethodGenericParam = prevGenericExtesionEntry->mGenericParams[genericParamIdx];
  1105. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  1106. }
  1107. }
  1108. if ((isBetter) || (isWorse))
  1109. {
  1110. RETURN_RESULTS;
  1111. }
  1112. }
  1113. }
  1114. }
  1115. RETURN_BETTER_OR_WORSE(newMethodDef->mCheckedKind == mCheckedKind, prevMethodDef->mCheckedKind == mCheckedKind);
  1116. RETURN_BETTER_OR_WORSE(newMethodDef->mAppendKind == mAllowAppendKind, prevMethodDef->mAppendKind == mAllowAppendKind);
  1117. RETURN_BETTER_OR_WORSE(newMethodDef->mCommutableKind != BfCommutableKind_Reverse, prevMethodDef->mCommutableKind != BfCommutableKind_Reverse);
  1118. // If one of these methods is local to the current extension then choose that one
  1119. auto activeDef = mModule->GetActiveTypeDef();
  1120. RETURN_BETTER_OR_WORSE(newMethodDef->mDeclaringType == activeDef, prevMethodDef->mDeclaringType == activeDef);
  1121. RETURN_BETTER_OR_WORSE(newMethodDef->mDeclaringType->IsExtension(), prevMethodDef->mDeclaringType->IsExtension());
  1122. RETURN_BETTER_OR_WORSE(newMethodDef->mIsMutating, prevMethodDef->mIsMutating);
  1123. if (newMethodDef->mHasComptime != prevMethodDef->mHasComptime)
  1124. {
  1125. bool isComptime = (mModule->mIsComptimeModule) || ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  1126. RETURN_BETTER_OR_WORSE(newMethodDef->mHasComptime == isComptime, prevMethodDef->mHasComptime == isComptime);
  1127. }
  1128. RETURN_RESULTS;
  1129. }
  1130. BfTypedValue BfMethodMatcher::ResolveArgTypedValue(BfResolvedArg& resolvedArg, BfType* checkType, BfTypeVector* genericArgumentsSubstitute, BfType *origCheckType, BfResolveArgFlags flags)
  1131. {
  1132. BfTypedValue argTypedValue = resolvedArg.mTypedValue;
  1133. if ((resolvedArg.mArgFlags & BfArgFlag_DelegateBindAttempt) != 0)
  1134. {
  1135. BfExprEvaluator exprEvaluator(mModule);
  1136. exprEvaluator.mExpectingType = checkType;
  1137. BF_ASSERT(resolvedArg.mExpression->IsA<BfDelegateBindExpression>());
  1138. auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(resolvedArg.mExpression);
  1139. BfMethodInstance* boundMethodInstance = NULL;
  1140. auto bindType = checkType;
  1141. if ((bindType == NULL) && (origCheckType != NULL) && (!origCheckType->IsUnspecializedTypeVariation()))
  1142. bindType = checkType;
  1143. if (exprEvaluator.CanBindDelegate(delegateBindExpr, &boundMethodInstance, bindType, genericArgumentsSubstitute))
  1144. {
  1145. if (delegateBindExpr->mNewToken == NULL)
  1146. {
  1147. if (boundMethodInstance->GetOwner()->IsFunction())
  1148. {
  1149. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), boundMethodInstance->GetOwner());
  1150. }
  1151. else if ((boundMethodInstance->mDisallowCalling) || ((flags & BfResolveArgFlag_FromGeneric) == 0))
  1152. {
  1153. argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), checkType);
  1154. }
  1155. else
  1156. {
  1157. resolvedArg.mExpectedType = checkType;
  1158. auto methodRefType = mModule->CreateMethodRefType(boundMethodInstance);
  1159. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  1160. mModule->AddCallDependency(boundMethodInstance);
  1161. argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodRefType);
  1162. }
  1163. }
  1164. else
  1165. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1166. }
  1167. }
  1168. else if ((resolvedArg.mArgFlags & BfArgFlag_LambdaBindAttempt) != 0)
  1169. {
  1170. if ((argTypedValue) && (argTypedValue.mType->IsMethodRef()) &&
  1171. ((checkType == NULL) || (!checkType->IsMethodRef())))
  1172. {
  1173. // This may be from a previous checkMethod, clear it out
  1174. argTypedValue = BfTypedValue();
  1175. }
  1176. BfExprEvaluator exprEvaluator(mModule);
  1177. exprEvaluator.mExpectingType = checkType;
  1178. BF_ASSERT(resolvedArg.mExpression->IsA<BfLambdaBindExpression>());
  1179. auto lambdaBindExpr = (BfLambdaBindExpression*)resolvedArg.mExpression;
  1180. if ((checkType != NULL) && (checkType->IsDelegate()))
  1181. {
  1182. BfMethodInstance* methodInstance = mModule->GetRawMethodInstanceAtIdx(checkType->ToTypeInstance(), 0, "Invoke");
  1183. if (methodInstance != NULL)
  1184. {
  1185. if (methodInstance->GetParamCount() == (int)lambdaBindExpr->mParams.size())
  1186. {
  1187. if (lambdaBindExpr->mNewToken == NULL)
  1188. {
  1189. if (!resolvedArg.mTypedValue)
  1190. {
  1191. // Resolve for real
  1192. resolvedArg.mTypedValue = mModule->CreateValueFromExpression(lambdaBindExpr, checkType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_NoAutoComplete));
  1193. }
  1194. argTypedValue = resolvedArg.mTypedValue;
  1195. }
  1196. else
  1197. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1198. //argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), checkType);
  1199. }
  1200. }
  1201. }
  1202. else if ((checkType == NULL) && (origCheckType != NULL) && (origCheckType->IsUnspecializedTypeVariation()) && (genericArgumentsSubstitute != NULL) && (origCheckType->IsDelegateOrFunction()))
  1203. {
  1204. BfMethodInstance* methodInstance = mModule->GetRawMethodInstanceAtIdx(origCheckType->ToTypeInstance(), 0, "Invoke");
  1205. if (methodInstance != NULL)
  1206. {
  1207. if ((methodInstance->mReturnType->IsGenericParam()) && (((BfGenericParamType*)methodInstance->mReturnType)->mGenericParamKind == BfGenericParamKind_Method))
  1208. {
  1209. bool isValid = true;
  1210. int returnMethodGenericArgIdx = ((BfGenericParamType*)methodInstance->mReturnType)->mGenericParamIdx;
  1211. if ((*genericArgumentsSubstitute)[returnMethodGenericArgIdx] != NULL)
  1212. {
  1213. isValid = false;
  1214. }
  1215. if (methodInstance->mParams.size() != (int)lambdaBindExpr->mParams.size())
  1216. isValid = false;
  1217. for (auto& param : methodInstance->mParams)
  1218. {
  1219. if (param.mResolvedType->IsGenericParam())
  1220. {
  1221. auto genericParamType = (BfGenericParamType*)param.mResolvedType;
  1222. if ((genericParamType->mGenericParamKind == BfGenericParamKind_Method) && ((*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx] == NULL))
  1223. {
  1224. isValid = false;
  1225. }
  1226. }
  1227. }
  1228. if (isValid)
  1229. {
  1230. bool success = false;
  1231. (*genericArgumentsSubstitute)[returnMethodGenericArgIdx] = mModule->GetPrimitiveType(BfTypeCode_None);
  1232. auto tryType = mModule->ResolveGenericType(origCheckType, NULL, genericArgumentsSubstitute, mModule->mCurTypeInstance);
  1233. if (tryType != NULL)
  1234. {
  1235. auto inferredReturnType = mModule->CreateValueFromExpression(lambdaBindExpr, tryType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_InferReturnType | BfEvalExprFlags_NoAutoComplete));
  1236. if (inferredReturnType.mType != NULL)
  1237. {
  1238. (*genericArgumentsSubstitute)[returnMethodGenericArgIdx] = inferredReturnType.mType;
  1239. if (((flags & BfResolveArgFlag_FromGenericParam) != 0) && (lambdaBindExpr->mNewToken == NULL))
  1240. {
  1241. auto resolvedType = mModule->ResolveGenericType(origCheckType, NULL, genericArgumentsSubstitute, mModule->mCurTypeInstance);
  1242. if (resolvedType != NULL)
  1243. {
  1244. // Resolve for real
  1245. resolvedArg.mTypedValue = mModule->CreateValueFromExpression(lambdaBindExpr, resolvedType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_NoAutoComplete));
  1246. argTypedValue = resolvedArg.mTypedValue;
  1247. }
  1248. }
  1249. success = true;
  1250. }
  1251. }
  1252. if (!success)
  1253. {
  1254. // Put back
  1255. (*genericArgumentsSubstitute)[returnMethodGenericArgIdx] = NULL;
  1256. }
  1257. }
  1258. }
  1259. }
  1260. }
  1261. }
  1262. else if ((resolvedArg.mArgFlags & BfArgFlag_UnqualifiedDotAttempt) != 0)
  1263. {
  1264. if ((checkType != NULL) && (checkType->IsPayloadEnum()))
  1265. {
  1266. // Should we actually check the member name?
  1267. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1268. }
  1269. }
  1270. else if ((resolvedArg.mArgFlags & BfArgFlag_UntypedDefault) != 0)
  1271. {
  1272. if (checkType != NULL)
  1273. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1274. }
  1275. else if ((resolvedArg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  1276. {
  1277. if (resolvedArg.mExpression != NULL)
  1278. {
  1279. if ((resolvedArg.mExpectedType != checkType) || (resolvedArg.mExpectedType == NULL)) // Did our last check match for this type?
  1280. {
  1281. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  1282. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  1283. bool prevNoBind = false;
  1284. if (mModule->mCurMethodState != NULL)
  1285. {
  1286. prevNoBind = mModule->mCurMethodState->mNoBind;
  1287. mModule->mCurMethodState->mNoBind = true;
  1288. }
  1289. auto prevBlock = mModule->mBfIRBuilder->GetInsertBlock();
  1290. BfExprEvaluator exprEvaluator(mModule);
  1291. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags);
  1292. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowIntUnknown | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_NoAutoComplete);
  1293. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1294. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  1295. auto expectType = checkType;
  1296. if (expectType != NULL)
  1297. {
  1298. if (expectType->IsRef())
  1299. {
  1300. auto refType = (BfRefType*)expectType;
  1301. expectType = refType->mElementType;
  1302. }
  1303. if ((genericArgumentsSubstitute != NULL) && (expectType->IsUnspecializedType()))
  1304. expectType = mModule->ResolveGenericType(expectType, NULL, genericArgumentsSubstitute, mModule->mCurTypeInstance, true);
  1305. }
  1306. exprEvaluator.mExpectingType = expectType;
  1307. exprEvaluator.Evaluate(resolvedArg.mExpression);
  1308. argTypedValue = exprEvaluator.GetResult();
  1309. if ((argTypedValue) && (argTypedValue.mType->IsVar()))
  1310. argTypedValue = BfTypedValue();
  1311. if (mModule->mCurMethodState != NULL)
  1312. mModule->mCurMethodState->mNoBind = prevNoBind;
  1313. if ((argTypedValue) && (!argTypedValue.mType->IsVar()))
  1314. {
  1315. if (checkType != NULL)
  1316. resolvedArg.mExpectedType = checkType;
  1317. auto storeTypedValue = argTypedValue;
  1318. if ((storeTypedValue.mValue) & (!storeTypedValue.mValue.IsFake()))
  1319. {
  1320. // We actually want to ensure that this cached value is a fake val. There are potential cases where a fake val
  1321. // won't be generated but we should throw an error, so we need to make sure we actually re-evaluate when the call
  1322. // is generated
  1323. //storeTypedValue.mValue = mModule->mBfIRBuilder->GetFakeVal();
  1324. resolvedArg.mWantsRecalc = true;
  1325. }
  1326. resolvedArg.mTypedValue = storeTypedValue;
  1327. //BF_ASSERT(argTypedValue.mValue.mId != -1);
  1328. }
  1329. mModule->mBfIRBuilder->SetInsertPoint(prevBlock);
  1330. }
  1331. }
  1332. }
  1333. else if ((resolvedArg.mArgFlags & BfArgFlag_VariableDeclaration) != 0)
  1334. {
  1335. if ((checkType != NULL) && (checkType->IsRef()))
  1336. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1337. }
  1338. return argTypedValue;
  1339. }
  1340. bool BfMethodMatcher::WantsCheckMethod(BfProtectionCheckFlags& flags, BfTypeInstance* startTypeInstance, BfTypeInstance* checkTypeInstance, BfMethodDef* checkMethod)
  1341. {
  1342. MatchFailKind matchFailKind = MatchFailKind_None;
  1343. if (!mModule->CheckProtection(flags, checkTypeInstance, checkMethod->mDeclaringType->mProject, checkMethod->mProtection, startTypeInstance))
  1344. {
  1345. if ((mBypassVirtual) &&
  1346. ((checkMethod->mProtection == BfProtection_Protected) || (checkMethod->mProtection == BfProtection_ProtectedInternal)) &&
  1347. (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, startTypeInstance)))
  1348. {
  1349. // Allow explicit 'base' call
  1350. }
  1351. else
  1352. {
  1353. return false;
  1354. }
  1355. }
  1356. if (mCheckedKind != checkMethod->mCheckedKind)
  1357. {
  1358. bool passes = true;
  1359. if (mCheckedKind != BfCheckedKind_NotSet)
  1360. {
  1361. passes = false;
  1362. }
  1363. else
  1364. {
  1365. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  1366. if (defaultCheckedKind != checkMethod->mCheckedKind)
  1367. passes = false;
  1368. }
  1369. if (!passes)
  1370. {
  1371. return false;
  1372. }
  1373. }
  1374. return true;
  1375. }
  1376. bool BfMethodMatcher::InferFromGenericConstraints(BfMethodInstance* methodInstance, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs)
  1377. {
  1378. if (!genericParamInst->mExternType->IsGenericParam())
  1379. return false;
  1380. auto genericParamType = (BfGenericParamType*)genericParamInst->mExternType;
  1381. if (genericParamType->mGenericParamKind != BfGenericParamKind_Method)
  1382. return false;
  1383. BfType* checkArgType = NULL;
  1384. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  1385. {
  1386. auto leftType = checkOpConstraint.mLeftType;
  1387. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  1388. leftType = mModule->ResolveGenericType(leftType, NULL, methodGenericArgs, mModule->mCurTypeInstance);
  1389. if (leftType != NULL)
  1390. leftType = mModule->FixIntUnknown(leftType);
  1391. auto rightType = checkOpConstraint.mRightType;
  1392. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  1393. rightType = mModule->ResolveGenericType(rightType, NULL, methodGenericArgs, mModule->mCurTypeInstance);
  1394. if (rightType != NULL)
  1395. rightType = mModule->FixIntUnknown(rightType);
  1396. BfConstraintState constraintSet;
  1397. constraintSet.mPrevState = mModule->mContext->mCurConstraintState;
  1398. constraintSet.mGenericParamInstance = genericParamInst;
  1399. constraintSet.mLeftType = leftType;
  1400. constraintSet.mRightType = rightType;
  1401. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mModule->mContext->mCurConstraintState, &constraintSet);
  1402. if (!mModule->CheckConstraintState(NULL))
  1403. return false;
  1404. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  1405. {
  1406. if ((leftType == NULL) || (rightType == NULL))
  1407. continue;
  1408. BfExprEvaluator exprEvaluator(mModule);
  1409. BfTypedValue leftValue(mModule->mBfIRBuilder->GetFakeVal(), leftType);
  1410. BfTypedValue rightValue(mModule->mBfIRBuilder->GetFakeVal(), rightType);
  1411. //
  1412. {
  1413. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  1414. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  1415. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, BfBinOpFlag_NoClassify, leftValue, rightValue);
  1416. }
  1417. if (exprEvaluator.mResult)
  1418. checkArgType = exprEvaluator.mResult.mType;
  1419. }
  1420. else
  1421. {
  1422. if (rightType == NULL)
  1423. continue;
  1424. BfTypedValue rightValue(mModule->mBfIRBuilder->GetFakeVal(), rightType);
  1425. StringT<128> failedOpName;
  1426. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  1427. {
  1428. }
  1429. else
  1430. {
  1431. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  1432. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  1433. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  1434. {
  1435. }
  1436. else
  1437. {
  1438. BfExprEvaluator exprEvaluator(mModule);
  1439. exprEvaluator.mResult = rightValue;
  1440. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  1441. if (exprEvaluator.mResult)
  1442. checkArgType = exprEvaluator.mResult.mType;
  1443. }
  1444. }
  1445. }
  1446. }
  1447. if ((checkArgType == NULL) && ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_ComptypeExpr) != 0))
  1448. {
  1449. for (auto comptypeConstraint : genericParamInst->mComptypeConstraint)
  1450. {
  1451. checkArgType = mModule->ResolveGenericMethodTypeRef(comptypeConstraint, methodInstance, genericParamInst, methodGenericArgs);
  1452. if (checkArgType == NULL)
  1453. return false;
  1454. }
  1455. }
  1456. if (checkArgType == NULL)
  1457. return false;
  1458. if (checkArgType->IsVar())
  1459. return false;
  1460. (*methodGenericArgs)[genericParamType->mGenericParamIdx] = checkArgType;
  1461. return true;
  1462. }
  1463. bool BfMethodMatcher::CheckMethod(BfTypeInstance* targetTypeInstance, BfTypeInstance* typeInstance, BfMethodDef* checkMethod, bool isFailurePass)
  1464. {
  1465. BP_ZONE("BfMethodMatcher::CheckMethod");
  1466. BackupMatchKind curMatchKind = BackupMatchKind_None;
  1467. bool hadMatch = false;
  1468. // Never consider overrides - they only get found at original method declaration
  1469. // mBypassVirtual gets set when we are doing an explicit "base" call, or when we are a struct --
  1470. // because on structs we know the exact type
  1471. if ((checkMethod->mIsOverride) && (!mBypassVirtual) && (!typeInstance->IsValueType()))
  1472. return false;
  1473. mMethodCheckCount++;
  1474. BfMethodInstance* methodInstance = mModule->GetRawMethodInstance(typeInstance, checkMethod);
  1475. if (methodInstance == NULL)
  1476. return false;
  1477. BfMethodInstance* typeUnspecMethodInstance = mModule->GetUnspecializedMethodInstance(methodInstance, true);
  1478. BfTypeVector* typeGenericArguments = NULL;
  1479. if (typeInstance->mGenericTypeInfo != NULL)
  1480. typeGenericArguments = &typeInstance->mGenericTypeInfo->mTypeGenericArguments;
  1481. if ((mInterfaceMethodInstance != NULL) && (methodInstance->GetExplicitInterface() != NULL))
  1482. {
  1483. BfTypeInstance* wantInterface = mInterfaceMethodInstance->mMethodInstanceGroup->mOwner;
  1484. if (wantInterface != methodInstance->GetExplicitInterface())
  1485. return false;
  1486. }
  1487. if ((checkMethod->mIsVirtual) && (!checkMethod->mIsOverride) && (!mBypassVirtual) &&
  1488. (targetTypeInstance != NULL) && (targetTypeInstance->IsObject()))
  1489. {
  1490. mModule->PopulateType(targetTypeInstance, BfPopulateType_DataAndMethods);
  1491. if ((methodInstance->mVirtualTableIdx < targetTypeInstance->mVirtualMethodTable.mSize) && (methodInstance->mVirtualTableIdx >= 0))
  1492. {
  1493. BfVirtualMethodEntry& vEntry = targetTypeInstance->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  1494. if ((vEntry.mImplementingMethod.mTypeInstance != NULL) && (vEntry.mImplementingMethod.mTypeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted) &&
  1495. (mModule->mCompiler->IsAutocomplete()))
  1496. {
  1497. // Silently ignore
  1498. }
  1499. else
  1500. {
  1501. auto implMethod = (BfMethodInstance*)vEntry.mImplementingMethod;
  1502. if ((implMethod != methodInstance) && (implMethod != NULL))
  1503. {
  1504. SetAndRestoreValue<bool> prevBypassVirtual(mBypassVirtual, true);
  1505. return CheckMethod(targetTypeInstance, implMethod->GetOwner(), implMethod->mMethodDef, isFailurePass);
  1506. }
  1507. }
  1508. }
  1509. else
  1510. {
  1511. // Being in autocomplete mode is the only excuse for not having the virtual method table slotted
  1512. if ((!mModule->mCompiler->IsAutocomplete()) && (!targetTypeInstance->mTypeFailed) && (!targetTypeInstance->IsUnspecializedTypeVariation()))
  1513. {
  1514. mModule->AssertErrorState();
  1515. }
  1516. }
  1517. }
  1518. BfGenericInferContext genericInferContext;
  1519. genericInferContext.mModule = mModule;
  1520. genericInferContext.mCheckMethodGenericArguments = &mCheckMethodGenericArguments;
  1521. HashSet<int> allowEmptyGenericSet;
  1522. BfAutoComplete* autoComplete = NULL;
  1523. if ((mModule->mCompiler->mResolvePassData != NULL) && (!isFailurePass) && ((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) == 0))
  1524. autoComplete = mModule->mCompiler->mResolvePassData->mAutoComplete;
  1525. if (checkMethod->mMethodType != BfMethodType_Extension)
  1526. {
  1527. if (((checkMethod->mIsStatic) && (!mAllowStatic)) ||
  1528. ((!checkMethod->mIsStatic) && (!mAllowNonStatic)))
  1529. {
  1530. if (!typeInstance->IsFunction())
  1531. autoComplete = NULL;
  1532. }
  1533. }
  1534. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1535. {
  1536. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  1537. methodMatchEntry.mMethodDef = checkMethod;
  1538. methodMatchEntry.mTypeInstance = typeInstance;
  1539. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  1540. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  1541. }
  1542. BfTypeVector* genericArgumentsSubstitute = NULL;
  1543. int argIdx = 0;
  1544. int argMatchCount = 0;
  1545. bool needInferGenericParams = (checkMethod->mGenericParams.size() != 0) &&
  1546. ((!mHadExplicitGenericArguments) || (mHadPartialGenericArguments));
  1547. int paramIdx = 0;
  1548. BfType* paramsElementType = NULL;
  1549. if (checkMethod->HasAppend())
  1550. paramIdx++;
  1551. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(checkMethod);
  1552. if (mHadExplicitGenericArguments)
  1553. {
  1554. int genericArgDelta = (int)(checkMethod->mGenericParams.size() - (mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx));
  1555. if (mHadOpenGenericArguments)
  1556. {
  1557. if (genericArgDelta <= 0)
  1558. goto NoMatch;
  1559. }
  1560. else
  1561. {
  1562. if (genericArgDelta != 0)
  1563. goto NoMatch;
  1564. }
  1565. }
  1566. for (auto& checkGenericArgRef : mCheckMethodGenericArguments)
  1567. checkGenericArgRef = NULL;
  1568. mCheckMethodGenericArguments.resize(checkMethod->mGenericParams.size());
  1569. for (auto& genericArgRef : mCheckMethodGenericArguments)
  1570. genericArgRef = NULL;
  1571. if (mHadExplicitGenericArguments)
  1572. {
  1573. if (uniqueGenericStartIdx > 0)
  1574. {
  1575. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1576. mCheckMethodGenericArguments.clear();
  1577. mCheckMethodGenericArguments.reserve(mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx);
  1578. for (int i = 0; i < uniqueGenericStartIdx; i++)
  1579. mCheckMethodGenericArguments.Add(NULL);
  1580. for (int i = 0; i < (int)mExplicitMethodGenericArguments.size(); i++)
  1581. mCheckMethodGenericArguments.Add(mExplicitMethodGenericArguments[i]);
  1582. }
  1583. else
  1584. {
  1585. genericArgumentsSubstitute = &mExplicitMethodGenericArguments;
  1586. }
  1587. if ((mHadPartialGenericArguments) && (needInferGenericParams))
  1588. {
  1589. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1590. for (int i = 0; i < (int)mExplicitMethodGenericArguments.mSize; i++)
  1591. mCheckMethodGenericArguments[i] = mExplicitMethodGenericArguments[i];
  1592. }
  1593. }
  1594. else if (needInferGenericParams)
  1595. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1596. if (mHasArgNames)
  1597. {
  1598. checkMethod->BuildParamNameMap();
  1599. bool prevWasNull = false;
  1600. for (int argIdx = (int)mArguments.mSize - 1; argIdx >= 0; argIdx--)
  1601. {
  1602. auto& arg = mArguments[argIdx];
  1603. if (arg.mNameNode != NULL)
  1604. {
  1605. if (prevWasNull)
  1606. {
  1607. if (argIdx >= checkMethod->mParams.mSize)
  1608. goto NoMatch;
  1609. if (checkMethod->mParams[argIdx]->mName != arg.mNameNode->ToStringView())
  1610. goto NoMatch;
  1611. }
  1612. else
  1613. {
  1614. if (!checkMethod->mParamNameMap->ContainsKey(arg.mNameNode->ToStringView()))
  1615. goto NoMatch;
  1616. }
  1617. prevWasNull = false;
  1618. }
  1619. else
  1620. {
  1621. prevWasNull = true;
  1622. }
  1623. }
  1624. }
  1625. if ((checkMethod->mIsMutating) && (targetTypeInstance != NULL) && (targetTypeInstance->IsValueType()) &&
  1626. ((mTarget.IsReadOnly()) || (!mTarget.IsAddr())) &&
  1627. (!targetTypeInstance->IsValuelessType()))
  1628. {
  1629. goto NoMatch;
  1630. }
  1631. if (mSkipImplicitParams)
  1632. {
  1633. //paramOfs = methodInstance->GetImplicitParamCount();
  1634. //paramIdx += paramOfs;
  1635. }
  1636. if (needInferGenericParams)
  1637. {
  1638. genericInferContext.mPrevArgValues.resize(checkMethod->mGenericParams.size());
  1639. int paramOfs = methodInstance->GetImplicitParamCount();
  1640. int paramCount = methodInstance->GetParamCount();
  1641. SizedArray<int, 8> deferredArgs;
  1642. int argIdx = 0;
  1643. int paramIdx = 0;
  1644. if (checkMethod->HasAppend())
  1645. paramIdx++;
  1646. if (checkMethod->mMethodType == BfMethodType_Extension)
  1647. {
  1648. argIdx--;
  1649. }
  1650. paramIdx += paramOfs;
  1651. bool hadInferFailure = false;
  1652. int inferParamOffset = paramOfs - argIdx;
  1653. int paramsParamIdx = -1;
  1654. enum ResultKind
  1655. {
  1656. ResultKind_Ok,
  1657. ResultKind_Failed,
  1658. ResultKind_Deferred,
  1659. };
  1660. auto _CheckArg = [&](int argIdx)
  1661. {
  1662. paramIdx = argIdx + inferParamOffset;
  1663. if ((paramsParamIdx != -1) && (paramIdx > paramsParamIdx))
  1664. paramIdx = paramsParamIdx;
  1665. auto wantType = methodInstance->GetParamType(paramIdx);
  1666. auto checkType = wantType;
  1667. auto origCheckType = checkType;
  1668. if (checkType->IsGenericParam())
  1669. {
  1670. BfGenericParamInstance* genericParamInstance = NULL;
  1671. auto genericParamType = (BfGenericParamType*)checkType;
  1672. checkType = NULL;
  1673. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1674. {
  1675. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  1676. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  1677. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1678. }
  1679. else
  1680. genericParamInstance = mModule->GetGenericParamInstance(genericParamType);
  1681. if (checkType == NULL)
  1682. {
  1683. checkType = genericParamInstance->mTypeConstraint;
  1684. origCheckType = checkType; // We can do "ResolveGenericType" on this type
  1685. }
  1686. }
  1687. bool attemptedGenericResolve = false;
  1688. if ((checkType != NULL) && (genericArgumentsSubstitute != NULL) && (checkType->IsUnspecializedType()))
  1689. {
  1690. attemptedGenericResolve = true;
  1691. checkType = mModule->ResolveGenericType(origCheckType, NULL, genericArgumentsSubstitute, mModule->mCurTypeInstance);
  1692. }
  1693. if (wantType->IsUnspecializedType())
  1694. {
  1695. BfTypedValue argTypedValue;
  1696. if (argIdx == -1)
  1697. {
  1698. if (mOrigTarget)
  1699. argTypedValue = mOrigTarget;
  1700. else
  1701. argTypedValue = mTarget;
  1702. }
  1703. else
  1704. {
  1705. BfResolveArgFlags flags = BfResolveArgFlag_FromGeneric;
  1706. if (wantType->IsGenericParam())
  1707. flags = (BfResolveArgFlags)(flags | BfResolveArgFlag_FromGenericParam);
  1708. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], checkType, genericArgumentsSubstitute, origCheckType, flags);
  1709. }
  1710. if (!argTypedValue.IsUntypedValue())
  1711. {
  1712. auto type = argTypedValue.mType;
  1713. if (!argTypedValue)
  1714. {
  1715. if ((checkType == NULL) && (attemptedGenericResolve) && (genericInferContext.GetUnresolvedCount() >= 2))
  1716. {
  1717. deferredArgs.Add(argIdx);
  1718. return ResultKind_Deferred;
  1719. }
  1720. return ResultKind_Failed;
  1721. }
  1722. if (type->IsVar())
  1723. mHasVarArguments = true;
  1724. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_Params)
  1725. {
  1726. if ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1727. {
  1728. // Match to entire thing
  1729. }
  1730. else
  1731. {
  1732. paramsParamIdx = paramIdx;
  1733. if ((wantType->IsArray()) || (wantType->IsSizedArray()) || (wantType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  1734. wantType = wantType->GetUnderlyingType();
  1735. }
  1736. }
  1737. if (!genericInferContext.InferGenericArgument(methodInstance, type, wantType, argTypedValue.mValue))
  1738. return ResultKind_Failed;
  1739. }
  1740. }
  1741. return ResultKind_Ok;
  1742. };
  1743. for (; argIdx < (int)mArguments.size(); argIdx++)
  1744. {
  1745. paramIdx = argIdx + inferParamOffset;
  1746. if ((paramIdx >= paramCount) && (paramsParamIdx == -1))
  1747. break; // Possible for delegate 'params' type methods
  1748. auto resultKind = _CheckArg(argIdx);
  1749. if (resultKind == ResultKind_Failed)
  1750. goto NoMatch;
  1751. }
  1752. if ((methodInstance->mParams.mSize > 0) && (methodInstance->GetParamKind(methodInstance->mParams.mSize - 1) == BfParamKind_Params))
  1753. {
  1754. // Handle `params int[C]` generic sized array params case
  1755. auto paramsType = methodInstance->GetParamType(methodInstance->mParams.mSize - 1);
  1756. if (paramsType->IsUnknownSizedArrayType())
  1757. {
  1758. auto unknownSizedArray = (BfUnknownSizedArrayType*)paramsType;
  1759. if (unknownSizedArray->mElementCountSource->IsMethodGenericParam())
  1760. {
  1761. auto genericParam = (BfGenericParamType*)unknownSizedArray->mElementCountSource;
  1762. if ((*genericArgumentsSubstitute)[genericParam->mGenericParamIdx] == NULL)
  1763. {
  1764. int paramsCount = (int)mArguments.mSize - inferParamOffset;
  1765. (*genericArgumentsSubstitute)[genericParam->mGenericParamIdx] = mModule->CreateConstExprValueType(
  1766. BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, paramsCount), mModule->GetPrimitiveType(BfTypeCode_IntPtr)));
  1767. }
  1768. }
  1769. }
  1770. else if (paramsType->IsParamsType())
  1771. {
  1772. paramsType = paramsType->GetUnderlyingType();
  1773. if (paramsType->IsGenericParam())
  1774. {
  1775. auto genericParamType = (BfGenericParamType*)paramsType;
  1776. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1777. {
  1778. auto genericParamInst = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1779. if ((genericParamInst->mTypeConstraint != NULL) && (genericParamInst->mTypeConstraint->IsInstanceOf(mModule->mCompiler->mTupleTypeDef)))
  1780. {
  1781. bool isValid = true;
  1782. BfTypeVector genericArgs;
  1783. for (int argIdx = methodInstance->mParams.mSize - 1 - inferParamOffset; argIdx < (int)mArguments.size(); argIdx++)
  1784. {
  1785. BfTypedValue argTypedValue = ResolveArgTypedValue(mArguments[argIdx], NULL, genericArgumentsSubstitute);
  1786. if (!argTypedValue)
  1787. {
  1788. isValid = false;
  1789. break;
  1790. }
  1791. genericArgs.Add(mModule->FixIntUnknown(argTypedValue.mType));
  1792. }
  1793. if (isValid)
  1794. {
  1795. (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx] = mModule->CreateTupleType(genericArgs, SubstituteList());
  1796. }
  1797. }
  1798. }
  1799. }
  1800. }
  1801. }
  1802. if (!deferredArgs.IsEmpty())
  1803. {
  1804. genericInferContext.InferGenericArguments(methodInstance);
  1805. }
  1806. while (!deferredArgs.IsEmpty())
  1807. {
  1808. int prevDeferredSize = (int)deferredArgs.size();
  1809. for (int i = 0; i < prevDeferredSize; i++)
  1810. {
  1811. auto resultKind = _CheckArg(deferredArgs[i]);
  1812. if (resultKind == ResultKind_Failed)
  1813. goto NoMatch;
  1814. }
  1815. deferredArgs.RemoveRange(0, prevDeferredSize);
  1816. if (prevDeferredSize == deferredArgs.size())
  1817. {
  1818. // No progress
  1819. goto NoMatch;
  1820. }
  1821. }
  1822. //
  1823. {
  1824. int paramIdx = (int)mArguments.size() + paramOfs;
  1825. while (paramIdx < checkMethod->mParams.size())
  1826. {
  1827. if ((paramIdx < methodInstance->mDefaultValues.size()) && (methodInstance->mDefaultValues[paramIdx]))
  1828. {
  1829. auto wantType = methodInstance->GetParamType(paramIdx);
  1830. auto checkType = wantType;
  1831. if (checkType->IsGenericParam())
  1832. {
  1833. BfGenericParamInstance* genericParamInstance = NULL;
  1834. auto genericParamType = (BfGenericParamType*)checkType;
  1835. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1836. {
  1837. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  1838. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  1839. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1840. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  1841. {
  1842. if (mCheckMethodGenericArguments[genericParamType->mGenericParamIdx] == NULL)
  1843. allowEmptyGenericSet.Add(genericParamType->mGenericParamIdx);
  1844. }
  1845. }
  1846. }
  1847. }
  1848. paramIdx++;
  1849. }
  1850. }
  1851. if ((mCheckReturnType != NULL) && (methodInstance->mReturnType->IsUnspecializedType()))
  1852. {
  1853. if (!genericInferContext.InferGenericArgument(methodInstance, mCheckReturnType, methodInstance->mReturnType, BfIRValue()))
  1854. return ResultKind_Failed;
  1855. }
  1856. bool failed = false;
  1857. bool inferredAllGenericArguments = false;
  1858. for (int pass = 0; true; pass++)
  1859. {
  1860. bool madeProgress = false;
  1861. bool hasUninferred = false;
  1862. failed = false;
  1863. for (int genericArgIdx = uniqueGenericStartIdx; genericArgIdx < (int)checkMethod->mGenericParams.size(); genericArgIdx++)
  1864. {
  1865. if (genericArgIdx >= mCheckMethodGenericArguments.mSize)
  1866. {
  1867. failed = true;
  1868. }
  1869. else
  1870. {
  1871. auto& genericArg = mCheckMethodGenericArguments[genericArgIdx];
  1872. if (genericArg == NULL)
  1873. {
  1874. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericArgIdx];
  1875. InferFromGenericConstraints(methodInstance, genericParam, &mCheckMethodGenericArguments);
  1876. if (genericArg != NULL)
  1877. {
  1878. if (inferredAllGenericArguments)
  1879. genericInferContext.InferGenericArguments(methodInstance, genericArgIdx);
  1880. madeProgress = true;
  1881. }
  1882. hasUninferred = true;
  1883. if (!allowEmptyGenericSet.Contains(genericArgIdx))
  1884. failed = true;
  1885. }
  1886. }
  1887. }
  1888. if (!hasUninferred)
  1889. break;
  1890. if (inferredAllGenericArguments)
  1891. {
  1892. if (!madeProgress)
  1893. break;
  1894. }
  1895. genericInferContext.InferGenericArguments(methodInstance);
  1896. inferredAllGenericArguments = true;
  1897. }
  1898. if (failed)
  1899. goto NoMatch;
  1900. }
  1901. if (checkMethod->mMethodType == BfMethodType_Extension)
  1902. argIdx--;
  1903. // Iterate through params
  1904. while (true)
  1905. {
  1906. // Too many arguments
  1907. if (paramIdx >= (int)methodInstance->GetParamCount())
  1908. {
  1909. break;
  1910. }
  1911. bool isDeferredEval = false;
  1912. if ((argIdx >= 0) && (methodInstance->GetParamKind(paramIdx) == BfParamKind_Params) && (paramsElementType == NULL))
  1913. {
  1914. if (argIdx >= (int) mArguments.size())
  1915. break; // No params
  1916. BfTypedValue argTypedValue = ResolveArgTypedValue(mArguments[argIdx], NULL, genericArgumentsSubstitute);
  1917. if (!argTypedValue)
  1918. goto NoMatch;
  1919. if ((!argTypedValue.HasType()) && (!mArguments[argIdx].IsDeferredEval()))
  1920. goto NoMatch;
  1921. auto paramsArrayType = methodInstance->GetParamType(paramIdx);
  1922. paramsArrayType = mModule->ResolveGenericType(paramsArrayType, NULL, genericArgumentsSubstitute, mModule->mCurTypeInstance);
  1923. if (paramsArrayType == NULL)
  1924. goto NoMatch;
  1925. if ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1926. {
  1927. // Direct-pass params
  1928. if ((argTypedValue.IsUntypedValue()) || (mModule->CanCast(argTypedValue, paramsArrayType)))
  1929. {
  1930. argIdx++;
  1931. argMatchCount++;
  1932. paramIdx++;
  1933. break;
  1934. }
  1935. goto NoMatch;
  1936. }
  1937. if ((paramsArrayType->IsArray()) || (paramsArrayType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  1938. {
  1939. paramsElementType = paramsArrayType->GetUnderlyingType();
  1940. while (argIdx < (int)mArguments.size())
  1941. {
  1942. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], paramsElementType, genericArgumentsSubstitute);
  1943. if (!argTypedValue.HasType())
  1944. goto NoMatch;
  1945. BfCastFlags castFlags = ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp) != 0) ? BfCastFlags_NoConversionOperator : BfCastFlags_None;
  1946. if ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp_Explicit) != 0)
  1947. castFlags = (BfCastFlags)(castFlags | BfCastFlags_Explicit);
  1948. if (!mModule->CanCast(argTypedValue, paramsElementType, castFlags))
  1949. goto NoMatch;
  1950. argIdx++;
  1951. argMatchCount++;
  1952. }
  1953. }
  1954. else
  1955. goto NoMatch;
  1956. break;
  1957. }
  1958. if (methodInstance->IsImplicitCapture(paramIdx))
  1959. {
  1960. paramIdx++;
  1961. continue;
  1962. }
  1963. if (argIdx >= (int) mArguments.size())
  1964. {
  1965. // We have defaults the rest of the way, so that's cool
  1966. if (methodInstance->GetParamInitializer(paramIdx) != NULL)
  1967. break;
  1968. // We have unused params left over
  1969. goto NoMatch;
  1970. }
  1971. auto wantType = methodInstance->GetParamType(paramIdx);
  1972. if ((genericArgumentsSubstitute != NULL) && (wantType->IsUnspecializedType()))
  1973. {
  1974. wantType = typeUnspecMethodInstance->GetParamType(paramIdx);
  1975. auto resolvedType = mModule->ResolveGenericType(wantType, typeGenericArguments, genericArgumentsSubstitute, mModule->mCurTypeInstance, false);
  1976. if (resolvedType == NULL)
  1977. goto NoMatch;
  1978. wantType = resolvedType;
  1979. }
  1980. wantType = mModule->ResolveSelfType(wantType, typeInstance);
  1981. if ((argIdx >= 0) && ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0))
  1982. {
  1983. // We had a 'params' expression but this method didn't have a params slot in this parameter
  1984. goto NoMatch;
  1985. }
  1986. BfTypedValue argTypedValue;
  1987. if (argIdx == -1)
  1988. argTypedValue = mTarget;
  1989. else
  1990. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], wantType, genericArgumentsSubstitute);
  1991. if (!argTypedValue.IsUntypedValue())
  1992. {
  1993. if (!argTypedValue.HasType())
  1994. {
  1995. // Check to see if this is the last argument and that it's a potential enum match
  1996. if ((wantType->IsEnum()) && (argIdx == mArguments.size() - 1))
  1997. {
  1998. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(mArguments[argIdx].mExpression))
  1999. {
  2000. if (memberRefExpr->mTarget == NULL)
  2001. {
  2002. // Is dot expression
  2003. curMatchKind = BackupMatchKind_PartialLastArgMatch;
  2004. }
  2005. }
  2006. }
  2007. bool matches = false;
  2008. if (wantType->IsOut())
  2009. {
  2010. if (auto memberRefExpr = BfNodeDynCast<BfUninitializedExpression>(mArguments[argIdx].mExpression))
  2011. matches = true;
  2012. }
  2013. if (!matches)
  2014. goto NoMatch;
  2015. }
  2016. else
  2017. {
  2018. if ((checkMethod->mMethodType == BfMethodType_Extension) && (argIdx == -1))
  2019. {
  2020. if ((wantType->IsRef()) && (!argTypedValue.mType->IsRef()))
  2021. wantType = wantType->GetUnderlyingType();
  2022. }
  2023. if ((wantType->IsRef()) && (!argTypedValue.mType->IsRef()) &&
  2024. ((mAllowImplicitRef) || (wantType->IsIn())))
  2025. wantType = wantType->GetUnderlyingType();
  2026. BfCastFlags castFlags = ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp) != 0) ? BfCastFlags_NoConversionOperator : BfCastFlags_None;
  2027. if ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp_Explicit) != 0)
  2028. castFlags = (BfCastFlags)(castFlags | BfCastFlags_Explicit);
  2029. if ((mCheckReturnType != NULL) && (wantType->IsVar()))
  2030. {
  2031. // If we allowed this then it would allow too many matches (and allow conversion from any type during CastToValue)
  2032. goto NoMatch;
  2033. }
  2034. if (!mModule->CanCast(argTypedValue, wantType, castFlags))
  2035. {
  2036. if ((argIdx == -1) && (wantType->IsWrappableType()) && (mModule->GetWrappedStructType(wantType) == argTypedValue.mType))
  2037. {
  2038. // Extension target can be wrapped
  2039. }
  2040. else if ((mAllowImplicitWrap) && (argTypedValue.mType->IsWrappableType()) && (mModule->GetWrappedStructType(argTypedValue.mType) == wantType))
  2041. {
  2042. // Is wrapped type
  2043. }
  2044. else
  2045. goto NoMatch;
  2046. }
  2047. }
  2048. }
  2049. paramIdx++;
  2050. argIdx++;
  2051. argMatchCount++;
  2052. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  2053. {
  2054. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  2055. if (!methodMatchInfo->mHadExactMatch)
  2056. {
  2057. bool isBetter = false;
  2058. bool isWorse = false;
  2059. int methodIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  2060. if ((methodMatchInfo->mBestIdx != -1) && (methodMatchInfo->mBestIdx < (int)methodMatchInfo->mInstanceList.size()))
  2061. {
  2062. auto prevMethodMatchEntry = &methodMatchInfo->mInstanceList[methodMatchInfo->mBestIdx];
  2063. if (checkMethod->mParams.size() < mArguments.size())
  2064. {
  2065. isWorse = true;
  2066. }
  2067. else if ((prevMethodMatchEntry->mMethodDef != NULL) && (prevMethodMatchEntry->mMethodDef->mParams.size() < (int) mArguments.size()))
  2068. {
  2069. isBetter = true;
  2070. }
  2071. }
  2072. }
  2073. }
  2074. }
  2075. // Too many arguments (not all incoming arguments processed)
  2076. if (argIdx < (int)mArguments.size())
  2077. {
  2078. if (!methodInstance->IsVarArgs())
  2079. goto NoMatch;
  2080. }
  2081. if (mCheckReturnType != NULL)
  2082. {
  2083. auto returnType = methodInstance->mReturnType;
  2084. if (returnType->IsVar())
  2085. {
  2086. // If we allowed this then it would allow too many matches (and allow conversion to any type during CastToValue)
  2087. goto NoMatch;
  2088. }
  2089. bool doFullTypeResolve = false;
  2090. if (returnType->IsUnspecializedTypeVariation())
  2091. {
  2092. returnType = typeUnspecMethodInstance->mReturnType;
  2093. doFullTypeResolve = true;
  2094. }
  2095. if ((genericArgumentsSubstitute != NULL) && (returnType->IsUnspecializedType()))
  2096. doFullTypeResolve = true;
  2097. if (doFullTypeResolve)
  2098. {
  2099. auto resolvedType = mModule->ResolveGenericType(returnType, typeGenericArguments, genericArgumentsSubstitute, mModule->mCurTypeInstance, false);
  2100. if (resolvedType == NULL)
  2101. goto NoMatch;
  2102. returnType = resolvedType;
  2103. }
  2104. returnType = mModule->ResolveSelfType(returnType, typeInstance);
  2105. BfCastFlags castFlags = ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp) != 0) ? (BfCastFlags)(BfCastFlags_NoConversionOperator | BfCastFlags_NoInterfaceImpl) : BfCastFlags_None;
  2106. if ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp_Explicit) != 0)
  2107. castFlags = (BfCastFlags)(castFlags | BfCastFlags_Explicit);
  2108. if (!mModule->CanCast(mModule->GetFakeTypedValue(returnType), mCheckReturnType, castFlags))
  2109. goto NoMatch;
  2110. }
  2111. if ((genericArgumentsSubstitute != NULL) && (genericArgumentsSubstitute->size() != 0))
  2112. {
  2113. for (int checkGenericIdx = uniqueGenericStartIdx; checkGenericIdx < (int)genericArgumentsSubstitute->size(); checkGenericIdx++)
  2114. {
  2115. auto& genericParams = methodInstance->mMethodInfoEx->mGenericParams;
  2116. auto genericArg = (*genericArgumentsSubstitute)[checkGenericIdx];
  2117. if (genericArg == NULL)
  2118. {
  2119. if (allowEmptyGenericSet.Contains(checkGenericIdx))
  2120. continue;
  2121. goto NoMatch;
  2122. }
  2123. if (genericArg == NULL)
  2124. goto NoMatch;
  2125. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericArg, NULL, genericParams[checkGenericIdx], genericArgumentsSubstitute, NULL))
  2126. goto NoMatch;
  2127. }
  2128. }
  2129. for (int externConstraintIdx = 0; externConstraintIdx < (int)checkMethod->mExternalConstraints.size(); externConstraintIdx++)
  2130. {
  2131. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[checkMethod->mGenericParams.size() + externConstraintIdx];
  2132. BF_ASSERT(genericParam->mExternType != NULL);
  2133. auto externType = genericParam->mExternType;
  2134. BfTypeVector* externGenericArgumentsSubstitute = genericArgumentsSubstitute;
  2135. if (externType->IsVar())
  2136. {
  2137. auto& externConstraint = checkMethod->mExternalConstraints[externConstraintIdx];
  2138. if (externConstraint.mTypeRef != NULL)
  2139. {
  2140. externType = mModule->ResolveGenericMethodTypeRef(externConstraint.mTypeRef, methodInstance, genericParam, genericArgumentsSubstitute);
  2141. if (externType == NULL)
  2142. goto NoMatch;
  2143. }
  2144. }
  2145. if (externType->IsGenericParam())
  2146. {
  2147. auto genericParamType = (BfGenericParamType*)externType;
  2148. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  2149. {
  2150. if (genericArgumentsSubstitute != NULL)
  2151. {
  2152. auto genericArg = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  2153. if (genericArg == NULL)
  2154. {
  2155. if (allowEmptyGenericSet.Contains(genericParamType->mGenericParamIdx))
  2156. continue;
  2157. goto NoMatch;
  2158. }
  2159. externType = genericArg;
  2160. }
  2161. }
  2162. }
  2163. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), externType, NULL, genericParam, externGenericArgumentsSubstitute, NULL))
  2164. goto NoMatch;
  2165. }
  2166. // if (auto methodDecl = BfNodeDynCast<BfMethodDeclaration>(checkMethod->mMethodDeclaration))
  2167. // {
  2168. // if ((methodDecl->mGenericConstraintsDeclaration != NULL) && (methodDecl->mGenericConstraintsDeclaration->mHasExpressions))
  2169. // {
  2170. // for (auto genericConstraint : methodDecl->mGenericConstraintsDeclaration->mGenericConstraints)
  2171. // {
  2172. // if (auto genericConstraintExpr = BfNodeDynCast<BfGenericConstraintExpression>(genericConstraint))
  2173. // {
  2174. // if (genericConstraintExpr->mExpression == NULL)
  2175. // continue;
  2176. // BfConstResolver constResolver(mModule);
  2177. // constResolver.mExpectingType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  2178. // constResolver.Resolve(genericConstraintExpr->mExpression, constResolver.mExpectingType);
  2179. // }
  2180. // }
  2181. // }
  2182. // }
  2183. // Method is applicable, check to see which method is better
  2184. if (mBestMethodDef != NULL)
  2185. {
  2186. bool isBetter = false;
  2187. bool isWorse = false;
  2188. BfMethodInstance* prevMethodInstance = mModule->GetRawMethodInstance(mBestMethodTypeInstance, mBestMethodDef);
  2189. bool allowSpecializeFail = mModule->mCurTypeInstance->IsUnspecializedType();
  2190. if (mModule->mCurMethodInstance != NULL)
  2191. allowSpecializeFail = mModule->mCurMethodInstance->mIsUnspecialized;
  2192. CompareMethods(prevMethodInstance, &mBestMethodGenericArguments, methodInstance, genericArgumentsSubstitute, &isBetter, &isWorse, allowSpecializeFail);
  2193. // If we had both a 'better' and 'worse', that's ambiguous because the methods are each better in different ways (not allowed)
  2194. // And if neither better nor worse then they are equally good, which is not allowed either
  2195. if (((!isBetter) && (!isWorse)) || ((isBetter) && (isWorse)))
  2196. {
  2197. if (!mHasVarArguments)
  2198. {
  2199. // If we are ambiguous based on a subset of an extern 'var' constraint then don't throw an error
  2200. auto _CheckMethodInfo = [&](BfMethodInstance* checkMethodInstance)
  2201. {
  2202. if (checkMethodInstance->mMethodInfoEx == NULL)
  2203. return;
  2204. for (auto genericParam : checkMethodInstance->mMethodInfoEx->mGenericParams)
  2205. {
  2206. if ((genericParam->mExternType == NULL) || (!genericParam->mExternType->IsGenericParam()))
  2207. continue;
  2208. auto genericParamType = (BfGenericParamType*)genericParam->mExternType;
  2209. if (genericParamType->mGenericParamKind != BfGenericParamKind_Type)
  2210. continue;
  2211. auto externGenericParam = mModule->GetGenericParamInstance(genericParamType);
  2212. if ((externGenericParam->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  2213. mHasVarArguments = true;
  2214. }
  2215. };
  2216. _CheckMethodInfo(methodInstance);
  2217. _CheckMethodInfo(prevMethodInstance);
  2218. }
  2219. if (mHasVarArguments)
  2220. {
  2221. if (methodInstance->mReturnType != prevMethodInstance->mReturnType)
  2222. mHadVarConflictingReturnType = true;
  2223. }
  2224. else
  2225. {
  2226. BfAmbiguousEntry ambiguousEntry;
  2227. ambiguousEntry.mMethodInstance = methodInstance;
  2228. if (genericArgumentsSubstitute != NULL)
  2229. ambiguousEntry.mBestMethodGenericArguments = *genericArgumentsSubstitute;
  2230. if (methodInstance->mMethodDef->mGenericParams.size() != 0)
  2231. {
  2232. BF_ASSERT(!ambiguousEntry.mBestMethodGenericArguments.empty());
  2233. }
  2234. mAmbiguousEntries.push_back(ambiguousEntry);
  2235. goto Done;
  2236. }
  2237. }
  2238. if (!isBetter)
  2239. goto Done;
  2240. }
  2241. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  2242. {
  2243. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  2244. // Try to persist with previous partial match, if we have one - this keeps us from locking onto
  2245. // an incorrect method just because it had the current number of params that we've typed so far
  2246. if (methodMatchInfo->mPrevBestIdx == -1)
  2247. {
  2248. methodMatchInfo->mHadExactMatch = true;
  2249. methodMatchInfo->mBestIdx = (int) methodMatchInfo->mInstanceList.size() - 1;
  2250. }
  2251. }
  2252. mAmbiguousEntries.Clear();
  2253. hadMatch = true;
  2254. mBestMethodDef = checkMethod;
  2255. mBestRawMethodInstance = methodInstance;
  2256. for (auto& arg : mArguments)
  2257. arg.mBestBoundType = arg.mTypedValue.mType;
  2258. NoMatch:
  2259. if (!hadMatch)
  2260. {
  2261. if (mBestMethodDef != NULL)
  2262. return false;
  2263. if (checkMethod->mMethodType == BfMethodType_Extension)
  2264. {
  2265. auto thisParam = methodInstance->GetParamType(0);
  2266. auto resolveThisParam = mModule->ResolveGenericType(thisParam, NULL, &mCheckMethodGenericArguments, mModule->mCurTypeInstance);
  2267. if (resolveThisParam == NULL)
  2268. return false;
  2269. if (!mModule->CanCast(mTarget, resolveThisParam,
  2270. ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp) != 0) ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_NoConversionOperator) : BfCastFlags_Explicit))
  2271. return false;
  2272. }
  2273. if (mBackupMethodDef != NULL)
  2274. {
  2275. int prevParamDiff = (int)mBackupMethodDef->GetExplicitParamCount() - (int)mArguments.size();
  2276. int paramDiff = (int)checkMethod->GetExplicitParamCount() - (int)mArguments.size();
  2277. if ((prevParamDiff < 0) && (prevParamDiff > paramDiff))
  2278. return false;
  2279. if ((prevParamDiff >= 0) && (paramDiff < 0))
  2280. return false;
  2281. if (argMatchCount < mBackupArgMatchCount)
  2282. return false;
  2283. else if (argMatchCount == mBackupArgMatchCount)
  2284. {
  2285. if (curMatchKind < mBackupMatchKind)
  2286. return false;
  2287. // We search from the most specific type, so don't prefer a less specific type
  2288. if (mBestMethodTypeInstance != typeInstance)
  2289. return false;
  2290. }
  2291. }
  2292. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  2293. {
  2294. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  2295. if ((methodMatchInfo->mPrevBestIdx == -1) && (!methodMatchInfo->mHadExactMatch))
  2296. {
  2297. methodMatchInfo->mBestIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  2298. }
  2299. }
  2300. mBackupMatchKind = curMatchKind;
  2301. mBackupMethodDef = checkMethod;
  2302. mBackupArgMatchCount = argMatchCount;
  2303. // Lie temporarily to store at least one candidate (but mBestMethodDef is still NULL)
  2304. hadMatch = true;
  2305. }
  2306. if (hadMatch)
  2307. {
  2308. mBestMethodTypeInstance = typeInstance;
  2309. if (genericArgumentsSubstitute != &mBestMethodGenericArguments)
  2310. {
  2311. if (genericArgumentsSubstitute != NULL)
  2312. {
  2313. for (auto& genericArg : *genericArgumentsSubstitute)
  2314. genericArg = mModule->FixIntUnknown(genericArg);
  2315. mBestMethodGenericArguments = *genericArgumentsSubstitute;
  2316. // #ifdef _DEBUG
  2317. // for (auto arg : mBestMethodGenericArguments)
  2318. // BF_ASSERT((arg == NULL) || (!arg->IsVar()));
  2319. // #endif
  2320. }
  2321. else
  2322. mBestMethodGenericArguments.clear();
  2323. }
  2324. }
  2325. Done:
  2326. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  2327. {
  2328. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  2329. if (!methodMatchInfo->mInstanceList.IsEmpty())
  2330. {
  2331. auto& matchInstance = methodMatchInfo->mInstanceList[methodMatchInfo->mInstanceList.size() - 1];
  2332. matchInstance.mArgMatchCount = argMatchCount;
  2333. matchInstance.mIsMatch = hadMatch;
  2334. if (genericArgumentsSubstitute != NULL)
  2335. matchInstance.mGenericArguments = *genericArgumentsSubstitute;
  2336. }
  2337. }
  2338. return mBestMethodDef == checkMethod;
  2339. }
  2340. void BfMethodMatcher::FlushAmbiguityError(bool useWarning)
  2341. {
  2342. if (!mAmbiguousEntries.empty())
  2343. {
  2344. if (mModule->PreFail())
  2345. {
  2346. BfError* error;
  2347. if (!mMethodName.empty())
  2348. {
  2349. if (useWarning)
  2350. error = mModule->Warn(0, StrFormat("Ambiguous method call for '%s'", mMethodName.c_str()), mTargetSrc);
  2351. else
  2352. error = mModule->Fail(StrFormat("Ambiguous method call for '%s'", mMethodName.c_str()), mTargetSrc);
  2353. }
  2354. else
  2355. {
  2356. if (useWarning)
  2357. error = mModule->Warn(0, "Ambiguous method call", mTargetSrc);
  2358. else
  2359. error = mModule->Fail("Ambiguous method call", mTargetSrc);
  2360. }
  2361. if (error != NULL)
  2362. {
  2363. BfMethodInstance* bestMethodInstance = mModule->GetUnspecializedMethodInstance(mBestRawMethodInstance, true);
  2364. BfTypeVector* typeGenericArguments = NULL;
  2365. if (mBestMethodTypeInstance->mGenericTypeInfo != NULL)
  2366. typeGenericArguments = &mBestMethodTypeInstance->mGenericTypeInfo->mTypeGenericArguments;
  2367. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(bestMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  2368. typeGenericArguments, mBestMethodGenericArguments.empty() ? NULL : &mBestMethodGenericArguments).c_str()),
  2369. bestMethodInstance->mMethodDef->GetRefNode());
  2370. for (auto& ambiguousEntry : mAmbiguousEntries)
  2371. {
  2372. auto typeInstance = ambiguousEntry.mMethodInstance->GetOwner();
  2373. auto unspecTypeMethodInstance = mModule->GetUnspecializedMethodInstance(ambiguousEntry.mMethodInstance, true);
  2374. BfTypeVector* typeGenericArguments = NULL;
  2375. if (typeInstance->mGenericTypeInfo != NULL)
  2376. typeGenericArguments = &typeInstance->mGenericTypeInfo->mTypeGenericArguments;
  2377. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(unspecTypeMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  2378. typeGenericArguments, ambiguousEntry.mBestMethodGenericArguments.empty() ? NULL : &ambiguousEntry.mBestMethodGenericArguments).c_str()),
  2379. ambiguousEntry.mMethodInstance->mMethodDef->GetRefNode());
  2380. }
  2381. }
  2382. }
  2383. mAmbiguousEntries.Clear();
  2384. }
  2385. }
  2386. bool BfMethodMatcher::IsType(BfTypedValue& typedVal, BfType* type)
  2387. {
  2388. if (typedVal.mType == type)
  2389. return true;
  2390. if (!typedVal)
  2391. return false;
  2392. if (!typedVal.mType->IsPrimitiveType())
  2393. return false;
  2394. if (!type->IsPrimitiveType())
  2395. return false;
  2396. auto fromPrimType = typedVal.mType->ToPrimitiveType();
  2397. if ((fromPrimType->mTypeDef->mTypeCode != BfTypeCode_IntUnknown) &&
  2398. (fromPrimType->mTypeDef->mTypeCode != BfTypeCode_UIntUnknown))
  2399. return false;
  2400. auto constant = mModule->mBfIRBuilder->GetConstant(typedVal.mValue);
  2401. if (constant == NULL)
  2402. return false;
  2403. auto toPrimType = type->ToPrimitiveType();
  2404. if (!mModule->mBfIRBuilder->IsInt(toPrimType->mTypeDef->mTypeCode))
  2405. return false;
  2406. if (type->mSize == 8)
  2407. return false;
  2408. int64 minVal = -(1LL << (8 * type->mSize - 1));
  2409. int64 maxVal = (1LL << (8 * type->mSize - 1)) - 1;
  2410. if ((constant->mInt64 >= minVal) && (constant->mInt64 <= maxVal))
  2411. return true;
  2412. return false;
  2413. }
  2414. // This method checks all base classes before checking interfaces. Is that correct?
  2415. bool BfMethodMatcher::CheckType(BfTypeInstance* typeInstance, BfTypedValue target, bool isFailurePass, bool forceOuterCheck)
  2416. {
  2417. BfMethodDef* prevBestMethodDef = mBestMethodDef;
  2418. auto curTypeInst = typeInstance;
  2419. auto curTypeDef = typeInstance->mTypeDef;
  2420. int checkInterfaceIdx = 0;
  2421. bool targetIsBase = target.IsBase();
  2422. bool checkExtensionBase = false;
  2423. if (targetIsBase)
  2424. {
  2425. if ((curTypeInst == mModule->mCurTypeInstance) && (curTypeInst->mTypeDef->mIsCombinedPartial))
  2426. {
  2427. checkExtensionBase = true;
  2428. }
  2429. else
  2430. {
  2431. curTypeInst = curTypeInst->mBaseType;
  2432. }
  2433. }
  2434. BfTypeInstance* targetTypeInstance = NULL;
  2435. if (target.mType != NULL)
  2436. targetTypeInstance = target.mType->ToTypeInstance();
  2437. while (true)
  2438. {
  2439. bool doSearch = true;
  2440. if ((mMethodType == BfMethodType_Extension) && (!curTypeDef->mHasExtensionMethods))
  2441. doSearch = false;
  2442. BfMethodDef* nextMethodDef = NULL;
  2443. if (doSearch)
  2444. {
  2445. curTypeDef->PopulateMemberSets();
  2446. BfMemberSetEntry* entry;
  2447. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  2448. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  2449. }
  2450. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  2451. if (target)
  2452. {
  2453. if (mBypassVirtual)
  2454. {
  2455. // Not an "instance lookup"
  2456. }
  2457. else
  2458. {
  2459. protectionCheckFlags = (BfProtectionCheckFlags)(protectionCheckFlags | BfProtectionCheckFlag_InstanceLookup);
  2460. }
  2461. }
  2462. while (nextMethodDef != NULL)
  2463. {
  2464. bool allowExplicitInterface = curTypeInst->IsInterface() && mBypassVirtual;
  2465. auto activeTypeDef = mModule->GetActiveTypeDef();
  2466. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  2467. bool isDelegate = typeInstance->IsDelegate();
  2468. auto checkMethod = nextMethodDef;
  2469. nextMethodDef = nextMethodDef->mNextWithSameName;
  2470. if (mModule->mContext->mResolvingVarField)
  2471. {
  2472. bool isResolvingVarField = false;
  2473. auto checkTypeState = mModule->mContext->mCurTypeState;
  2474. while (checkTypeState != NULL)
  2475. {
  2476. if ((checkTypeState->mResolveKind == BfTypeState::ResolveKind_ResolvingVarType) &&
  2477. (checkTypeState->mType == typeInstance))
  2478. isResolvingVarField = true;
  2479. checkTypeState = checkTypeState->mPrevState;
  2480. }
  2481. if (isResolvingVarField)
  2482. {
  2483. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  2484. // Don't even consider - we can't do method calls on ourselves when we are resolving var fields, because
  2485. // we are not allowed to generate methods when our field types are unknown. We may fix this in the future,
  2486. // but currently it breaks out expected order of operations. One issue is that our call signatures change
  2487. // depending on whether we are valueless or splattable, which depend on underlying type information
  2488. break;
  2489. }
  2490. }
  2491. if ((checkExtensionBase) && (curTypeInst == mModule->mCurTypeInstance))
  2492. {
  2493. // Accept either a method in the same project but that's the root definition, OR a method that's in a dependent project
  2494. bool accept = false;
  2495. if (activeTypeDef->mProject == checkMethod->mDeclaringType->mProject)
  2496. accept = (activeTypeDef->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension());
  2497. else
  2498. accept = activeTypeDef->mProject->ContainsReference(checkMethod->mDeclaringType->mProject);
  2499. if (!accept)
  2500. continue;
  2501. }
  2502. if ((!allowExplicitInterface) && (checkMethod->mExplicitInterface != NULL) && (mInterfaceMethodInstance == NULL))
  2503. {
  2504. continue;
  2505. }
  2506. if (checkMethod->mMethodType != mMethodType)
  2507. continue;
  2508. // if (checkMethod->mName != mMethodName)
  2509. // continue;
  2510. if ((checkMethod->mDeclaringType->IsExtension()) && (mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) &&
  2511. (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoExtensionAttributeTypeDef)))
  2512. {
  2513. mModule->mAttributeState->mUsed = true;
  2514. continue;
  2515. }
  2516. if (!isDelegate)
  2517. {
  2518. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  2519. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, visibleProjectSet)))
  2520. continue;
  2521. }
  2522. MatchFailKind matchFailKind = MatchFailKind_None;
  2523. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkMethod->mDeclaringType->mProject, checkMethod->mProtection, typeInstance))
  2524. {
  2525. if ((mBypassVirtual) &&
  2526. ((checkMethod->mProtection == BfProtection_Protected) || (checkMethod->mProtection == BfProtection_ProtectedInternal)) &&
  2527. (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, typeInstance)))
  2528. {
  2529. // Allow explicit 'base' call
  2530. }
  2531. else
  2532. {
  2533. if (!isFailurePass)
  2534. continue;
  2535. matchFailKind = MatchFailKind_Protection;
  2536. }
  2537. }
  2538. if (mCheckedKind != checkMethod->mCheckedKind)
  2539. {
  2540. bool passes = true;
  2541. if (mCheckedKind != BfCheckedKind_NotSet)
  2542. {
  2543. passes = false;
  2544. }
  2545. else
  2546. {
  2547. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  2548. if (defaultCheckedKind != checkMethod->mCheckedKind)
  2549. passes = false;
  2550. }
  2551. if (!passes)
  2552. {
  2553. if (!isFailurePass)
  2554. continue;
  2555. matchFailKind = MatchFailKind_CheckedMismatch;
  2556. }
  2557. }
  2558. CheckMethod(targetTypeInstance, curTypeInst, checkMethod, isFailurePass);
  2559. if ((isFailurePass) &&
  2560. ((mBestMethodDef == checkMethod) || (mBackupMethodDef == checkMethod)))
  2561. mMatchFailKind = matchFailKind;
  2562. }
  2563. if ((mBestMethodDef != NULL) && (mMethodType != BfMethodType_Extension))
  2564. {
  2565. if ((mUsingLists != NULL) && (mUsingLists->mSize != 0))
  2566. mUsingLists->Clear();
  2567. if (mAutoFlushAmbiguityErrors)
  2568. FlushAmbiguityError();
  2569. return true;
  2570. }
  2571. if ((mUsingLists != NULL) && (curTypeInst->mTypeDef->mHasUsingFields))
  2572. mModule->PopulateUsingFieldData(curTypeInst);
  2573. if (mUsingLists != NULL)
  2574. {
  2575. auto _CheckUsingData = [&](BfUsingFieldData* usingData)
  2576. {
  2577. BfUsingFieldData::Entry* entry = NULL;
  2578. if (!usingData->mMethods.TryGetValue(mMethodName, &entry))
  2579. return;
  2580. for (int listIdx = 0; listIdx < entry->mLookups.mSize; listIdx++)
  2581. {
  2582. bool passesProtection = true;
  2583. auto& entryList = entry->mLookups[listIdx];
  2584. for (int entryIdx = 0; entryIdx < entryList.mSize; entryIdx++)
  2585. {
  2586. auto& entry = entryList[entryIdx];
  2587. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  2588. if (!mModule->CheckProtection(protectionCheckFlags, entry.mTypeInstance, entry.GetDeclaringType(mModule)->mProject,
  2589. (entryIdx < entryList.mSize - 1) ? entry.GetUsingProtection() : entry.GetProtection(), curTypeInst))
  2590. {
  2591. passesProtection = false;
  2592. break;
  2593. }
  2594. }
  2595. if (!passesProtection)
  2596. continue;
  2597. auto& entry = entryList.back();
  2598. BF_ASSERT(entry.mKind == BfUsingFieldData::MemberRef::Kind_Method);
  2599. auto methodDef = entry.mTypeInstance->mTypeDef->mMethods[entry.mIdx];
  2600. CheckMethod(curTypeInst, entry.mTypeInstance, methodDef, isFailurePass);
  2601. if ((mBestMethodDef != methodDef) && (mBackupMethodDef != methodDef))
  2602. {
  2603. bool foundAmbiguous = false;
  2604. for (int checkIdx = 0; checkIdx < mAmbiguousEntries.mSize; checkIdx++)
  2605. {
  2606. if (mAmbiguousEntries[checkIdx].mMethodInstance->mMethodDef == methodDef)
  2607. {
  2608. mAmbiguousEntries.RemoveAt(checkIdx);
  2609. foundAmbiguous = true;
  2610. break;
  2611. }
  2612. }
  2613. if (!foundAmbiguous)
  2614. continue;
  2615. }
  2616. if (mUsingLists->mSize == 0)
  2617. {
  2618. mUsingLists->Add(&entryList);
  2619. }
  2620. else
  2621. {
  2622. if (entryList.mSize < (*mUsingLists)[0]->mSize)
  2623. {
  2624. // New is shorter
  2625. mUsingLists->Clear();
  2626. mUsingLists->Add(&entryList);
  2627. }
  2628. else if (entryList.mSize > (*mUsingLists)[0]->mSize)
  2629. {
  2630. // Ignore longer
  2631. }
  2632. else
  2633. {
  2634. mUsingLists->Add(&entryList);
  2635. }
  2636. }
  2637. }
  2638. };
  2639. if ((curTypeInst->mTypeInfoEx != NULL) && (curTypeInst->mTypeInfoEx->mUsingFieldData != NULL))
  2640. _CheckUsingData(curTypeInst->mTypeInfoEx->mUsingFieldData);
  2641. if (mBestMethodDef != NULL)
  2642. break;
  2643. }
  2644. auto baseType = curTypeInst->mBaseType;
  2645. if (baseType == NULL)
  2646. {
  2647. //TODO: Why were we doing the interface checking?
  2648. if ((curTypeInst->IsInterface()) && (curTypeInst == target.mType))
  2649. {
  2650. // When we are directly calling on interfaces rather than indirectly matching through binding
  2651. baseType = mModule->mContext->mBfObjectType;
  2652. }
  2653. else if ((curTypeInst != mModule->mContext->mBfObjectType) && (!curTypeInst->IsInterface()))
  2654. {
  2655. // This can happen for structs
  2656. baseType = mModule->mContext->mBfObjectType;
  2657. }
  2658. else if ((typeInstance->IsInterface()) && (checkInterfaceIdx < (int)typeInstance->mInterfaces.size()))
  2659. {
  2660. baseType = typeInstance->mInterfaces[checkInterfaceIdx].mInterfaceType;
  2661. checkInterfaceIdx++;
  2662. }
  2663. else
  2664. {
  2665. break;
  2666. }
  2667. }
  2668. curTypeDef = baseType->mTypeDef;
  2669. curTypeInst = baseType;
  2670. if ((isFailurePass) && (mBackupMethodDef != NULL))
  2671. break;
  2672. }
  2673. if (mBestMethodDef == NULL)
  2674. {
  2675. // FAILED, but select the first method which will fire an actual error on param type matching
  2676. mBestMethodDef = mBackupMethodDef;
  2677. }
  2678. if (((mBestMethodDef == NULL) && (!target) && (mAllowImplicitThis)) ||
  2679. (forceOuterCheck))
  2680. {
  2681. // No explicit target - maybe this was a static call in the outer type?
  2682. auto outerType = mModule->GetOuterType(typeInstance);
  2683. if (outerType != NULL)
  2684. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  2685. }
  2686. if (mAutoFlushAmbiguityErrors)
  2687. FlushAmbiguityError();
  2688. return mBestMethodDef != prevBestMethodDef;
  2689. }
  2690. void BfMethodMatcher::TryDevirtualizeCall(BfTypedValue target, BfTypedValue* origTarget, BfTypedValue* staticResult)
  2691. {
  2692. if ((mBestMethodDef == NULL) || (target.mType == NULL))
  2693. return;
  2694. if ((mModule->mCompiler->IsAutocomplete()) || (mModule->mContext->mResolvingVarField))
  2695. return;
  2696. if ((mModule->mBfIRBuilder->mIgnoreWrites) && (!mBestMethodDef->mIsConcrete) && (!mBestMethodTypeInstance->IsInterface()))
  2697. return;
  2698. if (mBestMethodTypeInstance->IsInterface())
  2699. {
  2700. mModule->PopulateType(mBestMethodTypeInstance, BfPopulateType_DataAndMethods);
  2701. auto activeTypeDef = mModule->GetActiveTypeDef();
  2702. // Statically map this call
  2703. auto checkType = target.mType;
  2704. if (checkType->IsPointer())
  2705. checkType = ((BfPointerType*)checkType)->mElementType;
  2706. if (checkType->IsWrappableType())
  2707. checkType = mModule->GetWrappedStructType(checkType);
  2708. if ((checkType != NULL) && (checkType->IsTypeInstance()) && (!checkType->IsInterface()))
  2709. {
  2710. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  2711. auto checkTypeInst = checkType->ToTypeInstance();
  2712. if (mBestMethodTypeInstance->IsInstanceOf(mModule->mCompiler->mIHashableTypeDef))
  2713. {
  2714. if ((origTarget != NULL) && (origTarget->mType->IsPointer()) && (staticResult != NULL))
  2715. {
  2716. BfTypedValue ptrVal = mModule->LoadValue(*origTarget);
  2717. *staticResult = BfTypedValue(mModule->mBfIRBuilder->CreatePtrToInt(ptrVal.mValue, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  2718. return;
  2719. }
  2720. }
  2721. while (checkTypeInst != NULL)
  2722. {
  2723. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  2724. if (checkTypeInst->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted)
  2725. {
  2726. for (auto&& iface : checkTypeInst->mInterfaces)
  2727. {
  2728. //TODO: Why did we have this check? This caused Dictionary to not be able to devirtualize
  2729. // calls to TKey GetHashCode when TKey was from a user's project...
  2730. /*if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  2731. continue;*/
  2732. if (iface.mInterfaceType == mBestMethodTypeInstance)
  2733. {
  2734. if (bestIFaceEntry == NULL)
  2735. {
  2736. bestIFaceEntry = &iface;
  2737. continue;
  2738. }
  2739. bool isBetter;
  2740. bool isWorse;
  2741. mModule->CompareDeclTypes(NULL, iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  2742. if (isBetter == isWorse)
  2743. {
  2744. // Failed
  2745. }
  2746. else
  2747. {
  2748. if (isBetter)
  2749. bestIFaceEntry = &iface;
  2750. }
  2751. }
  2752. }
  2753. }
  2754. if (bestIFaceEntry != NULL)
  2755. break;
  2756. checkTypeInst = checkTypeInst->mBaseType;
  2757. if ((checkTypeInst == NULL) && (checkType->HasWrappedRepresentation()))
  2758. {
  2759. auto underlyingType = checkType->GetUnderlyingType();
  2760. if ((underlyingType != NULL) && (underlyingType->IsWrappableType()))
  2761. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  2762. if (checkTypeInst == checkType)
  2763. break;
  2764. }
  2765. }
  2766. if (bestIFaceEntry != NULL)
  2767. {
  2768. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + mBestMethodDef->mIdx];
  2769. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  2770. if (bestMethodInstance != NULL)
  2771. {
  2772. bool isMissingArg = false;
  2773. for (auto genericArg : mBestMethodGenericArguments)
  2774. {
  2775. if (genericArg == NULL)
  2776. isMissingArg = true;
  2777. }
  2778. if (!isMissingArg)
  2779. {
  2780. // Assert error state?
  2781. mBestMethodTypeInstance = ifaceMethodEntry.mMethodRef.mTypeInstance;
  2782. mBestMethodDef = bestMethodInstance->mMethodDef;
  2783. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, bestMethodInstance->mMethodDef, mBestMethodGenericArguments,
  2784. bestMethodInstance->mIsForeignMethodDef ? BfGetMethodInstanceFlag_ForeignMethodDef : BfGetMethodInstanceFlag_None,
  2785. bestMethodInstance->GetForeignType());
  2786. }
  2787. }
  2788. else
  2789. {
  2790. // Failed
  2791. mFakeConcreteTarget = true;
  2792. }
  2793. }
  2794. }
  2795. }
  2796. if ((target.mType->IsValueType()) && (mBestMethodTypeInstance->IsObject()) && (mBestMethodDef->mIsVirtual))
  2797. {
  2798. auto structType = target.mType->ToTypeInstance();
  2799. if (structType == NULL)
  2800. {
  2801. mModule->InternalError("Invalid type in TryDevirtualizeCall");
  2802. return;
  2803. }
  2804. auto virtualMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, mBestMethodDef, BfTypeVector());
  2805. BF_ASSERT(virtualMethodInstance.mMethodInstance->mVirtualTableIdx != -1);
  2806. BfTypeInstance* boxedType;
  2807. if (structType->HasOverrideMethods())
  2808. {
  2809. // We don't actually need this boxed type, so just resolve it unreified
  2810. auto useModule = mModule->mContext->mUnreifiedModule;
  2811. boxedType = useModule->CreateBoxedType(target.mType);
  2812. useModule->PopulateType(boxedType, BfPopulateType_DataAndMethods);
  2813. useModule->AddDependency(boxedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_WeakReference);
  2814. }
  2815. else
  2816. {
  2817. boxedType = mModule->mContext->mBfObjectType;
  2818. }
  2819. auto methodRef = boxedType->mVirtualMethodTable[virtualMethodInstance.mMethodInstance->mVirtualTableIdx];
  2820. if (methodRef.mImplementingMethod.mTypeInstance->IsBoxed())
  2821. {
  2822. auto useModule = mModule->mContext->mUnreifiedModule;
  2823. auto boxedMethodInstance = useModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  2824. BfBoxedType* vBoxedType = (BfBoxedType*)methodRef.mImplementingMethod.mTypeInstance;
  2825. mBestMethodTypeInstance = vBoxedType->mElementType->ToTypeInstance();
  2826. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, boxedMethodInstance.mMethodInstance->mMethodDef, BfTypeVector());
  2827. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  2828. }
  2829. else
  2830. {
  2831. mBestMethodTypeInstance = methodRef.mImplementingMethod.mTypeInstance;
  2832. mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  2833. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  2834. }
  2835. mBypassVirtual = true;
  2836. }
  2837. }
  2838. bool BfMethodMatcher::HasVarGenerics()
  2839. {
  2840. for (auto genericArg : mBestMethodGenericArguments)
  2841. if (genericArg->IsVar())
  2842. return true;
  2843. for (auto genericArg : mExplicitMethodGenericArguments)
  2844. if (genericArg->IsVar())
  2845. return true;
  2846. return false;
  2847. }
  2848. void BfMethodMatcher::CheckOuterTypeStaticMethods(BfTypeInstance* typeInstance, bool isFailurePass)
  2849. {
  2850. bool allowPrivate = true;
  2851. bool allowProtected = true;
  2852. auto curTypeInst = typeInstance;
  2853. auto curTypeDef = typeInstance->mTypeDef;
  2854. while (true)
  2855. {
  2856. curTypeDef->PopulateMemberSets();
  2857. BfMethodDef* nextMethodDef = NULL;
  2858. BfMemberSetEntry* entry;
  2859. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  2860. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  2861. while (nextMethodDef != NULL)
  2862. {
  2863. auto checkMethod = nextMethodDef;
  2864. nextMethodDef = nextMethodDef->mNextWithSameName;
  2865. // These can only be invoked when the target itself is the interface
  2866. if (checkMethod->mExplicitInterface != NULL)
  2867. continue;
  2868. if ((checkMethod->mMethodType != mMethodType) || (!checkMethod->mIsStatic))
  2869. continue;
  2870. if (checkMethod->mName != mMethodName)
  2871. continue;
  2872. if ((!isFailurePass) && (!mModule->CheckProtection(checkMethod->mProtection, NULL, allowProtected, allowPrivate)))
  2873. continue;
  2874. CheckMethod(typeInstance, curTypeInst, checkMethod, isFailurePass);
  2875. }
  2876. if (mBestMethodDef != NULL)
  2877. return;
  2878. auto baseType = curTypeInst->mBaseType;
  2879. if (baseType == NULL)
  2880. break;
  2881. curTypeDef = baseType->mTypeDef;
  2882. curTypeInst = baseType;
  2883. allowPrivate = false;
  2884. if ((isFailurePass) && (mBackupMethodDef != NULL))
  2885. break;
  2886. }
  2887. if (mBestMethodDef == NULL)
  2888. {
  2889. // FAILED, but select the first method which will fire an actual error on param type matching
  2890. mBestMethodDef = mBackupMethodDef;
  2891. }
  2892. if (mBestMethodDef == NULL)
  2893. {
  2894. // No explicit target - maybe this was a static call in the outer type?
  2895. auto outerType = mModule->GetOuterType(typeInstance);
  2896. if (outerType != NULL)
  2897. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  2898. }
  2899. }
  2900. //////////////////////////////////////////////////////////////////////////
  2901. void BfResolvedArgs::HandleFixits(BfModule* module)
  2902. {
  2903. auto compiler = module->mCompiler;
  2904. if ((!compiler->IsAutocomplete()) || (compiler->mResolvePassData->mResolveType != BfResolveType_GetFixits))
  2905. return;
  2906. SetAndRestoreValue<bool> ignoreErrors(module->mIgnoreErrors, true);
  2907. for (int argIdx = 0; argIdx < (int)mResolvedArgs.size(); argIdx++)
  2908. {
  2909. auto& resolvedArg = mResolvedArgs[argIdx];
  2910. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  2911. if (expr != NULL)
  2912. {
  2913. module->CreateValueFromExpression(expr, resolvedArg.mExpectedType);
  2914. }
  2915. }
  2916. }
  2917. //////////////////////////////////////////////////////////////////////////
  2918. BfExprEvaluator::BfExprEvaluator(BfModule* module)
  2919. {
  2920. mBfEvalExprFlags = BfEvalExprFlags_None;
  2921. mModule = module;
  2922. mPropDef = NULL;
  2923. mPropSrc = NULL;
  2924. mPropGetMethodFlags = BfGetMethodInstanceFlag_None;
  2925. mPropCheckedKind = BfCheckedKind_NotSet;
  2926. mUsedAsStatement = false;
  2927. mPropDefBypassVirtual = false;
  2928. mExpectingType = NULL;
  2929. mFunctionBindResult = NULL;
  2930. mExplicitCast = false;
  2931. mDeferCallData = NULL;
  2932. mPrefixedAttributeState = NULL;
  2933. mResolveGenericParam = true;
  2934. mNoBind = false;
  2935. mResultLocalVar = NULL;
  2936. mResultFieldInstance = NULL;
  2937. mResultLocalVarField = 0;
  2938. mResultLocalVarFieldCount = 0;
  2939. mResultLocalVarRefNode = NULL;
  2940. mIsVolatileReference = false;
  2941. mIsHeapReference = false;
  2942. mResultIsTempComposite = false;
  2943. mAllowReadOnlyReference = false;
  2944. mInsidePendingNullable = false;
  2945. mReceivingValue = NULL;
  2946. }
  2947. BfExprEvaluator::~BfExprEvaluator()
  2948. {
  2949. }
  2950. BfAutoComplete* BfExprEvaluator::GetAutoComplete()
  2951. {
  2952. if (mModule->mCompiler->mResolvePassData == NULL)
  2953. return NULL;
  2954. if ((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) != 0)
  2955. return NULL;
  2956. // For local methods- only process autocomplete on capture phase
  2957. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  2958. return NULL;
  2959. // if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod))
  2960. // return NULL;
  2961. return mModule->mCompiler->mResolvePassData->mAutoComplete;
  2962. }
  2963. bool BfExprEvaluator::IsComptime()
  2964. {
  2965. return (mModule->mIsComptimeModule) || ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  2966. }
  2967. bool BfExprEvaluator::IsConstEval()
  2968. {
  2969. return ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  2970. }
  2971. bool BfExprEvaluator::IsComptimeEntry()
  2972. {
  2973. if (mModule->mIsComptimeModule)
  2974. return false;
  2975. return ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  2976. }
  2977. int BfExprEvaluator::GetStructRetIdx(BfMethodInstance* methodInstance, bool forceStatic)
  2978. {
  2979. if (IsComptime())
  2980. return -1;
  2981. return methodInstance->GetStructRetIdx(forceStatic);
  2982. }
  2983. BfType* BfExprEvaluator::BindGenericType(BfAstNode* node, BfType* bindType)
  2984. {
  2985. if ((mModule->mCurMethodState == NULL) || (mModule->mCurMethodInstance == NULL) || (bindType == NULL))
  2986. return bindType;
  2987. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  2988. return bindType;
  2989. if ((mBfEvalExprFlags & BfEvalExprFlags_DeclType) != 0)
  2990. return bindType;
  2991. BF_ASSERT((!mModule->mCurMethodInstance->mIsUnspecializedVariation) || (mModule->mIsComptimeModule));
  2992. auto parser = node->GetSourceData()->ToParserData();
  2993. if (parser == NULL)
  2994. return bindType;
  2995. int64 nodeId = ((int64)parser->mDataId << 32) + node->GetSrcStart();
  2996. auto genericTypeBindings = mModule->mCurMethodState->GetRootMethodState()->mGenericTypeBindings;
  2997. auto methodInstance = mModule->mCurMethodInstance;
  2998. bool isMixinBind = false;
  2999. if (mModule->mCurMethodState->mMixinState != NULL)
  3000. {
  3001. auto mixinMethodInstance = mModule->mCurMethodState->mMixinState->mMixinMethodInstance;
  3002. if (!mixinMethodInstance->mMethodDef->mGenericParams.IsEmpty())
  3003. {
  3004. auto unspecMixinMethodInstance = mModule->GetUnspecializedMethodInstance(mixinMethodInstance, false);
  3005. if (!unspecMixinMethodInstance->mHasBeenProcessed)
  3006. {
  3007. // Make sure the unspecialized method is processed so we can take its bindings
  3008. // Clear mCurMethodState so we don't think we're in a local method
  3009. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mModule->mCurMethodState, NULL);
  3010. if (unspecMixinMethodInstance->mMethodProcessRequest == NULL)
  3011. unspecMixinMethodInstance->mDeclModule->mIncompleteMethodCount++;
  3012. mModule->mContext->ProcessMethod(unspecMixinMethodInstance);
  3013. }
  3014. isMixinBind = true;
  3015. methodInstance = mixinMethodInstance;
  3016. genericTypeBindings = &unspecMixinMethodInstance->mMethodInfoEx->mGenericTypeBindings;
  3017. }
  3018. }
  3019. if ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation))
  3020. {
  3021. if (isMixinBind)
  3022. return bindType;
  3023. if (!bindType->IsGenericParam())
  3024. return bindType;
  3025. if (genericTypeBindings == NULL)
  3026. return bindType;
  3027. (*genericTypeBindings)[nodeId] = bindType;
  3028. return bindType;
  3029. }
  3030. else
  3031. {
  3032. if (genericTypeBindings == NULL)
  3033. return bindType;
  3034. BfType** typePtr = NULL;
  3035. if (genericTypeBindings->TryGetValue(nodeId, &typePtr))
  3036. return *typePtr;
  3037. return bindType;
  3038. }
  3039. }
  3040. BfType * BfExprEvaluator::ResolveTypeRef(BfTypeReference* typeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  3041. {
  3042. if (mExpectingType != NULL)
  3043. {
  3044. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(typeRef))
  3045. {
  3046. if (namedTypeRef->ToString() == "ExpectedType")
  3047. {
  3048. return mModule->ResolveTypeResult(typeRef, mExpectingType, populateType, resolveFlags);
  3049. }
  3050. }
  3051. }
  3052. return mModule->ResolveTypeRef(typeRef, populateType, resolveFlags);
  3053. }
  3054. void BfExprEvaluator::ResolveGenericType()
  3055. {
  3056. if (mResult)
  3057. {
  3058. if (mModule->IsUnboundGeneric(mResult.mType))
  3059. mResult.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  3060. //mResult.mType = mModule->ResolveGenericType(mResult.mType, true);
  3061. }
  3062. }
  3063. void BfExprEvaluator::Evaluate(BfAstNode* astNode, bool propogateNullConditional, bool ignoreNullConditional, bool allowSplat)
  3064. {
  3065. BP_ZONE("BfExprEvaluator::Evaluate");
  3066. // ParenthesizedExpression breaks null conditional chain
  3067. if (astNode->IsExact<BfParenthesizedExpression>())
  3068. propogateNullConditional = false;
  3069. bool scopeWasConditional = false;
  3070. BfPendingNullConditional* pendingNullCond = NULL;
  3071. mInsidePendingNullable = false;
  3072. if (mModule->mCurMethodState != NULL)
  3073. {
  3074. scopeWasConditional = mModule->mCurMethodState->mCurScope->mIsConditional;
  3075. pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  3076. if (!propogateNullConditional)
  3077. mModule->mCurMethodState->mPendingNullConditional = NULL;
  3078. if (pendingNullCond != NULL)
  3079. {
  3080. mInsidePendingNullable = true;
  3081. mModule->mCurMethodState->mCurScope->mIsConditional = true;
  3082. }
  3083. }
  3084. astNode->Accept(this);
  3085. GetResult();
  3086. if ((mResultIsTempComposite) && (mResult.IsAddr()))
  3087. mResult.mKind = BfTypedValueKind_TempAddr;
  3088. if ((!allowSplat) && (mResult.IsSplat()))
  3089. mResult = mModule->AggregateSplat(mResult);
  3090. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowIntUnknown) == 0)
  3091. mModule->FixIntUnknown(mResult);
  3092. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  3093. {
  3094. if (mResult.mValue.IsConst())
  3095. {
  3096. auto constant = mModule->mBfIRBuilder->GetConstant(mResult.mValue);
  3097. if (constant->mConstType == BfConstType_TypeOf)
  3098. {
  3099. auto typeOfConst = (BfTypeOf_Const*)constant;
  3100. mResult.mValue = mModule->CreateTypeDataRef(typeOfConst->mType);
  3101. }
  3102. }
  3103. }
  3104. if (mModule->mCurMethodState != NULL)
  3105. {
  3106. if (mInsidePendingNullable)
  3107. mModule->mCurMethodState->mCurScope->mIsConditional = scopeWasConditional;
  3108. if (!propogateNullConditional)
  3109. {
  3110. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  3111. mResult = mModule->FlushNullConditional(mResult, ignoreNullConditional);
  3112. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  3113. }
  3114. }
  3115. }
  3116. void BfExprEvaluator::Visit(BfErrorNode* errorNode)
  3117. {
  3118. mModule->Fail("Invalid token", errorNode);
  3119. auto autoComplete = GetAutoComplete();
  3120. if (autoComplete != NULL)
  3121. {
  3122. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(errorNode->mRefNode))
  3123. return;
  3124. autoComplete->CheckIdentifier(errorNode->mRefNode, true);
  3125. }
  3126. }
  3127. void BfExprEvaluator::Visit(BfTypeReference* typeRef)
  3128. {
  3129. mResult.mType = ResolveTypeRef(typeRef, BfPopulateType_Declaration);
  3130. }
  3131. void BfExprEvaluator::Visit(BfAttributedExpression* attribExpr)
  3132. {
  3133. BfAttributeState attributeState;
  3134. attributeState.mSrc = attribExpr->mAttributes;
  3135. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  3136. if (auto block = BfNodeDynCast<BfBlock>(attribExpr->mExpression))
  3137. attributeState.mTarget = BfAttributeTargets_Block;
  3138. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attribExpr->mAttributes, attributeState.mTarget);
  3139. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  3140. if (auto ignoreErrorsAttrib = attributeState.mCustomAttributes->Get(mModule->mCompiler->mIgnoreErrorsAttributeTypeDef))
  3141. {
  3142. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  3143. if (!ignoreErrorsAttrib->mCtorArgs.IsEmpty())
  3144. {
  3145. auto constant = mModule->mCurTypeInstance->mConstHolder->GetConstant(ignoreErrorsAttrib->mCtorArgs[0]);
  3146. if (constant->mBool)
  3147. attributeState.mFlags = BfAttributeState::Flag_StopOnError;
  3148. }
  3149. VisitChild(attribExpr->mExpression);
  3150. attributeState.mUsed = true;
  3151. if ((!mResult) ||
  3152. ((mResult) && (mResult.mType->IsVar())))
  3153. {
  3154. if (!mResult)
  3155. mModule->Fail("Expression did not result in a value", attribExpr->mExpression);
  3156. // Make empty or 'var' resolve as 'false' because var is only valid if we threw errors
  3157. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Boolean));
  3158. }
  3159. }
  3160. else if (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mConstSkipAttributeTypeDef))
  3161. {
  3162. if ((mModule->mCurMethodState == NULL) || (mModule->mCurMethodState->mCurScope == NULL) || (!mModule->mCurMethodState->mCurScope->mInConstIgnore))
  3163. {
  3164. VisitChild(attribExpr->mExpression);
  3165. }
  3166. else
  3167. {
  3168. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  3169. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  3170. }
  3171. attributeState.mUsed = true;
  3172. }
  3173. else
  3174. {
  3175. VisitChild(attribExpr->mExpression);
  3176. }
  3177. mModule->FinishAttributeState(&attributeState);
  3178. }
  3179. void BfExprEvaluator::Visit(BfNamedExpression* namedExpr)
  3180. {
  3181. if (namedExpr->mExpression != NULL)
  3182. VisitChild(namedExpr->mExpression);
  3183. }
  3184. void BfExprEvaluator::Visit(BfBlock* blockExpr)
  3185. {
  3186. if (mModule->mCurMethodState == NULL)
  3187. {
  3188. mModule->Fail("Illegal use of block expression", blockExpr);
  3189. return;
  3190. }
  3191. auto autoComplete = GetAutoComplete();
  3192. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(blockExpr)))
  3193. {
  3194. // Don't show outer method match info when our cursor is inside a block (being passed as a parameter)
  3195. autoComplete->RemoveMethodMatchInfo();
  3196. }
  3197. if (blockExpr->mChildArr.IsEmpty())
  3198. {
  3199. mModule->Fail("An empty block cannot be used as an expression", blockExpr);
  3200. return;
  3201. }
  3202. bool lastWasResultExpr = false;
  3203. if (auto lastExpr = BfNodeDynCast<BfExpressionStatement>(blockExpr->mChildArr.GetLast()))
  3204. {
  3205. if (!lastExpr->IsMissingSemicolon())
  3206. mModule->Fail("Expression blocks must end in an expression which is missing its terminating semicolon", lastExpr->mTrailingSemicolon);
  3207. }
  3208. else if (blockExpr->mChildArr.GetLast()->IsExpression())
  3209. {
  3210. // Expression
  3211. }
  3212. else
  3213. {
  3214. mModule->Fail("Expression blocks must end with an expression", blockExpr);
  3215. }
  3216. mModule->VisitEmbeddedStatement(blockExpr, this, BfNodeIsA<BfUnscopedBlock>(blockExpr) ? BfEmbeddedStatementFlags_Unscoped : BfEmbeddedStatementFlags_None);
  3217. }
  3218. bool BfExprEvaluator::CheckVariableDeclaration(BfAstNode* checkNode, bool requireSimpleIfExpr, bool exprMustBeTrue, bool silentFail)
  3219. {
  3220. if (BfNodeIsA<BfUninitializedExpression>(checkNode))
  3221. return true;
  3222. BfAstNode* checkChild = checkNode;
  3223. bool childWasAndRHS = false;
  3224. bool foundIf = false;
  3225. auto parentNodeEntry = mModule->mParentNodeEntry;
  3226. if (parentNodeEntry != NULL)
  3227. {
  3228. if (BfNodeIsA<BfInvocationExpression>(parentNodeEntry->mNode))
  3229. {
  3230. checkChild = parentNodeEntry->mNode;
  3231. parentNodeEntry = parentNodeEntry->mPrev;
  3232. }
  3233. }
  3234. auto _Fail = [&](const StringImpl& errorStr, BfAstNode* node)
  3235. {
  3236. if (!silentFail)
  3237. {
  3238. auto error = mModule->Fail(errorStr, node);
  3239. if ((error != NULL) && (node != checkNode))
  3240. {
  3241. mModule->mCompiler->mPassInstance->MoreInfo("See variable declaration", checkNode);
  3242. }
  3243. }
  3244. return false;
  3245. };
  3246. while (parentNodeEntry != NULL)
  3247. {
  3248. BfAstNode* checkParent = parentNodeEntry->mNode;
  3249. if (auto binOpExpr = BfNodeDynCastExact<BfBinaryOperatorExpression>(checkParent))
  3250. {
  3251. if (binOpExpr->mOp == BfBinaryOp_ConditionalAnd)
  3252. {
  3253. // This is always okay
  3254. childWasAndRHS = (binOpExpr->mRight != NULL) && (binOpExpr->mRight->Contains(checkChild));
  3255. }
  3256. else if ((binOpExpr->mOp == BfBinaryOp_ConditionalOr) && (!exprMustBeTrue))
  3257. {
  3258. if ((binOpExpr->mRight != NULL) && (binOpExpr->mRight->Contains(checkChild)))
  3259. {
  3260. return _Fail("Conditional short-circuiting may skip variable initialization", binOpExpr->mOpToken);
  3261. }
  3262. }
  3263. else
  3264. {
  3265. if (exprMustBeTrue)
  3266. {
  3267. return _Fail("Operator cannot be used with variable initialization", binOpExpr->mOpToken);
  3268. }
  3269. }
  3270. }
  3271. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkParent))
  3272. {
  3273. // This is okay
  3274. }
  3275. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkParent))
  3276. {
  3277. if (exprMustBeTrue)
  3278. {
  3279. return _Fail("Operator cannot be used with variable initialization", unaryOp->mOpToken);
  3280. return false;
  3281. }
  3282. if (childWasAndRHS)
  3283. {
  3284. return _Fail("Operator may allow conditional short-circuiting to skip variable initialization", unaryOp->mOpToken);
  3285. }
  3286. }
  3287. else if (auto ifStmt = BfNodeDynCast<BfIfStatement>(checkParent))
  3288. {
  3289. // Done
  3290. foundIf = true;
  3291. break;
  3292. }
  3293. else
  3294. {
  3295. if (requireSimpleIfExpr)
  3296. {
  3297. return _Fail("Variable declaration expression can only be contained in simple 'if' expressions", checkNode);
  3298. }
  3299. break;
  3300. }
  3301. checkChild = parentNodeEntry->mNode;
  3302. parentNodeEntry = parentNodeEntry->mPrev;
  3303. }
  3304. return foundIf;
  3305. }
  3306. bool BfExprEvaluator::HasVariableDeclaration(BfAstNode* checkNode)
  3307. {
  3308. BfVarDeclChecker checker;
  3309. checker.VisitChild(checkNode);
  3310. return checker.mHasVarDecl;
  3311. }
  3312. void BfExprEvaluator::Visit(BfVariableDeclaration* varDecl)
  3313. {
  3314. mModule->UpdateExprSrcPos(varDecl);
  3315. if ((mModule->mCurMethodState == NULL) || (!mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations))
  3316. {
  3317. mModule->Fail("Variable declarations are not allowed in this context", varDecl);
  3318. if (varDecl->mInitializer != NULL)
  3319. {
  3320. VisitChild(varDecl->mInitializer);
  3321. }
  3322. return;
  3323. }
  3324. CheckVariableDeclaration(varDecl, true, false, false);
  3325. if (varDecl->mInitializer == NULL)
  3326. {
  3327. mModule->Fail("Variable declarations used as expressions must have an initializer", varDecl);
  3328. }
  3329. BfTupleExpression* tupleVariableDeclaration = BfNodeDynCast<BfTupleExpression>(varDecl->mNameNode);
  3330. if (tupleVariableDeclaration != NULL)
  3331. {
  3332. mModule->Fail("Tuple variable declarations cannot be used as expressions", varDecl);
  3333. mModule->HandleTupleVariableDeclaration(varDecl);
  3334. }
  3335. else
  3336. mModule->HandleVariableDeclaration(varDecl, this);
  3337. }
  3338. void BfExprEvaluator::DoCaseExpression(BfTypedValue caseValAddr, BfCaseExpression* caseExpr)
  3339. {
  3340. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  3341. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  3342. if (auto bindExpr = BfNodeDynCast<BfEnumCaseBindExpression>(caseExpr->mCaseExpression))
  3343. {
  3344. if (caseValAddr)
  3345. {
  3346. BfTypedValue enumTagVal;
  3347. if (caseValAddr.mType->IsPayloadEnum())
  3348. {
  3349. int dscrDataIdx;
  3350. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  3351. enumTagVal = BfTypedValue(mModule->ExtractValue(caseValAddr, dscrDataIdx), dscrType);
  3352. }
  3353. else
  3354. enumTagVal = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Int32));
  3355. mResult = mModule->HandleCaseBind(caseValAddr, enumTagVal, bindExpr);
  3356. return;
  3357. }
  3358. }
  3359. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  3360. bool isPayloadEnum = (caseValAddr.mType != NULL) && (caseValAddr.mType->IsPayloadEnum());
  3361. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(caseExpr->mCaseExpression);
  3362. if ((caseValAddr) &&
  3363. ((isPayloadEnum) || (tupleExpr != NULL)))
  3364. {
  3365. bool hasVariable = false;
  3366. bool hasOut = false;
  3367. bool clearOutOnMismatch = false;
  3368. if (auto invocateExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression))
  3369. {
  3370. for (auto arg : invocateExpr->mArguments)
  3371. {
  3372. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(arg))
  3373. {
  3374. hasVariable = true;
  3375. }
  3376. else if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(arg))
  3377. {
  3378. if ((unaryOpExpr->mOpToken != NULL) && (unaryOpExpr->mOpToken->mToken == BfToken_Out))
  3379. {
  3380. hasOut = true;
  3381. }
  3382. }
  3383. }
  3384. }
  3385. if (hasVariable)
  3386. {
  3387. CheckVariableDeclaration(caseExpr, false, false, false);
  3388. }
  3389. // We can avoid clearing on mismatch if we can be sure we ONLY enter the true block on a match.
  3390. // An example of requiring clearing is: if ((result case .Ok(out val)) || (force))
  3391. if (hasOut)
  3392. clearOutOnMismatch = !CheckVariableDeclaration(caseExpr, true, true, true);
  3393. bool hadConditional = false;
  3394. if (isPayloadEnum)
  3395. {
  3396. int dscrDataIdx;
  3397. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  3398. auto enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  3399. int uncondTagId = -1;
  3400. mResult = mModule->TryCaseEnumMatch(caseValAddr, enumTagVal, caseExpr->mCaseExpression, NULL, NULL, NULL, uncondTagId, hadConditional, clearOutOnMismatch, false);
  3401. }
  3402. else
  3403. {
  3404. mResult = mModule->TryCaseTupleMatch(caseValAddr, tupleExpr, NULL, NULL, NULL, hadConditional, clearOutOnMismatch, false);
  3405. }
  3406. if (mResult)
  3407. return;
  3408. }
  3409. if ((caseValAddr) && (IsVar(caseValAddr.mType)))
  3410. {
  3411. auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression);
  3412. if (invocationExpr != NULL)
  3413. {
  3414. for (auto expr : invocationExpr->mArguments)
  3415. {
  3416. if (expr == NULL)
  3417. continue;
  3418. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(expr))
  3419. {
  3420. auto localVar = mModule->HandleVariableDeclaration(varDecl, BfTypedValue());
  3421. if (localVar != NULL)
  3422. localVar->mReadFromId = 0;
  3423. }
  3424. }
  3425. }
  3426. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  3427. mResult = mModule->GetDefaultTypedValue(boolType);
  3428. return;
  3429. }
  3430. BfTypedValue caseMatch;
  3431. if (caseExpr->mCaseExpression != NULL)
  3432. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, caseValAddr.mType, BfEvalExprFlags_AllowEnumId);
  3433. if ((!caseMatch) || (!caseValAddr))
  3434. {
  3435. mResult = mModule->GetDefaultTypedValue(boolType);
  3436. return;
  3437. }
  3438. if (caseValAddr.mType == caseMatch.mType)
  3439. {
  3440. if (((caseValAddr.mType->IsEnum()) && (caseValAddr.mType->IsStruct())) &&
  3441. ((caseMatch) && (caseMatch.mType->IsPayloadEnum()) && (caseMatch.mValue.IsConst())))
  3442. {
  3443. BfTypedValue enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  3444. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(enumTagVal.mValue, caseMatch.mValue), boolType);
  3445. return;
  3446. }
  3447. }
  3448. else
  3449. {
  3450. // We need to get rid of the int-const for the 'scalar match'. We get a full payload enum value so we can
  3451. // possibly use it in a user-defined comparison operator
  3452. if ((caseMatch.mType->IsStruct()) && (caseMatch.mValue.IsConst()))
  3453. {
  3454. // Is it possible this could throw an error twice? Hope not.
  3455. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  3456. }
  3457. }
  3458. PerformBinaryOperation(caseExpr->mCaseExpression, caseExpr->mValueExpression, BfBinaryOp_Equality, caseExpr->mEqualsNode, BfBinOpFlag_None, caseValAddr, caseMatch);
  3459. }
  3460. void BfExprEvaluator::Visit(BfCaseExpression* caseExpr)
  3461. {
  3462. if (caseExpr->mEqualsNode != NULL)
  3463. {
  3464. mModule->Warn(0, "Deprecated case syntax", caseExpr->mEqualsNode);
  3465. }
  3466. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  3467. BfTypedValue caseValAddr;
  3468. if (caseExpr->mValueExpression != NULL)
  3469. caseValAddr = mModule->CreateValueFromExpression(caseExpr->mValueExpression, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  3470. if ((caseValAddr.mType != NULL) && (caseValAddr.mType->IsPointer()))
  3471. {
  3472. caseValAddr = mModule->LoadValue(caseValAddr);
  3473. caseValAddr = BfTypedValue(caseValAddr.mValue, caseValAddr.mType->GetUnderlyingType(), true);
  3474. }
  3475. BfIRValue hasValueValue;
  3476. if (caseValAddr.mType != NULL)
  3477. mModule->mBfIRBuilder->PopulateType(caseValAddr.mType);
  3478. if ((caseValAddr.mType != NULL) && (caseValAddr.mType->IsNullable()))
  3479. {
  3480. auto nullableElementType = caseValAddr.mType->GetUnderlyingType();
  3481. hasValueValue = mModule->ExtractValue(caseValAddr, nullableElementType->IsValuelessType() ? 1 : 2);
  3482. if (!nullableElementType->IsValuelessType())
  3483. caseValAddr = BfTypedValue(mModule->ExtractValue(caseValAddr, 1), nullableElementType); // value
  3484. else
  3485. caseValAddr = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), nullableElementType);
  3486. }
  3487. BfIRBlock nullBB;
  3488. BfIRBlock endBB;
  3489. if (hasValueValue)
  3490. {
  3491. auto caseBB = mModule->mBfIRBuilder->CreateBlock("caseexpr.case");
  3492. endBB = mModule->mBfIRBuilder->CreateBlock("caseexpr.end");
  3493. mModule->mBfIRBuilder->CreateCondBr(hasValueValue, caseBB, endBB);
  3494. nullBB = mModule->mBfIRBuilder->GetInsertBlock();
  3495. mModule->mBfIRBuilder->AddBlock(caseBB);
  3496. mModule->mBfIRBuilder->SetInsertPoint(caseBB);
  3497. }
  3498. DoCaseExpression(caseValAddr, caseExpr);
  3499. if (!mResult)
  3500. mResult = mModule->GetDefaultTypedValue(boolType);
  3501. else
  3502. {
  3503. BF_ASSERT(mResult.mType == boolType);
  3504. }
  3505. if (hasValueValue)
  3506. {
  3507. auto endCaseBB = mModule->mBfIRBuilder->GetInsertBlock();
  3508. mModule->mBfIRBuilder->CreateBr(endBB);
  3509. mModule->mBfIRBuilder->AddBlock(endBB);
  3510. mModule->mBfIRBuilder->SetInsertPoint(endBB);
  3511. auto phiValue = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  3512. mModule->mBfIRBuilder->AddPhiIncoming(phiValue, mModule->GetDefaultValue(boolType), nullBB);
  3513. mModule->mBfIRBuilder->AddPhiIncoming(phiValue, mResult.mValue, endCaseBB);
  3514. mResult = BfTypedValue(phiValue, boolType);
  3515. }
  3516. if (caseExpr->mNotToken != NULL)
  3517. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  3518. }
  3519. void BfExprEvaluator::Visit(BfTypedValueExpression* typedValueExpr)
  3520. {
  3521. mResult = typedValueExpr->mTypedValue;
  3522. }
  3523. static bool IsCharType(BfTypeCode typeCode)
  3524. {
  3525. switch (typeCode)
  3526. {
  3527. case BfTypeCode_Char8:
  3528. case BfTypeCode_Char16:
  3529. case BfTypeCode_Char32:
  3530. return true;
  3531. default:
  3532. return false;
  3533. }
  3534. }
  3535. bool BfExprEvaluator::CheckForMethodName(BfAstNode* refNode, BfTypeInstance* typeInst, const StringImpl& findName)
  3536. {
  3537. BF_ASSERT((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0);
  3538. auto autoComplete = GetAutoComplete();
  3539. while (typeInst != NULL)
  3540. {
  3541. auto typeDef = typeInst->mTypeDef;
  3542. typeDef->PopulateMemberSets();
  3543. BfMemberSetEntry* memberSetEntry;
  3544. if (typeDef->mMethodSet.TryGetWith(findName, &memberSetEntry))
  3545. {
  3546. if (mModule->mCompiler->mResolvePassData != NULL)
  3547. mModule->mCompiler->mResolvePassData->HandleMethodReference(refNode, typeDef, (BfMethodDef*)memberSetEntry->mMemberDef);
  3548. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(refNode)))
  3549. {
  3550. autoComplete->SetDefinitionLocation(((BfMethodDef*)memberSetEntry->mMemberDef)->GetRefNode());
  3551. if ((autoComplete->mResolveType == BfResolveType_GetSymbolInfo) && (autoComplete->mDefType == NULL))
  3552. {
  3553. autoComplete->mDefType = typeDef;
  3554. autoComplete->mDefMethod = (BfMethodDef*)memberSetEntry->mMemberDef;
  3555. }
  3556. }
  3557. if (mModule->mCompiler->mResolvePassData != NULL)
  3558. {
  3559. if (auto sourceClassifier = mModule->mCompiler->mResolvePassData->GetSourceClassifier(refNode))
  3560. sourceClassifier->SetElementType(refNode, BfSourceElementType_Method);
  3561. }
  3562. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NameOfSuccess);
  3563. return true;
  3564. }
  3565. typeInst = typeInst->mBaseType;
  3566. }
  3567. return false;
  3568. }
  3569. bool BfExprEvaluator::IsVar(BfType* type, bool forceIgnoreWrites)
  3570. {
  3571. if (type->IsVar())
  3572. return true;
  3573. if ((type->IsGenericParam()) && (!forceIgnoreWrites) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  3574. {
  3575. BF_ASSERT(mModule->mIsComptimeModule);
  3576. return true;
  3577. }
  3578. return false;
  3579. }
  3580. void BfExprEvaluator::GetLiteral(BfAstNode* refNode, const BfVariant& variant, BfType* type)
  3581. {
  3582. switch (variant.mTypeCode)
  3583. {
  3584. case BfTypeCode_NullPtr:
  3585. {
  3586. auto nullType = mModule->ResolveTypeDef(mModule->mSystem->mTypeNullPtr);
  3587. /*mResult = BfTypedValue(ConstantPointerNull::get((PointerType*) nullType->mIRType), nullType);*/
  3588. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstNull(), nullType);
  3589. }
  3590. break;
  3591. case BfTypeCode_CharPtr:
  3592. {
  3593. if ((mExpectingType != NULL) && (mExpectingType->IsSizedArray()))
  3594. {
  3595. auto sizedArray = (BfSizedArrayType*)mExpectingType;
  3596. if (sizedArray->mElementType == mModule->GetPrimitiveType(BfTypeCode_Char8))
  3597. {
  3598. if (sizedArray->IsUndefSizedArray())
  3599. sizedArray = mModule->CreateSizedArrayType(sizedArray->mElementType, variant.mString->GetLength());
  3600. if (variant.mString->GetLength() > sizedArray->mElementCount)
  3601. {
  3602. mModule->Fail(StrFormat("String literal is too long to fit into '%s'", mModule->TypeToString(sizedArray).c_str()), refNode);
  3603. }
  3604. Array<BfIRValue> charValues;
  3605. for (int i = 0; i < (int)BF_MIN(variant.mString->GetLength(), sizedArray->mElementCount); i++)
  3606. {
  3607. char c = (*variant.mString)[i];
  3608. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)(uint8)c));
  3609. }
  3610. if (sizedArray->mElementCount > charValues.size())
  3611. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, 0));
  3612. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(sizedArray), charValues), sizedArray);
  3613. return;
  3614. }
  3615. }
  3616. if ((mExpectingType == NULL) || (!mExpectingType->IsPointer()))
  3617. {
  3618. mResult = BfTypedValue(mModule->GetStringObjectValue(*variant.mString),
  3619. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  3620. }
  3621. else
  3622. {
  3623. auto charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  3624. auto charPtrType = mModule->CreatePointerType(charType);
  3625. mResult = BfTypedValue(mModule->GetStringCharPtr(*variant.mString),
  3626. charPtrType);
  3627. }
  3628. }
  3629. break;
  3630. case BfTypeCode_Boolean:
  3631. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  3632. break;
  3633. case BfTypeCode_Char8:
  3634. case BfTypeCode_Char16:
  3635. case BfTypeCode_Char32:
  3636. case BfTypeCode_Int8:
  3637. case BfTypeCode_UInt8:
  3638. case BfTypeCode_Int16:
  3639. case BfTypeCode_UInt16:
  3640. case BfTypeCode_Int32:
  3641. case BfTypeCode_UInt32:
  3642. case BfTypeCode_Int64:
  3643. case BfTypeCode_UInt64:
  3644. case BfTypeCode_IntPtr:
  3645. case BfTypeCode_UIntPtr:
  3646. case BfTypeCode_IntUnknown:
  3647. case BfTypeCode_UIntUnknown:
  3648. if ((mExpectingType != NULL) && (mExpectingType->IsIntegral()) && (mExpectingType->IsChar() == IsCharType(variant.mTypeCode)))
  3649. {
  3650. auto primType = (BfPrimitiveType*)mExpectingType;
  3651. if (mModule->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, variant.mUInt64))
  3652. {
  3653. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, variant.mUInt64), mExpectingType);
  3654. break;
  3655. }
  3656. }
  3657. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  3658. break;
  3659. case BfTypeCode_Float:
  3660. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mSingle), mModule->GetPrimitiveType(variant.mTypeCode));
  3661. break;
  3662. case BfTypeCode_Double:
  3663. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mDouble), mModule->GetPrimitiveType(variant.mTypeCode));
  3664. break;
  3665. case BfTypeCode_StringId:
  3666. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  3667. break;
  3668. case BfTypeCode_Let:
  3669. if (mExpectingType != NULL)
  3670. {
  3671. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(mExpectingType)), mExpectingType);
  3672. break;
  3673. }
  3674. mModule->Fail("Invalid undef literal", refNode);
  3675. break;
  3676. case BfTypeCode_Struct:
  3677. if (type != NULL)
  3678. {
  3679. BfVariant::StructData* structData = (BfVariant::StructData*)variant.mPtr;
  3680. mResult = BfTypedValue(mModule->mBfIRBuilder->ReadConstant(structData->mData, type), type);
  3681. }
  3682. break;
  3683. default:
  3684. mModule->Fail("Invalid literal", refNode);
  3685. break;
  3686. }
  3687. }
  3688. void BfExprEvaluator::Visit(BfLiteralExpression* literalExpr)
  3689. {
  3690. switch (literalExpr->mValue.mWarnType)
  3691. {
  3692. case BfWarning_BF4201_Only7Hex:
  3693. mModule->Warn(BfWarning_BF4201_Only7Hex, "Only 7 hex digits specified. Add a leading zero to clarify intention.", literalExpr);
  3694. break;
  3695. case BfWarning_BF4202_TooManyHexForInt:
  3696. mModule->Warn(BfWarning_BF4202_TooManyHexForInt, "Nine hex digits specified. If an 8-digit hex literal was not intended then add a leading zero to clarify.", literalExpr);
  3697. break;
  3698. }
  3699. GetLiteral(literalExpr, literalExpr->mValue);
  3700. }
  3701. void BfExprEvaluator::Visit(BfStringInterpolationExpression* stringInterpolationExpression)
  3702. {
  3703. if ((mBfEvalExprFlags & BfEvalExprFlags_StringInterpolateFormat) != 0)
  3704. {
  3705. BfVariant variant;
  3706. variant.mTypeCode = BfTypeCode_CharPtr;
  3707. variant.mString = stringInterpolationExpression->mString;
  3708. GetLiteral(stringInterpolationExpression, variant);
  3709. return;
  3710. }
  3711. //
  3712. {
  3713. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlag(mBfEvalExprFlags);
  3714. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mConstEvalAttributeTypeDef)))
  3715. {
  3716. mModule->mAttributeState->mUsed = true;
  3717. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  3718. }
  3719. if (IsConstEval())
  3720. {
  3721. auto stringType = mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef);
  3722. if (stringType != NULL)
  3723. {
  3724. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, true);
  3725. SizedArray<BfExpression*, 2> argExprs;
  3726. argExprs.Add(stringInterpolationExpression);
  3727. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  3728. BfResolvedArgs argValues(&sizedArgExprs);
  3729. ResolveArgValues(argValues, BfResolveArgsFlag_InsideStringInterpolationAlloc);
  3730. auto result = MatchMethod(stringInterpolationExpression, NULL, BfTypedValue(stringType), false, false, "ConstF", argValues, BfMethodGenericArguments());
  3731. if (result.mType == stringType)
  3732. {
  3733. mResult = result;
  3734. return;
  3735. }
  3736. }
  3737. mModule->Fail("Const evaluation of string interpolation not allowed", stringInterpolationExpression);
  3738. }
  3739. }
  3740. if (stringInterpolationExpression->mAllocNode != NULL)
  3741. {
  3742. auto stringType = mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef)->ToTypeInstance();
  3743. BfTokenNode* newToken = NULL;
  3744. BfAllocTarget allocTarget;
  3745. ResolveAllocTarget(allocTarget, stringInterpolationExpression->mAllocNode, newToken);
  3746. //
  3747. {
  3748. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  3749. CreateObject(NULL, stringInterpolationExpression->mAllocNode, stringType, NULL);
  3750. }
  3751. BfTypedValue newString = mResult;
  3752. BF_ASSERT(newString);
  3753. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, true);
  3754. SizedArray<BfExpression*, 2> argExprs;
  3755. argExprs.Add(stringInterpolationExpression);
  3756. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  3757. BfResolvedArgs argValues(&sizedArgExprs);
  3758. ResolveArgValues(argValues, BfResolveArgsFlag_InsideStringInterpolationAlloc);
  3759. MatchMethod(stringInterpolationExpression, NULL, newString, false, false, "AppendF", argValues, BfMethodGenericArguments());
  3760. mResult = newString;
  3761. return;
  3762. }
  3763. mModule->Fail("Invalid use of string interpolation expression. Consider adding an allocation specifier such as 'scope'.", stringInterpolationExpression);
  3764. for (auto block : stringInterpolationExpression->mExpressions)
  3765. {
  3766. VisitChild(block);
  3767. }
  3768. }
  3769. BfTypedValue BfExprEvaluator::LoadLocal(BfLocalVariable* varDecl, bool allowRef)
  3770. {
  3771. if (!mModule->mIsInsideAutoComplete)
  3772. varDecl->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  3773. // The Beef backend prefers readonly addrs since that reduces register pressure, whereas
  3774. // LLVM prefers values to avoid memory loads. This only applies to primitive types...
  3775. bool preferValue = (varDecl->mResolvedType->IsPrimitiveType()) && (!mModule->IsTargetingBeefBackend());
  3776. BfTypedValue localResult;
  3777. if (varDecl->mIsThis)
  3778. {
  3779. return mModule->GetThis();
  3780. }
  3781. else if (varDecl->mConstValue)
  3782. {
  3783. localResult = BfTypedValue(varDecl->mConstValue, varDecl->mResolvedType, false);
  3784. }
  3785. else if (varDecl->mIsSplat)
  3786. {
  3787. if (!varDecl->mResolvedType->IsValuelessType())
  3788. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  3789. else if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3790. {
  3791. BF_ASSERT(varDecl->mResolvedType->IsValuelessType());
  3792. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType->GetUnderlyingType());
  3793. }
  3794. else
  3795. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType);
  3796. //BF_ASSERT(varDecl->mValue.IsArg());
  3797. }
  3798. else if ((varDecl->mValue) && ((varDecl->mIsReadOnly && preferValue) || (!varDecl->mAddr)))
  3799. {
  3800. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3801. {
  3802. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3803. BfType* innerType = refType->mElementType;
  3804. if (innerType->IsGenericParam())
  3805. {
  3806. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3807. {
  3808. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_MutableValue);
  3809. return localResult;
  3810. }
  3811. else
  3812. {
  3813. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_Addr);
  3814. return localResult;
  3815. }
  3816. }
  3817. localResult = BfTypedValue(varDecl->mValue, innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3818. }
  3819. else
  3820. {
  3821. BfTypedValueKind kind;
  3822. if ((varDecl->mResolvedType->IsComposite()) && (varDecl->mValue.IsArg()))
  3823. {
  3824. kind = varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr;
  3825. }
  3826. else
  3827. kind = BfTypedValueKind_Value;
  3828. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, kind);
  3829. }
  3830. }
  3831. else if (varDecl->mAddr)
  3832. {
  3833. if ((!mModule->mBfIRBuilder->mIgnoreWrites) && (varDecl->mAddr.IsFake()) && (!varDecl->mResolvedType->IsValuelessType()))
  3834. {
  3835. // In an ignore case match we can may need to create a fake "out" when someone tries to read it
  3836. auto defaultTypedValue = mModule->GetDefaultTypedValue(varDecl->mResolvedType, true, BfDefaultValueKind_Addr);
  3837. varDecl->mAddr = defaultTypedValue.mValue;
  3838. }
  3839. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3840. {
  3841. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3842. BfType* innerType = refType->mElementType;
  3843. if (innerType->IsValuelessNonOpaqueType())
  3844. {
  3845. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3846. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, BfTypedValueKind_MutableValue);
  3847. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3848. }
  3849. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3850. {
  3851. if (innerType->IsGenericParam())
  3852. {
  3853. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, BfTypedValueKind_MutableValue);
  3854. return localResult;
  3855. }
  3856. }
  3857. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3858. }
  3859. else if (varDecl->mHasLocalStructBacking)
  3860. {
  3861. // varDecl->mAddr is a "struct**"
  3862. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3863. }
  3864. else
  3865. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3866. }
  3867. else if ((varDecl->mResolvedType->IsModifiedTypeType()) && (((BfModifiedTypeType*)varDecl->mResolvedType)->mModifiedKind == BfToken_Params))
  3868. {
  3869. localResult = BfTypedValue(BfIRValue(), varDecl->mResolvedType);
  3870. }
  3871. else if (varDecl->mResolvedType->IsValuelessNonOpaqueType())
  3872. {
  3873. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3874. {
  3875. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3876. BfType* innerType = refType->mElementType;
  3877. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, true);
  3878. return localResult;
  3879. }
  3880. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), varDecl->mResolvedType, true);
  3881. }
  3882. else if (varDecl->mCompositeCount >= 0)
  3883. {
  3884. if ((mBfEvalExprFlags & BfEvalExprFlags_InParamsExpr) != 0)
  3885. {
  3886. localResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  3887. }
  3888. else if (!varDecl->mAddr)
  3889. {
  3890. bool isValid = true;
  3891. Array<BfTypedValue> argVals;
  3892. auto methodState = mModule->mCurMethodState->GetMethodStateForLocal(varDecl);
  3893. for (int compositeIdx = 0; compositeIdx < varDecl->mCompositeCount; compositeIdx++)
  3894. {
  3895. BfResolvedArg compositeResolvedArg;
  3896. auto compositeLocalVar = methodState->mLocals[varDecl->mLocalVarIdx + compositeIdx + 1];
  3897. auto argValue = LoadLocal(compositeLocalVar, true);
  3898. if (argValue)
  3899. {
  3900. if (!argValue.mType->IsStruct())
  3901. argValue = mModule->LoadValue(argValue, NULL, mIsVolatileReference);
  3902. argVals.Add(argValue);
  3903. }
  3904. else
  3905. isValid = false;
  3906. }
  3907. if (isValid)
  3908. {
  3909. BfTypeInstance* tupleType = NULL;
  3910. if (varDecl->mResolvedType->IsTuple())
  3911. tupleType = (BfTupleType*)varDecl->mResolvedType;
  3912. else if ((varDecl->mResolvedType->IsDelegateOrFunction()))
  3913. {
  3914. auto invokeFunction = mModule->GetDelegateInvokeMethod(varDecl->mResolvedType->ToTypeInstance());
  3915. if (invokeFunction != NULL)
  3916. {
  3917. BfTypeVector fieldTypes;
  3918. SubstituteList fieldNames;
  3919. for (int paramIdx = 0; paramIdx < invokeFunction->GetParamCount(); paramIdx++)
  3920. {
  3921. fieldNames.Add(invokeFunction->GetParamName(paramIdx));
  3922. fieldTypes.Add(invokeFunction->GetParamType(paramIdx));
  3923. }
  3924. tupleType = mModule->CreateTupleType(fieldTypes, fieldNames);
  3925. }
  3926. }
  3927. if (tupleType == NULL)
  3928. {
  3929. isValid = false;
  3930. }
  3931. else if (tupleType->IsValuelessType())
  3932. {
  3933. localResult = mModule->GetDefaultTypedValue(tupleType);
  3934. }
  3935. else
  3936. {
  3937. BF_ASSERT(tupleType->mFieldInstances.mSize == argVals.mSize);
  3938. auto instAlloca = mModule->CreateAlloca(tupleType);
  3939. for (int i = 0; i < argVals.mSize; i++)
  3940. {
  3941. auto& fieldInstance = tupleType->mFieldInstances[i];
  3942. if (fieldInstance.mDataIdx >= 0)
  3943. {
  3944. auto val = mModule->Cast(varDecl->mNameNode, argVals[i], fieldInstance.mResolvedType);
  3945. if (val)
  3946. {
  3947. val = mModule->LoadOrAggregateValue(val);
  3948. if (!val.mType->IsValuelessType())
  3949. {
  3950. auto elemPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(instAlloca, 0, fieldInstance.mDataIdx);
  3951. mModule->mBfIRBuilder->CreateStore(val.mValue, elemPtr);
  3952. }
  3953. }
  3954. }
  3955. }
  3956. varDecl->mResolvedType = tupleType;
  3957. varDecl->mAddr = instAlloca;
  3958. varDecl->mIsReadOnly = true;
  3959. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ReadOnlyAddr);
  3960. }
  3961. }
  3962. if (!isValid)
  3963. {
  3964. localResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTupleTypeDef));
  3965. }
  3966. }
  3967. }
  3968. else
  3969. {
  3970. BF_ASSERT((mModule->mCurMethodState->mClosureState != NULL) || (mModule->mBfIRBuilder->mIgnoreWrites));
  3971. // Just temporary
  3972. auto varType = varDecl->mResolvedType;
  3973. auto allocType = varType;
  3974. if (varType->IsRef())
  3975. {
  3976. BfRefType* refType = (BfRefType*)varType;
  3977. allocType = refType->mElementType;
  3978. }
  3979. auto declType = varDecl->mResolvedType;
  3980. if (declType->IsRef())
  3981. {
  3982. BfRefType* refType = (BfRefType*)declType;
  3983. declType = refType->mElementType;
  3984. }
  3985. mModule->PopulateType(allocType);
  3986. varDecl->mAddr = mModule->mBfIRBuilder->CreateAlloca(mModule->mBfIRBuilder->MapType(allocType));
  3987. localResult = BfTypedValue(varDecl->mAddr, declType, true);
  3988. return localResult;
  3989. }
  3990. if ((varDecl->mIsThis) && (localResult.mKind == BfTypedValueKind_Value))
  3991. localResult.mKind = BfTypedValueKind_ThisValue;
  3992. return localResult;
  3993. }
  3994. BfTypedValue BfExprEvaluator::LookupIdentifier(BfAstNode* refNode, const StringImpl& findName, bool ignoreInitialError, bool* hadError)
  3995. {
  3996. int varSkipCount = 0;
  3997. StringT<128> wantName;
  3998. wantName.Reference(findName);
  3999. if (findName.StartsWith('@'))
  4000. {
  4001. wantName = findName;
  4002. while (wantName.StartsWith("@"))
  4003. {
  4004. if (wantName != "@return")
  4005. varSkipCount++;
  4006. wantName.Remove(0);
  4007. }
  4008. }
  4009. if (wantName.IsEmpty())
  4010. {
  4011. mModule->Fail("Shadowed variable name expected after '@'", refNode);
  4012. }
  4013. if ((mModule->mCompiler->mCeMachine != NULL) && (mModule->mCompiler->mCeMachine->mDebugger != NULL) && (mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  4014. {
  4015. auto ceDebugger = mModule->mCompiler->mCeMachine->mDebugger;
  4016. auto ceContext = ceDebugger->mCurDbgState->mCeContext;
  4017. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  4018. if (activeFrame->mFunction->mDbgInfo != NULL)
  4019. {
  4020. int varSkipCountLeft = varSkipCount;
  4021. int instIdx = activeFrame->GetInstIdx();
  4022. for (int i = activeFrame->mFunction->mDbgInfo->mVariables.mSize - 1; i >= 0; i--)
  4023. {
  4024. auto& dbgVar = activeFrame->mFunction->mDbgInfo->mVariables[i];
  4025. if (dbgVar.mName == wantName)
  4026. {
  4027. if (varSkipCountLeft > 0)
  4028. {
  4029. varSkipCountLeft--;
  4030. }
  4031. else if ((dbgVar.mValue.mKind == CeOperandKind_AllocaAddr) || (dbgVar.mValue.mKind == CeOperandKind_FrameOfs))
  4032. {
  4033. if ((instIdx >= dbgVar.mStartCodePos) && (instIdx < dbgVar.mEndCodePos))
  4034. {
  4035. return BfTypedValue(mModule->mBfIRBuilder->CreateConstAggCE(mModule->mBfIRBuilder->MapType(dbgVar.mType), activeFrame->mFrameAddr + dbgVar.mValue.mFrameOfs),
  4036. dbgVar.mType, dbgVar.mIsConst ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  4037. }
  4038. }
  4039. }
  4040. }
  4041. }
  4042. if (findName == "FR")
  4043. {
  4044. auto ptrType = mModule->CreatePointerType(mModule->GetPrimitiveType(BfTypeCode_UInt8));
  4045. auto intVal = mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, activeFrame->mFrameAddr);
  4046. auto ptrVal = mModule->mBfIRBuilder->CreateIntToPtr(intVal, mModule->mBfIRBuilder->MapType(ptrType));
  4047. return BfTypedValue(ptrVal, ptrType);
  4048. }
  4049. }
  4050. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(refNode);
  4051. if (mModule->mCurMethodState != NULL)
  4052. {
  4053. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  4054. auto checkMethodState = mModule->mCurMethodState;
  4055. bool isMixinOuterVariablePass = false;
  4056. while (checkMethodState != NULL)
  4057. {
  4058. BP_ZONE("LookupIdentifier:LocalVar");
  4059. BfTypeInstance* closureTypeInst = NULL;
  4060. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  4061. {
  4062. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  4063. }
  4064. int varSkipCountLeft = varSkipCount;
  4065. BfLocalVarEntry* entry;
  4066. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(wantName, &entry))
  4067. {
  4068. auto varDecl = entry->mLocalVar;
  4069. if (varDecl != NULL)
  4070. varSkipCountLeft -= varDecl->mNamePrefixCount;
  4071. while ((varSkipCountLeft > 0) && (varDecl != NULL))
  4072. {
  4073. varDecl = varDecl->mShadowedLocal;
  4074. varSkipCountLeft--;
  4075. }
  4076. if ((varDecl != NULL) && (varDecl->mNotCaptured))
  4077. {
  4078. mModule->Fail("Local variable is not captured", refNode);
  4079. }
  4080. if ((varSkipCountLeft == 0) && (varDecl != NULL))
  4081. {
  4082. if ((closureTypeInst != NULL) && (wantName == "this"))
  4083. break;
  4084. if (varDecl->mResolvedType->IsVoid())
  4085. {
  4086. if ((varDecl->mIsReadOnly) && (varDecl->mParamIdx == -2) && (varDecl->mParamFailed))
  4087. {
  4088. BF_ASSERT(mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  4089. mModule->Fail("The result of append allocations cannot be used in append size calculation methods. Consider moving all append allocations to the start of this method body.", refNode);
  4090. }
  4091. }
  4092. if (!varDecl->mIsThis)
  4093. mModule->SetElementType(identifierNode, (varDecl->IsParam()) ? BfSourceElementType_Parameter : BfSourceElementType_Local);
  4094. BfTypedValue localResult = LoadLocal(varDecl);
  4095. if ((localResult) && (localResult.mType->IsParamsType()) && ((mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) == 0))
  4096. {
  4097. localResult = mModule->LoadOrAggregateValue(localResult);
  4098. }
  4099. auto autoComplete = GetAutoComplete();
  4100. if (identifierNode != NULL)
  4101. {
  4102. if (autoComplete != NULL)
  4103. autoComplete->CheckLocalRef(identifierNode, varDecl);
  4104. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  4105. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL) && (!mModule->mCurMethodState->IsTemporary()))
  4106. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, varDecl->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, varDecl->mLocalVarId);
  4107. }
  4108. if (!isMixinOuterVariablePass)
  4109. {
  4110. mResultLocalVar = varDecl;
  4111. mResultFieldInstance = NULL;
  4112. mResultLocalVarRefNode = identifierNode;
  4113. }
  4114. return localResult;
  4115. }
  4116. }
  4117. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  4118. if (closureTypeInst != NULL)
  4119. {
  4120. int varSkipCountLeft = varSkipCount;
  4121. closureTypeInst->mTypeDef->PopulateMemberSets();
  4122. BfMemberSetEntry* memberSetEntry = NULL;
  4123. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith((StringImpl&)findName, &memberSetEntry))
  4124. {
  4125. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  4126. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  4127. if (!field.mResolvedType->IsValuelessType())
  4128. {
  4129. if (mModule->mCurMethodState->mClosureState->mCapturing)
  4130. {
  4131. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  4132. return mModule->GetDefaultTypedValue(field.mResolvedType);
  4133. }
  4134. auto localVar = mModule->mCurMethodState->mLocals[0];
  4135. auto thisValue = localVar->mValue;
  4136. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  4137. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  4138. if (field.mResolvedType->IsRef())
  4139. {
  4140. auto refType = (BfRefType*)field.mResolvedType;
  4141. auto underlyingType = refType->GetUnderlyingType();
  4142. result = BfTypedValue(mModule->mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  4143. }
  4144. else if (fieldDef->mIsReadOnly)
  4145. result = mModule->LoadValue(result);
  4146. //mModule->SetElementType(identifierNode, (localVar->IsParam()) ? BfSourceElementType_Parameter : BfSourceElementType_Local);
  4147. mResultLocalVar = localVar;
  4148. mResultFieldInstance = &field;
  4149. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  4150. return result;
  4151. }
  4152. }
  4153. }
  4154. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  4155. {
  4156. checkMethodState = checkMethodState->mPrevMethodState;
  4157. continue;
  4158. }
  4159. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  4160. bool isLocalMixinProcessing = false;
  4161. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  4162. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  4163. isLocalMixinProcessing = true;
  4164. if (!isLocalMixinProcessing)
  4165. break;
  4166. isMixinOuterVariablePass = true;
  4167. checkMethodState = checkMethodState->mPrevMethodState;
  4168. }
  4169. }
  4170. if ((mModule->mCurMethodInstance == NULL) && (mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->IsEnum()))
  4171. {
  4172. if (findName == "_")
  4173. {
  4174. BfFieldDef* resolvingFieldDef = NULL;
  4175. auto checkTypeState = mModule->mContext->mCurTypeState;
  4176. while (checkTypeState != NULL)
  4177. {
  4178. if (checkTypeState->mCurFieldDef != NULL)
  4179. {
  4180. if (checkTypeState->mType == mModule->mCurTypeInstance)
  4181. resolvingFieldDef = checkTypeState->mCurFieldDef;
  4182. }
  4183. checkTypeState = checkTypeState->mPrevState;
  4184. }
  4185. if ((resolvingFieldDef != NULL) &&
  4186. (mModule->mCompiler->mResolvePassData != NULL) &&
  4187. (!mModule->mCompiler->mResolvePassData->mParsers.IsEmpty()) &&
  4188. (mModule->mCompiler->mResolvePassData->mParsers[0] == resolvingFieldDef->mFieldDeclaration->GetParser()) &&
  4189. (GetAutoComplete() != NULL))
  4190. {
  4191. return mModule->GetDefaultTypedValue(mModule->mCurTypeInstance);
  4192. }
  4193. else if ((resolvingFieldDef != NULL) && (resolvingFieldDef->mIdx > 0))
  4194. {
  4195. auto enumType = mModule->mCurTypeInstance;
  4196. if (!enumType->mFieldInstances.IsEmpty())
  4197. {
  4198. auto fieldInstance = &mModule->mCurTypeInstance->mFieldInstances[resolvingFieldDef->mIdx - 1];
  4199. if ((fieldInstance->mConstIdx != -1) &&
  4200. (fieldInstance->mResolvedType == mModule->mCurTypeInstance))
  4201. {
  4202. auto foreignConst = enumType->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4203. auto retVal = mModule->ConstantToCurrent(foreignConst, enumType->mConstHolder, enumType);
  4204. return BfTypedValue(retVal, enumType);
  4205. }
  4206. }
  4207. }
  4208. }
  4209. }
  4210. BfTypedValue thisValue = mModule->GetThis(false);
  4211. bool forcedIFaceLookup = false;
  4212. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef))
  4213. {
  4214. thisValue.mType = mModule->mCurMethodInstance->GetForeignType();
  4215. forcedIFaceLookup = true;
  4216. }
  4217. if (thisValue)
  4218. {
  4219. if (findName == "this")
  4220. {
  4221. mModule->MarkUsingThis();
  4222. return thisValue;
  4223. }
  4224. if (findName == "base")
  4225. {
  4226. auto baseValue = thisValue;
  4227. if (baseValue.IsThis())
  4228. baseValue.ToBase();
  4229. if (mModule->GetActiveTypeDef()->mTypeCode != BfTypeCode_Extension)
  4230. {
  4231. MakeBaseConcrete(baseValue);
  4232. }
  4233. mModule->MarkUsingThis();
  4234. return baseValue;
  4235. }
  4236. if (!mModule->mCurMethodState->HasNonStaticMixin())
  4237. {
  4238. mResultLocalVar = mModule->GetThisVariable();
  4239. mResultFieldInstance = NULL;
  4240. mResultLocalVarRefNode = identifierNode;
  4241. }
  4242. }
  4243. if (!thisValue.HasType())
  4244. {
  4245. if ((mModule->mContext->mCurTypeState != NULL) && (mModule->mContext->mCurTypeState->mType == mModule->mCurTypeInstance) &&
  4246. (mModule->mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_Attributes))
  4247. {
  4248. // Can't do static lookups yet
  4249. }
  4250. else
  4251. thisValue = BfTypedValue(mModule->mCurTypeInstance);
  4252. }
  4253. BfTypedValue result;
  4254. if (thisValue.HasType())
  4255. {
  4256. result = LookupField(identifierNode, thisValue, findName, BfLookupFieldFlag_IsImplicitThis);
  4257. if (mResultFieldInstance == NULL)
  4258. {
  4259. mResultLocalVar = NULL;
  4260. mResultLocalVarRefNode = NULL;
  4261. }
  4262. }
  4263. if (mPropDef != NULL)
  4264. {
  4265. if (forcedIFaceLookup)
  4266. {
  4267. if (mPropTarget == thisValue)
  4268. {
  4269. mPropDefBypassVirtual = true;
  4270. mOrigPropTarget = mModule->GetThis();
  4271. }
  4272. }
  4273. }
  4274. if ((!result) && (mPropDef == NULL))
  4275. {
  4276. if (mModule->mContext->mCurTypeState != NULL)
  4277. {
  4278. // This is not necessarily true since we changed ConstResolver
  4279. //BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mTypeInstance);
  4280. BfGlobalLookup globalLookup;
  4281. globalLookup.mKind = BfGlobalLookup::Kind_Field;
  4282. globalLookup.mName = findName;
  4283. mModule->PopulateGlobalContainersList(globalLookup);
  4284. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  4285. {
  4286. if (globalContainer.mTypeInst == NULL)
  4287. continue;
  4288. thisValue = BfTypedValue(globalContainer.mTypeInst);
  4289. result = LookupField(identifierNode, thisValue, findName);
  4290. if ((result) || (mPropDef != NULL))
  4291. {
  4292. mModule->SetHighestElementType(identifierNode, BfSourceElementType_Member);
  4293. return result;
  4294. }
  4295. }
  4296. }
  4297. auto staticSearch = mModule->GetStaticSearch();
  4298. if (staticSearch != NULL)
  4299. {
  4300. for (auto typeInst : staticSearch->mStaticTypes)
  4301. {
  4302. thisValue = BfTypedValue(typeInst);
  4303. result = LookupField(identifierNode, thisValue, findName);
  4304. if ((result) || (mPropDef != NULL))
  4305. {
  4306. mModule->SetHighestElementType(identifierNode, BfSourceElementType_Member);
  4307. return result;
  4308. }
  4309. }
  4310. }
  4311. }
  4312. else
  4313. {
  4314. mModule->SetHighestElementType(identifierNode, BfSourceElementType_Member);
  4315. }
  4316. if ((!result) && (identifierNode != NULL))
  4317. {
  4318. result = mModule->TryLookupGenericConstVaue(identifierNode, mExpectingType);
  4319. if ((mBfEvalExprFlags & (BfEvalExprFlags_Comptime | BfEvalExprFlags_AllowGenericConstValue)) == BfEvalExprFlags_Comptime)
  4320. {
  4321. if (result.mKind == BfTypedValueKind_GenericConstValue)
  4322. {
  4323. auto genericParamDef = mModule->GetGenericParamInstance((BfGenericParamType*)result.mType);
  4324. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  4325. {
  4326. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  4327. if (genericTypeConstraint != NULL)
  4328. {
  4329. auto primType = genericTypeConstraint->ToPrimitiveType();
  4330. if (primType != NULL)
  4331. {
  4332. BfTypedValue result;
  4333. result.mKind = BfTypedValueKind_Value;
  4334. result.mType = genericTypeConstraint;
  4335. result.mValue = mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->GetPrimitiveType(primType->mTypeDef->mTypeCode));
  4336. return result;
  4337. }
  4338. }
  4339. else
  4340. {
  4341. BF_FATAL("Error");
  4342. }
  4343. }
  4344. }
  4345. }
  4346. mModule->FixValueActualization(result);
  4347. }
  4348. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (findName == "@this"))
  4349. {
  4350. if (mModule->mCurMethodState->mClosureState->mCapturing)
  4351. {
  4352. if (mModule->mCurMethodState->mClosureState->mDelegateType != NULL)
  4353. {
  4354. mModule->mCurMethodState->mClosureState->mCapturedDelegateSelf = true;
  4355. return mModule->GetDefaultTypedValue(mModule->mCurMethodState->mClosureState->mDelegateType);
  4356. }
  4357. }
  4358. else
  4359. {
  4360. if (!mModule->mCurMethodState->mLocals.IsEmpty())
  4361. {
  4362. auto thisLocal = mModule->mCurMethodState->mLocals[0];
  4363. if (thisLocal->mIsThis)
  4364. {
  4365. if (thisLocal->mAddr)
  4366. return BfTypedValue(mModule->mBfIRBuilder->CreateLoad(thisLocal->mAddr), thisLocal->mResolvedType);
  4367. else
  4368. return BfTypedValue(thisLocal->mValue, thisLocal->mResolvedType);
  4369. }
  4370. }
  4371. }
  4372. }
  4373. return result;
  4374. }
  4375. BfTypedValue BfExprEvaluator::LookupIdentifier(BfIdentifierNode* identifierNode, bool ignoreInitialError, bool* hadError)
  4376. {
  4377. auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode);
  4378. if (qualifiedNameNode != NULL)
  4379. {
  4380. LookupQualifiedName(qualifiedNameNode, ignoreInitialError, hadError);
  4381. auto qualifiedResult = mResult;
  4382. mResult = BfTypedValue();
  4383. return qualifiedResult;
  4384. }
  4385. StringT<128> identifierStr;
  4386. identifierNode->ToString(identifierStr);
  4387. return LookupIdentifier(identifierNode, identifierStr, ignoreInitialError, hadError);
  4388. }
  4389. void BfExprEvaluator::Visit(BfIdentifierNode* identifierNode)
  4390. {
  4391. auto autoComplete = GetAutoComplete();
  4392. if (autoComplete != NULL)
  4393. autoComplete->CheckIdentifier(identifierNode, true);
  4394. mResult = LookupIdentifier(identifierNode);
  4395. if ((!mResult) && (mPropDef == NULL))
  4396. {
  4397. mModule->CheckTypeRefFixit(identifierNode);
  4398. if ((autoComplete != NULL) && (autoComplete->CheckFixit(identifierNode)))
  4399. {
  4400. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  4401. {
  4402. // During this phase we don't have lambda and local method params available so they would result in erroneous fixits
  4403. }
  4404. else if (mModule->mCurMethodInstance != NULL)
  4405. {
  4406. BfType* fieldType = mExpectingType;
  4407. if (fieldType == NULL)
  4408. fieldType = mModule->mContext->mBfObjectType;
  4409. autoComplete->FixitAddMember(mModule->mCurTypeInstance, fieldType, identifierNode->ToString(), true, mModule->mCurTypeInstance);
  4410. if (!mModule->mCurMethodInstance->mMethodDef->mIsStatic)
  4411. autoComplete->FixitAddMember(mModule->mCurTypeInstance, fieldType, identifierNode->ToString(), false, mModule->mCurTypeInstance);
  4412. for (auto typeDef : mModule->mSystem->mTypeDefs)
  4413. {
  4414. if (!typeDef->mIsCombinedPartial)
  4415. continue;
  4416. if (!typeDef->IsGlobalsContainer())
  4417. continue;
  4418. typeDef->PopulateMemberSets();
  4419. String findName = identifierNode->ToString();
  4420. BfMemberSetEntry* memberSetEntry;
  4421. if ((typeDef->mMethodSet.TryGetWith(findName, &memberSetEntry)) ||
  4422. (typeDef->mFieldSet.TryGetWith(findName, &memberSetEntry)) ||
  4423. (typeDef->mPropertySet.TryGetWith(findName, &memberSetEntry)))
  4424. {
  4425. if (mModule->GetActiveTypeDef()->mProject->ContainsReference(typeDef->mProject))
  4426. autoComplete->FixitAddNamespace(identifierNode, typeDef->mNamespace.ToString());
  4427. }
  4428. }
  4429. }
  4430. }
  4431. if (((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0) && (mModule->mCurTypeInstance != NULL) && (CheckForMethodName(identifierNode, mModule->mCurTypeInstance, identifierNode->ToString())))
  4432. return;
  4433. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  4434. mModule->Fail("Identifier not found", identifierNode);
  4435. }
  4436. }
  4437. void BfExprEvaluator::Visit(BfAttributedIdentifierNode* attrIdentifierNode)
  4438. {
  4439. if ((mModule->mAttributeState != NULL))
  4440. {
  4441. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  4442. VisitChild(attrIdentifierNode->mIdentifier);
  4443. }
  4444. else
  4445. {
  4446. BfAttributeState attributeState;
  4447. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  4448. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  4449. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  4450. VisitChild(attrIdentifierNode->mIdentifier);
  4451. }
  4452. }
  4453. static int gPropIdx = 0;
  4454. void BfExprEvaluator::FixitAddMember(BfTypeInstance* typeInst, BfType* fieldType, const StringImpl& fieldName, bool isStatic)
  4455. {
  4456. if (fieldType == NULL)
  4457. {
  4458. fieldType = mExpectingType;
  4459. }
  4460. if (fieldType != NULL)
  4461. {
  4462. if (fieldType->IsRef())
  4463. fieldType = fieldType->GetUnderlyingType();
  4464. }
  4465. mModule->mCompiler->mResolvePassData->mAutoComplete->FixitAddMember(typeInst, fieldType, fieldName, isStatic, mModule->mCurTypeInstance);
  4466. }
  4467. BfTypedValue BfExprEvaluator::TryArrowLookup(BfTypedValue typedValue, BfTokenNode* arrowToken)
  4468. {
  4469. auto arrowValue = PerformUnaryOperation_TryOperator(typedValue, NULL, BfUnaryOp_Arrow, arrowToken, BfUnaryOpFlag_None);
  4470. if (arrowValue)
  4471. return arrowValue;
  4472. if (mModule->PreFail())
  4473. mModule->Fail(StrFormat("Type '%s' does not contain a '->' operator", mModule->TypeToString(typedValue.mType).c_str()), arrowToken);
  4474. return typedValue;
  4475. }
  4476. BfTypedValue BfExprEvaluator::LoadProperty(BfAstNode* targetSrc, BfTypedValue target, BfTypeInstance* typeInstance, BfPropertyDef* prop, BfLookupFieldFlags flags, BfCheckedKind checkedKind, bool isInlined)
  4477. {
  4478. BfTypedValue origTarget = target;
  4479. if ((target.mType != NULL) && (target.mType->IsStructPtr()))
  4480. {
  4481. target = mModule->LoadValue(target);
  4482. target = BfTypedValue(target.mValue, target.mType->GetUnderlyingType(), target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  4483. }
  4484. if ((flags & BfLookupFieldFlag_IsAnonymous) == 0)
  4485. mModule->SetElementType(targetSrc, BfSourceElementType_Method);
  4486. if ((!prop->mIsStatic) && ((flags & BfLookupFieldFlag_IsImplicitThis) != 0))
  4487. mModule->MarkUsingThis();
  4488. mPropSrc = targetSrc;
  4489. mPropDef = prop;
  4490. mPropCheckedKind = checkedKind;
  4491. if (isInlined)
  4492. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  4493. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  4494. {
  4495. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef))
  4496. {
  4497. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_Friend);
  4498. mModule->mAttributeState->mUsed = true;
  4499. }
  4500. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  4501. {
  4502. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_DisableObjectAccessChecks);
  4503. mModule->mAttributeState->mUsed = true;
  4504. }
  4505. }
  4506. if (mPropDef->mIsStatic)
  4507. {
  4508. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!typeInstance->mTypeDef->IsGlobalsContainer()))
  4509. {
  4510. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  4511. mModule->Fail(StrFormat("Property '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  4512. mModule->TypeToString(typeInstance).c_str(), mPropDef->mName.c_str()), targetSrc);
  4513. }
  4514. }
  4515. bool isBaseLookup = (target.mType) && (typeInstance != target.mType);
  4516. if ((isBaseLookup) && (target.mType->IsWrappableType()))
  4517. isBaseLookup = false;
  4518. if (prop->mIsStatic)
  4519. mPropTarget = BfTypedValue(typeInstance);
  4520. else if (isBaseLookup)
  4521. {
  4522. if (target.mValue.IsFake())
  4523. {
  4524. mPropTarget = BfTypedValue(target.mValue, typeInstance, target.mKind);
  4525. }
  4526. else
  4527. {
  4528. mPropTarget = mModule->Cast(targetSrc, target, typeInstance);
  4529. BF_ASSERT(mPropTarget);
  4530. }
  4531. }
  4532. else
  4533. mPropTarget = target;
  4534. mOrigPropTarget = mPropTarget;
  4535. if (prop->mIsStatic)
  4536. mOrigPropTarget = target;
  4537. #ifdef _DEBUG
  4538. if (mPropTarget)
  4539. {
  4540. auto propTargetTypeInst = mPropTarget.mType->ToTypeInstance();
  4541. if (propTargetTypeInst != NULL)
  4542. {
  4543. BF_ASSERT(prop->mDeclaringType->mFullNameEx == propTargetTypeInst->mTypeDef->mFullNameEx);
  4544. }
  4545. }
  4546. #endif
  4547. if ((flags & BfLookupFieldFlag_IsAnonymous) == 0)
  4548. {
  4549. auto autoComplete = GetAutoComplete();
  4550. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  4551. if (((autoComplete != NULL) && (autoComplete->mIsGetDefinition)) ||
  4552. ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Property)))
  4553. {
  4554. BfPropertyDef* basePropDef = mPropDef;
  4555. BfTypeInstance* baseTypeInst = typeInstance;
  4556. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  4557. resolvePassData->HandlePropertyReference(targetSrc, baseTypeInst->mTypeDef, basePropDef);
  4558. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetSrc)))
  4559. {
  4560. if (autoComplete->mIsGetDefinition)
  4561. {
  4562. //NOTE: passing 'force=true' in here causes https://github.com/beefytech/Beef/issues/1064
  4563. autoComplete->SetDefinitionLocation(basePropDef->GetRefNode());
  4564. }
  4565. autoComplete->mDefProp = basePropDef;
  4566. autoComplete->mDefType = baseTypeInst->mTypeDef;
  4567. }
  4568. }
  4569. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)))
  4570. {
  4571. BfPropertyDef* basePropDef = mPropDef;
  4572. BfTypeInstance* baseTypeInst = typeInstance;
  4573. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  4574. autoComplete->mResultString = ":";
  4575. autoComplete->mResultString += mModule->TypeToString(baseTypeInst);
  4576. autoComplete->mResultString += ".";
  4577. autoComplete->mResultString += basePropDef->mName;
  4578. }
  4579. }
  4580. // Check for direct auto-property access
  4581. if ((target.mType == mModule->mCurTypeInstance) && ((flags & BfLookupFieldFlag_BindOnly) == 0))
  4582. {
  4583. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(mPropDef->mFieldDeclaration))
  4584. {
  4585. if ((typeInstance->mTypeDef->HasAutoProperty(propertyDeclaration)) && (propertyDeclaration->mVirtualSpecifier == NULL))
  4586. {
  4587. BfMethodDef* getter = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, BfCheckedKind_NotSet, mPropTarget);
  4588. BfMethodDef* setter = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, BfCheckedKind_NotSet, mPropTarget);
  4589. bool optAllowed = true;
  4590. if ((getter != NULL) && (getter->mBody != NULL))
  4591. optAllowed = false;
  4592. if ((setter != NULL) && (setter->mBody != NULL))
  4593. optAllowed = false;
  4594. if (optAllowed)
  4595. {
  4596. auto autoFieldName = typeInstance->mTypeDef->GetAutoPropertyName(propertyDeclaration);
  4597. auto result = LookupField(targetSrc, target, autoFieldName, (BfLookupFieldFlags)(BfLookupFieldFlag_IgnoreProtection | BfLookupFieldFlag_IsImplicitThis));
  4598. if (result)
  4599. {
  4600. bool needsCopy = true;
  4601. if (BfNodeIsA<BfRefTypeRef>(prop->mTypeRef))
  4602. {
  4603. // Allow full ref
  4604. }
  4605. else
  4606. {
  4607. if (setter == NULL)
  4608. {
  4609. if (((mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)) &&
  4610. (target.mType == mModule->mCurTypeInstance))
  4611. {
  4612. // Allow writing inside ctor
  4613. }
  4614. else
  4615. {
  4616. result.MakeReadOnly();
  4617. needsCopy = false;
  4618. }
  4619. }
  4620. if (result.mKind == BfTypedValueKind_Addr)
  4621. result.mKind = BfTypedValueKind_CopyOnMutateAddr;
  4622. }
  4623. mPropDef = NULL;
  4624. mPropSrc = NULL;
  4625. mOrigPropTarget = BfTypedValue();
  4626. return result;
  4627. }
  4628. }
  4629. }
  4630. }
  4631. }
  4632. if (!mPropDef->mIsStatic)
  4633. {
  4634. SetAndRestoreValue<BfTypedValue> prevResult(mResult, target);
  4635. CheckResultForReading(mResult);
  4636. }
  4637. return BfTypedValue();
  4638. }
  4639. BfTypedValue BfExprEvaluator::LoadField(BfAstNode* targetSrc, BfTypedValue target, BfTypeInstance* typeInstance, BfFieldDef* fieldDef, BfLookupFieldFlags flags)
  4640. {
  4641. if (fieldDef->mIsProperty)
  4642. {
  4643. BfPropertyDef* propDef = (BfPropertyDef*)fieldDef;
  4644. return LoadProperty(targetSrc, target, typeInstance, propDef, flags, BfCheckedKind_NotSet, false);
  4645. }
  4646. bool isFailurePass = (flags & BfLookupFieldFlag_IsFailurePass) != 0;
  4647. auto fieldInstance = &typeInstance->mFieldInstances[fieldDef->mIdx];
  4648. bool isResolvingFields = typeInstance->mResolvingConstField || typeInstance->mResolvingVarField;
  4649. if (fieldDef->mIsVolatile)
  4650. mIsVolatileReference = true;
  4651. if (fieldInstance->mCustomAttributes != NULL)
  4652. mModule->CheckErrorAttributes(fieldInstance->mOwner, NULL, fieldInstance, fieldInstance->mCustomAttributes, targetSrc);
  4653. if (isFailurePass)
  4654. {
  4655. if (mModule->GetCeDbgState() == NULL)
  4656. mModule->Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", mModule->TypeToString(typeInstance).c_str(), fieldDef->mName.c_str()), targetSrc);
  4657. }
  4658. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  4659. if ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field) && ((flags & BfLookupFieldFlag_IsAnonymous) == 0))
  4660. {
  4661. resolvePassData->HandleFieldReference(targetSrc, typeInstance->mTypeDef, fieldDef);
  4662. }
  4663. if ((!typeInstance->mTypeFailed) && (!isResolvingFields) && (typeInstance->IsIncomplete()))
  4664. {
  4665. if ((fieldInstance->mResolvedType == NULL) ||
  4666. (!fieldDef->mIsStatic))
  4667. {
  4668. mModule->PopulateType(typeInstance, BfPopulateType_Data);
  4669. // Update fieldInstance pointer as it may have moved
  4670. fieldInstance = &typeInstance->mFieldInstances[fieldDef->mIdx];
  4671. }
  4672. }
  4673. if (fieldInstance->mResolvedType == NULL)
  4674. {
  4675. if (mModule->mCompiler->EnsureCeUnpaused(typeInstance))
  4676. {
  4677. BF_ASSERT((typeInstance->mTypeFailed) || (isResolvingFields));
  4678. }
  4679. return BfTypedValue();
  4680. }
  4681. if (fieldInstance->mFieldIdx == -1)
  4682. {
  4683. mModule->AssertErrorState();
  4684. return BfTypedValue();
  4685. }
  4686. if ((!fieldDef->mIsStatic) && ((flags & BfLookupFieldFlag_IsImplicitThis) != 0))
  4687. mModule->MarkUsingThis();
  4688. mResultFieldInstance = fieldInstance;
  4689. // Are we accessing a 'var' field that has not yet been resolved?
  4690. if (IsVar(fieldInstance->mResolvedType))
  4691. {
  4692. // This can happen if we have one var field referencing another var field
  4693. fieldInstance->mResolvedType = mModule->ResolveVarFieldType(typeInstance, fieldInstance, fieldDef);
  4694. if (fieldInstance->mResolvedType == NULL)
  4695. return BfTypedValue();
  4696. }
  4697. auto resolvedFieldType = fieldInstance->mResolvedType;
  4698. if (fieldInstance->mIsEnumPayloadCase)
  4699. {
  4700. resolvedFieldType = typeInstance;
  4701. }
  4702. mModule->PopulateType(resolvedFieldType, BfPopulateType_Data);
  4703. mModule->AddDependency(typeInstance, mModule->mCurTypeInstance, fieldDef->mIsConst ? BfDependencyMap::DependencyFlag_ConstValue : BfDependencyMap::DependencyFlag_ReadFields);
  4704. if (fieldInstance->mHadConstEval)
  4705. {
  4706. mModule->AddDependency(typeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ConstEvalConstField);
  4707. if ((mModule->mContext->mCurTypeState != NULL) && (mModule->mContext->mCurTypeState->mCurFieldDef != NULL))
  4708. {
  4709. // If we're initializing another const field then also set it as having const eval
  4710. auto resolvingFieldInstance = &mModule->mContext->mCurTypeState->mType->ToTypeInstance()->mFieldInstances[mModule->mContext->mCurTypeState->mCurFieldDef->mIdx];
  4711. if (resolvingFieldInstance->GetFieldDef()->mIsConst)
  4712. resolvingFieldInstance->mHadConstEval = true;
  4713. }
  4714. }
  4715. if ((flags & BfLookupFieldFlag_IsAnonymous) == 0)
  4716. {
  4717. auto autoComplete = GetAutoComplete();
  4718. if (autoComplete != NULL)
  4719. {
  4720. autoComplete->CheckFieldRef(BfNodeDynCast<BfIdentifierNode>(targetSrc), fieldInstance);
  4721. if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)))
  4722. {
  4723. autoComplete->mResultString = ":";
  4724. autoComplete->mResultString += mModule->TypeToString(fieldInstance->mResolvedType);
  4725. autoComplete->mResultString += " ";
  4726. autoComplete->mResultString += mModule->TypeToString(typeInstance);
  4727. autoComplete->mResultString += ".";
  4728. autoComplete->mResultString += fieldDef->mName;
  4729. if (fieldInstance->mConstIdx != -1)
  4730. {
  4731. String constStr = autoComplete->ConstantToString(typeInstance->mConstHolder, BfTypedValue(BfIRValue(BfIRValueFlags_Const, fieldInstance->mConstIdx), fieldInstance->mResolvedType));
  4732. if (!constStr.IsEmpty())
  4733. {
  4734. autoComplete->mResultString += " = ";
  4735. if (constStr.StartsWith(':'))
  4736. autoComplete->mResultString.Append(StringView(constStr, 1, constStr.mLength - 1));
  4737. else
  4738. autoComplete->mResultString += constStr;
  4739. }
  4740. }
  4741. auto fieldDecl = fieldInstance->GetFieldDef()->GetFieldDeclaration();
  4742. if ((fieldDecl != NULL) && (fieldDecl->mDocumentation != NULL))
  4743. {
  4744. String docString;
  4745. fieldDecl->mDocumentation->GetDocString(docString);
  4746. autoComplete->mResultString += "\x03";
  4747. autoComplete->mResultString += docString;
  4748. }
  4749. }
  4750. }
  4751. }
  4752. if (fieldDef->mIsStatic)
  4753. {
  4754. if (target)
  4755. {
  4756. //BF_ASSERT((flags & BfLookupFieldFlag_HasInstance) != 0);
  4757. flags = (BfLookupFieldFlags)(flags | BfLookupFieldFlag_HasInstance);
  4758. }
  4759. if (((flags & BfLookupFieldFlag_HasInstance) != 0) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!typeInstance->mTypeDef->IsGlobalsContainer()))
  4760. {
  4761. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  4762. mModule->Fail(StrFormat("Member '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  4763. mModule->TypeToString(typeInstance).c_str(), fieldDef->mName.c_str()), targetSrc);
  4764. }
  4765. // Target must be an implicit 'this', or an error (accessing a static with a non-static target).
  4766. // Not actually needed in either case since this is a static lookup.
  4767. mResultLocalVar = NULL;
  4768. }
  4769. bool isConst = false;
  4770. if (fieldDef->mIsConst)
  4771. {
  4772. isConst = true;
  4773. auto fieldDef = fieldInstance->GetFieldDef();
  4774. if ((resolvedFieldType->IsPointer()) && (fieldDef->mIsExtern))
  4775. isConst = false;
  4776. }
  4777. if (isConst)
  4778. {
  4779. if (fieldInstance->mIsEnumPayloadCase)
  4780. {
  4781. auto dscrType = typeInstance->GetDiscriminatorType();
  4782. mModule->mBfIRBuilder->PopulateType(typeInstance);
  4783. int tagIdx = -fieldInstance->mDataIdx - 1;
  4784. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowEnumId) != 0)
  4785. {
  4786. return BfTypedValue(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), fieldInstance->mOwner);
  4787. }
  4788. mModule->PopulateType(fieldInstance->mOwner, BfPopulateType_Data);
  4789. if (auto fieldTypeInstance = fieldInstance->mResolvedType->ToTypeInstance())
  4790. {
  4791. bool hasFields = false;
  4792. for (auto& fieldInstance : fieldTypeInstance->mFieldInstances)
  4793. {
  4794. if (!fieldInstance.mResolvedType->IsVoid())
  4795. hasFields = true;
  4796. }
  4797. if (hasFields)
  4798. mModule->FailAfter("Enum payload arguments expected", targetSrc);
  4799. }
  4800. SizedArray<BfIRValue, 3> values;
  4801. values.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(typeInstance->mBaseType)));
  4802. values.Add(mModule->GetDefaultValue(typeInstance->GetUnionInnerType()));
  4803. values.Add(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx));
  4804. return BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(typeInstance), values), typeInstance);
  4805. }
  4806. if (fieldInstance->mConstIdx == -1)
  4807. {
  4808. if ((mBfEvalExprFlags & BfEvalExprFlags_DeclType) != 0)
  4809. {
  4810. // We don't need a real value
  4811. return BfTypedValue(mModule->GetDefaultValue(resolvedFieldType), resolvedFieldType);
  4812. }
  4813. typeInstance->mModule->ResolveConstField(typeInstance, fieldInstance, fieldDef);
  4814. if (fieldInstance->mConstIdx == -1)
  4815. return BfTypedValue(mModule->GetDefaultValue(resolvedFieldType), resolvedFieldType);
  4816. }
  4817. BF_ASSERT(fieldInstance->mConstIdx != -1);
  4818. auto foreignConst = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4819. auto retVal = mModule->ConstantToCurrent(foreignConst, typeInstance->mConstHolder, resolvedFieldType);
  4820. return BfTypedValue(retVal, resolvedFieldType);
  4821. }
  4822. else if (fieldDef->mIsStatic)
  4823. {
  4824. if ((mModule->mAttributeState == NULL) || (mModule->mAttributeState->mCustomAttributes == NULL) ||
  4825. (!mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoStaticCtorAttributeTypeDef)))
  4826. {
  4827. mModule->CheckStaticAccess(typeInstance);
  4828. }
  4829. auto retVal = mModule->ReferenceStaticField(fieldInstance);
  4830. bool isStaticCtor = (mModule->mCurMethodInstance != NULL) &&
  4831. (mModule->mCurMethodInstance->mMethodDef->IsCtorOrInit()) &&
  4832. (mModule->mCurMethodInstance->mMethodDef->mIsStatic);
  4833. if ((mModule->mCompiler->mOptions.mRuntimeChecks) && (fieldInstance->IsAppendedObject()) && (!fieldDef->mIsStatic) && (!mModule->mBfIRBuilder->mIgnoreWrites) &&
  4834. (!mModule->IsSkippingExtraResolveChecks()))
  4835. {
  4836. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  4837. auto intPtrType = mModule->CreatePointerType(intType);
  4838. auto intPtrVal = mModule->mBfIRBuilder->CreateBitCast(retVal.mValue, mModule->mBfIRBuilder->MapType(intPtrType));
  4839. auto intVal = mModule->mBfIRBuilder->CreateLoad(intPtrVal);
  4840. auto oobBlock = mModule->mBfIRBuilder->CreateBlock("oob", true);
  4841. auto contBlock = mModule->mBfIRBuilder->CreateBlock("cont", true);
  4842. auto cmpRes = mModule->mBfIRBuilder->CreateCmpEQ(intVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4843. mModule->mBfIRBuilder->CreateCondBr(cmpRes, oobBlock, contBlock);
  4844. mModule->mBfIRBuilder->SetInsertPoint(oobBlock);
  4845. auto internalType = mModule->ResolveTypeDef(mModule->mCompiler->mInternalTypeDef);
  4846. auto oobFunc = mModule->GetMethodByName(internalType->ToTypeInstance(), "ThrowObjectNotInitialized");
  4847. if (oobFunc.mFunc)
  4848. {
  4849. if (mModule->mIsComptimeModule)
  4850. mModule->mCompiler->mCeMachine->QueueMethod(oobFunc.mMethodInstance, oobFunc.mFunc);
  4851. SizedArray<BfIRValue, 1> args;
  4852. args.push_back(mModule->GetConstValue(0));
  4853. mModule->mBfIRBuilder->CreateCall(oobFunc.mFunc, args);
  4854. mModule->mBfIRBuilder->CreateUnreachable();
  4855. }
  4856. else
  4857. {
  4858. mModule->Fail("System.Internal class must contain method 'ThrowObjectNotInitialized'", fieldDef->GetRefNode());
  4859. }
  4860. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  4861. }
  4862. if ((fieldDef->mIsReadOnly) && (!isStaticCtor))
  4863. {
  4864. if (retVal.IsAddr())
  4865. retVal.mKind = BfTypedValueKind_ReadOnlyAddr;
  4866. }
  4867. else
  4868. mIsHeapReference = true;
  4869. return retVal;
  4870. }
  4871. else if (!target)
  4872. {
  4873. if (((mBfEvalExprFlags & BfEvalExprFlags_NameOf) == 0) && (mModule->PreFail()))
  4874. {
  4875. if ((flags & BfLookupFieldFlag_CheckingOuter) != 0)
  4876. mModule->Fail(StrFormat("An instance reference is required to reference non-static outer field '%s.%s'", mModule->TypeToString(typeInstance).c_str(), fieldDef->mName.c_str()),
  4877. targetSrc);
  4878. else if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  4879. {
  4880. if ((mBfEvalExprFlags & BfEvalExprFlags_DeclType) == 0)
  4881. mModule->Fail(StrFormat("Cannot reference field '%s' before append allocations", fieldDef->mName.c_str()), targetSrc);
  4882. }
  4883. else
  4884. mModule->Fail(StrFormat("Cannot reference non-static field '%s' from a static method", fieldDef->mName.c_str()), targetSrc);
  4885. }
  4886. return mModule->GetDefaultTypedValue(resolvedFieldType, false, BfDefaultValueKind_Addr);
  4887. }
  4888. if (resolvedFieldType->IsValuelessType())
  4889. {
  4890. return BfTypedValue(BfIRValue::sValueless, resolvedFieldType, true);
  4891. }
  4892. if ((mResultLocalVar != NULL) && (fieldInstance->mMergedDataIdx != -1))
  4893. {
  4894. if (mResultLocalVarFieldCount != 1)
  4895. {
  4896. fieldInstance->GetDataRange(mResultLocalVarField, mResultLocalVarFieldCount);
  4897. mResultLocalVarRefNode = targetSrc;
  4898. }
  4899. }
  4900. if ((typeInstance->IsIncomplete()) && (!typeInstance->mNeedsMethodProcessing))
  4901. {
  4902. BF_ASSERT(typeInstance->mTypeFailed || (mModule->mCurMethodState == NULL) || (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCompiler->IsAutocomplete()));
  4903. return mModule->GetDefaultTypedValue(resolvedFieldType);
  4904. }
  4905. bool isTemporary = target.IsTempAddr();
  4906. bool wantsLoadValue = false;
  4907. bool wantsReadOnly = false;
  4908. if ((fieldDef->mIsReadOnly) && (mModule->mCurMethodInstance != NULL) && ((!mModule->mCurMethodInstance->mMethodDef->IsCtorOrInit()) || (!target.IsThis())))
  4909. wantsReadOnly = true;
  4910. bool isComposite = target.mType->IsComposite();
  4911. if ((isComposite) && (!target.mType->IsTypedPrimitive()) && (!target.IsAddr()))
  4912. isTemporary = true;
  4913. if ((isComposite) && (!target.IsAddr()))
  4914. wantsLoadValue = true;
  4915. if ((target.mType->IsWrappableType()) && (!target.mType->IsPointer()))
  4916. {
  4917. BfTypeInstance* primStructType = mModule->GetWrappedStructType(target.mType);
  4918. BfIRValue allocaInst = mModule->CreateAlloca(primStructType, true, "tmpStruct");
  4919. BfIRValue elementAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  4920. mModule->mBfIRBuilder->CreateStore(target.mValue, elementAddr);
  4921. target = BfTypedValue(allocaInst, primStructType, true);
  4922. }
  4923. BfTypedValue targetValue;
  4924. if ((target.mType != typeInstance) && (!target.IsSplat()))
  4925. {
  4926. if ((!isComposite) || (target.IsAddr()))
  4927. targetValue = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  4928. else
  4929. {
  4930. BfIRValue curVal = target.mValue;
  4931. auto baseCheckType = target.mType->ToTypeInstance();
  4932. while (baseCheckType != typeInstance)
  4933. {
  4934. curVal = mModule->mBfIRBuilder->CreateExtractValue(curVal, 0);
  4935. baseCheckType = baseCheckType->mBaseType;
  4936. }
  4937. targetValue = BfTypedValue(curVal, typeInstance);
  4938. }
  4939. }
  4940. else
  4941. targetValue = target;
  4942. bool doAccessCheck = true;
  4943. if ((flags & BfLookupFieldFlag_BindOnly) != 0)
  4944. doAccessCheck = false;
  4945. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  4946. doAccessCheck = false;
  4947. if (target.IsThis())
  4948. {
  4949. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  4950. doAccessCheck = false;
  4951. }
  4952. if (doAccessCheck)
  4953. mModule->EmitObjectAccessCheck(target);
  4954. if (fieldInstance->mDataIdx < 0)
  4955. {
  4956. mModule->mCompiler->RequestExtraCompile();
  4957. mModule->InternalError("LoadField field DataIdx<0 where InstSize>0");
  4958. mModule->DeferRebuildType(typeInstance);
  4959. return mModule->GetDefaultTypedValue(resolvedFieldType);
  4960. }
  4961. BfTypedValue retVal;
  4962. if (targetValue.IsSplat())
  4963. {
  4964. retVal = mModule->ExtractValue(targetValue, fieldInstance, fieldInstance->mDataIdx);
  4965. }
  4966. else if ((target.mType->IsStruct()) && (!target.IsAddr()))
  4967. {
  4968. mModule->mBfIRBuilder->PopulateType(targetValue.mType);
  4969. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateExtractValue(targetValue.mValue, fieldInstance->mDataIdx/*, fieldDef->mName*/),
  4970. resolvedFieldType);
  4971. }
  4972. else
  4973. {
  4974. mModule->mBfIRBuilder->PopulateType(typeInstance);
  4975. if ((targetValue.IsAddr()) && (!typeInstance->IsValueType()))
  4976. targetValue = mModule->LoadValue(targetValue);
  4977. if (fieldInstance->IsAppendedObject())
  4978. {
  4979. auto elemPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(targetValue.mValue, 0, fieldInstance->mDataIdx);
  4980. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(elemPtr, mModule->mBfIRBuilder->MapType(resolvedFieldType)), resolvedFieldType);
  4981. }
  4982. else
  4983. {
  4984. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(targetValue.mValue, 0, fieldInstance->mDataIdx/*, fieldDef->mName*/),
  4985. resolvedFieldType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  4986. }
  4987. }
  4988. if (typeInstance->mIsUnion)
  4989. {
  4990. auto unionInnerType = typeInstance->GetUnionInnerType();
  4991. if (unionInnerType != resolvedFieldType)
  4992. {
  4993. BfTypedValue unionTypedValue = retVal;
  4994. unionTypedValue.mType = unionInnerType;
  4995. if (!unionTypedValue.IsAddr())
  4996. unionTypedValue = mModule->MakeAddressable(unionTypedValue);
  4997. BfIRType llvmPtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(resolvedFieldType));
  4998. retVal.mValue = mModule->mBfIRBuilder->CreateBitCast(unionTypedValue.mValue, llvmPtrType);
  4999. retVal.mKind = unionTypedValue.mKind;
  5000. }
  5001. }
  5002. if ((fieldDef->mIsVolatile) && (retVal.IsAddr()))
  5003. retVal.mKind = BfTypedValueKind_VolatileAddr;
  5004. if (wantsLoadValue)
  5005. retVal = mModule->LoadValue(retVal, NULL, mIsVolatileReference);
  5006. else
  5007. {
  5008. if ((wantsReadOnly) && (retVal.IsAddr()) && (!retVal.IsReadOnly()))
  5009. retVal.mKind = BfTypedValueKind_ReadOnlyAddr;
  5010. else if ((target.IsCopyOnMutate()) && (retVal.IsAddr()))
  5011. retVal.mKind = BfTypedValueKind_CopyOnMutateAddr_Derived;
  5012. mIsHeapReference = true;
  5013. }
  5014. if (isTemporary)
  5015. {
  5016. if (retVal.IsAddr())
  5017. retVal.mKind = BfTypedValueKind_TempAddr;
  5018. }
  5019. return retVal;
  5020. }
  5021. BfTypedValue BfExprEvaluator::LookupField(BfAstNode* targetSrc, BfTypedValue target, const StringImpl& fieldName, BfLookupFieldFlags flags)
  5022. {
  5023. if (target)
  5024. flags = (BfLookupFieldFlags)(flags | BfLookupFieldFlag_HasInstance);
  5025. if ((target.mType != NULL && (target.mType->IsGenericParam())))
  5026. {
  5027. auto genericParamType = (BfGenericParamType*)target.mType;
  5028. auto genericParamInst = mModule->GetGenericParamInstance(genericParamType);
  5029. if (target.mValue)
  5030. {
  5031. for (auto iface : genericParamInst->mInterfaceConstraints)
  5032. {
  5033. auto result = LookupField(targetSrc, BfTypedValue(target.mValue, iface), fieldName, flags);
  5034. if ((result) || (mPropDef != NULL))
  5035. {
  5036. return result;
  5037. }
  5038. }
  5039. }
  5040. bool isUnspecializedSection = false;
  5041. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  5042. isUnspecializedSection = (mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized);
  5043. else
  5044. isUnspecializedSection = (mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->IsUnspecializedType());
  5045. if (isUnspecializedSection)
  5046. {
  5047. auto origTarget = target;
  5048. if (genericParamInst->mTypeConstraint != NULL)
  5049. {
  5050. target.mType = genericParamInst->mTypeConstraint;
  5051. }
  5052. else
  5053. target.mType = mModule->mContext->mBfObjectType;
  5054. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  5055. {
  5056. target.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  5057. }
  5058. if (origTarget.mType->IsTypeGenericParam())
  5059. {
  5060. // Check for extern constraint in method generic params
  5061. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  5062. {
  5063. for (auto genericParam : mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams)
  5064. {
  5065. if (genericParam->mExternType == origTarget.mType)
  5066. {
  5067. if (genericParam->mTypeConstraint != NULL)
  5068. {
  5069. target.mType = genericParam->mTypeConstraint;
  5070. break;
  5071. }
  5072. }
  5073. }
  5074. }
  5075. }
  5076. if (target.mType->IsWrappableType())
  5077. target.mType = mModule->GetWrappedStructType(target.mType);
  5078. }
  5079. else
  5080. {
  5081. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  5082. {
  5083. //target.mType = mModule->ResolveGenericType(mResult.mType);
  5084. }
  5085. else if (genericParamInst->mTypeConstraint != NULL)
  5086. {
  5087. target = mModule->Cast(targetSrc, target, genericParamInst->mTypeConstraint);
  5088. BF_ASSERT(target);
  5089. }
  5090. else
  5091. {
  5092. // This shouldn't occur - this would infer that we are accessing a member of Object or something...
  5093. //target.mType = mModule->ResolveGenericType(mResult.mType);
  5094. }
  5095. }
  5096. }
  5097. if ((target.mType != NULL) && (IsVar(target.mType, (flags & BfLookupFieldFlag_BindOnly) != 0)))
  5098. return BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  5099. BfTypeInstance* startCheckType = mModule->mCurTypeInstance;
  5100. mPropDef = NULL;
  5101. mPropDefBypassVirtual = false;
  5102. if (target)
  5103. {
  5104. if ((!target.mType->IsValueType()) && (target.IsAddr()))
  5105. target = mModule->LoadValue(target);
  5106. if (target.mType->IsPrimitiveType())
  5107. {
  5108. auto primType = (BfPrimitiveType*)target.mType;
  5109. startCheckType = mModule->GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  5110. }
  5111. else
  5112. {
  5113. startCheckType = target.mType->ToTypeInstance();
  5114. if ((startCheckType == NULL) && (target.mType->IsPointer()))
  5115. {
  5116. startCheckType = ((BfPointerType*)target.mType)->mElementType->ToTypeInstance();
  5117. if ((startCheckType != NULL) && (!startCheckType->IsValueType()))
  5118. return BfTypedValue();
  5119. }
  5120. }
  5121. //BF_ASSERT(startCheckType != NULL);
  5122. }
  5123. else if (target.mType != NULL)
  5124. {
  5125. startCheckType = target.mType->ToTypeInstance();
  5126. }
  5127. if ((startCheckType != NULL) && (startCheckType->mBaseType == NULL))
  5128. {
  5129. if (startCheckType->mDefineState == BfTypeDefineState_ResolvingBaseType)
  5130. {
  5131. // Fixes cases where we have something like 'Base[Value]' as a base typeref
  5132. return BfTypedValue();
  5133. }
  5134. mModule->PopulateType(startCheckType, BfPopulateType_BaseType);
  5135. }
  5136. String findName;
  5137. int varSkipCount = 0;
  5138. if (fieldName.StartsWith('@'))
  5139. {
  5140. findName = fieldName;
  5141. while (findName.StartsWith('@'))
  5142. {
  5143. findName.Remove(0);
  5144. varSkipCount++;
  5145. }
  5146. }
  5147. else
  5148. findName.Reference(fieldName);
  5149. auto activeTypeDef = mModule->GetActiveTypeDef();
  5150. for (int pass = 0; pass < 2; pass++)
  5151. {
  5152. auto curCheckType = startCheckType;
  5153. bool isFailurePass = pass == 1;
  5154. if (isFailurePass)
  5155. flags = (BfLookupFieldFlags)(flags | BfLookupFieldFlag_IsFailurePass);
  5156. bool isBaseLookup = false;
  5157. int checkInterfaceIdx = 0;
  5158. while (curCheckType != NULL)
  5159. {
  5160. if (((flags & BfLookupFieldFlag_CheckingOuter) != 0) && ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0))
  5161. {
  5162. // Don't fully populateType for CheckingOuter - it carries a risk of an inadvertent data cycle
  5163. // Avoiding this could cause issues finding emitted statics/constants
  5164. }
  5165. else
  5166. {
  5167. bool isPopulatingType = false;
  5168. auto checkTypeState = mModule->mContext->mCurTypeState;
  5169. while (checkTypeState != NULL)
  5170. {
  5171. if (curCheckType == checkTypeState->mType)
  5172. {
  5173. isPopulatingType = true;
  5174. if (checkTypeState->mResolveKind == BfTypeState::ResolveKind_Attributes)
  5175. {
  5176. // Don't allow lookups yet
  5177. return BfTypedValue();
  5178. }
  5179. }
  5180. checkTypeState = checkTypeState->mPrevState;
  5181. }
  5182. if ((!isPopulatingType) && (curCheckType->mDefineState < Beefy::BfTypeDefineState_Defined))
  5183. {
  5184. // We MAY have emitted fields so we need to do this
  5185. mModule->mContext->mUnreifiedModule->PopulateType(curCheckType, Beefy::BfPopulateType_Interfaces_All);
  5186. }
  5187. }
  5188. curCheckType->mTypeDef->PopulateMemberSets();
  5189. BfFieldDef* nextField = NULL;
  5190. BfMemberSetEntry* entry;
  5191. if (curCheckType->mTypeDef->mFieldSet.TryGetWith(findName, &entry))
  5192. nextField = (BfFieldDef*)entry->mMemberDef;
  5193. if (nextField != NULL)
  5194. varSkipCount -= nextField->mNamePrefixCount;
  5195. while ((varSkipCount > 0) && (nextField != NULL))
  5196. {
  5197. nextField = nextField->mNextWithSameName;
  5198. varSkipCount--;
  5199. }
  5200. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  5201. if (target)
  5202. {
  5203. if ((flags & (BfLookupFieldFlag_IsImplicitThis | BfLookupFieldFlag_BaseLookup)) != 0)
  5204. {
  5205. // Not an "instance lookup"
  5206. }
  5207. else
  5208. {
  5209. protectionCheckFlags = (BfProtectionCheckFlags)(protectionCheckFlags | BfProtectionCheckFlag_InstanceLookup);
  5210. }
  5211. }
  5212. BfFieldDef* matchedField = NULL;
  5213. while (nextField != NULL)
  5214. {
  5215. if ((flags & BfLookupFieldFlag_BindOnly) != 0)
  5216. break;
  5217. auto field = nextField;
  5218. nextField = nextField->mNextWithSameName;
  5219. auto checkProtection = field->mProtection;
  5220. if (checkProtection == BfProtection_Hidden)
  5221. {
  5222. // Allow accessing hidden fields
  5223. checkProtection = BfProtection_Private;
  5224. }
  5225. if (((flags & BfLookupFieldFlag_IgnoreProtection) == 0) && (!isFailurePass) &&
  5226. (!mModule->CheckProtection(protectionCheckFlags, curCheckType, field->mDeclaringType->mProject, checkProtection, startCheckType)))
  5227. {
  5228. continue;
  5229. }
  5230. bool isResolvingFields = curCheckType->mResolvingConstField || curCheckType->mResolvingVarField;
  5231. if (curCheckType->mFieldInstances.IsEmpty())
  5232. {
  5233. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  5234. }
  5235. if (field->mIdx >= (int)curCheckType->mFieldInstances.size())
  5236. {
  5237. if (mModule->mCompiler->EnsureCeUnpaused(curCheckType))
  5238. {
  5239. BF_DBG_FATAL("OOB in DoLookupField");
  5240. }
  5241. return mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  5242. }
  5243. BF_ASSERT(field->mIdx < (int)curCheckType->mFieldInstances.size());
  5244. auto fieldInstance = &curCheckType->mFieldInstances[field->mIdx];
  5245. if (!fieldInstance->mFieldIncluded)
  5246. continue;
  5247. if (curCheckType->IsUnspecializedType())
  5248. {
  5249. // The check for non-unspecialized types is already handled in mFieldIncluded
  5250. if (!curCheckType->IsTypeMemberIncluded(field->mDeclaringType, activeTypeDef, mModule))
  5251. continue;
  5252. }
  5253. if (!mModule->IsInSpecializedSection())
  5254. {
  5255. if (!curCheckType->IsTypeMemberAccessible(field->mDeclaringType, activeTypeDef))
  5256. continue;
  5257. }
  5258. if (matchedField != NULL)
  5259. {
  5260. auto error = mModule->Fail(StrFormat("Ambiguous reference to field '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  5261. if (error != NULL)
  5262. {
  5263. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", matchedField->mDeclaringType->mProject->mName.c_str()), matchedField->mFieldDeclaration);
  5264. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", field->mDeclaringType->mProject->mName.c_str()), field->mFieldDeclaration);
  5265. break;
  5266. }
  5267. }
  5268. matchedField = field;
  5269. }
  5270. if (matchedField != NULL)
  5271. return LoadField(targetSrc, target, curCheckType, matchedField, flags);
  5272. BfPropertyDef* nextProp = NULL;
  5273. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(fieldName, &entry))
  5274. nextProp = (BfPropertyDef*)entry->mMemberDef;
  5275. if (nextProp != NULL)
  5276. {
  5277. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  5278. bool isInlined = false;
  5279. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  5280. {
  5281. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  5282. {
  5283. isInlined = true;
  5284. mModule->mAttributeState->mUsed = true;
  5285. }
  5286. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  5287. {
  5288. checkedKind = BfCheckedKind_Checked;
  5289. mModule->mAttributeState->mUsed = true;
  5290. }
  5291. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  5292. {
  5293. checkedKind = BfCheckedKind_Unchecked;
  5294. mModule->mAttributeState->mUsed = true;
  5295. }
  5296. }
  5297. BfPropertyDef* matchedProp = NULL;
  5298. while (nextProp != NULL)
  5299. {
  5300. auto prop = nextProp;
  5301. nextProp = nextProp->mNextWithSameName;
  5302. if ((!isFailurePass) && ((mBfEvalExprFlags & BfEvalExprFlags_NameOf) == 0) && (!mModule->CheckProtection(protectionCheckFlags, curCheckType, prop->mDeclaringType->mProject, prop->mProtection, startCheckType)))
  5303. {
  5304. continue;
  5305. }
  5306. if (!prop->mMethods.IsEmpty())
  5307. {
  5308. BfMethodDef* checkMethod = prop->mMethods[0];
  5309. // Properties with explicit interfaces or marked as overrides can only be called indirectly
  5310. if ((checkMethod->mExplicitInterface != NULL) || (checkMethod->mIsOverride))
  5311. continue;
  5312. }
  5313. if ((!target.IsStatic()) || (prop->mIsStatic) || ((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0))
  5314. {
  5315. if (!curCheckType->IsTypeMemberIncluded(prop->mDeclaringType, activeTypeDef, mModule))
  5316. continue;
  5317. if (!mModule->IsInSpecializedSection())
  5318. {
  5319. if (!curCheckType->IsTypeMemberAccessible(prop->mDeclaringType, mModule->GetVisibleProjectSet()))
  5320. continue;
  5321. }
  5322. if (matchedProp != NULL)
  5323. {
  5324. if ((matchedProp->mDeclaringType->IsExtension()) && (!prop->mDeclaringType->IsExtension()))
  5325. {
  5326. // Prefer non-extension
  5327. continue;
  5328. }
  5329. else
  5330. {
  5331. if (mModule->PreFail())
  5332. {
  5333. auto error = mModule->Fail(StrFormat("Ambiguous reference to property '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  5334. if (error != NULL)
  5335. {
  5336. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", matchedProp->mDeclaringType->mProject->mName.c_str()), matchedProp->mFieldDeclaration);
  5337. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", prop->mDeclaringType->mProject->mName.c_str()), prop->mFieldDeclaration);
  5338. break;
  5339. }
  5340. }
  5341. }
  5342. }
  5343. matchedProp = prop;
  5344. }
  5345. }
  5346. if (matchedProp != NULL)
  5347. return LoadProperty(targetSrc, target, curCheckType, matchedProp, flags, checkedKind, isInlined);
  5348. }
  5349. if (curCheckType->mTypeDef->mHasUsingFields)
  5350. mModule->PopulateUsingFieldData(curCheckType);
  5351. ///
  5352. {
  5353. Array<SizedArray<BfUsingFieldData::MemberRef, 1>*> foundLists;
  5354. auto _CheckUsingData = [&](BfUsingFieldData* usingData)
  5355. {
  5356. BfUsingFieldData::Entry* entry = NULL;
  5357. if (!usingData->mEntries.TryGetValue(findName, &entry))
  5358. return;
  5359. for (int listIdx = 0; listIdx < entry->mLookups.mSize; listIdx++)
  5360. {
  5361. bool passesProtection = true;
  5362. auto& entryList = entry->mLookups[listIdx];
  5363. for (int entryIdx = 0; entryIdx < entryList.mSize; entryIdx++)
  5364. {
  5365. auto& entry = entryList[entryIdx];
  5366. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  5367. if (!mModule->CheckProtection(protectionCheckFlags, entry.mTypeInstance, entry.GetDeclaringType(mModule)->mProject,
  5368. (entryIdx < entryList.mSize - 1) ? entry.GetUsingProtection() : entry.GetProtection(), curCheckType))
  5369. {
  5370. passesProtection = false;
  5371. break;
  5372. }
  5373. }
  5374. if (!passesProtection)
  5375. continue;
  5376. if (foundLists.mSize == 0)
  5377. {
  5378. foundLists.Add(&entryList);
  5379. }
  5380. else
  5381. {
  5382. if (entryList.mSize < foundLists[0]->mSize)
  5383. {
  5384. // New is shorter
  5385. foundLists.Clear();
  5386. foundLists.Add(&entryList);
  5387. }
  5388. else if (entryList.mSize > foundLists[0]->mSize)
  5389. {
  5390. // Ignore longer
  5391. }
  5392. else
  5393. {
  5394. foundLists.Add(&entryList);
  5395. }
  5396. }
  5397. }
  5398. };
  5399. if ((curCheckType->mTypeInfoEx != NULL) && (curCheckType->mTypeInfoEx->mUsingFieldData != NULL))
  5400. _CheckUsingData(curCheckType->mTypeInfoEx->mUsingFieldData);
  5401. if (!foundLists.IsEmpty())
  5402. {
  5403. auto foundList = foundLists[0];
  5404. if (foundLists.mSize > 1)
  5405. {
  5406. BfError* error = mModule->Fail("Ambiguous 'using' field reference", targetSrc);
  5407. if (error != NULL)
  5408. {
  5409. for (auto checkList : foundLists)
  5410. {
  5411. String errorStr = "'";
  5412. for (int entryIdx = 0; entryIdx < checkList->mSize; entryIdx++)
  5413. {
  5414. if (entryIdx == 0)
  5415. errorStr += (*checkList)[entryIdx].GetFullName(mModule);
  5416. else
  5417. {
  5418. errorStr += ".";
  5419. errorStr += (*checkList)[entryIdx].GetName(mModule);
  5420. }
  5421. }
  5422. errorStr += "' is a candidate";
  5423. mModule->mCompiler->mPassInstance->MoreInfo(errorStr, (*checkList)[0].GetRefNode(mModule));
  5424. }
  5425. }
  5426. }
  5427. BfTypedValue curResult = target;
  5428. for (int entryIdx = 0; entryIdx < foundList->mSize; entryIdx++)
  5429. {
  5430. if ((entryIdx == 0) && (foundList->back().IsStatic()))
  5431. entryIdx = (int)foundList->mSize - 1;
  5432. auto& entry = (*foundList)[entryIdx];
  5433. if (mPropDef != NULL)
  5434. {
  5435. SetAndRestoreValue<BfTypedValue> prevResult(mResult, BfTypedValue());
  5436. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_Friend);
  5437. curResult = GetResult();
  5438. if (!curResult)
  5439. return curResult;
  5440. }
  5441. auto useFlags = flags;
  5442. if (entryIdx < foundList->mSize - 1)
  5443. useFlags = (BfLookupFieldFlags)(flags | BfLookupFieldFlag_IsAnonymous);
  5444. if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Field)
  5445. {
  5446. curResult = LoadField(targetSrc, curResult, entry.mTypeInstance, entry.mTypeInstance->mTypeDef->mFields[entry.mIdx], useFlags);
  5447. }
  5448. else if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Property)
  5449. {
  5450. curResult = LoadProperty(targetSrc, curResult, entry.mTypeInstance, entry.mTypeInstance->mTypeDef->mProperties[entry.mIdx], useFlags, BfCheckedKind_NotSet, false);
  5451. }
  5452. else if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Local)
  5453. {
  5454. auto localDef = mModule->mCurMethodState->mLocals[entry.mIdx];
  5455. curResult = LoadLocal(localDef);
  5456. }
  5457. if ((!curResult) && (mPropDef == NULL))
  5458. return curResult;
  5459. if (entryIdx == foundList->mSize - 1)
  5460. {
  5461. auto autoComplete = GetAutoComplete();
  5462. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetSrc)))
  5463. autoComplete->SetDefinitionLocation(entry.GetRefNode(mModule));
  5464. if ((autoComplete != NULL) && (autoComplete->CheckFixit(targetSrc)))
  5465. autoComplete->FixitAddFullyQualify(targetSrc, findName, *foundList);
  5466. }
  5467. }
  5468. return curResult;
  5469. }
  5470. }
  5471. if ((!isBaseLookup) && (startCheckType->IsInterface() && (checkInterfaceIdx < (int)startCheckType->mInterfaces.size())))
  5472. {
  5473. curCheckType = startCheckType->mInterfaces[checkInterfaceIdx].mInterfaceType;
  5474. checkInterfaceIdx++;
  5475. }
  5476. else
  5477. {
  5478. isBaseLookup = true;
  5479. curCheckType = curCheckType->mBaseType;
  5480. }
  5481. }
  5482. }
  5483. auto outerTypeDef = mModule->GetOuterType(startCheckType);
  5484. if (outerTypeDef != NULL)
  5485. {
  5486. BfLookupFieldFlags newFlags = BfLookupFieldFlag_CheckingOuter;
  5487. if (((flags & BfLookupFieldFlag_HasInstance) != 0) &&
  5488. ((flags & BfLookupFieldFlag_IsImplicitThis) == 0))
  5489. newFlags = (BfLookupFieldFlags)(newFlags | BfLookupFieldFlag_HasInstance);
  5490. // Check statics in outer type
  5491. return LookupField(targetSrc, BfTypedValue(outerTypeDef), fieldName, newFlags);
  5492. }
  5493. return BfTypedValue();
  5494. }
  5495. void BfExprEvaluator::ResolveArgValues(BfResolvedArgs& resolvedArgs, BfResolveArgsFlags flags)
  5496. {
  5497. static int idx = 0;
  5498. idx++;
  5499. int curIdx = idx;
  5500. if (resolvedArgs.mArguments == NULL)
  5501. return;
  5502. int argCount = (int)resolvedArgs.mArguments->size();
  5503. if ((resolvedArgs.mCommas != NULL) && (resolvedArgs.mCommas->size() != 0) && (resolvedArgs.mCommas->size() >= resolvedArgs.mArguments->size()))
  5504. {
  5505. //mModule->FailAfter("Expression expected", resolvedArgs.mCommas->back());
  5506. argCount++;
  5507. }
  5508. BfAutoComplete* autoComplete = GetAutoComplete();
  5509. bool hadIgnoredFixits = false;
  5510. if (autoComplete != NULL)
  5511. {
  5512. hadIgnoredFixits = autoComplete->mIgnoreFixits;
  5513. if (flags & BfResolveArgsFlag_DeferFixits)
  5514. autoComplete->mIgnoreFixits = true;
  5515. }
  5516. int deferredArgIdx = 0;
  5517. SizedArray<BfExpression*, 8> deferredArgs;
  5518. int argIdx = 0;
  5519. while (true)
  5520. {
  5521. //printf("Args: %p %p %d\n", resolvedArgs.mArguments, resolvedArgs.mArguments->mVals, resolvedArgs.mArguments->mSize);
  5522. BfExpression* argExpr = NULL;
  5523. bool isDeferredArg = false;
  5524. int curArgIdx = -1;
  5525. if (deferredArgIdx < deferredArgs.size())
  5526. {
  5527. argExpr = deferredArgs[deferredArgIdx++];
  5528. isDeferredArg = true;
  5529. }
  5530. else if (argIdx >= argCount)
  5531. {
  5532. break;
  5533. }
  5534. else
  5535. {
  5536. curArgIdx = argIdx++;
  5537. if (curArgIdx < resolvedArgs.mArguments->size())
  5538. argExpr = (*resolvedArgs.mArguments)[curArgIdx];
  5539. }
  5540. if (argExpr == NULL)
  5541. {
  5542. if (curArgIdx == 0)
  5543. {
  5544. if (resolvedArgs.mOpenToken != NULL)
  5545. mModule->FailAfter("Expression expected", resolvedArgs.mOpenToken);
  5546. }
  5547. else if (resolvedArgs.mCommas != NULL)
  5548. mModule->FailAfter("Expression expected", (*resolvedArgs.mCommas)[curArgIdx - 1]);
  5549. }
  5550. if (auto typedValueExpr = BfNodeDynCast<BfTypedValueExpression>(argExpr))
  5551. {
  5552. BfResolvedArg resolvedArg;
  5553. resolvedArg.mTypedValue = typedValueExpr->mTypedValue;
  5554. if (resolvedArg.mTypedValue.IsParams())
  5555. resolvedArg.mArgFlags = BfArgFlag_ParamsExpr;
  5556. resolvedArg.mExpression = typedValueExpr->mRefNode;
  5557. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  5558. continue;
  5559. }
  5560. BfResolvedArg resolvedArg;
  5561. if (isDeferredArg)
  5562. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_StringInterpolateArg);
  5563. BfExprEvaluator exprEvaluator(mModule);
  5564. exprEvaluator.mResolveGenericParam = (flags & BfResolveArgsFlag_AllowUnresolvedTypes) == 0;
  5565. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr |
  5566. (mBfEvalExprFlags & (BfEvalExprFlags_Comptime)));
  5567. bool handled = false;
  5568. bool evaluated = false;
  5569. if (auto namedExpression = BfNodeDynCastExact<BfNamedExpression>(argExpr))
  5570. {
  5571. resolvedArg.mNameNode = namedExpression->mNameNode;
  5572. argExpr = namedExpression->mExpression;
  5573. }
  5574. if (auto interpolateExpr = BfNodeDynCastExact<BfStringInterpolationExpression>(argExpr))
  5575. {
  5576. if ((interpolateExpr->mAllocNode == NULL) || ((flags & BfResolveArgsFlag_InsideStringInterpolationAlloc) != 0))
  5577. {
  5578. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_StringInterpolateFormat);
  5579. for (auto innerExpr : interpolateExpr->mExpressions)
  5580. deferredArgs.Add(innerExpr);
  5581. }
  5582. }
  5583. if (auto unaryOpExpr = BfNodeDynCastExact<BfUnaryOperatorExpression>(argExpr))
  5584. {
  5585. if ((unaryOpExpr->mOp == BfUnaryOp_Cascade) && ((flags & BfResolveArgsFlag_FromIndexer) == 0))
  5586. {
  5587. if ((mBfEvalExprFlags & BfEvalExprFlags_InCascade) != 0)
  5588. mModule->Fail("Cascade already specified on call target", unaryOpExpr->mOpToken);
  5589. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_Cascade);
  5590. argExpr = unaryOpExpr->mExpression;
  5591. }
  5592. }
  5593. bool deferParamEval = false;
  5594. if ((flags & BfResolveArgsFlag_DeferParamEval) != 0)
  5595. {
  5596. if (argExpr != NULL)
  5597. {
  5598. BfDeferEvalChecker deferEvalChecker;
  5599. if ((flags & BfResolveArgsFlag_DeferStrings) != 0)
  5600. deferEvalChecker.mDeferStrings = true;
  5601. deferEvalChecker.mDeferDelegateBind = false;
  5602. deferEvalChecker.Check(argExpr);
  5603. deferParamEval = deferEvalChecker.mNeedsDeferEval;
  5604. }
  5605. }
  5606. if (deferParamEval)
  5607. {
  5608. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredEval);
  5609. handled = true;
  5610. }
  5611. else if (auto delegateBindExpression = BfNodeDynCast<BfDelegateBindExpression>(argExpr))
  5612. {
  5613. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DelegateBindAttempt);
  5614. handled = true;
  5615. }
  5616. else if (auto lambdaBindExpression = BfNodeDynCast<BfLambdaBindExpression>(argExpr))
  5617. {
  5618. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_LambdaBindAttempt);
  5619. handled = true;
  5620. }
  5621. else if (auto defaultExpr = BfNodeDynCast<BfDefaultExpression>(argExpr))
  5622. {
  5623. if (defaultExpr->mTypeRef == NULL)
  5624. {
  5625. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UntypedDefault);
  5626. handled = true;
  5627. }
  5628. }
  5629. else if (auto varDeclExpr = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  5630. {
  5631. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  5632. handled = true;
  5633. }
  5634. else if (auto unaryExpr = BfNodeDynCast<BfUnaryOperatorExpression>(argExpr))
  5635. {
  5636. if (unaryExpr->mOp == BfUnaryOp_Params)
  5637. {
  5638. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ParamsExpr);
  5639. }
  5640. }
  5641. else if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(argExpr))
  5642. {
  5643. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UninitializedExpr);
  5644. handled = true;
  5645. }
  5646. if (!handled)
  5647. {
  5648. BfAstNode* checkArgExpr = argExpr;
  5649. while (checkArgExpr != NULL)
  5650. {
  5651. if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(checkArgExpr))
  5652. {
  5653. if (memberRef->mTarget == NULL)
  5654. {
  5655. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  5656. handled = true;
  5657. break;
  5658. }
  5659. else
  5660. checkArgExpr = memberRef->mTarget;
  5661. }
  5662. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(checkArgExpr))
  5663. {
  5664. checkArgExpr = invokeExpr->mTarget;
  5665. }
  5666. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkArgExpr))
  5667. {
  5668. checkArgExpr = parenExpr->mExpression;
  5669. }
  5670. else
  5671. break;
  5672. }
  5673. }
  5674. if ((argExpr != NULL) && (!handled))
  5675. {
  5676. bool deferParamValues = (flags & BfResolveArgsFlag_DeferParamValues) != 0;
  5677. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || deferParamValues);
  5678. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  5679. if (deferParamValues)
  5680. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredValue);
  5681. if (!evaluated)
  5682. {
  5683. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  5684. if ((resolvedArg.mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  5685. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_StringInterpolateFormat);
  5686. int lastLocalVarIdx = (mModule->mCurMethodState != NULL) ? mModule->mCurMethodState->mLocals.mSize : 0;
  5687. exprEvaluator.Evaluate(argExpr, false, false, true);
  5688. if ((deferParamValues) && (mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mLocals.mSize > lastLocalVarIdx))
  5689. {
  5690. // Remove any ignored locals
  5691. mModule->RestoreScoreState_LocalVariables(lastLocalVarIdx);
  5692. }
  5693. }
  5694. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  5695. {
  5696. auto localVar = exprEvaluator.mResultLocalVar;
  5697. int fieldIdx = mResultLocalVarField - 1;
  5698. auto methodState = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  5699. if (localVar->mCompositeCount >= 0)
  5700. {
  5701. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) != 0)
  5702. {
  5703. for (int compositeIdx = 0; compositeIdx < localVar->mCompositeCount; compositeIdx++)
  5704. {
  5705. BfResolvedArg compositeResolvedArg;
  5706. auto compositeLocalVar = methodState->mLocals[localVar->mLocalVarIdx + compositeIdx + 1];
  5707. auto argValue = exprEvaluator.LoadLocal(compositeLocalVar, true);
  5708. if (argValue)
  5709. {
  5710. if (!argValue.mType->IsStruct())
  5711. argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  5712. }
  5713. resolvedArg.mTypedValue = argValue;
  5714. resolvedArg.mExpression = argExpr;
  5715. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_FromParamComposite);
  5716. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  5717. exprEvaluator.mIsVolatileReference = false;
  5718. }
  5719. if ((localVar->mResolvedType->IsModifiedTypeType()) && (((BfModifiedTypeType*)localVar->mResolvedType)->mModifiedKind == BfToken_Params))
  5720. {
  5721. // Is a 'params'
  5722. }
  5723. else
  5724. continue;
  5725. }
  5726. else
  5727. exprEvaluator.mResult = mModule->LoadOrAggregateValue(exprEvaluator.mResult);
  5728. }
  5729. }
  5730. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  5731. auto argValue = exprEvaluator.mResult;
  5732. if (argValue)
  5733. {
  5734. mModule->mBfIRBuilder->PopulateType(argValue.mType);
  5735. resolvedArg.mResolvedType = argValue.mType;
  5736. if (resolvedArg.mResolvedType->IsRef())
  5737. argValue.mKind = BfTypedValueKind_Value;
  5738. if (exprEvaluator.mIsVolatileReference)
  5739. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_Volatile);
  5740. }
  5741. resolvedArg.mUncastedTypedValue = argValue;
  5742. resolvedArg.mTypedValue = argValue;
  5743. if (deferParamValues)
  5744. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  5745. }
  5746. resolvedArg.mExpression = argExpr;
  5747. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  5748. }
  5749. if (autoComplete != NULL)
  5750. autoComplete->mIgnoreFixits = hadIgnoredFixits;
  5751. }
  5752. void BfExprEvaluator::PerformCallChecks(BfMethodInstance* methodInstance, BfAstNode* targetSrc)
  5753. {
  5754. BfCustomAttributes* customAttributes = methodInstance->GetCustomAttributes();
  5755. if (customAttributes != NULL)
  5756. mModule->CheckErrorAttributes(methodInstance->GetOwner(), methodInstance, NULL, customAttributes, targetSrc);
  5757. }
  5758. void BfExprEvaluator::CheckSkipCall(BfAstNode* targetSrc, SizedArrayImpl<BfResolvedArg>& argValues)
  5759. {
  5760. for (auto& argValue : argValues)
  5761. {
  5762. if ((!argValue.IsDeferredValue()) && (argValue.mExpression != NULL))
  5763. {
  5764. mModule->Fail("Illegal SkipCall invocation", targetSrc);
  5765. return;
  5766. }
  5767. }
  5768. }
  5769. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, BfMethodInstance* methodInstance, BfIRValue func, bool bypassVirtual, SizedArrayImpl<BfIRValue>& irArgs, BfTypedValue* sret, BfCreateCallFlags callFlags, BfType* origTargetType)
  5770. {
  5771. // static int sCallIdx = 0;
  5772. // if (!mModule->mCompiler->mIsResolveOnly)
  5773. // sCallIdx++;
  5774. // int callIdx = sCallIdx;
  5775. // if (callIdx == 0x000000E8)
  5776. // {
  5777. // NOP;
  5778. // }
  5779. bool isDelegateThunk = ((callFlags & (BfCreateCallFlags_DelegateThunkNonStatic | BfCreateCallFlags_DelegateThunkStatic)) != 0);
  5780. auto methodDef = methodInstance->mMethodDef;
  5781. BfIRValue funcCallInst = func;
  5782. auto importCallKind = methodInstance->GetImportCallKind();
  5783. if ((funcCallInst) && (importCallKind != BfImportCallKind_None))
  5784. {
  5785. if ((funcCallInst.IsFake()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  5786. {
  5787. mModule->mFuncReferences.TryGetValue(methodInstance, &funcCallInst);
  5788. }
  5789. if ((importCallKind == BfImportCallKind_GlobalVar) &&
  5790. (methodInstance->mHotMethod == NULL) &&
  5791. (mModule->mCompiler->IsHotCompile()))
  5792. {
  5793. // This may actually be a BfImportCallKind_GlobalVar_Hot, so check it...
  5794. mModule->CheckHotMethod(methodInstance, "");
  5795. importCallKind = methodInstance->GetImportCallKind();
  5796. }
  5797. if (importCallKind == BfImportCallKind_GlobalVar_Hot)
  5798. {
  5799. //TODO: Check against NULL for calling BfLoadSharedLibraries
  5800. auto checkVal = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  5801. BfIRBlock nullBlock = mModule->mBfIRBuilder->CreateBlock("importNull");
  5802. BfIRBlock doneBlock = mModule->mBfIRBuilder->CreateBlock("importLoad");
  5803. auto condVal = mModule->mBfIRBuilder->CreateIsNull(checkVal);
  5804. mModule->mBfIRBuilder->CreateCondBr(condVal, nullBlock, doneBlock);
  5805. mModule->mBfIRBuilder->AddBlock(nullBlock);
  5806. mModule->mBfIRBuilder->SetInsertPoint(nullBlock);
  5807. auto loadSharedLibsFunc = mModule->GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  5808. mModule->mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  5809. mModule->mBfIRBuilder->CreateBr(doneBlock);
  5810. mModule->mBfIRBuilder->AddBlock(doneBlock);
  5811. mModule->mBfIRBuilder->SetInsertPoint(doneBlock);
  5812. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  5813. }
  5814. else
  5815. {
  5816. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  5817. }
  5818. }
  5819. if ((methodInstance->GetOwner()->IsInstanceOf(mModule->mCompiler->mDeferredCallTypeDef)) &&
  5820. (methodInstance->mMethodDef->mName == "Cancel"))
  5821. {
  5822. if (mModule->mCurMethodState != NULL)
  5823. mModule->mCurMethodState->mCancelledDeferredCall = true;
  5824. }
  5825. if ((methodDef->mIsNoReturn) && ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) == 0))
  5826. {
  5827. mModule->mCurMethodState->SetHadReturn(true);
  5828. mModule->mCurMethodState->mLeftBlockUncond = true;
  5829. mModule->MarkScopeLeft(&mModule->mCurMethodState->mHeadScope, true);
  5830. }
  5831. if (mModule->mCurTypeInstance != NULL)
  5832. {
  5833. bool isVirtual = (methodInstance->mVirtualTableIdx != -1) && (!bypassVirtual);
  5834. mModule->AddDependency(methodInstance->mMethodInstanceGroup->mOwner, mModule->mCurTypeInstance, isVirtual ? BfDependencyMap::DependencyFlag_VirtualCall : BfDependencyMap::DependencyFlag_Calls);
  5835. mModule->AddCallDependency(methodInstance, bypassVirtual);
  5836. }
  5837. if (methodInstance->GetOwner()->IsUnspecializedType())
  5838. {
  5839. BF_ASSERT((!methodInstance->mIRFunction) || (methodInstance == mModule->mCurMethodInstance) || (methodInstance->mMethodDef->mIsLocalMethod));
  5840. }
  5841. if (mFunctionBindResult != NULL)
  5842. {
  5843. BF_ASSERT(mFunctionBindResult->mMethodInstance == NULL);
  5844. mFunctionBindResult->mMethodInstance = methodInstance;
  5845. for (auto arg : irArgs)
  5846. mFunctionBindResult->mIRArgs.push_back(arg);
  5847. }
  5848. BfType* origReturnType = methodInstance->mReturnType;
  5849. /*if (origReturnType->IsSelf())
  5850. {
  5851. origReturnType = methodInstance->GetOwner();
  5852. BF_ASSERT(origReturnType->IsInterface());
  5853. }*/
  5854. BfType* returnType = origReturnType;
  5855. BfTypedValue sretVal;
  5856. auto _GetDefaultReturnValue = [&]()
  5857. {
  5858. if (methodInstance->mVirtualTableIdx == -1)
  5859. {
  5860. if (methodInstance->GetOwner()->IsInterface())
  5861. {
  5862. // We're attempting to directly invoke a non-virtual interface method, if we're return an interface then
  5863. // it is a concrete interface
  5864. if (returnType->IsInterface())
  5865. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  5866. }
  5867. }
  5868. if ((returnType->IsVar()) && (mExpectingType != NULL))
  5869. returnType = mExpectingType;
  5870. if (returnType->IsRef())
  5871. {
  5872. auto result = mModule->GetDefaultTypedValue(returnType->GetUnderlyingType(), true, BfDefaultValueKind_Addr);
  5873. if (methodDef->mIsReadOnly)
  5874. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  5875. return result;
  5876. }
  5877. else
  5878. {
  5879. auto val = mModule->GetDefaultTypedValue(returnType, true, (GetStructRetIdx(methodInstance) != -1) ? BfDefaultValueKind_Addr : BfDefaultValueKind_Value);
  5880. if (val.mKind == BfTypedValueKind_Addr)
  5881. val.mKind = BfTypedValueKind_RestrictedTempAddr;
  5882. return val;
  5883. }
  5884. };
  5885. mModule->PopulateType(origReturnType, BfPopulateType_Data);
  5886. if ((GetStructRetIdx(methodInstance) != -1) && (!isDelegateThunk))
  5887. {
  5888. // We need to ensure that mReceivingValue has the correct type, otherwise it's possible that a conversion operator needs to be applied
  5889. // This happens for returning Result<T>'s with a 'T' value
  5890. if ((sret == NULL) && (mReceivingValue != NULL) && (mReceivingValue->mType == returnType))
  5891. {
  5892. sretVal = *mReceivingValue;
  5893. sret = &sretVal;
  5894. auto ptrType = mModule->CreatePointerType(returnType);
  5895. if (returnType != sret->mType)
  5896. {
  5897. sret->mValue = mModule->mBfIRBuilder->CreateBitCast(sret->mValue, mModule->mBfIRBuilder->MapType(ptrType));
  5898. sret->mType = returnType;
  5899. }
  5900. mReceivingValue = NULL;
  5901. }
  5902. if (sret == NULL)
  5903. {
  5904. sretVal = BfTypedValue(mModule->CreateAlloca(returnType), returnType, BfTypedValueKind_RestrictedTempAddr);
  5905. sret = &sretVal;
  5906. }
  5907. }
  5908. else
  5909. {
  5910. BF_ASSERT(sret == NULL);
  5911. }
  5912. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  5913. {
  5914. if ((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0)
  5915. {
  5916. // We need to perform call such as Compiler.Mixin and String.ConstF
  5917. }
  5918. else
  5919. return _GetDefaultReturnValue();
  5920. }
  5921. BF_ASSERT(!methodInstance->mDisallowCalling);
  5922. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mAutoComplete != NULL))
  5923. {
  5924. bool wantQuickEval = true;
  5925. if (IsComptime())
  5926. {
  5927. auto autoComplete = mModule->mCompiler->mResolvePassData->mAutoComplete;
  5928. wantQuickEval =
  5929. ((autoComplete->mResolveType != BfResolveType_Autocomplete) &&
  5930. (autoComplete->mResolveType != BfResolveType_Autocomplete_HighPri) &&
  5931. (autoComplete->mResolveType != BfResolveType_GetResultString));
  5932. for (auto& entry : mModule->mCompiler->mResolvePassData->mEmitEmbedEntries)
  5933. {
  5934. if (entry.mValue.mCursorIdx >= 0)
  5935. {
  5936. // Needed for Go To Definition in Compiler.Mixin
  5937. wantQuickEval = false;
  5938. }
  5939. }
  5940. }
  5941. if (wantQuickEval)
  5942. {
  5943. // In an autocomplete pass we may have stale method references that need to be resolved
  5944. // in the full classify pass, and in the full classify pass while just refreshing internals, we
  5945. // may have NULL funcs temporarily. We simply skip generating the method call here.
  5946. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  5947. {
  5948. if (methodInstance->mReturnType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  5949. {
  5950. if ((mExpectingType != NULL) && (mExpectingType->IsSizedArray()))
  5951. {
  5952. return BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(mExpectingType)), mExpectingType);
  5953. }
  5954. }
  5955. auto returnType = methodInstance->mReturnType;
  5956. if ((returnType->IsVar()) && (mExpectingType != NULL))
  5957. returnType = mExpectingType;
  5958. if (methodInstance->mReturnType->IsValuelessType())
  5959. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  5960. return BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(returnType)), returnType);
  5961. }
  5962. BfTypedValue result;
  5963. if (sret != NULL)
  5964. result = *sret;
  5965. else
  5966. result = _GetDefaultReturnValue();
  5967. return result;
  5968. }
  5969. }
  5970. bool forceBind = false;
  5971. if (mModule->mCompiler->mCeMachine != NULL)
  5972. {
  5973. bool doConstReturn = false;
  5974. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  5975. {
  5976. if (mFunctionBindResult != NULL)
  5977. {
  5978. forceBind = true;
  5979. }
  5980. else if ((mBfEvalExprFlags & BfEvalExprFlags_InCascade) != 0)
  5981. {
  5982. mModule->Fail("Const evaluation not allowed with cascade operator", targetSrc);
  5983. }
  5984. else if (((methodInstance->mComptimeFlags & BfComptimeFlag_OnlyFromComptime) != 0) && (!mModule->mIsComptimeModule))
  5985. {
  5986. // This either generated an error already or this is just the non-const type check pass for a comptime-only method
  5987. doConstReturn = true;
  5988. }
  5989. else if ((mBfEvalExprFlags & BfEvalExprFlags_DisallowComptime) != 0)
  5990. {
  5991. doConstReturn = true;
  5992. }
  5993. else if (((callFlags & BfCreateCallFlags_GenericParamThis) != 0) && (methodInstance->GetOwner()->IsInterface()))
  5994. {
  5995. mModule->Warn(0, "Concrete method may fail to comptime during specialization", targetSrc);
  5996. doConstReturn = true;
  5997. }
  5998. else if (methodDef->mIsVirtual)
  5999. {
  6000. // This could only really be the case for a Type, since no other 'this' could qualify as const
  6001. }
  6002. else
  6003. {
  6004. CeEvalFlags evalFlags = CeEvalFlags_None;
  6005. if ((mBfEvalExprFlags & BfEvalExprFlags_NoCeRebuildFlags) != 0)
  6006. evalFlags = (CeEvalFlags)(evalFlags | CeEvalFlags_NoRebuild);
  6007. if ((mModule->mIsComptimeModule) && (mModule->mCompiler->mCeMachine->mDebugger != NULL) && (mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  6008. {
  6009. auto ceDbgState = mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState;
  6010. if ((ceDbgState->mDbgExpressionFlags & DwEvalExpressionFlag_AllowCalls) != 0)
  6011. {
  6012. ceDbgState->mHadSideEffects = true;
  6013. //SetAndRestoreValue<CeDebugger*> prevDebugger(mModule->mCompiler->mCeMachine->mDebugger, NULL);
  6014. evalFlags = (CeEvalFlags)(evalFlags | CeEvalFlags_DbgCall);
  6015. auto result = ceDbgState->mCeContext->Call(targetSrc, mModule, methodInstance, irArgs, evalFlags, mExpectingType);
  6016. if (result)
  6017. return result;
  6018. }
  6019. else
  6020. {
  6021. ceDbgState->mBlockedSideEffects = true;
  6022. }
  6023. }
  6024. else
  6025. {
  6026. CeCallSource ceCallSource(targetSrc);
  6027. ceCallSource.mOrigCalleeType = origTargetType;
  6028. auto constRet = mModule->mCompiler->mCeMachine->Call(ceCallSource, mModule, methodInstance, irArgs, evalFlags, mExpectingType);
  6029. if (constRet)
  6030. {
  6031. auto constant = mModule->mBfIRBuilder->GetConstant(constRet.mValue);
  6032. BF_ASSERT(!constRet.mType->IsVar());
  6033. return constRet;
  6034. }
  6035. if (mModule->mCompiler->mFastFinish)
  6036. {
  6037. if ((mModule->mCurMethodInstance == NULL) || (!mModule->mCurMethodInstance->mIsAutocompleteMethod))
  6038. {
  6039. // We didn't properly resolve this so queue for a rebuild later
  6040. mModule->DeferRebuildType(mModule->mCurTypeInstance);
  6041. }
  6042. }
  6043. doConstReturn = true;
  6044. }
  6045. }
  6046. }
  6047. else if (mModule->mIsComptimeModule)
  6048. {
  6049. //TODO: This meant that unspecialized types were not even allowed to have Init methods that called into themselves
  6050. // if (methodInstance->mIsUnspecialized)
  6051. // {
  6052. // doConstReturn = true;
  6053. // }
  6054. // else
  6055. {
  6056. mModule->mCompiler->mCeMachine->QueueMethod(methodInstance, func);
  6057. }
  6058. }
  6059. if (doConstReturn)
  6060. {
  6061. if ((returnType->IsVar()) && (mExpectingType != NULL))
  6062. returnType = mExpectingType;
  6063. if (returnType->IsRef())
  6064. {
  6065. return _GetDefaultReturnValue();
  6066. }
  6067. else
  6068. {
  6069. if (returnType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  6070. {
  6071. if ((mExpectingType != NULL) && (mExpectingType->IsUndefSizedArray()))
  6072. {
  6073. if (returnType->GetUnderlyingType() == mExpectingType->GetUnderlyingType())
  6074. return mModule->GetDefaultTypedValue(mExpectingType, true, BfDefaultValueKind_Undef);
  6075. }
  6076. }
  6077. if (methodInstance->mReturnType->IsValuelessType())
  6078. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  6079. return mModule->GetDefaultTypedValue(returnType, true, BfDefaultValueKind_Undef);
  6080. }
  6081. return _GetDefaultReturnValue();
  6082. }
  6083. }
  6084. if (!forceBind)
  6085. {
  6086. if (((!func) && (methodInstance->mIsUnspecialized)) || (mModule->mBfIRBuilder->mIgnoreWrites))
  6087. {
  6088. // We don't actually submit method calls for unspecialized methods
  6089. // - this includes all methods in unspecialized types
  6090. return _GetDefaultReturnValue();
  6091. }
  6092. }
  6093. if (methodInstance->mVirtualTableIdx != -1)
  6094. {
  6095. if ((!bypassVirtual) && (mDeferCallData == NULL))
  6096. {
  6097. if ((methodDef->mIsOverride) && (mModule->mCurMethodInstance->mIsReified))
  6098. {
  6099. // Ensure that declaring method gets referenced
  6100. auto typeInstance = methodInstance->GetOwner();
  6101. auto& vEntry = typeInstance->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  6102. BfMethodInstance* declaringMethodInstance = vEntry.mDeclaringMethod;
  6103. if ((declaringMethodInstance->mMethodInstanceGroup->mOnDemandKind < BfMethodOnDemandKind_InWorkList) || (!declaringMethodInstance->mIsReified))
  6104. mModule->GetMethodInstance(declaringMethodInstance);
  6105. }
  6106. auto funcType = mModule->mBfIRBuilder->MapMethod(methodInstance);
  6107. auto funcPtrType1 = mModule->mBfIRBuilder->GetPointerTo(funcType);
  6108. auto funcPtrType2 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType1);
  6109. auto funcPtrType3 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType2);
  6110. auto funcPtrType4 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType3);
  6111. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  6112. {
  6113. if (mModule->mIsComptimeModule)
  6114. {
  6115. funcCallInst = mModule->mBfIRBuilder->Comptime_GetInterfaceFunc(irArgs[0], methodInstance->mMethodInstanceGroup->mOwner->mTypeId, methodInstance->mMethodDef->mIdx, funcPtrType1);
  6116. }
  6117. else
  6118. {
  6119. // IFace dispatch
  6120. auto ifaceTypeInst = methodInstance->mMethodInstanceGroup->mOwner;
  6121. BfIRValue slotOfs = mModule->GetInterfaceSlotNum(methodInstance->mMethodInstanceGroup->mOwner);
  6122. auto vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  6123. auto vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  6124. auto ifacePtrPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  6125. auto ifacePtr = mModule->mBfIRBuilder->CreateLoad(ifacePtrPtr);
  6126. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(ifacePtr, methodInstance->mVirtualTableIdx/*, "vfn"*/);
  6127. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  6128. }
  6129. }
  6130. else if (mModule->mIsComptimeModule)
  6131. {
  6132. funcCallInst = mModule->mBfIRBuilder->Comptime_GetVirtualFunc(irArgs[0], methodInstance->mVirtualTableIdx, funcPtrType1);
  6133. }
  6134. else
  6135. {
  6136. mModule->HadSlotCountDependency();
  6137. // Virtual dispatch
  6138. // int vDataIdx = 0;
  6139. // vDataIdx += 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots;
  6140. BfIRValue vDataPtr;
  6141. BfIRValue vDataIdx;
  6142. if ((mModule->mCompiler->mOptions.mHasVDataExtender) && (mModule->mCompiler->IsHotCompile()))
  6143. {
  6144. auto typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  6145. int extMethodIdx = (methodInstance->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  6146. if (extMethodIdx >= 0)
  6147. {
  6148. BF_ASSERT(mModule->mCompiler->IsHotCompile());
  6149. // We have grown outside our original virtual table, Load the new vdataPtr from the mHasVDataExtender
  6150. // vDataPtr = obj.vtable.extension.entry[curVersion]
  6151. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  6152. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr));
  6153. // The offset of the vExt is one past the base vtable. When a base class extends its virtual table, an entry
  6154. // for that new method is inserted in mVirtualMethodTable (thus increasing the index relative to GetBaseVTableSize()),
  6155. // but the actual written vtable position doesn't change, hence offsetting from GetOrigBaseVTableSize()
  6156. #ifdef _DEBUG
  6157. int vExtIdx = typeInst->GetImplBaseVTableSize();
  6158. BF_ASSERT(typeInst->mVirtualMethodTable[vExtIdx].mDeclaringMethod.mMethodNum == -1); // A type entry with a -1 mMethodNum means it's a vtable ext slot
  6159. #endif
  6160. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  6161. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, mModule->mCompiler->GetVDataPrefixDataCount() + mModule->mCompiler->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  6162. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, vExtOfs));
  6163. BfIRValue extendPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx);
  6164. vDataPtr = mModule->mBfIRBuilder->CreateLoad(extendPtr);
  6165. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, extMethodIdx);
  6166. }
  6167. else
  6168. {
  6169. // Map this new virtual index back to the original index
  6170. // Find the type instance that declared the original method
  6171. auto declTypeInst = typeInst;
  6172. while (declTypeInst->mBaseType != NULL)
  6173. {
  6174. mModule->PopulateType(declTypeInst->mBaseType, BfPopulateType_DataAndMethods);
  6175. if (methodInstance->mVirtualTableIdx >= declTypeInst->mBaseType->mVirtualMethodTableSize)
  6176. break;
  6177. BF_ASSERT(methodInstance->mMethodDef->mIsOverride);
  6178. declTypeInst = declTypeInst->mBaseType;
  6179. }
  6180. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  6181. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32,
  6182. (methodInstance->mVirtualTableIdx - declTypeInst->GetImplBaseVTableSize()) + declTypeInst->GetOrigImplBaseVTableSize()));
  6183. }
  6184. }
  6185. else
  6186. {
  6187. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  6188. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, methodInstance->mVirtualTableIdx));
  6189. }
  6190. if (!vDataPtr)
  6191. {
  6192. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType3);
  6193. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  6194. }
  6195. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx/*, "vfn"*/);
  6196. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  6197. }
  6198. }
  6199. }
  6200. else // non-virtual
  6201. {
  6202. if (methodInstance->GetOwner()->IsInterface())
  6203. {
  6204. // We're attempting to directly invoke a non-virtual interface method, this will happen during the unspecialized pass
  6205. // OR if we had an error and didn't find an implementing member in the actual target
  6206. if (((mModule->mCurMethodInstance == NULL) || (!mModule->mCurMethodInstance->mIsUnspecialized)) &&
  6207. (!mModule->mCurTypeInstance->IsInterface()))
  6208. mModule->AssertErrorState();
  6209. if (returnType->IsInterface())
  6210. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  6211. return _GetDefaultReturnValue();
  6212. }
  6213. }
  6214. if (mFunctionBindResult != NULL)
  6215. {
  6216. mFunctionBindResult->mFunc = funcCallInst;
  6217. if (irArgs.size() != 0)
  6218. {
  6219. auto targetType = methodInstance->mMethodInstanceGroup->mOwner;
  6220. if ((targetType->IsValueType()) && (targetType->IsSplattable()) && (!methodDef->HasNoThisSplat()) && (!IsComptime()))
  6221. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, BfTypedValueKind_SplatHead);
  6222. else
  6223. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, targetType->IsComposite() ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  6224. }
  6225. else
  6226. {
  6227. mFunctionBindResult->mTarget = BfTypedValue();
  6228. }
  6229. return BfTypedValue();
  6230. }
  6231. if (methodInstance->mReturnType == NULL)
  6232. {
  6233. mModule->AssertErrorState();
  6234. return BfTypedValue();
  6235. }
  6236. if (((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized)) && (mModule->mBfIRBuilder->mIgnoreWrites))
  6237. {
  6238. // Don't actually do the call - our target may be a generic param
  6239. return _GetDefaultReturnValue();
  6240. }
  6241. if (mDeferCallData != NULL)
  6242. {
  6243. if (mDeferCallData->mFuncAlloca_Orig == func)
  6244. mModule->AddDeferredCall(BfModuleMethodInstance(methodInstance, mDeferCallData->mFuncAlloca), irArgs, mDeferCallData->mScopeAlloc, mDeferCallData->mRefNode, bypassVirtual, false, true);
  6245. else
  6246. mModule->AddDeferredCall(BfModuleMethodInstance(methodInstance, func), irArgs, mDeferCallData->mScopeAlloc, mDeferCallData->mRefNode, bypassVirtual);
  6247. return mModule->GetFakeTypedValue(returnType);
  6248. }
  6249. if (!funcCallInst)
  6250. {
  6251. if ((mModule->HasCompiledOutput()) || (mModule->mCompiler->mOptions.mExtraResolveChecks))
  6252. {
  6253. // This can happen either from an error, or from the resolver while doing Internals_Changed processing
  6254. mModule->AssertErrorState();
  6255. }
  6256. return _GetDefaultReturnValue();
  6257. }
  6258. bool hasResult = !methodInstance->mReturnType->IsValuelessType();
  6259. BfIRValue firstArg;
  6260. if (irArgs.size() != 0)
  6261. firstArg = irArgs[0];
  6262. auto methodInstOwner = methodInstance->GetOwner();
  6263. auto expectCallingConvention = mModule->GetIRCallingConvention(methodInstance);
  6264. if ((methodInstOwner->IsFunction()) && (methodInstance->GetParamCount() > 0) && (methodInstance->GetParamName(0) == "this"))
  6265. {
  6266. auto paramType = methodInstance->GetParamType(0);
  6267. if (!paramType->IsValueType())
  6268. expectCallingConvention = BfIRCallingConv_ThisCall;
  6269. }
  6270. if (((callFlags & BfCreateCallFlags_DelegateThunkStatic) != 0) && (expectCallingConvention == BfIRCallingConv_ThisCall))
  6271. expectCallingConvention = BfIRCallingConv_CDecl;
  6272. if ((methodInstance->mAlwaysInline) && (mModule->mCompiler->mOptions.mEmitLineInfo))
  6273. {
  6274. // Emit a NOP so we always have a "step over" point
  6275. mModule->EmitEnsureInstructionAt();
  6276. }
  6277. if (returnType->IsComposite())
  6278. mModule->mBfIRBuilder->PopulateType(returnType);
  6279. methodInstance->mMethodInstanceGroup->mHasEmittedReference = true;
  6280. BfIRValue callInst;
  6281. int callIRArgCount = (int)irArgs.size();
  6282. if (sret != NULL)
  6283. {
  6284. SizedArray<BfIRValue, 8> sretIRArgs;
  6285. int sretIdx = GetStructRetIdx(methodInstance);
  6286. int inIdx = 0;
  6287. for (int outIdx = 0; outIdx < irArgs.size() + 1; outIdx++)
  6288. {
  6289. if (outIdx == sretIdx)
  6290. {
  6291. sretIRArgs.Add(sret->mValue);
  6292. continue;
  6293. }
  6294. sretIRArgs.Add(irArgs[inIdx++]);
  6295. }
  6296. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, sretIRArgs);
  6297. callIRArgCount++;
  6298. }
  6299. else
  6300. {
  6301. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, irArgs);
  6302. if ((hasResult) && (!methodDef->mName.IsEmpty()) && (!methodInstance->mIsIntrinsic))
  6303. mModule->mBfIRBuilder->SetName(callInst, methodDef->mName);
  6304. }
  6305. if ((expectCallingConvention != BfIRCallingConv_CDecl) && (!methodInstance->mIsIntrinsic))
  6306. mModule->mBfIRBuilder->SetCallCallingConv(callInst, expectCallingConvention);
  6307. if ((methodDef->mIsNoReturn) && (!methodInstance->mIsIntrinsic))
  6308. mModule->mBfIRBuilder->Call_AddAttribute(callInst, -1, BfIRAttribute_NoReturn);
  6309. bool hadAttrs = false;
  6310. int paramIdx = 0;
  6311. bool doingThis = methodInstance->HasThis();
  6312. int argIdx = 0;
  6313. if ((callFlags & BfCreateCallFlags_DelegateThunkStatic) != 0)
  6314. doingThis = false;
  6315. bool forceThisPtr = ((callFlags & BfCreateCallFlags_DelegateThunkNonStatic) != 0);
  6316. if (methodDef->mHasExplicitThis)
  6317. paramIdx++;
  6318. int paramCount = methodInstance->GetParamCount();
  6319. for ( ; argIdx < callIRArgCount ; )
  6320. {
  6321. if (methodInstance->mIsIntrinsic)
  6322. break;
  6323. if ((sret != NULL) && (argIdx == GetStructRetIdx(methodInstance)))
  6324. {
  6325. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_StructRet);
  6326. argIdx++;
  6327. continue;
  6328. }
  6329. auto _HandleParamType = [&] (BfType* paramType)
  6330. {
  6331. if (paramType->IsStruct())
  6332. {
  6333. if ((!doingThis) || (!methodDef->mIsMutating && methodInstance->AllowsSplatting(paramIdx)))
  6334. {
  6335. BfTypeCode loweredTypeCode = BfTypeCode_None;
  6336. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  6337. if (paramType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  6338. {
  6339. argIdx++;
  6340. if (loweredTypeCode2 != BfTypeCode_None)
  6341. argIdx++;
  6342. return; // Lowering never requires attributes
  6343. }
  6344. }
  6345. }
  6346. int addDeref = -1;
  6347. if (paramType->IsRef())
  6348. {
  6349. auto refType = (BfRefType*)paramType;
  6350. auto elementType = refType->mElementType;
  6351. mModule->PopulateType(elementType, BfPopulateType_Data);
  6352. addDeref = elementType->mSize;
  6353. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  6354. mModule->AssertErrorState();
  6355. }
  6356. if ((paramType->IsComposite()) && (!paramType->IsTypedPrimitive()))
  6357. {
  6358. if (mModule->mCompiler->mOptions.mAllowStructByVal)
  6359. {
  6360. //byval
  6361. }
  6362. else
  6363. {
  6364. mModule->PopulateType(paramType, BfPopulateType_Data);
  6365. auto typeInst = paramType->ToTypeInstance();
  6366. if ((typeInst != NULL) && (typeInst->mIsCRepr) && (typeInst->IsSplattable()) && (!IsComptime()))
  6367. {
  6368. // We're splatting
  6369. }
  6370. else
  6371. {
  6372. if (doingThis)
  6373. {
  6374. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_NoCapture);
  6375. addDeref = paramType->mSize;
  6376. }
  6377. else if (methodInstance->WantsStructsAttribByVal(paramType))
  6378. {
  6379. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ByVal, mModule->mSystem->mPtrSize);
  6380. }
  6381. }
  6382. }
  6383. }
  6384. else if (paramType->IsPrimitiveType())
  6385. {
  6386. auto primType = (BfPrimitiveType*)paramType;
  6387. if ((primType->mTypeDef->mTypeCode == BfTypeCode_Boolean) && (!methodInstance->mIsIntrinsic))
  6388. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ZExt);
  6389. }
  6390. if (addDeref >= 0)
  6391. {
  6392. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  6393. }
  6394. argIdx++;
  6395. };
  6396. BfType* paramType = NULL;
  6397. if (doingThis)
  6398. {
  6399. int thisIdx = methodInstance->GetThisIdx();
  6400. paramType = methodInstance->GetThisType();
  6401. if (paramType->IsValuelessType())
  6402. {
  6403. doingThis = false;
  6404. continue;
  6405. }
  6406. bool isSplatted = methodInstance->GetParamIsSplat(thisIdx) && (!IsComptime()); // (resolvedTypeRef->IsSplattable()) && (!methodDef->mIsMutating);
  6407. if (isSplatted)
  6408. {
  6409. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  6410. doingThis = false;
  6411. continue;
  6412. }
  6413. else
  6414. _HandleParamType(paramType);
  6415. }
  6416. else
  6417. {
  6418. if (paramIdx >= methodInstance->GetParamCount())
  6419. break;
  6420. paramType = methodInstance->GetParamType(paramIdx);
  6421. BfTypeCode loweredTypeCode = BfTypeCode_None;
  6422. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  6423. if (paramType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  6424. {
  6425. argIdx++;
  6426. paramIdx++;
  6427. if (loweredTypeCode2 != BfTypeCode_None)
  6428. argIdx++;
  6429. continue;
  6430. }
  6431. if ((paramType->IsValuelessType()) && (!paramType->IsMethodRef()))
  6432. {
  6433. paramIdx++;
  6434. continue;
  6435. }
  6436. if ((methodInstance->GetParamIsSplat(paramIdx)) && (!IsComptime()))
  6437. {
  6438. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  6439. paramIdx++;
  6440. continue;
  6441. }
  6442. else
  6443. _HandleParamType(methodInstance->GetParamType(paramIdx));
  6444. }
  6445. if (doingThis)
  6446. doingThis = false;
  6447. else
  6448. paramIdx++;
  6449. //argIdx++;
  6450. }
  6451. if ((callFlags & BfCreateCallFlags_TailCall) != 0)
  6452. mModule->mBfIRBuilder->SetTailCall(callInst);
  6453. if (methodDef->mIsNoReturn)
  6454. {
  6455. mModule->mBfIRBuilder->CreateUnreachable();
  6456. // For debuggability when looking back at stack trace
  6457. //mModule->ExtendLocalLifetimes(0);
  6458. if (mModule->IsTargetingBeefBackend())
  6459. {
  6460. auto checkScope = mModule->mCurMethodState->mCurScope;
  6461. while (checkScope != NULL)
  6462. {
  6463. mModule->EmitLifetimeEnds(checkScope);
  6464. checkScope = checkScope->mPrevScope;
  6465. }
  6466. // This 'fake' branch extends lifetimes of outer variable scopes
  6467. if (mModule->mCurMethodState->mIRExitBlock)
  6468. mModule->mBfIRBuilder->CreateBr_Fake(mModule->mCurMethodState->mIRExitBlock);
  6469. }
  6470. }
  6471. else
  6472. {
  6473. if (mModule->mCurMethodState != NULL)
  6474. mModule->mCurMethodState->mMayNeedThisAccessCheck = true;
  6475. }
  6476. if (isDelegateThunk)
  6477. return BfTypedValue(callInst, methodInstance->mReturnType);
  6478. BfTypedValue result;
  6479. if (sret != NULL)
  6480. result = *sret;
  6481. else if (hasResult)
  6482. {
  6483. BfTypeCode loweredRetType = BfTypeCode_None;
  6484. BfTypeCode loweredRetType2 = BfTypeCode_None;
  6485. if ((!IsComptime()) && (methodInstance->GetLoweredReturnType(&loweredRetType, &loweredRetType2)) && (loweredRetType != BfTypeCode_None))
  6486. {
  6487. auto retVal = mModule->CreateAlloca(methodInstance->mReturnType);
  6488. BfIRType loweredIRType = mModule->GetIRLoweredType(loweredRetType, loweredRetType2);
  6489. loweredIRType = mModule->mBfIRBuilder->GetPointerTo(loweredIRType);
  6490. auto castedRetVal = mModule->mBfIRBuilder->CreateBitCast(retVal, loweredIRType);
  6491. mModule->mBfIRBuilder->CreateStore(callInst, castedRetVal);
  6492. result = BfTypedValue(retVal, methodInstance->mReturnType, BfTypedValueKind_RestrictedTempAddr);
  6493. }
  6494. else
  6495. result = BfTypedValue(callInst, methodInstance->mReturnType);
  6496. }
  6497. else
  6498. result = mModule->GetFakeTypedValue(methodInstance->mReturnType);
  6499. if (result.mType->IsRef())
  6500. {
  6501. result = mModule->RemoveRef(result);
  6502. if (methodDef->mIsReadOnly)
  6503. {
  6504. if (result.mKind == BfTypedValueKind_Addr)
  6505. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  6506. }
  6507. }
  6508. return result;
  6509. }
  6510. BfTypedValue BfExprEvaluator::CreateCall(BfMethodMatcher* methodMatcher, BfTypedValue target)
  6511. {
  6512. auto moduleMethodInstance = GetSelectedMethod(*methodMatcher);
  6513. if (moduleMethodInstance.mMethodInstance == NULL)
  6514. return BfTypedValue();
  6515. if ((target) && (target.mType != moduleMethodInstance.mMethodInstance->GetOwner()))
  6516. {
  6517. auto castedTarget = mModule->Cast(methodMatcher->mTargetSrc, target, moduleMethodInstance.mMethodInstance->GetOwner());
  6518. BF_ASSERT(castedTarget);
  6519. target = castedTarget;
  6520. }
  6521. PerformCallChecks(moduleMethodInstance.mMethodInstance, methodMatcher->mTargetSrc);
  6522. BfCreateCallFlags callFlags = BfCreateCallFlags_None;
  6523. if (methodMatcher->mAllowImplicitRef)
  6524. callFlags = (BfCreateCallFlags)(callFlags | BfCreateCallFlags_AllowImplicitRef);
  6525. return CreateCall(methodMatcher->mTargetSrc, target, BfTypedValue(), methodMatcher->mBestMethodDef, moduleMethodInstance, callFlags, methodMatcher->mArguments);
  6526. }
  6527. void BfExprEvaluator::MakeBaseConcrete(BfTypedValue& typedValue)
  6528. {
  6529. if (typedValue.IsBase())
  6530. {
  6531. auto baseType = mModule->mCurTypeInstance->mBaseType;
  6532. if (baseType == NULL)
  6533. baseType = mModule->mContext->mBfObjectType;
  6534. mModule->PopulateType(baseType, BfPopulateType_Data);
  6535. typedValue = mModule->Cast(NULL, typedValue, baseType, BfCastFlags_Explicit);
  6536. }
  6537. }
  6538. void BfExprEvaluator::SplatArgs(BfTypedValue value, SizedArrayImpl<BfIRValue>& irArgs)
  6539. {
  6540. if (value.IsSplat())
  6541. {
  6542. int componentIdx = 0;
  6543. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->ExtractSplatValue(value, componentIdx++, checkType)); }, value.mType);
  6544. return;
  6545. }
  6546. mModule->mBfIRBuilder->PopulateType(value.mType);
  6547. std::function<void(BfTypedValue)> checkTypeLambda = [&](BfTypedValue curValue)
  6548. {
  6549. BfType* checkType = curValue.mType;
  6550. if (checkType->IsStruct())
  6551. {
  6552. auto checkTypeInstance = checkType->ToTypeInstance();
  6553. if (checkTypeInstance->mBaseType != NULL)
  6554. mModule->PopulateType(checkTypeInstance->mBaseType);
  6555. if ((checkTypeInstance->mBaseType != NULL) && (!checkTypeInstance->mBaseType->IsValuelessType()))
  6556. {
  6557. BfTypedValue baseValue;
  6558. if (curValue.IsAddr())
  6559. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, 0), checkTypeInstance->mBaseType, true);
  6560. else
  6561. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateExtractValue(curValue.mValue, 0), checkTypeInstance->mBaseType);
  6562. checkTypeLambda(baseValue);
  6563. }
  6564. if (checkTypeInstance->mIsUnion)
  6565. {
  6566. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  6567. if (!unionInnerType->IsValuelessType())
  6568. {
  6569. BfTypedValue unionValue = mModule->ExtractValue(curValue, NULL, 1);
  6570. checkTypeLambda(unionValue);
  6571. }
  6572. if (checkTypeInstance->IsEnum())
  6573. {
  6574. BfTypedValue dscrValue = mModule->ExtractValue(curValue, NULL, 2);
  6575. checkTypeLambda(dscrValue);
  6576. }
  6577. }
  6578. else
  6579. {
  6580. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  6581. {
  6582. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  6583. if (fieldInstance->mDataIdx >= 0)
  6584. {
  6585. BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  6586. checkTypeLambda(fieldValue);
  6587. }
  6588. }
  6589. }
  6590. }
  6591. else if (checkType->IsMethodRef())
  6592. {
  6593. BF_ASSERT(curValue.IsAddr());
  6594. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  6595. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6596. {
  6597. auto checkType = methodRefType->GetCaptureType(dataIdx);
  6598. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6599. {
  6600. BF_ASSERT(dataIdx == 0);
  6601. auto ptrType = mModule->CreatePointerType(checkType);
  6602. auto elemPtr = mModule->mBfIRBuilder->CreateBitCast(curValue.mValue, mModule->mBfIRBuilder->MapType(ptrType));
  6603. checkTypeLambda(BfTypedValue(elemPtr, checkType, BfTypedValueKind_Addr));
  6604. //BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  6605. //checkTypeLambda(fieldValue);
  6606. }
  6607. else
  6608. {
  6609. auto elemVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, dataIdx);
  6610. if (!checkType->IsComposite())
  6611. elemVal = mModule->mBfIRBuilder->CreateLoad(elemVal);
  6612. irArgs.Add(elemVal);
  6613. //irArgs.Add(mModule->ExtractValue(curValue, dataIdx));
  6614. }
  6615. }
  6616. }
  6617. else if (!checkType->IsValuelessType())
  6618. {
  6619. auto loadedVal = mModule->LoadValue(curValue);
  6620. loadedVal = mModule->PrepareConst(loadedVal);
  6621. irArgs.push_back(loadedVal.mValue);
  6622. }
  6623. };
  6624. checkTypeLambda(value);
  6625. }
  6626. void BfExprEvaluator::PushArg(BfTypedValue argVal, SizedArrayImpl<BfIRValue>& irArgs, bool disableSplat, bool disableLowering, bool isIntrinsic, bool createCompositeCopy)
  6627. {
  6628. MakeBaseConcrete(argVal);
  6629. if (IsVar(argVal.mType))
  6630. {
  6631. argVal = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  6632. }
  6633. if (argVal.mType->IsIncomplete())
  6634. mModule->PopulateType(argVal.mType);
  6635. if (argVal.mType->IsValuelessNonOpaqueType())
  6636. return;
  6637. bool wantSplat = false;
  6638. if ((argVal.mType->IsSplattable()) && (!disableSplat) && (!IsComptime()))
  6639. {
  6640. disableLowering = true;
  6641. auto argTypeInstance = argVal.mType->ToTypeInstance();
  6642. if (!disableSplat)
  6643. {
  6644. if ((argTypeInstance != NULL) && (argTypeInstance->mIsCRepr))
  6645. wantSplat = true;
  6646. else if ((int)irArgs.size() + argVal.mType->GetSplatCount() <= mModule->mCompiler->mOptions.mMaxSplatRegs)
  6647. wantSplat = true;
  6648. }
  6649. }
  6650. if (wantSplat)
  6651. {
  6652. SplatArgs(argVal, irArgs);
  6653. }
  6654. else
  6655. {
  6656. if (argVal.mType->IsComposite())
  6657. {
  6658. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  6659. {
  6660. // Const eval entry - we want any incoming consts as they are
  6661. }
  6662. else if (isIntrinsic)
  6663. {
  6664. // We can handle composites either by value or not
  6665. }
  6666. else
  6667. argVal = mModule->MakeAddressable(argVal);
  6668. if ((!IsComptime()) && (!disableLowering) && (!isIntrinsic))
  6669. {
  6670. BfTypeCode loweredTypeCode = BfTypeCode_None;
  6671. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  6672. if (argVal.mType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  6673. {
  6674. BfIRValue argPtrVal = argVal.mValue;
  6675. int loweredSize = mModule->mBfIRBuilder->GetSize(loweredTypeCode) + mModule->mBfIRBuilder->GetSize(loweredTypeCode2);
  6676. if (argVal.mType->mSize < loweredSize)
  6677. {
  6678. auto allocaVal = mModule->CreateAlloca(mModule->GetPrimitiveType(BfTypeCode_UInt8), true, NULL, mModule->GetConstValue(loweredSize));
  6679. mModule->mBfIRBuilder->SetAllocaAlignment(allocaVal,
  6680. BF_MAX(argVal.mType->mAlign,
  6681. BF_MAX(mModule->mBfIRBuilder->GetSize(loweredTypeCode), mModule->mBfIRBuilder->GetSize(loweredTypeCode2))));
  6682. auto castedPtr = mModule->mBfIRBuilder->CreateBitCast(allocaVal, mModule->mBfIRBuilder->MapType(mModule->CreatePointerType(argVal.mType)));
  6683. auto argIRVal = mModule->mBfIRBuilder->CreateAlignedLoad(argVal.mValue, argVal.mType->mAlign);
  6684. mModule->mBfIRBuilder->CreateAlignedStore(argIRVal, castedPtr, argVal.mType->mAlign);
  6685. argPtrVal = castedPtr;
  6686. }
  6687. auto primType = mModule->mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  6688. auto ptrType = mModule->mBfIRBuilder->GetPointerTo(primType);
  6689. BfIRValue primPtrVal = mModule->mBfIRBuilder->CreateBitCast(argPtrVal, ptrType);
  6690. auto primVal = mModule->mBfIRBuilder->CreateLoad(primPtrVal);
  6691. irArgs.push_back(primVal);
  6692. if (loweredTypeCode2 != BfTypeCode_None)
  6693. {
  6694. auto primType2 = mModule->mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  6695. auto ptrType2 = mModule->mBfIRBuilder->GetPointerTo(primType2);
  6696. BfIRValue primPtrVal2;
  6697. if (mModule->mBfIRBuilder->GetSize(loweredTypeCode) < mModule->mBfIRBuilder->GetSize(loweredTypeCode2))
  6698. primPtrVal2 = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->CreateBitCast(primPtrVal, ptrType2), 1);
  6699. else
  6700. primPtrVal2 = mModule->mBfIRBuilder->CreateBitCast(mModule->mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), ptrType2);
  6701. auto primVal2 = mModule->mBfIRBuilder->CreateLoad(primPtrVal2);
  6702. irArgs.Add(primVal2);
  6703. }
  6704. return;
  6705. }
  6706. }
  6707. if ((createCompositeCopy) && (!argVal.IsTempAddr()))
  6708. {
  6709. // Non-Beef calling conventions require copies of composites
  6710. auto copyAddr = mModule->CreateAlloca(argVal.mType);
  6711. mModule->mBfIRBuilder->CreateStore(mModule->LoadValue(argVal).mValue, copyAddr);
  6712. argVal = BfTypedValue(copyAddr, argVal.mType, BfTypedValueKind_TempAddr);
  6713. }
  6714. }
  6715. else
  6716. argVal = mModule->LoadValue(argVal);
  6717. irArgs.Add(argVal.mValue);
  6718. }
  6719. }
  6720. void BfExprEvaluator::PushThis(BfAstNode* targetSrc, BfTypedValue argVal, BfMethodInstance* methodInstance, SizedArrayImpl<BfIRValue>& irArgs, bool skipMutCheck)
  6721. {
  6722. MakeBaseConcrete(argVal);
  6723. auto methodDef = methodInstance->mMethodDef;
  6724. if (methodInstance->IsSkipCall())
  6725. return;
  6726. if (!argVal)
  6727. {
  6728. //BF_ASSERT(mFunctionBindResult != NULL);
  6729. return;
  6730. }
  6731. if (methodDef->mIsMutating)
  6732. {
  6733. bool checkMut = false;
  6734. if (argVal.mType->IsGenericParam())
  6735. {
  6736. // For capturing mutability
  6737. if (mResultLocalVar != NULL)
  6738. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  6739. }
  6740. if (((argVal.mType->IsComposite()) || (argVal.mType->IsTypedPrimitive())))
  6741. {
  6742. if (argVal.IsCopyOnMutate())
  6743. argVal = mModule->CopyValue(argVal);
  6744. if ((argVal.IsReadOnly()) || (!argVal.IsAddr()))
  6745. {
  6746. if (!skipMutCheck)
  6747. {
  6748. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(methodInstance).c_str());
  6749. CheckModifyResult(argVal, targetSrc, err.c_str());
  6750. }
  6751. if (argVal.IsSplat())
  6752. {
  6753. argVal = mModule->AggregateSplat(argVal);
  6754. argVal = mModule->MakeAddressable(argVal);
  6755. }
  6756. }
  6757. else
  6758. {
  6759. if (mResultLocalVar != NULL)
  6760. {
  6761. // When we are capturing, we need to note that we require capturing by reference here
  6762. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  6763. }
  6764. }
  6765. }
  6766. }
  6767. if (argVal.mType->IsValuelessNonOpaqueType())
  6768. return;
  6769. auto owner = methodInstance->GetOwner();
  6770. bool allowThisSplatting;
  6771. if (mModule->mIsComptimeModule)
  6772. allowThisSplatting = owner->IsTypedPrimitive() || owner->IsValuelessNonOpaqueType();
  6773. else
  6774. allowThisSplatting = methodInstance->AllowsSplatting(-1);
  6775. if ((!allowThisSplatting) || (methodDef->mIsMutating) || (methodInstance->ForcingThisPtr()))
  6776. {
  6777. argVal = mModule->MakeAddressable(argVal);
  6778. irArgs.push_back(argVal.mValue);
  6779. return;
  6780. }
  6781. auto thisType = methodInstance->GetThisType();
  6782. PushArg(argVal, irArgs, !methodInstance->AllowsSplatting(-1), thisType->IsPointer());
  6783. }
  6784. void BfExprEvaluator::FinishDeferredEvals(SizedArrayImpl<BfResolvedArg>& argValues)
  6785. {
  6786. for (int argIdx = 0; argIdx < argValues.size(); argIdx++)
  6787. {
  6788. auto& argValue = argValues[argIdx].mTypedValue;
  6789. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  6790. {
  6791. if (!argValue)
  6792. {
  6793. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  6794. if (expr != NULL)
  6795. argValue = mModule->CreateValueFromExpression(expr, argValues[argIdx].mExpectedType, BfEvalExprFlags_NoCast);
  6796. }
  6797. }
  6798. }
  6799. }
  6800. void BfExprEvaluator::FinishDeferredEvals(BfResolvedArgs& argValues)
  6801. {
  6802. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  6803. {
  6804. auto& argValue = argValues.mResolvedArgs[argIdx].mTypedValue;
  6805. if ((argValues.mResolvedArgs[argIdx].mArgFlags & (BfArgFlag_VariableDeclaration)) != 0)
  6806. {
  6807. auto variableDeclaration = BfNodeDynCast<BfVariableDeclaration>((*argValues.mArguments)[argIdx]);
  6808. if ((variableDeclaration != NULL) && (variableDeclaration->mNameNode != NULL))
  6809. {
  6810. if (mModule->mCurMethodState == NULL)
  6811. {
  6812. mModule->Fail("Illegal local variable", variableDeclaration);
  6813. }
  6814. else
  6815. {
  6816. BfLocalVariable* localVar = new BfLocalVariable();
  6817. localVar->mName = variableDeclaration->mNameNode->ToString();
  6818. localVar->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_Var);
  6819. localVar->mAddr = mModule->mBfIRBuilder->GetFakeVal();
  6820. localVar->mReadFromId = 0;
  6821. localVar->mWrittenToId = 0;
  6822. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  6823. mModule->CheckVariableDef(localVar);
  6824. localVar->Init();
  6825. mModule->AddLocalVariableDef(localVar, true);
  6826. auto curScope = mModule->mCurMethodState->mCurScope;
  6827. if (curScope->mScopeKind == BfScopeKind_StatementTarget)
  6828. mModule->MoveLocalToParentScope(localVar);
  6829. }
  6830. }
  6831. }
  6832. }
  6833. FinishDeferredEvals(argValues.mResolvedArgs);
  6834. }
  6835. void BfExprEvaluator::AddCallDependencies(BfMethodInstance* methodInstance)
  6836. {
  6837. if (methodInstance->mReturnType != NULL)
  6838. mModule->AddDependency(methodInstance->mReturnType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  6839. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  6840. {
  6841. auto paramType = methodInstance->GetParamType(paramIdx);
  6842. mModule->AddDependency(paramType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  6843. }
  6844. if (methodInstance->mMethodInfoEx != NULL)
  6845. {
  6846. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  6847. {
  6848. if (genericArg->IsWrappableType())
  6849. genericArg = mModule->GetWrappedStructType(genericArg);
  6850. if (genericArg != NULL)
  6851. mModule->AddDependency(genericArg, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  6852. }
  6853. }
  6854. }
  6855. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, const BfTypedValue& inTarget, const BfTypedValue& origTarget, BfMethodDef* methodDef, BfModuleMethodInstance moduleMethodInstance, BfCreateCallFlags callFlags, SizedArrayImpl<BfResolvedArg>& argValues, BfTypedValue* argCascade)
  6856. {
  6857. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlag(mBfEvalExprFlags);
  6858. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mConstEvalAttributeTypeDef)))
  6859. {
  6860. mModule->mAttributeState->mUsed = true;
  6861. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  6862. }
  6863. else if ((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0)
  6864. {
  6865. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  6866. }
  6867. else if (((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_Comptime) != 0) && (!mModule->mIsComptimeModule))
  6868. {
  6869. if ((mModule->mCurMethodInstance == NULL) || (mModule->mCurMethodInstance->mComptimeFlags == BfComptimeFlag_None))
  6870. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  6871. }
  6872. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || IsConstEval());
  6873. if (((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_OnlyFromComptime) != 0) &&
  6874. ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) &&
  6875. ((mModule->mCurMethodInstance == NULL) || (mModule->mCurMethodInstance->mComptimeFlags == BfComptimeFlag_None)) &&
  6876. (!mModule->mIsComptimeModule))
  6877. {
  6878. mModule->Fail(StrFormat("Method '%s' can only be invoked at comptime. Consider adding [Comptime] to the current method.", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  6879. }
  6880. bool bypassVirtual = (callFlags & BfCreateCallFlags_BypassVirtual) != 0;
  6881. bool skipThis = (callFlags & BfCreateCallFlags_SkipThis) != 0;;
  6882. static int sCallIdx = 0;
  6883. if (!mModule->mCompiler->mIsResolveOnly)
  6884. sCallIdx++;
  6885. int callIdx = sCallIdx;
  6886. if (callIdx == 0x000015CB)
  6887. {
  6888. NOP;
  6889. }
  6890. // Temporarily disable so we don't capture calls in params
  6891. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  6892. SetAndRestoreValue<bool> prevAllowVariableDeclarations;
  6893. if (mModule->mCurMethodState != NULL)
  6894. prevAllowVariableDeclarations.Init(mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations, false);
  6895. BfMethodInstance* methodInstance = moduleMethodInstance.mMethodInstance;
  6896. SizedArray<BfIRValue, 4> irArgs;
  6897. if ((methodDef->mIsAbstract) && (bypassVirtual))
  6898. {
  6899. mModule->Fail(StrFormat("Abstract base method '%s' cannot be invoked", mModule->MethodToString(methodInstance).c_str()), targetSrc);
  6900. }
  6901. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  6902. BfType* returnType = methodInstance->mReturnType;
  6903. /*if (returnType->IsSelf())
  6904. {
  6905. returnType = methodInstance->GetOwner();
  6906. BF_ASSERT(returnType->IsInterface());
  6907. }*/
  6908. Array<BfTypedValue> argCascades;
  6909. BfTypedValue target = inTarget;
  6910. if (!skipThis)
  6911. {
  6912. if ((target) && (target.mType->IsFunction()) && (methodInstance->GetOwner() == target.mType))
  6913. {
  6914. CheckResultForReading(target);
  6915. target = mModule->LoadValue(target);
  6916. auto funcType = mModule->mBfIRBuilder->MapMethod(moduleMethodInstance.mMethodInstance);
  6917. auto funcPtrType = mModule->mBfIRBuilder->GetPointerTo(funcType);
  6918. moduleMethodInstance.mFunc = mModule->mBfIRBuilder->CreateIntToPtr(target.mValue, funcPtrType);
  6919. if (mDeferCallData != NULL)
  6920. {
  6921. mDeferCallData->mFuncAlloca_Orig = moduleMethodInstance.mFunc;
  6922. mDeferCallData->mFuncAlloca = mModule->CreateAlloca(funcPtrType, target.mType->mAlign, false, "FuncAlloca");
  6923. mModule->mBfIRBuilder->CreateStore(mDeferCallData->mFuncAlloca_Orig, mDeferCallData->mFuncAlloca);
  6924. }
  6925. }
  6926. else if (!methodDef->mIsStatic)
  6927. {
  6928. if ((!target) && (prevBindResult.mPrevVal != NULL))
  6929. {
  6930. auto bindResult = prevBindResult.mPrevVal;
  6931. if (bindResult->mBindType != NULL)
  6932. {
  6933. // Allow binding a function to a 'this' type even if no target is specified
  6934. auto delegateInfo = bindResult->mBindType->GetDelegateInfo();
  6935. if (delegateInfo != NULL)
  6936. {
  6937. if (delegateInfo->mHasExplicitThis)
  6938. {
  6939. target = mModule->GetDefaultTypedValue(delegateInfo->mParams[0], false, BfDefaultValueKind_Addr);
  6940. bypassVirtual = true;
  6941. }
  6942. }
  6943. else if (bindResult->mBindType->IsFunction())
  6944. {
  6945. BfMethodInstance* invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(bindResult->mBindType->ToTypeInstance(), 0, "Invoke");
  6946. if (!invokeMethodInstance->mMethodDef->mIsStatic)
  6947. {
  6948. target = mModule->GetDefaultTypedValue(invokeMethodInstance->GetThisType(), false, BfDefaultValueKind_Addr);
  6949. }
  6950. }
  6951. }
  6952. }
  6953. if (!target)
  6954. {
  6955. FinishDeferredEvals(argValues);
  6956. auto error = mModule->Fail(StrFormat("An instance reference is required to %s the non-static method '%s'",
  6957. (prevBindResult.mPrevVal != NULL) ? "bind" : "invoke",
  6958. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  6959. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  6960. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  6961. return mModule->GetDefaultTypedValue(returnType);
  6962. }
  6963. auto prevResult = mResult;
  6964. mResult = target;
  6965. CheckResultForReading(mResult);
  6966. mResult = prevResult;
  6967. if (methodDef->mMethodType != BfMethodType_Ctor)
  6968. {
  6969. bool doAccessCheck = true;
  6970. if (target.IsThis())
  6971. {
  6972. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  6973. doAccessCheck = false;
  6974. }
  6975. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  6976. doAccessCheck = false;
  6977. if ((doAccessCheck) && (!isSkipCall) && (prevBindResult.mPrevVal == NULL))
  6978. mModule->EmitObjectAccessCheck(target);
  6979. }
  6980. if (((prevBindResult.mPrevVal == NULL) || (!prevBindResult.mPrevVal->mSkipThis)) &&
  6981. (!isSkipCall))
  6982. {
  6983. bool skipMutCheck = false;
  6984. if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mSkipMutCheck))
  6985. {
  6986. // If we are binding a delegate, then we will end up making a copy of the target anyway
  6987. // so we don't need to do a mutability check
  6988. skipMutCheck = true;
  6989. }
  6990. if (methodDef->mMethodType == BfMethodType_Extension)
  6991. PushArg(target, irArgs);
  6992. else
  6993. PushThis(targetSrc, target, moduleMethodInstance.mMethodInstance, irArgs, skipMutCheck);
  6994. }
  6995. }
  6996. else if (methodDef->mMethodType == BfMethodType_Extension)
  6997. {
  6998. // Handled in args
  6999. }
  7000. else
  7001. {
  7002. if (prevBindResult.mPrevVal == NULL)
  7003. {
  7004. if ((mModule->mAttributeState == NULL) || (mModule->mAttributeState->mCustomAttributes == NULL) ||
  7005. (!mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoStaticCtorAttributeTypeDef)))
  7006. {
  7007. mModule->CheckStaticAccess(methodInstance->mMethodInstanceGroup->mOwner);
  7008. }
  7009. }
  7010. if (target)
  7011. {
  7012. FinishDeferredEvals(argValues);
  7013. mModule->Fail(StrFormat("Method '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  7014. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  7015. return mModule->GetDefaultTypedValue(returnType);
  7016. }
  7017. }
  7018. }
  7019. if (isSkipCall)
  7020. {
  7021. CheckSkipCall(targetSrc, argValues);
  7022. FinishDeferredEvals(argValues);
  7023. mModule->EmitEnsureInstructionAt();
  7024. return mModule->GetDefaultTypedValue(returnType);
  7025. }
  7026. bool hasNamedArgs = false;
  7027. for (auto& arg : argValues)
  7028. if (arg.mNameNode != NULL)
  7029. hasNamedArgs = true;
  7030. if (hasNamedArgs)
  7031. {
  7032. methodDef->BuildParamNameMap();
  7033. BfIdentifierNode* outOfPlaceName = NULL;
  7034. int curParamIdx = 0;
  7035. SizedArrayImpl<BfResolvedArg> origArgValues = argValues;
  7036. argValues.Clear();
  7037. for (int argIdx = 0; argIdx < origArgValues.mSize; argIdx++)
  7038. {
  7039. int paramIdx = curParamIdx;
  7040. auto& argValue = origArgValues[argIdx];
  7041. if (argValue.mNameNode != NULL)
  7042. {
  7043. int namedParamIdx = -1;
  7044. if (methodDef->mParamNameMap->TryGetValue(argValue.mNameNode->ToStringView(), &namedParamIdx))
  7045. {
  7046. paramIdx = namedParamIdx;
  7047. }
  7048. else
  7049. {
  7050. if (mModule->PreFail())
  7051. {
  7052. mModule->Fail(StrFormat("The best overload for '%s' does not have a parameter named '%s'", methodInstance->mMethodDef->mName.c_str(),
  7053. argValue.mNameNode->ToString().c_str()), argValue.mNameNode);
  7054. }
  7055. }
  7056. if (paramIdx != curParamIdx)
  7057. outOfPlaceName = argValue.mNameNode;
  7058. }
  7059. else if (outOfPlaceName != NULL)
  7060. {
  7061. if (mModule->PreFail())
  7062. mModule->Fail(StrFormat("Named argument '%s' is used out-of-position but is followed by an unnamed argument", outOfPlaceName->ToString().c_str()), outOfPlaceName);
  7063. outOfPlaceName = NULL;
  7064. }
  7065. if ((paramIdx < methodInstance->GetParamCount()) && (paramIdx != argIdx))
  7066. {
  7067. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_Normal)
  7068. {
  7069. auto wantType = methodInstance->GetParamType(paramIdx);
  7070. auto resolvedValue = ResolveArgValue(argValue, wantType);
  7071. if (resolvedValue)
  7072. {
  7073. argValue.mTypedValue = resolvedValue;
  7074. argValue.mArgFlags = (BfArgFlags)(argValue.mArgFlags | BfArgFlag_Finalized);
  7075. }
  7076. }
  7077. }
  7078. while (paramIdx >= argValues.mSize)
  7079. argValues.Add(BfResolvedArg());
  7080. if (argValues[paramIdx].mExpression != NULL)
  7081. {
  7082. if (argValue.mNameNode != NULL)
  7083. {
  7084. if (mModule->PreFail())
  7085. mModule->Fail(StrFormat("Named argument '%s' cannot be specified multiple times", argValue.mNameNode->ToString().c_str()), argValue.mNameNode);
  7086. }
  7087. }
  7088. argValues[paramIdx] = argValue;
  7089. curParamIdx++;
  7090. }
  7091. }
  7092. int argIdx = 0;
  7093. int paramIdx = 0;
  7094. BfIRValue expandedParamAlloca;
  7095. BfTypedValue expandedParamsArray;
  7096. BfType* expandedParamsElementType = NULL;
  7097. bool hadDelegateParamIdx = false;
  7098. int extendedParamIdx = 0;
  7099. AddCallDependencies(methodInstance);
  7100. bool wasCapturingMatchInfo = false;
  7101. auto autoComplete = GetAutoComplete();
  7102. if (autoComplete != NULL)
  7103. {
  7104. // Set to false to make sure we don't capture method match info from 'params' array creation
  7105. wasCapturingMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  7106. autoComplete->mIsCapturingMethodMatchInfo = false;
  7107. }
  7108. defer(
  7109. {
  7110. if (autoComplete != NULL)
  7111. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMatchInfo;
  7112. });
  7113. BfScopeData* boxScopeData = (mDeferCallData != NULL) ? mDeferCallData->mScopeAlloc : NULL;
  7114. if ((boxScopeData == NULL) && (mModule->mCurMethodState != NULL))
  7115. boxScopeData = mModule->mCurMethodState->mCurScope;
  7116. bool failed = false;
  7117. while (true)
  7118. {
  7119. int argExprIdx = argIdx;
  7120. if (methodDef->mMethodType == BfMethodType_Extension)
  7121. argExprIdx--;
  7122. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  7123. bool isDirectPass = false;
  7124. if (paramIdx >= (int)methodInstance->GetParamCount())
  7125. {
  7126. if (methodInstance->IsVarArgs())
  7127. {
  7128. if (argExprIdx >= (int)argValues.size())
  7129. break;
  7130. BfTypedValue argValue = ResolveArgValue(argValues[argExprIdx], NULL);
  7131. if (argValue)
  7132. {
  7133. auto typeInst = argValue.mType->ToTypeInstance();
  7134. if (argValue.mType == mModule->GetPrimitiveType(BfTypeCode_Float))
  7135. argValue = mModule->Cast(argValues[argExprIdx].mExpression, argValue, mModule->GetPrimitiveType(BfTypeCode_Double));
  7136. if ((typeInst != NULL) && (typeInst->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  7137. {
  7138. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  7139. BfType* charPtrType = mModule->CreatePointerType(charType);
  7140. argValue = mModule->Cast(argValues[argExprIdx].mExpression, argValue, charPtrType);
  7141. }
  7142. PushArg(argValue, irArgs, true, false);
  7143. }
  7144. argIdx++;
  7145. continue;
  7146. }
  7147. if (argExprIdx < (int)argValues.size())
  7148. {
  7149. if (mModule->PreFail())
  7150. {
  7151. BfAstNode* errorRef = argValues[argExprIdx].mExpression;
  7152. if (errorRef == NULL)
  7153. errorRef = targetSrc;
  7154. BfError* error;
  7155. if ((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0)
  7156. {
  7157. int checkIdx = argExprIdx - 1;
  7158. while (checkIdx >= 0)
  7159. {
  7160. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  7161. {
  7162. errorRef = argValues[checkIdx].mExpression;
  7163. break;
  7164. }
  7165. checkIdx--;
  7166. }
  7167. error = mModule->Fail("Expanded string interpolation generates too many arguments. If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  7168. }
  7169. else if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mBindType != NULL))
  7170. error = mModule->Fail(StrFormat("Method '%s' has too few parameters to bind to '%s'.", mModule->MethodToString(methodInstance).c_str(), mModule->TypeToString(prevBindResult.mPrevVal->mBindType).c_str()), errorRef);
  7171. else
  7172. error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", (int)argValues.size() - argExprIdx), errorRef);
  7173. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  7174. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  7175. }
  7176. failed = true;
  7177. break;
  7178. }
  7179. break;
  7180. }
  7181. // Only create actual params if we're not just trying to bind the function
  7182. if ((prevBindResult.mPrevVal != NULL) && (!prevBindResult.mPrevVal->mWantsArgs))
  7183. break;
  7184. BfType* wantType = NULL;
  7185. bool wantsSplat = false;
  7186. if (expandedParamsElementType != NULL)
  7187. {
  7188. wantType = expandedParamsElementType;
  7189. }
  7190. else
  7191. {
  7192. wantsSplat = methodInstance->GetParamIsSplat(paramIdx) && (!IsComptime());
  7193. if (methodInstance->IsImplicitCapture(paramIdx))
  7194. {
  7195. auto paramType = methodInstance->GetParamType(paramIdx);
  7196. if (mModule->mCurMethodInstance->IsMixin())
  7197. {
  7198. // Don't bother, also- can fail on captures
  7199. }
  7200. else
  7201. {
  7202. // static int captureIdx = 0;
  7203. // captureIdx++;
  7204. // int curCaptureIdx = captureIdx;
  7205. //
  7206. // if (curCaptureIdx == 0x91)
  7207. // {
  7208. // NOP;
  7209. // }
  7210. auto lookupVal = DoImplicitArgCapture(targetSrc, methodInstance, paramIdx, failed, BfImplicitParamKind_General, origTarget);
  7211. if (lookupVal)
  7212. {
  7213. if (wantsSplat)
  7214. {
  7215. SplatArgs(lookupVal, irArgs);
  7216. }
  7217. else if (paramType->IsRef())
  7218. {
  7219. irArgs.push_back(lookupVal.mValue);
  7220. }
  7221. else
  7222. PushArg(lookupVal, irArgs, true);
  7223. }
  7224. }
  7225. paramIdx++;
  7226. continue;
  7227. }
  7228. wantType = methodInstance->GetParamType(paramIdx);
  7229. if (!mModule->mCurTypeInstance->IsInterface())
  7230. {
  7231. // Resolve `Self` types
  7232. if (wantType->IsUnspecializedTypeVariation())
  7233. {
  7234. wantType = mModule->ResolveSelfType(wantType, methodInstance->GetOwner());
  7235. }
  7236. }
  7237. if (IsVar(wantType))
  7238. {
  7239. // Case happens when we can't find the argument type
  7240. failed = true;
  7241. }
  7242. BfParamKind paramKind = methodInstance->GetParamKind(paramIdx);
  7243. if (paramKind == BfParamKind_Params)
  7244. {
  7245. //TODO: Check to see if it's a direct array pass
  7246. if (argIdx < (int)argValues.size())
  7247. {
  7248. auto argValue = argValues[argIdx].mTypedValue;
  7249. if ((argValue.IsParams()) /*&& (mModule->CanCast(argValue, wantType))*/)
  7250. isDirectPass = true;
  7251. }
  7252. if (!isDirectPass)
  7253. {
  7254. int numElements = BF_MAX((int)argValues.size() - argIdx, 0);
  7255. if (methodDef->mMethodType == BfMethodType_Extension)
  7256. numElements++;
  7257. if (IsConstEval())
  7258. {
  7259. if ((wantType->IsArray()) || (wantType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  7260. {
  7261. auto genericTypeInst = wantType->ToGenericTypeInstance();
  7262. expandedParamsElementType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  7263. auto irSizedArrayType = mModule->mBfIRBuilder->GetSizedArrayType(mModule->mBfIRBuilder->MapType(expandedParamsElementType), numElements);
  7264. Array<BfIRValue> values;
  7265. for (int i = 0; i < numElements; i++)
  7266. values.Add(mModule->mBfIRBuilder->GetFakeVal());
  7267. expandedParamsArray = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(irSizedArrayType, values), wantType);
  7268. PushArg(expandedParamsArray, irArgs);
  7269. continue;
  7270. }
  7271. }
  7272. else if (wantType->IsArray())
  7273. {
  7274. BfArrayType* arrayType = (BfArrayType*)wantType;
  7275. mModule->PopulateType(arrayType, BfPopulateType_DataAndMethods);
  7276. expandedParamsElementType = arrayType->mGenericTypeInfo->mTypeGenericArguments[0];
  7277. int arrayClassSize = arrayType->mInstSize - expandedParamsElementType->mSize;
  7278. expandedParamsArray = BfTypedValue(mModule->AllocFromType(arrayType->GetUnderlyingType(), boxScopeData, BfIRValue(), mModule->GetConstValue(numElements), 1, BfAllocFlags_None),
  7279. arrayType, false);
  7280. BfResolvedArgs resolvedArgs;
  7281. MatchConstructor(targetSrc, NULL, expandedParamsArray, arrayType, resolvedArgs, false, BfMethodGenericArguments(), BfAllowAppendKind_No);
  7282. //TODO: Assert 'length' var is at slot 1
  7283. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(expandedParamsArray.mValue, mModule->mBfIRBuilder->MapType(arrayType->mBaseType));
  7284. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  7285. if (arrayLengthBitCount == 0)
  7286. {
  7287. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", targetSrc);
  7288. return BfTypedValue();
  7289. }
  7290. auto& fieldInstance = arrayType->mBaseType->mFieldInstances[0];
  7291. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, fieldInstance.mDataIdx);
  7292. if (arrayLengthBitCount == 64)
  7293. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue64(numElements), addr, 8);
  7294. else
  7295. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue32(numElements), addr, 4);
  7296. PushArg(expandedParamsArray, irArgs);
  7297. continue;
  7298. }
  7299. else if (wantType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  7300. {
  7301. mModule->PopulateType(wantType);
  7302. mModule->mBfIRBuilder->PopulateType(wantType);
  7303. auto genericTypeInst = wantType->ToGenericTypeInstance();
  7304. expandedParamsElementType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  7305. expandedParamsArray = BfTypedValue(mModule->CreateAlloca(wantType), wantType, true);
  7306. expandedParamAlloca = mModule->CreateAlloca(genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0], true, NULL, mModule->GetConstValue(numElements));
  7307. mModule->mBfIRBuilder->CreateAlignedStore(expandedParamAlloca, mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 1), mModule->mSystem->mPtrSize);
  7308. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue(numElements), mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 2), mModule->mSystem->mPtrSize);
  7309. PushArg(expandedParamsArray, irArgs, !wantsSplat);
  7310. continue;
  7311. }
  7312. else if (wantType->IsSizedArray())
  7313. {
  7314. mModule->PopulateType(wantType);
  7315. mModule->mBfIRBuilder->PopulateType(wantType);
  7316. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)wantType;
  7317. expandedParamsElementType = wantType->GetUnderlyingType();
  7318. if (numElements != sizedArrayType->mElementCount)
  7319. {
  7320. BfAstNode* refNode = targetSrc;
  7321. if (argExprIdx < (int)argValues.size())
  7322. refNode = argValues[argExprIdx].mExpression;
  7323. mModule->Fail(StrFormat("Incorrect number of arguments to match params type '%s'", mModule->TypeToString(wantType).c_str()), refNode);
  7324. }
  7325. expandedParamsArray = BfTypedValue(mModule->CreateAlloca(wantType), wantType, true);
  7326. expandedParamAlloca = mModule->mBfIRBuilder->CreateBitCast(expandedParamsArray.mValue, mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(expandedParamsElementType)));
  7327. PushArg(expandedParamsArray, irArgs, !wantsSplat);
  7328. continue;
  7329. }
  7330. }
  7331. }
  7332. else if (paramKind == BfParamKind_DelegateParam)
  7333. hadDelegateParamIdx = true;
  7334. }
  7335. BfAstNode* arg = NULL;
  7336. bool hadMissingArg = false;
  7337. if (argExprIdx == -1)
  7338. arg = targetSrc;
  7339. if (argExprIdx >= 0)
  7340. {
  7341. if (argExprIdx < (int)argValues.size())
  7342. {
  7343. arg = argValues[argExprIdx].mExpression;
  7344. if (((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0) && (!expandedParamsArray) && (!hadDelegateParamIdx))
  7345. {
  7346. BfAstNode* errorRef = arg;
  7347. int checkIdx = argExprIdx - 1;
  7348. while (checkIdx >= 0)
  7349. {
  7350. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  7351. {
  7352. errorRef = argValues[checkIdx].mExpression;
  7353. break;
  7354. }
  7355. checkIdx--;
  7356. }
  7357. mModule->Warn(BfWarning_BF4205_StringInterpolationParam, "Expanded string interpolation argument not used as 'params'. If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  7358. }
  7359. // if ((arg == NULL) && (argValues[argExprIdx].mExpression != NULL))
  7360. // hadMissingArg = true;
  7361. if ((arg == NULL) && (!argValues[argExprIdx].mTypedValue))
  7362. hadMissingArg = true;
  7363. }
  7364. else
  7365. hadMissingArg = true;
  7366. }
  7367. BfTypedValue argValue;
  7368. if (hadMissingArg)
  7369. {
  7370. if (expandedParamsArray)
  7371. break;
  7372. if ((argIdx >= (int) methodInstance->mDefaultValues.size()) || (!methodInstance->mDefaultValues[argIdx]))
  7373. {
  7374. BfAstNode* refNode = targetSrc;
  7375. if (argValues.size() > 0)
  7376. {
  7377. auto checkExpr = argValues.back().mExpression;
  7378. if (checkExpr != NULL)
  7379. refNode = checkExpr;
  7380. }
  7381. BfAstNode* prevNode = NULL;
  7382. if (targetSrc == NULL)
  7383. {
  7384. // We must be in BfModule::EmitCtorBody
  7385. }
  7386. else if (auto tupleExpr = BfNodeDynCastExact<BfTupleExpression>(targetSrc))
  7387. {
  7388. if (tupleExpr->mCommas.size() > 0)
  7389. prevNode = tupleExpr->mCommas.back();
  7390. else
  7391. prevNode = tupleExpr->mOpenParen;
  7392. if (tupleExpr->mCloseParen != NULL)
  7393. refNode = tupleExpr->mCloseParen;
  7394. }
  7395. else if (mModule->mParentNodeEntry != NULL)
  7396. {
  7397. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(mModule->mParentNodeEntry->mNode))
  7398. {
  7399. if (objectCreateExpr->mCommas.size() > 0)
  7400. prevNode = objectCreateExpr->mCommas.back();
  7401. else
  7402. prevNode = objectCreateExpr->mOpenToken;
  7403. if (objectCreateExpr->mCloseToken != NULL)
  7404. refNode = objectCreateExpr->mCloseToken;
  7405. if (auto newNode = BfNodeDynCast<BfNewNode>(objectCreateExpr->mNewNode))
  7406. {
  7407. if (newNode->mAllocNode == targetSrc)
  7408. refNode = targetSrc;
  7409. }
  7410. }
  7411. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  7412. {
  7413. if (invokeExpr->mCommas.size() > 0)
  7414. prevNode = invokeExpr->mCommas.back();
  7415. else
  7416. prevNode = invokeExpr->mOpenParen;
  7417. if (invokeExpr->mCloseParen != NULL)
  7418. refNode = invokeExpr->mCloseParen;
  7419. }
  7420. }
  7421. if (refNode == NULL)
  7422. refNode = methodInstance->GetOwner()->mTypeDef->GetRefNode();
  7423. if ((autoComplete != NULL) && (prevNode != NULL))
  7424. autoComplete->CheckEmptyStart(prevNode, wantType);
  7425. BfError* error = NULL;
  7426. if (mModule->mParentNodeEntry != NULL)
  7427. {
  7428. bool showCtorError = false;
  7429. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(mModule->mParentNodeEntry->mNode))
  7430. {
  7431. if (ctorDeclaration->mInitializer == NULL)
  7432. showCtorError = true;
  7433. }
  7434. if (auto typerDecl = BfNodeDynCast<BfTypeDeclaration>(mModule->mParentNodeEntry->mNode))
  7435. showCtorError = true;
  7436. if (showCtorError)
  7437. {
  7438. if (mModule->PreFail())
  7439. {
  7440. error = mModule->Fail(StrFormat("No parameterless constructor is available for base class. Consider calling base constructor '%s'.",
  7441. mModule->MethodToString(methodInstance).c_str()), refNode);
  7442. }
  7443. auto srcNode = mModule->mCurMethodInstance->mMethodDef->GetRefNode();
  7444. if ((autoComplete != NULL) && (autoComplete->CheckFixit(srcNode)))
  7445. autoComplete->FixitAddConstructor(mModule->mCurTypeInstance);
  7446. }
  7447. }
  7448. if (mModule->PreFail())
  7449. {
  7450. if (error == NULL)
  7451. {
  7452. if (hasNamedArgs)
  7453. error = mModule->Fail(StrFormat("There is no argument given that corresponds to the required formal parameter '%s' of '%s'.",
  7454. methodInstance->GetParamName(paramIdx).c_str(), mModule->MethodToString(methodInstance).c_str()), refNode);
  7455. else
  7456. error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", methodInstance->GetParamCount() - paramIdx), refNode);
  7457. }
  7458. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  7459. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  7460. }
  7461. failed = true;
  7462. break;
  7463. }
  7464. auto foreignDefaultVal = methodInstance->mDefaultValues[argIdx];
  7465. auto foreignConst = methodInstance->GetOwner()->mConstHolder->GetConstant(foreignDefaultVal.mValue);
  7466. if (foreignConst->mConstType == BfConstType_AggZero)
  7467. {
  7468. // Allow this
  7469. }
  7470. else if (foreignConst->mTypeCode == BfTypeCode_NullPtr)
  7471. {
  7472. if (wantType->IsNullable())
  7473. {
  7474. argValue = mModule->GetDefaultTypedValue(wantType, false, BfDefaultValueKind_Addr);
  7475. }
  7476. }
  7477. else if (foreignConst->mConstType == BfConstType_GlobalVar)
  7478. {
  7479. auto globalVar = (BfGlobalVar*)foreignConst;
  7480. if (globalVar->mName[0] == '#')
  7481. {
  7482. if (strcmp(globalVar->mName, "#CallerLineNum") == 0)
  7483. {
  7484. argValue = BfTypedValue(mModule->GetConstValue(mModule->mCurFilePosition.mCurLine + 1), mModule->GetPrimitiveType(BfTypeCode_Int32));
  7485. }
  7486. else if (strcmp(globalVar->mName, "#CallerFilePath") == 0)
  7487. {
  7488. String filePath = "";
  7489. if (mModule->mCurFilePosition.mFileInstance != NULL)
  7490. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  7491. argValue = BfTypedValue(mModule->GetStringObjectValue(filePath),
  7492. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7493. }
  7494. else if (strcmp(globalVar->mName, "#CallerFileName") == 0)
  7495. {
  7496. String filePath = "";
  7497. if (mModule->mCurFilePosition.mFileInstance != NULL)
  7498. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  7499. argValue = BfTypedValue(mModule->GetStringObjectValue(GetFileName(filePath)),
  7500. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7501. }
  7502. else if (strcmp(globalVar->mName, "#CallerFileDir") == 0)
  7503. {
  7504. String filePath = "";
  7505. if (mModule->mCurFilePosition.mFileInstance != NULL)
  7506. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  7507. argValue = BfTypedValue(mModule->GetStringObjectValue(GetFileDir(filePath)),
  7508. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7509. }
  7510. else if (strcmp(globalVar->mName, "#CallerTypeName") == 0)
  7511. {
  7512. String typeName = "";
  7513. if (mModule->mCurTypeInstance != NULL)
  7514. typeName = mModule->TypeToString(mModule->mCurTypeInstance);
  7515. argValue = BfTypedValue(mModule->GetStringObjectValue(typeName),
  7516. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7517. }
  7518. else if (strcmp(globalVar->mName, "#CallerType") == 0)
  7519. {
  7520. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  7521. BfType* type = mModule->mCurTypeInstance;
  7522. if (type != NULL)
  7523. {
  7524. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7525. argValue = BfTypedValue(mModule->CreateTypeDataRef(type), typeType);
  7526. }
  7527. }
  7528. else if (strcmp(globalVar->mName, "#CallerMemberName") == 0)
  7529. {
  7530. String memberName = "";
  7531. if (mModule->mCurMethodInstance != NULL)
  7532. memberName = mModule->MethodToString(mModule->mCurMethodInstance);
  7533. argValue = BfTypedValue(mModule->GetStringObjectValue(memberName),
  7534. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7535. }
  7536. else if (strcmp(globalVar->mName, "#CallerProject") == 0)
  7537. {
  7538. String projectName = "";
  7539. if (mModule->mCurMethodInstance != NULL)
  7540. projectName = mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mProject->mName;
  7541. argValue = BfTypedValue(mModule->GetStringObjectValue(projectName),
  7542. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7543. }
  7544. else if (strcmp(globalVar->mName, "#ProjectName") == 0)
  7545. {
  7546. String projectName = methodInstance->mMethodDef->mDeclaringType->mProject->mName;
  7547. argValue = BfTypedValue(mModule->GetStringObjectValue(projectName),
  7548. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7549. }
  7550. else
  7551. {
  7552. argValue = mModule->GetCompilerFieldValue(globalVar->mName);
  7553. }
  7554. }
  7555. }
  7556. else if (foreignConst->mConstType == BfConstType_GEP32_2)
  7557. {
  7558. auto constGep32_2 = (BfConstantGEP32_2*)foreignConst;
  7559. auto gepTarget = methodInstance->GetOwner()->mConstHolder->GetConstantById(constGep32_2->mTarget);
  7560. if (gepTarget->mConstType == BfConstType_GlobalVar)
  7561. {
  7562. auto globalVar = (BfGlobalVar*)gepTarget;
  7563. if (globalVar->mName[0] == '#')
  7564. {
  7565. if (strcmp(globalVar->mName, "#CallerExpression") == 0)
  7566. {
  7567. int exprIdx = constGep32_2->mIdx1;
  7568. if ((exprIdx >= 0) && (exprIdx < (int)argValues.size()))
  7569. {
  7570. auto expr = argValues[exprIdx].mExpression;
  7571. if (expr != NULL)
  7572. {
  7573. argValue = BfTypedValue(mModule->GetStringObjectValue(expr->ToString()),
  7574. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7575. }
  7576. }
  7577. else
  7578. {
  7579. mModule->Fail("CallerExpression index out of bounds", targetSrc);
  7580. argValue = BfTypedValue(mModule->GetStringObjectValue(""),
  7581. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7582. }
  7583. }
  7584. }
  7585. }
  7586. }
  7587. if (!argValue)
  7588. {
  7589. argValue = mModule->GetTypedValueFromConstant(foreignConst, methodInstance->GetOwner()->mConstHolder, foreignDefaultVal.mType);
  7590. if (!argValue)
  7591. mModule->Fail("Default parameter value failed", targetSrc);
  7592. mModule->mBfIRBuilder->PopulateType(foreignDefaultVal.mType);
  7593. }
  7594. }
  7595. else
  7596. {
  7597. if (argExprIdx == -1)
  7598. argValue = target;
  7599. else
  7600. argValue = argValues[argExprIdx].mTypedValue;
  7601. if ((argValue.IsParams()) && (!isDirectPass))
  7602. {
  7603. BfAstNode* refNode = arg;
  7604. if (auto unaryOperatorExpr = BfNodeDynCast<BfUnaryOperatorExpression>(refNode))
  7605. refNode = unaryOperatorExpr->mOpToken;
  7606. mModule->Warn(0, "Unused 'params' expression", refNode);
  7607. }
  7608. if (wantType->IsMethodRef())
  7609. {
  7610. auto expr = argValues[argExprIdx].mExpression;
  7611. if (expr != NULL)
  7612. SetMethodElementType(expr);
  7613. if (!argValue)
  7614. argValue = mModule->CreateValueFromExpression(BfNodeDynCast<BfExpression>(arg), wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  7615. // Add any implicit captures now
  7616. auto methodRefType = (BfMethodRefType*)wantType;
  7617. BfMethodInstance* useMethodInstance = methodRefType->mMethodRef;
  7618. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  7619. {
  7620. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  7621. auto lookupVal = DoImplicitArgCapture(arg, useMethodInstance, paramIdx, failed, BfImplicitParamKind_General, argValue);
  7622. if (lookupVal)
  7623. {
  7624. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  7625. SplatArgs(lookupVal, irArgs);
  7626. else
  7627. {
  7628. if (lookupVal.mType->IsComposite())
  7629. lookupVal = mModule->MakeAddressable(lookupVal, false);
  7630. irArgs.push_back(lookupVal.mValue);
  7631. }
  7632. }
  7633. }
  7634. paramIdx++;
  7635. argIdx++;
  7636. continue;
  7637. }
  7638. else if (argExprIdx >= 0)
  7639. {
  7640. BfParamKind paramKind = BfParamKind_Normal;
  7641. BfIdentifierNode* paramNameNode = NULL;
  7642. if (paramIdx < methodInstance->GetParamCount())
  7643. {
  7644. paramKind = methodInstance->GetParamKind(paramIdx);
  7645. paramNameNode = methodInstance->GetParamNameNode(paramIdx);
  7646. }
  7647. argValues[argExprIdx].mExpectedType = wantType;
  7648. argValue = ResolveArgValue(argValues[argExprIdx], wantType, NULL, paramKind, paramNameNode);
  7649. }
  7650. }
  7651. if (!argValue)
  7652. {
  7653. failed = true;
  7654. }
  7655. if ((arg != NULL) && (autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(arg)))
  7656. {
  7657. if (!autoComplete->mResultString.Contains('\r'))
  7658. {
  7659. String str;
  7660. str += methodInstance->GetParamName(paramIdx);
  7661. str += " @ ";
  7662. bool isCtor = methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor;
  7663. if (isCtor)
  7664. str += methodInstance->GetOwner()->mTypeDef->mName->ToString();
  7665. else
  7666. str += methodInstance->mMethodDef->mName;
  7667. str += "(";
  7668. for (int i = isCtor ? 1 : 0; i < methodInstance->GetParamCount(); i++)
  7669. {
  7670. if (i > (isCtor ? 1 : 0))
  7671. str += ",";
  7672. if (i == paramIdx)
  7673. {
  7674. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_Params)
  7675. str += "params ";
  7676. str += mModule->TypeToString(methodInstance->GetParamType(paramIdx));
  7677. }
  7678. }
  7679. str += ")";
  7680. if (!autoComplete->mResultString.StartsWith(":"))
  7681. autoComplete->mResultString.Clear();
  7682. int crPos = (int)autoComplete->mResultString.IndexOf('\n');
  7683. if (crPos == -1)
  7684. crPos = autoComplete->mResultString.mLength;
  7685. int insertPos = BF_MAX(1, crPos);
  7686. if (autoComplete->mResultString.IsEmpty())
  7687. autoComplete->mResultString += ":";
  7688. if (insertPos > 1)
  7689. str.Insert(0, '\r');
  7690. autoComplete->mResultString.Insert(insertPos, str);
  7691. }
  7692. }
  7693. if (argValue)
  7694. {
  7695. if ((isThis) && (argValue.mType->IsRef()))
  7696. {
  7697. // Convert a 'ref this' to a 'this*'
  7698. argValue.mType = mModule->CreatePointerType(argValue.mType->GetUnderlyingType());
  7699. }
  7700. BfAstNode* refNode = arg;
  7701. if (refNode == NULL)
  7702. refNode = targetSrc;
  7703. if ((wantType->IsRef()) && (!argValue.mType->IsRef()) &&
  7704. (((callFlags & BfCreateCallFlags_AllowImplicitRef) != 0) || (wantType->IsIn())))
  7705. {
  7706. auto underlyingType = wantType->GetUnderlyingType();
  7707. if (mModule->mCurMethodState != NULL)
  7708. {
  7709. SetAndRestoreValue<BfScopeData*> prevScopeData(mModule->mCurMethodState->mOverrideScope, boxScopeData);
  7710. argValue = mModule->Cast(refNode, argValue, underlyingType);
  7711. }
  7712. else
  7713. argValue = mModule->Cast(refNode, argValue, underlyingType, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  7714. if (argValue)
  7715. argValue = mModule->ToRef(argValue, (BfRefType*)wantType);
  7716. }
  7717. else
  7718. {
  7719. if (mModule->mCurMethodState != NULL)
  7720. {
  7721. SetAndRestoreValue<BfScopeData*> prevScopeData(mModule->mCurMethodState->mOverrideScope, boxScopeData);
  7722. argValue = mModule->Cast(refNode, argValue, wantType, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  7723. }
  7724. else
  7725. argValue = mModule->Cast(refNode, argValue, wantType, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  7726. }
  7727. if (!argValue)
  7728. {
  7729. if ((argExprIdx < (int)argValues.size()) && ((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0))
  7730. {
  7731. BfAstNode* errorRef = NULL;
  7732. int checkIdx = argExprIdx - 1;
  7733. while (checkIdx >= 0)
  7734. {
  7735. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  7736. {
  7737. errorRef = argValues[checkIdx].mExpression;
  7738. break;
  7739. }
  7740. checkIdx--;
  7741. }
  7742. if (errorRef != NULL)
  7743. mModule->Warn(0, "If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  7744. }
  7745. failed = true;
  7746. }
  7747. else if ((wantType->IsComposite()) && (!expandedParamsArray))
  7748. {
  7749. if (methodInstance->mIsIntrinsic)
  7750. {
  7751. // Intrinsics can handle structs either by value or address
  7752. }
  7753. else
  7754. {
  7755. // We need to make a temp and get the addr of that
  7756. if ((!wantsSplat) && (!argValue.IsValuelessType()) && (!argValue.IsAddr()) && (!IsConstEval()))
  7757. {
  7758. argValue = mModule->MakeAddressable(argValue);
  7759. }
  7760. }
  7761. }
  7762. else if (!wantType->IsRef())
  7763. argValue = mModule->LoadValue(argValue);
  7764. }
  7765. if ((argExprIdx != -1) && (argExprIdx < (int)argValues.size()) && ((argValues[argExprIdx].mArgFlags & BfArgFlag_Cascade) != 0))
  7766. {
  7767. mUsedAsStatement = true;
  7768. if (argValues[argExprIdx].mUncastedTypedValue)
  7769. argCascades.Add(argValues[argExprIdx].mUncastedTypedValue);
  7770. else
  7771. argCascades.Add(argValue);
  7772. }
  7773. if (expandedParamsArray)
  7774. {
  7775. if (argValue)
  7776. {
  7777. if (argValue.mValue.IsFake())
  7778. {
  7779. if ((!mModule->IsInUnspecializedGeneric()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  7780. mModule->InternalError("Invalid expandedParamsArray value");
  7781. }
  7782. else if (IsConstEval())
  7783. {
  7784. auto constant = mModule->mBfIRBuilder->GetConstant(expandedParamsArray.mValue);
  7785. BF_ASSERT(constant->mConstType == BfConstType_Agg);
  7786. auto constAgg = (BfConstantAgg*)constant;
  7787. constAgg->mValues[extendedParamIdx] = argValue.mValue;
  7788. }
  7789. else if (expandedParamAlloca)
  7790. {
  7791. argValue = mModule->LoadOrAggregateValue(argValue);
  7792. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamAlloca, extendedParamIdx);
  7793. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, addr, argValue.mType->mAlign);
  7794. }
  7795. else
  7796. {
  7797. auto firstElem = mModule->GetFieldByName(expandedParamsArray.mType->ToTypeInstance(), "mFirstElement");
  7798. if (firstElem != NULL)
  7799. {
  7800. argValue = mModule->LoadValue(argValue);
  7801. auto firstAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, firstElem->mDataIdx);
  7802. auto indexedAddr = mModule->CreateIndexedValue(argValue.mType, firstAddr, extendedParamIdx);
  7803. if (argValue.IsSplat())
  7804. mModule->AggregateSplatIntoAddr(argValue, indexedAddr);
  7805. else
  7806. mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, indexedAddr, argValue.mType->mAlign);
  7807. }
  7808. }
  7809. }
  7810. extendedParamIdx++;
  7811. }
  7812. else
  7813. {
  7814. if ((paramIdx == 0) && (methodInstance->GetParamName(paramIdx) == "this") && (wantType->IsPointer()))
  7815. {
  7816. auto underlyingType = wantType->GetUnderlyingType();
  7817. mModule->PopulateType(underlyingType, BfPopulateType_Data);
  7818. if ((underlyingType->IsValuelessType()) && (!underlyingType->IsVoid()))
  7819. {
  7820. // We don't actually pass a 'this' pointer for mut methods on valueless structs
  7821. argIdx++;
  7822. paramIdx++;
  7823. continue;
  7824. }
  7825. }
  7826. if (argValue)
  7827. {
  7828. if (isThis)
  7829. PushThis(targetSrc, argValue, methodInstance, irArgs);
  7830. else if (wantsSplat)
  7831. SplatArgs(argValue, irArgs);
  7832. else
  7833. PushArg(argValue, irArgs, true, false, methodInstance->mIsIntrinsic, methodInstance->mCallingConvention != BfCallingConvention_Unspecified);
  7834. }
  7835. paramIdx++;
  7836. }
  7837. argIdx++;
  7838. }
  7839. if (failed)
  7840. {
  7841. // Process the other unused arguments
  7842. while (argIdx < argValues.size())
  7843. {
  7844. mModule->AssertErrorState();
  7845. auto argValue = argValues[argIdx].mTypedValue;
  7846. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval | BfArgFlag_VariableDeclaration | BfArgFlag_UninitializedExpr)) != 0)
  7847. {
  7848. if (!argValue)
  7849. {
  7850. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  7851. if (expr != NULL)
  7852. argValue = mModule->CreateValueFromExpression(expr);
  7853. }
  7854. }
  7855. argIdx++;
  7856. }
  7857. prevIgnoreWrites.Restore();
  7858. return mModule->GetDefaultTypedValue(returnType, false, BfDefaultValueKind_Addr);
  7859. }
  7860. prevBindResult.Restore();
  7861. if (!methodDef->mIsStatic)
  7862. {
  7863. bool ignoreVirtualError = (mModule->mBfIRBuilder->mIgnoreWrites) && (mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef);
  7864. if ((methodInstance->GetOwner()->IsInterface()) && (!target.mType->IsGenericParam()) && (!target.mType->IsConcreteInterfaceType()) &&
  7865. (!mModule->mCurTypeInstance->IsInterface()) && (!ignoreVirtualError))
  7866. {
  7867. if (methodInstance->mVirtualTableIdx == -1)
  7868. {
  7869. mModule->PopulateType(methodInstance->GetOwner(), BfPopulateType_DataAndMethods);
  7870. }
  7871. if (methodInstance->mVirtualTableIdx == -1)
  7872. {
  7873. if (methodInstance->mMethodDef->mIsConcrete)
  7874. {
  7875. mModule->Fail(StrFormat("The method '%s' cannot be invoked from an interface reference because its return value is declared as 'concrete'", mModule->MethodToString(methodInstance).c_str()), targetSrc);
  7876. }
  7877. else if (methodInstance->HasSelf())
  7878. {
  7879. mModule->Fail(StrFormat("The method '%s' cannot be invoked from an interface reference because it contains 'Self' type references", mModule->MethodToString(methodInstance).c_str()), targetSrc);
  7880. }
  7881. else
  7882. {
  7883. if ((bypassVirtual) && (mModule->mCurTypeInstance->IsInterface()))
  7884. {
  7885. // Allow a base call to be defined
  7886. }
  7887. else if ((methodInstance->IsSpecializedGenericMethod()) && (origTarget) && (!origTarget.mType->IsInterface()))
  7888. {
  7889. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  7890. mModule->AssertErrorState();
  7891. }
  7892. else if ((!mModule->mCurMethodInstance->mIsUnspecialized))
  7893. {
  7894. // Compiler error?
  7895. String errorString = "Unable to dynamically dispatch '%s'";
  7896. if (methodInstance->IsSpecializedGenericMethod())
  7897. errorString = "Unable to dynamically dispatch '%s' because generic methods can only be directly dispatched";
  7898. if (methodInstance->mReturnType->IsConcreteInterfaceType())
  7899. errorString = "Unable to dynamically dispatch '%s' because the concrete return type is unknown";
  7900. mModule->Fail(StrFormat(errorString.c_str(), mModule->MethodToString(methodInstance).c_str()), targetSrc);
  7901. }
  7902. //BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  7903. }
  7904. if (mFunctionBindResult != NULL)
  7905. {
  7906. mFunctionBindResult->mMethodInstance = methodInstance;
  7907. mFunctionBindResult->mTarget = target;
  7908. mFunctionBindResult->mFunc = moduleMethodInstance.mFunc;
  7909. for (auto arg : irArgs)
  7910. mFunctionBindResult->mIRArgs.push_back(arg);
  7911. }
  7912. prevIgnoreWrites.Restore();
  7913. return mModule->GetDefaultTypedValue(returnType);
  7914. }
  7915. }
  7916. }
  7917. else
  7918. {
  7919. //BF_ASSERT(!methodInstance->GetOwner()->IsInterface());
  7920. }
  7921. prevIgnoreWrites.Restore();
  7922. if (target.mType != NULL)
  7923. {
  7924. // When we call a method from a static ctor, that method could access static fields so we need to make sure
  7925. // the type has been initialized
  7926. auto targetTypeInst = target.mType->ToTypeInstance();
  7927. if (targetTypeInst != NULL)
  7928. {
  7929. if (prevBindResult.mPrevVal == NULL)
  7930. {
  7931. if ((mModule->mAttributeState == NULL) || (mModule->mAttributeState->mCustomAttributes == NULL) ||
  7932. (!mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoStaticCtorAttributeTypeDef)))
  7933. {
  7934. mModule->CheckStaticAccess(targetTypeInst);
  7935. }
  7936. }
  7937. }
  7938. }
  7939. if (methodInstance->mReturnType == NULL)
  7940. {
  7941. mModule->AssertErrorState();
  7942. mModule->Fail("Circular reference in method instance", targetSrc);
  7943. return BfTypedValue();
  7944. }
  7945. BfCreateCallFlags physCallFlags = BfCreateCallFlags_None;
  7946. if ((origTarget.mType != NULL) && (origTarget.mType->IsGenericParam()))
  7947. physCallFlags = (BfCreateCallFlags)(physCallFlags | BfCreateCallFlags_GenericParamThis);
  7948. auto func = moduleMethodInstance.mFunc;
  7949. BfTypedValue callResult = CreateCall(targetSrc, methodInstance, func, bypassVirtual, irArgs, NULL, physCallFlags, origTarget.mType);
  7950. prevIgnoreWrites.Restore();
  7951. if ((methodInstance->mMethodDef->mIsNoReturn) && ((mBfEvalExprFlags & BfEvalExprFlags_IsExpressionBody) != 0) &&
  7952. (mExpectingType != NULL) && (callResult.mType != mExpectingType))
  7953. {
  7954. callResult = mModule->GetDefaultTypedValue(mExpectingType);
  7955. }
  7956. // This gets triggered for non-sret (ie: comptime) composite returns so they aren't considered readonly
  7957. if ((callResult.mKind == BfTypedValueKind_Value) && (!callResult.mValue.IsConst()) &&
  7958. (!callResult.mType->IsValuelessType()) && (callResult.mType->IsComposite()) && (!methodInstance->GetLoweredReturnType()))
  7959. {
  7960. bool makeAddressable = true;
  7961. auto typeInstance = callResult.mType->ToTypeInstance();
  7962. if ((typeInstance != NULL) && (typeInstance->mHasUnderlyingArray))
  7963. makeAddressable = false;
  7964. if (makeAddressable)
  7965. {
  7966. callResult = mModule->MakeAddressable(callResult, true);
  7967. }
  7968. }
  7969. if (argCascades.mSize == 1)
  7970. {
  7971. if (argCascade == NULL)
  7972. return argCascades[0];
  7973. *argCascade = argCascades[0];
  7974. }
  7975. if (argCascades.mSize > 1)
  7976. {
  7977. if (argCascade == NULL)
  7978. return mModule->CreateTuple(argCascades, {});
  7979. *argCascade = mModule->CreateTuple(argCascades, {});
  7980. }
  7981. return callResult;
  7982. }
  7983. BfTypedValue BfExprEvaluator::MatchConstructor(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, BfTypeInstance* targetType, BfResolvedArgs& argValues, bool callCtorBodyOnly,
  7984. const BfMethodGenericArguments& methodGenericArguments, BfAllowAppendKind allowAppendKind, BfTypedValue* appendIndexValue)
  7985. {
  7986. // Temporarily disable so we don't capture calls in params
  7987. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  7988. auto origAllowAppendKind = allowAppendKind;
  7989. if (allowAppendKind == BfAllowAppendKind_Infer)
  7990. {
  7991. mModule->PopulateType(targetType);
  7992. allowAppendKind = targetType->IsZeroGap() ? BfAllowAppendKind_ZeroGap : BfAllowAppendKind_Yes;
  7993. }
  7994. static int sCtorCount = 0;
  7995. sCtorCount++;
  7996. BfMethodMatcher methodMatcher(targetSrc, mModule, "", argValues.mResolvedArgs, methodGenericArguments);
  7997. methodMatcher.mAllowAppendKind = allowAppendKind;
  7998. methodMatcher.mBfEvalExprFlags = mBfEvalExprFlags;
  7999. BfTypeVector typeGenericArguments;
  8000. auto curTypeInst = targetType;
  8001. auto curTypeDef = targetType->mTypeDef;
  8002. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  8003. auto activeTypeDef = mModule->GetActiveTypeDef();
  8004. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  8005. bool isFailurePass = false;
  8006. for (int pass = 0; pass < 2; pass++)
  8007. {
  8008. isFailurePass = pass == 1;
  8009. curTypeDef->PopulateMemberSets();
  8010. BfMethodDef* nextMethodDef = NULL;
  8011. BfMemberSetEntry* entry;
  8012. if (curTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  8013. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  8014. while (nextMethodDef != NULL)
  8015. {
  8016. auto checkMethod = nextMethodDef;
  8017. nextMethodDef = nextMethodDef->mNextWithSameName;
  8018. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  8019. continue; // Don't match private default ctor if there's a user-defined one
  8020. if (checkMethod->mIsStatic)
  8021. continue;
  8022. if ((checkMethod->mDeclaringType->IsExtension()) && (mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) &&
  8023. (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoExtensionAttributeTypeDef)))
  8024. {
  8025. mModule->mAttributeState->mUsed = true;
  8026. continue;
  8027. }
  8028. if (!mModule->IsInSpecializedSection())
  8029. {
  8030. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  8031. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, visibleProjectSet)))
  8032. continue;
  8033. }
  8034. auto checkProt = checkMethod->mProtection;
  8035. if (!isFailurePass)
  8036. {
  8037. if (callCtorBodyOnly)
  8038. {
  8039. if (curTypeDef != mModule->mCurTypeInstance->mTypeDef)
  8040. {
  8041. // We're calling the base class's ctor from a derived class
  8042. if (checkProt <= BfProtection_Private)
  8043. continue;
  8044. }
  8045. }
  8046. else
  8047. {
  8048. if ((checkProt == BfProtection_Protected) || (checkProt == BfProtection_ProtectedInternal)) // Treat protected constructors as private
  8049. checkProt = BfProtection_Private;
  8050. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkMethod->mDeclaringType->mProject, checkProt, curTypeInst))
  8051. continue;
  8052. }
  8053. }
  8054. methodMatcher.CheckMethod(NULL, curTypeInst, checkMethod, isFailurePass);
  8055. }
  8056. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  8057. break;
  8058. }
  8059. if (methodMatcher.mBestMethodDef == NULL)
  8060. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8061. if (methodMatcher.mBestMethodDef == NULL)
  8062. {
  8063. mModule->Fail("No constructor available", targetSrc);
  8064. return BfTypedValue();
  8065. }
  8066. auto methodDef = methodMatcher.mBestMethodDef;
  8067. if (mModule->mCompiler->mResolvePassData != NULL)
  8068. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetSrc, curTypeInst->mTypeDef->GetDefinition(), methodDef);
  8069. // There should always be a constructor
  8070. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  8071. //auto moduleMethodInstance = mModule->GetMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher.mBestMethodGenericArguments);
  8072. auto moduleMethodInstance = GetSelectedMethod(methodMatcher);
  8073. if (!moduleMethodInstance)
  8074. return BfTypedValue();
  8075. if (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc))
  8076. return BfTypedValue();
  8077. BfAutoComplete* autoComplete = GetAutoComplete();
  8078. if (autoComplete != NULL)
  8079. {
  8080. BfTypeInstance* resolvedTypeInstance = target.mType->ToTypeInstance();
  8081. auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(methodDef->mMethodDeclaration);
  8082. if ((autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(targetSrc)) && (!BfNodeIsA<BfDelegateBindExpression>(targetSrc)))
  8083. {
  8084. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  8085. (autoComplete->mDefProp == NULL)
  8086. && ((autoComplete->mDefType == NULL) || (autoComplete->mDefType == resolvedTypeInstance->mTypeDef)))
  8087. {
  8088. // Do we need to do this mDefType setting? If we do, then make sure we only get the element type of generics and such
  8089. //autoComplete->mDefType = resolvedTypeInstance->mTypeDef;
  8090. if (ctorDecl != NULL)
  8091. autoComplete->SetDefinitionLocation(ctorDecl->mThisToken, true);
  8092. else if (resolvedTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  8093. autoComplete->SetDefinitionLocation(resolvedTypeInstance->mTypeDef->mTypeDeclaration->mNameNode, true);
  8094. }
  8095. }
  8096. else if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)) &&
  8097. (moduleMethodInstance.mMethodInstance != NULL))
  8098. {
  8099. autoComplete->mResultString = ":";
  8100. autoComplete->mResultString += mModule->MethodToString(moduleMethodInstance.mMethodInstance);
  8101. }
  8102. }
  8103. BfConstructorDeclaration* ctorDecl = (BfConstructorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration;
  8104. if ((methodMatcher.mBestMethodDef->HasAppend()) && (targetType->IsObject()))
  8105. {
  8106. if (allowAppendKind == BfAllowAppendKind_No)
  8107. {
  8108. if (mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration == NULL)
  8109. mModule->Fail("Constructors with append allocations cannot be called from a default constructor. Considering adding an explicit default constructor with the [AllowAppend] specifier.", targetSrc);
  8110. else
  8111. mModule->Fail("Constructors with append allocations cannot be called from a constructor without [AllowAppend] specified.", targetSrc);
  8112. }
  8113. else
  8114. {
  8115. if ((allowAppendKind == BfAllowAppendKind_Yes) && (methodMatcher.mBestMethodDef->mAppendKind == BfAllowAppendKind_ZeroGap))
  8116. {
  8117. BfError* error;
  8118. if (origAllowAppendKind == BfAllowAppendKind_Infer)
  8119. error = mModule->Fail(StrFormat("Cannot call ZeroGap constructor for type '%s' because of fields added from type extensions", mModule->TypeToString(targetType).c_str()), targetSrc);
  8120. else
  8121. error = mModule->Fail(StrFormat("Cannot call ZeroGap constructor for type '%s' from here", mModule->TypeToString(targetType).c_str()), targetSrc);
  8122. if ((error != NULL) && (methodMatcher.mBestMethodDef->mMethodDeclaration != NULL))
  8123. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodMatcher.mBestMethodDef->GetRefNode());
  8124. }
  8125. BfResolvedArg resolvedArg;
  8126. if (appendIndexValue != NULL)
  8127. {
  8128. resolvedArg.mTypedValue = *appendIndexValue;
  8129. }
  8130. else
  8131. {
  8132. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  8133. auto intPtrRefType = mModule->CreateRefType(intPtrType);
  8134. if (target.mValue.IsFake())
  8135. {
  8136. resolvedArg.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), intPtrRefType);
  8137. }
  8138. else
  8139. {
  8140. BFMODULE_FATAL(mModule, "Bad");
  8141. }
  8142. }
  8143. methodMatcher.mArguments.Insert(0, resolvedArg);
  8144. }
  8145. }
  8146. if (methodMatcher.mAutoFlushAmbiguityErrors)
  8147. methodMatcher.FlushAmbiguityError(true);
  8148. if (isFailurePass)
  8149. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  8150. prevBindResult.Restore();
  8151. return CreateCall(methodMatcher.mTargetSrc, target, BfTypedValue(), methodMatcher.mBestMethodDef, moduleMethodInstance, BfCreateCallFlags_None, methodMatcher.mArguments);
  8152. }
  8153. static int sInvocationIdx = 0;
  8154. BfTypedValue BfExprEvaluator::ResolveArgValue(BfResolvedArg& resolvedArg, BfType* wantType, BfTypedValue* receivingValue, BfParamKind paramKind, BfIdentifierNode* paramNameNode)
  8155. {
  8156. BfTypedValue argValue = resolvedArg.mTypedValue;
  8157. if ((resolvedArg.mArgFlags & BfArgFlag_Finalized) != 0)
  8158. return argValue;
  8159. if ((resolvedArg.mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  8160. {
  8161. if ((!argValue) || (argValue.mValue.IsFake()) || (resolvedArg.mWantsRecalc))
  8162. {
  8163. resolvedArg.mWantsRecalc = false;
  8164. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  8165. if (expr != NULL)
  8166. {
  8167. BfExprEvaluator exprEvaluator(mModule);
  8168. exprEvaluator.mReceivingValue = receivingValue;
  8169. BfEvalExprFlags flags = (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr);
  8170. if ((paramKind == BfParamKind_Params) || (paramKind == BfParamKind_DelegateParam))
  8171. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowParamsExpr);
  8172. argValue = mModule->CreateValueFromExpression(exprEvaluator, expr, wantType, flags);
  8173. if ((argValue) && (argValue.mType != wantType) && (wantType != NULL))
  8174. {
  8175. if ((mDeferCallData != NULL) && (wantType == mModule->mContext->mBfObjectType))
  8176. {
  8177. BfAllocTarget allocTarget(mDeferCallData->mScopeAlloc);
  8178. argValue = mModule->BoxValue(expr, argValue, wantType, allocTarget, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  8179. }
  8180. else
  8181. argValue = mModule->Cast(expr, argValue, wantType, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  8182. }
  8183. }
  8184. }
  8185. }
  8186. else if ((resolvedArg.mArgFlags & (BfArgFlag_DeferredValue)) != 0)
  8187. {
  8188. // We should have already had an error on the first call
  8189. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, mModule->mHadBuildError);
  8190. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  8191. BF_ASSERT(expr != NULL);
  8192. argValue = mModule->CreateValueFromExpression(expr, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr));
  8193. resolvedArg.mUncastedTypedValue = argValue;
  8194. if ((argValue) && (wantType != NULL))
  8195. argValue = mModule->Cast(expr, argValue, wantType);
  8196. }
  8197. else if ((resolvedArg.mArgFlags & (BfArgFlag_UntypedDefault)) != 0)
  8198. {
  8199. argValue = mModule->GetDefaultTypedValue(wantType);
  8200. }
  8201. else if ((resolvedArg.mArgFlags & (BfArgFlag_VariableDeclaration | BfArgFlag_UninitializedExpr)) != 0)
  8202. {
  8203. auto variableDeclaration = BfNodeDynCast<BfVariableDeclaration>(resolvedArg.mExpression);
  8204. auto variableType = wantType;
  8205. bool isLet = (variableDeclaration != NULL) && (variableDeclaration->mTypeRef->IsExact<BfLetTypeReference>());
  8206. bool isVar = (variableDeclaration == NULL) || (variableDeclaration->mTypeRef->IsExact<BfVarTypeReference>());
  8207. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  8208. {
  8209. mModule->Fail("Variables cannot be declared in method arguments inside null conditional expressions", variableDeclaration);
  8210. }
  8211. if ((!isLet) && (!isVar))
  8212. {
  8213. if (variableType->IsVar())
  8214. {
  8215. auto resolvedType = mModule->ResolveTypeRef(variableDeclaration->mTypeRef);
  8216. if (resolvedType != NULL)
  8217. variableType = resolvedType;
  8218. }
  8219. else
  8220. {
  8221. mModule->Fail("Only 'ref' or 'var' variables can be declared in method arguments", variableDeclaration);
  8222. auto autoComplete = GetAutoComplete();
  8223. if (autoComplete != NULL)
  8224. autoComplete->CheckTypeRef(variableDeclaration->mTypeRef, true, true);
  8225. }
  8226. }
  8227. else
  8228. {
  8229. if (variableType->IsVar())
  8230. {
  8231. mModule->Fail("Variable type required for 'var' parameter types", variableDeclaration);
  8232. }
  8233. }
  8234. if (wantType->IsRef())
  8235. {
  8236. auto refType = (BfRefType*)wantType;
  8237. variableType = refType->mElementType;
  8238. }
  8239. if ((variableDeclaration != NULL) && (variableDeclaration->mInitializer != NULL))
  8240. {
  8241. mModule->Fail("Initializers cannot be used when declaring variables for 'out' parameters", variableDeclaration->mEqualsNode);
  8242. mModule->CreateValueFromExpression(variableDeclaration->mInitializer, variableType, BfEvalExprFlags_NoCast);
  8243. }
  8244. argValue = mModule->CreateOutVariable(resolvedArg.mExpression, variableDeclaration, paramNameNode, variableType, BfTypedValue());
  8245. }
  8246. return argValue;
  8247. }
  8248. BfTypedValue BfExprEvaluator::CheckEnumCreation(BfAstNode* targetSrc, BfTypeInstance* enumType, const StringImpl& caseName, BfResolvedArgs& argValues)
  8249. {
  8250. auto activeTypeDef = mModule->GetActiveTypeDef();
  8251. mModule->PopulateType(enumType);
  8252. mModule->mBfIRBuilder->PopulateType(enumType);
  8253. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  8254. // if (resolvePassData != NULL)
  8255. // {
  8256. // if (mModule->mParentNodeEntry != NULL)
  8257. // {
  8258. // if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  8259. // {
  8260. // if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  8261. // {
  8262. // BfAstNode* dotNode = memberRefExpr->mDotToken;
  8263. // BfAstNode* nameNode = targetSrc;
  8264. // String filter;
  8265. // auto autoComplete = resolvePassData->mAutoComplete;
  8266. // if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(dotNode, nameNode, filter)))
  8267. // autoComplete->AddEnumTypeMembers(enumType, caseName, false, enumType == mModule->mCurTypeInstance);
  8268. // }
  8269. // }
  8270. // }
  8271. // }
  8272. for (int fieldIdx = 0; fieldIdx < (int)enumType->mFieldInstances.size(); fieldIdx++)
  8273. {
  8274. auto fieldInstance = &enumType->mFieldInstances[fieldIdx];
  8275. auto fieldDef = fieldInstance->GetFieldDef();
  8276. if (fieldDef == NULL)
  8277. continue;
  8278. if ((fieldInstance->mIsEnumPayloadCase) && (fieldDef->mName == caseName))
  8279. {
  8280. if ((!enumType->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, mModule)) ||
  8281. (!enumType->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  8282. continue;
  8283. auto autoComplete = GetAutoComplete();
  8284. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  8285. {
  8286. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  8287. methodMatchEntry.mPayloadEnumField = fieldInstance;
  8288. methodMatchEntry.mTypeInstance = enumType;
  8289. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  8290. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  8291. }
  8292. if (resolvePassData != NULL)
  8293. {
  8294. BfAstNode* nameNode = targetSrc;
  8295. if (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field)
  8296. resolvePassData->HandleFieldReference(nameNode, enumType->mTypeDef, fieldDef);
  8297. }
  8298. BfIRValue enumValue;
  8299. BfTypedValue result;
  8300. bool wantConst = IsConstEval();
  8301. if (wantConst)
  8302. {
  8303. //
  8304. }
  8305. else if ((mReceivingValue != NULL) && (mReceivingValue->mType == enumType) && (mReceivingValue->IsAddr()))
  8306. {
  8307. result = *mReceivingValue;
  8308. mReceivingValue = NULL;
  8309. enumValue = result.mValue;
  8310. }
  8311. else
  8312. {
  8313. mResultIsTempComposite = true;
  8314. enumValue = mModule->CreateAlloca(enumType);
  8315. result = BfTypedValue(enumValue, fieldInstance->mOwner, BfTypedValueKind_TempAddr);
  8316. }
  8317. BF_ASSERT(fieldInstance->mResolvedType->IsTuple());
  8318. auto tupleType = (BfTypeInstance*)fieldInstance->mResolvedType;
  8319. mModule->mBfIRBuilder->PopulateType(tupleType);
  8320. if (tupleType->IsDeleting())
  8321. {
  8322. mModule->FailInternal("Deleted tuple type found in CheckEnumCreation", targetSrc);
  8323. return BfTypedValue();
  8324. }
  8325. bool constFailed = false;
  8326. SizedArray<BfIRValue, 8> constTupleMembers;
  8327. BfIRValue fieldPtr;
  8328. BfIRValue tuplePtr;
  8329. if (wantConst)
  8330. {
  8331. constTupleMembers.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(tupleType->mBaseType)));
  8332. }
  8333. else if (!tupleType->IsValuelessType())
  8334. {
  8335. fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, 1);
  8336. auto tuplePtrType = mModule->CreatePointerType(tupleType);
  8337. auto mappedPtrType = mModule->mBfIRBuilder->MapType(tuplePtrType);
  8338. tuplePtr = mModule->mBfIRBuilder->CreateBitCast(fieldPtr, mappedPtrType);
  8339. }
  8340. for (int tupleFieldIdx = 0; tupleFieldIdx < (int)tupleType->mFieldInstances.size(); tupleFieldIdx++)
  8341. {
  8342. auto tupleFieldInstance = &tupleType->mFieldInstances[tupleFieldIdx];
  8343. auto resolvedFieldType = tupleFieldInstance->GetResolvedType();
  8344. if (tupleFieldIdx >= argValues.mResolvedArgs.size())
  8345. {
  8346. BfAstNode* refNode = targetSrc;
  8347. BfAstNode* prevNode = NULL;
  8348. if (mModule->mParentNodeEntry != NULL)
  8349. {
  8350. if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  8351. {
  8352. if (invokeExpr->mCloseParen != NULL)
  8353. refNode = invokeExpr->mCloseParen;
  8354. }
  8355. }
  8356. BfError* error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", tupleType->mFieldInstances.size() - (int)argValues.mArguments->size()), refNode);
  8357. if (error != NULL)
  8358. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  8359. if (wantConst)
  8360. constFailed = true;
  8361. break;
  8362. }
  8363. BfTypedValue receivingValue;
  8364. BfIRValue tupleFieldPtr;
  8365. mModule->PopulateType(tupleFieldInstance->mResolvedType);
  8366. if (tupleFieldInstance->mResolvedType->IsValuelessType())
  8367. {
  8368. receivingValue = mModule->GetDefaultTypedValue(tupleFieldInstance->mResolvedType);
  8369. }
  8370. else if (tuplePtr)
  8371. {
  8372. tupleFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(tuplePtr, 0, tupleFieldInstance->mDataIdx);
  8373. receivingValue = BfTypedValue(tupleFieldPtr, tupleFieldInstance->mResolvedType, true);
  8374. }
  8375. auto argValue = ResolveArgValue(argValues.mResolvedArgs[tupleFieldIdx], resolvedFieldType, &receivingValue);
  8376. if (!argValue)
  8377. {
  8378. if (wantConst)
  8379. constFailed = true;
  8380. continue;
  8381. }
  8382. if (resolvedFieldType->IsValuelessType())
  8383. continue;
  8384. // Used receiving value?
  8385. if (argValue.mValue == receivingValue.mValue)
  8386. continue;
  8387. argValue = mModule->AggregateSplat(argValue);
  8388. argValues.mResolvedArgs[tupleFieldIdx].mExpectedType = resolvedFieldType;
  8389. if ((argValues.mResolvedArgs[tupleFieldIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt)) != 0)
  8390. {
  8391. auto expr = BfNodeDynCast<BfExpression>(argValues.mResolvedArgs[tupleFieldIdx].mExpression);
  8392. BF_ASSERT(expr != NULL);
  8393. argValue = mModule->CreateValueFromExpression(expr, resolvedFieldType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  8394. }
  8395. if (argValue)
  8396. {
  8397. if ((argValue.mType->IsRef()) && (argValue.mType->GetUnderlyingType() == resolvedFieldType))
  8398. {
  8399. if (auto unaryOperator = BfNodeDynCast<BfUnaryOperatorExpression>(argValues.mResolvedArgs[tupleFieldIdx].mExpression))
  8400. {
  8401. mModule->Fail(StrFormat("Invalid use of '%s'. Enum payloads can only be retrieved through 'case' expressions.", BfGetOpName(unaryOperator->mOp)), unaryOperator->mOpToken);
  8402. argValue = mModule->GetDefaultTypedValue(resolvedFieldType);
  8403. }
  8404. else if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(argValues.mResolvedArgs[tupleFieldIdx].mExpression))
  8405. {
  8406. mModule->Fail("Invalid variable declaration. Enum payloads can only be retrieved through 'case' expressions.", varDecl);
  8407. argValue = mModule->GetDefaultTypedValue(resolvedFieldType);
  8408. }
  8409. }
  8410. // argValue can have a value even if tuplePtr does not have a value. This can happen if we are assigning to a (void) tuple,
  8411. // but we have a value that needs to be attempted to be casted to void
  8412. argValue = mModule->Cast(argValues.mResolvedArgs[tupleFieldIdx].mExpression, argValue, resolvedFieldType, wantConst ? BfCastFlags_WantsConst : BfCastFlags_None);
  8413. if (wantConst)
  8414. {
  8415. if (!argValue.mValue.IsConst())
  8416. {
  8417. mModule->Fail("Field not const", argValues.mResolvedArgs[tupleFieldIdx].mExpression);
  8418. constFailed = true;
  8419. }
  8420. constTupleMembers.Add(argValue.mValue);
  8421. }
  8422. else if (tupleFieldPtr)
  8423. {
  8424. argValue = mModule->LoadValue(argValue);
  8425. if (argValue)
  8426. mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, tupleFieldPtr, resolvedFieldType->mAlign);
  8427. }
  8428. }
  8429. else if (wantConst)
  8430. constFailed = true;
  8431. }
  8432. if ((intptr)argValues.mResolvedArgs.size() > tupleType->mFieldInstances.size())
  8433. {
  8434. BfAstNode* errorRef = argValues.mResolvedArgs[tupleType->mFieldInstances.size()].mExpression;
  8435. if (errorRef == NULL)
  8436. errorRef = targetSrc;
  8437. BfError* error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", argValues.mResolvedArgs.size() - tupleType->mFieldInstances.size()), errorRef);
  8438. if (error != NULL)
  8439. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  8440. if (wantConst)
  8441. constFailed = true;
  8442. }
  8443. auto dscrType = enumType->GetDiscriminatorType();
  8444. auto dscrField = &enumType->mFieldInstances.back();
  8445. int tagIdx = -fieldInstance->mDataIdx - 1;
  8446. if ((wantConst) && (!constFailed))
  8447. {
  8448. auto unionType = enumType->GetUnionInnerType();
  8449. auto constTuple = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(tupleType, BfIRPopulateType_Full), constTupleMembers);
  8450. Array<uint8> memArr;
  8451. memArr.Resize(unionType->mSize);
  8452. if (!mModule->mBfIRBuilder->WriteConstant(constTuple, memArr.mVals, tupleType))
  8453. {
  8454. constFailed = true;
  8455. }
  8456. else
  8457. {
  8458. auto unionValue = mModule->mBfIRBuilder->ReadConstant(memArr.mVals, unionType);
  8459. if (!unionValue)
  8460. {
  8461. constFailed = true;
  8462. }
  8463. else
  8464. {
  8465. SizedArray<BfIRValue, 3> constEnumMembers;
  8466. constEnumMembers.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(enumType->mBaseType, BfIRPopulateType_Full)));
  8467. constEnumMembers.Add(unionValue);
  8468. constEnumMembers.Add(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx));
  8469. return BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(enumType, BfIRPopulateType_Full), constEnumMembers), enumType);
  8470. }
  8471. }
  8472. }
  8473. if (constFailed)
  8474. {
  8475. return mModule->GetDefaultTypedValue(enumType, false, BfDefaultValueKind_Addr);
  8476. }
  8477. auto dscFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, dscrField->mDataIdx);
  8478. mModule->mBfIRBuilder->CreateAlignedStore(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), dscFieldPtr, 4);
  8479. return result;
  8480. }
  8481. }
  8482. return BfTypedValue();
  8483. }
  8484. bool BfExprEvaluator::CheckGenericCtor(BfGenericParamType* genericParamType, BfResolvedArgs& argValues, BfAstNode* targetSrc)
  8485. {
  8486. BfGenericParamFlags genericParamFlags = BfGenericParamFlag_None;
  8487. BfType* typeConstraint = NULL;
  8488. auto genericParam = mModule->GetMergedGenericParamData((BfGenericParamType*)genericParamType, genericParamFlags, typeConstraint);
  8489. bool success = true;
  8490. if ((argValues.mArguments != NULL) && (argValues.mArguments->size() != 0))
  8491. {
  8492. mModule->Fail(StrFormat("Only default parameterless constructors can be called on generic argument '%s'", genericParam->GetGenericParamDef()->mName.c_str()), targetSrc);
  8493. success = false;
  8494. }
  8495. else if ((genericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0)
  8496. {
  8497. mModule->Fail(StrFormat("Must add 'where %s : new, struct' constraint to generic parameter to instantiate type", genericParam->GetGenericParamDef()->mName.c_str()), targetSrc);
  8498. success = false;
  8499. }
  8500. else if ((genericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) == 0)
  8501. {
  8502. mModule->Fail(StrFormat("Must add 'where %s : new' constraint to generic parameter to instantiate type", genericParam->GetGenericParamDef()->mName.c_str()), targetSrc);
  8503. success = false;
  8504. }
  8505. else if ((genericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0)
  8506. {
  8507. mModule->Fail(StrFormat("Must add 'where %s : struct' constraint to generic parameter to instantiate type without allocator", genericParam->GetGenericParamDef()->mName.c_str()), targetSrc);
  8508. success = false;
  8509. }
  8510. else if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  8511. {
  8512. mModule->Fail(StrFormat("Generic parameter '%s' constructor cannot be guaranteed to be const-evaluable", genericParam->GetGenericParamDef()->mName.c_str()), targetSrc);
  8513. }
  8514. return success;
  8515. }
  8516. BfTypedValue BfExprEvaluator::MatchMethod(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, bool allowImplicitThis, bool bypassVirtual, const StringImpl& methodName,
  8517. BfResolvedArgs& argValues, const BfMethodGenericArguments& methodGenericArgs, BfCheckedKind checkedKind)
  8518. {
  8519. BP_ZONE("MatchMethod");
  8520. auto methodGenericArguments = methodGenericArgs.mArguments;
  8521. if (bypassVirtual)
  8522. {
  8523. // "bypassVirtual" means that we know for sure that the target is EXACTLY the specified target type,
  8524. // not derived from (or implementing) the target type. This cannot apply to interfaces.
  8525. BF_ASSERT(!target.mType->IsInterface());
  8526. }
  8527. auto origTarget = target;
  8528. if (mFunctionBindResult != NULL)
  8529. {
  8530. BF_ASSERT(!mFunctionBindResult->mOrigTarget);
  8531. mFunctionBindResult->mOrigTarget = origTarget;
  8532. }
  8533. if (target)
  8534. {
  8535. if (target.mType->IsConcreteInterfaceType())
  8536. target.mType = target.mType->GetUnderlyingType();
  8537. // Turn T* into a T, if we can
  8538. if ((target.mType->IsPointer()) && (target.mType->GetUnderlyingType()->IsGenericParam()))
  8539. {
  8540. auto underlyingType = target.mType->GetUnderlyingType();
  8541. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)underlyingType);
  8542. if (((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsValueType())) ||
  8543. ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Struct)) != 0))
  8544. {
  8545. target.mType = underlyingType;
  8546. }
  8547. }
  8548. if ((!target.mType->IsGenericParam()) &&
  8549. ((!target.IsSplat()) || (target.mType->IsWrappableType())) &&
  8550. (!IsVar(target.mType)))
  8551. target = MakeCallableTarget(targetSrc, target);
  8552. }
  8553. // static int sCallIdx = 0;
  8554. // if (!mModule->mCompiler->mIsResolveOnly)
  8555. // sCallIdx++;
  8556. // int callIdx = sCallIdx;
  8557. // if (callIdx == 118)
  8558. // {
  8559. // NOP;
  8560. // }
  8561. bool prevAllowVariableDeclarations = true;
  8562. if (mModule->mCurMethodState != NULL)
  8563. {
  8564. // Don't allow variable declarations in arguments for this method call
  8565. prevAllowVariableDeclarations = mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations;
  8566. mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations = false;
  8567. }
  8568. defer
  8569. (
  8570. if (mModule->mCurMethodState != NULL)
  8571. mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations = prevAllowVariableDeclarations;
  8572. );
  8573. // Temporarily disable so we don't capture calls in params
  8574. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  8575. sInvocationIdx++;
  8576. bool wantCtor = methodName.IsEmpty();
  8577. BfAutoComplete::MethodMatchInfo* restoreCapturingMethodMatchInfo = NULL;
  8578. auto autoComplete = GetAutoComplete();
  8579. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  8580. {
  8581. if ((!targetSrc->IsFromParser(mModule->mCompiler->mResolvePassData->mParsers[0])) ||
  8582. ((autoComplete->mMethodMatchInfo->mInvocationSrcIdx != -1) && (autoComplete->mMethodMatchInfo->mInvocationSrcIdx != targetSrc->GetSrcStart())))
  8583. {
  8584. autoComplete->mIsCapturingMethodMatchInfo = false;
  8585. restoreCapturingMethodMatchInfo = autoComplete->mMethodMatchInfo;
  8586. }
  8587. }
  8588. defer(
  8589. {
  8590. if ((restoreCapturingMethodMatchInfo != NULL) && (autoComplete->mMethodMatchInfo == restoreCapturingMethodMatchInfo))
  8591. autoComplete->mIsCapturingMethodMatchInfo = true;
  8592. });
  8593. /*if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  8594. autoComplete->mIsCapturingMethodMatchInfo = false;*/
  8595. bool isUnboundCall = false;
  8596. if (target.mType != NULL)
  8597. {
  8598. if (target.mType->IsGenericParam())
  8599. {
  8600. auto genericParamTarget = (BfGenericParamType*) target.mType;
  8601. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  8602. isUnboundCall = (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0;
  8603. if (isUnboundCall)
  8604. {
  8605. if (mModule->mCurMethodInstance->mIsUnspecialized)
  8606. {
  8607. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  8608. target.mType = varType;
  8609. }
  8610. }
  8611. }
  8612. else if (IsVar(target.mType))
  8613. isUnboundCall = true;
  8614. }
  8615. /*if (mPrefixedAttributeState != NULL)
  8616. {
  8617. auto customAttr = mPrefixedAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  8618. if (customAttr != NULL)
  8619. {
  8620. if (!mModule->IsInGeneric())
  8621. {
  8622. mModule->Fail("'Unbound' can only be used within generics");
  8623. }
  8624. mPrefixedAttributeState->mUsed = true;
  8625. isUnboundCall = true;
  8626. }
  8627. }*/
  8628. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  8629. {
  8630. auto customAttr = mModule->mAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  8631. if (customAttr != NULL)
  8632. {
  8633. if (!mModule->IsInGeneric())
  8634. {
  8635. mModule->Fail("'Unbound' can only be used within generics");
  8636. }
  8637. mModule->mAttributeState->mUsed = true;
  8638. isUnboundCall = true;
  8639. }
  8640. }
  8641. if (isUnboundCall)
  8642. {
  8643. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  8644. {
  8645. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  8646. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  8647. {
  8648. if ((argValues.mResolvedArgs[argIdx].mArgFlags & BfArgFlag_DeferredEval) != 0)
  8649. {
  8650. mModule->CreateValueFromExpression((*argValues.mArguments)[argIdx], varType);
  8651. }
  8652. }
  8653. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  8654. }
  8655. }
  8656. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isUnboundCall);
  8657. bool wantsExtensionCheck = target;
  8658. auto targetType = target.mType;
  8659. BfTypeDef* curTypeDef = NULL;
  8660. BfType* selfType = NULL;
  8661. BfTypeInstance* targetTypeInst = NULL;
  8662. bool checkNonStatic = true;
  8663. if (target)
  8664. {
  8665. if (IsVar(targetType))
  8666. return mModule->GetDefaultTypedValue(targetType);
  8667. targetTypeInst = targetType->ToTypeInstance();
  8668. if (targetTypeInst != NULL)
  8669. curTypeDef = targetTypeInst->mTypeDef;
  8670. }
  8671. else if (targetType != NULL) // Static targeted
  8672. {
  8673. if (targetType->IsWrappableType())
  8674. {
  8675. if ((targetType->IsPrimitiveType()) && (methodName.IsEmpty()))
  8676. {
  8677. if (argValues.mArguments->IsEmpty())
  8678. {
  8679. return mModule->GetDefaultTypedValue(targetType);
  8680. }
  8681. else if (argValues.mArguments->mSize == 1)
  8682. {
  8683. FinishDeferredEvals(argValues);
  8684. // This is just a primitive cast
  8685. auto& resolvedArg = argValues.mResolvedArgs[0];
  8686. BfTypedValue castedValue;
  8687. BfTypedValue castTarget = resolvedArg.mTypedValue;
  8688. if (resolvedArg.mTypedValue)
  8689. {
  8690. castTarget = mModule->LoadValue(castTarget);
  8691. castedValue = mModule->Cast(targetSrc, castTarget, targetType, BfCastFlags_Explicit);
  8692. }
  8693. if (!castedValue)
  8694. castedValue = mModule->GetDefaultTypedValue(targetType);
  8695. return castedValue;
  8696. }
  8697. }
  8698. targetTypeInst = mModule->GetWrappedStructType(targetType);
  8699. }
  8700. else if (targetType->IsGenericParam())
  8701. {
  8702. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)targetType);
  8703. if (genericParamInstance->mTypeConstraint != NULL)
  8704. targetTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  8705. if (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var)
  8706. {
  8707. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  8708. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  8709. }
  8710. }
  8711. else
  8712. targetTypeInst = targetType->ToTypeInstance();
  8713. if (targetTypeInst == NULL)
  8714. {
  8715. //mModule->Fail("No static methods available", targetSrc);
  8716. //return BfTypedValue();
  8717. }
  8718. else
  8719. {
  8720. curTypeDef = targetTypeInst->mTypeDef;
  8721. checkNonStatic = false;
  8722. }
  8723. }
  8724. else // Current scopeData
  8725. {
  8726. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef) && (mModule->mCurMethodInstance->mMethodInfoEx->mForeignType->IsInterface()))
  8727. {
  8728. targetTypeInst = mModule->mCurMethodInstance->mMethodInfoEx->mForeignType;
  8729. curTypeDef = targetTypeInst->mTypeDef;
  8730. checkNonStatic = true;
  8731. target = mModule->GetThis();
  8732. selfType = mModule->mCurTypeInstance;
  8733. //target.mType = targetTypeInst;
  8734. }
  8735. else
  8736. {
  8737. curTypeDef = mModule->mCurTypeInstance->mTypeDef;
  8738. targetTypeInst = mModule->mCurTypeInstance;
  8739. if (mModule->mCurMethodState == NULL)
  8740. {
  8741. checkNonStatic = false;
  8742. }
  8743. else
  8744. {
  8745. if (mModule->mCurMethodState->mMixinState != NULL)
  8746. {
  8747. targetTypeInst = mModule->mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  8748. curTypeDef = targetTypeInst->mTypeDef;
  8749. }
  8750. if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  8751. {
  8752. checkNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  8753. }
  8754. else
  8755. checkNonStatic = !mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  8756. }
  8757. }
  8758. }
  8759. bool isIndirectMethodCall = false;
  8760. BfType* lookupType = targetType;
  8761. BfTypeInstance* lookupTypeInst = targetTypeInst;
  8762. if (targetType != NULL)
  8763. {
  8764. lookupType = BindGenericType(targetSrc, targetType);
  8765. if (lookupType->IsGenericParam())
  8766. lookupTypeInst = NULL;
  8767. }
  8768. if ((mModule->mIsReified) && (targetTypeInst != NULL) && (!targetTypeInst->mIsReified) && (!targetTypeInst->mModule->mReifyQueued))
  8769. mModule->PopulateType(targetTypeInst);
  8770. BfMethodDef* methodDef = NULL;
  8771. BfTypeVector checkMethodGenericArguments;
  8772. BfTypeInstance* curTypeInst = targetTypeInst;
  8773. Array<SizedArray<BfUsingFieldData::MemberRef, 1>*> methodUsingLists;
  8774. BfMethodMatcher methodMatcher(targetSrc, mModule, methodName, argValues.mResolvedArgs, methodGenericArgs);
  8775. methodMatcher.mUsingLists = &methodUsingLists;
  8776. methodMatcher.mOrigTarget = origTarget;
  8777. methodMatcher.mTarget = target;
  8778. methodMatcher.mCheckedKind = checkedKind;
  8779. methodMatcher.mAllowImplicitThis = allowImplicitThis;
  8780. methodMatcher.mAllowStatic = !target.mValue;
  8781. methodMatcher.mAllowNonStatic = !methodMatcher.mAllowStatic;
  8782. methodMatcher.mAutoFlushAmbiguityErrors = !wantsExtensionCheck;
  8783. if (allowImplicitThis)
  8784. {
  8785. if (mModule->mCurMethodState == NULL)
  8786. {
  8787. methodMatcher.mAllowStatic = true;
  8788. methodMatcher.mAllowNonStatic = false;
  8789. }
  8790. else if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  8791. {
  8792. methodMatcher.mAllowNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  8793. methodMatcher.mAllowStatic = true;
  8794. }
  8795. else
  8796. {
  8797. if (!mModule->mCurMethodInstance->mMethodDef->mIsStatic)
  8798. methodMatcher.mAllowNonStatic = true;
  8799. methodMatcher.mAllowStatic = true;
  8800. if (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod)
  8801. {
  8802. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  8803. methodMatcher.mAllowNonStatic = !rootMethodState->mMethodInstance->mMethodDef->mIsStatic;
  8804. }
  8805. }
  8806. }
  8807. if (methodName == BF_METHODNAME_CALCAPPEND)
  8808. methodMatcher.mMethodType = BfMethodType_CtorCalcAppend;
  8809. BF_ASSERT(methodMatcher.mBestMethodDef == NULL);
  8810. BfLocalMethod* matchedLocalMethod = NULL;
  8811. if (target.mType == NULL)
  8812. {
  8813. CheckLocalMethods(targetSrc, curTypeInst, methodName, methodMatcher, BfMethodType_Normal);
  8814. if (methodMatcher.mBestMethodDef == NULL)
  8815. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8816. if (methodMatcher.mBestMethodDef != NULL)
  8817. {
  8818. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  8819. auto methodDef = methodMatcher.mBestMethodDef;
  8820. if (mModule->mCompiler->mResolvePassData != NULL)
  8821. {
  8822. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  8823. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, curTypeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, ~methodDef->mIdx);
  8824. auto autoComplete = GetAutoComplete();
  8825. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  8826. {
  8827. autoComplete->SetDefinitionLocation(methodDef->GetRefNode(), true);
  8828. if (autoComplete->mDefType == NULL)
  8829. {
  8830. autoComplete->mDefMethod = mModule->mCurMethodState->GetRootMethodState()->mMethodInstance->mMethodDef;
  8831. autoComplete->mDefType = curTypeDef;
  8832. autoComplete->mReplaceLocalId = ~methodDef->mIdx;
  8833. }
  8834. }
  8835. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  8836. {
  8837. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  8838. methodMatchEntry.mMethodDef = methodDef;
  8839. methodMatchEntry.mTypeInstance = mModule->mCurTypeInstance;
  8840. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  8841. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  8842. }
  8843. }
  8844. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  8845. {
  8846. auto methodInstance = mModule->GetRawMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef);
  8847. if (methodInstance->mReturnType == NULL)
  8848. {
  8849. FinishDeferredEvals(argValues);
  8850. // If we are recursive then we won't even have a completed methodInstance yet to look at
  8851. return mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  8852. }
  8853. }
  8854. }
  8855. }
  8856. if (methodMatcher.mBestMethodDef == NULL)
  8857. {
  8858. if (lookupTypeInst == NULL)
  8859. {
  8860. if ((lookupType != NULL) && (lookupType->IsConcreteInterfaceType()))
  8861. {
  8862. auto concreteInterfaceType = (BfConcreteInterfaceType*)lookupType;
  8863. lookupTypeInst = concreteInterfaceType->mInterface;
  8864. }
  8865. else if (isUnboundCall)
  8866. {
  8867. //auto resolvedType = mModule->ResolveGenericType(lookupType);
  8868. }
  8869. else if (lookupType->IsGenericParam())
  8870. {
  8871. auto genericParamTarget = (BfGenericParamType*)lookupType;
  8872. auto _HandleGenericParamInstance = [&](BfGenericParamInstance* genericParamInstance)
  8873. {
  8874. if (genericParamInstance->mTypeConstraint != NULL)
  8875. lookupTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  8876. else
  8877. lookupTypeInst = mModule->mContext->mBfObjectType;
  8878. for (BfType* ifaceInst : genericParamInstance->mInterfaceConstraints)
  8879. {
  8880. BfTypeInstance* typeInst = ifaceInst->ToTypeInstance();
  8881. BF_ASSERT(typeInst != NULL);
  8882. if (methodMatcher.CheckType(typeInst, target, false))
  8883. methodMatcher.mSelfType = lookupType;
  8884. }
  8885. };
  8886. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget, true);
  8887. _HandleGenericParamInstance(genericParamInstance);
  8888. // Check method generic constraints
  8889. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  8890. {
  8891. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  8892. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  8893. {
  8894. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  8895. if (genericParam->mExternType == lookupType)
  8896. _HandleGenericParamInstance(genericParam);
  8897. }
  8898. }
  8899. }
  8900. }
  8901. if ((lookupTypeInst != NULL) && (!wantCtor))
  8902. {
  8903. methodMatcher.mBypassVirtual = bypassVirtual;
  8904. methodMatcher.CheckType(lookupTypeInst, target, false);
  8905. }
  8906. if ((lookupType != NULL) && (lookupType->IsGenericParam()))
  8907. {
  8908. //lookupType = mModule->ResolveGenericType(lookupType);
  8909. if (!lookupType->IsGenericParam())
  8910. {
  8911. target = MakeCallableTarget(targetSrc, target);
  8912. if (target)
  8913. {
  8914. lookupTypeInst = lookupType->ToTypeInstance();
  8915. }
  8916. }
  8917. }
  8918. }
  8919. bool isFailurePass = false;
  8920. if (methodMatcher.mBestMethodDef == NULL)
  8921. {
  8922. isFailurePass = true;
  8923. if (lookupTypeInst != NULL)
  8924. methodMatcher.CheckType(lookupTypeInst, target, true);
  8925. }
  8926. BfTypedValue staticResult;
  8927. //
  8928. {
  8929. auto devirtTarget = target;
  8930. if ((devirtTarget.mType == NULL) && (selfType != NULL))
  8931. devirtTarget.mType = selfType;
  8932. methodMatcher.TryDevirtualizeCall(devirtTarget, &origTarget, &staticResult);
  8933. }
  8934. if (staticResult)
  8935. return staticResult;
  8936. bypassVirtual |= methodMatcher.mBypassVirtual;
  8937. if (methodMatcher.mBestMethodDef != NULL)
  8938. {
  8939. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  8940. methodDef = methodMatcher.mBestMethodDef;
  8941. }
  8942. if ((methodDef) && (!methodDef->mIsStatic) && (!target) && (allowImplicitThis))
  8943. {
  8944. target = mModule->GetThis();
  8945. }
  8946. if (!methodUsingLists.IsEmpty())
  8947. {
  8948. auto foundList = methodUsingLists[0];
  8949. if (methodUsingLists.mSize > 1)
  8950. {
  8951. BfError* error = mModule->Fail("Ambiguous 'using' method reference", targetSrc);
  8952. if (error != NULL)
  8953. {
  8954. for (auto checkList : methodUsingLists)
  8955. {
  8956. String errorStr = "'";
  8957. for (int entryIdx = 0; entryIdx < checkList->mSize; entryIdx++)
  8958. {
  8959. if (entryIdx == 0)
  8960. errorStr += (*checkList)[entryIdx].GetFullName(mModule);
  8961. else
  8962. {
  8963. errorStr += ".";
  8964. errorStr += (*checkList)[entryIdx].GetName(mModule);
  8965. }
  8966. }
  8967. errorStr += "' is a candidate";
  8968. mModule->mCompiler->mPassInstance->MoreInfo(errorStr, (*checkList)[0].GetRefNode(mModule));
  8969. }
  8970. }
  8971. }
  8972. BfTypedValue curResult = target;
  8973. for (int entryIdx = 0; entryIdx < foundList->mSize; entryIdx++)
  8974. {
  8975. if ((entryIdx == 0) && (foundList->back().IsStatic()))
  8976. entryIdx = (int)foundList->mSize - 1;
  8977. auto& entry = (*foundList)[entryIdx];
  8978. if (mPropDef != NULL)
  8979. {
  8980. SetAndRestoreValue<BfTypedValue> prevResult(mResult, BfTypedValue());
  8981. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_Friend);
  8982. curResult = GetResult();
  8983. if (!curResult)
  8984. break;
  8985. }
  8986. auto useFlags = BfLookupFieldFlag_None;
  8987. if (entryIdx < foundList->mSize - 1)
  8988. useFlags = (BfLookupFieldFlags)(useFlags | BfLookupFieldFlag_IsAnonymous);
  8989. if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Field)
  8990. {
  8991. curResult = LoadField(targetSrc, curResult, entry.mTypeInstance, entry.mTypeInstance->mTypeDef->mFields[entry.mIdx], useFlags);
  8992. }
  8993. else if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Property)
  8994. {
  8995. curResult = LoadProperty(targetSrc, curResult, entry.mTypeInstance, entry.mTypeInstance->mTypeDef->mProperties[entry.mIdx], useFlags, BfCheckedKind_NotSet, false);
  8996. }
  8997. else if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Local)
  8998. {
  8999. auto localDef = mModule->mCurMethodState->mLocals[entry.mIdx];
  9000. curResult = LoadLocal(localDef);
  9001. }
  9002. else if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Local)
  9003. {
  9004. auto checkMethodDef = entry.mTypeInstance->mTypeDef->mMethods[entry.mIdx];
  9005. BF_ASSERT(methodDef == checkMethodDef);
  9006. break;
  9007. }
  9008. if ((!curResult) && (mPropDef == NULL))
  9009. break;
  9010. if (entryIdx == foundList->mSize - 1)
  9011. {
  9012. auto autoComplete = GetAutoComplete();
  9013. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetSrc)))
  9014. autoComplete->SetDefinitionLocation(entry.GetRefNode(mModule));
  9015. if ((autoComplete != NULL) && (autoComplete->CheckFixit(targetSrc)))
  9016. autoComplete->FixitAddFullyQualify(targetSrc, methodName, *foundList);
  9017. }
  9018. }
  9019. if (methodDef->mIsStatic)
  9020. target = BfTypedValue(curTypeInst);
  9021. else if (curResult)
  9022. target = curResult;
  9023. else if ((!methodDef->mIsStatic) && (curTypeInst != NULL))
  9024. target = mModule->GetDefaultTypedValue(curTypeInst);
  9025. }
  9026. // If we call "GetType" on a value type, statically determine the type rather than boxing and then dispatching
  9027. if ((methodDef) && (target) && (curTypeInst == mModule->mContext->mBfObjectType) &&
  9028. (methodDef->mName == "GetType") && (target.mType->IsValueType()) && (argValues.mArguments->IsEmpty()))
  9029. {
  9030. BfType* targetType = target.mType;
  9031. if (origTarget)
  9032. targetType = origTarget.mType;
  9033. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  9034. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  9035. return BfTypedValue(mModule->CreateTypeDataRef(targetType), typeType);
  9036. }
  9037. bool skipThis = false;
  9038. BfTypedValue fieldVal;
  9039. bool hasFieldVal = false;
  9040. // Fail, check for delegate field invocation
  9041. if ((methodDef == NULL) && ((methodGenericArguments == NULL) || (methodGenericArguments->size() == 0)))
  9042. {
  9043. // Check for payload enum initialization first
  9044. BfTypedValue enumResult;
  9045. BfTypeInstance* enumType = NULL;
  9046. if ((!target) && (target.HasType()) && (targetType->IsPayloadEnum()))
  9047. {
  9048. enumType = targetType->ToTypeInstance();
  9049. }
  9050. else if ((!target) && (!target.HasType()) && (mModule->mCurTypeInstance->IsPayloadEnum()))
  9051. {
  9052. enumType = mModule->mCurTypeInstance;
  9053. }
  9054. if (enumType != NULL)
  9055. {
  9056. enumResult = CheckEnumCreation(targetSrc, enumType, methodName, argValues);
  9057. }
  9058. if (enumResult)
  9059. {
  9060. if (mModule->mCompiler->mResolvePassData != NULL)
  9061. {
  9062. if (auto sourceClassifier = mModule->mCompiler->mResolvePassData->GetSourceClassifier(targetSrc))
  9063. {
  9064. sourceClassifier->SetElementType(targetSrc, BfSourceElementType_Normal);
  9065. }
  9066. }
  9067. return enumResult;
  9068. }
  9069. if (allowImplicitThis)
  9070. {
  9071. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  9072. if (identifierNode != NULL)
  9073. fieldVal = LookupIdentifier(identifierNode);
  9074. }
  9075. else
  9076. {
  9077. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags & ~BfEvalExprFlags_AllowEnumId));
  9078. fieldVal = LookupField(targetSrc, target, methodName);
  9079. }
  9080. if (fieldVal)
  9081. {
  9082. hasFieldVal = true;
  9083. wantsExtensionCheck = !fieldVal.mType->IsDelegate() && !fieldVal.mType->IsFunction();
  9084. }
  9085. else if (mPropDef != NULL)
  9086. {
  9087. hasFieldVal = true;
  9088. BfMethodDef* matchedMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  9089. if (matchedMethod != NULL)
  9090. {
  9091. auto getMethodInstance = mModule->GetRawMethodInstance(mPropTarget.mType->ToTypeInstance(), matchedMethod);
  9092. if ((getMethodInstance != NULL) &&
  9093. ((getMethodInstance->mReturnType->IsDelegate()) || (getMethodInstance->mReturnType->IsFunction())))
  9094. wantsExtensionCheck = false;
  9095. }
  9096. }
  9097. }
  9098. if ((!methodDef) && (!target.mValue))
  9099. {
  9100. // Check to see if we're constructing a struct via a call like: "Struct structVal = Struct()"
  9101. int wantNumGenericArgs = 0;
  9102. if ((methodGenericArguments != NULL) && (methodGenericArguments->size() > 0))
  9103. wantNumGenericArgs = (int)methodGenericArguments->size();
  9104. BfTypeInstance* resolvedTypeInstance = NULL;
  9105. BfResolveTypeRefFlags resolveFlags = BfResolveTypeRefFlag_None;
  9106. if (wantCtor)
  9107. {
  9108. resolvedTypeInstance = targetTypeInst;
  9109. }
  9110. else if (targetType != NULL)
  9111. {
  9112. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(methodBoundExpr))
  9113. {
  9114. auto resolvedType = mModule->ResolveTypeRef_Ref(invocationExpr->mTarget, methodGenericArguments, BfPopulateType_Data, resolveFlags);
  9115. if (resolvedType != NULL)
  9116. resolvedTypeInstance = resolvedType->ToTypeInstance();
  9117. }
  9118. }
  9119. else
  9120. {
  9121. BfIdentifierNode* identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  9122. if (identifierNode != NULL)
  9123. {
  9124. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  9125. BfType* refType;
  9126. if (methodGenericArguments != NULL)
  9127. {
  9128. refType = mModule->ResolveTypeRef_Ref(identifierNode, methodGenericArguments, BfPopulateType_Data, resolveFlags);
  9129. }
  9130. else
  9131. refType = mModule->ResolveTypeRef_Ref(identifierNode, NULL, BfPopulateType_Data, resolveFlags);
  9132. prevIgnoreErrors.Restore();
  9133. if ((refType != NULL) && (refType->IsPrimitiveType()))
  9134. {
  9135. for (auto& resolvedArg : argValues.mResolvedArgs)
  9136. resolvedArg.mExpectedType = refType;
  9137. FinishDeferredEvals(argValues);
  9138. if (argValues.mResolvedArgs.IsEmpty())
  9139. return mModule->GetDefaultTypedValue(refType);
  9140. if (argValues.mResolvedArgs.size() != 1)
  9141. {
  9142. mModule->Fail("Cast requires one parameter", targetSrc);
  9143. return BfTypedValue();
  9144. }
  9145. // This is just a primitive cast
  9146. auto& resolvedArg = argValues.mResolvedArgs[0];
  9147. BfTypedValue castedValue;
  9148. BfTypedValue castTarget = resolvedArg.mTypedValue;
  9149. if (resolvedArg.mTypedValue)
  9150. {
  9151. castTarget = mModule->LoadValue(castTarget);
  9152. castedValue = mModule->Cast(targetSrc, castTarget, refType, BfCastFlags_Explicit);
  9153. }
  9154. if (!castedValue)
  9155. castedValue = mModule->GetDefaultTypedValue(refType);
  9156. return castedValue;
  9157. }
  9158. if (refType != NULL)
  9159. {
  9160. resolvedTypeInstance = refType->ToTypeInstance();
  9161. if (refType->IsGenericParam())
  9162. {
  9163. CheckGenericCtor((BfGenericParamType*)refType, argValues, targetSrc);
  9164. return mModule->GetDefaultTypedValue(refType);
  9165. }
  9166. }
  9167. }
  9168. }
  9169. if (resolvedTypeInstance != NULL)
  9170. {
  9171. auto origTypeInstance = resolvedTypeInstance;
  9172. if ((mBfEvalExprFlags & BfEvalExprFlags_AppendFieldInitializer) == 0)
  9173. {
  9174. if ((!resolvedTypeInstance->IsStruct()) && (!resolvedTypeInstance->IsTypedPrimitive()))
  9175. {
  9176. if (mModule->PreFail())
  9177. mModule->Fail("Objects must be allocated through 'new' or 'scope'", targetSrc);
  9178. return BfTypedValue();
  9179. }
  9180. }
  9181. if (auto identifier = BfNodeDynCastExact<BfIdentifierNode>(targetSrc))
  9182. {
  9183. auto elementType = resolvedTypeInstance->IsEnum() ? BfSourceElementType_Type : BfSourceElementType_Struct;
  9184. if (resolvedTypeInstance->IsObject())
  9185. elementType = BfSourceElementType_RefType;
  9186. mModule->SetElementType(identifier, elementType);
  9187. }
  9188. if (mModule->mCompiler->mResolvePassData != NULL)
  9189. {
  9190. if ((!BfNodeIsA<BfMemberReferenceExpression>(targetSrc)) && ((resolveFlags & BfResolveTypeRefFlag_FromIndirectSource) == 0))
  9191. mModule->mCompiler->mResolvePassData->HandleTypeReference(targetSrc, resolvedTypeInstance->mTypeDef);
  9192. }
  9193. BfTypedValue structInst;
  9194. mModule->PopulateType(resolvedTypeInstance);
  9195. if (!resolvedTypeInstance->IsValuelessType())
  9196. {
  9197. if ((mReceivingValue != NULL) && (mReceivingValue->mType == resolvedTypeInstance) && (mReceivingValue->IsAddr()))
  9198. {
  9199. structInst = *mReceivingValue;
  9200. mReceivingValue = NULL;
  9201. }
  9202. else
  9203. {
  9204. auto allocaInst = mModule->CreateAlloca(resolvedTypeInstance);
  9205. structInst = BfTypedValue(allocaInst, resolvedTypeInstance, true);
  9206. }
  9207. mResultIsTempComposite = true;
  9208. }
  9209. else
  9210. {
  9211. structInst = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeInstance, true);
  9212. }
  9213. bool doBind = false;
  9214. mResultLocalVar = NULL;
  9215. mResultFieldInstance = NULL;
  9216. mResultLocalVarRefNode = NULL;
  9217. BfTypedValue result = MatchConstructor(targetSrc, methodBoundExpr, structInst, resolvedTypeInstance, argValues, false, BfMethodGenericArguments(),
  9218. resolvedTypeInstance->IsObject() ? BfAllowAppendKind_Infer : BfAllowAppendKind_No);
  9219. if ((result) && (!result.mType->IsVoid()))
  9220. return result;
  9221. mModule->ValidateAllocation(resolvedTypeInstance, targetSrc);
  9222. mModule->AddDependency(resolvedTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  9223. if (mUsedAsStatement)
  9224. {
  9225. mModule->Warn(0, "Struct constructor being used as a statement", targetSrc);
  9226. }
  9227. return structInst;
  9228. }
  9229. }
  9230. // For for extensions in current type
  9231. if (wantsExtensionCheck)
  9232. {
  9233. auto checkTypeInst = mModule->mCurTypeInstance;
  9234. methodMatcher.mMethodType = BfMethodType_Extension;
  9235. if (methodMatcher.CheckType(checkTypeInst, BfTypedValue(), false, true))
  9236. {
  9237. isFailurePass = false;
  9238. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  9239. methodDef = methodMatcher.mBestMethodDef;
  9240. }
  9241. }
  9242. // Look in globals. Always check for extension methods.
  9243. if ((((methodDef == NULL) && (!target.HasType())) ||
  9244. (wantsExtensionCheck)))
  9245. {
  9246. if (mModule->mContext->mCurTypeState != NULL)
  9247. {
  9248. BfGlobalLookup globalLookup;
  9249. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  9250. globalLookup.mName = methodName;
  9251. mModule->PopulateGlobalContainersList(globalLookup);
  9252. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  9253. {
  9254. if (globalContainer.mTypeInst == NULL)
  9255. continue;
  9256. methodMatcher.mMethodType = wantsExtensionCheck ? BfMethodType_Extension : BfMethodType_Normal;
  9257. if (methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false))
  9258. {
  9259. isFailurePass = false;
  9260. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  9261. methodDef = methodMatcher.mBestMethodDef;
  9262. }
  9263. }
  9264. }
  9265. }
  9266. // Look in static search. Always check for extension methods.
  9267. if ((methodDef == NULL) || (wantsExtensionCheck))
  9268. {
  9269. BfStaticSearch* staticSearch = mModule->GetStaticSearch();
  9270. if (staticSearch != NULL)
  9271. {
  9272. for (auto typeInst : staticSearch->mStaticTypes)
  9273. {
  9274. methodMatcher.mMethodType = wantsExtensionCheck ? BfMethodType_Extension : BfMethodType_Normal;
  9275. if (methodMatcher.CheckType(typeInst, BfTypedValue(), false))
  9276. {
  9277. isFailurePass = false;
  9278. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  9279. methodDef = methodMatcher.mBestMethodDef;
  9280. }
  9281. }
  9282. }
  9283. }
  9284. if ((methodDef == NULL) && (hasFieldVal))
  9285. {
  9286. if (mPropDef != NULL)
  9287. fieldVal = GetResult();
  9288. if (fieldVal)
  9289. {
  9290. if (fieldVal.mType->IsGenericParam())
  9291. {
  9292. bool delegateFailed = true;
  9293. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  9294. BfTypeInstance* typeInstConstraint = NULL;
  9295. if (genericParamInstance->mTypeConstraint != NULL)
  9296. typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  9297. if ((typeInstConstraint != NULL) &&
  9298. ((typeInstConstraint->IsInstanceOf(mModule->mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mModule->mCompiler->mFunctionTypeDef))))
  9299. {
  9300. MarkResultUsed();
  9301. if (argValues.mArguments->size() == 1)
  9302. {
  9303. BfExprEvaluator exprEvaluator(mModule);
  9304. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_AllowParamsExpr;
  9305. auto argExpr = (*argValues.mArguments)[0];
  9306. if (argExpr != NULL)
  9307. exprEvaluator.Evaluate(argExpr);
  9308. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  9309. {
  9310. auto localVar = exprEvaluator.mResultLocalVar;
  9311. auto checkType = localVar->mResolvedType;
  9312. if (checkType->IsParamsType())
  9313. checkType = checkType->GetUnderlyingType();
  9314. if ((localVar->mCompositeCount >= 0) && (checkType == fieldVal.mType))
  9315. {
  9316. delegateFailed = false;
  9317. if (mModule->mCurMethodInstance->mIsUnspecialized)
  9318. {
  9319. auto retTypeType = mModule->CreateModifiedTypeType(fieldVal.mType, BfToken_RetType);
  9320. return mModule->GetFakeTypedValue(retTypeType);
  9321. }
  9322. }
  9323. }
  9324. }
  9325. if (delegateFailed)
  9326. {
  9327. mModule->Fail(StrFormat("Generic delegates can only be invoked with 'params %s' composite parameters", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  9328. return BfTypedValue();
  9329. }
  9330. }
  9331. }
  9332. if (fieldVal.mType->IsTypeInstance())
  9333. {
  9334. prevBindResult.Restore();
  9335. auto fieldTypeInst = fieldVal.mType->ToTypeInstance();
  9336. MarkResultUsed();
  9337. if (mFunctionBindResult != NULL)
  9338. {
  9339. mFunctionBindResult->mOrigTarget = BfTypedValue();
  9340. }
  9341. return MatchMethod(targetSrc, NULL, fieldVal, false, false, "Invoke", argValues, methodGenericArgs, checkedKind);
  9342. }
  9343. if (IsVar(fieldVal.mType))
  9344. {
  9345. FinishDeferredEvals(argValues);
  9346. return BfTypedValue(mModule->GetDefaultValue(fieldVal.mType), fieldVal.mType);
  9347. }
  9348. if (fieldVal.mType->IsGenericParam())
  9349. {
  9350. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  9351. BfType* typeConstraint = genericParam->mTypeConstraint;
  9352. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  9353. {
  9354. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  9355. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  9356. {
  9357. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  9358. if ((genericParam->mExternType == fieldVal.mType) && (genericParam->mTypeConstraint != NULL))
  9359. typeConstraint = genericParam->mTypeConstraint;
  9360. }
  9361. }
  9362. if ((typeConstraint != NULL) &&
  9363. ((typeConstraint->IsDelegate()) || (typeConstraint->IsFunction())))
  9364. {
  9365. BfMethodInstance* invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(typeConstraint->ToTypeInstance(), 0, "Invoke");
  9366. if (invokeMethodInstance == NULL)
  9367. {
  9368. mModule->InternalError("Get Invoke failed", targetSrc);
  9369. return BfTypedValue();
  9370. }
  9371. methodDef = invokeMethodInstance->mMethodDef;
  9372. methodMatcher.mBestMethodInstance = invokeMethodInstance;
  9373. methodMatcher.mBestMethodTypeInstance = invokeMethodInstance->GetOwner();
  9374. methodMatcher.mBestMethodDef = invokeMethodInstance->mMethodDef;
  9375. target = mModule->GetDefaultTypedValue(methodMatcher.mBestMethodTypeInstance);
  9376. isFailurePass = false;
  9377. isIndirectMethodCall = true;
  9378. }
  9379. }
  9380. else if (fieldVal.mType->IsMethodRef())
  9381. {
  9382. auto functionBindResults = prevBindResult.mPrevVal;
  9383. if (functionBindResults != NULL)
  9384. {
  9385. functionBindResults->mOrigTarget = fieldVal;
  9386. }
  9387. origTarget = fieldVal;
  9388. auto methodRefType = (BfMethodRefType*)fieldVal.mType;
  9389. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  9390. methodDef = methodInstance->mMethodDef;
  9391. if (methodDef->mIsLocalMethod)
  9392. {
  9393. methodMatcher.mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodInstance);
  9394. }
  9395. else
  9396. {
  9397. BfTypeVector methodGenericArguments;
  9398. if (methodInstance->mMethodInfoEx != NULL)
  9399. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  9400. methodMatcher.mBestMethodInstance = mModule->GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, methodGenericArguments);
  9401. }
  9402. if (methodInstance->mMethodInfoEx != NULL)
  9403. {
  9404. methodMatcher.mBestMethodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  9405. }
  9406. methodMatcher.mBestMethodTypeInstance = methodInstance->GetOwner();
  9407. if (methodInstance->HasThis())
  9408. {
  9409. bool failed = false;
  9410. target = DoImplicitArgCapture(targetSrc, methodInstance, -1, failed, BfImplicitParamKind_General, origTarget);
  9411. }
  9412. else if (!methodDef->mIsStatic)
  9413. {
  9414. auto thisType = methodInstance->GetParamType(-1);
  9415. BF_ASSERT(thisType->IsValuelessType());
  9416. target = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodMatcher.mBestMethodTypeInstance);
  9417. }
  9418. else
  9419. target = BfTypedValue(methodMatcher.mBestMethodTypeInstance);
  9420. methodMatcher.mBypassVirtual = true;
  9421. bypassVirtual = true;
  9422. isFailurePass = false;
  9423. isIndirectMethodCall = true;
  9424. }
  9425. if (methodDef == NULL)
  9426. {
  9427. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  9428. return BfTypedValue();
  9429. }
  9430. }
  9431. }
  9432. if (methodDef == NULL)
  9433. {
  9434. }
  9435. // This will flush out any new ambiguity errors from extension methods
  9436. methodMatcher.FlushAmbiguityError();
  9437. if (methodDef == NULL)
  9438. {
  9439. FinishDeferredEvals(argValues);
  9440. auto compiler = mModule->mCompiler;
  9441. if ((autoComplete != NULL) && (autoComplete->CheckFixit(targetSrc)))
  9442. {
  9443. mModule->CheckTypeRefFixit(targetSrc);
  9444. bool wantStatic = !target.mValue;
  9445. if ((targetType == NULL) && (allowImplicitThis))
  9446. {
  9447. targetType = mModule->mCurTypeInstance;
  9448. if (mModule->mCurMethodInstance != NULL)
  9449. wantStatic = mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  9450. }
  9451. if (targetType != NULL)
  9452. {
  9453. auto typeInst = targetType->ToTypeInstance();
  9454. if ((typeInst != NULL) && (!methodName.IsEmpty()))
  9455. {
  9456. BfTypeVector paramTypes;
  9457. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  9458. {
  9459. auto& resolvedArg = argValues.mResolvedArgs[argIdx];
  9460. paramTypes.Add(resolvedArg.mTypedValue.mType);
  9461. }
  9462. autoComplete->FixitAddMethod(typeInst, methodName, mExpectingType, paramTypes, wantStatic);
  9463. }
  9464. }
  9465. }
  9466. if (methodName.IsEmpty())
  9467. {
  9468. // Would have caused a parsing error
  9469. }
  9470. else if ((target.mType != NULL) && (origTarget.mType != NULL))
  9471. {
  9472. if (mModule->PreFail())
  9473. {
  9474. if ((origTarget.mType->IsPointer()) && (origTarget.mType->GetUnderlyingType()->IsObjectOrInterface()))
  9475. {
  9476. mModule->Fail(StrFormat("Methods cannot be called on type '%s' because the type is a pointer to a reference type (ie: a double-reference).",
  9477. mModule->TypeToString(origTarget.mType).c_str()), targetSrc);
  9478. }
  9479. else
  9480. mModule->Fail(StrFormat("Method '%s' does not exist in type '%s'", methodName.c_str(), mModule->TypeToString(target.mType).c_str()), targetSrc);
  9481. }
  9482. }
  9483. else
  9484. {
  9485. if (mModule->PreFail())
  9486. mModule->Fail(StrFormat("Method '%s' does not exist", methodName.c_str()), targetSrc);
  9487. }
  9488. return BfTypedValue();
  9489. }
  9490. if ((prevBindResult.mPrevVal != NULL) && (methodMatcher.mMethodCheckCount > 1))
  9491. prevBindResult.mPrevVal->mCheckedMultipleMethods = true;
  9492. BfType* overrideReturnType = NULL;
  9493. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, curTypeInst, methodDef, methodMatcher, &overrideReturnType);
  9494. if ((mModule->mAttributeState != NULL) && ((mModule->mAttributeState->mFlags & (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)) ==
  9495. (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)))
  9496. {
  9497. FinishDeferredEvals(argValues);
  9498. return BfTypedValue();
  9499. }
  9500. if ((moduleMethodInstance.mMethodInstance != NULL) && (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc)))
  9501. {
  9502. FinishDeferredEvals(argValues);
  9503. return BfTypedValue();
  9504. }
  9505. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  9506. {
  9507. if (methodMatcher.mHasVarArguments)
  9508. {
  9509. BfType* retType = mModule->GetPrimitiveType(BfTypeCode_Var);
  9510. if ((!methodMatcher.mHadVarConflictingReturnType) && (methodMatcher.mBestRawMethodInstance != NULL) && (!methodMatcher.mBestRawMethodInstance->mReturnType->IsUnspecializedTypeVariation()) &&
  9511. (prevBindResult.mPrevVal == NULL))
  9512. {
  9513. if ((!methodMatcher.mBestRawMethodInstance->mReturnType->IsGenericParam()) ||
  9514. (((BfGenericParamType*)methodMatcher.mBestRawMethodInstance->mReturnType)->mGenericParamKind != BfGenericParamKind_Method))
  9515. retType = methodMatcher.mBestRawMethodInstance->mReturnType;
  9516. }
  9517. return mModule->GetDefaultTypedValue(retType, true, BfDefaultValueKind_Addr);
  9518. }
  9519. }
  9520. if ((bypassVirtual) && (!target.mValue) && (target.mType->IsInterface()))
  9521. {
  9522. target = mModule->GetThis();
  9523. }
  9524. if (!moduleMethodInstance)
  9525. {
  9526. FinishDeferredEvals(argValues);
  9527. if (mModule->IsInUnspecializedGeneric())
  9528. return mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  9529. return BfTypedValue();
  9530. }
  9531. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  9532. if ((moduleMethodInstance.mMethodInstance->IsOrInUnspecializedVariation()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  9533. {
  9534. // Invalid methods such as types with a HasVar tuple generic arg will be marked as mIsUnspecializedVariation and shouldn't actually be called
  9535. FinishDeferredEvals(argValues);
  9536. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  9537. }
  9538. if (methodDef->IsEmptyPartial())
  9539. {
  9540. // Ignore call
  9541. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  9542. }
  9543. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mIsStatic) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  9544. {
  9545. bool isConstrained = false;
  9546. if (target.mType != NULL)
  9547. isConstrained = target.mType->IsGenericParam();
  9548. if ((target.mType == NULL) && ((mModule->mCurMethodInstance->mIsForeignMethodDef) || (mModule->mCurTypeInstance->IsInterface())))
  9549. isConstrained = true;
  9550. // If mIgnoreWrites is off then we skip devirtualization, so allow this
  9551. if ((target.mType != NULL) && (!target.mType->IsInterface()) && (mModule->mBfIRBuilder->mIgnoreWrites))
  9552. isConstrained = true;
  9553. if (!isConstrained)
  9554. {
  9555. if (mModule->mCurTypeInstance->IsInterface())
  9556. {
  9557. if (methodDef->mBody == NULL)
  9558. mModule->Fail(StrFormat("Interface method '%s' must provide a body to be explicitly invoked", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  9559. }
  9560. else
  9561. mModule->Fail(StrFormat("Static interface method '%s' can only be dispatched from a concrete type, consider using this interface as a generic constraint", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  9562. FinishDeferredEvals(argValues);
  9563. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  9564. }
  9565. }
  9566. // 'base' could really mean 'this' if we're in an extension
  9567. if ((target.IsBase()) && (targetTypeInst == mModule->mCurTypeInstance))
  9568. target.ToThis();
  9569. else
  9570. MakeBaseConcrete(target);
  9571. BfType* callTargetType = curTypeInst;
  9572. if (methodDef->mMethodType == BfMethodType_Extension)
  9573. {
  9574. callTargetType = moduleMethodInstance.mMethodInstance->GetParamType(0);
  9575. if ((callTargetType->IsRef()) && (target.IsAddr()) && (!target.IsReadOnly()) && (target.mType->IsValueType()))
  9576. {
  9577. auto refType = (BfRefType*)callTargetType;
  9578. target = BfTypedValue(target.mValue, mModule->CreateRefType(target.mType, refType->mRefKind));
  9579. }
  9580. }
  9581. BfTypedValue callTarget;
  9582. if (isSkipCall)
  9583. {
  9584. // Just a fake value so we can continue on without generating any code (boxing, conversion, etc)
  9585. if (target)
  9586. {
  9587. if (((target.mType->IsComposite()) || (target.mType->IsTypedPrimitive())))
  9588. {
  9589. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mIsMutating) &&
  9590. ((target.IsReadOnly()) || (!target.IsAddr())))
  9591. {
  9592. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str());
  9593. CheckModifyResult(target, targetSrc, err.c_str());
  9594. }
  9595. }
  9596. callTarget = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), targetTypeInst);
  9597. }
  9598. }
  9599. else if (targetTypeInst == callTargetType)
  9600. {
  9601. if ((target) && (methodDef->HasNoThisSplat()))
  9602. {
  9603. callTarget = mModule->MakeAddressable(target);
  9604. }
  9605. else
  9606. callTarget = target;
  9607. if ((callTarget) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  9608. {
  9609. auto wantThis = moduleMethodInstance.mMethodInstance->GetParamType(-1);
  9610. if ((callTarget.mType != wantThis) && (wantThis->IsInterface()))
  9611. callTarget = mModule->Cast(targetSrc, callTarget, wantThis, BfCastFlags_Explicit);
  9612. }
  9613. }
  9614. else if (target)
  9615. {
  9616. if (methodMatcher.mFakeConcreteTarget)
  9617. {
  9618. BF_ASSERT(callTargetType->IsInterface());
  9619. callTarget = mModule->GetDefaultTypedValue(mModule->CreateConcreteInterfaceType(callTargetType->ToTypeInstance()));
  9620. }
  9621. else if (((target.mType->IsGenericParam()) || (target.mType->IsConcreteInterfaceType())) && (callTargetType->IsInterface()))
  9622. {
  9623. // Leave as generic
  9624. callTarget = target;
  9625. }
  9626. else
  9627. {
  9628. bool handled = false;
  9629. if ((target.mType->IsTypedPrimitive()) && (callTargetType->IsTypedPrimitive()))
  9630. {
  9631. handled = true;
  9632. callTarget = target;
  9633. }
  9634. else if ((target.mType->IsStructOrStructPtr()) || (target.mType->IsTypedPrimitive()))
  9635. {
  9636. //BF_ASSERT(target.IsAddr());
  9637. if (callTargetType->IsObjectOrInterface())
  9638. {
  9639. // Box it
  9640. callTarget = mModule->Cast(targetSrc, target, callTargetType, BfCastFlags_Explicit);
  9641. handled = true;
  9642. }
  9643. else
  9644. {
  9645. //BF_ASSERT(target.IsAddr() || target.IsSplat() || target.mType->IsPointer());
  9646. }
  9647. }
  9648. else
  9649. target = mModule->LoadValue(target);
  9650. if (!handled)
  9651. {
  9652. // Could we have just unconditionally done this?
  9653. callTarget = mModule->Cast(targetSrc, target, callTargetType, BfCastFlags_Explicit);
  9654. }
  9655. }
  9656. }
  9657. if (isFailurePass)
  9658. {
  9659. BfError* error;
  9660. if (methodMatcher.mMatchFailKind == BfMethodMatcher::MatchFailKind_CheckedMismatch)
  9661. error = mModule->Fail(StrFormat("'%s' cannot be used because its 'checked' specifier does not match the requested specifier", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  9662. else
  9663. error = mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  9664. if (error != NULL)
  9665. {
  9666. if ((error != NULL) && (moduleMethodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL))
  9667. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), moduleMethodInstance.mMethodInstance->mMethodDef->GetRefNode());
  9668. }
  9669. }
  9670. if ((mModule->mCompiler->mResolvePassData != NULL) && (methodDef != NULL))
  9671. {
  9672. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  9673. while (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode))
  9674. identifierNode = qualifiedNameNode->mRight;
  9675. if ((identifierNode != NULL) && (methodDef->mIdx >= 0) && (!isIndirectMethodCall) &&
  9676. ((targetTypeInst == NULL) || (!targetTypeInst->IsDelegateOrFunction())))
  9677. {
  9678. auto refMethodInstance = moduleMethodInstance.mMethodInstance;
  9679. if (refMethodInstance->mVirtualTableIdx != -1)
  9680. {
  9681. auto& virtualEntry = refMethodInstance->GetOwner()->mVirtualMethodTable[refMethodInstance->mVirtualTableIdx];
  9682. refMethodInstance = virtualEntry.mDeclaringMethod;
  9683. }
  9684. mModule->mCompiler->mResolvePassData->HandleMethodReference(identifierNode, refMethodInstance->GetOwner()->mTypeDef, refMethodInstance->mMethodDef);
  9685. auto autoComplete = GetAutoComplete();
  9686. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  9687. {
  9688. autoComplete->SetDefinitionLocation(methodDef->GetRefNode(), true);
  9689. int virtualIdx = moduleMethodInstance.mMethodInstance->mVirtualTableIdx;
  9690. if ((autoComplete->mResolveType == BfResolveType_GoToDefinition) &&
  9691. (virtualIdx != -1) && (targetTypeInst != NULL) && (!targetTypeInst->IsStruct()) && (!targetTypeInst->IsTypedPrimitive()) && (!targetTypeInst->IsInterface()) &&
  9692. // VirtualMethodTable can be empty if the non-autocomplete classifier hasn't completed yet. Allow failure, a PopulateType here can't force the method table to fill out
  9693. (targetTypeInst->mVirtualMethodTable.size() != 0))
  9694. {
  9695. auto methodEntry = targetTypeInst->mVirtualMethodTable[virtualIdx];
  9696. if (methodEntry.mImplementingMethod.mMethodNum != -1)
  9697. {
  9698. BfMethodInstance* callingMethodInstance = methodEntry.mImplementingMethod;
  9699. if (callingMethodInstance != NULL)
  9700. {
  9701. auto callingMethodDef = callingMethodInstance->mMethodDef;
  9702. auto callingMethodDeclaration = callingMethodDef->GetMethodDeclaration();
  9703. if ((callingMethodDeclaration != NULL) && (callingMethodDeclaration->mNameNode != NULL))
  9704. autoComplete->SetDefinitionLocation(callingMethodDeclaration->mNameNode, true);
  9705. }
  9706. }
  9707. }
  9708. if (autoComplete->mDefType == NULL)
  9709. {
  9710. autoComplete->mDefMethod = refMethodInstance->mMethodDef;
  9711. autoComplete->mDefType = refMethodInstance->GetOwner()->mTypeDef;
  9712. }
  9713. if (autoComplete->mResolveType == BfResolveType_GetResultString)
  9714. {
  9715. autoComplete->mResultString = ":";
  9716. autoComplete->mResultString += mModule->MethodToString(moduleMethodInstance.mMethodInstance);
  9717. auto methodDecl = moduleMethodInstance.mMethodInstance->mMethodDef->GetMethodDeclaration();
  9718. if ((methodDecl != NULL) && (methodDecl->mDocumentation != NULL))
  9719. {
  9720. autoComplete->mResultString += "\x03";
  9721. methodDecl->mDocumentation->GetDocString(autoComplete->mResultString);
  9722. }
  9723. }
  9724. }
  9725. }
  9726. }
  9727. // This was causing forward-backward-forward steps when we just used 'targetSrc'. Using closeParen is undesirable because most of the time
  9728. // we DO just want it to just go to the targetSrc... do we even need this?
  9729. /*if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(targetSrc->mParent))
  9730. {
  9731. // We set the srcPos to the close paren right before the call so we keep a forward progression of src positions in the case
  9732. // where some of the params are method calls and such
  9733. if (invokeExpr->mCloseParen != NULL)
  9734. mModule->UpdateExprSrcPos(invokeExpr->mCloseParen);
  9735. else
  9736. mModule->UpdateExprSrcPos(targetSrc);
  9737. }
  9738. else
  9739. mModule->UpdateExprSrcPos(targetSrc);*/
  9740. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  9741. {
  9742. //BF_ASSERT(!callTarget.mValue.IsFake());
  9743. }
  9744. prevBindResult.Restore();
  9745. // Check mut
  9746. if ((callTarget.mType != NULL) &&
  9747. (callTarget.mType->IsGenericParam()) &&
  9748. ((!callTarget.IsAddr()) || (callTarget.IsReadOnly())) &&
  9749. (callTarget.mKind != BfTypedValueKind_MutableValue) &&
  9750. (moduleMethodInstance.mMethodInstance->mMethodDef->mIsMutating))
  9751. {
  9752. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)callTarget.mType);
  9753. bool needsMut = true;
  9754. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class | BfGenericParamFlag_Var)) != 0)
  9755. needsMut = false;
  9756. if (genericParamInstance->mTypeConstraint != NULL)
  9757. {
  9758. auto typeConstaintTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  9759. if ((typeConstaintTypeInstance != NULL) && (!typeConstaintTypeInstance->IsComposite()))
  9760. needsMut = false;
  9761. }
  9762. if ((mFunctionBindResult != NULL) && (mFunctionBindResult->mSkipMutCheck))
  9763. needsMut = false;
  9764. if (needsMut)
  9765. {
  9766. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str());
  9767. CheckModifyResult(callTarget, targetSrc, err.c_str(), true);
  9768. }
  9769. }
  9770. // Check mut on interface
  9771. if ((callTarget.mType != NULL) &&
  9772. (callTarget.mType->IsInterface()) &&
  9773. (target.IsThis()) &&
  9774. (mModule->mCurTypeInstance) &&
  9775. (!mModule->mCurMethodInstance->mMethodDef->mIsMutating) &&
  9776. (methodDef->mIsMutating))
  9777. {
  9778. mModule->Fail(StrFormat("Cannot call mutating method '%s' within default interface method '%s'. Consider adding 'mut' specifier to this method.",
  9779. mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), targetSrc);
  9780. }
  9781. BfTypedValue result;
  9782. BfTypedValue argCascade;
  9783. BfCreateCallFlags subCallFlags = BfCreateCallFlags_None;
  9784. if (bypassVirtual)
  9785. subCallFlags = (BfCreateCallFlags)(subCallFlags | BfCreateCallFlags_BypassVirtual);
  9786. if (skipThis)
  9787. subCallFlags = (BfCreateCallFlags)(subCallFlags | BfCreateCallFlags_SkipThis);
  9788. result = CreateCall(targetSrc, callTarget, origTarget, methodDef, moduleMethodInstance, subCallFlags, argValues.mResolvedArgs, &argCascade);
  9789. if (overrideReturnType != NULL)
  9790. {
  9791. BF_ASSERT(moduleMethodInstance.mMethodInstance->mIsUnspecializedVariation);
  9792. result = mModule->GetDefaultTypedValue(overrideReturnType, false, BfDefaultValueKind_Addr);
  9793. }
  9794. if (result)
  9795. {
  9796. if (result.mType->IsRef())
  9797. result = mModule->RemoveRef(result);
  9798. }
  9799. PerformCallChecks(moduleMethodInstance.mMethodInstance, targetSrc);
  9800. if (result)
  9801. {
  9802. bool discardedReturnValue = mUsedAsStatement;
  9803. if (discardedReturnValue)
  9804. {
  9805. auto _ShowDiscardWaring = [&](const String& text, BfCustomAttributes* customAttributes, BfIRConstHolder* constHolder, BfAstNode* refNode)
  9806. {
  9807. if (customAttributes != NULL)
  9808. {
  9809. auto customAttribute = customAttributes->Get(mModule->mCompiler->mNoDiscardAttributeTypeDef);
  9810. if (!customAttribute->mCtorArgs.IsEmpty())
  9811. {
  9812. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  9813. if ((str != NULL) && (!str->IsEmpty()))
  9814. {
  9815. mModule->Warn(0, text + ": " + *str, targetSrc);
  9816. return;
  9817. }
  9818. }
  9819. }
  9820. mModule->Warn(0, text, targetSrc);
  9821. };
  9822. bool showedWarning = false;
  9823. if (moduleMethodInstance.mMethodInstance->mMethodDef->mIsNoDiscard)
  9824. {
  9825. _ShowDiscardWaring("Discarding return value of method with [NoDiscard] attribute", moduleMethodInstance.mMethodInstance->GetCustomAttributes(),
  9826. moduleMethodInstance.mMethodInstance->GetOwner()->mConstHolder, targetSrc);
  9827. showedWarning = true;
  9828. }
  9829. auto typeInst = result.mType->ToTypeInstance();
  9830. if (typeInst != NULL)
  9831. {
  9832. if ((typeInst->mTypeDef->mIsNoDiscard) && (!showedWarning))
  9833. {
  9834. _ShowDiscardWaring("Discarding return value whose type has [NoDiscard] attribute", typeInst->mCustomAttributes, typeInst->mConstHolder, targetSrc);
  9835. }
  9836. BfModuleMethodInstance moduleMethodInstance = mModule->GetMethodByName(typeInst, "ReturnValueDiscarded", 0, true);
  9837. if (moduleMethodInstance)
  9838. {
  9839. bool wasCapturingMethodMatchInfo = false;
  9840. if (autoComplete != NULL)
  9841. {
  9842. wasCapturingMethodMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  9843. autoComplete->mIsCapturingMethodMatchInfo = false;
  9844. }
  9845. defer
  9846. (
  9847. if (autoComplete != NULL)
  9848. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMethodMatchInfo;
  9849. );
  9850. auto wasGetDefinition = (autoComplete != NULL) && (autoComplete->mIsGetDefinition);
  9851. if (wasGetDefinition)
  9852. autoComplete->mIsGetDefinition = false;
  9853. result = mModule->MakeAddressable(result);
  9854. BfResolvedArgs resolvedArgs;
  9855. MatchMethod(targetSrc, NULL, result, false, false, "ReturnValueDiscarded", resolvedArgs, BfMethodGenericArguments());
  9856. if (wasGetDefinition)
  9857. autoComplete->mIsGetDefinition = true;
  9858. }
  9859. }
  9860. }
  9861. }
  9862. if (argCascade)
  9863. {
  9864. if (argCascade.mType->IsRef())
  9865. argCascade = mModule->RemoveRef(argCascade);
  9866. result = argCascade;
  9867. }
  9868. if (result)
  9869. {
  9870. if ((result.mType->IsUnspecializedTypeVariation()) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  9871. {
  9872. BfType* selfType = NULL;
  9873. if (methodMatcher.mSelfType != NULL)
  9874. {
  9875. BF_ASSERT(mModule->IsInGeneric());
  9876. selfType = methodMatcher.mSelfType;
  9877. }
  9878. else
  9879. {
  9880. // Will be an error
  9881. selfType = methodMatcher.mBestMethodTypeInstance;
  9882. }
  9883. if ((selfType != NULL) && (!selfType->IsInterface()))
  9884. {
  9885. auto resolvedType = mModule->ResolveSelfType(result.mType, selfType);
  9886. if ((resolvedType != NULL) && (resolvedType != result.mType))
  9887. result = mModule->GetDefaultTypedValue(resolvedType);
  9888. }
  9889. }
  9890. }
  9891. return result;
  9892. }
  9893. void BfExprEvaluator::LookupQualifiedName(BfQualifiedNameNode* nameNode, bool ignoreInitialError, bool* hadError)
  9894. {
  9895. BfIdentifierNode* nameLeft = nameNode->mLeft;
  9896. BfIdentifierNode* nameRight = nameNode->mRight;
  9897. StringT<64> fieldName;
  9898. if (nameNode->mRight != NULL)
  9899. nameNode->mRight->ToString(fieldName);
  9900. bool wasBaseLookup = false;
  9901. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  9902. {
  9903. if (CheckIsBase(qualifiedLeftName->mRight))
  9904. {
  9905. wasBaseLookup = true;
  9906. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  9907. if (type == NULL)
  9908. return;
  9909. auto fieldName = nameNode->mRight->ToString();
  9910. auto target = mModule->GetThis();
  9911. target.mType = type;
  9912. mResult = LookupField(nameNode->mRight, target, fieldName);
  9913. if ((mPropDef != NULL) && (mPropDef->IsVirtual()))
  9914. mPropDefBypassVirtual = true;
  9915. return;
  9916. }
  9917. }
  9918. if (!wasBaseLookup)
  9919. mResult = LookupIdentifier(nameNode->mLeft, ignoreInitialError, hadError);
  9920. GetResult();
  9921. if (!mResult)
  9922. {
  9923. if (!ignoreInitialError)
  9924. mModule->Fail("Identifier not found", nameNode->mLeft);
  9925. return;
  9926. }
  9927. if (mResult.mType->IsObject())
  9928. {
  9929. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  9930. }
  9931. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  9932. {
  9933. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  9934. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  9935. mResult.mType = structPtrType->mElementType;
  9936. if (mResult.mKind == BfTypedValueKind_ThisValue)
  9937. mResult.mKind = BfTypedValueKind_ThisAddr;
  9938. else
  9939. mResult.mKind = BfTypedValueKind_Addr;
  9940. }
  9941. mIsVolatileReference = false;
  9942. mIsHeapReference = false;
  9943. if (!mResult)
  9944. return;
  9945. auto origResult = mResult;
  9946. auto lookupType = BindGenericType(nameNode, mResult.mType);
  9947. if (IsVar(mResult.mType))
  9948. {
  9949. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType, true);
  9950. return;
  9951. }
  9952. if ((!mResult.mType->IsTypeInstance()) && (!mResult.mType->IsGenericParam()))
  9953. {
  9954. if (hadError != NULL)
  9955. *hadError = true;
  9956. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  9957. mResult = BfTypedValue();
  9958. return;
  9959. }
  9960. BfTypedValue lookupVal = mResult;
  9961. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  9962. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  9963. {
  9964. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType, true);
  9965. SizedArray<BfTypeInstance*, 8> searchConstraints;
  9966. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  9967. {
  9968. if (!searchConstraints.Contains(ifaceConstraint))
  9969. {
  9970. searchConstraints.push_back(ifaceConstraint);
  9971. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  9972. {
  9973. auto innerIFace = innerIFaceEntry.mInterfaceType;
  9974. if (!searchConstraints.Contains(innerIFace))
  9975. {
  9976. searchConstraints.push_back(innerIFace);
  9977. }
  9978. }
  9979. }
  9980. }
  9981. BfTypedValue prevTarget;
  9982. BfPropertyDef* prevDef = NULL;
  9983. for (auto ifaceConstraint : searchConstraints)
  9984. {
  9985. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  9986. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  9987. if (mPropDef != NULL)
  9988. {
  9989. if (prevDef != NULL)
  9990. {
  9991. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  9992. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  9993. if ((isWorse) && (!isBetter))
  9994. continue;
  9995. if (isBetter == isWorse)
  9996. {
  9997. auto error = mModule->Fail("Ambiguous property reference", nameNode->mRight);
  9998. if (error != NULL)
  9999. {
  10000. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  10001. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  10002. }
  10003. }
  10004. }
  10005. prevDef = mPropDef;
  10006. prevTarget = mPropTarget;
  10007. }
  10008. }
  10009. /*if ((mResult) || (mPropDef != NULL))
  10010. break;*/
  10011. }
  10012. if (mPropDef != NULL)
  10013. {
  10014. mOrigPropTarget = origResult;
  10015. if (((CheckIsBase(nameNode->mLeft)) || (wasBaseLookup)) && (mPropDef->IsVirtual()))
  10016. mPropDefBypassVirtual = true;
  10017. }
  10018. if ((mResult) || (mPropDef != NULL))
  10019. return;
  10020. if (hadError != NULL)
  10021. *hadError = true;
  10022. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  10023. auto compiler = mModule->mCompiler;
  10024. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  10025. {
  10026. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), false);
  10027. }
  10028. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(lookupType).c_str()), nameNode->mRight);
  10029. }
  10030. void BfExprEvaluator::LookupQualifiedName(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreInitialError, bool* hadError)
  10031. {
  10032. String fieldName;
  10033. if (nameRight != NULL)
  10034. fieldName = nameRight->ToString();
  10035. bool wasBaseLookup = false;
  10036. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  10037. {
  10038. if (CheckIsBase(qualifiedLeftName->mRight))
  10039. {
  10040. wasBaseLookup = true;
  10041. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  10042. if (type == NULL)
  10043. return;
  10044. auto fieldName = nameRight->ToString();
  10045. auto target = mModule->GetThis();
  10046. target.mType = type;
  10047. mResult = LookupField(nameRight, target, fieldName);
  10048. if ((mPropDef != NULL) && (mPropDef->IsVirtual()))
  10049. mPropDefBypassVirtual = true;
  10050. return;
  10051. }
  10052. }
  10053. if (!wasBaseLookup)
  10054. {
  10055. mResult = LookupIdentifier(nameLeft, ignoreInitialError, hadError);
  10056. if ((mResult) && (!mResult.mType->IsComposite()))
  10057. CheckResultForReading(mResult);
  10058. }
  10059. GetResult();
  10060. if (!mResult)
  10061. {
  10062. if (!ignoreInitialError)
  10063. mModule->Fail("Identifier not found", nameLeft);
  10064. return;
  10065. }
  10066. if (mResult.mType->IsObject())
  10067. {
  10068. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  10069. }
  10070. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  10071. {
  10072. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  10073. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  10074. mResult.mType = structPtrType->mElementType;
  10075. if (mResult.mKind == BfTypedValueKind_ThisValue)
  10076. mResult.mKind = BfTypedValueKind_ThisAddr;
  10077. else
  10078. mResult.mKind = BfTypedValueKind_Addr;
  10079. }
  10080. mIsVolatileReference = false;
  10081. mIsHeapReference = false;
  10082. if (!mResult)
  10083. return;
  10084. if (mResult.mType->IsAllocType())
  10085. mResult.mType = mResult.mType->GetUnderlyingType();
  10086. auto origResult = mResult;
  10087. if (IsVar(mResult.mType))
  10088. {
  10089. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  10090. mResult = BfTypedValue(mModule->GetDefaultValue(varType), varType, true);
  10091. return;
  10092. }
  10093. if ((!mResult.mType->IsTypeInstance()) && (!mResult.mType->IsGenericParam()))
  10094. {
  10095. if (mResult.mType->IsSizedArray())
  10096. {
  10097. if (mResult.mType->IsValuelessType())
  10098. {
  10099. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  10100. mResult.mValue = mModule->mBfIRBuilder->GetFakeVal();
  10101. }
  10102. else
  10103. {
  10104. mResult = mModule->MakeAddressable(mResult);
  10105. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  10106. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  10107. }
  10108. }
  10109. else if (mResult.mType->IsWrappableType())
  10110. {
  10111. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  10112. }
  10113. else
  10114. {
  10115. if (hadError != NULL)
  10116. *hadError = true;
  10117. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  10118. mResult = BfTypedValue();
  10119. return;
  10120. }
  10121. }
  10122. BfTypedValue lookupVal = mResult;
  10123. auto lookupType = BindGenericType(nameNode, mResult.mType);
  10124. if ((lookupType->IsGenericParam()) && (!mResult.mType->IsGenericParam()))
  10125. {
  10126. bool prevUseMixinGenerics = false;
  10127. if (mModule->mCurMethodState->mMixinState != NULL)
  10128. {
  10129. prevUseMixinGenerics = mModule->mCurMethodState->mMixinState->mUseMixinGenerics;
  10130. mModule->mCurMethodState->mMixinState->mUseMixinGenerics = true;
  10131. }
  10132. // Try to lookup from generic binding
  10133. mResult = LookupField(nameRight, BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), lookupType), fieldName, BfLookupFieldFlag_BindOnly);
  10134. if (mModule->mCurMethodState->mMixinState != NULL)
  10135. mModule->mCurMethodState->mMixinState->mUseMixinGenerics = prevUseMixinGenerics;
  10136. if (mPropDef != NULL)
  10137. {
  10138. mOrigPropTarget = lookupVal;
  10139. return;
  10140. }
  10141. }
  10142. if (mPropDef == NULL)
  10143. mResult = LookupField(nameRight, lookupVal, fieldName, CheckIsBase(nameLeft) ? BfLookupFieldFlag_BaseLookup : BfLookupFieldFlag_None);
  10144. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  10145. {
  10146. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType, true);
  10147. SizedArray<BfTypeInstance*, 8> searchConstraints;
  10148. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  10149. {
  10150. if (!searchConstraints.Contains(ifaceConstraint))
  10151. {
  10152. searchConstraints.push_back(ifaceConstraint);
  10153. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  10154. {
  10155. auto innerIFace = innerIFaceEntry.mInterfaceType;
  10156. if (!searchConstraints.Contains(innerIFace))
  10157. {
  10158. searchConstraints.push_back(innerIFace);
  10159. }
  10160. }
  10161. }
  10162. }
  10163. BfTypedValue prevTarget;
  10164. BfPropertyDef* prevDef = NULL;
  10165. for (auto ifaceConstraint : searchConstraints)
  10166. {
  10167. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  10168. mResult = LookupField(nameRight, lookupVal, fieldName);
  10169. if (mPropDef != NULL)
  10170. {
  10171. if (prevDef != NULL)
  10172. {
  10173. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  10174. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  10175. if ((isWorse) && (!isBetter))
  10176. continue;
  10177. if (isBetter == isWorse)
  10178. {
  10179. auto error = mModule->Fail("Ambiguous property reference", nameRight);
  10180. if (error != NULL)
  10181. {
  10182. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  10183. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  10184. }
  10185. }
  10186. }
  10187. prevDef = mPropDef;
  10188. prevTarget = mPropTarget;
  10189. }
  10190. }
  10191. if ((mPropDef == NULL) && (genericParamInst->IsEnum()))
  10192. {
  10193. if ((fieldName == "Underlying") || (fieldName == "UnderlyingRef"))
  10194. {
  10195. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  10196. return;
  10197. }
  10198. }
  10199. }
  10200. if (mPropDef != NULL)
  10201. {
  10202. mOrigPropTarget = origResult;
  10203. if ((CheckIsBase(nameLeft)) || (wasBaseLookup))
  10204. {
  10205. if (mPropDef->IsVirtual())
  10206. mPropDefBypassVirtual = true;
  10207. }
  10208. }
  10209. if ((mResult) || (mPropDef != NULL))
  10210. return;
  10211. if (hadError != NULL)
  10212. *hadError = true;
  10213. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  10214. auto compiler = mModule->mCompiler;
  10215. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  10216. {
  10217. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), false);
  10218. }
  10219. if (((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0) && (typeInst != NULL) && (CheckForMethodName(nameRight, typeInst, fieldName)))
  10220. return;
  10221. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(lookupType).c_str()), nameRight);
  10222. }
  10223. void BfExprEvaluator::LookupQualifiedStaticField(BfQualifiedNameNode* nameNode, bool ignoreIdentifierNotFoundError)
  10224. {
  10225. // Lookup left side as a type
  10226. {
  10227. BfType* type = NULL;
  10228. {
  10229. type = mModule->ResolveTypeRef(nameNode->mLeft, NULL, BfPopulateType_Data, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_IgnoreLookupError));
  10230. mModule->CheckTypeRefFixit(nameNode->mLeft);
  10231. }
  10232. if (type != NULL)
  10233. {
  10234. BfTypedValue lookupType;
  10235. if (type->IsWrappableType())
  10236. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  10237. else
  10238. lookupType = BfTypedValue(type);
  10239. auto findName = nameNode->mRight->ToString();
  10240. /*if (findName == "base")
  10241. {
  10242. mResult = BfTypedValue(lookupType);
  10243. return;
  10244. }*/
  10245. mResult = LookupField(nameNode->mRight, lookupType, findName);
  10246. if ((mResult) || (mPropDef != NULL))
  10247. return;
  10248. if (lookupType.mType != NULL)
  10249. {
  10250. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  10251. auto compiler = mModule->mCompiler;
  10252. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  10253. {
  10254. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), true);
  10255. }
  10256. }
  10257. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  10258. mModule->Fail("Field not found", nameNode->mRight);
  10259. return;
  10260. }
  10261. }
  10262. String fieldName = nameNode->mRight->ToString();
  10263. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  10264. LookupQualifiedStaticField(qualifiedLeftName, true);
  10265. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameNode->mLeft))
  10266. {
  10267. mResult = LookupIdentifier(leftName);
  10268. }
  10269. GetResult();
  10270. if (!mResult)
  10271. {
  10272. if (!ignoreIdentifierNotFoundError)
  10273. mModule->Fail("Identifier not found", nameNode->mLeft);
  10274. return;
  10275. }
  10276. if (mResult.mType->IsObject())
  10277. {
  10278. mResult = mModule->LoadValue(mResult);
  10279. }
  10280. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  10281. {
  10282. BfPointerType* structPtrType = (BfPointerType*) mResult.mType;
  10283. mResult = mModule->LoadValue(mResult);
  10284. mResult.mType = structPtrType->mElementType;
  10285. }
  10286. if (!mResult)
  10287. return;
  10288. if (!mResult.mType->IsTypeInstance())
  10289. {
  10290. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  10291. return;
  10292. }
  10293. auto leftResult = mResult;
  10294. mResult = LookupField(nameNode->mRight, leftResult, fieldName);
  10295. if ((mResult) || (mPropDef != NULL))
  10296. return;
  10297. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(leftResult.mType).c_str()), nameNode->mRight);
  10298. }
  10299. void BfExprEvaluator::LookupQualifiedStaticField(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreIdentifierNotFoundError)
  10300. {
  10301. // Lookup left side as a type
  10302. {
  10303. BfType* type = mModule->ResolveTypeRef(nameLeft, NULL, BfPopulateType_Declaration, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_IgnoreLookupError | BfResolveTypeRefFlag_AllowGlobalContainer));
  10304. if ((type != NULL) && (type->IsVar()) && (nameLeft->Equals("var")))
  10305. type = NULL;
  10306. if (type != NULL)
  10307. {
  10308. BfTypedValue lookupType;
  10309. if (type->IsWrappableType())
  10310. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  10311. else
  10312. lookupType = BfTypedValue(type);
  10313. auto findName = nameRight->ToString();
  10314. if ((lookupType.mType != NULL) && (lookupType.mType->IsGenericParam()))
  10315. {
  10316. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType.mType);
  10317. if (genericParamInstance->mTypeConstraint != NULL)
  10318. {
  10319. mResult = LookupField(nameRight, BfTypedValue(genericParamInstance->mTypeConstraint), findName);
  10320. if ((mResult) || (mPropDef != NULL))
  10321. {
  10322. mOrigPropTarget = lookupType;
  10323. return;
  10324. }
  10325. }
  10326. for (auto constraint : genericParamInstance->mInterfaceConstraints)
  10327. {
  10328. mResult = LookupField(nameRight, BfTypedValue(constraint), findName);
  10329. if ((mResult) || (mPropDef != NULL))
  10330. {
  10331. mOrigPropTarget = lookupType;
  10332. return;
  10333. }
  10334. }
  10335. }
  10336. /*if (findName == "base")
  10337. {
  10338. mResult = BfTypedValue(lookupType);
  10339. return;
  10340. }*/
  10341. mResult = LookupField(nameRight, lookupType, findName);
  10342. if ((mResult) || (mPropDef != NULL))
  10343. return;
  10344. if (lookupType.mType != NULL)
  10345. {
  10346. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  10347. auto compiler = mModule->mCompiler;
  10348. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  10349. {
  10350. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), true);
  10351. }
  10352. }
  10353. if ((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0)
  10354. {
  10355. auto typeInst = lookupType.mType->ToTypeInstance();
  10356. if ((typeInst != NULL) && (CheckForMethodName(nameRight, typeInst, findName)))
  10357. return;
  10358. }
  10359. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  10360. mModule->Fail("Field not found", nameRight);
  10361. return;
  10362. }
  10363. }
  10364. String fieldName = nameRight->ToString();
  10365. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  10366. LookupQualifiedStaticField(qualifiedLeftName, qualifiedLeftName->mLeft, qualifiedLeftName->mRight, true);
  10367. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameLeft))
  10368. {
  10369. mResult = LookupIdentifier(leftName);
  10370. }
  10371. GetResult();
  10372. if (!mResult)
  10373. {
  10374. if (!ignoreIdentifierNotFoundError)
  10375. mModule->Fail("Identifier not found", nameLeft);
  10376. return;
  10377. }
  10378. if (mResult.mType->IsObject())
  10379. {
  10380. mResult = mModule->LoadValue(mResult);
  10381. }
  10382. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  10383. {
  10384. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  10385. mResult = mModule->LoadValue(mResult);
  10386. mResult = BfTypedValue(mResult.mValue, structPtrType->mElementType, true);
  10387. }
  10388. if (!mResult)
  10389. return;
  10390. if (!mResult.mType->IsTypeInstance())
  10391. {
  10392. if (mResult.mType->IsSizedArray())
  10393. {
  10394. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  10395. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  10396. }
  10397. else if (mResult.mType->IsWrappableType())
  10398. {
  10399. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  10400. }
  10401. else
  10402. {
  10403. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  10404. return;
  10405. }
  10406. }
  10407. auto leftResult = mResult;
  10408. mResult = LookupField(nameRight, leftResult, fieldName);
  10409. if ((mResult) || (mPropDef != NULL))
  10410. return;
  10411. mModule->CheckTypeRefFixit(nameLeft);
  10412. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(leftResult.mType).c_str()), nameRight);
  10413. }
  10414. void BfExprEvaluator::Visit(BfQualifiedNameNode* nameNode)
  10415. {
  10416. auto autoComplete = GetAutoComplete();
  10417. if (autoComplete != NULL)
  10418. {
  10419. autoComplete->CheckMemberReference(nameNode->mLeft, nameNode->mDot, nameNode->mRight);
  10420. }
  10421. bool hadError = false;
  10422. LookupQualifiedName(nameNode, nameNode->mLeft, nameNode->mRight, true, &hadError);
  10423. if ((mResult) || (mPropDef != NULL))
  10424. return;
  10425. if (hadError)
  10426. return;
  10427. LookupQualifiedStaticField(nameNode, nameNode->mLeft, nameNode->mRight, false);
  10428. }
  10429. void BfExprEvaluator::Visit(BfThisExpression* thisExpr)
  10430. {
  10431. mResult = mModule->GetThis();
  10432. if (!mResult)
  10433. {
  10434. mModule->Fail("Static methods don't have 'this'", thisExpr);
  10435. return;
  10436. }
  10437. auto autoComplete = GetAutoComplete();
  10438. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(thisExpr)))
  10439. autoComplete->SetDefinitionLocation(mModule->mCurTypeInstance->mTypeDef->GetRefNode());
  10440. mResultLocalVar = mModule->GetThisVariable();
  10441. mResultFieldInstance = NULL;
  10442. }
  10443. void BfExprEvaluator::Visit(BfBaseExpression* baseExpr)
  10444. {
  10445. mResult = mModule->GetThis();
  10446. if (!mResult)
  10447. {
  10448. mModule->Fail("Static methods don't have 'base'", baseExpr);
  10449. return;
  10450. }
  10451. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowBase) == 0)
  10452. mModule->Fail("Use of keyword 'base' is not valid in this context", baseExpr);
  10453. auto baseType = mModule->mCurTypeInstance->mBaseType;
  10454. if (baseType == NULL)
  10455. baseType = mModule->mContext->mBfObjectType;
  10456. auto autoComplete = GetAutoComplete();
  10457. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(baseExpr)))
  10458. autoComplete->SetDefinitionLocation(baseType->mTypeDef->GetRefNode());
  10459. mModule->PopulateType(baseType, BfPopulateType_Data);
  10460. mResult = mModule->Cast(baseExpr, mResult, baseType, BfCastFlags_Explicit);
  10461. if (mResult.IsSplat())
  10462. mResult.mKind = BfTypedValueKind_BaseSplatHead;
  10463. else if (mResult.IsAddr())
  10464. mResult.mKind = BfTypedValueKind_BaseAddr;
  10465. else if (mResult)
  10466. mResult.mKind = BfTypedValueKind_BaseValue;
  10467. }
  10468. void BfExprEvaluator::Visit(BfMixinExpression* mixinExpr)
  10469. {
  10470. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  10471. {
  10472. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  10473. auto newVar = mModule->AllocFromType(varType, mModule->mCurMethodState->mCurScope);
  10474. mResult = BfTypedValue(newVar, varType, true);
  10475. return;
  10476. }
  10477. auto curMethodState = mModule->mCurMethodState;
  10478. if (curMethodState->mMixinState == NULL)
  10479. {
  10480. mModule->Fail("Mixin references can only be used within mixins", mixinExpr);
  10481. return;
  10482. }
  10483. int localIdx = GetMixinVariable();
  10484. if (localIdx != -1)
  10485. {
  10486. auto varDecl = curMethodState->mLocals[localIdx];
  10487. if (varDecl != NULL)
  10488. {
  10489. BfTypedValue localResult = LoadLocal(varDecl);
  10490. mResult = localResult;
  10491. mResultLocalVar = varDecl;
  10492. mResultFieldInstance = NULL;
  10493. mResultLocalVarRefNode = mixinExpr;
  10494. return;
  10495. }
  10496. }
  10497. if (mModule->mCurMethodInstance->mIsUnspecialized)
  10498. {
  10499. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  10500. return;
  10501. }
  10502. mModule->Fail("Mixin value cannot be inferred", mixinExpr);
  10503. }
  10504. void BfExprEvaluator::Visit(BfSizedArrayCreateExpression* createExpr)
  10505. {
  10506. auto type = mModule->ResolveTypeRef(createExpr->mTypeRef, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowInferredSizedArray);
  10507. if (type == NULL)
  10508. return;
  10509. if (type->IsArray())
  10510. {
  10511. // If we have a case like 'int[] (1, 2)' then we infer the sized array size from the initializer
  10512. auto arrayType = (BfArrayType*)type;
  10513. if (arrayType->mDimensions == 1)
  10514. {
  10515. int arraySize = 0;
  10516. if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(createExpr->mInitializer))
  10517. {
  10518. arraySize = (int)arrayInitExpr->mValues.size();
  10519. }
  10520. type = mModule->CreateSizedArrayType(arrayType->GetUnderlyingType(), arraySize);
  10521. }
  10522. }
  10523. if (!type->IsSizedArray())
  10524. {
  10525. mModule->Fail("Sized array expected", createExpr->mTypeRef);
  10526. return;
  10527. }
  10528. if (type->IsUndefSizedArray())
  10529. {
  10530. int arraySize = 0;
  10531. if (createExpr->mInitializer != NULL)
  10532. arraySize = (int)createExpr->mInitializer->mValues.size();
  10533. type = mModule->CreateSizedArrayType(type->GetUnderlyingType(), arraySize);
  10534. }
  10535. BfSizedArrayType* arrayType = (BfSizedArrayType*)type;
  10536. if (createExpr->mInitializer == NULL)
  10537. {
  10538. mModule->AssertErrorState();
  10539. mResult = mModule->GetDefaultTypedValue(arrayType);
  10540. return;
  10541. }
  10542. InitializedSizedArray(arrayType, createExpr->mInitializer->mOpenBrace, createExpr->mInitializer->mValues, createExpr->mInitializer->mCommas, createExpr->mInitializer->mCloseBrace);
  10543. }
  10544. void BfExprEvaluator::Visit(BfInitializerExpression* initExpr)
  10545. {
  10546. uint64 unassignedFieldFlags = 0;
  10547. if (auto typeRef = BfNodeDynCast<BfTypeReference>(initExpr->mTarget))
  10548. {
  10549. BfType* type = NULL;
  10550. if (auto typeRef = BfNodeDynCast<BfDotTypeReference>(initExpr->mTarget))
  10551. {
  10552. type = mExpectingType;
  10553. }
  10554. if (type == NULL)
  10555. type = mModule->ResolveTypeRef(typeRef);
  10556. if (type != NULL)
  10557. {
  10558. if (type->IsValueType())
  10559. {
  10560. if ((mReceivingValue != NULL) && (mReceivingValue->mType == type) && (mReceivingValue->IsAddr()))
  10561. {
  10562. mResult = *mReceivingValue;
  10563. mReceivingValue = NULL;
  10564. }
  10565. else
  10566. {
  10567. mResult = BfTypedValue(mModule->CreateAlloca(type), type, true);
  10568. }
  10569. auto typeInstance = type->ToTypeInstance();
  10570. if (typeInstance != NULL)
  10571. unassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  10572. }
  10573. else
  10574. {
  10575. mModule->Fail("Initializer expressions can only be used on value types or allocated values", initExpr->mTarget);
  10576. }
  10577. }
  10578. }
  10579. else if (auto objCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(initExpr->mTarget))
  10580. {
  10581. CreateObject(objCreateExpr, objCreateExpr->mNewNode, NULL, initExpr->mInlineTypeRef);
  10582. }
  10583. else
  10584. VisitChild(initExpr->mTarget);
  10585. if (!mResult)
  10586. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  10587. BfIRBlock initBlock = BfIRBlock();
  10588. if (unassignedFieldFlags != 0)
  10589. {
  10590. initBlock = mModule->mBfIRBuilder->CreateBlock("initStart", true);
  10591. mModule->mBfIRBuilder->CreateBr(initBlock);
  10592. mModule->mBfIRBuilder->SetInsertPoint(initBlock);
  10593. }
  10594. BfTypedValue origInitValue = GetResult(true);
  10595. BfTypedValue initValue = origInitValue;
  10596. if ((initValue) && (initValue.mType->IsRef()))
  10597. initValue = mModule->RemoveRef(initValue, false);
  10598. bool isFirstAdd = true;
  10599. SetAndRestoreValue<BfTypeInstance*> prevPrivateTypeInstance(mModule->mCurMethodState->mPrivateTypeInstance);
  10600. BfScopeData newScope;
  10601. if (initExpr->mInlineTypeRef != NULL)
  10602. mModule->mCurMethodState->mPrivateTypeInstance = initValue.mType->ToTypeInstance();
  10603. newScope.mAllowTargeting = false;
  10604. newScope.mInnerIsConditional = true;
  10605. newScope.mCloseNode = initExpr->mCloseBrace;
  10606. mModule->mCurMethodState->AddScope(&newScope);
  10607. mModule->NewScopeState();
  10608. BfLocalVariable* localDef = new BfLocalVariable();
  10609. localDef->mName = "_";
  10610. localDef->mResolvedType = initValue.mType;
  10611. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  10612. if (initValue.IsAddr())
  10613. {
  10614. localDef->mAddr = initValue.mValue;
  10615. }
  10616. else
  10617. {
  10618. localDef->mValue = initValue.mValue;
  10619. localDef->mIsSplat = initValue.IsSplat();
  10620. }
  10621. if (!localDef->mResolvedType->IsVar())
  10622. mModule->AddLocalVariableDef(localDef, true, true);
  10623. auto autoComplete = mModule->mCompiler->GetAutoComplete();
  10624. for (auto elementExpr : initExpr->mValues)
  10625. {
  10626. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  10627. {
  10628. mModule->Fail("Comptime cannot evaluate initializer expressions", elementExpr);
  10629. break;
  10630. }
  10631. bool wasValidInitKind = false;
  10632. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(elementExpr))
  10633. {
  10634. BfTypedValue fieldResult;
  10635. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(assignExpr->mLeft))
  10636. {
  10637. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  10638. {
  10639. auto type = initValue.mType;
  10640. if (type->IsPointer())
  10641. type = type->GetUnderlyingType();
  10642. if (auto typeInst = type->ToTypeInstance())
  10643. {
  10644. autoComplete->mInsertStartIdx = identifierNode->GetSrcStart();
  10645. autoComplete->mInsertEndIdx = identifierNode->GetSrcEnd();
  10646. autoComplete->AddTypeMembers(typeInst, false, true, identifierNode->ToString(), typeInst, false, true, false);
  10647. }
  10648. }
  10649. StringT<128> findName;
  10650. identifierNode->ToString(findName);
  10651. mResultFieldInstance = NULL;
  10652. fieldResult = LookupField(identifierNode, initValue, findName, BfLookupFieldFlag_IsImplicitThis);
  10653. if ((fieldResult.mKind == BfTypedValueKind_TempAddr) || (fieldResult.mKind == BfTypedValueKind_RestrictedTempAddr))
  10654. fieldResult.mKind = BfTypedValueKind_Addr;
  10655. if ((mResultFieldInstance != NULL) && (mResultFieldInstance->mMergedDataIdx != -1))
  10656. {
  10657. int resultLocalVarField = 0;
  10658. int resultLocalVarFieldCount = 0;
  10659. mResultFieldInstance->GetDataRange(resultLocalVarField, resultLocalVarFieldCount);
  10660. for (int i = 0; i < resultLocalVarFieldCount; i++)
  10661. unassignedFieldFlags &= ~((int64)1 << (resultLocalVarField - 1 + i));
  10662. }
  10663. wasValidInitKind = true;
  10664. if ((fieldResult) || (mPropDef != NULL))
  10665. {
  10666. if (mResultFieldInstance != NULL)
  10667. {
  10668. auto autoComplete = GetAutoComplete();
  10669. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  10670. {
  10671. auto fieldDef = mResultFieldInstance->GetFieldDef();
  10672. if (fieldDef != NULL)
  10673. autoComplete->SetDefinitionLocation(fieldDef->GetRefNode());
  10674. }
  10675. }
  10676. mResult = fieldResult;
  10677. PerformAssignment(assignExpr, true, BfTypedValue());
  10678. mResult = BfTypedValue();
  10679. }
  10680. else
  10681. {
  10682. mModule->Fail(StrFormat("'%s' does not contain a definition for '%s'", mModule->TypeToString(initValue.mType).c_str(),
  10683. findName.c_str()), identifierNode);
  10684. }
  10685. }
  10686. else if (auto indexerExpression = BfNodeDynCast<BfIndexerExpression>(assignExpr->mLeft))
  10687. {
  10688. if (indexerExpression->mTarget == NULL)
  10689. {
  10690. if ((initValue.mType->IsValueType()) && (!initValue.IsAddr()))
  10691. {
  10692. initValue = mModule->MakeAddressable(initValue, true, true);
  10693. }
  10694. mResult = BfTypedValue();
  10695. HandleIndexerExpression(indexerExpression, initValue);
  10696. wasValidInitKind = true;
  10697. if ((mPropDef) || (mResult))
  10698. {
  10699. PerformAssignment(assignExpr, true, BfTypedValue());
  10700. mResult = BfTypedValue();
  10701. }
  10702. }
  10703. }
  10704. }
  10705. else
  10706. {
  10707. BfBlock* block = BfNodeDynCast<BfBlock>(elementExpr);
  10708. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(elementExpr)))
  10709. {
  10710. if (auto identiferNode = BfNodeDynCast<BfIdentifierNode>(elementExpr))
  10711. {
  10712. auto type = initValue.mType;
  10713. if (type->IsPointer())
  10714. type = type->GetUnderlyingType();
  10715. if (auto typeInst = type->ToTypeInstance())
  10716. {
  10717. String filter;
  10718. identiferNode->ToString(filter);
  10719. autoComplete->AddTypeMembers(typeInst, false, true, filter, typeInst, false, true, false);
  10720. }
  10721. }
  10722. }
  10723. if ((block != NULL) && (!block->IsExpression()))
  10724. {
  10725. mModule->VisitCodeBlock(block);
  10726. }
  10727. else
  10728. {
  10729. BfExprEvaluator exprEvaluator(mModule);
  10730. SizedArray<BfExpression*, 2> argExprs;
  10731. argExprs.push_back(elementExpr);
  10732. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  10733. BfResolvedArgs argValues(&sizedArgExprs);
  10734. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  10735. exprEvaluator.MatchMethod(elementExpr, NULL, initValue, false, false, "Add", argValues, BfMethodGenericArguments());
  10736. }
  10737. wasValidInitKind = true;
  10738. }
  10739. if (!wasValidInitKind)
  10740. {
  10741. mModule->Fail("Invalid initializer member declarator", initExpr);
  10742. }
  10743. }
  10744. mModule->RestoreScopeState();
  10745. if (initExpr->mValues.IsEmpty())
  10746. {
  10747. // When we are first typing out 'override', we
  10748. if (initExpr->mInlineTypeRef != NULL)
  10749. {
  10750. if (auto defineBlock = BfNodeDynCast<BfBlock>(initExpr->mInlineTypeRef->mTypeDeclaration->mDefineNode))
  10751. {
  10752. if (defineBlock->mChildArr.mSize == 1)
  10753. {
  10754. auto lastNode = defineBlock->mChildArr[0];
  10755. if (lastNode->Equals("override"))
  10756. {
  10757. auto autoComplete = mModule->mCompiler->GetAutoComplete();
  10758. if (autoComplete != NULL)
  10759. {
  10760. int cursorIdx = autoComplete->GetCursorIdx(lastNode);
  10761. if ((autoComplete->IsAutocompleteNode(lastNode, 1)) && (cursorIdx == lastNode->GetSrcEnd()))
  10762. {
  10763. auto typeInst = initValue.mType->ToTypeInstance();
  10764. if (typeInst != NULL)
  10765. {
  10766. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mModule->mCurTypeInstance, typeInst);
  10767. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mModule->mCurMethodInstance, NULL);
  10768. autoComplete->AddOverrides("", true);
  10769. autoComplete->mInsertStartIdx = lastNode->mSrcStart;
  10770. autoComplete->mInsertEndIdx = lastNode->mSrcEnd;
  10771. }
  10772. }
  10773. }
  10774. }
  10775. }
  10776. }
  10777. }
  10778. }
  10779. else
  10780. {
  10781. auto lastNode = initExpr->mValues.back();
  10782. if (auto lastIdentifier = BfNodeDynCast<BfIdentifierNode>(lastNode))
  10783. {
  10784. auto autoComplete = mModule->mCompiler->GetAutoComplete();
  10785. if (autoComplete != NULL)
  10786. {
  10787. autoComplete->CheckIdentifier(lastIdentifier, false, false);
  10788. }
  10789. }
  10790. }
  10791. if (unassignedFieldFlags != 0)
  10792. {
  10793. auto curBlock = mModule->mBfIRBuilder->GetInsertBlock();
  10794. mModule->mBfIRBuilder->SetInsertPointAtStart(initBlock);
  10795. mModule->mBfIRBuilder->CreateMemSet(initValue.mValue, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  10796. mModule->GetConstValue(initValue.mType->mSize), initValue.mType->mAlign);
  10797. mModule->mBfIRBuilder->SetInsertPoint(curBlock);
  10798. }
  10799. mResult = origInitValue;
  10800. }
  10801. void BfExprEvaluator::Visit(BfCollectionInitializerExpression* arrayInitExpr)
  10802. {
  10803. mModule->Fail("Collection initializer not usable here", arrayInitExpr);
  10804. }
  10805. void BfExprEvaluator::Visit(BfTypeOfExpression* typeOfExpr)
  10806. {
  10807. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  10808. auto autoComplete = GetAutoComplete();
  10809. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  10810. {
  10811. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  10812. }
  10813. BfType* type;
  10814. if ((typeOfExpr->mTypeRef != NULL) && (typeOfExpr->mTypeRef->IsA<BfVarTypeReference>()))
  10815. {
  10816. type = mModule->GetPrimitiveType(BfTypeCode_Var);
  10817. }
  10818. else
  10819. {
  10820. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_AllowGlobalsSelf | BfResolveTypeRefFlag_AllowUnboundGeneric));
  10821. }
  10822. if (type == NULL)
  10823. {
  10824. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  10825. return;
  10826. }
  10827. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10828. mResult = BfTypedValue(mModule->CreateTypeDataRef(type), typeType);
  10829. }
  10830. bool BfExprEvaluator::LookupTypeProp(BfTypeOfExpression* typeOfExpr, BfIdentifierNode* propName)
  10831. {
  10832. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  10833. BfType* type;
  10834. //
  10835. {
  10836. // We ignore errors because we go through the normal Visit(BfTypeOfExpression) if this fails, which will throw the error again
  10837. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  10838. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeOfExpr->mTypeRef))
  10839. {
  10840. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  10841. type = mModule->ResolveTypeRefAllowUnboundGenerics(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  10842. }
  10843. else
  10844. {
  10845. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_IgnoreLookupError);
  10846. }
  10847. }
  10848. if (type == NULL)
  10849. {
  10850. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  10851. return false;
  10852. }
  10853. bool success = true;
  10854. defer(
  10855. {
  10856. if (success)
  10857. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_TypeSignature);
  10858. });
  10859. // We want to try to avoid triggering OnTypeInit for basic info
  10860. mModule->PopulateType(type, BfPopulateType_Interfaces_Direct);
  10861. auto typeInstance = type->ToTypeInstance();
  10862. auto _BoolResult = [&](bool val)
  10863. {
  10864. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, val ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  10865. };
  10866. auto _Int32Result = [&](int32 val)
  10867. {
  10868. mResult = BfTypedValue(mModule->GetConstValue32(val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  10869. };
  10870. String memberName;
  10871. propName->ToString(memberName);
  10872. bool handled = true;
  10873. if (memberName == "IsTypedPrimitive")
  10874. _BoolResult(type->IsPrimitiveType());
  10875. else if (memberName == "IsObject")
  10876. _BoolResult(type->IsObject());
  10877. else if (memberName == "IsValueType")
  10878. _BoolResult(type->IsValueType());
  10879. else if (memberName == "IsPrimitive")
  10880. _BoolResult(type->IsPrimitiveType());
  10881. else if (memberName == "IsInteger")
  10882. _BoolResult(type->IsInteger());
  10883. else if (memberName == "IsIntegral")
  10884. _BoolResult(type->IsIntegral());
  10885. else if (memberName == "IsSigned")
  10886. _BoolResult(type->IsSigned());
  10887. else if (memberName == "IsFloatingPoint")
  10888. _BoolResult(type->IsFloat());
  10889. else if (memberName == "IsPointer")
  10890. _BoolResult(type->IsPointer());
  10891. else if (memberName == "IsStruct")
  10892. _BoolResult(type->IsStruct());
  10893. else if (memberName == "IsSplattable")
  10894. _BoolResult(type->IsSplattable());
  10895. else if (memberName == "IsUnion")
  10896. _BoolResult(type->IsUnion());
  10897. else if (memberName == "IsBoxed")
  10898. _BoolResult(type->IsBoxed());
  10899. else if (memberName == "IsEnum")
  10900. _BoolResult(type->IsEnum());
  10901. else if (memberName == "IsTuple")
  10902. _BoolResult(type->IsTuple());
  10903. else if (memberName == "IsNullable")
  10904. _BoolResult(type->IsNullable());
  10905. else if (memberName == "IsGenericType")
  10906. _BoolResult(type->IsGenericTypeInstance());
  10907. else if (memberName == "IsGenericParam")
  10908. _BoolResult(type->IsGenericParam());
  10909. else if (memberName == "IsArray")
  10910. _BoolResult(type->IsArray());
  10911. else if (memberName == "IsSizedArray")
  10912. _BoolResult(type->IsSizedArray());
  10913. else if (memberName == "TypeId")
  10914. {
  10915. _Int32Result(type->mTypeId);
  10916. mResult.mType = mModule->ResolveTypeDef(mModule->mCompiler->mReflectTypeIdTypeDef);
  10917. }
  10918. else if (memberName == "GenericParamCount")
  10919. {
  10920. auto genericTypeInst = type->ToGenericTypeInstance();
  10921. _Int32Result((genericTypeInst != NULL) ? (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size() : 0);
  10922. }
  10923. else
  10924. {
  10925. // We need full data
  10926. mModule->PopulateType(type, BfPopulateType_Data);
  10927. if (memberName == "Size")
  10928. _Int32Result(type->mSize);
  10929. else if (memberName == "Align")
  10930. _Int32Result(type->mAlign);
  10931. else if (memberName == "Stride")
  10932. _Int32Result(type->GetStride());
  10933. else if (memberName == "InstanceSize")
  10934. _Int32Result((typeInstance != NULL) ? typeInstance->mInstSize : type->mSize);
  10935. else if (memberName == "InstanceAlign")
  10936. _Int32Result((typeInstance != NULL) ? typeInstance->mInstAlign : type->mSize);
  10937. else if (memberName == "InstanceStride")
  10938. _Int32Result((typeInstance != NULL) ? typeInstance->GetInstStride() : type->GetStride());
  10939. else if (memberName == "UnderlyingType")
  10940. {
  10941. bool handled = false;
  10942. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  10943. if (type->IsGenericParam())
  10944. {
  10945. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)type);
  10946. if (genericParamInstance->IsEnum())
  10947. {
  10948. handled = true;
  10949. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(typeType)), typeType);
  10950. }
  10951. }
  10952. else if (type->IsEnum())
  10953. {
  10954. if (type->IsDataIncomplete())
  10955. mModule->PopulateType(type);
  10956. auto underlyingType = type->GetUnderlyingType();
  10957. if (underlyingType != NULL)
  10958. {
  10959. handled = true;
  10960. mModule->AddDependency(underlyingType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10961. mResult = BfTypedValue(mModule->CreateTypeDataRef(underlyingType), typeType);
  10962. }
  10963. }
  10964. if (!handled)
  10965. mResult = BfTypedValue(mModule->CreateTypeDataRef(mModule->GetPrimitiveType(BfTypeCode_None)), typeType);
  10966. }
  10967. else if (memberName == "BitSize")
  10968. {
  10969. auto int32Type = mModule->GetPrimitiveType(BfTypeCode_Int32);
  10970. BfType* checkType = type;
  10971. if (checkType->IsTypedPrimitive())
  10972. checkType = checkType->GetUnderlyingType();
  10973. if (checkType->IsGenericParam())
  10974. {
  10975. mResult = mModule->GetDefaultTypedValue(int32Type, false, Beefy::BfDefaultValueKind_Undef);
  10976. return true;
  10977. }
  10978. if ((typeInstance != NULL) && (typeInstance->IsEnum()))
  10979. {
  10980. if (typeInstance->mTypeInfoEx != NULL)
  10981. {
  10982. int64 minValue = typeInstance->mTypeInfoEx->mMinValue;
  10983. if (minValue < 0)
  10984. minValue = ~minValue;
  10985. int64 maxValue = typeInstance->mTypeInfoEx->mMaxValue;
  10986. if (maxValue < 0)
  10987. maxValue = ~maxValue;
  10988. uint64 value = (uint64)minValue | (uint64)maxValue;
  10989. int bitCount = 1;
  10990. if (typeInstance->mTypeInfoEx->mMinValue < 0)
  10991. bitCount++;
  10992. while (value >>= 1)
  10993. bitCount++;
  10994. mModule->AddDependency(typeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  10995. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, bitCount), int32Type);
  10996. return true;
  10997. }
  10998. }
  10999. int bitSize = checkType->mSize * 8;
  11000. if (checkType->GetTypeCode() == BfTypeCode_Boolean)
  11001. bitSize = 1;
  11002. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, bitSize), int32Type);
  11003. return true;
  11004. }
  11005. else if ((memberName == "MinValue") || (memberName == "MaxValue"))
  11006. {
  11007. bool isMin = memberName == "MinValue";
  11008. bool isBitSize = memberName == "BitSize";
  11009. BfType* checkType = type;
  11010. if (checkType->IsTypedPrimitive())
  11011. checkType = checkType->GetUnderlyingType();
  11012. if (checkType->IsGenericParam())
  11013. {
  11014. bool foundMatch = false;
  11015. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)checkType);
  11016. if (((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Enum) != 0) ||
  11017. ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsInstanceOf(mModule->mCompiler->mEnumTypeDef))))
  11018. foundMatch = true;
  11019. else
  11020. {
  11021. for (auto constraint : genericParamInstance->mInterfaceConstraints)
  11022. {
  11023. if (constraint->IsInstanceOf(mModule->mCompiler->mIIntegerTypeDef))
  11024. foundMatch = true;
  11025. }
  11026. }
  11027. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  11028. {
  11029. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  11030. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  11031. {
  11032. genericParamInstance = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  11033. if (genericParamInstance->mExternType == type)
  11034. {
  11035. if (((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Enum) != 0) ||
  11036. ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsInstanceOf(mModule->mCompiler->mEnumTypeDef))))
  11037. foundMatch = true;
  11038. }
  11039. }
  11040. }
  11041. if (foundMatch)
  11042. {
  11043. mResult = mModule->GetDefaultTypedValue(type, false, Beefy::BfDefaultValueKind_Undef);
  11044. return true;
  11045. }
  11046. }
  11047. if (checkType->IsPrimitiveType())
  11048. {
  11049. auto primType = (BfPrimitiveType*)checkType;
  11050. if ((typeInstance != NULL) && (typeInstance->IsEnum()))
  11051. {
  11052. if (typeInstance->mTypeInfoEx != NULL)
  11053. {
  11054. mModule->AddDependency(typeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  11055. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)typeInstance->mTypeInfoEx->mMinValue : (uint64)typeInstance->mTypeInfoEx->mMaxValue), typeInstance);
  11056. return true;
  11057. }
  11058. }
  11059. else
  11060. {
  11061. switch (primType->mTypeDef->mTypeCode)
  11062. {
  11063. case BfTypeCode_Int8:
  11064. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x80 : 0x7F), primType);
  11065. return true;
  11066. case BfTypeCode_Int16:
  11067. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x8000 : 0x7FFF), primType);
  11068. return true;
  11069. case BfTypeCode_Int32:
  11070. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x80000000LL : 0x7FFFFFFF), primType);
  11071. return true;
  11072. case BfTypeCode_Int64:
  11073. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x8000000000000000LL : (uint64)0x7FFFFFFFFFFFFFFFLL), primType);
  11074. return true;
  11075. case BfTypeCode_UInt8:
  11076. case BfTypeCode_Char8:
  11077. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFF), primType);
  11078. return true;
  11079. case BfTypeCode_UInt16:
  11080. case BfTypeCode_Char16:
  11081. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFFFF), primType);
  11082. return true;
  11083. case BfTypeCode_UInt32:
  11084. case BfTypeCode_Char32:
  11085. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFLL), primType);
  11086. return true;
  11087. case BfTypeCode_UInt64:
  11088. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFFFFFFFFFLL), primType);
  11089. return true;
  11090. case BfTypeCode_IntPtr:
  11091. if (mModule->mSystem->mPtrSize == 8)
  11092. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x8000000000000000LL : (uint64)0x7FFFFFFFFFFFFFFFLL), primType);
  11093. else
  11094. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x80000000LL : 0x7FFFFFFF), primType);
  11095. return true;
  11096. case BfTypeCode_UIntPtr:
  11097. if (mModule->mSystem->mPtrSize == 8)
  11098. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFFFFFFFFFLL), primType);
  11099. else
  11100. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFLL), primType);
  11101. return true;
  11102. default: break;
  11103. }
  11104. }
  11105. }
  11106. if (type->IsEnum())
  11107. {
  11108. mModule->Fail(StrFormat("'MinValue' cannot be used on enum with payload '%s'", mModule->TypeToString(type).c_str()), propName);
  11109. }
  11110. else
  11111. {
  11112. mModule->Fail(StrFormat("'%s' cannot be used on type '%s'", memberName.c_str(), mModule->TypeToString(type).c_str()), propName);
  11113. }
  11114. }
  11115. else
  11116. {
  11117. success = false;
  11118. return false;
  11119. }
  11120. }
  11121. if ((type->IsGenericParam()) && (!mModule->mIsComptimeModule))
  11122. {
  11123. if (mResult.mType != NULL)
  11124. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, Beefy::BfDefaultValueKind_Undef);
  11125. }
  11126. auto autoComplete = GetAutoComplete();
  11127. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  11128. {
  11129. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  11130. }
  11131. return true;
  11132. }
  11133. void BfExprEvaluator::DoTypeIntAttr(BfTypeReference* typeRef, BfTokenNode* commaToken, BfIdentifierNode* memberName, BfToken token)
  11134. {
  11135. auto autoComplete = GetAutoComplete();
  11136. auto type = mModule->ResolveTypeRef(typeRef, BfPopulateType_Data, BfResolveTypeRefFlag_AutoComplete);
  11137. if (type == NULL)
  11138. return;
  11139. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage); // Local usage ensures it changes when the type data changes
  11140. auto typeInst = type->ToTypeInstance();
  11141. if ((typeInst != NULL) && (typeInst->mTypeDef->mIsOpaque))
  11142. {
  11143. mModule->Fail(StrFormat("Unable to determine attributes for opaque type '%s'", mModule->TypeToString(type).c_str()), typeRef);
  11144. }
  11145. BfType* sizeType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  11146. int attrVal = 0;
  11147. switch (token)
  11148. {
  11149. case BfToken_SizeOf: attrVal = type->mSize; break;
  11150. case BfToken_AlignOf: attrVal = type->mAlign; break;
  11151. case BfToken_StrideOf: attrVal = type->GetStride(); break;
  11152. default: break;
  11153. }
  11154. if (token == BfToken_OffsetOf)
  11155. {
  11156. bool found = false;
  11157. String findName;
  11158. if (memberName != NULL)
  11159. findName = memberName->ToString();
  11160. BfAstNode* refNode = typeRef;
  11161. if (memberName != NULL)
  11162. refNode = memberName;
  11163. auto checkTypeInst = typeInst;
  11164. while (checkTypeInst != NULL)
  11165. {
  11166. checkTypeInst->mTypeDef->PopulateMemberSets();
  11167. String filter;
  11168. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(commaToken, memberName, filter)))
  11169. {
  11170. auto activeTypeDef = mModule->GetActiveTypeDef();
  11171. mModule->PopulateType(checkTypeInst);
  11172. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  11173. for (auto fieldDef : checkTypeInst->mTypeDef->mFields)
  11174. {
  11175. if (fieldDef->mIsStatic)
  11176. continue;
  11177. if (!mModule->CheckProtection(protectionCheckFlags, typeInst, fieldDef->mDeclaringType->mProject, fieldDef->mProtection, typeInst))
  11178. continue;
  11179. if ((!typeInst->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, mModule)) ||
  11180. (!typeInst->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  11181. continue;
  11182. auto& fieldInst = checkTypeInst->mFieldInstances[fieldDef->mIdx];
  11183. autoComplete->AddField(checkTypeInst, fieldDef, &fieldInst, filter);
  11184. }
  11185. }
  11186. BfMemberSetEntry* memberSetEntry = NULL;
  11187. if (checkTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  11188. {
  11189. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  11190. if (fieldDef != NULL)
  11191. {
  11192. if (fieldDef->mIsStatic)
  11193. mModule->Fail(StrFormat("Cannot generate an offset from static field '%s.%s'", mModule->TypeToString(type).c_str(), fieldDef->mName.c_str()), refNode);
  11194. mModule->PopulateType(checkTypeInst);
  11195. auto& fieldInst = checkTypeInst->mFieldInstances[fieldDef->mIdx];
  11196. attrVal = fieldInst.mDataOffset;
  11197. found = true;
  11198. break;
  11199. }
  11200. }
  11201. checkTypeInst = checkTypeInst->mBaseType;
  11202. }
  11203. if (!found)
  11204. {
  11205. mModule->Fail(StrFormat("Unable to locate field '%s.%s'", mModule->TypeToString(type).c_str(), findName.c_str()), refNode);
  11206. }
  11207. }
  11208. bool isUndefVal = false;
  11209. if (type->IsGenericParam())
  11210. isUndefVal = true;
  11211. if (type->IsSizedArray())
  11212. {
  11213. auto sizedArray = (BfSizedArrayType*)type;
  11214. if (sizedArray->mElementCount == -1)
  11215. isUndefVal = true;
  11216. }
  11217. if (isUndefVal)
  11218. {
  11219. // We do this so we know it's a constant but we can't assume anything about its value
  11220. // We make the value an Int32 which doesn't match the IntPtr type, but it allows us to
  11221. // assume it can be implicitly cased to int32
  11222. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(sizeType)), sizeType);
  11223. }
  11224. else
  11225. mResult = BfTypedValue(mModule->GetConstValue(attrVal, sizeType), sizeType);
  11226. }
  11227. void BfExprEvaluator::Visit(BfSizeOfExpression* sizeOfExpr)
  11228. {
  11229. DoTypeIntAttr(sizeOfExpr->mTypeRef, NULL, NULL, BfToken_SizeOf);
  11230. }
  11231. void BfExprEvaluator::Visit(BfAlignOfExpression* alignOfExpr)
  11232. {
  11233. DoTypeIntAttr(alignOfExpr->mTypeRef, NULL, NULL, BfToken_AlignOf);
  11234. }
  11235. void BfExprEvaluator::Visit(BfStrideOfExpression* strideOfExpr)
  11236. {
  11237. DoTypeIntAttr(strideOfExpr->mTypeRef, NULL, NULL, BfToken_StrideOf);
  11238. }
  11239. void BfExprEvaluator::Visit(BfOffsetOfExpression* offsetOfExpr)
  11240. {
  11241. DoTypeIntAttr(offsetOfExpr->mTypeRef, offsetOfExpr->mCommaToken, offsetOfExpr->mMemberName, BfToken_OffsetOf);
  11242. }
  11243. void BfExprEvaluator::Visit(BfNameOfExpression* nameOfExpr)
  11244. {
  11245. String name;
  11246. if (mModule->IsInSpecializedGeneric())
  11247. {
  11248. if (auto identifierNode = BfNodeDynCastExact<BfIdentifierNode>(nameOfExpr->mTarget))
  11249. {
  11250. // This is necessary so we don't resolve 'T' to the actual generic argument type
  11251. name = identifierNode->ToString();
  11252. }
  11253. }
  11254. if (name.IsEmpty())
  11255. {
  11256. auto type = mModule->ResolveTypeRef(nameOfExpr->mTarget, {}, BfPopulateType_IdentityNoRemapAlias,
  11257. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_AllowUnboundGeneric | BfResolveTypeRefFlag_IgnoreLookupError | BfResolveTypeRefFlag_IgnoreProtection));
  11258. if (type != NULL)
  11259. {
  11260. auto typeInst = type->ToTypeInstance();
  11261. if (typeInst != NULL)
  11262. name = typeInst->mTypeDef->mName->ToString();
  11263. else
  11264. name = mModule->TypeToString(type);
  11265. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  11266. // Just do this for autocomplete
  11267. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  11268. VisitChild(nameOfExpr->mTarget);
  11269. }
  11270. }
  11271. if (name.IsEmpty())
  11272. {
  11273. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(nameOfExpr->mTarget))
  11274. {
  11275. String targetStr = nameOfExpr->mTarget->ToString();
  11276. BfAtomComposite targetComposite;
  11277. bool isValid = mModule->mSystem->ParseAtomComposite(targetStr, targetComposite);
  11278. bool namespaceExists = false;
  11279. BfProject* bfProject = NULL;
  11280. auto activeTypeDef = mModule->GetActiveTypeDef();
  11281. if (activeTypeDef != NULL)
  11282. bfProject = activeTypeDef->mProject;
  11283. auto _CheckProject = [&](BfProject* project)
  11284. {
  11285. if ((isValid) && (project->mNamespaces.ContainsKey(targetComposite)))
  11286. namespaceExists = true;
  11287. };
  11288. if (bfProject != NULL)
  11289. {
  11290. for (int depIdx = -1; depIdx < (int)bfProject->mDependencies.size(); depIdx++)
  11291. {
  11292. BfProject* depProject = (depIdx == -1) ? bfProject : bfProject->mDependencies[depIdx];
  11293. _CheckProject(depProject);
  11294. }
  11295. }
  11296. else
  11297. {
  11298. for (auto project : mModule->mSystem->mProjects)
  11299. _CheckProject(project);
  11300. }
  11301. if (namespaceExists)
  11302. {
  11303. if (mModule->mCompiler->mResolvePassData != NULL)
  11304. {
  11305. if (auto sourceClassifier = mModule->mCompiler->mResolvePassData->GetSourceClassifier(nameOfExpr->mTarget))
  11306. {
  11307. BfAstNode* checkIdentifier = identifer;
  11308. while (true)
  11309. {
  11310. auto qualifiedIdentifier = BfNodeDynCast<BfQualifiedNameNode>(checkIdentifier);
  11311. if (qualifiedIdentifier == NULL)
  11312. break;
  11313. sourceClassifier->SetElementType(qualifiedIdentifier->mRight, BfSourceElementType_Namespace);
  11314. checkIdentifier = qualifiedIdentifier->mLeft;
  11315. }
  11316. sourceClassifier->SetElementType(checkIdentifier, BfSourceElementType_Namespace);
  11317. }
  11318. }
  11319. name = targetComposite.mParts[targetComposite.mSize - 1]->ToString();
  11320. }
  11321. }
  11322. }
  11323. if (name.IsEmpty())
  11324. {
  11325. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NameOf));
  11326. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mBfIRBuilder->mIgnoreWrites, true);
  11327. VisitChild(nameOfExpr->mTarget);
  11328. if ((mBfEvalExprFlags & BfEvalExprFlags_NameOfSuccess) != 0)
  11329. {
  11330. BfAstNode* nameNode = nameOfExpr->mTarget;
  11331. if (auto attributedIdentifierNode = BfNodeDynCast<BfAttributedIdentifierNode>(nameNode))
  11332. nameNode = attributedIdentifierNode->mIdentifier;
  11333. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(nameNode))
  11334. nameNode = memberReferenceExpr->mMemberName;
  11335. if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(nameNode))
  11336. nameNode = qualifiedNameNode->mRight;
  11337. name = nameNode->ToString();
  11338. }
  11339. else if (mResultFieldInstance != NULL)
  11340. {
  11341. auto fieldDef = mResultFieldInstance->GetFieldDef();
  11342. if (fieldDef != NULL)
  11343. name = fieldDef->mName;
  11344. }
  11345. else if (mResultLocalVar != NULL)
  11346. {
  11347. name = mResultLocalVar->mName;
  11348. }
  11349. else if (mPropDef != NULL)
  11350. {
  11351. name = mPropDef->mName;
  11352. }
  11353. }
  11354. if ((name.IsEmpty()) && (nameOfExpr->mTarget != NULL))
  11355. mModule->Fail("Expression does not have a name", nameOfExpr->mTarget);
  11356. mResult = BfTypedValue(mModule->GetStringObjectValue(name), mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  11357. }
  11358. void BfExprEvaluator::Visit(BfIsConstExpression* isConstExpr)
  11359. {
  11360. if (isConstExpr->mExpression == NULL)
  11361. {
  11362. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  11363. return;
  11364. }
  11365. BfMethodState methodState;
  11366. SetAndRestoreValue<BfMethodState*> prevMethodState(mModule->mCurMethodState, &methodState, false);
  11367. if (mModule->mCurMethodState == NULL)
  11368. prevMethodState.Set();
  11369. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  11370. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  11371. SetAndRestoreValue<bool> allowUninitReads(mModule->mCurMethodState->mAllowUinitReads, true);
  11372. BfEvalExprFlags exprFlags = BfEvalExprFlags_None;
  11373. auto result = mModule->CreateValueFromExpression(isConstExpr->mExpression, NULL, BfEvalExprFlags_DeclType);
  11374. bool isConst = mModule->mBfIRBuilder->IsConstValue(result.mValue);
  11375. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, isConst ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  11376. }
  11377. void BfExprEvaluator::Visit(BfDefaultExpression* defaultExpr)
  11378. {
  11379. auto autoComplete = GetAutoComplete();
  11380. if (autoComplete != NULL)
  11381. autoComplete->CheckTypeRef(defaultExpr->mTypeRef, false, true);
  11382. BfType* type = NULL;
  11383. if (defaultExpr->mOpenParen == NULL)
  11384. {
  11385. if (mExpectingType)
  11386. {
  11387. type = mExpectingType;
  11388. }
  11389. else
  11390. {
  11391. mModule->Fail("Type cannot be inferred, consider adding explicit type name", defaultExpr);
  11392. return;
  11393. }
  11394. }
  11395. else
  11396. type = mModule->ResolveTypeRef(defaultExpr->mTypeRef);
  11397. if (type == NULL)
  11398. return;
  11399. BfDefaultValueKind defaultKind = BfDefaultValueKind_Const;
  11400. if (type->IsRef())
  11401. {
  11402. mModule->Fail(StrFormat("There is no default value for type '%s'", mModule->TypeToString(type).c_str()), defaultExpr);
  11403. defaultKind = BfDefaultValueKind_Addr;
  11404. }
  11405. mModule->ValidateAllocation(type, defaultExpr->mTypeRef);
  11406. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  11407. mResult = mModule->GetDefaultTypedValue(type, true, defaultKind);
  11408. }
  11409. void BfExprEvaluator::Visit(BfUninitializedExpression* uninitialziedExpr)
  11410. {
  11411. mModule->Fail("Invalid use of the '?' uninitialized specifier", uninitialziedExpr);
  11412. }
  11413. void BfExprEvaluator::Visit(BfCheckTypeExpression* checkTypeExpr)
  11414. {
  11415. auto targetValue = mModule->CreateValueFromExpression(checkTypeExpr->mTarget, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  11416. if (!targetValue)
  11417. return;
  11418. if (checkTypeExpr->mTypeRef == NULL)
  11419. {
  11420. mModule->AssertErrorState();
  11421. return;
  11422. }
  11423. auto autoComplete = GetAutoComplete();
  11424. if (autoComplete != NULL)
  11425. autoComplete->CheckTypeRef(checkTypeExpr->mTypeRef, false, true);
  11426. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  11427. if (checkTypeExpr->mTypeRef->IsA<BfVarTypeReference>())
  11428. {
  11429. bool isVar = false;
  11430. if ((targetValue.mType != NULL) && (targetValue.mType->IsVar()))
  11431. {
  11432. auto irb = mModule->mBfIRBuilder;
  11433. BfIRValue boolResult = mModule->CreateAlloca(boolType);
  11434. irb->CreateAlignedStore(irb->CreateConst(BfTypeCode_Boolean, 1), boolResult, 1);
  11435. mResult = BfTypedValue(irb->CreateAlignedLoad(boolResult, 1), boolType);
  11436. }
  11437. else
  11438. mResult = BfTypedValue(mModule->GetConstValue(0, boolType), boolType);
  11439. return;
  11440. }
  11441. auto targetType = mModule->ResolveTypeRef(checkTypeExpr->mTypeRef, BfPopulateType_Declaration);
  11442. if (!targetType)
  11443. {
  11444. mModule->AssertErrorState();
  11445. return;
  11446. }
  11447. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  11448. if (targetValue.mType->IsVar())
  11449. {
  11450. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Undef);
  11451. return;
  11452. }
  11453. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  11454. {
  11455. auto typeInstance = targetValue.mType->ToTypeInstance();
  11456. if (targetValue.mType->IsWrappableType())
  11457. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  11458. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  11459. if (!matches)
  11460. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  11461. if (!typeInstance->IsGenericParam())
  11462. {
  11463. if (matches)
  11464. mModule->Warn(0, "The result of this operation is always 'true'", checkTypeExpr->mIsToken);
  11465. else
  11466. mModule->Warn(0, "The result of this operation is always 'false'", checkTypeExpr->mIsToken);
  11467. }
  11468. mResult = BfTypedValue(mModule->GetConstValue(matches ? 1 : 0, boolType), boolType);
  11469. return;
  11470. }
  11471. if (targetType->IsValueType())
  11472. {
  11473. if ((targetValue.mType != mModule->mContext->mBfObjectType) && (!targetValue.mType->IsInterface()))
  11474. {
  11475. mResult = BfTypedValue(mModule->GetConstValue(0, boolType), boolType);
  11476. return;
  11477. }
  11478. }
  11479. int wantTypeId = 0;
  11480. if (!targetType->IsGenericParam())
  11481. wantTypeId = targetType->mTypeId;
  11482. auto objectType = mModule->mContext->mBfObjectType;
  11483. mModule->PopulateType(objectType, BfPopulateType_Full);
  11484. targetValue = mModule->LoadValue(targetValue);
  11485. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  11486. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  11487. bool wasGenericParamType = false;
  11488. if ((srcTypeInstance != NULL) && (targetTypeInstance != NULL))
  11489. {
  11490. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  11491. {
  11492. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  11493. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  11494. // it may be a "necessary cast" indeed
  11495. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  11496. {
  11497. if (srcTypeInstance == targetType)
  11498. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary check, the value is already type '%s'",
  11499. mModule->TypeToString(srcTypeInstance).c_str()), checkTypeExpr->mIsToken);
  11500. else
  11501. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary check, '%s' is a subtype of '%s'",
  11502. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), checkTypeExpr->mIsToken);
  11503. }
  11504. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  11505. return;
  11506. }
  11507. else if ((!targetType->IsInterface()) && (srcTypeInstance != mModule->mContext->mBfObjectType) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  11508. {
  11509. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  11510. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), checkTypeExpr->mIsToken);
  11511. }
  11512. }
  11513. if (mModule->mCompiler->IsAutocomplete())
  11514. {
  11515. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Addr);
  11516. return;
  11517. }
  11518. auto irb = mModule->mBfIRBuilder;
  11519. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  11520. auto matchBB = mModule->mBfIRBuilder->CreateBlock("is.match");
  11521. auto endBB = mModule->mBfIRBuilder->CreateBlock("is.done");
  11522. BfIRValue boolResult = mModule->CreateAlloca(boolType);
  11523. irb->CreateAlignedStore(irb->CreateConst(BfTypeCode_Boolean, 0), boolResult, 1);
  11524. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBB, endBB);
  11525. mModule->AddBasicBlock(matchBB);
  11526. irb->CreateAlignedStore(irb->CreateConst(BfTypeCode_Boolean, 1), boolResult, 1);
  11527. irb->CreateBr(endBB);
  11528. mModule->AddBasicBlock(endBB);
  11529. mResult = BfTypedValue(irb->CreateAlignedLoad(boolResult, 1), boolType);
  11530. }
  11531. void BfExprEvaluator::Visit(BfDynamicCastExpression* dynCastExpr)
  11532. {
  11533. auto targetValue = mModule->CreateValueFromExpression(dynCastExpr->mTarget);
  11534. auto targetType = mModule->ResolveTypeRefAllowUnboundGenerics(dynCastExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_None, false);
  11535. auto autoComplete = GetAutoComplete();
  11536. if (autoComplete != NULL)
  11537. {
  11538. autoComplete->CheckTypeRef(dynCastExpr->mTypeRef, false, true);
  11539. }
  11540. auto origTargetType = targetType;
  11541. if (!targetValue)
  11542. return;
  11543. if (!targetType)
  11544. {
  11545. mModule->AssertErrorState();
  11546. return;
  11547. }
  11548. bool wasGenericParamType = false;
  11549. if (targetType->IsGenericParam())
  11550. {
  11551. //targetType = mModule->ResolveGenericType(targetType);
  11552. //wasGenericParamType = true;
  11553. }
  11554. if ((targetValue.mType->IsMethodRef()) || (targetType->IsMethodRef()))
  11555. {
  11556. // We can never cast a MethodRef to any class type
  11557. mResult = mModule->GetDefaultTypedValue(targetType);
  11558. return;
  11559. }
  11560. if (mModule->mContext->mResolvingVarField)
  11561. {
  11562. mResult = mModule->GetDefaultTypedValue(targetType);
  11563. return;
  11564. }
  11565. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  11566. if (targetType->IsGenericParam())
  11567. {
  11568. wasGenericParamType = true;
  11569. BfGenericParamInstance* origGenericParam = NULL;
  11570. int pass = 0;
  11571. while ((targetType != NULL) && (targetType->IsGenericParam()))
  11572. {
  11573. auto genericParamType = (BfGenericParamType*)targetType;
  11574. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  11575. if (pass == 0)
  11576. origGenericParam = genericParam;
  11577. auto typeConstraint = genericParam->mTypeConstraint;
  11578. if ((typeConstraint == NULL) && (genericParam->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Interface)))
  11579. typeConstraint = mModule->mContext->mBfObjectType;
  11580. targetType = typeConstraint;
  11581. if (++pass >= 100) // Sanity - but we should have caught circular error before
  11582. break;
  11583. }
  11584. if ((targetType == NULL) || (!targetType->IsObjectOrInterface()))
  11585. {
  11586. mModule->Fail(StrFormat("The type parameter '%s' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' or 'interface' constraint",
  11587. origGenericParam->GetGenericParamDef()->mName.c_str()), dynCastExpr->mTypeRef);
  11588. return;
  11589. }
  11590. }
  11591. if (targetType->IsVar())
  11592. {
  11593. mResult = mModule->GetDefaultTypedValue(targetType);
  11594. return;
  11595. }
  11596. if ((!targetType->IsObjectOrInterface()) && (!targetType->IsNullable()))
  11597. {
  11598. mModule->Fail(StrFormat("The as operator must be used with a reference type or nullable type ('%s' is a non-nullable value type)",
  11599. mModule->TypeToString(origTargetType).c_str()), dynCastExpr->mTypeRef);
  11600. return;
  11601. }
  11602. if (targetValue.mType->IsGenericParam())
  11603. {
  11604. auto genericParamType = (BfGenericParamType*)targetValue.mType;
  11605. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  11606. auto typeConstraint = genericParam->mTypeConstraint;
  11607. if (typeConstraint == NULL)
  11608. typeConstraint = mModule->mContext->mBfObjectType;
  11609. if ((typeConstraint->IsDelegate()) && (typeConstraint == targetType))
  11610. {
  11611. // Delegate constraints may be matched by valueless method references, so this won't always match (don't warn)
  11612. mResult = mModule->GetDefaultTypedValue(targetType);
  11613. return;
  11614. }
  11615. targetValue = mModule->GetDefaultTypedValue(typeConstraint);
  11616. }
  11617. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  11618. auto _CheckResult = [&]()
  11619. {
  11620. if ((mResult) && (origTargetType->IsGenericParam()))
  11621. mResult = mModule->GetDefaultTypedValue(origTargetType, false, BfDefaultValueKind_Undef);
  11622. };
  11623. if ((targetValue.mType->IsNullable()) && (targetType->IsInterface()))
  11624. {
  11625. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_SilentFail);
  11626. if (!mResult)
  11627. {
  11628. mModule->Warn(0, StrFormat("Conversion from '%s' to '%s' will always be null",
  11629. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(origTargetType).c_str()), dynCastExpr->mAsToken);
  11630. mResult = BfTypedValue(mModule->GetDefaultValue(origTargetType), origTargetType);
  11631. }
  11632. _CheckResult();
  11633. return;
  11634. }
  11635. if (targetValue.mType->IsVar())
  11636. {
  11637. mResult = mModule->GetDefaultTypedValue(targetType, false, BfDefaultValueKind_Undef);
  11638. return;
  11639. }
  11640. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  11641. {
  11642. mModule->Warn(0, StrFormat("Type '%s' is not applicable for dynamic casting",
  11643. mModule->TypeToString(targetValue.mType).c_str()), dynCastExpr->mAsToken);
  11644. auto typeInstance = targetValue.mType->ToTypeInstance();
  11645. if (targetValue.mType->IsWrappableType())
  11646. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  11647. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  11648. if (targetType->IsNullable())
  11649. {
  11650. auto elementType = targetType->GetUnderlyingType();
  11651. if (elementType == targetValue.mType)
  11652. {
  11653. mModule->mBfIRBuilder->PopulateType(targetType);
  11654. // We match nullable element
  11655. auto allocaInst = mModule->CreateAlloca(targetType);
  11656. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 2); // has_value
  11657. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  11658. hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // value
  11659. mModule->mBfIRBuilder->CreateStore(targetValue.mValue, hasValueAddr);
  11660. mResult = BfTypedValue(allocaInst, targetType, true);
  11661. _CheckResult();
  11662. return;
  11663. }
  11664. }
  11665. if (!matches)
  11666. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  11667. if (matches)
  11668. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_Explicit);
  11669. else if (targetType->IsNullable())
  11670. {
  11671. auto allocaInst = mModule->CreateAlloca(targetType);
  11672. auto allocaBits = mModule->mBfIRBuilder->CreateBitCast(allocaInst, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  11673. mModule->mBfIRBuilder->CreateMemSet(allocaBits, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  11674. mModule->GetConstValue(targetType->mSize), targetType->mAlign);
  11675. mResult = BfTypedValue(allocaInst, targetType, true);
  11676. }
  11677. else
  11678. mResult = BfTypedValue(mModule->GetDefaultValue(targetType), targetType);
  11679. _CheckResult();
  11680. return;
  11681. }
  11682. if (targetType->IsNullable())
  11683. {
  11684. if (autoComplete != NULL)
  11685. {
  11686. mResult = mModule->GetDefaultTypedValue(targetType);
  11687. return;
  11688. }
  11689. auto elementType = targetType->GetUnderlyingType();
  11690. auto allocaInst = mModule->CreateAlloca(targetType);
  11691. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, elementType->IsValuelessType() ? 1 : 2); // has_value
  11692. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(0, boolType), hasValueAddr);
  11693. auto objectType = mModule->mContext->mBfObjectType;
  11694. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  11695. auto matchBB = mModule->mBfIRBuilder->CreateBlock("as.match");
  11696. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  11697. mModule->EmitDynamicCastCheck(targetValue, elementType, matchBB, endBB);
  11698. BfBoxedType* boxedType = mModule->CreateBoxedType(elementType);
  11699. mModule->AddBasicBlock(matchBB);
  11700. if (elementType->IsValuelessType())
  11701. {
  11702. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  11703. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  11704. }
  11705. else
  11706. {
  11707. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 2); // has_value
  11708. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  11709. auto nullableValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // value
  11710. auto srcBoxedType = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(boxedType, BfIRPopulateType_Full));
  11711. auto boxedValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(srcBoxedType, 0, 1); // mValue
  11712. auto boxedValue = mModule->mBfIRBuilder->CreateLoad(boxedValueAddr);
  11713. mModule->mBfIRBuilder->CreateStore(boxedValue, nullableValueAddr);
  11714. }
  11715. mModule->mBfIRBuilder->CreateBr(endBB);
  11716. mModule->AddBasicBlock(endBB);
  11717. mResult = BfTypedValue(allocaInst, targetType, true);
  11718. _CheckResult();
  11719. return;
  11720. }
  11721. targetValue = mModule->LoadValue(targetValue);
  11722. if (targetType->IsValueType())
  11723. {
  11724. mModule->Fail("Invalid dynamic cast type", dynCastExpr->mTypeRef);
  11725. return;
  11726. }
  11727. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  11728. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  11729. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  11730. {
  11731. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  11732. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  11733. // it may be a "necessary cast" indeed
  11734. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  11735. {
  11736. if (srcTypeInstance == targetType)
  11737. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, the value is already type '%s'",
  11738. mModule->TypeToString(srcTypeInstance).c_str()), dynCastExpr->mAsToken);
  11739. else
  11740. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, '%s' is a subtype of '%s'",
  11741. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), dynCastExpr->mAsToken);
  11742. }
  11743. auto castedValue = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetTypeInstance));
  11744. mResult = BfTypedValue(castedValue, targetTypeInstance);
  11745. _CheckResult();
  11746. return;
  11747. }
  11748. else if ((!targetType->IsInterface()) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  11749. {
  11750. if (!mModule->IsInSpecializedSection())
  11751. {
  11752. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  11753. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), dynCastExpr->mAsToken);
  11754. }
  11755. mResult = mModule->GetDefaultTypedValue(targetType);
  11756. return;
  11757. }
  11758. if (autoComplete != NULL)
  11759. {
  11760. mResult = mModule->GetDefaultTypedValue(targetType, false, BfDefaultValueKind_Addr);
  11761. _CheckResult();
  11762. return;
  11763. }
  11764. auto irb = mModule->mBfIRBuilder;
  11765. auto objectType = mModule->mContext->mBfObjectType;
  11766. mModule->PopulateType(objectType, BfPopulateType_Full);
  11767. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  11768. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  11769. auto matchBlock = irb->CreateBlock("as.match");
  11770. BfIRValue targetVal = mModule->CreateAlloca(targetType);
  11771. irb->CreateAlignedStore(irb->CreateConstNull(irb->MapType(targetType)), targetVal, targetType->mAlign);
  11772. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBlock, endBB);
  11773. mModule->AddBasicBlock(matchBlock);
  11774. BfIRValue castedCallResult = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetType));
  11775. irb->CreateAlignedStore(castedCallResult, targetVal, targetValue.mType->mAlign);
  11776. irb->CreateBr(endBB);
  11777. mModule->AddBasicBlock(endBB);
  11778. mResult = BfTypedValue(irb->CreateAlignedLoad(targetVal, targetType->mAlign), targetType);
  11779. _CheckResult();
  11780. }
  11781. void BfExprEvaluator::Visit(BfCastExpression* castExpr)
  11782. {
  11783. auto autoComplete = GetAutoComplete();
  11784. if ((autoComplete != NULL) && (castExpr->mTypeRef != NULL))
  11785. {
  11786. // 'mayBeIdentifier' because this may be a misidentified cast - it could be a parenthesized expression
  11787. autoComplete->CheckTypeRef(castExpr->mTypeRef, true, true);
  11788. }
  11789. BfType* resolvedType = NULL;
  11790. if ((BfNodeDynCastExact<BfDotTypeReference>(castExpr->mTypeRef) != NULL) && (mExpectingType != NULL))
  11791. {
  11792. //mModule->SetElementType(castExpr->mTypeRef, BfSourceElementType_TypeRef);
  11793. resolvedType = mExpectingType;
  11794. }
  11795. else
  11796. resolvedType = ResolveTypeRef(castExpr->mTypeRef);
  11797. if (resolvedType != NULL)
  11798. mModule->AddDependency(resolvedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  11799. // If resolvedType is NULL then that's okay- we just leave the following expression uncasted
  11800. if (castExpr->mExpression == NULL)
  11801. {
  11802. mModule->AssertErrorState();
  11803. return;
  11804. }
  11805. auto exprFlags = (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) | BfEvalExprFlags_ExplicitCast);
  11806. mResult = mModule->CreateValueFromExpression(castExpr->mExpression, resolvedType, exprFlags);
  11807. }
  11808. bool BfExprEvaluator::IsExactMethodMatch(BfMethodInstance* methodA, BfMethodInstance* methodB, bool ignoreImplicitParams)
  11809. {
  11810. if (methodA->mReturnType != methodB->mReturnType)
  11811. return false;
  11812. int implicitParamCountA = methodA->GetImplicitParamCount();
  11813. if (methodA->HasExplicitThis())
  11814. implicitParamCountA++;
  11815. int implicitParamCountB = methodB->GetImplicitParamCount();
  11816. if (methodB->HasExplicitThis())
  11817. implicitParamCountB++;
  11818. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  11819. return false;
  11820. for (int i = 0; i < (int)methodA->GetParamCount() - implicitParamCountA; i++)
  11821. {
  11822. auto paramA = methodA->GetParamType(i + implicitParamCountA);
  11823. auto paramB = methodB->GetParamType(i + implicitParamCountB);
  11824. if (paramA != paramB)
  11825. return false;
  11826. }
  11827. return true;
  11828. }
  11829. void BfExprEvaluator::ConstResolve(BfExpression* expr)
  11830. {
  11831. BfConstResolver constResolver(mModule);
  11832. constResolver.Resolve(expr);
  11833. mResult = constResolver.mResult;
  11834. }
  11835. BfTypeInstance* BfExprEvaluator::VerifyBaseDelegateType(BfTypeInstance* baseDelegateType)
  11836. {
  11837. mModule->PopulateType(baseDelegateType, BfPopulateType_DataAndMethods);
  11838. if (baseDelegateType->mFieldInstances.size() != 2)
  11839. {
  11840. mModule->AssertErrorState();
  11841. return NULL;
  11842. }
  11843. return baseDelegateType;
  11844. }
  11845. bool BfExprEvaluator::CanBindDelegate(BfDelegateBindExpression* delegateBindExpr, BfMethodInstance** boundMethod, BfType* origMethodExpectingType, BfTypeVector* methodGenericArgumentsSubstitute)
  11846. {
  11847. if ((mExpectingType == NULL) && (origMethodExpectingType == NULL))
  11848. {
  11849. return false;
  11850. }
  11851. bool isGenericMatch = mExpectingType == NULL;
  11852. auto expectingType = mExpectingType;
  11853. if (expectingType == NULL)
  11854. expectingType = origMethodExpectingType;
  11855. auto typeInstance = expectingType->ToTypeInstance();
  11856. if ((typeInstance == NULL) ||
  11857. ((!typeInstance->mTypeDef->mIsDelegate) && (!typeInstance->mTypeDef->mIsFunction)))
  11858. return false;
  11859. mModule->PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  11860. auto methodInstance = mModule->GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  11861. if (methodInstance == NULL)
  11862. {
  11863. BF_DBG_FATAL("Invoke not found");
  11864. return false;
  11865. }
  11866. if (delegateBindExpr->mTarget == NULL)
  11867. return false;
  11868. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  11869. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  11870. typedValueExprs.resize(methodInstance->GetParamCount());
  11871. SizedArray<BfExpression*, 4> args;
  11872. args.resize(methodInstance->GetParamCount());
  11873. auto _FixType = [&](BfType* type)
  11874. {
  11875. if (!isGenericMatch)
  11876. return type;
  11877. auto fixedType = mModule->ResolveGenericType(type, NULL, methodGenericArgumentsSubstitute, mModule->mCurTypeInstance);
  11878. if (fixedType != NULL)
  11879. return fixedType;
  11880. return (BfType*)mModule->GetPrimitiveType(BfTypeCode_Var);
  11881. };
  11882. auto _TypeMatches = [&](BfType* lhs, BfType* rhs)
  11883. {
  11884. if (lhs == rhs)
  11885. return true;
  11886. return lhs->IsVar();
  11887. };
  11888. for (int i = 0; i < (int) methodInstance->GetParamCount(); i++)
  11889. {
  11890. auto typedValueExpr = &typedValueExprs[i];
  11891. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  11892. typedValueExpr->mTypedValue.mType = _FixType(methodInstance->GetParamType(i));
  11893. typedValueExpr->mRefNode = NULL;
  11894. args[i] = typedValueExpr;
  11895. }
  11896. BfMethodGenericArguments methodGenericArgs;
  11897. if (delegateBindExpr->mGenericArgs != NULL)
  11898. methodGenericArgs.mArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  11899. BfFunctionBindResult bindResult;
  11900. bindResult.mSkipMutCheck = true; // Allow operating on copies
  11901. bindResult.mBindType = expectingType;
  11902. mFunctionBindResult = &bindResult;
  11903. SetAndRestoreValue<bool> ignoreError(mModule->mIgnoreErrors, true);
  11904. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArgs);
  11905. mFunctionBindResult = NULL;
  11906. if (bindResult.mMethodInstance == NULL)
  11907. return false;
  11908. if (boundMethod != NULL)
  11909. *boundMethod = bindResult.mMethodInstance;
  11910. auto matchedMethod = bindResult.mMethodInstance;
  11911. if (!_TypeMatches(_FixType(methodInstance->mReturnType), matchedMethod->mReturnType))
  11912. return false;
  11913. int implicitParamCountA = methodInstance->GetImplicitParamCount();
  11914. int implicitParamCountB = matchedMethod->GetImplicitParamCount();
  11915. if (methodInstance->GetParamCount() - implicitParamCountA != matchedMethod->GetParamCount() - implicitParamCountB)
  11916. return false;
  11917. for (int i = 0; i < (int)methodInstance->GetParamCount() - implicitParamCountA; i++)
  11918. {
  11919. auto paramA = _FixType(methodInstance->GetParamType(i + implicitParamCountA));
  11920. auto paramB = _FixType(matchedMethod->GetParamType(i + implicitParamCountB));
  11921. if (!_TypeMatches(paramA, paramB))
  11922. return false;
  11923. }
  11924. return true;
  11925. }
  11926. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfIdentifierNode* identifierNode, int shadowIdx)
  11927. {
  11928. String findName = identifierNode->ToString();
  11929. if (mModule->mCurMethodState != NULL)
  11930. {
  11931. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  11932. auto checkMethodState = mModule->mCurMethodState;
  11933. bool isMixinOuterVariablePass = false;
  11934. int shadowSkip = shadowIdx;
  11935. while (checkMethodState != NULL)
  11936. {
  11937. BP_ZONE("LookupIdentifier:DoImplicitArgCapture");
  11938. BfTypeInstance* closureTypeInst = NULL;
  11939. BfClosureInstanceInfo* closureInstanceInfo = NULL;
  11940. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  11941. {
  11942. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  11943. }
  11944. BfLocalVarEntry* entry;
  11945. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(findName, &entry))
  11946. {
  11947. auto varDecl = entry->mLocalVar;
  11948. while (varDecl != NULL)
  11949. {
  11950. if (varDecl->mNameNode == identifierNode)
  11951. {
  11952. if (shadowSkip > 0)
  11953. {
  11954. shadowSkip--;
  11955. }
  11956. else
  11957. {
  11958. BfTypedValue localResult = LoadLocal(varDecl);
  11959. if (!isMixinOuterVariablePass)
  11960. {
  11961. mResultLocalVar = varDecl;
  11962. mResultFieldInstance = NULL;
  11963. mResultLocalVarRefNode = identifierNode;
  11964. }
  11965. return localResult;
  11966. }
  11967. }
  11968. varDecl = varDecl->mShadowedLocal;
  11969. }
  11970. }
  11971. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  11972. if (closureTypeInst != NULL)
  11973. {
  11974. closureTypeInst->mTypeDef->PopulateMemberSets();
  11975. BfMemberSetEntry* memberSetEntry = NULL;
  11976. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  11977. {
  11978. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  11979. while (fieldDef != NULL)
  11980. {
  11981. BfIdentifierNode* fieldNameNode = NULL;
  11982. if (fieldDef->mIdx < (int)checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries.size())
  11983. fieldNameNode = checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries[fieldDef->mIdx].mNameNode;
  11984. if (fieldNameNode == identifierNode)
  11985. {
  11986. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  11987. if (!field.mResolvedType->IsValuelessType())
  11988. {
  11989. if (mModule->mCurMethodState->mClosureState->mCapturing)
  11990. {
  11991. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  11992. return mModule->GetDefaultTypedValue(field.mResolvedType);
  11993. }
  11994. auto localVar = mModule->mCurMethodState->mLocals[0];
  11995. auto thisValue = localVar->mValue;
  11996. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  11997. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  11998. if (field.mResolvedType->IsRef())
  11999. {
  12000. auto refType = (BfRefType*)field.mResolvedType;
  12001. auto underlyingType = refType->GetUnderlyingType();
  12002. result = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(result.mValue, underlyingType->mAlign), underlyingType, true);
  12003. }
  12004. else if (fieldDef->mIsReadOnly)
  12005. result = mModule->LoadValue(result);
  12006. mResultLocalVar = localVar;
  12007. mResultFieldInstance = &field;
  12008. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  12009. return result;
  12010. }
  12011. }
  12012. fieldDef = fieldDef->mNextWithSameName;
  12013. }
  12014. }
  12015. }
  12016. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  12017. {
  12018. checkMethodState = checkMethodState->mPrevMethodState;
  12019. continue;
  12020. }
  12021. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  12022. bool isLocalMixinProcessing = false;
  12023. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  12024. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  12025. isLocalMixinProcessing = true;
  12026. if (!isLocalMixinProcessing)
  12027. break;
  12028. isMixinOuterVariablePass = true;
  12029. checkMethodState = checkMethodState->mPrevMethodState;
  12030. }
  12031. }
  12032. return BfTypedValue();
  12033. }
  12034. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfMethodInstance* methodInstance, int paramIdx, bool& failed, BfImplicitParamKind paramKind, const BfTypedValue& methodRefTarget)
  12035. {
  12036. if ((methodRefTarget) && (methodRefTarget.mValue.mId != BfIRValue::ID_IMPLICIT))
  12037. {
  12038. if (methodRefTarget.mType->IsMethodRef())
  12039. {
  12040. BfMethodRefType* methodRefType = (BfMethodRefType*)methodRefTarget.mType;
  12041. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  12042. BF_ASSERT(methodRefMethodInst == methodInstance);
  12043. auto paramType = methodInstance->GetParamType(paramIdx);
  12044. int dataIdx = methodRefType->GetDataIdxFromParamIdx(paramIdx);
  12045. if (dataIdx == -1)
  12046. {
  12047. BF_ASSERT(paramType->IsValuelessType());
  12048. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), paramType);
  12049. }
  12050. if (methodRefTarget.IsSplat())
  12051. {
  12052. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  12053. {
  12054. BF_ASSERT(paramIdx == -1);
  12055. return BfTypedValue(methodRefTarget.mValue, paramType, BfTypedValueKind_SplatHead);
  12056. }
  12057. else
  12058. {
  12059. int splatIdx = dataIdx;
  12060. if (dataIdx > 0)
  12061. {
  12062. if (methodRefType->WantsDataPassedAsSplat(0))
  12063. splatIdx += methodRefType->GetCaptureType(0)->GetSplatCount() - 1;
  12064. }
  12065. bool isAddr = false;
  12066. BfIRValue value = mModule->ExtractSplatValue(methodRefTarget, splatIdx, paramType, &isAddr);
  12067. // We moved the composite load from ExtractSplatValue to here. Hopefully this is correct.
  12068. // in LLVM backend we get a direct 'arg' back, in Beef we get backing for a pointer to the struct (and thus need to load)
  12069. // if ((paramType->IsComposite()) && (mModule->IsTargetingBeefBackend()))
  12070. // value = mModule->mBfIRBuilder->CreateLoad(value);
  12071. auto lookupVal = BfTypedValue(value, paramType, isAddr);
  12072. if ((isAddr) && (!lookupVal.mType->IsComposite()))
  12073. lookupVal = mModule->LoadValue(lookupVal);
  12074. return lookupVal;
  12075. }
  12076. }
  12077. if ((paramType->IsComposite()) && (methodRefTarget.IsAddr()))
  12078. return BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefTarget.mValue, 0, dataIdx), paramType, true);
  12079. return BfTypedValue(mModule->ExtractValue(methodRefTarget, dataIdx), paramType);
  12080. }
  12081. }
  12082. // 'Default' implicit arg lookup, by identifier. May match field (for lambda), or local variable
  12083. if (paramKind == BfImplicitParamKind_General)
  12084. {
  12085. if (paramIdx == -1)
  12086. {
  12087. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(refNode))
  12088. {
  12089. BfAstNode* thisNode = NULL;
  12090. BfTypedValue thisValue;
  12091. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(delegateBindExpr->mTarget))
  12092. thisNode = memberReferenceExpr->mTarget;
  12093. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(delegateBindExpr->mTarget))
  12094. thisNode = qualifiedNameNode->mLeft;
  12095. else if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(delegateBindExpr->mTarget))
  12096. {
  12097. // Implicit
  12098. thisValue = mModule->GetThis();
  12099. }
  12100. if (auto thisExpr = BfNodeDynCast<BfExpression>(thisNode))
  12101. {
  12102. thisValue = mModule->CreateValueFromExpression(thisExpr);
  12103. if (!thisValue)
  12104. return BfTypedValue();
  12105. }
  12106. if (thisValue)
  12107. {
  12108. //TODO: handle 'mut', throw error if trying to capture from a non-mut, etc...
  12109. return thisValue;
  12110. }
  12111. }
  12112. }
  12113. String captureName = methodInstance->GetParamName(paramIdx);
  12114. BfIdentifierNode* identifierNode = methodInstance->GetParamNameNode(paramIdx);
  12115. BfTypedValue lookupVal;
  12116. if (identifierNode != NULL)
  12117. {
  12118. lookupVal = DoImplicitArgCapture(refNode, identifierNode, 0);
  12119. }
  12120. else
  12121. {
  12122. lookupVal = LookupIdentifier(NULL, captureName);
  12123. }
  12124. if (lookupVal)
  12125. {
  12126. auto paramType = methodInstance->GetParamType(paramIdx);
  12127. if (paramType->IsRef())
  12128. {
  12129. auto refType = (BfRefType*)paramType;
  12130. if (mResultLocalVar != NULL)
  12131. {
  12132. // When we are capturing, we need to note that we require capturing by reference here
  12133. auto localVar = mResultLocalVar;
  12134. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  12135. }
  12136. bool isValid = false;
  12137. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (lookupVal.mKind == BfTypedValueKind_MutableValue))
  12138. isValid = true;
  12139. if ((lookupVal.mType->IsRef()) || (lookupVal.IsAddr()))
  12140. isValid = true;
  12141. if (!isValid)
  12142. {
  12143. // Is there another way this can fail than to be in a lambda?
  12144. auto error = mModule->Fail(StrFormat("Method '%s' requires that '%s' be captured by reference. Consider adding by-reference capture specifier [&] to lambda.",
  12145. mModule->MethodToString(methodInstance).c_str(), captureName.c_str()), refNode, true);
  12146. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  12147. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  12148. failed = true;
  12149. }
  12150. }
  12151. else
  12152. {
  12153. if (lookupVal.mType->IsRef())
  12154. lookupVal = mModule->RemoveRef(lookupVal);
  12155. if (!lookupVal.mType->IsComposite())
  12156. lookupVal = mModule->LoadValue(lookupVal);
  12157. }
  12158. return lookupVal;
  12159. }
  12160. else
  12161. {
  12162. mModule->Fail(StrFormat("Failed to lookup implicit capture '%s'", captureName.c_str()), refNode, true);
  12163. failed = true;
  12164. return BfTypedValue();
  12165. }
  12166. }
  12167. return BfTypedValue();
  12168. }
  12169. void BfExprEvaluator::Visit(BfDelegateBindExpression* delegateBindExpr)
  12170. {
  12171. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  12172. if (mExpectingType == NULL)
  12173. {
  12174. mModule->Fail("Cannot infer delegate type", delegateBindExpr);
  12175. return;
  12176. }
  12177. BfTokenNode* newToken = NULL;
  12178. BfAllocTarget allocTarget;
  12179. ResolveAllocTarget(allocTarget, delegateBindExpr->mNewToken, newToken);
  12180. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  12181. SizedArray<BfExpression*, 4> args;
  12182. BfTypeInstance* delegateTypeInstance = NULL;
  12183. BfMethodInstance* methodInstance = NULL;
  12184. const char* bindTypeName = NULL;
  12185. bool isMethodRefMatch = false;
  12186. if (mExpectingType->IsMethodRef())
  12187. {
  12188. auto methodRefType = (BfMethodRefType*)mExpectingType;
  12189. BF_ASSERT(delegateBindExpr->mNewToken == NULL);
  12190. methodInstance = methodRefType->mMethodRef;
  12191. isMethodRefMatch = true;
  12192. }
  12193. else
  12194. {
  12195. if (mExpectingType->IsGenericParam())
  12196. {
  12197. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  12198. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsDelegate()))
  12199. {
  12200. delegateTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  12201. }
  12202. }
  12203. else
  12204. delegateTypeInstance = mExpectingType->ToTypeInstance();
  12205. if ((delegateTypeInstance == NULL) ||
  12206. ((!delegateTypeInstance->IsDelegate()) && (!delegateTypeInstance->IsFunction())))
  12207. {
  12208. mModule->Fail(StrFormat("Type '%s' cannot be used for method binding. Only delegate or function types are allowed.", mModule->TypeToString(mExpectingType).c_str()), delegateBindExpr);
  12209. return;
  12210. }
  12211. bindTypeName = (delegateTypeInstance->IsDelegate()) ? "delegate" : "function";
  12212. mModule->PopulateType(delegateTypeInstance, BfPopulateType_DataAndMethods);
  12213. methodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  12214. if (methodInstance == NULL)
  12215. {
  12216. BF_DBG_FATAL("Invoke not found");
  12217. return;
  12218. }
  12219. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(delegateBindExpr->mNewToken))
  12220. {
  12221. if (delegateTypeInstance->IsFunction())
  12222. mModule->Fail("Function bindings are direct assignments, allocation specifier is not applicable", delegateBindExpr->mNewToken);
  12223. else if (tokenNode->GetToken() == BfToken_Append)
  12224. {
  12225. mModule->Fail("Append allocation on delegate bind not supported", delegateBindExpr->mNewToken);
  12226. }
  12227. }
  12228. }
  12229. int paramOffset = methodInstance->HasExplicitThis() ? 1 : 0;
  12230. typedValueExprs.resize(methodInstance->GetParamCount() - paramOffset);
  12231. args.resize(methodInstance->GetParamCount() - paramOffset);
  12232. for (int i = 0; i < (int)methodInstance->GetParamCount() - paramOffset; i++)
  12233. {
  12234. auto typedValueExpr = &typedValueExprs[i];
  12235. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  12236. typedValueExpr->mTypedValue.mType = methodInstance->GetParamType(i + paramOffset);
  12237. if (methodInstance->GetParamKind(i + paramOffset) == BfParamKind_Params)
  12238. typedValueExpr->mTypedValue.mKind = BfTypedValueKind_Params;
  12239. typedValueExpr->mRefNode = NULL;
  12240. args[i] = typedValueExpr;
  12241. }
  12242. BfMethodGenericArguments methodGenericArgs;
  12243. if (delegateBindExpr->mGenericArgs != NULL)
  12244. methodGenericArgs.mArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  12245. if (delegateBindExpr->mTarget == NULL)
  12246. {
  12247. mModule->AssertErrorState();
  12248. return;
  12249. }
  12250. auto autoComplete = GetAutoComplete();
  12251. if (autoComplete != NULL)
  12252. {
  12253. SetAndRestoreValue<bool> prevForceAllowNonStatic(autoComplete->mForceAllowNonStatic, methodInstance->mMethodDef->mHasExplicitThis);
  12254. GetAutoComplete()->CheckNode(delegateBindExpr->mTarget, true);
  12255. }
  12256. if ((!delegateBindExpr->mTarget->IsA<BfIdentifierNode>()) &&
  12257. (!delegateBindExpr->mTarget->IsA<BfMemberReferenceExpression>()))
  12258. {
  12259. mModule->Fail(StrFormat("Invalid %s binding target, %s can only bind to method references. Consider wrapping expression in a lambda.", bindTypeName, bindTypeName), delegateBindExpr->mTarget);
  12260. mModule->CreateValueFromExpression(delegateBindExpr->mTarget);
  12261. return;
  12262. }
  12263. BfFunctionBindResult bindResult;
  12264. bindResult.mSkipMutCheck = true; // Allow operating on copies
  12265. bindResult.mBindType = delegateTypeInstance;
  12266. //
  12267. {
  12268. SetAndRestoreValue<BfType*> prevExpectingType(mExpectingType, methodInstance->mReturnType);
  12269. mFunctionBindResult = &bindResult;
  12270. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArgs);
  12271. mFunctionBindResult = NULL;
  12272. }
  12273. SetMethodElementType(delegateBindExpr->mTarget);
  12274. if (bindResult.mMethodInstance == NULL)
  12275. {
  12276. if ((mResult) && (IsVar(mResult.mType)))
  12277. return;
  12278. mResult = BfTypedValue();
  12279. return;
  12280. }
  12281. if (((bindResult.mMethodInstance->mComptimeFlags & BfComptimeFlag_Comptime) != 0) && ((mModule->mCurMethodInstance->mComptimeFlags & BfComptimeFlag_Comptime) == 0))
  12282. {
  12283. mModule->Fail(StrFormat("Cannot bind to const-eval method '%s', as this method is not available at runtime", mModule->MethodToString(bindResult.mMethodInstance).c_str()), delegateBindExpr->mTarget);
  12284. }
  12285. auto bindMethodInstance = bindResult.mMethodInstance;
  12286. if (isMethodRefMatch)
  12287. {
  12288. // WTF- this was always false, what was it supposed to catch?
  12289. // if (bindMethodInstance != bindResult.mMethodInstance)
  12290. // {
  12291. // mResult = BfTypedValue();
  12292. // return;
  12293. // }
  12294. }
  12295. else
  12296. {
  12297. bool isExactMethodMatch = IsExactMethodMatch(methodInstance, bindMethodInstance, true);
  12298. if ((mExpectingType != NULL) && (mExpectingType->IsFunction()) && (methodInstance->mMethodDef->mIsMutating != bindMethodInstance->mMethodDef->mIsMutating))
  12299. isExactMethodMatch = false;
  12300. if (!isExactMethodMatch)
  12301. {
  12302. if (bindResult.mCheckedMultipleMethods)
  12303. {
  12304. mModule->Fail(StrFormat("No overload for '%s' matches %s '%s'", bindMethodInstance->mMethodDef->mName.c_str(), bindTypeName,
  12305. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  12306. }
  12307. else
  12308. {
  12309. mModule->Fail(StrFormat("Method '%s' does not match %s '%s'", mModule->MethodToString(bindMethodInstance, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType | BfMethodNameFlag_IncludeMut)).c_str(), bindTypeName,
  12310. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  12311. }
  12312. mResult = BfTypedValue();
  12313. return;
  12314. }
  12315. }
  12316. bool isDirectFunction = false;
  12317. if ((bindResult.mMethodInstance->GetOwner()->IsFunction()) && (bindResult.mFunc))
  12318. isDirectFunction = true;
  12319. if (bindMethodInstance->mIsIntrinsic)
  12320. {
  12321. mModule->Fail(StrFormat("Method '%s' is an intrinsic and therefore cannot be used as a method binding target. Intrinsics have no addresses.", mModule->MethodToString(bindMethodInstance).c_str()), delegateBindExpr->mTarget);
  12322. mResult = BfTypedValue();
  12323. return;
  12324. }
  12325. bool hasIncompatibleCallingConventions = !mModule->mSystem->IsCompatibleCallingConvention(methodInstance->mCallingConvention, bindMethodInstance->mCallingConvention);
  12326. auto _GetInvokeMethodName = [&]()
  12327. {
  12328. StringT<512> methodName = "Invoke$";
  12329. methodName += mModule->mCurMethodInstance->mMethodDef->mName;
  12330. int prevSepPos = (int)methodName.LastIndexOf('$');
  12331. if (prevSepPos > 6)
  12332. {
  12333. methodName.RemoveToEnd(prevSepPos);
  12334. }
  12335. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  12336. HashContext hashCtx;
  12337. if (mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mPartialIdx != -1)
  12338. hashCtx.Mixin(mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mPartialIdx);
  12339. if (delegateBindExpr->mFatArrowToken != NULL)
  12340. {
  12341. hashCtx.Mixin(delegateBindExpr->mFatArrowToken->GetStartCharId());
  12342. }
  12343. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  12344. {
  12345. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  12346. {
  12347. StringT<128> genericTypeName;
  12348. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  12349. hashCtx.MixinStr(genericTypeName);
  12350. }
  12351. }
  12352. Val128 hashVal = hashCtx.Finish128();
  12353. methodName += '$';
  12354. methodName += BfTypeUtils::HashEncode64(hashVal.mLow);
  12355. StringT<512> mangledName;
  12356. BfMangler::MangleMethodName(mangledName, mModule->mCompiler->GetMangleKind(), mModule->mCurTypeInstance, methodName);
  12357. return mangledName;
  12358. };
  12359. if ((delegateBindExpr->mNewToken == NULL) || (delegateTypeInstance->IsFunction()))
  12360. {
  12361. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder != NULL))
  12362. {
  12363. BF_ASSERT(bindResult.mMethodInstance->mHotMethod != NULL);
  12364. mModule->mCurMethodState->mHotDataReferenceBuilder->mFunctionPtrs.Add(bindResult.mMethodInstance->mHotMethod);
  12365. }
  12366. if (isDirectFunction)
  12367. {
  12368. //if ((delegateTypeInstance != NULL) && (delegateTypeInstance->IsFunction()))
  12369. if (mExpectingType->IsFunction())
  12370. {
  12371. auto intPtrVal = mModule->mBfIRBuilder->CreatePtrToInt(bindResult.mFunc, BfTypeCode_IntPtr);
  12372. mResult = BfTypedValue(intPtrVal, mExpectingType);
  12373. return;
  12374. }
  12375. }
  12376. if (mExpectingType->IsFunction())
  12377. {
  12378. BfIRValue result;
  12379. if ((hasIncompatibleCallingConventions) && (mModule->HasExecutedOutput()))
  12380. {
  12381. //
  12382. {
  12383. SetAndRestoreValue<bool> prevIgnore(mModule->mBfIRBuilder->mIgnoreWrites, true);
  12384. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mOrigTarget, bindResult.mMethodInstance, mExpectingType);
  12385. }
  12386. if (result)
  12387. {
  12388. String methodName = _GetInvokeMethodName();
  12389. SizedArray<BfIRType, 8> irParamTypes;
  12390. BfIRType irReturnType;
  12391. methodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  12392. int thisFuncParamIdx = methodInstance->GetThisIdx();
  12393. int thisBindParamIdx = methodInstance->GetThisIdx();
  12394. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  12395. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  12396. mModule->mBfIRBuilder->SaveDebugLocation();
  12397. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  12398. auto funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  12399. auto srcCallingConv = mModule->GetIRCallingConvention(methodInstance);
  12400. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  12401. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  12402. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  12403. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  12404. SizedArray<BfIRValue, 8> irArgs;
  12405. for (int paramIdx = 0; paramIdx < irParamTypes.size(); paramIdx++)
  12406. {
  12407. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(paramIdx));
  12408. }
  12409. auto bindFuncVal = bindResult.mFunc;
  12410. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!mModule->mIsComptimeModule))
  12411. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  12412. auto callResult = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  12413. auto destCallingConv = mModule->GetIRCallingConvention(bindMethodInstance);
  12414. if (destCallingConv != BfIRCallingConv_CDecl)
  12415. mModule->mBfIRBuilder->SetCallCallingConv(callResult, destCallingConv);
  12416. if (methodInstance->mReturnType->IsValuelessType())
  12417. mModule->mBfIRBuilder->CreateRetVoid();
  12418. else
  12419. mModule->mBfIRBuilder->CreateRet(callResult);
  12420. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  12421. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  12422. mModule->mBfIRBuilder->RestoreDebugLocation();
  12423. result = mModule->mBfIRBuilder->CreatePtrToInt(funcValue, BfTypeCode_IntPtr);
  12424. }
  12425. }
  12426. else
  12427. {
  12428. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsGenericParam()) && (bindResult.mMethodInstance->GetOwner()->IsInterface()))
  12429. {
  12430. bool matching = true;
  12431. if (methodInstance->HasExplicitThis())
  12432. {
  12433. auto thisType = methodInstance->GetParamType(0);
  12434. if (thisType->IsPointer())
  12435. thisType = thisType->GetUnderlyingType();
  12436. if (thisType->IsRef())
  12437. thisType = thisType->GetUnderlyingType();
  12438. matching = thisType == bindResult.mOrigTarget.mType;
  12439. }
  12440. if (matching)
  12441. {
  12442. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), mExpectingType);
  12443. return;
  12444. }
  12445. }
  12446. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mOrigTarget, bindResult.mMethodInstance, mExpectingType, BfCastFlags_None, bindResult.mFunc);
  12447. }
  12448. if (result)
  12449. mResult = BfTypedValue(result, mExpectingType);
  12450. return;
  12451. }
  12452. if (bindResult.mMethodInstance->mDisallowCalling)
  12453. {
  12454. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  12455. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  12456. return;
  12457. }
  12458. auto methodRefType = mModule->CreateMethodRefType(bindResult.mMethodInstance);
  12459. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12460. mModule->AddCallDependency(bindResult.mMethodInstance);
  12461. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  12462. {
  12463. mResult = bindResult.mOrigTarget;
  12464. }
  12465. else
  12466. {
  12467. if ((bindResult.mMethodInstance->mMethodDef->mIsLocalMethod) || (!bindResult.mTarget))
  12468. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  12469. else
  12470. {
  12471. auto methodRefPtr = mModule->CreateAlloca(methodRefType, "bindResult");
  12472. auto elemPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefPtr, 0, 0);
  12473. BfTypedValue target;
  12474. if (bindResult.mTarget.IsSplat())
  12475. target = mModule->AggregateSplat(bindResult.mTarget, &bindResult.mIRArgs[0]);
  12476. else
  12477. target = bindResult.mTarget;
  12478. mModule->mBfIRBuilder->CreateStore(target.mValue, elemPtr);
  12479. mResult = BfTypedValue(methodRefPtr, methodRefType, true);
  12480. }
  12481. }
  12482. return;
  12483. }
  12484. int implicitParamCount = bindMethodInstance->GetImplicitParamCount();
  12485. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  12486. BfClosureType* closureTypeInst = NULL;
  12487. auto origTarget = bindResult.mOrigTarget;
  12488. auto target = bindResult.mTarget;
  12489. BfTypedValue methodRefTarget;
  12490. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  12491. methodRefTarget = bindResult.mOrigTarget;
  12492. bool isStructTarget = (target) && (target.mType->IsStruct());
  12493. bool bindCapturesThis = bindMethodInstance->HasThis() && !isStructTarget;
  12494. bool needsSplat = (isStructTarget) && (!bindMethodInstance->mMethodDef->mIsMutating) && (bindMethodInstance->AllowsSplatting(-1));
  12495. bool captureThisByValue = isStructTarget;
  12496. if (bindMethodInstance->mMethodDef->mIsLocalMethod)
  12497. {
  12498. // Local method captures always capture 'this' by reference
  12499. captureThisByValue = false;
  12500. }
  12501. if ((origTarget.mType != NULL) &&
  12502. ((origTarget.mType->IsRef()) || (origTarget.mType->IsPointer())))
  12503. {
  12504. captureThisByValue = false;
  12505. }
  12506. if (methodRefTarget)
  12507. BF_ASSERT(methodRefTarget.mType->IsMethodRef());
  12508. if (target.IsSplat())
  12509. target = mModule->AggregateSplat(target, &bindResult.mIRArgs[0]);
  12510. bool hasCaptures = false;
  12511. // Do we need a special delegate type for this?
  12512. if (((captureThisByValue) || (needsSplat) || (implicitParamCount > 0) /*|| (hasIncompatibleCallingConventions)*/) &&
  12513. (mModule->HasExecutedOutput()))
  12514. {
  12515. hasCaptures = true;
  12516. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  12517. if (captureThisByValue)
  12518. target = mModule->LoadValue(target);
  12519. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  12520. HashContext hashCtx;
  12521. hashCtx.MixinStr(delegateTypeName);
  12522. // We mix in the project for reasons described in the lambda binding handler
  12523. hashCtx.MixinStr(curProject->mName);
  12524. String structTargetTypeName;
  12525. String structTargetName;
  12526. // Implicit param separator
  12527. for (int implicitParamIdx = bindMethodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  12528. {
  12529. auto paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  12530. if ((implicitParamIdx == -1) && (captureThisByValue))
  12531. {
  12532. if (paramType->IsPointer())
  12533. paramType = paramType->GetUnderlyingType();
  12534. }
  12535. structTargetTypeName = mModule->TypeToString(paramType);
  12536. structTargetName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  12537. hashCtx.MixinStr(structTargetTypeName);
  12538. hashCtx.MixinStr(structTargetName);
  12539. }
  12540. Val128 hash128 = hashCtx.Finish128();
  12541. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  12542. checkClosureType->mContext = mModule->mContext;
  12543. checkClosureType->mBaseType = delegateTypeInstance;
  12544. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_TypeDef);
  12545. closureTypeInst = (BfClosureType*)resolvedClosureType;
  12546. if (checkClosureType == resolvedClosureType)
  12547. {
  12548. // This is a new closure type
  12549. closureTypeInst->Init(curProject);
  12550. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  12551. {
  12552. String fieldName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  12553. BfType* paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  12554. if ((implicitParamIdx == -1) && (captureThisByValue))
  12555. {
  12556. if (paramType->IsPointer())
  12557. paramType = paramType->GetUnderlyingType();
  12558. }
  12559. if (fieldName == "this")
  12560. fieldName = "__this";
  12561. closureTypeInst->AddField(paramType, fieldName);
  12562. }
  12563. closureTypeInst->Finish();
  12564. mModule->PopulateType(resolvedClosureType, BfPopulateType_Declaration);
  12565. }
  12566. else
  12567. {
  12568. // Already had this entry
  12569. delete checkClosureType;
  12570. }
  12571. useTypeInstance = closureTypeInst;
  12572. }
  12573. mModule->PopulateType(useTypeInstance);
  12574. if (delegateBindExpr->mTarget == NULL)
  12575. {
  12576. mModule->AssertErrorState();
  12577. return;
  12578. }
  12579. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  12580. // Do we need specialized calling code for this?
  12581. BfIRValue funcValue;
  12582. if (((needsSplat) || (implicitParamCount > 0) || (hasIncompatibleCallingConventions)) &&
  12583. (mModule->HasExecutedOutput()))
  12584. {
  12585. int fieldIdx = 0;
  12586. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  12587. {
  12588. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  12589. int gepIdx = fieldInst->mDataIdx;
  12590. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, gepIdx);
  12591. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  12592. if ((implicitParamIdx == -1) && (captureThisByValue))
  12593. {
  12594. if (fieldType->IsPointer())
  12595. fieldType = fieldType->GetUnderlyingType();
  12596. }
  12597. bool failed = false;
  12598. BfTypedValue lookupVal;
  12599. if (implicitParamIdx == -1)
  12600. lookupVal = target;
  12601. else
  12602. lookupVal = DoImplicitArgCapture(delegateBindExpr->mTarget, bindResult.mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_General, methodRefTarget);
  12603. if (!lookupVal)
  12604. continue;
  12605. if ((fieldType->IsPointer()) && (lookupVal.mType != fieldType))
  12606. {
  12607. BF_ASSERT(fieldType->GetUnderlyingType() == lookupVal.mType);
  12608. BF_ASSERT(lookupVal.IsAddr());
  12609. }
  12610. else if (!fieldType->IsRef())
  12611. lookupVal = mModule->LoadOrAggregateValue(lookupVal);
  12612. if (lookupVal)
  12613. mModule->mBfIRBuilder->CreateStore(lookupVal.mValue, fieldPtr);
  12614. fieldIdx++;
  12615. }
  12616. String methodName = _GetInvokeMethodName();
  12617. SizedArray<BfIRType, 8> irParamTypes;
  12618. BfIRType irReturnType;
  12619. bool hasThis = false;
  12620. if (hasCaptures)
  12621. {
  12622. hasThis = true;
  12623. methodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  12624. int thisIdx = 0;
  12625. if (GetStructRetIdx(methodInstance) == 0)
  12626. thisIdx = 1;
  12627. irParamTypes[thisIdx] = mModule->mBfIRBuilder->MapType(useTypeInstance);
  12628. }
  12629. else
  12630. {
  12631. BF_ASSERT(hasIncompatibleCallingConventions);
  12632. bindMethodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  12633. hasThis = bindMethodInstance->HasThis();
  12634. }
  12635. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  12636. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  12637. mModule->mBfIRBuilder->SaveDebugLocation();
  12638. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  12639. funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  12640. if (GetStructRetIdx(methodInstance) != -1)
  12641. {
  12642. mModule->mBfIRBuilder->Func_AddAttribute(funcValue, GetStructRetIdx(methodInstance) + 1, BfIRAttribute_NoAlias);
  12643. mModule->mBfIRBuilder->Func_AddAttribute(funcValue, GetStructRetIdx(methodInstance) + 1, BfIRAttribute_StructRet);
  12644. }
  12645. auto srcCallingConv = mModule->GetIRCallingConvention(methodInstance);
  12646. if ((!hasThis) && (methodInstance->mCallingConvention == BfCallingConvention_Stdcall))
  12647. srcCallingConv = BfIRCallingConv_StdCall;
  12648. else if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  12649. srcCallingConv = BfIRCallingConv_FastCall;
  12650. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  12651. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  12652. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  12653. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  12654. fieldIdx = 0;
  12655. SizedArray<BfIRValue, 8> irArgs;
  12656. int argIdx = 0;
  12657. if (GetStructRetIdx(bindMethodInstance) == 0)
  12658. {
  12659. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(GetStructRetIdx(methodInstance)));
  12660. argIdx++;
  12661. }
  12662. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  12663. {
  12664. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  12665. int gepIdx = fieldInst->mDataIdx;
  12666. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  12667. bool disableSplat = false;
  12668. if ((implicitParamIdx == -1) && (captureThisByValue))
  12669. {
  12670. if (fieldType->IsPointer())
  12671. {
  12672. fieldType = fieldType->GetUnderlyingType();
  12673. disableSplat = true;
  12674. }
  12675. }
  12676. int thisIdx = 0;
  12677. if (GetStructRetIdx(methodInstance) == 0)
  12678. thisIdx = 1;
  12679. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->GetArgument(thisIdx), 0, gepIdx);
  12680. BfTypedValue typedVal(fieldPtr, fieldType, true);
  12681. PushArg(typedVal, irArgs, disableSplat);
  12682. fieldIdx++;
  12683. }
  12684. if (hasThis)
  12685. argIdx++;
  12686. if (GetStructRetIdx(bindMethodInstance) == 1)
  12687. {
  12688. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(GetStructRetIdx(methodInstance)));
  12689. argIdx++;
  12690. }
  12691. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  12692. {
  12693. auto paramType = methodInstance->GetParamType(paramIdx);
  12694. if ((paramType->IsSplattable()) && (!IsComptime()))
  12695. {
  12696. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++)); }, paramType);
  12697. }
  12698. else if (!paramType->IsValuelessType())
  12699. {
  12700. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++));
  12701. }
  12702. }
  12703. auto bindFuncVal = bindResult.mFunc;
  12704. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!mModule->mIsComptimeModule))
  12705. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  12706. auto callInst = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  12707. if (GetStructRetIdx(bindMethodInstance) != -1)
  12708. mModule->mBfIRBuilder->Call_AddAttribute(callInst, GetStructRetIdx(bindMethodInstance) + 1, BfIRAttribute_StructRet);
  12709. auto destCallingConv = mModule->GetIRCallingConvention(bindMethodInstance);
  12710. if (destCallingConv != BfIRCallingConv_CDecl)
  12711. mModule->mBfIRBuilder->SetCallCallingConv(callInst, destCallingConv);
  12712. if ((methodInstance->mReturnType->IsValuelessType()) || (GetStructRetIdx(methodInstance) != -1))
  12713. {
  12714. mModule->mBfIRBuilder->CreateRetVoid();
  12715. }
  12716. else
  12717. {
  12718. mModule->mBfIRBuilder->CreateRet(callInst);
  12719. }
  12720. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  12721. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  12722. mModule->mBfIRBuilder->RestoreDebugLocation();
  12723. }
  12724. else if ((closureTypeInst != NULL) && (captureThisByValue))
  12725. {
  12726. // When we need to aggregrate a splat for a target, we just point out delegate's mTarget to inside ourselves where we aggregated the value
  12727. int dataIdx = 1;
  12728. if (!closureTypeInst->mFieldInstances.IsEmpty())
  12729. {
  12730. auto& fieldInst = closureTypeInst->mFieldInstances[0];
  12731. BF_ASSERT(fieldInst.GetFieldDef()->mName == "__this");
  12732. dataIdx = fieldInst.mDataIdx;
  12733. }
  12734. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, dataIdx);
  12735. target = mModule->LoadValue(target);
  12736. mModule->mBfIRBuilder->CreateStore(target.mValue, fieldPtr);
  12737. target = BfTypedValue(fieldPtr, target.mType, true);
  12738. }
  12739. BfResolvedArgs resolvedArgs;
  12740. MatchConstructor(delegateBindExpr, delegateBindExpr, mResult, useTypeInstance, resolvedArgs, false, BfMethodGenericArguments(), BfAllowAppendKind_No);
  12741. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  12742. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType, BfIRPopulateType_Full));
  12743. // >> delegate.mTarget = bindResult.mTarget
  12744. BfIRValue valPtr;
  12745. if (mModule->HasExecutedOutput())
  12746. {
  12747. if ((implicitParamCount > 0) || (needsSplat)) // Point back to self, it contains capture data
  12748. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12749. else if (bindResult.mTarget)
  12750. {
  12751. if ((target.mType->IsObjectOrInterface()) &&
  12752. (mModule->mCompiler->mOptions.mObjectHasDebugFlags) && (!mModule->mIsComptimeModule) &&
  12753. (mModule->mCompiler->mSystem->mPtrSize == 8))
  12754. {
  12755. auto numVal = mModule->mBfIRBuilder->CreatePtrToInt(target.mValue, BfTypeCode_UInt64);
  12756. auto orVal = mModule->mBfIRBuilder->CreateOr(numVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)0x8000000000000000ULL));
  12757. valPtr = mModule->mBfIRBuilder->CreateIntToPtr(orVal, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12758. }
  12759. else
  12760. valPtr = mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12761. }
  12762. else
  12763. valPtr = mModule->GetDefaultValue(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  12764. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 2);
  12765. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  12766. }
  12767. if (!funcValue)
  12768. {
  12769. funcValue = bindResult.mFunc;
  12770. if (!funcValue)
  12771. {
  12772. if ((mModule->HasExecutedOutput()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  12773. mModule->AssertErrorState();
  12774. return;
  12775. }
  12776. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!bindResult.mMethodInstance->mMethodDef->mIsVirtual) && (!mModule->mIsComptimeModule))
  12777. {
  12778. funcValue = mModule->mBfIRBuilder->RemapBindFunction(funcValue);
  12779. }
  12780. }
  12781. // >> delegate.mFuncPtr = bindResult.mFunc
  12782. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  12783. valPtr = mModule->mBfIRBuilder->CreateBitCast(funcValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  12784. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 1);
  12785. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  12786. }
  12787. void BfExprEvaluator::VisitLambdaBodies(BfAstNode* body, BfFieldDtorDeclaration* fieldDtor)
  12788. {
  12789. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  12790. mModule->VisitChild(blockBody);
  12791. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  12792. {
  12793. auto result = mModule->CreateValueFromExpression(bodyExpr);
  12794. if ((result) && (mModule->mCurMethodState->mClosureState != NULL) &&
  12795. (mModule->mCurMethodState->mClosureState->mReturnTypeInferState == BfReturnTypeInferState_Inferring))
  12796. mModule->mCurMethodState->mClosureState->mReturnType = result.mType;
  12797. }
  12798. while (fieldDtor != NULL)
  12799. {
  12800. mModule->mCurMethodState->mLeftBlockUncond = false;
  12801. mModule->VisitChild(fieldDtor->mBody);
  12802. fieldDtor = fieldDtor->mNextFieldDtor;
  12803. }
  12804. }
  12805. BfLambdaInstance* BfExprEvaluator::GetLambdaInstance(BfLambdaBindExpression* lambdaBindExpr, BfAllocTarget& allocTarget)
  12806. {
  12807. if (mModule->mCurMethodState == NULL)
  12808. return NULL;
  12809. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  12810. BfAstNodeList cacheNodeList;
  12811. cacheNodeList.mList.Add(lambdaBindExpr);
  12812. ///
  12813. {
  12814. auto checkMethodState = mModule->mCurMethodState;
  12815. while (checkMethodState != NULL)
  12816. {
  12817. if (checkMethodState->mMixinState != NULL)
  12818. cacheNodeList.mList.Add(checkMethodState->mMixinState->mSource);
  12819. checkMethodState = checkMethodState->mPrevMethodState;
  12820. }
  12821. }
  12822. bool isInferReturnType = (mBfEvalExprFlags & BfEvalExprFlags_InferReturnType) != 0;
  12823. BfLambdaInstance* lambdaInstance = NULL;
  12824. if ((!isInferReturnType) && (rootMethodState->mLambdaCache.TryGetValue(cacheNodeList, &lambdaInstance)))
  12825. return lambdaInstance;
  12826. static int sBindCount = 0;
  12827. sBindCount++;
  12828. bool isFunctionBind = false;
  12829. BfTypeInstance* delegateTypeInstance = NULL;
  12830. BfMethodInstance* invokeMethodInstance = NULL;
  12831. if (mExpectingType == NULL)
  12832. {
  12833. mModule->Fail("Cannot infer delegate type", lambdaBindExpr);
  12834. delegateTypeInstance = mModule->ResolveTypeDef(mModule->mCompiler->mActionTypeDef)->ToTypeInstance();
  12835. }
  12836. else
  12837. {
  12838. delegateTypeInstance = mExpectingType->ToTypeInstance();
  12839. if ((delegateTypeInstance == NULL) ||
  12840. ((!delegateTypeInstance->mTypeDef->mIsDelegate) && (!delegateTypeInstance->mTypeDef->mIsFunction)))
  12841. {
  12842. if (lambdaBindExpr->mFatArrowToken != NULL)
  12843. mModule->Fail("Can only bind lambdas to delegate types", lambdaBindExpr->mFatArrowToken);
  12844. delegateTypeInstance = mModule->ResolveTypeDef(mModule->mCompiler->mActionTypeDef)->ToTypeInstance();
  12845. }
  12846. else
  12847. {
  12848. invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  12849. }
  12850. isFunctionBind = delegateTypeInstance->mTypeDef->mIsFunction;
  12851. }
  12852. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(lambdaBindExpr->mNewToken))
  12853. {
  12854. if (isFunctionBind)
  12855. {
  12856. mModule->Fail("Function lambda binding does not require allocation", lambdaBindExpr->mNewToken);
  12857. }
  12858. else if (tokenNode->GetToken() == BfToken_Append)
  12859. {
  12860. mModule->Fail("Append allocation on delegate bind not supported", lambdaBindExpr->mNewToken);
  12861. }
  12862. }
  12863. if (invokeMethodInstance != NULL)
  12864. {
  12865. if ((int)lambdaBindExpr->mParams.size() < invokeMethodInstance->GetParamCount())
  12866. {
  12867. BfAstNode* refNode = lambdaBindExpr->mCloseParen;
  12868. if (refNode == NULL)
  12869. refNode = lambdaBindExpr;
  12870. mModule->Fail(StrFormat("Not enough parameters for delegate type '%s'. Expected %d more.",
  12871. mModule->TypeToString(delegateTypeInstance).c_str(), invokeMethodInstance->GetParamCount() - lambdaBindExpr->mParams.size()), refNode);
  12872. }
  12873. else if ((int)lambdaBindExpr->mParams.size() > invokeMethodInstance->GetParamCount())
  12874. {
  12875. BfAstNode* refNode = lambdaBindExpr->mParams[invokeMethodInstance->GetParamCount()];
  12876. mModule->Fail(StrFormat("Too many parameters for delegate type '%s'. Expected %d fewer.",
  12877. mModule->TypeToString(delegateTypeInstance).c_str(), lambdaBindExpr->mParams.size() - invokeMethodInstance->GetParamCount()), refNode);
  12878. }
  12879. }
  12880. auto autoComplete = GetAutoComplete();
  12881. bool wasCapturingMethodInfo = false;
  12882. if ((autoComplete != NULL) && (invokeMethodInstance != NULL))
  12883. {
  12884. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  12885. bool isAutocompleteNode = false;
  12886. if (lambdaBindExpr->mFatArrowToken != NULL)
  12887. {
  12888. if (autoComplete->IsAutocompleteNode(lambdaBindExpr, lambdaBindExpr->mFatArrowToken))
  12889. isAutocompleteNode = true;
  12890. }
  12891. else if (autoComplete->IsAutocompleteNode(lambdaBindExpr))
  12892. isAutocompleteNode = true;
  12893. if (isAutocompleteNode)
  12894. autoComplete->CheckInvocation(lambdaBindExpr, lambdaBindExpr->mOpenParen, lambdaBindExpr->mCloseParen, lambdaBindExpr->mCommas);
  12895. if (autoComplete->mIsCapturingMethodMatchInfo)
  12896. {
  12897. autoComplete->mMethodMatchInfo->mInstanceList.Clear();
  12898. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  12899. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  12900. methodMatchEntry.mTypeInstance = invokeMethodInstance->GetOwner();
  12901. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  12902. methodMatchEntry.mMethodDef = invokeMethodInstance->mMethodDef;
  12903. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  12904. methodMatchInfo->mBestIdx = 0;
  12905. methodMatchInfo->mMostParamsMatched = 0;
  12906. int cursorIdx = lambdaBindExpr->GetParser()->mCursorIdx;
  12907. if ((lambdaBindExpr->mCloseParen == NULL) || (cursorIdx <= lambdaBindExpr->mCloseParen->GetSrcStart()))
  12908. {
  12909. int paramIdx = 0;
  12910. for (int commaIdx = 0; commaIdx < (int)lambdaBindExpr->mCommas.size(); commaIdx++)
  12911. {
  12912. auto commaNode = lambdaBindExpr->mCommas[commaIdx];
  12913. if ((commaNode != NULL) && (cursorIdx >= commaNode->GetSrcStart()))
  12914. paramIdx = commaIdx + 1;
  12915. }
  12916. bool isEmpty = true;
  12917. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  12918. {
  12919. auto paramNode = lambdaBindExpr->mParams[paramIdx];
  12920. if (paramNode != NULL)
  12921. isEmpty = false;
  12922. }
  12923. if (isEmpty)
  12924. {
  12925. if (paramIdx < (int)invokeMethodInstance->GetParamCount())
  12926. {
  12927. String paramName = invokeMethodInstance->GetParamName(paramIdx);
  12928. autoComplete->mEntriesSet.Clear();
  12929. if (paramName.IsEmpty())
  12930. paramName += StrFormat("val%d", paramIdx + 1);
  12931. autoComplete->AddEntry(AutoCompleteEntry("paramName", paramName));
  12932. autoComplete->mInsertStartIdx = cursorIdx;
  12933. autoComplete->mInsertEndIdx = cursorIdx;
  12934. if ((paramIdx == 0) && (lambdaBindExpr->mParams.IsEmpty()))
  12935. {
  12936. String totalNames;
  12937. for (int checkIdx = 0; checkIdx < (int)invokeMethodInstance->GetParamCount(); checkIdx++)
  12938. {
  12939. if (!totalNames.IsEmpty())
  12940. totalNames += ", ";
  12941. String paramName = invokeMethodInstance->GetParamName(checkIdx);
  12942. if (paramName.IsEmpty())
  12943. paramName += StrFormat("val%d", checkIdx + 1);
  12944. totalNames += paramName;
  12945. }
  12946. autoComplete->AddEntry(AutoCompleteEntry("paramNames", totalNames));
  12947. }
  12948. }
  12949. }
  12950. }
  12951. }
  12952. }
  12953. defer
  12954. (
  12955. {
  12956. if (autoComplete != NULL)
  12957. autoComplete->mIsCapturingMethodMatchInfo = (wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo != NULL);
  12958. }
  12959. );
  12960. if (lambdaBindExpr->mBody == NULL)
  12961. {
  12962. mModule->AssertErrorState();
  12963. return NULL;
  12964. }
  12965. if ((lambdaBindExpr->mNewToken == NULL) && (isInferReturnType))
  12966. {
  12967. // Method ref, but let this follow infer route
  12968. }
  12969. else if ((lambdaBindExpr->mNewToken == NULL) || (isFunctionBind))
  12970. {
  12971. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  12972. {
  12973. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  12974. VisitLambdaBodies(lambdaBindExpr->mBody, lambdaBindExpr->mDtor);
  12975. }
  12976. if ((lambdaBindExpr->mNewToken != NULL) && (isFunctionBind))
  12977. mModule->Fail("Binds to functions should do not require allocations.", lambdaBindExpr->mNewToken);
  12978. if (lambdaBindExpr->mDtor != NULL)
  12979. {
  12980. mModule->Fail("Valueless method reference cannot contain destructor. Consider either removing destructor or using an allocated lambda.", lambdaBindExpr->mDtor->mTildeToken);
  12981. // Eat it
  12982. auto fieldDtor = lambdaBindExpr->mDtor;
  12983. while (fieldDtor != NULL)
  12984. {
  12985. mModule->VisitEmbeddedStatement(fieldDtor->mBody);
  12986. fieldDtor = fieldDtor->mNextFieldDtor;
  12987. }
  12988. }
  12989. if (invokeMethodInstance != NULL)
  12990. {
  12991. BfLocalMethod* localMethod = new BfLocalMethod();
  12992. localMethod->mMethodName = "anon";
  12993. localMethod->mSystem = mModule->mSystem;
  12994. localMethod->mModule = mModule;
  12995. localMethod->mExpectedFullName = mModule->GetLocalMethodName(localMethod->mMethodName, lambdaBindExpr->mFatArrowToken, mModule->mCurMethodState, mModule->mCurMethodState->mMixinState);
  12996. localMethod->mLambdaInvokeMethodInstance = invokeMethodInstance;
  12997. localMethod->mLambdaBindExpr = lambdaBindExpr;
  12998. localMethod->mDeclMethodState = mModule->mCurMethodState;
  12999. mModule->mContext->mLocalMethodGraveyard.push_back(localMethod);
  13000. auto moduleMethodInstance = mModule->GetLocalMethodInstance(localMethod, BfTypeVector());
  13001. if (moduleMethodInstance.mMethodInstance->mDisallowCalling)
  13002. {
  13003. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  13004. return NULL;
  13005. }
  13006. auto methodRefType = mModule->CreateMethodRefType(moduleMethodInstance.mMethodInstance);
  13007. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  13008. mModule->AddCallDependency(moduleMethodInstance.mMethodInstance);
  13009. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  13010. return NULL;
  13011. }
  13012. }
  13013. //SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites);
  13014. SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites || mModule->mCurMethodInstance->mIsUnspecialized);
  13015. BfTypeInstance* outerClosure = NULL;
  13016. if ((mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  13017. outerClosure = mModule->mCurMethodState->mClosureState->mClosureType;
  13018. Val128 val128(delegateTypeInstance->mTypeId);
  13019. bool isConstEval = ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  13020. BfMethodState methodState;
  13021. methodState.mPrevMethodState = mModule->mCurMethodState;
  13022. BfIRFunctionType funcType;
  13023. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  13024. SizedArray<BfIRType, 0> paramTypes;
  13025. funcType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), paramTypes, false);
  13026. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  13027. BF_ASSERT(prevInsertBlock || isConstEval);
  13028. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  13029. mModule->mBfIRBuilder->SaveDebugLocation();
  13030. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  13031. BfDeferredLocalAssignData deferredLocalAssignData;
  13032. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  13033. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData);
  13034. SetAndRestoreValue<BfMethodState*> prevMethodState(mModule->mCurMethodState, &methodState);
  13035. methodState.mIRHeadBlock = mModule->mBfIRBuilder->CreateBlock("head", true);
  13036. methodState.mIRInitBlock = mModule->mBfIRBuilder->CreateBlock("init", true);
  13037. methodState.mIREntryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  13038. methodState.mCurScope->mDIScope = prevMethodState.mPrevVal->mCurScope->mDIScope;//invokeMethodInstance->mDIFunction;
  13039. methodState.mCurLocalVarId = -1;
  13040. methodState.mIRFunction = prevMethodState.mPrevVal->mIRFunction;
  13041. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  13042. mModule->mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  13043. BfClosureState closureState;
  13044. if (delegateTypeInstance->IsDelegate())
  13045. closureState.mReturnType = mModule->GetDelegateReturnType(delegateTypeInstance);
  13046. else
  13047. closureState.mReturnType = mModule->mContext->mBfObjectType;
  13048. closureState.mCapturing = true;
  13049. if (delegateTypeInstance->IsDelegate())
  13050. closureState.mDelegateType = delegateTypeInstance;
  13051. closureState.mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  13052. methodState.mClosureState = &closureState;
  13053. closureState.mClosureType = outerClosure;
  13054. BF_ASSERT(methodState.mCurLocalVarId == -1);
  13055. int outerLocalsCount = (int)methodState.mLocals.size();
  13056. // static int sItrCount = 0;
  13057. // ++sItrCount;
  13058. // int itrCount = sItrCount;
  13059. // if ((itrCount == 8) || (itrCount == 10))
  13060. // {
  13061. // NOP;
  13062. // }
  13063. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  13064. HashContext hashCtx;
  13065. hashCtx.MixinStr(delegateTypeName);
  13066. BfSource* bfSource = delegateTypeInstance->mTypeDef->mSource;
  13067. BfMethodDef* methodDef = new BfMethodDef();
  13068. methodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  13069. Val128 closureMethodHash;
  13070. OwnedVector<BfParameterDeclaration> tempParamDecls;
  13071. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(lambdaBindExpr->mBody)))
  13072. {
  13073. // Don't show outer method match info when our cursor is inside a lambda expression (being passed as a parameter)
  13074. autoComplete->RemoveMethodMatchInfo();
  13075. }
  13076. if (invokeMethodInstance != NULL)
  13077. {
  13078. for (int paramIdx = 0; paramIdx < (int)invokeMethodInstance->GetParamCount(); paramIdx++)
  13079. {
  13080. BfLocalVariable* localVar = new BfLocalVariable();
  13081. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  13082. {
  13083. localVar->mName = lambdaBindExpr->mParams[paramIdx]->ToString();
  13084. localVar->mNameNode = lambdaBindExpr->mParams[paramIdx];
  13085. }
  13086. else
  13087. {
  13088. mModule->AssertErrorState();
  13089. localVar->mName = invokeMethodInstance->GetParamName(paramIdx);
  13090. }
  13091. localVar->mResolvedType = invokeMethodInstance->GetParamType(paramIdx);
  13092. mModule->PopulateType(localVar->mResolvedType);
  13093. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  13094. localVar->mReadFromId = 0;
  13095. auto rootMethodState = methodState.GetRootMethodState();
  13096. localVar->mLocalVarId = rootMethodState->mCurLocalVarId++;
  13097. mModule->DoAddLocalVariable(localVar);
  13098. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  13099. if (resolvePassData != NULL)
  13100. resolvePassData->HandleLocalReference(BfNodeDynCast<BfIdentifierNode>(localVar->mNameNode), mModule->mCurTypeInstance->mTypeDef,
  13101. mModule->mCurMethodInstance->mMethodDef, localVar->mLocalVarId);
  13102. }
  13103. for (int paramIdx = 0; paramIdx < (int)invokeMethodInstance->mMethodDef->mParams.size(); paramIdx++)
  13104. {
  13105. auto invokeParamDef = invokeMethodInstance->mMethodDef->mParams[paramIdx];
  13106. BfParameterDef* paramDef = new BfParameterDef();
  13107. paramDef->mParamDeclaration = tempParamDecls.Alloc();
  13108. BfAstNode::Zero(paramDef->mParamDeclaration);
  13109. paramDef->mTypeRef = invokeParamDef->mTypeRef;
  13110. paramDef->mParamKind = invokeParamDef->mParamKind;
  13111. if ((paramIdx < (int)lambdaBindExpr->mParams.size()) && (invokeMethodInstance->GetParamKind(paramIdx) != BfParamKind_DelegateParam))
  13112. {
  13113. //TODO: Not always correct if we have a 'params'
  13114. paramDef->mParamDeclaration->mNameNode = lambdaBindExpr->mParams[paramIdx];
  13115. paramDef->mName = paramDef->mParamDeclaration->mNameNode->ToString();
  13116. }
  13117. else
  13118. {
  13119. paramDef->mParamDeclaration->mNameNode = NULL;
  13120. paramDef->mName = invokeParamDef->mName;
  13121. }
  13122. methodDef->mParams.push_back(paramDef);
  13123. if (autoComplete != NULL)
  13124. autoComplete->CheckLocalDef(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), methodState.mLocals.back());
  13125. }
  13126. }
  13127. bool isAutocomplete = mModule->mCompiler->IsAutocomplete();
  13128. methodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  13129. methodDef->mBody = lambdaBindExpr->mBody;
  13130. ///
  13131. auto varMethodState = methodState.mPrevMethodState;
  13132. bool hasExplicitCaptureNames = false;
  13133. for (auto& captureEntry : allocTarget.mCaptureInfo->mCaptures)
  13134. {
  13135. if (captureEntry.mNameNode == NULL)
  13136. {
  13137. hasExplicitCaptureNames = false;
  13138. break;
  13139. }
  13140. hasExplicitCaptureNames = true;
  13141. }
  13142. auto _SetNotCapturedFlag = [&](bool notCaptured)
  13143. {
  13144. auto varMethodState = methodState.mPrevMethodState;
  13145. while (varMethodState != NULL)
  13146. {
  13147. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  13148. {
  13149. auto localVar = varMethodState->mLocals[localIdx];
  13150. localVar->mNotCaptured = notCaptured;
  13151. }
  13152. varMethodState = varMethodState->mPrevMethodState;
  13153. if (varMethodState == NULL)
  13154. break;
  13155. if (varMethodState->mMixinState != NULL)
  13156. break;
  13157. if (varMethodState->mClosureState != NULL)
  13158. {
  13159. if (!varMethodState->mClosureState->mCapturing)
  13160. break;
  13161. }
  13162. }
  13163. };
  13164. if (hasExplicitCaptureNames)
  13165. {
  13166. _SetNotCapturedFlag(true);
  13167. auto varMethodState = methodState.mPrevMethodState;
  13168. while (varMethodState != NULL)
  13169. {
  13170. for (auto& captureEntry : allocTarget.mCaptureInfo->mCaptures)
  13171. {
  13172. if (captureEntry.mNameNode != NULL)
  13173. {
  13174. StringT<64> captureName;
  13175. captureEntry.mNameNode->ToString(captureName);
  13176. BfLocalVarEntry* entry;
  13177. if (varMethodState->mLocalVarSet.TryGetWith<StringImpl&>(captureName, &entry))
  13178. {
  13179. auto localVar = entry->mLocalVar;
  13180. while (localVar != NULL)
  13181. {
  13182. if (autoComplete != NULL)
  13183. autoComplete->CheckLocalRef(captureEntry.mNameNode, localVar);
  13184. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  13185. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL))
  13186. {
  13187. if (auto captureIdentifierNode = BfNodeDynCast<BfIdentifierNode>(captureEntry.mNameNode))
  13188. mModule->mCompiler->mResolvePassData->HandleLocalReference(captureIdentifierNode, localVar->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVar->mLocalVarId);
  13189. }
  13190. localVar->mNotCaptured = false;
  13191. localVar = localVar->mShadowedLocal;
  13192. }
  13193. }
  13194. }
  13195. }
  13196. varMethodState = varMethodState->mPrevMethodState;
  13197. if (varMethodState == NULL)
  13198. break;
  13199. if (varMethodState->mMixinState != NULL)
  13200. break;
  13201. if (varMethodState->mClosureState != NULL)
  13202. {
  13203. if (!varMethodState->mClosureState->mCapturing)
  13204. break;
  13205. }
  13206. }
  13207. }
  13208. BfClosureInstanceInfo* closureInstanceInfo = new BfClosureInstanceInfo();
  13209. auto checkInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  13210. closureState.mCaptureStartAccessId = methodState.mPrevMethodState->GetRootMethodState()->mCurAccessId;
  13211. closureState.mCaptureVisitingBody = true;
  13212. closureState.mClosureInstanceInfo = closureInstanceInfo;
  13213. if ((mBfEvalExprFlags & BfEvalExprFlags_InferReturnType) != 0)
  13214. {
  13215. closureState.mReturnType = NULL;
  13216. closureState.mReturnTypeInferState = BfReturnTypeInferState_Inferring;
  13217. }
  13218. VisitLambdaBodies(lambdaBindExpr->mBody, lambdaBindExpr->mDtor);
  13219. if (hasExplicitCaptureNames)
  13220. _SetNotCapturedFlag(false);
  13221. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  13222. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  13223. {
  13224. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  13225. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  13226. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  13227. }
  13228. bool earlyExit = false;
  13229. if (isInferReturnType)
  13230. {
  13231. if ((closureState.mReturnTypeInferState == BfReturnTypeInferState_Fail) ||
  13232. (closureState.mReturnType == NULL))
  13233. {
  13234. mResult = BfTypedValue();
  13235. }
  13236. else
  13237. {
  13238. mResult = BfTypedValue(closureState.mReturnType);
  13239. }
  13240. earlyExit = true;
  13241. }
  13242. else if (mModule->mCurMethodInstance->mIsUnspecialized)
  13243. {
  13244. earlyExit = true;
  13245. mResult = mModule->GetDefaultTypedValue(delegateTypeInstance);
  13246. }
  13247. if (earlyExit)
  13248. {
  13249. prevIgnoreWrites.Restore();
  13250. mModule->mBfIRBuilder->RestoreDebugLocation();
  13251. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  13252. if (!prevInsertBlock.IsFake())
  13253. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  13254. delete methodDef;
  13255. delete closureInstanceInfo;
  13256. return NULL;
  13257. }
  13258. closureState.mCaptureVisitingBody = false;
  13259. prevIgnoreWrites.Restore();
  13260. mModule->mBfIRBuilder->RestoreDebugLocation();
  13261. auto _GetCaptureType = [&](const StringImpl& str, BfCaptureInfo::Entry** captureInfo = NULL)
  13262. {
  13263. if (allocTarget.mCaptureInfo->mCaptures.IsEmpty())
  13264. return BfCaptureType_Copy;
  13265. for (auto& captureEntry : allocTarget.mCaptureInfo->mCaptures)
  13266. {
  13267. if ((captureEntry.mNameNode == NULL) || (captureEntry.mNameNode->Equals(str)))
  13268. {
  13269. if (captureInfo != NULL)
  13270. *captureInfo = &captureEntry;
  13271. captureEntry.mUsed = true;
  13272. return captureEntry.mCaptureType;
  13273. }
  13274. }
  13275. return BfCaptureType_None;
  13276. };
  13277. Array<BfClosureCapturedEntry> capturedEntries;
  13278. bool copyOuterCaptures = false;
  13279. //
  13280. {
  13281. auto varMethodState = methodState.mPrevMethodState;
  13282. while (varMethodState != NULL)
  13283. {
  13284. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  13285. {
  13286. auto localVar = varMethodState->mLocals[localIdx];
  13287. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  13288. {
  13289. if ((localVar->mIsThis) && (outerClosure != NULL))
  13290. {
  13291. continue;
  13292. }
  13293. auto outerLocal = localVar;
  13294. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  13295. {
  13296. closureState.mConstLocals.push_back(*outerLocal);
  13297. continue;
  13298. }
  13299. BfClosureCapturedEntry capturedEntry;
  13300. auto capturedType = outerLocal->mResolvedType;
  13301. bool captureByRef = false;
  13302. BfCaptureInfo::Entry* captureInfoEntry = NULL;
  13303. auto captureType = _GetCaptureType(localVar->mName, &captureInfoEntry);
  13304. if (captureType == BfCaptureType_None)
  13305. {
  13306. continue;
  13307. }
  13308. if (!capturedType->IsRef())
  13309. {
  13310. if (captureType == BfCaptureType_Reference)
  13311. {
  13312. if ((localVar->mIsThis) && (!localVar->mResolvedType->IsValueType()))
  13313. {
  13314. // Just ignore attempting to capture referencetype 'this' by reference
  13315. }
  13316. else
  13317. captureByRef = true;
  13318. }
  13319. else if (captureType == BfCaptureType_Auto)
  13320. {
  13321. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  13322. captureByRef = true;
  13323. else if ((outerLocal->mResolvedType->mSize > 8) ||
  13324. ((localVar->mIsThis) && (outerLocal->mResolvedType->IsValueType())))
  13325. {
  13326. // Capture "large" values by reference
  13327. captureByRef = true;
  13328. }
  13329. }
  13330. }
  13331. else
  13332. {
  13333. bool allowRef = false;
  13334. if (captureType == BfCaptureType_Reference)
  13335. allowRef = true;
  13336. else if (captureType == BfCaptureType_Auto)
  13337. allowRef = localVar->mWrittenToId < closureState.mCaptureStartAccessId;
  13338. if (!allowRef)
  13339. {
  13340. capturedType = ((BfRefType*)capturedType)->mElementType;
  13341. }
  13342. }
  13343. if (captureByRef)
  13344. {
  13345. capturedType = mModule->CreateRefType(capturedType);
  13346. }
  13347. if (captureType != BfCaptureType_Copy)
  13348. capturedEntry.mExplicitlyByReference = true;
  13349. capturedEntry.mType = capturedType;
  13350. capturedEntry.mNameNode = outerLocal->mNameNode;
  13351. if (outerLocal->mName == "this")
  13352. capturedEntry.mName = "__this";
  13353. else
  13354. {
  13355. capturedEntry.mName = outerLocal->mName;
  13356. BfLocalVarEntry* entry = NULL;
  13357. if (varMethodState->mLocalVarSet.TryGetWith<StringImpl&>(capturedEntry.mName, &entry))
  13358. {
  13359. auto startCheckVar = entry->mLocalVar;
  13360. int shadowIdx = 0;
  13361. auto checkVar = startCheckVar;
  13362. while (checkVar != NULL)
  13363. {
  13364. if (checkVar == outerLocal)
  13365. {
  13366. // We only use mShadowIdx when we have duplicate name nodes (ie: in the case of for looks with iterator vs value)
  13367. auto shadowCheckVar = startCheckVar;
  13368. while (shadowCheckVar != checkVar)
  13369. {
  13370. if (shadowCheckVar->mNameNode == checkVar->mNameNode)
  13371. capturedEntry.mShadowIdx++;
  13372. shadowCheckVar = shadowCheckVar->mShadowedLocal;
  13373. }
  13374. for (int i = 0; i < shadowIdx; i++)
  13375. capturedEntry.mName.Insert(0, '@');
  13376. break;
  13377. }
  13378. shadowIdx++;
  13379. checkVar = checkVar->mShadowedLocal;
  13380. }
  13381. }
  13382. }
  13383. capturedEntries.Add(capturedEntry);
  13384. }
  13385. }
  13386. varMethodState = varMethodState->mPrevMethodState;
  13387. if (varMethodState == NULL)
  13388. break;
  13389. if (varMethodState->mMixinState != NULL)
  13390. break;
  13391. if (varMethodState->mClosureState != NULL)
  13392. {
  13393. if (!varMethodState->mClosureState->mCapturing)
  13394. break;
  13395. }
  13396. }
  13397. }
  13398. for (auto& captureEntry : allocTarget.mCaptureInfo->mCaptures)
  13399. {
  13400. if ((!captureEntry.mUsed) && (captureEntry.mNameNode != NULL))
  13401. mModule->Warn(0, "Capture specifier not used", captureEntry.mNameNode);
  13402. }
  13403. for (auto copyField : closureState.mReferencedOuterClosureMembers)
  13404. {
  13405. auto fieldDef = copyField->GetFieldDef();
  13406. auto captureType = _GetCaptureType(fieldDef->mName);
  13407. BfClosureCapturedEntry capturedEntry;
  13408. capturedEntry.mName = fieldDef->mName;
  13409. capturedEntry.mType = copyField->mResolvedType;
  13410. if ((captureType != BfCaptureType_Copy) && (capturedEntry.mType->IsRef()))
  13411. {
  13412. capturedEntry.mExplicitlyByReference = true;
  13413. }
  13414. else if ((captureType == BfCaptureType_Copy) && (capturedEntry.mType->IsRef()))
  13415. {
  13416. auto refType = (BfRefType*)capturedEntry.mType;
  13417. capturedEntry.mType = refType->mElementType;
  13418. }
  13419. else if ((captureType != BfCaptureType_Copy) && (!capturedEntry.mType->IsRef()) && (!fieldDef->mIsReadOnly))
  13420. {
  13421. capturedEntry.mType = mModule->CreateRefType(capturedEntry.mType);
  13422. }
  13423. }
  13424. std::sort(capturedEntries.begin(), capturedEntries.end());
  13425. bool hasCapture = false;
  13426. BfMethodInstanceGroup methodInstanceGroup;
  13427. methodInstanceGroup.mOwner = mModule->mCurTypeInstance;
  13428. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  13429. BfMethodInstance* methodInstance = new BfMethodInstance();
  13430. methodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13431. methodInstance->GetMethodInfoEx()->mClosureInstanceInfo = closureInstanceInfo;
  13432. if (invokeMethodInstance != NULL)
  13433. methodInstance->mParams = invokeMethodInstance->mParams;
  13434. methodInstance->mIsClosure = true;
  13435. // We want the closure ID to match between hot reloads -- otherwise we wouldn't be able to modify them,
  13436. // so we use the charId from the 'fat arrow' token
  13437. int closureId = 0;
  13438. if (lambdaBindExpr->mFatArrowToken != NULL)
  13439. closureId = lambdaBindExpr->mFatArrowToken->GetStartCharId();
  13440. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  13441. BF_ASSERT(curProject != NULL);
  13442. // We need to make these per-project even though you'd think we might not because we
  13443. // insert generic type specializations in the generic definition's project,
  13444. // BECAUSE: we would need to scan the captured fields the same way we scan the
  13445. // generic arguments to determine if each project can see it or not in the vdata
  13446. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  13447. BfClosureType* closureTypeInst = NULL;
  13448. // If we are allowing hot swapping we may add a capture later. We also need an equal method that ignores 'target' even when we're capturing ourself
  13449. if ((capturedEntries.size() != 0) || (lambdaBindExpr->mDtor != NULL) || (copyOuterCaptures) || (mModule->mCompiler->mOptions.mAllowHotSwapping) || (closureState.mCapturedDelegateSelf))
  13450. {
  13451. hashCtx.MixinStr(curProject->mName);
  13452. if (copyOuterCaptures)
  13453. {
  13454. hashCtx.Mixin(outerClosure->mTypeId);
  13455. }
  13456. for (auto& capturedEntry : capturedEntries)
  13457. {
  13458. hashCtx.Mixin(capturedEntry.mType->mTypeId);
  13459. hashCtx.MixinStr(capturedEntry.mName);
  13460. hashCtx.Mixin(capturedEntry.mExplicitlyByReference);
  13461. }
  13462. if (lambdaBindExpr->mDtor != NULL)
  13463. {
  13464. // Has DTOR thunk
  13465. bool hasDtorThunk = true;
  13466. hashCtx.Mixin(hasDtorThunk);
  13467. }
  13468. Val128 hash128 = hashCtx.Finish128();
  13469. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  13470. checkClosureType->mContext = mModule->mContext;
  13471. checkClosureType->mBaseType = delegateTypeInstance;
  13472. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_TypeDef);
  13473. closureTypeInst = (BfClosureType*)resolvedClosureType;
  13474. if (checkClosureType == resolvedClosureType)
  13475. {
  13476. // This is a new closure type
  13477. closureTypeInst->Init(curProject);
  13478. closureTypeInst->mTypeDef->mProject = curProject;
  13479. auto delegateDirectTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeDefReference>();
  13480. delegateDirectTypeRef->Init(mModule->mCompiler->mDelegateTypeDef);
  13481. closureTypeInst->mDirectAllocNodes.push_back(delegateDirectTypeRef);
  13482. BfMethodDef* methodDef = BfDefBuilder::AddMethod(closureTypeInst->mTypeDef, BfMethodType_Normal, BfProtection_Public, false, "Equals");
  13483. methodDef->mReturnTypeRef = mModule->mSystem->mDirectBoolTypeRef;
  13484. BfDefBuilder::AddParam(methodDef, delegateDirectTypeRef, "val");
  13485. methodDef->mIsVirtual = true;
  13486. methodDef->mIsOverride = true;
  13487. if (copyOuterCaptures)
  13488. {
  13489. for (auto& fieldInstance : outerClosure->mFieldInstances)
  13490. {
  13491. BfFieldDef* origFieldDef = fieldInstance.GetFieldDef();
  13492. BfFieldDef* fieldDef = closureTypeInst->AddField(fieldInstance.mResolvedType, origFieldDef->mName);
  13493. fieldDef->mIsReadOnly = origFieldDef->mIsReadOnly;
  13494. }
  13495. }
  13496. for (auto& capturedEntry : capturedEntries)
  13497. {
  13498. BfFieldDef* fieldDef = closureTypeInst->AddField(capturedEntry.mType, capturedEntry.mName);
  13499. if (!capturedEntry.mExplicitlyByReference)
  13500. fieldDef->mIsReadOnly = true;
  13501. }
  13502. if (lambdaBindExpr->mDtor != NULL)
  13503. {
  13504. auto dtorDef = closureTypeInst->AddDtor();
  13505. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  13506. auto voidPtrType = mModule->CreatePointerType(voidType);
  13507. closureTypeInst->AddField(voidPtrType, "__dtorThunk");
  13508. }
  13509. closureTypeInst->Finish();
  13510. }
  13511. else
  13512. {
  13513. // Already had this entry
  13514. delete checkClosureType;
  13515. }
  13516. useTypeInstance = closureTypeInst;
  13517. }
  13518. mModule->mBfIRBuilder->PopulateType(useTypeInstance);
  13519. mModule->PopulateType(useTypeInstance);
  13520. methodDef->mIsStatic = closureTypeInst == NULL;
  13521. SizedArray<BfIRType, 8> origParamTypes;
  13522. BfIRType origReturnType;
  13523. bool forceStatic = false;
  13524. if (invokeMethodInstance != NULL)
  13525. {
  13526. forceStatic = methodDef->mIsStatic;
  13527. auto invokeFunctionType = mModule->mBfIRBuilder->MapMethod(invokeMethodInstance);
  13528. invokeMethodInstance->GetIRFunctionInfo(mModule, origReturnType, origParamTypes, forceStatic);
  13529. }
  13530. else
  13531. {
  13532. origReturnType = mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_None));
  13533. }
  13534. SizedArray<BfIRType, 3> newTypes;
  13535. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) == 0))
  13536. newTypes.push_back(origParamTypes[0]);
  13537. if (!methodDef->mIsStatic)
  13538. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  13539. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) == 1))
  13540. newTypes.push_back(origParamTypes[1]);
  13541. int paramStartIdx = 0;
  13542. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) != -1))
  13543. paramStartIdx++;
  13544. if (!methodDef->mIsStatic)
  13545. paramStartIdx++;
  13546. for (int i = paramStartIdx; i < (int)origParamTypes.size(); i++)
  13547. newTypes.push_back(origParamTypes[i]);
  13548. auto closureFuncType = mModule->mBfIRBuilder->CreateFunctionType(origReturnType, newTypes, false);
  13549. prevMethodState.Restore();
  13550. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  13551. if ((prevInsertBlock) && (!prevInsertBlock.IsFake()))
  13552. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  13553. // Just a check
  13554. mModule->mBfIRBuilder->GetInsertBlock();
  13555. //auto rootMethodState = mModule->mCurMethodState;
  13556. HashContext closureHashCtx;
  13557. closureHashCtx.Mixin(closureId);
  13558. // When we're a nested lambda, strip off the outer hash and closureTypeInst markers
  13559. methodDef->mName = mModule->mCurMethodInstance->mMethodDef->mName;
  13560. int prevSepPos = (int)methodDef->mName.LastIndexOf('$');
  13561. if (prevSepPos != -1)
  13562. {
  13563. closureHashCtx.Mixin(methodDef->mName.c_str() + prevSepPos, (int)methodDef->mName.length() - prevSepPos);
  13564. methodDef->mName.RemoveToEnd(prevSepPos);
  13565. }
  13566. // Mix in this because this can be emitted multiple times when there's multiple ctors and field initializers with lambdas
  13567. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  13568. {
  13569. if (auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration))
  13570. {
  13571. if (ctorDecl->mThisToken != NULL)
  13572. closureHashCtx.Mixin(ctorDecl->mThisToken->GetStartCharId());
  13573. }
  13574. }
  13575. auto checkMethodState = mModule->mCurMethodState;
  13576. while (checkMethodState != NULL)
  13577. {
  13578. if (checkMethodState->mMethodInstance != NULL)
  13579. {
  13580. if (checkMethodState->mMethodInstance->mMethodInfoEx != NULL)
  13581. {
  13582. for (auto methodGenericArg : checkMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  13583. {
  13584. StringT<128> genericTypeName;
  13585. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  13586. closureHashCtx.MixinStr(genericTypeName);
  13587. }
  13588. }
  13589. }
  13590. checkMethodState = checkMethodState->mPrevMethodState;
  13591. }
  13592. uint64 closureHash = closureHashCtx.Finish64();
  13593. methodDef->mName += "$";
  13594. methodDef->mName += BfTypeUtils::HashEncode64(closureHash);
  13595. methodInstance->mMethodDef = methodDef;
  13596. if (invokeMethodInstance != NULL)
  13597. {
  13598. methodInstance->mParams = invokeMethodInstance->mParams;
  13599. methodInstance->mReturnType = invokeMethodInstance->mReturnType;
  13600. }
  13601. else
  13602. methodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  13603. StringT<128> closureFuncName;
  13604. BfMangler::Mangle(closureFuncName, mModule->mCompiler->GetMangleKind(), methodInstance);
  13605. auto closureFunc = mModule->mBfIRBuilder->CreateFunction(closureFuncType, BfIRLinkageType_External, closureFuncName);
  13606. methodInstance->mIRFunction = closureFunc;
  13607. if (methodInstance->mIsReified)
  13608. mModule->CheckHotMethod(methodInstance, closureFuncName);
  13609. if ((methodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  13610. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(methodInstance->mHotMethod);
  13611. methodState.Reset();
  13612. lambdaInstance = new BfLambdaInstance();
  13613. rootMethodState->mLambdaCache[cacheNodeList] = lambdaInstance;
  13614. lambdaInstance->mDelegateTypeInstance = delegateTypeInstance;
  13615. lambdaInstance->mUseTypeInstance = useTypeInstance;
  13616. lambdaInstance->mClosureTypeInstance = closureTypeInst;
  13617. lambdaInstance->mOuterClosure = outerClosure;
  13618. lambdaInstance->mCopyOuterCaptures = copyOuterCaptures;
  13619. lambdaInstance->mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  13620. lambdaInstance->mIsStatic = methodDef->mIsStatic;
  13621. lambdaInstance->mClosureFunc = closureFunc;
  13622. lambdaInstance->mMethodInstance = methodInstance;
  13623. lambdaInstance->mConstLocals = closureState.mConstLocals;
  13624. lambdaInstance->mParamDecls = tempParamDecls;
  13625. lambdaInstance->mDeclMixinState = mModule->mCurMethodState->mMixinState;
  13626. if (lambdaInstance->mDeclMixinState != NULL)
  13627. lambdaInstance->mDeclMixinState->mHasDeferredUsage = true;
  13628. tempParamDecls.ClearWithoutDeleting();
  13629. closureState.mCapturing = false;
  13630. closureState.mClosureType = useTypeInstance;
  13631. closureInstanceInfo->mThisOverride = useTypeInstance;
  13632. mModule->mIncompleteMethodCount++;
  13633. SetAndRestoreValue<BfClosureState*> prevClosureState(mModule->mCurMethodState->mClosureState, &closureState);
  13634. if (mModule->HasExecutedOutput())
  13635. mModule->SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  13636. // This keeps us from giving errors twice. ProcessMethod can give errors when we capture by value but needed to
  13637. // capture by reference, so we still need to do it for resolve-only
  13638. bool processMethods = (mModule->mCompiler->GetAutoComplete() == NULL) && !mModule->mHadBuildError;
  13639. mModule->mBfIRBuilder->SaveDebugLocation();
  13640. //
  13641. {
  13642. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  13643. if (mModule->mCompiler->mResolvePassData != NULL)
  13644. {
  13645. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  13646. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  13647. }
  13648. if (processMethods)
  13649. {
  13650. // If we are in an always-ignored block, we will have mIgnoreWrites set
  13651. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  13652. // mModule->ProcessMethod(methodInstance);
  13653. }
  13654. if (mModule->mCompiler->mResolvePassData != NULL)
  13655. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  13656. }
  13657. mModule->mBfIRBuilder->RestoreDebugLocation();
  13658. if (mModule->IsSkippingExtraResolveChecks())
  13659. closureFunc = BfIRFunction();
  13660. BfIRFunction dtorFunc;
  13661. if (lambdaBindExpr->mDtor != NULL)
  13662. {
  13663. SizedArray<BfIRType, 1> newTypes;
  13664. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  13665. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  13666. auto dtorFuncType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), newTypes, false);
  13667. BfMethodDef* dtorMethodDef = new BfMethodDef();
  13668. dtorMethodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  13669. dtorMethodDef->mName = "~this$";
  13670. dtorMethodDef->mName += methodDef->mName;
  13671. dtorMethodDef->mMethodType = BfMethodType_Normal;
  13672. dtorMethodDef->mBody = lambdaBindExpr->mDtor;
  13673. dtorMethodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  13674. BfMethodInstance* dtorMethodInstance = new BfMethodInstance();
  13675. dtorMethodInstance->mMethodDef = dtorMethodDef;
  13676. dtorMethodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  13677. dtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13678. StringT<128> dtorMangledName;
  13679. BfMangler::Mangle(dtorMangledName, mModule->mCompiler->GetMangleKind(), dtorMethodInstance);
  13680. dtorFunc = mModule->mBfIRBuilder->CreateFunction(dtorFuncType, BfIRLinkageType_External, dtorMangledName);
  13681. mModule->SetupIRMethod(NULL, dtorFunc, false);
  13682. dtorMethodInstance->mIRFunction = dtorFunc;
  13683. mModule->mIncompleteMethodCount++;
  13684. mModule->mBfIRBuilder->SaveDebugLocation();
  13685. //
  13686. if (processMethods)
  13687. {
  13688. // If we are in an always-ignored block, we will have mIgnoreWrites set
  13689. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  13690. // mModule->ProcessMethod(dtorMethodInstance);
  13691. }
  13692. mModule->mBfIRBuilder->RestoreDebugLocation();
  13693. if (mModule->IsSkippingExtraResolveChecks())
  13694. dtorFunc = BfIRFunction();
  13695. if (dtorMethodInstance->mIsReified)
  13696. mModule->CheckHotMethod(dtorMethodInstance, dtorMangledName);
  13697. if ((dtorMethodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  13698. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(dtorMethodInstance->mHotMethod);
  13699. lambdaInstance->mDtorMethodInstance = dtorMethodInstance;
  13700. lambdaInstance->mDtorFunc = dtorFunc;
  13701. dtorMethodInstance->mMethodInstanceGroup = NULL;
  13702. }
  13703. prevClosureState.Restore();
  13704. if ((prevInsertBlock) && (!prevInsertBlock.IsFake()))
  13705. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  13706. for (auto& capturedEntry : capturedEntries)
  13707. {
  13708. BfLambdaCaptureInfo lambdaCapture;
  13709. if (capturedEntry.mName == "__this")
  13710. lambdaCapture.mName = "this";
  13711. else
  13712. lambdaCapture.mName = capturedEntry.mName;
  13713. lambdaInstance->mCaptures.Add(lambdaCapture);
  13714. closureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  13715. }
  13716. if (processMethods)
  13717. rootMethodState->mDeferredLambdaInstances.Add(lambdaInstance);
  13718. methodInstance->mMethodInstanceGroup = NULL;
  13719. return lambdaInstance;
  13720. }
  13721. void BfExprEvaluator::Visit(BfLambdaBindExpression* lambdaBindExpr)
  13722. {
  13723. BfTokenNode* newToken = NULL;
  13724. BfCaptureInfo captureInfo;
  13725. BfAllocTarget allocTarget;
  13726. allocTarget.mCaptureInfo = &captureInfo;
  13727. ResolveAllocTarget(allocTarget, lambdaBindExpr->mNewToken, newToken);
  13728. if (mModule->mCurMethodInstance == NULL)
  13729. mModule->Fail("Invalid use of lambda bind expression", lambdaBindExpr);
  13730. if (((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mBlindCapturing)) ||
  13731. (mModule->mCurMethodInstance == NULL))
  13732. {
  13733. // We're just capturing. We just need to visit the bodies here. This helps infinite recursion with local methods containing lambdas calling each other
  13734. if (lambdaBindExpr->mBody != NULL)
  13735. mModule->VisitChild(lambdaBindExpr->mBody);
  13736. if ((lambdaBindExpr->mDtor != NULL) && (lambdaBindExpr->mDtor->mBody != NULL))
  13737. mModule->VisitChild(lambdaBindExpr->mDtor->mBody);
  13738. return;
  13739. }
  13740. BfLambdaInstance* lambdaInstance = GetLambdaInstance(lambdaBindExpr, allocTarget);
  13741. if (lambdaInstance == NULL)
  13742. return;
  13743. BfTypeInstance* delegateTypeInstance = lambdaInstance->mDelegateTypeInstance;
  13744. BfTypeInstance* useTypeInstance = lambdaInstance->mUseTypeInstance;
  13745. BfTypeInstance* closureTypeInst = lambdaInstance->mClosureTypeInstance;
  13746. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  13747. if (!delegateTypeInstance->IsDelegate())
  13748. {
  13749. mModule->AssertErrorState();
  13750. return;
  13751. }
  13752. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  13753. if (baseDelegateType == NULL)
  13754. {
  13755. mModule->Fail("Invalid delegate type", lambdaBindExpr);
  13756. return;
  13757. }
  13758. mModule->PopulateType(baseDelegateType);
  13759. auto& funcPtrField = baseDelegateType->mFieldInstances[0];
  13760. auto& targetField = baseDelegateType->mFieldInstances[1];
  13761. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType));
  13762. // >> delegate.mTarget = bindResult.mTarget
  13763. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  13764. BfIRValue valPtr;
  13765. if (!lambdaInstance->mIsStatic)
  13766. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  13767. else
  13768. valPtr = mModule->GetDefaultValue(nullPtrType);
  13769. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, targetField.mDataIdx);
  13770. mModule->mBfIRBuilder->CreateAlignedStore(valPtr, fieldPtr, targetField.mResolvedType->mAlign);
  13771. // >> delegate.mFuncPtr = bindResult.mFunc
  13772. if (lambdaInstance->mClosureFunc)
  13773. {
  13774. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  13775. auto valPtr = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mClosureFunc, mModule->mBfIRBuilder->MapType(nullPtrType));
  13776. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, funcPtrField.mDataIdx);
  13777. mModule->mBfIRBuilder->CreateAlignedStore(valPtr, fieldPtr, funcPtrField.mResolvedType->mAlign);
  13778. }
  13779. mModule->AddDependency(useTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  13780. // Copy captures into the delegate
  13781. if (lambdaInstance->mClosureTypeInstance != NULL)
  13782. {
  13783. int fieldIdx = 0;
  13784. if (lambdaInstance->mCopyOuterCaptures)
  13785. {
  13786. for (auto& fieldInstance : lambdaInstance->mOuterClosure->mFieldInstances)
  13787. {
  13788. if (!fieldInstance.mResolvedType->IsValuelessType())
  13789. {
  13790. BF_ASSERT(fieldInstance.mDataIdx == fieldIdx + 1);
  13791. auto localVar = mModule->mCurMethodState->mLocals[0];
  13792. auto capturedValue = mModule->mBfIRBuilder->CreateInBoundsGEP(localVar->mValue, 0, fieldInstance.mDataIdx);
  13793. capturedValue = mModule->mBfIRBuilder->CreateAlignedLoad(capturedValue, fieldInstance.mResolvedType->mAlign);
  13794. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance.mDataIdx);
  13795. mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  13796. fieldIdx++;
  13797. }
  13798. }
  13799. }
  13800. int captureIdx = 0;
  13801. for (int captureIdx = 0; captureIdx < (int)lambdaInstance->mCaptures.size(); captureIdx++)
  13802. {
  13803. auto& capturedEntry = lambdaInstance->mCaptures[captureIdx];
  13804. auto& closureCaptureEntry = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[captureIdx];
  13805. BfIdentifierNode* identifierNode = closureCaptureEntry.mNameNode;
  13806. BfIRValue capturedValue;
  13807. auto fieldInstance = &closureTypeInst->mFieldInstances[fieldIdx];
  13808. BfTypedValue capturedTypedVal;
  13809. if (identifierNode != NULL)
  13810. capturedTypedVal = DoImplicitArgCapture(NULL, identifierNode, closureCaptureEntry.mShadowIdx);
  13811. else
  13812. capturedTypedVal = LookupIdentifier(NULL, capturedEntry.mName);
  13813. if (!fieldInstance->mResolvedType->IsRef())
  13814. capturedTypedVal = mModule->LoadOrAggregateValue(capturedTypedVal);
  13815. else if (!capturedTypedVal.IsAddr())
  13816. capturedTypedVal = mModule->MakeAddressable(capturedTypedVal, false, true);
  13817. capturedValue = capturedTypedVal.mValue;
  13818. if (capturedValue)
  13819. {
  13820. if (!IsVar(capturedTypedVal.mType))
  13821. {
  13822. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance->mDataIdx);
  13823. mModule->mBfIRBuilder->CreateAlignedStore(capturedValue, fieldPtr, fieldInstance->mResolvedType->mAlign);
  13824. }
  13825. }
  13826. else
  13827. {
  13828. mModule->Fail(StrFormat("Unable to capture '%s'", capturedEntry.mName.c_str()), lambdaBindExpr);
  13829. mModule->AssertErrorState();
  13830. }
  13831. fieldIdx++;
  13832. }
  13833. if (lambdaInstance->mDtorFunc)
  13834. {
  13835. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, closureTypeInst->mFieldInstances[fieldIdx].mDataIdx);
  13836. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  13837. auto voidPtrType = mModule->CreatePointerType(voidType);
  13838. auto dtorThunk = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mDtorFunc, mModule->mBfIRBuilder->MapType(voidPtrType));
  13839. mModule->mBfIRBuilder->CreateAlignedStore(dtorThunk, fieldPtr, mModule->mSystem->mPtrSize);
  13840. fieldIdx++;
  13841. }
  13842. }
  13843. }
  13844. void BfExprEvaluator::ProcessArrayInitializer(BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, int dimensions, SizedArrayImpl<int64>& dimLengths, int dim, bool& hasFailed)
  13845. {
  13846. bool setSize = false;
  13847. if (dim == dimLengths.size())
  13848. {
  13849. dimLengths.push_back((int)valueExprs.size());
  13850. setSize = true;
  13851. }
  13852. else if (dimLengths[dim] == -1)
  13853. {
  13854. dimLengths[dim] = (int)valueExprs.size();
  13855. setSize = true;
  13856. }
  13857. int64 initCountDiff = (int)valueExprs.size() - dimLengths[dim];
  13858. if ((dimLengths[dim] != -1) && (initCountDiff != 0) && (!hasFailed))
  13859. {
  13860. if (initCountDiff > 0)
  13861. {
  13862. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[(int)dimLengths[dim]]);
  13863. hasFailed = true;
  13864. }
  13865. else
  13866. {
  13867. // If it ends with ", ?) or ",)" then allow unsized
  13868. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  13869. (commas.size() < valueExprs.size()))
  13870. {
  13871. BfAstNode* refNode = closeToken;
  13872. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  13873. refNode = mModule->mParentNodeEntry->mNode;
  13874. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  13875. hasFailed = true;
  13876. }
  13877. }
  13878. }
  13879. for (int i = 0; i < (int)valueExprs.size(); i++)
  13880. {
  13881. BfExpression* expr = valueExprs[i];
  13882. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(expr))
  13883. {
  13884. continue;
  13885. }
  13886. auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr);
  13887. if (dim < dimensions - 1)
  13888. {
  13889. if (innerInitExpr == NULL)
  13890. {
  13891. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(expr))
  13892. {
  13893. ProcessArrayInitializer(innerTupleExpr->mOpenParen, innerTupleExpr->mValues, innerTupleExpr->mCommas, innerTupleExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  13894. }
  13895. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  13896. {
  13897. SizedArray<BfExpression*, 1> values;
  13898. values.Add(parenExpr->mExpression);
  13899. SizedArray<BfTokenNode*, 1> commas;
  13900. ProcessArrayInitializer(parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  13901. }
  13902. else
  13903. {
  13904. hasFailed = true;
  13905. mModule->Fail("A nested array initializer is expected", expr);
  13906. continue;
  13907. }
  13908. }
  13909. else
  13910. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  13911. }
  13912. else if (innerInitExpr != NULL)
  13913. {
  13914. hasFailed = true;
  13915. mModule->Fail("Unexpected nested initializer", expr);
  13916. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  13917. }
  13918. else
  13919. {
  13920. //mModule->Fail("Expected initializer", )
  13921. }
  13922. }
  13923. }
  13924. void BfExprEvaluator::CheckObjectCreateTypeRef(BfType* expectingType, BfAstNode* afterNode)
  13925. {
  13926. auto autoComplete = GetAutoComplete();
  13927. if ((autoComplete != NULL) && (afterNode != NULL) && (autoComplete->mIsAutoComplete) &&
  13928. (afterNode->IsFromParser(mModule->mCompiler->mResolvePassData->mParsers[0])) &&
  13929. (afterNode->GetParser()->mCursorIdx == afterNode->GetSrcEnd() + 1))
  13930. {
  13931. BfType* expectingType = mExpectingType;
  13932. BfTypeInstance* expectingTypeInst = NULL;
  13933. if (mExpectingType != NULL)
  13934. {
  13935. expectingTypeInst = mExpectingType->ToTypeInstance();
  13936. }
  13937. if ((mExpectingType != NULL) && (((expectingTypeInst == NULL) || (!expectingTypeInst->mTypeDef->mIsDelegate))))
  13938. {
  13939. // Why were we doing this? It floods the autocomplete with every possible type
  13940. //autoComplete->AddTopLevelTypes(NULL);
  13941. autoComplete->mInsertStartIdx = afterNode->GetSourceData()->ToParser()->mCursorIdx;
  13942. BF_ASSERT(autoComplete->mInsertStartIdx != -1);
  13943. auto expectingType = mExpectingType;
  13944. while (expectingType->IsArray())
  13945. {
  13946. auto arrayType = (BfArrayType*)expectingType;
  13947. expectingType = arrayType->mGenericTypeInfo->mTypeGenericArguments[0];
  13948. }
  13949. auto expectingTypeInst = expectingType->ToTypeInstance();
  13950. if (expectingTypeInst != NULL)
  13951. {
  13952. if (!expectingTypeInst->IsAnonymous())
  13953. autoComplete->AddTypeInstanceEntry(expectingTypeInst);
  13954. }
  13955. else
  13956. autoComplete->mDefaultSelection = mModule->TypeToString(expectingType);
  13957. }
  13958. }
  13959. }
  13960. void BfExprEvaluator::Visit(BfObjectCreateExpression* objCreateExpr)
  13961. {
  13962. CreateObject(objCreateExpr, objCreateExpr->mNewNode, NULL, NULL);
  13963. }
  13964. void BfExprEvaluator::CreateObject(BfObjectCreateExpression* objCreateExpr, BfAstNode* allocNode, BfType* wantAllocType, BfInlineTypeReference* inlineTypeRef)
  13965. {
  13966. auto autoComplete = GetAutoComplete();
  13967. if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mTypeRef != NULL))
  13968. {
  13969. autoComplete->CheckTypeRef(objCreateExpr->mTypeRef, false, true);
  13970. }
  13971. if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mOpenToken != NULL) && (objCreateExpr->mCloseToken != NULL) &&
  13972. (objCreateExpr->mOpenToken->mToken == BfToken_LBrace) && (autoComplete->CheckFixit(objCreateExpr->mOpenToken)))
  13973. {
  13974. auto refNode = objCreateExpr->mOpenToken;
  13975. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  13976. if (parser != NULL)
  13977. {
  13978. autoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("Change initializer braces to parentheses\treformat|%s|%d-1|(\x01|%s|%d-1|)",
  13979. parser->mFileName.c_str(), refNode->mSrcStart,
  13980. parser->mFileName.c_str(), objCreateExpr->mCloseToken->mSrcStart).c_str()));
  13981. }
  13982. }
  13983. BfMethodGenericArguments methodGenericArguments;
  13984. if ((objCreateExpr != NULL) && (objCreateExpr->mCtorExplicit != NULL) && (objCreateExpr->mCtorExplicit->mGenericArgs != NULL))
  13985. methodGenericArguments.mArguments = &objCreateExpr->mCtorExplicit->mGenericArgs->mGenericArgs;
  13986. CheckObjectCreateTypeRef(mExpectingType, allocNode);
  13987. BfAttributeState attributeState;
  13988. attributeState.mTarget = BfAttributeTargets_Alloc;
  13989. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  13990. BfTokenNode* newToken = NULL;
  13991. BfAllocTarget allocTarget;
  13992. ResolveAllocTarget(allocTarget, allocNode, newToken, &attributeState.mCustomAttributes);
  13993. bool isStructAlloc = newToken == NULL;
  13994. bool isScopeAlloc = (newToken != NULL) && (newToken->GetToken() == BfToken_Scope);
  13995. bool isAppendAlloc = (newToken != NULL) && (newToken->GetToken() == BfToken_Append);
  13996. bool isStackAlloc = (isScopeAlloc) || (isStructAlloc);
  13997. bool isArrayAlloc = false;// (objCreateExpr->mArraySizeSpecifier != NULL);
  13998. bool isRawArrayAlloc = (objCreateExpr != NULL) && (objCreateExpr->mStarToken != NULL);
  13999. if ((objCreateExpr != NULL) && (objCreateExpr->mCtorExplicit != NULL) && (objCreateExpr->mCtorExplicit->mThisToken != NULL))
  14000. {
  14001. mModule->SetElementType(objCreateExpr->mCtorExplicit->mThisToken, BfSourceElementType_Method);
  14002. }
  14003. if (isScopeAlloc)
  14004. {
  14005. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  14006. {
  14007. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", allocNode);
  14008. }
  14009. if (allocNode == newToken) // Scope, no target specified
  14010. {
  14011. if (mModule->mParentNodeEntry != NULL)
  14012. {
  14013. if (auto assignExpr = BfNodeDynCastExact<BfAssignmentExpression>(mModule->mParentNodeEntry->mNode))
  14014. {
  14015. if (mModule->mCurMethodState->mCurScope->mCloseNode == NULL)
  14016. {
  14017. // If we are assigning this to a property then it's possible the property setter can actually deal with a temporary allocation so no warning in that case
  14018. if ((mBfEvalExprFlags & BfEvalExprFlags_PendingPropSet) == 0)
  14019. mModule->Warn(0, "This allocation will immediately go out of scope. Consider specifying a wider scope target such as 'scope::'", allocNode);
  14020. }
  14021. }
  14022. }
  14023. }
  14024. }
  14025. BfAutoParentNodeEntry autoParentNodeEntry(mModule, objCreateExpr);
  14026. SizedArray<BfAstNode*, 2> dimLengthRefs;
  14027. SizedArray<BfIRValue, 2> dimLengthVals;
  14028. BfArrayType* arrayType = NULL;
  14029. BfType* unresolvedTypeRef = NULL;
  14030. BfType* resolvedTypeRef = NULL;
  14031. if (wantAllocType != NULL)
  14032. {
  14033. unresolvedTypeRef = wantAllocType;
  14034. resolvedTypeRef = wantAllocType;
  14035. }
  14036. else if (objCreateExpr->mTypeRef == NULL)
  14037. {
  14038. if ((!mExpectingType) || (!mExpectingType->IsArray()))
  14039. {
  14040. mModule->Fail("Cannot imply array type. Explicitly state array type or use array in an assignment to an array type.", objCreateExpr);
  14041. resolvedTypeRef = mModule->mContext->mBfObjectType;
  14042. unresolvedTypeRef = resolvedTypeRef;
  14043. }
  14044. else
  14045. {
  14046. auto arrayType = (BfArrayType*)mExpectingType;
  14047. unresolvedTypeRef = arrayType->GetUnderlyingType();
  14048. resolvedTypeRef = unresolvedTypeRef;
  14049. }
  14050. }
  14051. else
  14052. {
  14053. if ((objCreateExpr->mTypeRef->IsExact<BfDotTypeReference>()) && (mExpectingType != NULL))
  14054. {
  14055. //mModule->SetElementType(objCreateExpr->mTypeRef, BfSourceElementType_TypeRef);
  14056. if ((mExpectingType->IsObject()) || (mExpectingType->IsGenericParam()))
  14057. {
  14058. unresolvedTypeRef = mExpectingType;
  14059. if (unresolvedTypeRef->IsArray())
  14060. {
  14061. arrayType = (BfArrayType*)unresolvedTypeRef;
  14062. unresolvedTypeRef = unresolvedTypeRef->GetUnderlyingType();
  14063. isArrayAlloc = true;
  14064. }
  14065. }
  14066. else if (mExpectingType->IsPointer())
  14067. {
  14068. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  14069. }
  14070. else if (mExpectingType->IsStruct())
  14071. {
  14072. unresolvedTypeRef = mExpectingType;
  14073. }
  14074. else if (mExpectingType->IsVar())
  14075. unresolvedTypeRef = mExpectingType;
  14076. }
  14077. if (unresolvedTypeRef == NULL)
  14078. {
  14079. if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  14080. {
  14081. isArrayAlloc = true;
  14082. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  14083. {
  14084. if ((mExpectingType != NULL) &&
  14085. ((mExpectingType->IsArray()) || (mExpectingType->IsPointer()) || (mExpectingType->IsSizedArray())))
  14086. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  14087. }
  14088. if (unresolvedTypeRef == NULL)
  14089. unresolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  14090. if (unresolvedTypeRef == NULL)
  14091. unresolvedTypeRef = mModule->GetPrimitiveType(BfTypeCode_Var);
  14092. int dimensions = 1;
  14093. bool commaExpected = false;
  14094. if (arrayTypeRef->mParams.size() != 0)
  14095. {
  14096. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  14097. for (auto arg : arrayTypeRef->mParams)
  14098. {
  14099. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  14100. {
  14101. if (tokenNode->GetToken() == BfToken_Comma)
  14102. {
  14103. if (isRawArrayAlloc)
  14104. {
  14105. mModule->Fail("Sized arrays cannot be multidimensional.", tokenNode);
  14106. continue;
  14107. }
  14108. dimensions++;
  14109. if (dimensions == 5)
  14110. {
  14111. mModule->Fail("Too many array dimensions, consider using a jagged array.", tokenNode);
  14112. }
  14113. commaExpected = false;
  14114. continue;
  14115. }
  14116. }
  14117. auto expr = BfNodeDynCast<BfExpression>(arg);
  14118. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  14119. {
  14120. mModule->CreateValueFromExpression(expr, intType);
  14121. continue;
  14122. }
  14123. dimLengthRefs.Add(expr);
  14124. BfTypedValue dimLength;
  14125. if (expr == NULL)
  14126. {
  14127. // Not specified
  14128. dimLengthVals.push_back(BfIRValue());
  14129. continue;
  14130. }
  14131. if (arg != NULL)
  14132. {
  14133. dimLength = mModule->CreateValueFromExpression(expr, intType, BfEvalExprFlags_NoCast);
  14134. BfCastFlags castFlags = BfCastFlags_None;
  14135. if ((dimLength) && (dimLength.mType->IsInteger()))
  14136. {
  14137. // Allow uint for size - just force to int
  14138. if (!((BfPrimitiveType*)dimLength.mType)->IsSigned())
  14139. castFlags = BfCastFlags_Explicit;
  14140. }
  14141. if (dimLength)
  14142. dimLength = mModule->Cast(expr, dimLength, intType, castFlags);
  14143. }
  14144. if (commaExpected)
  14145. {
  14146. mModule->AssertErrorState();
  14147. continue;
  14148. }
  14149. if (!dimLength)
  14150. {
  14151. dimLength = mModule->GetDefaultTypedValue(intType);
  14152. }
  14153. dimLengthVals.push_back(dimLength.mValue);
  14154. commaExpected = true;
  14155. }
  14156. }
  14157. if ((arrayTypeRef->mParams.size() == 0) && (objCreateExpr->mOpenToken == NULL))
  14158. mModule->Fail("Array size or array initializer expected", arrayTypeRef->mOpenBracket);
  14159. if (dimensions > 4)
  14160. dimensions = 4;
  14161. if ((!isRawArrayAlloc) && (!unresolvedTypeRef->IsVar()))
  14162. arrayType = mModule->CreateArrayType(unresolvedTypeRef, dimensions);
  14163. }
  14164. if (unresolvedTypeRef == NULL)
  14165. {
  14166. unresolvedTypeRef = ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  14167. }
  14168. }
  14169. resolvedTypeRef = unresolvedTypeRef;
  14170. if ((resolvedTypeRef != NULL) && (IsVar(resolvedTypeRef)))
  14171. resolvedTypeRef = unresolvedTypeRef;
  14172. }
  14173. if (inlineTypeRef != NULL)
  14174. {
  14175. auto inlineType = mModule->ResolveTypeRef(inlineTypeRef);
  14176. if (inlineType != NULL)
  14177. {
  14178. unresolvedTypeRef = inlineType;
  14179. resolvedTypeRef = inlineType;
  14180. }
  14181. }
  14182. if (resolvedTypeRef == NULL)
  14183. {
  14184. unresolvedTypeRef = mModule->GetPrimitiveType(BfTypeCode_Var);
  14185. resolvedTypeRef = unresolvedTypeRef;
  14186. }
  14187. auto resultType = resolvedTypeRef;
  14188. if ((resolvedTypeRef->IsInterface()) && (!isArrayAlloc))
  14189. {
  14190. mModule->Fail("Cannot create an instance of an interface", objCreateExpr->mTypeRef);
  14191. resolvedTypeRef = mModule->mContext->mBfObjectType;
  14192. }
  14193. BfTypeInstance* typeInstance = resolvedTypeRef->ToTypeInstance();
  14194. int elementSize = resolvedTypeRef->mSize;
  14195. int elementAlign = resolvedTypeRef->mAlign;
  14196. BfIRType allocType = mModule->mBfIRBuilder->MapType(resolvedTypeRef);
  14197. if (typeInstance != NULL)
  14198. {
  14199. if (!mModule->mCurTypeInstance->mResolvingVarField)
  14200. mModule->PopulateType(typeInstance);
  14201. if ((typeInstance->mTypeDef->mIsDelegate) && (!isArrayAlloc))
  14202. mModule->Fail("Delegates must be constructed through delegate binding", objCreateExpr->mTypeRef);
  14203. elementSize = BF_MAX(0, typeInstance->mInstSize);
  14204. elementAlign = typeInstance->mInstAlign;
  14205. allocType = mModule->mBfIRBuilder->MapTypeInst(typeInstance);
  14206. }
  14207. if (isAppendAlloc)
  14208. {
  14209. if (!mModule->mCurTypeInstance->IsObject())
  14210. {
  14211. mModule->Fail("Append allocations are only allowed in classes", allocNode);
  14212. isAppendAlloc = false;
  14213. }
  14214. else if ((mBfEvalExprFlags & BfEvalExprFlags_VariableDeclaration) == 0)
  14215. {
  14216. mModule->Fail("Append allocations are only allowed as local variable initializers in constructor body", allocNode);
  14217. isAppendAlloc = false;
  14218. }
  14219. else
  14220. {
  14221. auto methodDef = mModule->mCurMethodInstance->mMethodDef;
  14222. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14223. {
  14224. mModule->Fail("Append allocations are only allowed as local variable declarations in the main method body", allocNode);
  14225. isAppendAlloc = false;
  14226. }
  14227. else if (!methodDef->HasAppend())
  14228. {
  14229. mModule->Fail("Append allocations can only be used on constructors with [AllowAppend] specified", allocNode);
  14230. isAppendAlloc = false;
  14231. }
  14232. else if (methodDef->mMethodType != BfMethodType_Ctor)
  14233. {
  14234. mModule->Fail("Append allocations are only allowed in constructors", allocNode);
  14235. isAppendAlloc = false;
  14236. }
  14237. else if (methodDef->mIsStatic)
  14238. {
  14239. mModule->Fail("Append allocations are only allowed in non-static constructors", allocNode);
  14240. isAppendAlloc = false;
  14241. }
  14242. }
  14243. }
  14244. if (isArrayAlloc)
  14245. {
  14246. const int MAX_DIMENSIONS = 2;
  14247. int dimensions = 1;
  14248. if (arrayType != NULL)
  14249. {
  14250. dimensions = arrayType->mDimensions;
  14251. mModule->AddDependency(arrayType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  14252. }
  14253. bool zeroMemory = true;
  14254. if (objCreateExpr->mOpenToken != NULL)
  14255. {
  14256. if ((objCreateExpr->mArguments.size() == 1) &&
  14257. (BfNodeDynCastExact<BfUninitializedExpression>(objCreateExpr->mArguments[0]) != NULL))
  14258. {
  14259. // Special case for a single "{ ? }"
  14260. zeroMemory = false;
  14261. }
  14262. else
  14263. {
  14264. SizedArray<int64, 2> dimLengths;
  14265. if (dimLengthVals.size() != 0)
  14266. {
  14267. for (int dim = 0; dim < dimensions; dim++)
  14268. {
  14269. BfIRValue dimLengthVal;
  14270. if (dim < (int)dimLengthVals.size())
  14271. dimLengthVal = dimLengthVals[dim];
  14272. if (!dimLengthVal)
  14273. {
  14274. dimLengths.push_back(-1);
  14275. continue;
  14276. }
  14277. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVal);
  14278. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  14279. {
  14280. int64 dimLength = constant->mInt64;
  14281. if (dimLength < 0)
  14282. {
  14283. mModule->Fail(StrFormat("Invalid array dimension '%lld'", dimLength), dimLengthRefs[dim]);
  14284. dimLength = -1;
  14285. }
  14286. dimLengths.push_back(dimLength);
  14287. }
  14288. else if ((constant != NULL) && (constant->mConstType == BfConstType_Undef))
  14289. {
  14290. dimLengths.push_back(-1);
  14291. }
  14292. else
  14293. {
  14294. mModule->Fail("A constant length is required when using an initializer", dimLengthRefs[dim]);
  14295. dimLengths.push_back(-1);
  14296. }
  14297. }
  14298. }
  14299. // Ending in an ", )" means we need to zero-fill ending
  14300. zeroMemory = objCreateExpr->mCommas.size() >= objCreateExpr->mArguments.size();
  14301. bool hasFailed = false;
  14302. ProcessArrayInitializer(objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, dimensions, dimLengths, 0, hasFailed);
  14303. dimLengthVals.resize(dimLengths.size());
  14304. for (int i = 0; i < (int)dimLengthVals.size(); i++)
  14305. {
  14306. if (!dimLengthVals[i])
  14307. {
  14308. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  14309. dimLengthVals[i] = mModule->GetConstValue(dimLengths[i], intType);
  14310. }
  14311. }
  14312. }
  14313. }
  14314. while ((int)dimLengthVals.size() < dimensions)
  14315. dimLengthVals.push_back(mModule->GetConstValue(0));
  14316. BfTypedValue arrayValue;
  14317. BfIRValue arraySize;
  14318. for (BfIRValue dimSize : dimLengthVals)
  14319. {
  14320. if (!arraySize)
  14321. arraySize = dimSize;
  14322. else
  14323. arraySize = mModule->mBfIRBuilder->CreateMul(arraySize, dimSize);
  14324. }
  14325. BfAllocFlags allocFlags = BfAllocFlags_None;
  14326. if (isRawArrayAlloc)
  14327. allocFlags = (BfAllocFlags)(allocFlags | BfAllocFlags_RawArray);
  14328. int writeIdx = 0;
  14329. struct BfInitContext
  14330. {
  14331. public:
  14332. BfModule* mModule;
  14333. BfType* resultType;
  14334. int dimensions;
  14335. SizedArray<BfIRValue, 2>& dimLengthVals;
  14336. BfIRValue arraySize;
  14337. int& writeIdx;
  14338. BfInitContext(BfModule* module, BfType* resultType, int dimensions, SizedArray<BfIRValue, 2>& dimLengthVals, BfIRValue arraySize, int& writeIdx) :
  14339. mModule(module), resultType(resultType), dimensions(dimensions), dimLengthVals(dimLengthVals), arraySize(arraySize), writeIdx(writeIdx)
  14340. {
  14341. }
  14342. void Handle(BfIRValue addr, int curDim, const BfSizedArray<BfExpression*>& valueExprs)
  14343. {
  14344. int exprIdx = 0;
  14345. int dimWriteIdx = 0;
  14346. bool isUninit = false;
  14347. int dimLength = -1;
  14348. if (dimLengthVals[curDim].IsConst())
  14349. {
  14350. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[curDim]);
  14351. dimLength = constant->mInt32;
  14352. }
  14353. while (exprIdx < (int)valueExprs.size())
  14354. {
  14355. auto initExpr = valueExprs[exprIdx];
  14356. exprIdx++;
  14357. if (!initExpr)
  14358. break;
  14359. if (auto unintExpr = BfNodeDynCastExact<BfUninitializedExpression>(initExpr))
  14360. {
  14361. isUninit = true;
  14362. break;
  14363. }
  14364. if (exprIdx > dimLength)
  14365. break;
  14366. if (curDim < dimensions - 1)
  14367. {
  14368. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(initExpr))
  14369. {
  14370. Handle(addr, curDim + 1, innerTupleExpr->mValues);
  14371. }
  14372. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(initExpr))
  14373. {
  14374. SizedArray<BfExpression*, 1> values;
  14375. values.Add(parenExpr->mExpression);
  14376. Handle(addr, curDim + 1, values);
  14377. }
  14378. else if (auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(initExpr))
  14379. {
  14380. Handle(addr, curDim + 1, innerInitExpr->mValues);
  14381. }
  14382. dimWriteIdx++;
  14383. continue;
  14384. }
  14385. BfIRValue elemAddr;
  14386. if (!resultType->IsValuelessType())
  14387. elemAddr = mModule->CreateIndexedValue(resultType, addr, writeIdx);
  14388. else
  14389. elemAddr = mModule->mBfIRBuilder->GetFakeVal();
  14390. writeIdx++;
  14391. dimWriteIdx++;
  14392. BfTypedValue elemPtrTypedVal = BfTypedValue(elemAddr, resultType, BfTypedValueKind_Addr);
  14393. BfExprEvaluator exprEvaluator(mModule);
  14394. exprEvaluator.mExpectingType = resultType;
  14395. exprEvaluator.mReceivingValue = &elemPtrTypedVal;
  14396. exprEvaluator.Evaluate(initExpr);
  14397. exprEvaluator.GetResult();
  14398. if (exprEvaluator.mReceivingValue == NULL)
  14399. {
  14400. // We wrote directly to the array in-place, we're done with this element
  14401. continue;
  14402. }
  14403. auto storeValue = exprEvaluator.mResult;
  14404. if (!storeValue)
  14405. continue;
  14406. storeValue = mModule->Cast(initExpr, storeValue, resultType);
  14407. if (!storeValue)
  14408. continue;
  14409. if (!resultType->IsValuelessType())
  14410. {
  14411. storeValue = mModule->LoadOrAggregateValue(storeValue);
  14412. mModule->mBfIRBuilder->CreateStore(storeValue.mValue, elemAddr);
  14413. }
  14414. }
  14415. int clearFromIdx = writeIdx;
  14416. int sectionElemCount = 1;
  14417. BfIRValue numElemsLeft = arraySize;
  14418. if (dimLength != -1)
  14419. {
  14420. int clearCount = dimLength - dimWriteIdx;
  14421. if (clearCount > 0)
  14422. {
  14423. for (int checkDim = curDim + 1; checkDim < (int)dimLengthVals.size(); checkDim++)
  14424. {
  14425. if (dimLengthVals[checkDim].IsConst())
  14426. {
  14427. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[checkDim]);
  14428. clearCount *= constant->mInt32;
  14429. sectionElemCount *= constant->mInt32;
  14430. }
  14431. }
  14432. }
  14433. writeIdx += clearCount;
  14434. numElemsLeft = mModule->GetConstValue(clearCount);
  14435. }
  14436. // Actually leave it alone?
  14437. if ((isUninit) &&
  14438. ((mModule->IsOptimized()) || (mModule->mIsComptimeModule) || (mModule->mBfIRBuilder->mIgnoreWrites)))
  14439. return;
  14440. bool doClear = true;
  14441. if (numElemsLeft.IsConst())
  14442. {
  14443. auto constant = mModule->mBfIRBuilder->GetConstant(numElemsLeft);
  14444. doClear = constant->mInt64 > 0;
  14445. }
  14446. if (doClear)
  14447. {
  14448. // We multiply by GetStride. This relies on the fact that we over-allocate on the array allocation -- the last
  14449. // element doesn't need to be padded out to the element alignment, but we do anyway. Otherwise this would be
  14450. // a more complicated computation
  14451. auto clearBytes = mModule->mBfIRBuilder->CreateMul(numElemsLeft, mModule->GetConstValue(resultType->GetStride()));
  14452. if (isUninit)
  14453. {
  14454. // Limit to a reasonable number of bytes to stomp with 0xCC
  14455. int maxStompBytes = BF_MIN(128, resultType->GetStride() * sectionElemCount);
  14456. if (clearBytes.IsConst())
  14457. {
  14458. auto constant = mModule->mBfIRBuilder->GetConstant(clearBytes);
  14459. if (constant->mInt64 > maxStompBytes)
  14460. clearBytes = mModule->GetConstValue(maxStompBytes);
  14461. }
  14462. else
  14463. {
  14464. auto insertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  14465. auto gtBlock = mModule->mBfIRBuilder->CreateBlock("unint.gt");
  14466. auto contBlock = mModule->mBfIRBuilder->CreateBlock("unint.cont");
  14467. auto cmp = mModule->mBfIRBuilder->CreateCmpLTE(clearBytes, mModule->GetConstValue(maxStompBytes), true);
  14468. mModule->mBfIRBuilder->CreateCondBr(cmp, contBlock, gtBlock);
  14469. mModule->mBfIRBuilder->AddBlock(gtBlock);
  14470. mModule->mBfIRBuilder->SetInsertPoint(gtBlock);
  14471. mModule->mBfIRBuilder->CreateBr(contBlock);
  14472. mModule->mBfIRBuilder->AddBlock(contBlock);
  14473. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  14474. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_IntPtr)), 2);
  14475. mModule->mBfIRBuilder->AddPhiIncoming(phi, clearBytes, insertBlock);
  14476. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(maxStompBytes), gtBlock);
  14477. clearBytes = phi;
  14478. }
  14479. }
  14480. mModule->mBfIRBuilder->PopulateType(resultType);
  14481. if ((!resultType->IsValuelessType()) && (!addr.IsConst()))
  14482. {
  14483. mModule->mBfIRBuilder->CreateMemSet(mModule->CreateIndexedValue(resultType, addr, clearFromIdx),
  14484. mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, isUninit ? 0xCC : 0), clearBytes, resultType->mAlign);
  14485. }
  14486. }
  14487. }
  14488. };
  14489. BfInitContext initContext(mModule, resultType, dimensions, dimLengthVals, arraySize, writeIdx);
  14490. if (IsVar(resultType))
  14491. {
  14492. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  14493. mResult = BfTypedValue(BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), mModule->GetPrimitiveType(BfTypeCode_Var)));
  14494. initContext.Handle(mResult.mValue, 0, objCreateExpr->mArguments);
  14495. return;
  14496. }
  14497. if (isRawArrayAlloc)
  14498. {
  14499. // If we have a constant-sized alloc then make the type a pointer to the sized array, otherwise just a pointer to the raw type
  14500. BfType* ptrType = mModule->CreatePointerType(resultType);
  14501. if (isAppendAlloc)
  14502. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, false), ptrType);
  14503. else
  14504. {
  14505. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), ptrType);
  14506. }
  14507. initContext.Handle(arrayValue.mValue, 0, objCreateExpr->mArguments);
  14508. mResult = arrayValue;
  14509. return;
  14510. }
  14511. if (dimLengthVals.size() > 4)
  14512. {
  14513. dimLengthVals.RemoveRange(4, dimLengthVals.size() - 4);
  14514. mModule->Fail("Too many array dimensions, consider using a jagged array.", objCreateExpr);
  14515. }
  14516. if (arrayType == NULL)
  14517. return;
  14518. if (isAppendAlloc)
  14519. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, zeroMemory), arrayType);
  14520. else
  14521. {
  14522. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), arrayType);
  14523. if (isScopeAlloc)
  14524. {
  14525. // See notes below on "general" SkipObjectAccessCheck usage on why we can do this
  14526. mModule->SkipObjectAccessCheck(arrayValue);
  14527. }
  14528. }
  14529. //mModule->InitTypeInst(arrayValue, scopeData);
  14530. BfAstNode* refNode = objCreateExpr->mTypeRef;
  14531. while (true)
  14532. {
  14533. if (auto arrayRef = BfNodeDynCast<BfElementedTypeRef>(refNode))
  14534. {
  14535. refNode = arrayRef->mElementType;
  14536. continue;
  14537. }
  14538. break;
  14539. }
  14540. BfResolvedArgs resolvedArgs;
  14541. auto rawAutoComplete = mModule->mCompiler->GetAutoComplete();
  14542. if (rawAutoComplete != NULL)
  14543. {
  14544. SetAndRestoreValue<bool> prevCapturing(rawAutoComplete->mIsCapturingMethodMatchInfo, false);
  14545. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, methodGenericArguments, BfAllowAppendKind_No);
  14546. }
  14547. else
  14548. {
  14549. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, methodGenericArguments, BfAllowAppendKind_No);
  14550. }
  14551. //TODO: Assert 'length' var is at slot 1
  14552. mModule->PopulateType(arrayType->mBaseType, BfPopulateType_DataAndMethods);
  14553. mModule->mBfIRBuilder->PopulateType(arrayType);
  14554. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(arrayValue.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(arrayType->mBaseType));
  14555. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  14556. if (arrayLengthBitCount == 0)
  14557. {
  14558. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", objCreateExpr);
  14559. return;
  14560. }
  14561. mResult = arrayValue;
  14562. auto lengthFieldInstance = mModule->GetFieldByName(arrayType->mBaseType->ToTypeInstance(), "mLength");
  14563. if (lengthFieldInstance == NULL)
  14564. return;
  14565. auto firstElementFieldInstance = mModule->GetFieldByName(arrayType->ToTypeInstance(), "mFirstElement");
  14566. if (firstElementFieldInstance == NULL)
  14567. return;
  14568. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, lengthFieldInstance->mDataIdx);
  14569. if (arrayLengthBitCount == 64)
  14570. mModule->mBfIRBuilder->CreateAlignedStore(arraySize, addr, 8);
  14571. else
  14572. {
  14573. auto arraySize32 = mModule->mBfIRBuilder->CreateNumericCast(arraySize, true, BfTypeCode_Int32);
  14574. mModule->mBfIRBuilder->CreateAlignedStore(arraySize32, addr, 4);
  14575. }
  14576. for (int lowerDim = 1; lowerDim < (int)dimLengthVals.size(); lowerDim++)
  14577. {
  14578. auto length1FieldInstance = mModule->GetFieldByName(arrayType->ToTypeInstance(), "mLength1");
  14579. if (length1FieldInstance == NULL)
  14580. return;
  14581. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, length1FieldInstance->mDataIdx + lowerDim - 1);
  14582. auto lowerDimVal = mModule->mBfIRBuilder->CreateNumericCast(dimLengthVals[lowerDim], true, (arrayLengthBitCount == 64) ? BfTypeCode_Int64 : BfTypeCode_Int32);
  14583. mModule->mBfIRBuilder->CreateStore(lowerDimVal, addr);
  14584. }
  14585. if (resultType->IsValuelessType())
  14586. addr = mModule->mBfIRBuilder->GetFakeVal();
  14587. else
  14588. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, firstElementFieldInstance->mDataIdx);
  14589. initContext.Handle(addr, 0, objCreateExpr->mArguments);
  14590. return;
  14591. }
  14592. else
  14593. {
  14594. if (resolvedTypeRef->IsVar())
  14595. {
  14596. // Leave as a var
  14597. }
  14598. else if ((!resolvedTypeRef->IsObjectOrInterface()) && (!resolvedTypeRef->IsGenericParam()))
  14599. {
  14600. resultType = mModule->CreatePointerType(resolvedTypeRef);
  14601. }
  14602. }
  14603. if ((isStackAlloc) && (mModule->mCurMethodState == NULL))
  14604. {
  14605. mModule->Fail("Cannot use 'stack' here", allocNode);
  14606. isStackAlloc = false;
  14607. isScopeAlloc = false;
  14608. }
  14609. bool isGenericParam = unresolvedTypeRef->IsGenericParam();
  14610. if (resolvedTypeRef->IsGenericParam())
  14611. {
  14612. BfGenericParamFlags genericParamFlags = BfGenericParamFlag_None;
  14613. BfType* typeConstraint = NULL;
  14614. auto genericParam = mModule->GetMergedGenericParamData((BfGenericParamType*)resolvedTypeRef, genericParamFlags, typeConstraint);
  14615. if (typeConstraint == NULL)
  14616. {
  14617. if ((genericParamFlags & BfGenericParamFlag_Var) != 0)
  14618. {
  14619. // Allow it
  14620. }
  14621. else
  14622. {
  14623. if ((genericParamFlags & BfGenericParamFlag_New) == 0)
  14624. {
  14625. mModule->Fail(StrFormat("Must add 'where %s : new' constraint to generic parameter to instantiate type", genericParam->GetName().c_str()), objCreateExpr->mTypeRef);
  14626. }
  14627. if (objCreateExpr->mArguments.size() != 0)
  14628. {
  14629. mModule->Fail(StrFormat("Only default parameterless constructors can be called on generic argument '%s'", genericParam->GetName().c_str()), objCreateExpr->mTypeRef);
  14630. }
  14631. }
  14632. }
  14633. if (((typeConstraint != NULL) && (typeConstraint->IsValueType())) ||
  14634. ((genericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0))
  14635. {
  14636. resultType = mModule->CreatePointerType(resolvedTypeRef);
  14637. }
  14638. else if (((typeConstraint != NULL) && (!typeConstraint->IsValueType())) ||
  14639. ((genericParamFlags & (BfGenericParamFlag_Class)) != 0))
  14640. {
  14641. // Leave as 'T'
  14642. resultType = resolvedTypeRef;
  14643. }
  14644. else
  14645. resultType = mModule->CreateModifiedTypeType(resolvedTypeRef, BfToken_AllocType);
  14646. mResult.mType = resultType;
  14647. if (typeInstance == NULL)
  14648. {
  14649. mResult = mModule->GetDefaultTypedValue(resultType);
  14650. return;
  14651. }
  14652. }
  14653. else if (resolvedTypeRef->IsSizedArray())
  14654. {
  14655. // Handle the case of "int[3]* val = new .(1, 2, 3)"
  14656. if (auto dotTypeRef = BfNodeDynCastExact<BfDotTypeReference>(objCreateExpr->mTypeRef))
  14657. {
  14658. BfIRValue allocValue;
  14659. if (isAppendAlloc)
  14660. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, BfIRValue(), 0, BfIRValue(), 0, false, false);
  14661. else
  14662. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None);
  14663. auto result = BfTypedValue(allocValue, resolvedTypeRef, BfTypedValueKind_Addr);
  14664. InitializedSizedArray((BfSizedArrayType*)resolvedTypeRef, objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, &result);
  14665. // Turn from an addr of a sized array to pointer of sized array
  14666. mResult = BfTypedValue(mResult.mValue, resultType);
  14667. return;
  14668. }
  14669. }
  14670. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isGenericParam);
  14671. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  14672. {
  14673. mModule->Fail("Cannot create an instance of an abstract class", objCreateExpr->mTypeRef);
  14674. return;
  14675. }
  14676. BfFunctionBindResult bindResult;
  14677. bindResult.mSkipThis = true;
  14678. bindResult.mWantsArgs = true;
  14679. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, &bindResult);
  14680. BfIRValue appendSizeValue;
  14681. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeRef, resolvedTypeRef->IsStruct());
  14682. BfResolvedArgs argValues;
  14683. if (objCreateExpr != NULL)
  14684. {
  14685. argValues.Init(objCreateExpr->mOpenToken, &objCreateExpr->mArguments, &objCreateExpr->mCommas, objCreateExpr->mCloseToken);
  14686. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval); ////
  14687. }
  14688. if (typeInstance == NULL)
  14689. {
  14690. // No CTOR needed
  14691. if (objCreateExpr->mArguments.size() != 0)
  14692. {
  14693. mModule->Fail(StrFormat("Only default parameterless constructors can be called on primitive type '%s'", mModule->TypeToString(resolvedTypeRef).c_str()), objCreateExpr->mTypeRef);
  14694. }
  14695. }
  14696. else if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mOpenToken != NULL))
  14697. {
  14698. auto wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  14699. autoComplete->CheckInvocation(objCreateExpr, objCreateExpr->mOpenToken, objCreateExpr->mCloseToken, objCreateExpr->mCommas);
  14700. BfAstNode* refNode = objCreateExpr->mTypeRef;
  14701. if ((objCreateExpr->mCtorExplicit != NULL) && (objCreateExpr->mCtorExplicit->mThisToken != NULL))
  14702. refNode = objCreateExpr->mCtorExplicit->mThisToken;
  14703. auto checkTypeInst = typeInstance;
  14704. if (checkTypeInst->IsAnonymousInitializerType())
  14705. checkTypeInst = checkTypeInst->mBaseType;
  14706. MatchConstructor(refNode, objCreateExpr, emtpyThis, checkTypeInst, argValues, false, methodGenericArguments, BfAllowAppendKind_Infer);
  14707. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  14708. {
  14709. if (autoComplete->mMethodMatchInfo != NULL)
  14710. autoComplete->mIsCapturingMethodMatchInfo = true;
  14711. }
  14712. else
  14713. autoComplete->mIsCapturingMethodMatchInfo = false;
  14714. }
  14715. else if (!resolvedTypeRef->IsFunction())
  14716. {
  14717. auto refNode = allocNode;
  14718. if (objCreateExpr != NULL)
  14719. refNode = objCreateExpr->mTypeRef;
  14720. auto checkTypeInst = typeInstance;
  14721. if (checkTypeInst->IsAnonymousInitializerType())
  14722. checkTypeInst = checkTypeInst->mBaseType;
  14723. MatchConstructor(refNode, objCreateExpr, emtpyThis, checkTypeInst, argValues, false, methodGenericArguments, BfAllowAppendKind_Infer);
  14724. }
  14725. if (objCreateExpr != NULL)
  14726. mModule->ValidateAllocation(typeInstance, objCreateExpr->mTypeRef);
  14727. prevBindResult.Restore();
  14728. int allocAlign = resolvedTypeRef->mAlign;
  14729. if (typeInstance != NULL)
  14730. allocAlign = typeInstance->mInstAlign;
  14731. int appendAllocAlign = 0;
  14732. BfAllocFlags allocFlags = BfAllocFlags_None;
  14733. if ((bindResult.mMethodInstance != NULL) && (bindResult.mMethodInstance->mMethodDef->HasAppend()))
  14734. {
  14735. if (!bindResult.mFunc)
  14736. {
  14737. BF_ASSERT((!mModule->HasExecutedOutput()) || (mModule->mBfIRBuilder->mIgnoreWrites));
  14738. appendSizeValue = mModule->GetConstValue(0);
  14739. }
  14740. else
  14741. {
  14742. //auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  14743. BfTypeVector methodGenericArguments;
  14744. if (bindResult.mMethodInstance->mMethodInfoEx != NULL)
  14745. methodGenericArguments = bindResult.mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  14746. auto methodOwner = bindResult.mMethodInstance->GetOwner();
  14747. auto calcAppendMethodDef = methodOwner->mTypeDef->mMethods[bindResult.mMethodInstance->mMethodDef->mIdx + 1];
  14748. BF_ASSERT(calcAppendMethodDef->mName == BF_METHODNAME_CALCAPPEND);
  14749. auto calcAppendMethodModule = mModule->GetMethodInstance(methodOwner, calcAppendMethodDef, methodGenericArguments);
  14750. SizedArray<BfIRValue, 2> irArgs;
  14751. if (bindResult.mIRArgs.size() > 1)
  14752. irArgs.Insert(0, &bindResult.mIRArgs[1], bindResult.mIRArgs.size() - 1);
  14753. BfTypedValue appendSizeTypedValue = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, irArgs);
  14754. if (!appendSizeTypedValue)
  14755. {
  14756. BF_ASSERT(calcAppendMethodModule.mFunc);
  14757. appendSizeTypedValue = CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, irArgs);
  14758. BF_ASSERT(appendSizeTypedValue.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  14759. }
  14760. appendSizeValue = appendSizeTypedValue.mValue;
  14761. allocAlign = BF_MAX(allocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  14762. appendAllocAlign = calcAppendMethodModule.mMethodInstance->mAppendAllocAlign;
  14763. if (calcAppendMethodModule.mMethodInstance->mHasAppendWantMark)
  14764. allocFlags = (BfAllocFlags)(allocFlags | BfAllocFlags_HasAppendWantMark);
  14765. }
  14766. if (appendAllocAlign != 0)
  14767. {
  14768. int endingAlign = typeInstance->GetEndingInstanceAlignment();
  14769. if (endingAlign % appendAllocAlign != 0)
  14770. {
  14771. int extraSize = appendAllocAlign - (endingAlign % appendAllocAlign);
  14772. appendSizeValue = mModule->mBfIRBuilder->CreateAdd(appendSizeValue, mModule->GetConstValue(extraSize));
  14773. }
  14774. }
  14775. if ((allocFlags & BfAllocFlags_HasAppendWantMark) != 0)
  14776. {
  14777. int markInfoSize = sizeof(intptr) + sizeof(intptr) * 4; // Stack trace, MarkAppendEntry
  14778. appendSizeValue = mModule->mBfIRBuilder->CreateAdd(appendSizeValue, mModule->GetConstValue(markInfoSize));
  14779. }
  14780. }
  14781. // WTF? I'm not even sure this is correct - add more tests
  14782. appendAllocAlign = BF_MAX(appendAllocAlign, allocAlign);
  14783. BfIRValue allocValue;
  14784. if (IsVar(resolvedTypeRef))
  14785. {
  14786. mResult = mModule->GetDefaultTypedValue(resultType);
  14787. return;
  14788. }
  14789. else
  14790. {
  14791. if (isAppendAlloc)
  14792. {
  14793. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, appendSizeValue, appendAllocAlign);
  14794. }
  14795. else
  14796. {
  14797. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, appendSizeValue, BfIRValue(), 0, allocFlags, allocAlign);
  14798. }
  14799. if (((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) && (mModule->mCompiler->mCeMachine != NULL))
  14800. {
  14801. mModule->mCompiler->mCeMachine->SetAppendAllocInfo(mModule, allocValue, appendSizeValue);
  14802. }
  14803. mResult = BfTypedValue(allocValue, resultType);
  14804. }
  14805. if (isScopeAlloc)
  14806. {
  14807. // This allows readonly (ie: 'let') local usage to not require an access check. No matter what scope the alloc is tied to, the
  14808. // lifetime of the local variable will be no longer than that of the allocated value
  14809. mModule->SkipObjectAccessCheck(mResult);
  14810. }
  14811. /*if (typeInstance != NULL)
  14812. {
  14813. mModule->InitTypeInst(mResult, scopeData, true);
  14814. }
  14815. if (isStackAlloc)
  14816. {
  14817. mModule->AddStackAlloc(mResult, objCreateExpr, scopeData);
  14818. }*/
  14819. if (mResult)
  14820. {
  14821. if (bindResult.mMethodInstance == NULL)
  14822. {
  14823. // Why did we have this? It was already zeroed right?
  14824. // Zero
  14825. //mModule->mBfIRBuilder->CreateMemSet(mResult.mValue, mModule->GetConstValue8(0), mModule->GetConstValue(resolvedTypeRef->mSize), resolvedTypeRef->mAlign);
  14826. }
  14827. else if (bindResult.mFunc)
  14828. {
  14829. bool hasRealtimeLeakCheck = (mModule->mCompiler->mOptions.mEnableRealtimeLeakCheck) && (!IsComptime());
  14830. if ((typeInstance->IsObject()) || (typeInstance->IsAnonymousInitializerType()))
  14831. {
  14832. bool wantsCtorClear = true;
  14833. if (hasRealtimeLeakCheck)
  14834. {
  14835. // Dbg_ObjectAlloc clears internally so we don't need to call CtorClear for those
  14836. if ((!isStackAlloc) && (!isAppendAlloc) && (!allocTarget.mCustomAllocator) && (allocTarget.mScopedInvocationTarget == NULL))
  14837. wantsCtorClear = false;
  14838. }
  14839. if (wantsCtorClear)
  14840. {
  14841. auto ctorClear = mModule->GetMethodByName(typeInstance, "__BfCtorClear");
  14842. if (!ctorClear)
  14843. {
  14844. mModule->AssertErrorState();
  14845. }
  14846. else if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) == 0)
  14847. {
  14848. SizedArray<BfIRValue, 1> irArgs;
  14849. irArgs.push_back(mResult.mValue);
  14850. CreateCall(objCreateExpr, ctorClear.mMethodInstance, ctorClear.mFunc, false, irArgs);
  14851. }
  14852. }
  14853. }
  14854. if (typeInstance->IsObject())
  14855. {
  14856. if ((!mModule->mIsComptimeModule) && (isStackAlloc) && (hasRealtimeLeakCheck))
  14857. {
  14858. BfMethodInstance* markMethod = mModule->GetRawMethodByName(mModule->mContext->mBfObjectType, "GCMarkMembers");
  14859. BF_ASSERT(markMethod != NULL);
  14860. if (markMethod != NULL)
  14861. {
  14862. auto& vtableEntry = typeInstance->mVirtualMethodTable[markMethod->mVirtualTableIdx];
  14863. if (vtableEntry.mImplementingMethod.mTypeInstance != mModule->mContext->mBfObjectType)
  14864. {
  14865. auto impMethodInstance = (BfMethodInstance*)vtableEntry.mImplementingMethod;
  14866. bool needsCall = false;
  14867. if (allocFlags & BfAllocFlags_HasAppendWantMark)
  14868. needsCall = true;
  14869. if (!needsCall)
  14870. {
  14871. if (impMethodInstance != NULL)
  14872. {
  14873. needsCall = impMethodInstance->mMethodDef->mBody != NULL;
  14874. }
  14875. else
  14876. {
  14877. needsCall = true;
  14878. BF_ASSERT(vtableEntry.mImplementingMethod.mKind == BfMethodRefKind_AmbiguousRef);
  14879. }
  14880. }
  14881. if (!needsCall)
  14882. {
  14883. if (typeInstance->HasAppendedField(true))
  14884. needsCall = true;
  14885. }
  14886. if (needsCall)
  14887. {
  14888. SizedArray<BfIRValue, 1> irArgs;
  14889. irArgs.push_back(mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(mModule->mContext->mBfObjectType)));
  14890. auto gcType = mModule->ResolveTypeDef(mModule->mCompiler->mGCTypeDef);
  14891. BF_ASSERT(gcType != NULL);
  14892. if (gcType != NULL)
  14893. {
  14894. auto addStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "AddStackMarkableObject", 1);
  14895. BF_ASSERT(addStackObjMethod);
  14896. if (addStackObjMethod)
  14897. {
  14898. mModule->mBfIRBuilder->CreateCall(addStackObjMethod.mFunc, irArgs);
  14899. }
  14900. auto removeStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "RemoveStackMarkableObject", 1);
  14901. BF_ASSERT(removeStackObjMethod);
  14902. if (removeStackObjMethod)
  14903. {
  14904. mModule->AddDeferredCall(removeStackObjMethod, irArgs, allocTarget.mScopeData, allocNode);
  14905. }
  14906. }
  14907. }
  14908. }
  14909. }
  14910. }
  14911. }
  14912. auto origThisTypedValue = mResult;
  14913. auto thisTypedValue = mResult;
  14914. if (inlineTypeRef != NULL)
  14915. {
  14916. BfType* wantType = bindResult.mMethodInstance->GetOwner();
  14917. if (thisTypedValue.mType->IsPointer())
  14918. wantType = mModule->CreatePointerType(wantType);
  14919. thisTypedValue = mModule->Cast(allocNode, thisTypedValue, wantType);
  14920. }
  14921. if ((bindResult.mMethodInstance->mMethodDef->HasAppend()) && (mResult.mType->IsObject()))
  14922. {
  14923. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14924. auto typeInst = mResult.mType->ToTypeInstance();
  14925. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  14926. BfIRValue intPtrVal = mModule->CreateAlloca(intPtrType);
  14927. auto intPtrThisVal = mModule->mBfIRBuilder->CreatePtrToInt(thisTypedValue.mValue, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  14928. auto curValPtr = mModule->mBfIRBuilder->CreateAdd(intPtrThisVal, mModule->GetConstValue(typeInst->mInstSize, intPtrType));
  14929. mModule->mBfIRBuilder->CreateStore(curValPtr, intPtrVal);
  14930. bindResult.mIRArgs[0] = intPtrVal;
  14931. }
  14932. if (!typeInstance->IsValuelessType())
  14933. bindResult.mIRArgs.Insert(0, thisTypedValue.mValue);
  14934. auto result = CreateCall(objCreateExpr, bindResult.mMethodInstance, bindResult.mFunc, false, bindResult.mIRArgs);
  14935. if ((result) && (!result.mType->IsVoid()))
  14936. mResult = result;
  14937. if (origThisTypedValue.mType != thisTypedValue.mType)
  14938. {
  14939. auto origThisType = origThisTypedValue.mType;
  14940. if (origThisType->IsPointer())
  14941. origThisType = origThisType->GetUnderlyingType();
  14942. auto origThisTypeInst = origThisType->ToTypeInstance();
  14943. if (origThisTypeInst != NULL)
  14944. {
  14945. BF_ASSERT(origThisTypeInst->IsAnonymousInitializerType());
  14946. auto ctorMethod = mModule->GetMethodByName(origThisTypeInst, "__BfCtor", 0);
  14947. if (!ctorMethod)
  14948. {
  14949. mModule->AssertErrorState();
  14950. }
  14951. else if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) == 0)
  14952. {
  14953. SizedArray<BfIRValue, 1> irArgs;
  14954. irArgs.push_back(origThisTypedValue.mValue);
  14955. CreateCall(objCreateExpr, ctorMethod.mMethodInstance, ctorMethod.mFunc, false, irArgs);
  14956. }
  14957. }
  14958. }
  14959. }
  14960. }
  14961. if (((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) && (mModule->mCompiler->mCeMachine != NULL))
  14962. {
  14963. mModule->mCompiler->mCeMachine->ClearAppendAllocInfo();
  14964. }
  14965. if ((mResult) && (isStructAlloc))
  14966. {
  14967. if (mResult.mType->IsPointer())
  14968. {
  14969. mResult = mModule->LoadValue(mResult);
  14970. mResult = BfTypedValue(mResult.mValue, mResult.mType->GetUnderlyingType(), true);
  14971. }
  14972. else
  14973. mModule->Fail(StrFormat("Allocation specifier such as 'new' is required for reference type '%s'", mModule->TypeToString(mResult.mType).c_str()), objCreateExpr);
  14974. }
  14975. }
  14976. void BfExprEvaluator::Visit(BfBoxExpression* boxExpr)
  14977. {
  14978. /*if ((boxExpr->mAllocNode == NULL) || (boxExpr->mExpression == NULL))
  14979. {
  14980. mModule->AssertErrorState();
  14981. return;
  14982. }*/
  14983. BfTokenNode* newToken = NULL;
  14984. BfAllocTarget allocTarget;
  14985. ResolveAllocTarget(allocTarget, boxExpr->mAllocNode, newToken);
  14986. if ((boxExpr->mAllocNode != NULL) && (boxExpr->mAllocNode->mToken == BfToken_Scope))
  14987. {
  14988. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  14989. {
  14990. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", boxExpr->mAllocNode);
  14991. }
  14992. }
  14993. if (boxExpr->mExpression == NULL)
  14994. {
  14995. mModule->AssertErrorState();
  14996. return;
  14997. }
  14998. auto exprValue = mModule->CreateValueFromExpression(boxExpr->mExpression);
  14999. if (exprValue)
  15000. {
  15001. bool doFail = false;
  15002. bool doWarn = false;
  15003. BfType* boxedType = NULL;
  15004. if (exprValue.mType->IsGenericParam())
  15005. {
  15006. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  15007. auto genericParamTarget = (BfGenericParamType*)exprValue.mType;
  15008. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  15009. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class)) == BfGenericParamFlag_Class)
  15010. doWarn = true;
  15011. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsObjectOrInterface()))
  15012. doWarn = true;
  15013. boxedType = mModule->mContext->mBfObjectType;
  15014. }
  15015. else
  15016. {
  15017. doFail = !exprValue.mType->IsValueTypeOrValueTypePtr();
  15018. doWarn = exprValue.mType->IsObjectOrInterface();
  15019. }
  15020. if (doWarn)
  15021. {
  15022. mModule->Warn(0, StrFormat("Boxing is unnecessary since type '%s' is already a reference type.", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  15023. mResult = exprValue;
  15024. return;
  15025. }
  15026. if (doFail)
  15027. {
  15028. mModule->Fail(StrFormat("Box target '%s' must be a value type or pointer to a value type", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  15029. return;
  15030. }
  15031. if (boxedType == NULL)
  15032. boxedType = mModule->CreateBoxedType(exprValue.mType);
  15033. if (boxedType == NULL)
  15034. boxedType = mModule->mContext->mBfObjectType;
  15035. mResult = mModule->BoxValue(boxExpr->mExpression, exprValue, boxedType, allocTarget);
  15036. if (!mResult)
  15037. {
  15038. mModule->Fail(StrFormat("Type '%s' is not boxable", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  15039. return;
  15040. }
  15041. }
  15042. }
  15043. void BfExprEvaluator::ResolveAllocTarget(BfAllocTarget& allocTarget, BfAstNode* allocNode, BfTokenNode*& newToken, BfCustomAttributes** outCustomAttributes)
  15044. {
  15045. auto autoComplete = GetAutoComplete();
  15046. BfAttributeDirective* attributeDirective = NULL;
  15047. allocTarget.mRefNode = allocNode;
  15048. newToken = BfNodeDynCast<BfTokenNode>(allocNode);
  15049. if (allocNode == NULL)
  15050. {
  15051. // Scope
  15052. if (mModule->mCurMethodState != NULL)
  15053. allocTarget.mScopeData = mModule->mCurMethodState->mCurScope->GetTargetable();
  15054. }
  15055. else if (newToken == NULL)
  15056. {
  15057. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(allocNode))
  15058. {
  15059. newToken = scopeNode->mScopeToken;
  15060. allocTarget.mScopeData = mModule->FindScope(scopeNode->mTargetNode, true);
  15061. if (autoComplete != NULL)
  15062. {
  15063. auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(scopeNode->mTargetNode);
  15064. if ((scopeNode->mTargetNode == NULL) || (targetIdentifier != NULL))
  15065. autoComplete->CheckLabel(targetIdentifier, scopeNode->mColonToken, allocTarget.mScopeData);
  15066. }
  15067. attributeDirective = scopeNode->mAttributes;
  15068. }
  15069. if (auto newNode = BfNodeDynCast<BfNewNode>(allocNode))
  15070. {
  15071. newToken = newNode->mNewToken;
  15072. if (auto allocExpr = BfNodeDynCast<BfExpression>(newNode->mAllocNode))
  15073. {
  15074. allocTarget.mCustomAllocator = mModule->CreateValueFromExpression(allocExpr);
  15075. allocTarget.mRefNode = allocExpr;
  15076. }
  15077. else if (auto scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(newNode->mAllocNode))
  15078. {
  15079. allocTarget.mScopedInvocationTarget = scopedInvocationTarget;
  15080. }
  15081. attributeDirective = newNode->mAttributes;
  15082. }
  15083. }
  15084. else if (newToken->GetToken() == BfToken_Scope)
  15085. {
  15086. if (mModule->mCurMethodState != NULL)
  15087. allocTarget.mScopeData = mModule->mCurMethodState->mCurScope->GetTargetable();
  15088. }
  15089. if (attributeDirective != NULL)
  15090. {
  15091. auto customAttrs = mModule->GetCustomAttributes(attributeDirective, BfAttributeTargets_Alloc, BfGetCustomAttributesFlags_AllowNonConstArgs, allocTarget.mCaptureInfo);
  15092. if (customAttrs != NULL)
  15093. {
  15094. for (auto& attrib : customAttrs->mAttributes)
  15095. {
  15096. if (attrib.mType->IsInstanceOf(mModule->mCompiler->mAlignAttributeTypeDef))
  15097. {
  15098. allocTarget.mAlignOverride = 16; // System conservative default
  15099. if (!attrib.mCtorArgs.IsEmpty())
  15100. {
  15101. BfIRConstHolder* constHolder = mModule->mCurTypeInstance->mConstHolder;
  15102. auto constant = constHolder->GetConstant(attrib.mCtorArgs[0]);
  15103. if (constant != NULL)
  15104. {
  15105. int alignOverride = (int)BF_MAX(1, constant->mInt64);
  15106. if ((alignOverride & (alignOverride - 1)) == 0)
  15107. allocTarget.mAlignOverride = alignOverride;
  15108. else
  15109. mModule->Fail("Alignment must be a power of 2", attrib.GetRefNode());
  15110. }
  15111. }
  15112. }
  15113. else if (attrib.mType->IsInstanceOf(mModule->mCompiler->mFriendAttributeTypeDef))
  15114. allocTarget.mIsFriend = true;
  15115. }
  15116. if (outCustomAttributes != NULL)
  15117. *outCustomAttributes = customAttrs;
  15118. else
  15119. delete customAttrs;
  15120. }
  15121. }
  15122. }
  15123. BfTypedValue BfExprEvaluator::MakeCallableTarget(BfAstNode* targetSrc, BfTypedValue target)
  15124. {
  15125. if ((target.mType->IsRef()) || (target.mType->IsPointer()))
  15126. {
  15127. auto underlying = target.mType->GetUnderlyingType();
  15128. bool underlyingIsStruct = underlying->IsStruct();
  15129. if (underlyingIsStruct)
  15130. {
  15131. target = mModule->LoadValue(target);
  15132. target.mType = underlying;
  15133. target.mKind = BfTypedValueKind_Addr;
  15134. }
  15135. }
  15136. if ((target.mType->IsStruct()) && (!target.IsAddr()))
  15137. {
  15138. if (IsConstEval())
  15139. return target;
  15140. target = mModule->MakeAddressable(target);
  15141. }
  15142. if (IsVar(target.mType))
  15143. {
  15144. target.mType = mModule->mContext->mBfObjectType;
  15145. return target;
  15146. }
  15147. if (target.mType->IsWrappableType())
  15148. {
  15149. auto primStructType = mModule->GetWrappedStructType(target.mType);
  15150. if (primStructType != NULL)
  15151. {
  15152. mModule->PopulateType(primStructType);
  15153. if (primStructType->IsTypedPrimitive())
  15154. {
  15155. // Type is already the same
  15156. target.mType = primStructType;
  15157. }
  15158. else if (target.IsAddr())
  15159. {
  15160. auto ptrType = mModule->CreatePointerType(primStructType);
  15161. target = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapType(ptrType)), primStructType, true);
  15162. }
  15163. else if ((primStructType->IsSplattable()) && (target.IsSplat()) && (!IsComptime()))
  15164. {
  15165. target.mType = primStructType;
  15166. target.mKind = BfTypedValueKind_SplatHead;
  15167. }
  15168. else
  15169. {
  15170. auto allocPtr = mModule->CreateAlloca(primStructType);
  15171. auto srcPtrType = mModule->mBfIRBuilder->CreateBitCast(allocPtr, mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(target.mType)));
  15172. mModule->mBfIRBuilder->CreateStore(target.mValue, srcPtrType);
  15173. target = BfTypedValue(allocPtr, primStructType, true);
  15174. }
  15175. }
  15176. return target;
  15177. }
  15178. if (target.mType->IsGenericParam())
  15179. {
  15180. target.mType = mModule->mContext->mBfObjectType;
  15181. return target;
  15182. }
  15183. if ((!target.mType->IsTypeInstance()) && (!target.mType->IsConcreteInterfaceType()))
  15184. {
  15185. mModule->Fail(StrFormat("Methods cannot be called on type '%s'", mModule->TypeToString(target.mType).c_str()), targetSrc);
  15186. return BfTypedValue();
  15187. }
  15188. return target;
  15189. }
  15190. int BfExprEvaluator::GetMixinVariable()
  15191. {
  15192. auto curMethodState = mModule->mCurMethodState;
  15193. for (int localIdx = (int)curMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  15194. {
  15195. auto varDecl = curMethodState->mLocals[localIdx];
  15196. if (varDecl->mName == "mixin")
  15197. return localIdx;
  15198. }
  15199. return -1;
  15200. }
  15201. BfModuleMethodInstance BfExprEvaluator::GetSelectedMethod(BfAstNode* targetSrc, BfTypeInstance* curTypeInst, BfMethodDef* methodDef, BfMethodMatcher& methodMatcher, BfType** overrideReturnType)
  15202. {
  15203. bool failed = false;
  15204. BfTypeVector resolvedGenericArguments;
  15205. BfMethodState* rootMethodState = NULL;
  15206. if (mModule->mCurMethodState != NULL)
  15207. rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  15208. int localInferrableGenericArgCount = -1;
  15209. if ((methodMatcher.mBestMethodGenericArguments.size() == 0) && (!methodMatcher.mExplicitMethodGenericArguments.IsEmpty()))
  15210. {
  15211. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(methodDef);
  15212. int64 genericArgCountDiff = (int)methodMatcher.mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx - (int)methodDef->mGenericParams.size();
  15213. BfInvocationExpression* invocationExpr = NULL;
  15214. if (mModule->mParentNodeEntry != NULL)
  15215. {
  15216. invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode);
  15217. }
  15218. if (genericArgCountDiff > 0)
  15219. {
  15220. BfAstNode* errorNode = targetSrc;
  15221. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL))
  15222. {
  15223. errorNode = invocationExpr->mGenericArgs->mGenericArgs[(int)methodDef->mGenericParams.size()];
  15224. if (errorNode == NULL)
  15225. invocationExpr->mGenericArgs->mCommas.GetSafe((int)methodDef->mGenericParams.size() - 1, errorNode);
  15226. if (errorNode == NULL)
  15227. errorNode = targetSrc;
  15228. }
  15229. mModule->Fail(StrFormat("Too many generic arguments, expected %d fewer", genericArgCountDiff), errorNode);
  15230. }
  15231. else if ((genericArgCountDiff < 0) && (!methodMatcher.mHadOpenGenericArguments))
  15232. {
  15233. BfAstNode* errorNode = targetSrc;
  15234. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL) && (invocationExpr->mGenericArgs->mCloseChevron != NULL))
  15235. errorNode = invocationExpr->mGenericArgs->mCloseChevron;
  15236. mModule->Fail(StrFormat("Too few generic arguments, expected %d more", -genericArgCountDiff), errorNode);
  15237. }
  15238. methodMatcher.mBestMethodGenericArguments.resize(methodDef->mGenericParams.size());
  15239. for (int i = 0; i < std::min(methodDef->mGenericParams.size() - uniqueGenericStartIdx, methodMatcher.mExplicitMethodGenericArguments.size()); i++)
  15240. {
  15241. methodMatcher.mBestMethodGenericArguments[i + uniqueGenericStartIdx] = methodMatcher.mExplicitMethodGenericArguments[i];
  15242. }
  15243. }
  15244. BfMethodInstance* unspecializedMethod = NULL;
  15245. bool hasVarGenerics = false;
  15246. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  15247. {
  15248. BfMethodInstance* outerMethodInstance = NULL;
  15249. auto& genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  15250. if (genericArg == NULL)
  15251. {
  15252. if ((methodDef->mIsLocalMethod) && (checkGenericIdx < mModule->mCurMethodInstance->GetNumGenericArguments()))
  15253. {
  15254. // If the root method is generic and we need that param then use that...
  15255. auto rootMethodInstance = rootMethodState->mMethodInstance;
  15256. if ((rootMethodInstance->mMethodInfoEx != NULL) && (checkGenericIdx < rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size()))
  15257. {
  15258. genericArg = rootMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  15259. }
  15260. else
  15261. {
  15262. if (localInferrableGenericArgCount == -1)
  15263. localInferrableGenericArgCount = mModule->GetLocalInferrableGenericArgCount(methodDef);
  15264. // Otherwise we can only infer generics at the level that the called method was contained
  15265. if (checkGenericIdx < localInferrableGenericArgCount)
  15266. genericArg = mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  15267. }
  15268. }
  15269. }
  15270. if (genericArg == NULL)
  15271. {
  15272. if (unspecializedMethod == NULL)
  15273. unspecializedMethod = mModule->GetRawMethodInstance(curTypeInst, methodDef);
  15274. auto genericParam = unspecializedMethod->mMethodInfoEx->mGenericParams[checkGenericIdx];
  15275. if ((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsDelegate()))
  15276. {
  15277. // The only other option was to bind to a MethodRef
  15278. genericArg = mModule->ResolveGenericType(genericParam->mTypeConstraint, NULL, &methodMatcher.mBestMethodGenericArguments, mModule->mCurTypeInstance);
  15279. }
  15280. else
  15281. {
  15282. if (((genericParam->mGenericParamFlags & BfGenericParamFlag_Const) != 0) && (genericParam->mTypeConstraint != NULL))
  15283. {
  15284. for (int paramIdx = 0; paramIdx < (int)unspecializedMethod->mDefaultValues.size(); paramIdx++)
  15285. {
  15286. auto defaultVal = unspecializedMethod->mDefaultValues[paramIdx];
  15287. if (!defaultVal)
  15288. continue;
  15289. auto& param = unspecializedMethod->mParams[paramIdx];
  15290. if (param.mResolvedType->IsGenericParam())
  15291. {
  15292. auto genericParamType = (BfGenericParamType*)param.mResolvedType;
  15293. if ((genericParamType->mGenericParamKind == BfGenericParamKind_Method) && (genericParamType->mGenericParamIdx == checkGenericIdx))
  15294. {
  15295. BfTypedValue constExprVal;
  15296. constExprVal.mType = genericParam->mTypeConstraint;
  15297. auto constant = curTypeInst->mConstHolder->GetConstant(defaultVal.mValue);
  15298. constExprVal.mValue = mModule->ConstantToCurrent(constant, curTypeInst->mConstHolder, genericParam->mTypeConstraint);
  15299. genericArg = mModule->CreateConstExprValueType(constExprVal);
  15300. }
  15301. }
  15302. }
  15303. }
  15304. }
  15305. if (genericArg == NULL)
  15306. {
  15307. BfGenericInferContext genericInferContext;
  15308. genericInferContext.mModule = mModule;
  15309. genericInferContext.mCheckMethodGenericArguments = &methodMatcher.mBestMethodGenericArguments;
  15310. genericInferContext.InferGenericArguments(unspecializedMethod);
  15311. }
  15312. if (genericArg == NULL)
  15313. {
  15314. failed = true;
  15315. BfError* error = mModule->Fail(StrFormat("Unable to determine generic argument '%s'", methodDef->mGenericParams[checkGenericIdx]->mName.c_str()).c_str(), targetSrc);
  15316. if ((genericParam->mTypeConstraint != NULL) && (!genericParam->mTypeConstraint->IsUnspecializedType()))
  15317. genericArg = genericParam->mTypeConstraint;
  15318. else
  15319. genericArg = mModule->mContext->mBfObjectType;
  15320. if (error != NULL)
  15321. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), unspecializedMethod->mMethodDef->GetRefNode());
  15322. }
  15323. }
  15324. if (genericArg->IsVar())
  15325. {
  15326. //BF_ASSERT(methodMatcher.mHasVarArguments);
  15327. hasVarGenerics = true;
  15328. }
  15329. if (genericArg->IsIntUnknown())
  15330. genericArg = mModule->FixIntUnknown(genericArg);
  15331. auto resolvedGenericArg = genericArg;
  15332. resolvedGenericArguments.push_back(genericArg);
  15333. }
  15334. BfTypeInstance* foreignType = NULL;
  15335. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  15336. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef)))
  15337. {
  15338. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForceInline);
  15339. mModule->mAttributeState->mUsed = true;
  15340. }
  15341. if ((!mModule->mCurTypeInstance->IsInterface()) && (methodDef->mBody != NULL))
  15342. {
  15343. if ((methodMatcher.mBypassVirtual) && (methodMatcher.mBestMethodTypeInstance->IsInterface()))
  15344. {
  15345. // This is an explicit 'base' call to a default interface method. We pull the methodDef into our own concrete type.
  15346. foreignType = curTypeInst;
  15347. curTypeInst = mModule->mCurTypeInstance;
  15348. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  15349. }
  15350. else if ((methodDef->mIsStatic) && (curTypeInst->IsInterface()))
  15351. {
  15352. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  15353. {
  15354. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  15355. foreignType = curTypeInst;
  15356. curTypeInst = mModule->mCurTypeInstance;
  15357. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  15358. }
  15359. }
  15360. }
  15361. if (hasVarGenerics)
  15362. return BfModuleMethodInstance();
  15363. BfModuleMethodInstance moduleMethodInstance;
  15364. if (methodMatcher.mBestMethodInstance)
  15365. {
  15366. moduleMethodInstance = methodMatcher.mBestMethodInstance;
  15367. }
  15368. else
  15369. {
  15370. moduleMethodInstance = mModule->GetMethodInstance(curTypeInst, methodDef, resolvedGenericArguments, flags, foreignType);
  15371. }
  15372. if (mModule->IsSkippingExtraResolveChecks())
  15373. {
  15374. //BF_ASSERT(methodInstance.mFunc == NULL);
  15375. }
  15376. if (moduleMethodInstance.mMethodInstance == NULL)
  15377. return NULL;
  15378. if (methodDef->IsEmptyPartial())
  15379. return moduleMethodInstance;
  15380. if (moduleMethodInstance.mMethodInstance->mMethodInfoEx != NULL)
  15381. {
  15382. for (int checkGenericIdx = 0; checkGenericIdx < (int)moduleMethodInstance.mMethodInstance->mMethodInfoEx->mGenericParams.size(); checkGenericIdx++)
  15383. {
  15384. auto genericParams = moduleMethodInstance.mMethodInstance->mMethodInfoEx->mGenericParams[checkGenericIdx];
  15385. BfTypeVector* checkMethodGenericArgs = NULL;
  15386. BfType* genericArg = NULL;
  15387. if (checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size())
  15388. {
  15389. genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  15390. }
  15391. else
  15392. {
  15393. checkMethodGenericArgs = &methodMatcher.mBestMethodGenericArguments;
  15394. genericArg = genericParams->mExternType;
  15395. auto owner = moduleMethodInstance.mMethodInstance->GetOwner();
  15396. BfTypeVector* typeGenericArguments = NULL;
  15397. if (owner->mGenericTypeInfo != NULL)
  15398. typeGenericArguments = &owner->mGenericTypeInfo->mTypeGenericArguments;
  15399. //genericArg = mModule->ResolveGenericType(genericArg, typeGenericArguments, checkMethodGenericArgs);
  15400. }
  15401. if (genericArg->IsVar())
  15402. continue;
  15403. BfAstNode* paramSrc;
  15404. if (checkGenericIdx >= methodMatcher.mBestMethodGenericArgumentSrcs.size())
  15405. {
  15406. paramSrc = targetSrc;
  15407. }
  15408. else
  15409. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  15410. // Note: don't pass methodMatcher.mBestMethodGenericArguments into here, this method is already specialized
  15411. BfError* error = NULL;
  15412. if (!mModule->CheckGenericConstraints(BfGenericParamSource(moduleMethodInstance.mMethodInstance), genericArg, paramSrc, genericParams, NULL,
  15413. failed ? NULL : &error))
  15414. {
  15415. if (moduleMethodInstance.mMethodInstance->IsSpecializedGenericMethod())
  15416. {
  15417. // We mark this as failed to make sure we don't try to process a method that doesn't even follow the constraints
  15418. moduleMethodInstance.mMethodInstance->mFailedConstraints = true;
  15419. }
  15420. if (moduleMethodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL)
  15421. {
  15422. if (error != NULL)
  15423. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), moduleMethodInstance.mMethodInstance->mMethodDef->GetRefNode());
  15424. }
  15425. }
  15426. }
  15427. }
  15428. else
  15429. BF_ASSERT(methodMatcher.mBestMethodGenericArguments.IsEmpty());
  15430. if ((overrideReturnType != NULL) && (moduleMethodInstance.mMethodInstance->mIsUnspecializedVariation) &&
  15431. ((moduleMethodInstance.mMethodInstance->mReturnType->IsUnspecializedTypeVariation()) || (moduleMethodInstance.mMethodInstance->mReturnType->IsVar())))
  15432. {
  15433. if (unspecializedMethod == NULL)
  15434. unspecializedMethod = mModule->GetRawMethodInstance(curTypeInst, methodDef);
  15435. BfTypeVector* typeGenericArgs = NULL;
  15436. auto typeUnspecMethodInstance = unspecializedMethod;
  15437. if (curTypeInst->IsUnspecializedTypeVariation())
  15438. {
  15439. typeUnspecMethodInstance = mModule->GetUnspecializedMethodInstance(typeUnspecMethodInstance, true);
  15440. typeGenericArgs = &curTypeInst->mGenericTypeInfo->mTypeGenericArguments;
  15441. }
  15442. BfType* specializedReturnType = mModule->ResolveGenericType(typeUnspecMethodInstance->mReturnType, typeGenericArgs, &methodMatcher.mBestMethodGenericArguments,
  15443. mModule->mCurTypeInstance);
  15444. if (specializedReturnType != NULL)
  15445. *overrideReturnType = specializedReturnType;
  15446. }
  15447. return moduleMethodInstance;
  15448. }
  15449. BfModuleMethodInstance BfExprEvaluator::GetSelectedMethod(BfMethodMatcher& methodMatcher)
  15450. {
  15451. if (!methodMatcher.mBestMethodInstance)
  15452. methodMatcher.mBestMethodInstance = GetSelectedMethod(methodMatcher.mTargetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  15453. return methodMatcher.mBestMethodInstance;
  15454. }
  15455. void BfExprEvaluator::CheckLocalMethods(BfAstNode* targetSrc, BfTypeInstance* typeInstance, const StringImpl& methodName, BfMethodMatcher& methodMatcher, BfMethodType methodType)
  15456. {
  15457. auto _GetNodeId = [&]()
  15458. {
  15459. auto parser = targetSrc->GetSourceData()->ToParserData();
  15460. return ((int64)parser->mDataId << 32) + targetSrc->GetSrcStart();
  15461. };
  15462. BfMethodState* ctxMethodState = NULL;
  15463. BfClosureInstanceInfo* ctxClosureInstanceInfo = NULL;
  15464. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL))
  15465. {
  15466. ctxClosureInstanceInfo = mModule->mCurMethodState->mClosureState->mClosureInstanceInfo;
  15467. ctxMethodState = mModule->mCurMethodState;
  15468. }
  15469. bool atCtxMethodState = false;
  15470. auto checkMethodState = mModule->mCurMethodState;
  15471. auto rootMethodState = checkMethodState;
  15472. while (checkMethodState != NULL)
  15473. {
  15474. rootMethodState = checkMethodState;
  15475. if (checkMethodState == ctxMethodState)
  15476. atCtxMethodState = true;
  15477. if ((ctxClosureInstanceInfo != NULL) && (!ctxMethodState->mClosureState->mCapturing))
  15478. {
  15479. BfMethodDef* localMethodDef = NULL;
  15480. if (ctxClosureInstanceInfo->mLocalMethodBindings.TryGetValue(_GetNodeId(), &localMethodDef))
  15481. {
  15482. methodMatcher.CheckMethod(mModule->mCurTypeInstance, mModule->mCurTypeInstance, localMethodDef, true);
  15483. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  15484. return;
  15485. }
  15486. }
  15487. else
  15488. {
  15489. BfLocalMethod* matchedLocalMethod = NULL;
  15490. BfLocalMethod* localMethod = NULL;
  15491. if (checkMethodState->mLocalMethodMap.TryGetValue(methodName, &localMethod))
  15492. {
  15493. auto typeInst = mModule->mCurTypeInstance;
  15494. if (checkMethodState->mMixinState != NULL)
  15495. typeInst = checkMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  15496. while (localMethod != NULL)
  15497. {
  15498. auto methodDef = mModule->GetLocalMethodDef(localMethod);
  15499. if (methodDef->mMethodType == methodType)
  15500. {
  15501. methodMatcher.CheckMethod(mModule->mCurTypeInstance, typeInst, methodDef, true);
  15502. if (methodMatcher.mBestMethodDef == methodDef)
  15503. matchedLocalMethod = localMethod;
  15504. }
  15505. localMethod = localMethod->mNextWithSameName;
  15506. }
  15507. }
  15508. if (matchedLocalMethod != NULL)
  15509. {
  15510. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  15511. {
  15512. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, typeInstance, matchedLocalMethod->mMethodDef, methodMatcher);
  15513. if (moduleMethodInstance)
  15514. {
  15515. auto methodInstance = moduleMethodInstance.mMethodInstance;
  15516. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState != NULL))
  15517. {
  15518. // The called method is calling us from its mLocalMethodRefs set. Stretch our mCaptureStartAccessId back to incorporate its
  15519. // captures as well
  15520. if (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId < mModule->mCurMethodState->mClosureState->mCaptureStartAccessId)
  15521. mModule->mCurMethodState->mClosureState->mCaptureStartAccessId = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId;
  15522. }
  15523. else
  15524. {
  15525. if (methodInstance->mDisallowCalling) // We need to process the captures from this guy
  15526. {
  15527. if (mModule->mCurMethodState->mClosureState->mLocalMethodRefSet.Add(methodInstance))
  15528. mModule->mCurMethodState->mClosureState->mLocalMethodRefs.Add(methodInstance);
  15529. }
  15530. }
  15531. }
  15532. }
  15533. if (ctxClosureInstanceInfo != NULL)
  15534. {
  15535. BF_ASSERT(mModule->mCurMethodState->mClosureState->mCapturing);
  15536. ctxClosureInstanceInfo->mLocalMethodBindings[_GetNodeId()] = methodMatcher.mBestMethodDef;
  15537. }
  15538. break;
  15539. }
  15540. }
  15541. checkMethodState = checkMethodState->mPrevMethodState;
  15542. }
  15543. }
  15544. void BfExprEvaluator::InjectMixin(BfAstNode* targetSrc, BfTypedValue target, bool allowImplicitThis, const StringImpl& name, const BfSizedArray<BfExpression*>& arguments, const BfMethodGenericArguments& methodGenericArgs)
  15545. {
  15546. if (mModule->mCurMethodState == NULL)
  15547. return;
  15548. if (mDeferCallData != NULL)
  15549. {
  15550. mModule->Fail("Mixins cannot be directly deferred. Consider wrapping in a block.", targetSrc);
  15551. }
  15552. BfAstNode* origTargetSrc = targetSrc;
  15553. BfScopedInvocationTarget* scopedInvocationTarget = NULL;
  15554. if (mModule->mParentNodeEntry != NULL)
  15555. {
  15556. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  15557. {
  15558. scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(invocationExpr->mTarget);
  15559. }
  15560. }
  15561. auto targetNameNode = targetSrc;
  15562. if (scopedInvocationTarget != NULL)
  15563. targetNameNode = scopedInvocationTarget->mTarget;
  15564. while (true)
  15565. {
  15566. if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(targetNameNode))
  15567. {
  15568. targetNameNode = qualifiedNameNode->mRight;
  15569. continue;
  15570. }
  15571. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(targetNameNode))
  15572. {
  15573. targetNameNode = memberRefExpr->mMemberName;
  15574. continue;
  15575. }
  15576. break;
  15577. }
  15578. BfTypeInstance* mixinClass = NULL;
  15579. if (target.mType != NULL)
  15580. mixinClass = target.mType->ToTypeInstance();
  15581. int inLine = mModule->mCurFilePosition.mCurLine;
  15582. SizedArray<BfResolvedArg, 4> args;
  15583. SizedArray<BfExprEvaluator*, 8> argExprEvaluators;
  15584. defer
  15585. (
  15586. {
  15587. for (auto exprEvaluator : argExprEvaluators)
  15588. delete exprEvaluator;
  15589. }
  15590. );
  15591. auto _AddArg = [&](BfExpression* argExpr)
  15592. {
  15593. BfResolvedArg resolvedArg;
  15594. argExprEvaluators.push_back(new BfExprEvaluator(mModule));
  15595. BfExprEvaluator* exprEvaluator = argExprEvaluators.back();
  15596. exprEvaluator->mResolveGenericParam = false;
  15597. exprEvaluator->mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator->mBfEvalExprFlags | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr);
  15598. bool deferExpr = false;
  15599. if (auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  15600. {
  15601. deferExpr = true;
  15602. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  15603. }
  15604. if (deferExpr)
  15605. {
  15606. //
  15607. }
  15608. else if (argExpr != NULL)
  15609. exprEvaluator->Evaluate(argExpr, false, false, true);
  15610. else
  15611. mModule->Fail("Missing argument", targetSrc);
  15612. auto argValue = exprEvaluator->mResult;
  15613. mModule->FixIntUnknown(argValue);
  15614. if (argValue)
  15615. {
  15616. if (argValue.mType->IsRef())
  15617. {
  15618. exprEvaluator->FinishExpressionResult();
  15619. }
  15620. }
  15621. resolvedArg.mTypedValue = argValue;
  15622. resolvedArg.mExpression = argExpr;
  15623. args.push_back(resolvedArg);
  15624. };
  15625. for (BfExpression* argExpr : arguments)
  15626. {
  15627. _AddArg(argExpr);
  15628. }
  15629. auto autoComplete = GetAutoComplete();
  15630. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  15631. autoComplete->mIsCapturingMethodMatchInfo = false;
  15632. BfMethodMatcher methodMatcher(targetSrc, mModule, name, args, methodGenericArgs);
  15633. methodMatcher.mMethodType = BfMethodType_Mixin;
  15634. methodMatcher.mSkipImplicitParams = true;
  15635. auto curTypeInst = mModule->mCurTypeInstance;
  15636. if (mixinClass != NULL)
  15637. curTypeInst = mixinClass;
  15638. if (target.mType == NULL)
  15639. {
  15640. CheckLocalMethods(targetSrc, curTypeInst, name, methodMatcher, BfMethodType_Mixin);
  15641. }
  15642. if (methodMatcher.mBestMethodDef == NULL)
  15643. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  15644. if (methodMatcher.mBestMethodDef == NULL)
  15645. {
  15646. if (mixinClass != NULL)
  15647. methodMatcher.CheckType(mixinClass, BfTypedValue(), false);
  15648. else
  15649. methodMatcher.CheckType(mModule->mCurTypeInstance, BfTypedValue(), false);
  15650. }
  15651. if ((methodMatcher.mBestMethodDef == NULL) && (target.mType == NULL) && (mModule->mContext->mCurTypeState != NULL))
  15652. {
  15653. BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mType);
  15654. BfGlobalLookup globalLookup;
  15655. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  15656. globalLookup.mName = name;
  15657. mModule->PopulateGlobalContainersList(globalLookup);
  15658. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  15659. {
  15660. if (globalContainer.mTypeInst == NULL)
  15661. continue;
  15662. methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false);
  15663. if (methodMatcher.mBestMethodDef != NULL)
  15664. break;
  15665. }
  15666. }
  15667. if (methodMatcher.mBestMethodDef == NULL)
  15668. {
  15669. BfStaticSearch* staticSearch = mModule->GetStaticSearch();
  15670. if (staticSearch != NULL)
  15671. {
  15672. for (auto typeInst : staticSearch->mStaticTypes)
  15673. {
  15674. if (methodMatcher.CheckType(typeInst, BfTypedValue(), false))
  15675. {
  15676. if (methodMatcher.mBestMethodDef != NULL)
  15677. break;
  15678. }
  15679. }
  15680. }
  15681. }
  15682. if (methodMatcher.mBestMethodDef == NULL)
  15683. {
  15684. mModule->Fail("Cannot find mixin", targetSrc);
  15685. return;
  15686. }
  15687. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  15688. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetNameNode)) && (autoComplete->mDefType == NULL))
  15689. {
  15690. autoComplete->mInsertStartIdx = targetNameNode->GetSrcStart();
  15691. autoComplete->mInsertEndIdx = targetNameNode->GetSrcEnd();
  15692. autoComplete->mDefType = methodMatcher.mBestMethodTypeInstance->mTypeDef;
  15693. autoComplete->mDefMethod = methodMatcher.mBestMethodDef;
  15694. autoComplete->SetDefinitionLocation(methodMatcher.mBestMethodDef->GetMethodDeclaration()->mNameNode);
  15695. }
  15696. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method))
  15697. {
  15698. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() - 1);
  15699. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetNameNode, methodMatcher.mBestMethodTypeInstance->mTypeDef, methodMatcher.mBestMethodDef);
  15700. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() + 1);
  15701. }
  15702. auto curMethodState = mModule->mCurMethodState;
  15703. auto moduleMethodInstance = GetSelectedMethod(targetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  15704. if (!moduleMethodInstance)
  15705. {
  15706. if (methodMatcher.mHasVarArguments)
  15707. {
  15708. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  15709. return;
  15710. }
  15711. mModule->Fail("Failed to get selected mixin", targetSrc);
  15712. return;
  15713. }
  15714. if (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc))
  15715. return;
  15716. auto methodInstance = moduleMethodInstance.mMethodInstance;
  15717. PerformCallChecks(methodInstance, targetSrc);
  15718. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  15719. {
  15720. auto& genericParams = methodInstance->mMethodInfoEx->mGenericParams;
  15721. auto genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  15722. if (genericArg->IsVar())
  15723. continue;
  15724. BfAstNode* paramSrc;
  15725. if (methodMatcher.mBestMethodGenericArgumentSrcs.size() == 0)
  15726. paramSrc = targetSrc;
  15727. else
  15728. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  15729. // Note: don't pass methodMatcher.mBestMethodGenericArguments into here, this method is already specialized
  15730. BfError* error = NULL;
  15731. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericArg, paramSrc, genericParams[checkGenericIdx], NULL, &error))
  15732. {
  15733. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  15734. {
  15735. if (error != NULL)
  15736. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15737. }
  15738. }
  15739. }
  15740. if (curMethodState->mCurScope->mMixinDepth >= 128)
  15741. {
  15742. mModule->Fail("Maximum nested mixin depth exceeded", targetSrc);
  15743. return;
  15744. }
  15745. // Check circular ref based on methodInstance. We must check the arg types since we could be making progress in mixin evaluation
  15746. // based on method selection within the mixin dependent on args
  15747. {
  15748. bool hasCircularRef = false;
  15749. BfMixinState* checkMixinState = NULL;
  15750. auto checkMethodState = curMethodState;
  15751. while (checkMethodState != NULL)
  15752. {
  15753. auto curMixinState = checkMethodState->mMixinState;
  15754. while (curMixinState != NULL)
  15755. {
  15756. if ((curMixinState->mDoCircularVarResult) && (curMixinState->mMixinMethodInstance == methodInstance))
  15757. {
  15758. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  15759. return;
  15760. }
  15761. if ((!curMixinState->mCheckedCircularRef) && (curMixinState->mMixinMethodInstance == methodInstance))
  15762. {
  15763. checkMixinState = curMixinState;
  15764. checkMixinState->mCheckedCircularRef = true;
  15765. }
  15766. else if (checkMixinState != NULL)
  15767. {
  15768. if ((curMixinState->mMixinMethodInstance == checkMixinState->mMixinMethodInstance) &&
  15769. (curMixinState->mArgTypes == checkMixinState->mArgTypes) &&
  15770. (curMixinState->mArgConsts.mSize == checkMixinState->mArgConsts.mSize))
  15771. {
  15772. bool constsMatch = true;
  15773. for (int i = 0; i < curMixinState->mArgConsts.mSize; i++)
  15774. {
  15775. if (!mModule->mBfIRBuilder->CheckConstEquality(curMixinState->mArgConsts[i], checkMixinState->mArgConsts[i]))
  15776. {
  15777. constsMatch = false;
  15778. break;
  15779. }
  15780. }
  15781. if (constsMatch)
  15782. hasCircularRef = true;
  15783. }
  15784. }
  15785. curMixinState = curMixinState->mPrevMixinState;
  15786. }
  15787. checkMethodState = checkMethodState->mPrevMethodState;
  15788. }
  15789. if (hasCircularRef)
  15790. {
  15791. for (auto argType : checkMixinState->mArgTypes)
  15792. {
  15793. if (argType->IsVar())
  15794. checkMixinState->mDoCircularVarResult = true;
  15795. }
  15796. if (checkMixinState->mDoCircularVarResult)
  15797. {
  15798. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  15799. return;
  15800. }
  15801. mModule->Fail("Circular reference detected between mixins", targetSrc);
  15802. return;
  15803. }
  15804. }
  15805. AddCallDependencies(methodInstance);
  15806. if (!methodMatcher.mBestMethodDef->mIsStatic)
  15807. {
  15808. if ((!target) && (allowImplicitThis))
  15809. target = mModule->GetThis();
  15810. if (!target)
  15811. {
  15812. BfError* error = mModule->Fail(StrFormat("An instance reference is required to invoke the non-static mixin '%s'",
  15813. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  15814. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  15815. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15816. }
  15817. }
  15818. else
  15819. {
  15820. if (target)
  15821. {
  15822. BfError* error = mModule->Fail(StrFormat("Mixin '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  15823. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  15824. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  15825. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15826. }
  15827. }
  15828. int methodParamCount = (int)methodInstance->GetParamCount();
  15829. // Implicit params are ignored for calling- they should be resolved at the injection site
  15830. int implicitParamCount = methodInstance->GetImplicitParamCount();
  15831. int explicitParamCount = methodParamCount - implicitParamCount;
  15832. while ((int)args.size() < explicitParamCount)
  15833. {
  15834. int argIdx = (int)args.size();
  15835. BfExpression* expr = methodInstance->GetParamInitializer(argIdx);
  15836. if (expr == NULL)
  15837. break;
  15838. _AddArg(expr);
  15839. }
  15840. if ((int)args.size() < explicitParamCount)
  15841. {
  15842. BfError* error = mModule->Fail(StrFormat("Not enough arguments specified, expected %d more.", explicitParamCount - (int)arguments.size()), targetSrc);
  15843. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  15844. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15845. return;
  15846. }
  15847. else if ((int)args.size() > explicitParamCount)
  15848. {
  15849. BfError* error = mModule->Fail(StrFormat("Too many arguments specified, expected %d fewer.", (int)arguments.size() - explicitParamCount), targetSrc);
  15850. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  15851. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15852. return;
  15853. }
  15854. int paramIdx = implicitParamCount;
  15855. auto argExprEvaluatorItr = argExprEvaluators.begin();
  15856. for (int argIdx = 0; argIdx < (int)args.size(); argIdx++)
  15857. {
  15858. auto exprEvaluator = *argExprEvaluatorItr;
  15859. //auto paramType = methodInstance->GetParamKind(paramIdx);
  15860. BfType* wantType = methodInstance->mParams[paramIdx].mResolvedType;
  15861. auto& arg = args[argIdx];
  15862. if ((arg.mArgFlags & BfArgFlag_VariableDeclaration) != 0)
  15863. {
  15864. arg.mTypedValue = ResolveArgValue(arg, wantType);
  15865. }
  15866. if (wantType->IsGenericParam())
  15867. {
  15868. //
  15869. }
  15870. else if (!wantType->IsVar())
  15871. {
  15872. if (arg.mTypedValue.mType == NULL)
  15873. {
  15874. mModule->AssertErrorState();
  15875. return;
  15876. }
  15877. if (arg.mTypedValue.mType != wantType)
  15878. {
  15879. exprEvaluator->FinishExpressionResult();
  15880. arg.mTypedValue = mModule->LoadValue(arg.mTypedValue);
  15881. arg.mTypedValue = mModule->Cast(arg.mExpression, arg.mTypedValue, wantType);
  15882. /*// Do this to generate default implicit cast error
  15883. mModule->Fail(StrFormat("Mixin argument type '%s' must match parameter type '%s'.",
  15884. mModule->TypeToString(arg.mTypedValue.mType).c_str(),
  15885. mModule->TypeToString(wantType).c_str()), arg.mExpression);
  15886. return;*/
  15887. }
  15888. }
  15889. paramIdx++;
  15890. argExprEvaluatorItr++;
  15891. }
  15892. mModule->AddDependency(methodInstance->GetOwner(), mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  15893. auto startBlock = mModule->mBfIRBuilder->CreateBlock("mixinStart");
  15894. mModule->mBfIRBuilder->CreateBr(startBlock);
  15895. mModule->mBfIRBuilder->AddBlock(startBlock);
  15896. mModule->mBfIRBuilder->SetInsertPoint(startBlock);
  15897. //auto prevDebugLoc = mModule->mBfIRBuilder->getCurrentDebugLocation();
  15898. // This is so when we debug we can hit a steppoint on the inlined "call line"
  15899. mModule->EmitEnsureInstructionAt();
  15900. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  15901. BfMixinState* mixinState = rootMethodState->mMixinStates.Alloc();
  15902. mixinState->mInjectFilePosition = mModule->mCurFilePosition;
  15903. mixinState->mPrevMixinState = curMethodState->mMixinState;
  15904. mixinState->mLocalsStartIdx = (int)mModule->mCurMethodState->mLocals.size();
  15905. mixinState->mMixinMethodInstance = methodInstance;
  15906. mixinState->mSource = origTargetSrc;
  15907. mixinState->mCallerScope = mModule->mCurMethodState->mCurScope;
  15908. mixinState->mTargetScope = mixinState->mCallerScope;
  15909. mixinState->mResultExpr = NULL;
  15910. mixinState->mHasDeferredUsage = false;
  15911. mixinState->mUsedInvocationScope = false;
  15912. mixinState->mTarget = target;
  15913. auto checkNode = origTargetSrc;
  15914. if (scopedInvocationTarget != NULL)
  15915. {
  15916. auto targetScope = mModule->FindScope(scopedInvocationTarget->mScopeName, curMethodState->mMixinState);
  15917. if (targetScope != NULL)
  15918. {
  15919. mixinState->mTargetScope = targetScope;
  15920. if (autoComplete != NULL)
  15921. {
  15922. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(scopedInvocationTarget->mScopeName))
  15923. autoComplete->CheckLabel(identifer, NULL, targetScope);
  15924. }
  15925. }
  15926. }
  15927. mModule->mBfIRBuilder->SaveDebugLocation();
  15928. SetAndRestoreValue<BfMixinState*> prevMixinState(curMethodState->mMixinState, mixinState);
  15929. SetAndRestoreValue<BfExprEvaluator*> prevExprEvaluator(curMethodState->mCurScope->mExprEvaluator, NULL);
  15930. SetAndRestoreValue<BfPendingNullConditional*> prevNullConditional(curMethodState->mPendingNullConditional, NULL);
  15931. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  15932. if (mModule->mCompiler->mResolvePassData != NULL)
  15933. {
  15934. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  15935. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  15936. }
  15937. defer
  15938. (
  15939. {
  15940. if (mModule->mCompiler->mResolvePassData != NULL)
  15941. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  15942. }
  15943. );
  15944. auto methodDef = methodInstance->mMethodDef;
  15945. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15946. BfScopeData scopeData;
  15947. scopeData.mCloseNode = methodDeclaration->mBody;
  15948. if (auto block = BfNodeDynCast<BfBlock>(methodDeclaration->mBody))
  15949. {
  15950. if (block->mCloseBrace != NULL)
  15951. scopeData.mCloseNode = block->mCloseBrace;
  15952. }
  15953. curMethodState->AddScope(&scopeData);
  15954. curMethodState->mCurScope->mMixinDepth++;
  15955. // We can't flush scope state because we extend params in as arbitrary values
  15956. mModule->NewScopeState(true, false);
  15957. bool wantsDIData = (mModule->mBfIRBuilder->DbgHasInfo()) && (mModule->mHasFullDebugInfo);
  15958. DISubprogram* diFunction = NULL;
  15959. int startLocalIdx = (int)mModule->mCurMethodState->mLocals.size();
  15960. int endLocalIdx = startLocalIdx;
  15961. if ((wantsDIData) || (mModule->mIsComptimeModule))
  15962. {
  15963. BfIRMDNode diFuncType = mModule->mBfIRBuilder->DbgCreateSubroutineType(methodInstance);
  15964. //int defLine = mModule->mCurFilePosition.mCurLine;
  15965. int flags = 0;
  15966. curMethodState->mCurScope->mDIInlinedAt = mModule->mBfIRBuilder->DbgGetCurrentLocation();
  15967. // We used to have the "def" line be the inlining position, but the linker we de-duplicate instances of these functions without regard to their unique line
  15968. // definitions, so we need to be consistent and use the actual line
  15969. mModule->UpdateSrcPos(methodDeclaration->mNameNode, BfSrcPosFlag_NoSetDebugLoc);
  15970. int defLine = mModule->mCurFilePosition.mCurLine;
  15971. auto diParentType = mModule->mBfIRBuilder->DbgGetTypeInst(methodInstance->GetOwner());
  15972. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  15973. {
  15974. String methodName = methodDef->mName;
  15975. methodName += "!";
  15976. BfMangler::Mangle(methodName, mModule->mCompiler->GetMangleKind(), methodInstance);
  15977. String linkageName;
  15978. if ((mModule->mIsComptimeModule) && (mModule->mCompiler->mCeMachine->mCurBuilder != NULL))
  15979. linkageName = StrFormat("%d", mModule->mCompiler->mCeMachine->mCurBuilder->DbgCreateMethodRef(methodInstance, ""));
  15980. curMethodState->mCurScope->mDIScope = mModule->mBfIRBuilder->DbgCreateFunction(diParentType, methodName, linkageName, mModule->mCurFilePosition.mFileInstance->mDIFile,
  15981. defLine + 1, diFuncType, false, true, mModule->mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  15982. scopeData.mAltDIFile = mModule->mCurFilePosition.mFileInstance->mDIFile;
  15983. }
  15984. }
  15985. if (methodDef->mBody != NULL)
  15986. mModule->UpdateSrcPos(methodDef->mBody);
  15987. mModule->SetIllegalSrcPos();
  15988. auto _AddLocalVariable = [&](BfLocalVariable* newLocalVar, BfExprEvaluator* exprEvaluator)
  15989. {
  15990. mModule->SetIllegalSrcPos();
  15991. bool hasConstValue = newLocalVar->mConstValue;
  15992. if (hasConstValue)
  15993. {
  15994. auto constant = mModule->mBfIRBuilder->GetConstant(newLocalVar->mConstValue);
  15995. hasConstValue = constant->mConstType < BfConstType_GlobalVar;
  15996. }
  15997. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL) && (exprEvaluator->mResultLocalVarField == 0))
  15998. {
  15999. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  16000. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  16001. auto inLocalVar = exprEvaluator->mResultLocalVar;
  16002. newLocalVar->mAssignedKind = inLocalVar->mAssignedKind;
  16003. newLocalVar->mUnassignedFieldFlags = inLocalVar->mUnassignedFieldFlags;
  16004. newLocalVar->mReadFromId = inLocalVar->mReadFromId;
  16005. newLocalVar->mIsReadOnly = inLocalVar->mIsReadOnly;
  16006. if ((newLocalVar->mAssignedKind == BfLocalVarAssignKind_None) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  16007. {
  16008. for (auto deferredAssign : mModule->mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  16009. {
  16010. if (deferredAssign.mLocalVar == inLocalVar)
  16011. newLocalVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16012. }
  16013. }
  16014. }
  16015. else
  16016. {
  16017. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  16018. }
  16019. if ((wantsDIData) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  16020. {
  16021. bool handled = false;
  16022. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  16023. if (hasConstValue)
  16024. {
  16025. // Already handled
  16026. handled = true;
  16027. }
  16028. else if (newLocalVar->mIsSplat)
  16029. {
  16030. bool found = false;
  16031. auto checkMethodState = mModule->mCurMethodState;
  16032. while ((checkMethodState != NULL) && (!found))
  16033. {
  16034. for (auto localVar : checkMethodState->mLocals)
  16035. {
  16036. if (localVar == newLocalVar)
  16037. continue;
  16038. if (!localVar->mIsSplat)
  16039. continue;
  16040. if (newLocalVar->mValue != localVar->mAddr)
  16041. continue;
  16042. bool isDupName = false;
  16043. for (auto param : methodDef->mParams)
  16044. {
  16045. if (param->mName == localVar->mName)
  16046. {
  16047. isDupName = true;
  16048. break;
  16049. }
  16050. }
  16051. if (isDupName)
  16052. {
  16053. auto splatAgg = mModule->AggregateSplat(BfTypedValue(newLocalVar->mValue, newLocalVar->mResolvedType, BfTypedValueKind_SplatHead));
  16054. // Don't allow alias if one of our args has the same name
  16055. newLocalVar->mIsSplat = false;
  16056. newLocalVar->mValue = BfIRValue();
  16057. if (splatAgg.IsAddr())
  16058. newLocalVar->mAddr = splatAgg.mValue;
  16059. else
  16060. newLocalVar->mValue = splatAgg.mValue;
  16061. found = true;
  16062. break;
  16063. }
  16064. String name = "$";
  16065. name += newLocalVar->mName;
  16066. name += "$alias$";
  16067. name += localVar->mName;
  16068. // auto fakeValue = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 0);
  16069. // auto diType = mModule->mBfIRBuilder->DbgGetType(mModule->GetPrimitiveType(BfTypeCode_Int32));
  16070. // auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  16071. // name, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  16072. // mModule->mBfIRBuilder->DbgInsertValueIntrinsic(fakeValue, diVariable);
  16073. auto diType = mModule->mBfIRBuilder->DbgGetType(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  16074. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  16075. name, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  16076. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(mModule->mBfIRBuilder->CreateConstNull(), diVariable);
  16077. handled = true;
  16078. found = true;
  16079. break;
  16080. }
  16081. checkMethodState = checkMethodState->mPrevMethodState;
  16082. }
  16083. }
  16084. if (handled)
  16085. {
  16086. //
  16087. }
  16088. else if ((mModule->IsTargetingBeefBackend()) && (!mModule->mIsComptimeModule))
  16089. {
  16090. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  16091. mModule->SetIllegalSrcPos();
  16092. // With the Beef backend we can assign two variables to the same value, but LLVM does not allow this
  16093. // so we have to create a ref to that variable
  16094. auto diType = mModule->mBfIRBuilder->DbgGetType(newLocalVar->mResolvedType);
  16095. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  16096. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  16097. if (newLocalVar->mIsSplat)
  16098. {
  16099. //TODO: Implement
  16100. }
  16101. else if (newLocalVar->mResolvedType->IsValuelessType())
  16102. {
  16103. // Do nothing
  16104. }
  16105. else
  16106. {
  16107. BfIRValue value = newLocalVar->mValue;
  16108. if (newLocalVar->mAddr)
  16109. value = newLocalVar->mAddr;
  16110. else if (newLocalVar->mConstValue)
  16111. value = newLocalVar->mConstValue;
  16112. auto aliasValue = mModule->mBfIRBuilder->CreateAliasValue(value);
  16113. if (mModule->WantsLifetimes())
  16114. scopeData.mDeferredLifetimeEnds.Add(aliasValue);
  16115. if (newLocalVar->mAddr)
  16116. mModule->mBfIRBuilder->DbgInsertDeclare(aliasValue, diVariable);
  16117. else
  16118. {
  16119. if (newLocalVar->mResolvedType->IsBoolean())
  16120. {
  16121. // Fix case of remote condbr referencing
  16122. newLocalVar->mAddr = mModule->CreateAlloca(newLocalVar->mResolvedType);
  16123. mModule->mBfIRBuilder->CreateStore(newLocalVar->mValue, newLocalVar->mAddr);
  16124. }
  16125. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(aliasValue, diVariable);
  16126. }
  16127. }
  16128. }
  16129. else if (newLocalVar->mAddr)
  16130. {
  16131. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  16132. mModule->SetIllegalSrcPos();
  16133. auto refType = mModule->CreateRefType(newLocalVar->mResolvedType);
  16134. auto allocaVal = mModule->CreateAlloca(refType);
  16135. mModule->mBfIRBuilder->CreateStore(newLocalVar->mAddr, allocaVal);
  16136. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  16137. {
  16138. auto diType = mModule->mBfIRBuilder->DbgGetType(refType);
  16139. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  16140. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  16141. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  16142. }
  16143. }
  16144. else if (newLocalVar->mValue)
  16145. {
  16146. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  16147. mModule->SetIllegalSrcPos();
  16148. auto localVal = LoadLocal(newLocalVar);
  16149. localVal = mModule->LoadValue(localVal);
  16150. localVal = mModule->AggregateSplat(localVal);
  16151. BfType* allocType = localVal.mType;
  16152. if (!allocType->IsValuelessType())
  16153. {
  16154. auto allocaVal = mModule->CreateAlloca(allocType);
  16155. mModule->mBfIRBuilder->CreateStore(localVal.mValue, allocaVal);
  16156. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  16157. {
  16158. if (newLocalVar->mIsSplat)
  16159. {
  16160. //TODO: Implement
  16161. }
  16162. else
  16163. {
  16164. auto diType = mModule->mBfIRBuilder->DbgGetType(allocType);
  16165. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  16166. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  16167. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  16168. }
  16169. }
  16170. }
  16171. }
  16172. }
  16173. newLocalVar->mParamIdx = -3;
  16174. mixinState->mArgTypes.Add(newLocalVar->mResolvedType);
  16175. if (mModule->mBfIRBuilder->IsConstValue(newLocalVar->mConstValue))
  16176. mixinState->mArgConsts.Add(newLocalVar->mConstValue);
  16177. };
  16178. argExprEvaluatorItr = argExprEvaluators.begin();
  16179. for (int argIdx = methodDef->mIsStatic ? 0 : -1; argIdx < (int)explicitParamCount; argIdx++)
  16180. {
  16181. int paramIdx = argIdx;
  16182. auto exprEvaluator = *argExprEvaluatorItr;
  16183. BfTypedValue argValue;
  16184. BfLocalVariable* localVar = new BfLocalVariable();
  16185. if (argIdx == -1)
  16186. {
  16187. argValue = target;
  16188. localVar->mName = "this";
  16189. localVar->mIsThis = true;
  16190. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16191. }
  16192. else
  16193. {
  16194. auto arg = &args[argIdx];
  16195. auto paramDef = methodDef->mParams[paramIdx];
  16196. localVar->mName = paramDef->mName;
  16197. if (!arg->mTypedValue)
  16198. {
  16199. auto wantType = methodInstance->GetParamType(paramIdx);
  16200. if (wantType->IsVar())
  16201. wantType = mModule->mContext->mBfObjectType;
  16202. arg->mTypedValue = mModule->GetDefaultTypedValue(wantType);
  16203. }
  16204. argValue = arg->mTypedValue;
  16205. }
  16206. if (!argValue)
  16207. continue;
  16208. localVar->mResolvedType = argValue.mType;
  16209. if (argValue.mType->IsRef())
  16210. {
  16211. auto refType = (BfRefType*)localVar->mResolvedType;
  16212. localVar->mAddr = mModule->LoadValue(argValue).mValue;
  16213. localVar->mResolvedType = argValue.mType->GetUnderlyingType();
  16214. localVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  16215. }
  16216. else if (argValue.IsAddr())
  16217. localVar->mAddr = argValue.mValue;
  16218. else
  16219. {
  16220. if (!argValue.mValue)
  16221. {
  16222. // Untyped value
  16223. }
  16224. else if (argValue.mValue.IsConst())
  16225. {
  16226. localVar->mConstValue = argValue.mValue;
  16227. }
  16228. else if (argValue.IsSplat())
  16229. {
  16230. localVar->mValue = argValue.mValue;
  16231. localVar->mIsSplat = true;
  16232. }
  16233. else
  16234. {
  16235. if (argValue.IsAddr())
  16236. localVar->mAddr = argValue.mValue;
  16237. else
  16238. localVar->mValue = argValue.mValue;
  16239. }
  16240. localVar->mIsReadOnly = argValue.IsReadOnly();
  16241. }
  16242. if (argValue.IsReadOnly())
  16243. localVar->mIsReadOnly = true;
  16244. if (argIdx == -1)
  16245. {
  16246. _AddLocalVariable(localVar, NULL);
  16247. }
  16248. else
  16249. {
  16250. _AddLocalVariable(localVar, exprEvaluator);
  16251. endLocalIdx++;
  16252. ++argExprEvaluatorItr;
  16253. }
  16254. }
  16255. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  16256. {
  16257. mModule->VisitCodeBlock(blockBody);
  16258. if (mixinState->mResultExpr != NULL)
  16259. {
  16260. if (auto exprNode = BfNodeDynCast<BfExpression>(mixinState->mResultExpr))
  16261. {
  16262. if (!exprNode->IsA<BfBlock>())
  16263. {
  16264. // Mixin expression result
  16265. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_AllowRefExpr));
  16266. mModule->UpdateSrcPos(exprNode);
  16267. VisitChild(exprNode);
  16268. FinishExpressionResult();
  16269. ResolveGenericType();
  16270. }
  16271. }
  16272. }
  16273. GetResult();
  16274. }
  16275. else if (auto expr = BfNodeDynCast<BfExpression>(methodDef->mBody))
  16276. {
  16277. mModule->UpdateSrcPos(expr);
  16278. mResult = mModule->CreateValueFromExpression(expr);
  16279. }
  16280. if (!mResult)
  16281. {
  16282. // If we didn't have an expression body then just make the result "void"
  16283. mResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  16284. }
  16285. mResult = mModule->RemoveRef(mResult);
  16286. if (mResult.IsAddr())
  16287. {
  16288. if (mModule->mCurMethodState->mCurScope->ExtendLifetime(mResult.mValue))
  16289. mModule->mBfIRBuilder->CreateLifetimeSoftEnd(mResult.mValue);
  16290. }
  16291. int localIdx = startLocalIdx;
  16292. argExprEvaluatorItr = argExprEvaluators.begin();
  16293. for (; localIdx < endLocalIdx; localIdx++)
  16294. {
  16295. auto exprEvaluator = *argExprEvaluatorItr;
  16296. BfLocalVariable* localVar = curMethodState->mLocals[localIdx];
  16297. //TODO: Merge unassigned flags together
  16298. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL))
  16299. {
  16300. auto inLocalVar = exprEvaluator->mResultLocalVar;
  16301. if (localVar->mAssignedKind != BfLocalVarAssignKind_None)
  16302. inLocalVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16303. if (localVar->mReadFromId != -1)
  16304. inLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  16305. }
  16306. ++argExprEvaluatorItr;
  16307. }
  16308. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  16309. {
  16310. if (blockBody->mCloseBrace != NULL)
  16311. mModule->UpdateSrcPos(blockBody->mCloseBrace);
  16312. }
  16313. else if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  16314. {
  16315. if (methodDeclaration->mFatArrowToken != NULL)
  16316. mModule->UpdateSrcPos(methodDeclaration->mFatArrowToken);
  16317. }
  16318. mModule->RestoreScopeState();
  16319. prevMixinState.Restore();
  16320. if ((scopedInvocationTarget != NULL) && (scopedInvocationTarget->mScopeName != NULL) && (!mixinState->mUsedInvocationScope))
  16321. {
  16322. mModule->Warn(0, "Scope specifier was not referenced in mixin", scopedInvocationTarget->mScopeName);
  16323. }
  16324. if (mixinState->mHasDeferredUsage)
  16325. {
  16326. mixinState->mTarget = BfTypedValue();
  16327. // Put deferred mixin states at the front
  16328. BF_ASSERT(rootMethodState->mMixinStates.back() == mixinState);
  16329. rootMethodState->mMixinStates.pop_back();
  16330. rootMethodState->mMixinStates.Insert(0, mixinState);
  16331. }
  16332. else
  16333. {
  16334. BF_ASSERT(rootMethodState->mMixinStates.back() == mixinState);
  16335. rootMethodState->mMixinStates.pop_back();
  16336. delete mixinState;
  16337. }
  16338. mModule->mBfIRBuilder->RestoreDebugLocation();
  16339. mModule->mBfIRBuilder->DupDebugLocation();
  16340. }
  16341. void BfExprEvaluator::SetMethodElementType(BfAstNode* target)
  16342. {
  16343. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(target))
  16344. {
  16345. SetMethodElementType(delegateBindExpr->mTarget);
  16346. return;
  16347. }
  16348. if (auto lambdaBindExpr = BfNodeDynCast<BfLambdaBindExpression>(target))
  16349. {
  16350. return;
  16351. }
  16352. if (auto attributedIdentifierNode = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  16353. {
  16354. if (attributedIdentifierNode->mIdentifier != NULL)
  16355. mModule->SetElementType(attributedIdentifierNode->mIdentifier, BfSourceElementType_Method);
  16356. }
  16357. else if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(target))
  16358. {
  16359. if (memberReferenceExpr->mMemberName != NULL)
  16360. SetMethodElementType(memberReferenceExpr->mMemberName);
  16361. }
  16362. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(target))
  16363. SetMethodElementType(qualifiedNameNode->mRight);
  16364. else
  16365. mModule->SetElementType(target, BfSourceElementType_Method);
  16366. }
  16367. void BfExprEvaluator::DoInvocation(BfAstNode* target, BfMethodBoundExpression* methodBoundExpr, const BfSizedArray<BfExpression*>& args, const BfMethodGenericArguments& methodGenericArgs, BfTypedValue* outCascadeValue)
  16368. {
  16369. auto methodGenericArguments = methodGenericArgs.mArguments;
  16370. // Just a check
  16371. mModule->mBfIRBuilder->GetInsertBlock();
  16372. bool wasCapturingMethodInfo = false;
  16373. auto autoComplete = GetAutoComplete();
  16374. if ((autoComplete != NULL) && (methodGenericArguments != NULL))
  16375. {
  16376. for (BfAstNode* methodGenericArg : *methodGenericArguments)
  16377. {
  16378. autoComplete->CheckNode(methodGenericArg, false, true);
  16379. }
  16380. }
  16381. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  16382. {
  16383. // We don't want to capture a call within the target node
  16384. wasCapturingMethodInfo = true;
  16385. autoComplete->mIsCapturingMethodMatchInfo = false;
  16386. }
  16387. bool allowImplicitThis = false;
  16388. BfAstNode* methodNodeSrc = target;
  16389. BfAttributeState attributeState;
  16390. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  16391. if (auto scopedTarget = BfNodeDynCast<BfScopedInvocationTarget>(target))
  16392. {
  16393. target = scopedTarget->mTarget;
  16394. if (autoComplete != NULL)
  16395. {
  16396. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopedTarget->mScopeName))
  16397. autoComplete->CheckLabel(identifier, scopedTarget->mColonToken, NULL);
  16398. }
  16399. //mModule->FindScope(scopedTarget->mScopeName);
  16400. }
  16401. bool isCascade = false;
  16402. BfAstNode* cascadeOperatorToken = NULL;
  16403. bool bypassVirtual = false;
  16404. bool gaveUnqualifiedDotError = false;
  16405. String targetFunctionName;
  16406. BfTypedValue thisValue;
  16407. //TODO: This may just be a fully qualified static method name, so let's check that also
  16408. if (auto memberRefExpression = BfNodeDynCast<BfMemberReferenceExpression>(target))
  16409. {
  16410. if (autoComplete != NULL)
  16411. {
  16412. if (memberRefExpression->mTarget != NULL)
  16413. autoComplete->CheckMemberReference(memberRefExpression->mTarget, memberRefExpression->mDotToken, memberRefExpression->mMemberName, false, mExpectingType);
  16414. else if (mExpectingType != NULL)
  16415. {
  16416. String filter;
  16417. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(memberRefExpression->mDotToken, memberRefExpression->mMemberName, filter)))
  16418. {
  16419. auto typeInst = mExpectingType->ToTypeInstance();
  16420. if (typeInst != NULL)
  16421. {
  16422. String filter;
  16423. if ((memberRefExpression->mMemberName != NULL) && (autoComplete->IsAutocompleteNode(memberRefExpression->mMemberName)))
  16424. filter = autoComplete->GetFilter(memberRefExpression->mMemberName);
  16425. bool allowPrivate = typeInst == mModule->mCurTypeInstance;
  16426. autoComplete->AddEnumTypeMembers(typeInst, filter, false, allowPrivate);
  16427. autoComplete->AddSelfResultTypeMembers(typeInst, typeInst, filter, allowPrivate);
  16428. }
  16429. }
  16430. }
  16431. }
  16432. if ((memberRefExpression->mTarget == NULL) && (memberRefExpression->mMemberName == NULL))
  16433. {
  16434. auto expectingType = mExpectingType;
  16435. if ((expectingType != NULL) && (expectingType->IsNullable()))
  16436. {
  16437. auto underlyingType = expectingType->GetUnderlyingType();
  16438. expectingType = underlyingType;
  16439. }
  16440. BfType* inRefType = NULL;
  16441. if ((expectingType != NULL) && (expectingType->IsRef()))
  16442. {
  16443. auto refType = (BfRefType*)expectingType;
  16444. if (refType->mRefKind == BfRefType::RefKind_In)
  16445. {
  16446. inRefType = expectingType;
  16447. auto underlyingType = expectingType->GetUnderlyingType();
  16448. expectingType = underlyingType;
  16449. }
  16450. }
  16451. if (expectingType != NULL)
  16452. {
  16453. if (expectingType->IsSizedArray())
  16454. {
  16455. if (mModule->mParentNodeEntry != NULL)
  16456. {
  16457. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  16458. {
  16459. InitializedSizedArray((BfSizedArrayType*)expectingType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen);
  16460. return;
  16461. }
  16462. }
  16463. }
  16464. else if ((expectingType->IsStruct()) || (expectingType->IsTypedPrimitive()))
  16465. {
  16466. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  16467. {
  16468. autoComplete->mIsCapturingMethodMatchInfo = true;
  16469. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  16470. }
  16471. if (mModule->mParentNodeEntry != NULL)
  16472. {
  16473. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  16474. {
  16475. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  16476. BfResolveArgsFlags resolveArgsFlags = BfResolveArgsFlag_DeferParamEval;
  16477. ResolveArgValues(argValues, resolveArgsFlags);
  16478. if ((mReceivingValue != NULL) && (mReceivingValue->mType == expectingType) && (mReceivingValue->IsAddr()))
  16479. {
  16480. mResult = *mReceivingValue;
  16481. mReceivingValue = NULL;
  16482. }
  16483. else
  16484. mResult = BfTypedValue(mModule->CreateAlloca(expectingType), expectingType, BfTypedValueKind_TempAddr);
  16485. auto ctorResult = MatchConstructor(target, methodBoundExpr, mResult, expectingType->ToTypeInstance(), argValues, false, BfMethodGenericArguments(), BfAllowAppendKind_No);
  16486. if ((ctorResult) && (!ctorResult.mType->IsVoid()))
  16487. mResult = ctorResult;
  16488. mModule->ValidateAllocation(expectingType, invocationExpr->mTarget);
  16489. if ((inRefType != NULL) && (mResult.mType == expectingType) && (mResult.IsAddr()))
  16490. {
  16491. // Put back the 'in'
  16492. mResult = BfTypedValue(mResult.mValue, inRefType);
  16493. }
  16494. return;
  16495. }
  16496. }
  16497. }
  16498. else if (expectingType->IsGenericParam())
  16499. {
  16500. if (mModule->mParentNodeEntry != NULL)
  16501. {
  16502. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  16503. {
  16504. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  16505. BfResolveArgsFlags resolveArgsFlags = BfResolveArgsFlag_None;
  16506. ResolveArgValues(argValues, resolveArgsFlags);
  16507. if (!mModule->mCurMethodInstance->mIsUnspecializedVariation)
  16508. CheckGenericCtor((BfGenericParamType*)expectingType, argValues, invocationExpr->mTarget);
  16509. mResult = mModule->GetDefaultTypedValue(expectingType);
  16510. return;
  16511. }
  16512. }
  16513. }
  16514. else if (expectingType->IsVar())
  16515. {
  16516. // Silently allow
  16517. gaveUnqualifiedDotError = true;
  16518. }
  16519. else if (expectingType->IsPrimitiveType())
  16520. {
  16521. // Allow
  16522. }
  16523. else if ((mBfEvalExprFlags & BfEvalExprFlags_AppendFieldInitializer) == 0)
  16524. {
  16525. gaveUnqualifiedDotError = true;
  16526. if (mModule->PreFail())
  16527. mModule->Fail(StrFormat("Cannot use inferred constructor on type '%s'", mModule->TypeToString(expectingType).c_str()), memberRefExpression->mDotToken);
  16528. }
  16529. }
  16530. }
  16531. if (memberRefExpression->IsA<BfBaseExpression>())
  16532. bypassVirtual = true;
  16533. if (memberRefExpression->mMemberName != NULL)
  16534. methodNodeSrc = memberRefExpression->mMemberName;
  16535. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpression->mMemberName))
  16536. {
  16537. if (attrIdentifier->mIdentifier != NULL)
  16538. methodNodeSrc = attrIdentifier->mIdentifier;
  16539. attributeState.mSrc = attrIdentifier->mAttributes;
  16540. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  16541. if (attrIdentifier->mIdentifier != NULL)
  16542. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  16543. }
  16544. else if (memberRefExpression->mMemberName != NULL)
  16545. targetFunctionName = memberRefExpression->mMemberName->ToString();
  16546. if (memberRefExpression->mTarget == NULL)
  16547. {
  16548. if (mExpectingType)
  16549. {
  16550. if (mExpectingType->IsVar())
  16551. {
  16552. }
  16553. mResult = BfTypedValue(mExpectingType);
  16554. }
  16555. else if (!gaveUnqualifiedDotError)
  16556. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", memberRefExpression->mDotToken);
  16557. }
  16558. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpression->mTarget))
  16559. {
  16560. // Static method
  16561. mResult = BfTypedValue(ResolveTypeRef(typeRef));
  16562. }
  16563. if (auto leftIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpression->mTarget))
  16564. {
  16565. bool hadError = false;
  16566. thisValue = LookupIdentifier(leftIdentifier, true, &hadError);
  16567. CheckResultForReading(thisValue);
  16568. if (mPropDef != NULL)
  16569. thisValue = GetResult(true);
  16570. if (hadError)
  16571. {
  16572. mModule->AssertErrorState();
  16573. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16574. }
  16575. if ((!thisValue) && (mPropDef == NULL))
  16576. {
  16577. // Identifier not found. Static method? Just check speculatively don't throw error
  16578. BfType* type;
  16579. {
  16580. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  16581. type = mModule->ResolveTypeRef(leftIdentifier, NULL, BfPopulateType_DataAndMethods, BfResolveTypeRefFlag_NoResolveGenericParam);
  16582. }
  16583. if (type != NULL)
  16584. thisValue = BfTypedValue(type);
  16585. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(leftIdentifier))
  16586. {
  16587. LookupQualifiedStaticField(qualifiedLeft, true);
  16588. thisValue = mResult;
  16589. mResult = BfTypedValue();
  16590. }
  16591. }
  16592. if (mPropDef != NULL)
  16593. thisValue = GetResult(true);
  16594. if (!thisValue.mType)
  16595. {
  16596. mModule->Fail("Identifier not found", leftIdentifier);
  16597. mModule->CheckTypeRefFixit(leftIdentifier);
  16598. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16599. }
  16600. if (mResult)
  16601. CheckResultForReading(mResult);
  16602. mResult = thisValue;
  16603. }
  16604. else if (auto expr = BfNodeDynCast<BfExpression>(memberRefExpression->mTarget))
  16605. {
  16606. BfType* expectingTargetType = NULL;
  16607. if (memberRefExpression->mDotToken->mToken == BfToken_DotDot)
  16608. expectingTargetType = mExpectingType;
  16609. bool handled = false;
  16610. if (auto subMemberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(expr))
  16611. {
  16612. String findName;
  16613. if (subMemberRefExpr->mMemberName != NULL)
  16614. findName = subMemberRefExpr->mMemberName->ToString();
  16615. if (findName == "base") // Generic IFace<T>.base
  16616. {
  16617. thisValue = mModule->GetThis();
  16618. if (thisValue)
  16619. {
  16620. VisitChild(subMemberRefExpr->mTarget);
  16621. if (mResult.HasType())
  16622. {
  16623. if (mResult.mValue)
  16624. {
  16625. mModule->Fail("Type name expected", subMemberRefExpr->mTarget);
  16626. }
  16627. else
  16628. {
  16629. auto type = mResult.mType;
  16630. if (type != NULL)
  16631. {
  16632. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  16633. {
  16634. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  16635. mModule->TypeToString(type).c_str(),
  16636. mModule->TypeToString(thisValue.mType).c_str()), subMemberRefExpr->mTarget);
  16637. }
  16638. else
  16639. {
  16640. if (type->IsInterface())
  16641. {
  16642. thisValue.mType = type;
  16643. }
  16644. else
  16645. {
  16646. auto castedThis = mModule->Cast(subMemberRefExpr->mMemberName, thisValue, type, BfCastFlags_Explicit);
  16647. if (castedThis)
  16648. thisValue = castedThis;
  16649. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  16650. }
  16651. }
  16652. handled = true;
  16653. }
  16654. bypassVirtual = true;
  16655. }
  16656. }
  16657. }
  16658. }
  16659. }
  16660. if (!handled)
  16661. {
  16662. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  16663. auto flags = (BfEvalExprFlags)(BfEvalExprFlags_PropogateNullConditional | BfEvalExprFlags_NoCast);
  16664. if (mFunctionBindResult != NULL)
  16665. {
  16666. if (auto paranExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  16667. {
  16668. // Allow 'ref' on binding, to indicate we want to capture 'this' by reference
  16669. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowRefExpr);
  16670. expr = paranExpr->mExpression;
  16671. }
  16672. }
  16673. if (expr != NULL)
  16674. mResult = mModule->CreateValueFromExpression(expr, expectingTargetType, flags);
  16675. }
  16676. }
  16677. isCascade = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_DotDot);
  16678. if (isCascade)
  16679. cascadeOperatorToken = memberRefExpression->mDotToken;
  16680. bool isNullCondLookup = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_QuestionDot);
  16681. if (isNullCondLookup)
  16682. mResult = SetupNullConditional(mResult, memberRefExpression->mDotToken);
  16683. if ((mResult.mType == NULL) && (memberRefExpression->mTarget != NULL))
  16684. {
  16685. mModule->AssertErrorState();
  16686. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16687. }
  16688. thisValue = mResult;
  16689. mResult = BfTypedValue();
  16690. if ((thisValue) && (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->mToken == BfToken_Arrow))
  16691. thisValue = TryArrowLookup(thisValue, memberRefExpression->mDotToken);
  16692. }
  16693. else if (auto qualifiedName = BfNodeDynCast<BfQualifiedNameNode>(target))
  16694. {
  16695. if (GetAutoComplete() != NULL)
  16696. GetAutoComplete()->CheckMemberReference(qualifiedName->mLeft, qualifiedName->mDot, qualifiedName->mRight);
  16697. if (qualifiedName->mLeft->GetSrcLength() == 4)
  16698. {
  16699. if (CheckIsBase(qualifiedName->mLeft))
  16700. bypassVirtual = true;
  16701. }
  16702. if (qualifiedName->mRight != NULL)
  16703. methodNodeSrc = qualifiedName->mRight;
  16704. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(qualifiedName->mRight))
  16705. {
  16706. if (attrIdentifier->mIdentifier != NULL)
  16707. methodNodeSrc = attrIdentifier->mIdentifier;
  16708. attributeState.mSrc = attrIdentifier->mAttributes;
  16709. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  16710. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  16711. }
  16712. else
  16713. targetFunctionName = qualifiedName->mRight->ToString();
  16714. bool hadError = false;
  16715. thisValue = LookupIdentifier(qualifiedName->mLeft, true, &hadError);
  16716. CheckResultForReading(thisValue);
  16717. if (mPropDef != NULL)
  16718. thisValue = GetResult(true);
  16719. if (hadError)
  16720. {
  16721. mModule->AssertErrorState();
  16722. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16723. }
  16724. if ((!thisValue) && (mPropDef == NULL))
  16725. {
  16726. // Identifier not found. Static method? Just check speculatively don't throw error
  16727. BfType* type;
  16728. {
  16729. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  16730. type = mModule->ResolveTypeRef(qualifiedName->mLeft, NULL, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowGlobalContainer | BfResolveTypeRefFlag_IgnoreLookupError));
  16731. }
  16732. if (type == NULL)
  16733. {
  16734. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  16735. type = mModule->ResolveTypeRef(qualifiedName, methodGenericArguments, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowGlobalContainer | BfResolveTypeRefFlag_IgnoreLookupError));
  16736. if (type != NULL)
  16737. {
  16738. // This is a CTOR call, treat it as such
  16739. targetFunctionName.clear();
  16740. }
  16741. }
  16742. if (type != NULL)
  16743. thisValue = BfTypedValue(type);
  16744. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(qualifiedName->mLeft))
  16745. {
  16746. String findName = qualifiedLeft->mRight->ToString();
  16747. bool handled = false;
  16748. if (findName == "base")
  16749. {
  16750. auto type = mModule->ResolveTypeRef(qualifiedLeft->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  16751. mModule->CheckTypeRefFixit(qualifiedLeft->mLeft);
  16752. thisValue = mModule->GetThis();
  16753. if (type != NULL)
  16754. {
  16755. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  16756. {
  16757. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  16758. mModule->TypeToString(type).c_str(),
  16759. mModule->TypeToString(thisValue.mType).c_str()), qualifiedLeft->mLeft);
  16760. }
  16761. else
  16762. {
  16763. if (type->IsInterface())
  16764. {
  16765. thisValue.mType = type;
  16766. }
  16767. else
  16768. {
  16769. auto castedThis = mModule->Cast(qualifiedLeft->mRight, thisValue, type, BfCastFlags_Explicit);
  16770. if (castedThis)
  16771. thisValue = castedThis;
  16772. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  16773. }
  16774. }
  16775. handled = true;
  16776. }
  16777. bypassVirtual = true;
  16778. }
  16779. if (!handled)
  16780. {
  16781. LookupQualifiedStaticField(qualifiedLeft, true);
  16782. thisValue = mResult;
  16783. mResult = BfTypedValue();
  16784. }
  16785. }
  16786. }
  16787. if (mPropDef != NULL)
  16788. thisValue = GetResult(true);
  16789. if (!thisValue.mType)
  16790. {
  16791. mModule->Fail("Identifier not found", qualifiedName->mLeft);
  16792. mModule->CheckTypeRefFixit(qualifiedName->mLeft);
  16793. mModule->CheckIdentifierFixit(qualifiedName->mLeft);
  16794. thisValue = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  16795. }
  16796. if (mResult)
  16797. CheckResultForReading(mResult);
  16798. mResult = BfTypedValue();
  16799. }
  16800. else if (auto identiferExpr = BfNodeDynCast<BfIdentifierNode>(target))
  16801. {
  16802. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  16803. {
  16804. if (attrIdentifier->mIdentifier != NULL)
  16805. methodNodeSrc = attrIdentifier->mIdentifier;
  16806. attributeState.mSrc = attrIdentifier->mAttributes;
  16807. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  16808. }
  16809. allowImplicitThis = true;
  16810. if (autoComplete != NULL)
  16811. autoComplete->CheckIdentifier(identiferExpr);
  16812. targetFunctionName = target->ToString();
  16813. if (targetFunctionName == "PrintF") // Just directly call that one
  16814. {
  16815. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  16816. BfType* charPtrType = mModule->CreatePointerType(charType);
  16817. auto func = mModule->GetBuiltInFunc(BfBuiltInFuncType_PrintF);
  16818. SizedArray<BfIRValue, 4> irArgs;
  16819. for (BfExpression* arg : args)
  16820. {
  16821. BfTypedValue value;
  16822. if (arg != NULL)
  16823. value = mModule->CreateValueFromExpression(arg);
  16824. if (!value)
  16825. return;
  16826. auto typeInst = value.mType->ToTypeInstance();
  16827. if ((typeInst != NULL) && (typeInst->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  16828. value = mModule->Cast(arg, value, charPtrType);
  16829. if ((value.mType->IsFloat()) && (value.mType->mSize != 8)) // Always cast float to double
  16830. value = mModule->Cast(arg, value, mModule->GetPrimitiveType(BfTypeCode_Double));
  16831. irArgs.push_back(value.mValue);
  16832. }
  16833. if ((targetFunctionName != "PrintF") || (irArgs.size() > 0))
  16834. {
  16835. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCall(func, irArgs/*, targetFunctionName*/),
  16836. mModule->ResolveTypeDef(mModule->mSystem->mTypeInt32));
  16837. }
  16838. return;
  16839. }
  16840. if (auto ceDbgState = mModule->GetCeDbgState())
  16841. {
  16842. if (targetFunctionName.StartsWith("__"))
  16843. {
  16844. auto ceDebugger = mModule->mCompiler->mCeMachine->mDebugger;
  16845. auto _ResolveArg = [&](int argIdx, BfType* type = NULL)
  16846. {
  16847. if ((argIdx < 0) || (argIdx >= args.mSize))
  16848. return BfTypedValue();
  16849. return mModule->CreateValueFromExpression(args[argIdx], type);
  16850. };
  16851. if (targetFunctionName == "__getHighBits")
  16852. {
  16853. auto typedVal = _ResolveArg(0);
  16854. if ((typedVal) && (typedVal.mType->IsPrimitiveType()))
  16855. {
  16856. auto primType = (BfPrimitiveType*)typedVal.mType;
  16857. int64 val = ceDebugger->ValueToInt(typedVal);
  16858. int64 bitCount = ceDebugger->ValueToInt(_ResolveArg(1));
  16859. int64 resultVal = val >> (typedVal.mType->mSize * 8 - bitCount);
  16860. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)resultVal), typedVal.mType);
  16861. return;
  16862. }
  16863. }
  16864. else if (targetFunctionName == "__clearHighBits")
  16865. {
  16866. auto typedVal = _ResolveArg(0);
  16867. if ((typedVal) && (typedVal.mType->IsPrimitiveType()))
  16868. {
  16869. auto primType = (BfPrimitiveType*)typedVal.mType;
  16870. int64 val = ceDebugger->ValueToInt(typedVal);
  16871. int64 bitCount = ceDebugger->ValueToInt(_ResolveArg(1));
  16872. int64 andBits = (0x8000000000000000LL) >> ((typedVal.mType->mSize - 8) * 8 + bitCount - 1);
  16873. int64 resultVal = val & ~andBits;
  16874. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)resultVal), typedVal.mType);
  16875. return;
  16876. }
  16877. }
  16878. else if ((targetFunctionName == "__cast") || (targetFunctionName == "__bitcast"))
  16879. {
  16880. BfType* type = NULL;
  16881. String typeName;
  16882. for (int argIdx = 0; argIdx < args.mSize - 1; argIdx++)
  16883. {
  16884. auto arg = _ResolveArg(argIdx);
  16885. if (!arg)
  16886. continue;
  16887. if (arg.mType->IsInstanceOf(mModule->mCompiler->mStringTypeDef))
  16888. {
  16889. auto strPtr = mModule->GetStringPoolString(arg.mValue, mModule->mBfIRBuilder);
  16890. if (strPtr != NULL)
  16891. {
  16892. if ((type != NULL) && (*strPtr == "*"))
  16893. {
  16894. type = mModule->CreatePointerType(type);
  16895. }
  16896. else
  16897. typeName += *strPtr;
  16898. }
  16899. }
  16900. if (arg.mType->IsInteger())
  16901. {
  16902. int64 intVal = ceDebugger->ValueToInt(arg);
  16903. if (typeName.IsEmpty())
  16904. {
  16905. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef)->ToTypeInstance();
  16906. auto fieldDef = typeType->mTypeDef->GetFieldByName("mTypeId");
  16907. if (fieldDef != NULL)
  16908. {
  16909. int typeId = ceDebugger->ReadMemory<int>((intptr)intVal + typeType->mFieldInstances[fieldDef->mIdx].mDataOffset);
  16910. type = mModule->mContext->FindTypeById(typeId);
  16911. }
  16912. }
  16913. else
  16914. typeName += StrFormat("%lld", intVal);
  16915. }
  16916. }
  16917. auto fromTypedVal = _ResolveArg(args.mSize - 1);
  16918. if (!typeName.IsEmpty())
  16919. type = ceDebugger->FindType(typeName);
  16920. if (type != NULL)
  16921. {
  16922. if (targetFunctionName == "__bitcast")
  16923. {
  16924. if ((type->IsObjectOrInterface()) || (type->IsPointer()))
  16925. {
  16926. auto ceAddrVal = ceDebugger->GetAddr(fromTypedVal);
  16927. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIntToPtr(ceAddrVal.mAddr, mModule->mBfIRBuilder->MapType(type)), type);
  16928. }
  16929. else
  16930. {
  16931. Array<uint8> memArr;
  16932. memArr.Resize(BF_MAX(type->mSize, fromTypedVal.mType->mSize));
  16933. mModule->mBfIRBuilder->WriteConstant(fromTypedVal.mValue, memArr.mVals, fromTypedVal.mType);
  16934. auto newVal = mModule->mBfIRBuilder->ReadConstant(memArr.mVals, type);
  16935. mResult = BfTypedValue(newVal, type);
  16936. }
  16937. }
  16938. else
  16939. mResult = mModule->Cast(target, fromTypedVal, type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  16940. }
  16941. return;
  16942. }
  16943. else if (targetFunctionName == "__stringView")
  16944. {
  16945. auto ptrVal = _ResolveArg(0);
  16946. auto sizeVal = _ResolveArg(1);
  16947. if (ceDbgState->mFormatInfo != NULL)
  16948. ceDbgState->mFormatInfo->mOverrideCount = (int)ceDebugger->ValueToInt(sizeVal);
  16949. mResult = ptrVal;
  16950. return;
  16951. }
  16952. else if ((targetFunctionName == "__funcName") || (targetFunctionName == "__funcTarget"))
  16953. {
  16954. auto addrVal = _ResolveArg(0);
  16955. auto ceAddrVal = ceDebugger->GetAddr(addrVal);
  16956. CeFunction* ceFunction = NULL;
  16957. int functionId = 0;
  16958. if (mModule->mSystem->mPtrSize == 4)
  16959. {
  16960. functionId = (int)addrVal;
  16961. }
  16962. else
  16963. {
  16964. CeFunction* checkCeFunction = (CeFunction*)ceAddrVal.mAddr;
  16965. functionId = checkCeFunction->SafeGetId();
  16966. }
  16967. if (mModule->mCompiler->mCeMachine->mFunctionIdMap.TryGetValue(functionId, &ceFunction))
  16968. {
  16969. BfMethodInstance* methodInstance = ceFunction->mMethodInstance;
  16970. if (methodInstance != NULL)
  16971. {
  16972. if (targetFunctionName == "__funcTarget")
  16973. {
  16974. BfType* targetType = methodInstance->GetOwner();
  16975. if (targetType->IsValueType())
  16976. targetType = mModule->CreatePointerType(targetType);
  16977. auto targetVal = _ResolveArg(1);
  16978. auto ceTargetVal = ceDebugger->GetAddr(targetVal);
  16979. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIntToPtr(ceTargetVal.mAddr, mModule->mBfIRBuilder->MapType(targetType)), targetType);
  16980. return;
  16981. }
  16982. else
  16983. {
  16984. mResult = BfTypedValue(mModule->GetStringObjectValue(mModule->MethodToString(methodInstance)),
  16985. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  16986. return;
  16987. }
  16988. }
  16989. else if ((ceFunction->mCeInnerFunctionInfo != NULL) && (targetFunctionName == "__funcName"))
  16990. {
  16991. mResult = BfTypedValue(mModule->GetStringObjectValue(BfDemangler::Demangle(ceFunction->mCeInnerFunctionInfo->mName, DbgLanguage_Beef)),
  16992. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  16993. return;
  16994. }
  16995. }
  16996. if (targetFunctionName == "__funcTarget")
  16997. mResult = _ResolveArg(1);
  16998. else
  16999. mResult = addrVal;
  17000. return;
  17001. }
  17002. }
  17003. }
  17004. }
  17005. else if (auto expr = BfNodeDynCast<BfExpression>(target))
  17006. {
  17007. auto innerInvocationResult = mModule->CreateValueFromExpression(expr);
  17008. if (!innerInvocationResult)
  17009. {
  17010. mModule->AssertErrorState();
  17011. innerInvocationResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  17012. }
  17013. if (innerInvocationResult.mType->IsVar())
  17014. {
  17015. mResult = innerInvocationResult;
  17016. return;
  17017. }
  17018. targetFunctionName = "Invoke";
  17019. if (innerInvocationResult.mType->IsTypeInstance())
  17020. {
  17021. auto invocationTypeInst = innerInvocationResult.mType->ToTypeInstance();
  17022. if ((invocationTypeInst->mTypeDef->mIsDelegate) || (invocationTypeInst->mTypeDef->mIsFunction))
  17023. {
  17024. thisValue = innerInvocationResult;
  17025. }
  17026. }
  17027. if (!thisValue)
  17028. {
  17029. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(innerInvocationResult.mType).c_str()), expr);
  17030. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  17031. }
  17032. }
  17033. else
  17034. {
  17035. mModule->Fail("Invalid invocation target", target);
  17036. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  17037. }
  17038. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  17039. {
  17040. autoComplete->mIsCapturingMethodMatchInfo = true;
  17041. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  17042. }
  17043. SetAndRestoreValue<BfAttributeState*> prevAttributeState;
  17044. if (attributeState.mCustomAttributes != NULL)
  17045. prevAttributeState.Init(mModule->mAttributeState, &attributeState);
  17046. if ((targetFunctionName != "") && (targetFunctionName[targetFunctionName.length() - 1] == '!'))
  17047. {
  17048. targetFunctionName = targetFunctionName.Substring(0, targetFunctionName.length() - 1);
  17049. InjectMixin(methodNodeSrc, thisValue, allowImplicitThis, targetFunctionName, args, methodGenericArgs);
  17050. return;
  17051. }
  17052. if (targetFunctionName.StartsWith('@'))
  17053. targetFunctionName.Remove(0, 1);
  17054. //TODO: We removed this... Messed up with PrimStruct 'this' non-mut errors
  17055. // We moved this until later in MatchMethod, we want the raw target for the GetType optimization, plus we shouldn't do this until we know we won't do a SkipCall
  17056. /*if (thisValue)
  17057. {
  17058. if ((!thisValue.mType->IsGenericParam()) && (!thisValue.IsSplat()) && (!thisValue.mType->IsVar()))
  17059. thisValue = MakeCallableTarget(target, thisValue);
  17060. }*/
  17061. int methodCount = 0;
  17062. bool mayBeSkipCall = false;
  17063. bool mayBeComptimeCall = false;
  17064. BfTypeInstance* checkTypeInst = NULL;
  17065. if (thisValue.mType != NULL)
  17066. {
  17067. if (thisValue.mType->IsAllocType())
  17068. thisValue.mType = thisValue.mType->GetUnderlyingType();
  17069. checkTypeInst = thisValue.mType->ToTypeInstance();
  17070. }
  17071. else if (allowImplicitThis)
  17072. {
  17073. checkTypeInst = mModule->mCurTypeInstance;
  17074. }
  17075. while (checkTypeInst != NULL)
  17076. {
  17077. checkTypeInst->mTypeDef->PopulateMemberSets();
  17078. BfMemberSetEntry* memberSetEntry;
  17079. if (checkTypeInst->mTypeDef->mMethodSet.TryGetWith(targetFunctionName, &memberSetEntry))
  17080. {
  17081. BfMethodDef* methodDef = (BfMethodDef*)memberSetEntry->mMemberDef;
  17082. while (methodDef != NULL)
  17083. {
  17084. if (methodDef->mIsSkipCall)
  17085. mayBeSkipCall = true;
  17086. if (methodDef->mHasComptime)
  17087. mayBeComptimeCall = true;
  17088. methodDef = methodDef->mNextWithSameName;
  17089. }
  17090. }
  17091. checkTypeInst = checkTypeInst->mBaseType;
  17092. }
  17093. SizedArray<BfExpression*, 8> copiedArgs;
  17094. for (BfExpression* arg : args)
  17095. copiedArgs.push_back(arg);
  17096. BfSizedArray<BfExpression*> sizedCopiedArgs(copiedArgs);
  17097. BfResolvedArgs argValues(&sizedCopiedArgs);
  17098. if (mModule->mParentNodeEntry != NULL)
  17099. {
  17100. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  17101. {
  17102. argValues.mOpenToken = invocationExpr->mOpenParen;
  17103. argValues.mCommas = &invocationExpr->mCommas;
  17104. argValues.mCloseToken = invocationExpr->mCloseParen;
  17105. }
  17106. }
  17107. BfResolveArgsFlags resolveArgsFlags = (BfResolveArgsFlags)(BfResolveArgsFlag_DeferFixits | BfResolveArgsFlag_AllowUnresolvedTypes);
  17108. resolveArgsFlags = (BfResolveArgsFlags)(resolveArgsFlags | BfResolveArgsFlag_DeferParamEval);
  17109. if ((mayBeSkipCall) || (mayBeComptimeCall))
  17110. resolveArgsFlags = (BfResolveArgsFlags)(resolveArgsFlags | BfResolveArgsFlag_DeferParamValues);
  17111. static int sCallIdx = 0;
  17112. sCallIdx++;
  17113. int callIdx = sCallIdx;
  17114. if (callIdx == 1557)
  17115. {
  17116. NOP;
  17117. }
  17118. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  17119. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  17120. {
  17121. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  17122. {
  17123. checkedKind = BfCheckedKind_Checked;
  17124. mModule->mAttributeState->mUsed = true;
  17125. }
  17126. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  17127. {
  17128. checkedKind = BfCheckedKind_Unchecked;
  17129. mModule->mAttributeState->mUsed = true;
  17130. }
  17131. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoStaticCtorAttributeTypeDef))
  17132. {
  17133. mModule->mAttributeState->mUsed = true;
  17134. }
  17135. }
  17136. if ((isCascade) && (cascadeOperatorToken != NULL) && ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0))
  17137. mModule->Fail("Cascade operator cannot be used in const evaluation", cascadeOperatorToken);
  17138. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, mUsedAsStatement || isCascade);
  17139. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlags(mBfEvalExprFlags);
  17140. if (isCascade)
  17141. {
  17142. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_InCascade);
  17143. thisValue = mModule->MakeAddressable(thisValue);
  17144. }
  17145. if (((mayBeComptimeCall) && (!mModule->mIsComptimeModule) && (!mModule->mBfIRBuilder->mIgnoreWrites)) ||
  17146. ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mConstEvalAttributeTypeDef))))
  17147. {
  17148. resolveArgsFlags = (BfResolveArgsFlags)(resolveArgsFlags | BfResolveArgsFlag_DeferParamEval | BfResolveArgsFlag_DeferStrings);
  17149. }
  17150. ResolveArgValues(argValues, resolveArgsFlags);
  17151. //
  17152. {
  17153. // We also apply this right before the actual call, but we need to set the comptime flag earlier
  17154. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlag(mBfEvalExprFlags);
  17155. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mConstEvalAttributeTypeDef)))
  17156. {
  17157. mModule->mAttributeState->mUsed = true;
  17158. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  17159. }
  17160. mResult = MatchMethod(methodNodeSrc, methodBoundExpr, thisValue, allowImplicitThis, bypassVirtual, targetFunctionName, argValues, methodGenericArgs, checkedKind);
  17161. }
  17162. argValues.HandleFixits(mModule);
  17163. if (mModule->mAttributeState == &attributeState)
  17164. mModule->FinishAttributeState(&attributeState);
  17165. if (isCascade)
  17166. {
  17167. if ((outCascadeValue != NULL) && (thisValue.mValue))
  17168. {
  17169. *outCascadeValue = thisValue;
  17170. }
  17171. else
  17172. {
  17173. mModule->Fail("Invalid use of cascade operator", cascadeOperatorToken);
  17174. }
  17175. }
  17176. }
  17177. void BfExprEvaluator::Visit(BfInvocationExpression* invocationExpr)
  17178. {
  17179. DoInvocation(invocationExpr);
  17180. }
  17181. void BfExprEvaluator::DoInvocation(BfInvocationExpression* invocationExpr)
  17182. {
  17183. BfAutoParentNodeEntry autoParentNodeEntry(mModule, invocationExpr);
  17184. // We need to check for sized array constructor like "uint8[2](1, 2)"
  17185. if (BfNodeDynCastExact<BfIndexerExpression>(invocationExpr->mTarget) != NULL)
  17186. {
  17187. auto checkTarget = invocationExpr->mTarget;
  17188. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  17189. {
  17190. checkTarget = indexerExpr->mTarget;
  17191. }
  17192. auto resolvedType = mModule->ResolveTypeRef(checkTarget, NULL, BfPopulateType_Identity, BfResolveTypeRefFlag_IgnoreLookupError);
  17193. if (resolvedType != NULL)
  17194. {
  17195. BfType* curType = resolvedType;
  17196. auto checkTarget = invocationExpr->mTarget;
  17197. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  17198. {
  17199. checkTarget = indexerExpr->mTarget;
  17200. if (indexerExpr->mCommas.size() != 0)
  17201. mModule->Fail("Only one value expected. Consider adding an allocation specifier such as 'new' if construction of a dynamic multidimensional was intended.", indexerExpr->mCommas[0]);
  17202. int arrSize = 0;
  17203. BfTypeState typeState;
  17204. typeState.mArrayInitializerSize = (int)invocationExpr->mArguments.size();
  17205. SetAndRestoreValue<BfTypeState*> prevTypeState(mModule->mContext->mCurTypeState, &typeState);
  17206. if (indexerExpr->mArguments.size() != 0)
  17207. {
  17208. BfConstResolver constResolver(mModule);
  17209. auto arg = indexerExpr->mArguments[0];
  17210. constResolver.mExpectingType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  17211. if (arg != NULL)
  17212. constResolver.Resolve(arg, NULL, BfConstResolveFlag_ArrayInitSize);
  17213. if (constResolver.mResult.mValue.IsConst())
  17214. {
  17215. auto constant = mModule->mBfIRBuilder->GetConstant(constResolver.mResult.mValue);
  17216. if ((mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 >= 0))
  17217. {
  17218. arrSize = constant->mInt32;
  17219. }
  17220. else
  17221. mModule->Fail("Non-negative integer expected", indexerExpr->mArguments[0]);
  17222. }
  17223. }
  17224. else
  17225. arrSize = invocationExpr->mArguments.size();
  17226. curType = mModule->CreateSizedArrayType(curType, arrSize);
  17227. }
  17228. InitializedSizedArray((BfSizedArrayType*)curType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen, NULL);
  17229. return;
  17230. }
  17231. }
  17232. auto autoComplete = GetAutoComplete();
  17233. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  17234. if (autoComplete != NULL)
  17235. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  17236. mModule->UpdateExprSrcPos(invocationExpr);
  17237. BfMethodGenericArguments methodGenericArgs;
  17238. if (invocationExpr->mGenericArgs != NULL)
  17239. {
  17240. methodGenericArgs.mArguments = &invocationExpr->mGenericArgs->mGenericArgs;
  17241. if ((!invocationExpr->mGenericArgs->mCommas.IsEmpty()) && (invocationExpr->mGenericArgs->mCommas.back()->mToken == BfToken_DotDotDot))
  17242. {
  17243. methodGenericArgs.mIsOpen = true;
  17244. methodGenericArgs.mIsPartial = true;
  17245. }
  17246. for (int i = 0; i < (int)methodGenericArgs.mArguments->mSize; i++)
  17247. if (BfNodeIsA<BfUninitializedExpression>((*methodGenericArgs.mArguments)[i]))
  17248. methodGenericArgs.mIsPartial = true;
  17249. }
  17250. SizedArray<BfExpression*, 8> copiedArgs;
  17251. for (BfExpression* arg : invocationExpr->mArguments)
  17252. copiedArgs.push_back(arg);
  17253. BfTypedValue cascadeValue;
  17254. DoInvocation(invocationExpr->mTarget, invocationExpr, copiedArgs, methodGenericArgs, &cascadeValue);
  17255. if (autoComplete != NULL)
  17256. {
  17257. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  17258. {
  17259. if (autoComplete->mMethodMatchInfo != NULL)
  17260. autoComplete->mIsCapturingMethodMatchInfo = true;
  17261. else
  17262. autoComplete->mIsCapturingMethodMatchInfo = false;
  17263. //BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  17264. }
  17265. else
  17266. autoComplete->mIsCapturingMethodMatchInfo = false;
  17267. }
  17268. /// Previous check for discard
  17269. if (cascadeValue)
  17270. mResult = cascadeValue;
  17271. }
  17272. BfMethodDef* BfExprEvaluator::GetPropertyMethodDef(BfPropertyDef* propDef, BfMethodType methodType, BfCheckedKind checkedKind, BfTypedValue propTarget)
  17273. {
  17274. bool allowMut = true;
  17275. if ((propTarget) && (propTarget.mType->IsValueType()))
  17276. {
  17277. if (propTarget.IsReadOnly())
  17278. {
  17279. allowMut = false;
  17280. }
  17281. else if (!propTarget.IsAddr())
  17282. {
  17283. mModule->PopulateType(propTarget.mType);
  17284. if (!propTarget.IsValuelessType())
  17285. allowMut = false;
  17286. }
  17287. }
  17288. int bestPri = -1000;
  17289. BfMethodDef* matchedMethod = NULL;
  17290. for (auto methodDef : propDef->mMethods)
  17291. {
  17292. if (methodDef->mMethodType != methodType)
  17293. continue;
  17294. int curPri = 0;
  17295. if (methodDef->mCheckedKind == checkedKind)
  17296. {
  17297. curPri = 5;
  17298. }
  17299. else if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  17300. curPri = 3;
  17301. else
  17302. curPri = 1;
  17303. if (methodDef->mIsMutating)
  17304. {
  17305. if (allowMut)
  17306. curPri++;
  17307. else
  17308. curPri -= 10;
  17309. }
  17310. if (curPri > bestPri)
  17311. {
  17312. bestPri = curPri;
  17313. matchedMethod = methodDef;
  17314. }
  17315. }
  17316. return matchedMethod;
  17317. /*BfMethodDef* matchedMethod = NULL;
  17318. BfMethodDef* backupMethod = NULL;
  17319. for (auto methodDef : propDef->mMethods)
  17320. {
  17321. if (methodDef->mMethodType != methodType)
  17322. continue;
  17323. if (methodDef->mCheckedKind == checkedKind)
  17324. {
  17325. matchedMethod = methodDef;
  17326. break;
  17327. }
  17328. if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  17329. matchedMethod = methodDef;
  17330. else
  17331. backupMethod = methodDef;
  17332. }
  17333. if (matchedMethod == NULL)
  17334. matchedMethod = backupMethod;
  17335. return matchedMethod;*/
  17336. }
  17337. BfModuleMethodInstance BfExprEvaluator::GetPropertyMethodInstance(BfMethodDef* methodDef)
  17338. {
  17339. if (mPropDefBypassVirtual)
  17340. {
  17341. if (mPropTarget.mType->IsInterface())
  17342. {
  17343. auto curTypeInst = mPropTarget.mType->ToTypeInstance();
  17344. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  17345. {
  17346. if (methodDef->mBody != NULL)
  17347. {
  17348. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  17349. mPropTarget = mModule->GetThis();
  17350. return mModule->GetMethodInstance(mModule->mCurTypeInstance, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_ForeignMethodDef, curTypeInst);
  17351. }
  17352. }
  17353. else
  17354. {
  17355. mModule->Fail("Property is not implemented by this type", mPropSrc);
  17356. return BfModuleMethodInstance();
  17357. }
  17358. }
  17359. else
  17360. {
  17361. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  17362. mModule->PopulateType(propTypeInst, BfPopulateType_DataAndMethods);
  17363. auto rawMethodInstance = mModule->GetRawMethodInstance(propTypeInst, methodDef);
  17364. if (rawMethodInstance->mVirtualTableIdx == -1)
  17365. {
  17366. if (!mModule->mCompiler->mIsResolveOnly)
  17367. {
  17368. // ResolveOnly does not force methods to slot
  17369. BF_ASSERT(rawMethodInstance->mVirtualTableIdx != -1);
  17370. mModule->Fail(StrFormat("Failed to devirtualize %s", mModule->MethodToString(rawMethodInstance).c_str()));
  17371. }
  17372. }
  17373. else
  17374. {
  17375. auto useTypeInst = mOrigPropTarget.mType->ToTypeInstance();
  17376. auto virtualMethod = (BfMethodInstance*)useTypeInst->mVirtualMethodTable[rawMethodInstance->mVirtualTableIdx].mImplementingMethod;
  17377. return mModule->ReferenceExternalMethodInstance(virtualMethod);
  17378. }
  17379. }
  17380. }
  17381. if ((mOrigPropTarget) && (mOrigPropTarget.mType != mPropTarget.mType) &&
  17382. ((!mOrigPropTarget.mType->IsGenericParam()) && (mPropTarget.mType->IsInterface())))
  17383. {
  17384. auto checkType = mOrigPropTarget.mType;
  17385. if ((checkType->IsNullable()) && (!mPropTarget.mType->IsNullable()))
  17386. checkType = checkType->GetUnderlyingType();
  17387. if (checkType->IsPointer())
  17388. checkType = ((BfPointerType*)checkType)->mElementType;
  17389. if (checkType->IsWrappableType())
  17390. checkType = mModule->GetWrappedStructType(checkType);
  17391. if ((checkType != NULL) && (checkType->IsTypeInstance()))
  17392. {
  17393. auto activeTypeDef = mModule->GetActiveTypeDef(NULL, false, true);
  17394. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  17395. bool checkedUnderlying = false;
  17396. auto checkTypeInst = checkType->ToTypeInstance();
  17397. while (checkTypeInst != NULL)
  17398. {
  17399. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  17400. BF_ASSERT((checkTypeInst->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || (mModule->mCompiler->IsAutocomplete()));
  17401. if (checkTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotted)
  17402. break;
  17403. for (auto& iface : checkTypeInst->mInterfaces)
  17404. {
  17405. if (!mModule->IsInSpecializedSection())
  17406. {
  17407. if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  17408. continue;
  17409. }
  17410. if (iface.mInterfaceType == mPropTarget.mType)
  17411. {
  17412. if (bestIFaceEntry == NULL)
  17413. {
  17414. bestIFaceEntry = &iface;
  17415. continue;
  17416. }
  17417. bool isBetter;
  17418. bool isWorse;
  17419. mModule->CompareDeclTypes(NULL, iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  17420. if (isBetter == isWorse)
  17421. {
  17422. // Failed
  17423. }
  17424. else
  17425. {
  17426. if (isBetter)
  17427. bestIFaceEntry = &iface;
  17428. }
  17429. }
  17430. }
  17431. if (bestIFaceEntry != NULL)
  17432. break;
  17433. checkTypeInst = checkTypeInst->mBaseType;
  17434. if (checkTypeInst == NULL)
  17435. {
  17436. if (!checkedUnderlying)
  17437. {
  17438. checkedUnderlying = true;
  17439. if (checkType->HasWrappedRepresentation())
  17440. {
  17441. auto underlyingType = checkType->GetUnderlyingType();
  17442. if (underlyingType != NULL)
  17443. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  17444. }
  17445. }
  17446. }
  17447. }
  17448. if (bestIFaceEntry != NULL)
  17449. {
  17450. if ((checkTypeInst->IsInterface()))
  17451. {
  17452. auto propTypeInst = bestIFaceEntry->mInterfaceType->ToTypeInstance();
  17453. if (propTypeInst == NULL)
  17454. {
  17455. mModule->Fail("INTERNAL ERROR: Invalid property target", mPropSrc);
  17456. return BfModuleMethodInstance();
  17457. }
  17458. BF_ASSERT(propTypeInst->mTypeDef->mFullNameEx == methodDef->mDeclaringType->mFullNameEx);
  17459. return mModule->GetMethodInstance(propTypeInst, methodDef, BfTypeVector(), mPropGetMethodFlags);
  17460. }
  17461. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + methodDef->mIdx];
  17462. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  17463. if (bestMethodInstance != NULL)
  17464. {
  17465. mPropTarget = mOrigPropTarget;
  17466. //mPropTarget.mType = checkTypeInst;
  17467. //mPropTarget = mModule->Cast( mOrigPropTarget, checkTypeInst);
  17468. return mModule->GetMethodInstanceAtIdx(ifaceMethodEntry.mMethodRef.mTypeInstance, ifaceMethodEntry.mMethodRef.mMethodNum);
  17469. }
  17470. }
  17471. }
  17472. mModule->AssertErrorState();
  17473. return BfModuleMethodInstance();
  17474. }
  17475. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  17476. if (propTypeInst == NULL)
  17477. {
  17478. propTypeInst = mModule->GetWrappedStructType(mPropTarget.mType);
  17479. }
  17480. if (propTypeInst == NULL)
  17481. {
  17482. mModule->Fail("INTERNAL ERROR: Invalid property target", mPropSrc);
  17483. return BfModuleMethodInstance();
  17484. }
  17485. BF_ASSERT(propTypeInst->mTypeDef->mFullNameEx == methodDef->mDeclaringType->mFullNameEx);
  17486. return mModule->GetMethodInstance(propTypeInst, methodDef, BfTypeVector(), mPropGetMethodFlags);
  17487. }
  17488. void BfExprEvaluator::CheckPropFail(BfMethodDef* propMethodDef, BfMethodInstance* methodInstance, bool checkProt)
  17489. {
  17490. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  17491. // If mExplicitInterface is null then we are implicitly calling through an interface
  17492. if ((checkProt) && (propTypeInst != NULL) && (methodInstance->GetExplicitInterface() == NULL) &&
  17493. (!mModule->CheckAccessMemberProtection(propMethodDef->mProtection, propTypeInst)))
  17494. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(methodInstance).c_str()), mPropSrc);
  17495. else if (mPropCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  17496. {
  17497. bool passes = true;
  17498. if (mPropCheckedKind != BfCheckedKind_NotSet)
  17499. {
  17500. passes = false;
  17501. }
  17502. else
  17503. {
  17504. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  17505. if (defaultCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  17506. passes = false;
  17507. }
  17508. if (!passes)
  17509. {
  17510. auto error = mModule->Fail(StrFormat("'%s' cannot be used because its 'checked' specifier does not match the requested specifier", mModule->MethodToString(methodInstance).c_str()), mPropSrc);
  17511. if (error != NULL)
  17512. {
  17513. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  17514. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  17515. }
  17516. }
  17517. }
  17518. }
  17519. bool BfExprEvaluator::HasResult()
  17520. {
  17521. return (mResult) || (mPropDef != NULL);
  17522. }
  17523. BfTypedValue BfExprEvaluator::GetResult(bool clearResult, bool resolveGenericType)
  17524. {
  17525. if ((!mResult) && (mPropDef != NULL))
  17526. {
  17527. bool handled = false;
  17528. if (mPropTarget.mType->IsGenericTypeInstance())
  17529. {
  17530. auto genericTypeInst = (BfTypeInstance*)mPropTarget.mType;
  17531. if (genericTypeInst->IsInstanceOf(mModule->mCompiler->mSizedArrayTypeDef))
  17532. {
  17533. if (mPropDef->mName == "Count")
  17534. {
  17535. auto sizedType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[1];
  17536. if (sizedType->IsConstExprValue())
  17537. {
  17538. auto constExprType = (BfConstExprValueType*)sizedType;
  17539. mResult = BfTypedValue(mModule->GetConstValue(constExprType->mValue.mInt64), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  17540. handled = true;
  17541. }
  17542. else
  17543. {
  17544. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  17545. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_IntPtr)), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  17546. handled = true;
  17547. }
  17548. }
  17549. }
  17550. }
  17551. if (!handled)
  17552. {
  17553. SetAndRestoreValue<BfFunctionBindResult*> prevFunctionBindResult(mFunctionBindResult, NULL);
  17554. SetAndRestoreValue<BfDeferCallData*> prevDeferCallRef(mDeferCallData, NULL);
  17555. BfMethodDef* matchedMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  17556. if (matchedMethod == NULL)
  17557. {
  17558. mModule->Fail("Property has no getter", mPropSrc);
  17559. return mResult;
  17560. }
  17561. auto methodInstance = GetPropertyMethodInstance(matchedMethod);
  17562. if (methodInstance.mMethodInstance == NULL)
  17563. return mResult;
  17564. BF_ASSERT(methodInstance.mMethodInstance->mMethodDef->mName == matchedMethod->mName);
  17565. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  17566. {
  17567. BF_ASSERT(!methodInstance.mFunc.IsFake());
  17568. }
  17569. if (mPropSrc != NULL)
  17570. mModule->UpdateExprSrcPos(mPropSrc);
  17571. auto autoComplete = GetAutoComplete();
  17572. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(mPropSrc)) && (autoComplete->mResolveType == BfResolveType_GetResultString))
  17573. {
  17574. autoComplete->mResultString = ":";
  17575. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->mReturnType);
  17576. autoComplete->mResultString += " ";
  17577. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetOwner());
  17578. autoComplete->mResultString += ".";
  17579. autoComplete->mResultString += mPropDef->mName;
  17580. }
  17581. CheckPropFail(matchedMethod, methodInstance.mMethodInstance, (mPropGetMethodFlags & BfGetMethodInstanceFlag_Friend) == 0);
  17582. PerformCallChecks(methodInstance.mMethodInstance, mPropSrc);
  17583. if (methodInstance.mMethodInstance->IsSkipCall())
  17584. {
  17585. mResult = mModule->GetDefaultTypedValue(methodInstance.mMethodInstance->mReturnType);
  17586. }
  17587. else
  17588. {
  17589. SizedArray<BfIRValue, 4> args;
  17590. if (!matchedMethod->mIsStatic)
  17591. {
  17592. auto owner = methodInstance.mMethodInstance->GetOwner();
  17593. bool isTypeMatch = mPropTarget.mType == owner;
  17594. if (owner->IsTypedPrimitive())
  17595. isTypeMatch |= mPropTarget.mType == owner->GetUnderlyingType();
  17596. if ((!isTypeMatch) ||
  17597. ((mPropTarget.mValue.IsFake()) && (!mOrigPropTarget.mValue.IsFake())))
  17598. {
  17599. auto prevPropTarget = mPropTarget;
  17600. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, owner);
  17601. if (!mPropTarget)
  17602. {
  17603. mModule->Fail("Internal property error", mPropSrc);
  17604. return BfTypedValue();
  17605. }
  17606. }
  17607. if ((mPropGetMethodFlags & BfGetMethodInstanceFlag_DisableObjectAccessChecks) == 0)
  17608. mModule->EmitObjectAccessCheck(mPropTarget);
  17609. }
  17610. SetAndRestoreValue<BfEvalExprFlags> prevExprFlags(mBfEvalExprFlags);
  17611. auto callFlags = mPropDefBypassVirtual ? BfCreateCallFlags_BypassVirtual : BfCreateCallFlags_None;
  17612. auto methodDef = methodInstance.mMethodInstance->mMethodDef;
  17613. if ((methodDef->mMethodDeclaration == NULL) && (mModule->mBfIRBuilder->IsConstValue(mPropTarget.mValue)) &&
  17614. (methodDef->mName == "get__Underlying"))
  17615. {
  17616. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  17617. }
  17618. mResult = CreateCall(mPropSrc, mPropTarget, mOrigPropTarget, matchedMethod, methodInstance, callFlags, mIndexerValues, NULL);
  17619. }
  17620. }
  17621. mPropDef = NULL;
  17622. mPropDefBypassVirtual = false;
  17623. mIndexerValues.clear();
  17624. mResultLocalVar = NULL;
  17625. mResultFieldInstance = NULL;
  17626. }
  17627. if (resolveGenericType)
  17628. ResolveGenericType();
  17629. BfTypedValue result = mResult;
  17630. if (clearResult)
  17631. mResult = BfTypedValue();
  17632. return result;
  17633. }
  17634. void BfExprEvaluator::CheckResultForReading(BfTypedValue& typedValue)
  17635. {
  17636. if (mModule->mCurMethodState == NULL)
  17637. return;
  17638. if ((mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCurMethodState->mAllowUinitReads))
  17639. return;
  17640. if ((mModule->mCurTypeInstance->mResolvingVarField) || (mModule->mCurTypeInstance->mResolvingConstField))
  17641. return;
  17642. if ((typedValue) && (typedValue.IsAddr()))
  17643. {
  17644. if ((mResultLocalVar != NULL) && (mResultLocalVarRefNode != NULL))
  17645. {
  17646. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors);
  17647. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  17648. {
  17649. // These errors can only be detected during capture time, so we don't ignore them on this pass
  17650. mModule->mIgnoreErrors = false;
  17651. }
  17652. int fieldIdx = mResultLocalVarField - 1;
  17653. auto localVar = mResultLocalVar;
  17654. /*if (localVar->mCompositeCount > 0)
  17655. {
  17656. mModule->Fail(StrFormat("Cannot read from composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  17657. typedValue = BfTypedValue();
  17658. return;
  17659. }*/
  17660. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  17661. {
  17662. mModule->TryLocalVariableInit(localVar);
  17663. }
  17664. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  17665. {
  17666. auto methodStateForLocal = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  17667. bool isAssigned = false;
  17668. int64 undefinedFieldFlags = localVar->mUnassignedFieldFlags;
  17669. auto deferredLocalAssignData = methodStateForLocal->mDeferredLocalAssignData;
  17670. while ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mIsChained))
  17671. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  17672. if (deferredLocalAssignData != NULL)
  17673. {
  17674. for (auto& assignedVar : deferredLocalAssignData->mAssignedLocals)
  17675. {
  17676. auto assignedLocal = assignedVar.mLocalVar;
  17677. if (assignedLocal == localVar)
  17678. {
  17679. int assignedFieldIdx = assignedVar.mLocalVarField;
  17680. if (assignedFieldIdx >= 0)
  17681. undefinedFieldFlags &= ~((int64)1 << assignedFieldIdx);
  17682. else
  17683. undefinedFieldFlags = 0;
  17684. }
  17685. }
  17686. if (deferredLocalAssignData->mLeftBlockUncond)
  17687. isAssigned = true;
  17688. }
  17689. if (fieldIdx == -1)
  17690. {
  17691. if (undefinedFieldFlags == 0)
  17692. isAssigned = true;
  17693. }
  17694. else
  17695. {
  17696. isAssigned = true;
  17697. for (int i = 0; i < mResultLocalVarFieldCount; i++)
  17698. if ((undefinedFieldFlags & (1LL << (fieldIdx + i))) != 0)
  17699. isAssigned = false;
  17700. }
  17701. if (!isAssigned)
  17702. {
  17703. if ((localVar->mIsThis) && (fieldIdx != -1))
  17704. {
  17705. // When we have initializers for fields, they won't all be processed in the autocomplte case
  17706. if (!mModule->mCompiler->IsAutocomplete())
  17707. {
  17708. auto bfError = mModule->Fail(StrFormat("Use of possibly unassigned field '%s'", mResultLocalVarRefNode->ToString().c_str()), mResultLocalVarRefNode, true);
  17709. }
  17710. }
  17711. else
  17712. {
  17713. mModule->Fail(StrFormat("Use of unassigned local variable '%s'", localVar->mName.c_str()), mResultLocalVarRefNode);
  17714. }
  17715. }
  17716. }
  17717. localVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  17718. }
  17719. }
  17720. }
  17721. void BfExprEvaluator::FinishExpressionResult()
  17722. {
  17723. CheckResultForReading(mResult);
  17724. mResultLocalVar = NULL;
  17725. mResultFieldInstance = NULL;
  17726. }
  17727. bool BfExprEvaluator::CheckAllowValue(const BfTypedValue& typedValue, BfAstNode* refNode)
  17728. {
  17729. return true;
  17730. }
  17731. void BfExprEvaluator::MarkResultUsed()
  17732. {
  17733. if (mResultLocalVar != NULL)
  17734. {
  17735. mResultLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  17736. }
  17737. }
  17738. void BfExprEvaluator::MarkResultAssigned()
  17739. {
  17740. if (mResultLocalVar != NULL)
  17741. {
  17742. //int localIdx = mResultLocalVarIdx;
  17743. //if (localIdx == 0x7FFF)
  17744. //return;
  17745. auto localVar = mResultLocalVar;
  17746. int fieldIdx = mResultLocalVarField - 1;
  17747. int count = mResultLocalVarFieldCount;
  17748. if (fieldIdx == -1)
  17749. count = 1;
  17750. for (int i = 0; i < count; i++)
  17751. mModule->mCurMethodState->GetMethodStateForLocal(localVar)->LocalDefined(localVar, fieldIdx + i);
  17752. //if (localIdx != 0x7FFF)
  17753. {
  17754. if (localVar->mCompositeCount > 0)
  17755. {
  17756. mModule->Fail(StrFormat("Cannot write to composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  17757. }
  17758. }
  17759. }
  17760. }
  17761. void BfExprEvaluator::MakeResultAsValue()
  17762. {
  17763. // Expressions like parens will turn a variable reference into a simple value
  17764. mResultLocalVar = NULL;
  17765. mResultFieldInstance = NULL;
  17766. }
  17767. bool BfExprEvaluator::CheckIsBase(BfAstNode* checkNode)
  17768. {
  17769. if (checkNode == NULL)
  17770. return false;
  17771. if (!checkNode->Equals("base"))
  17772. return false;
  17773. auto autoComplete = GetAutoComplete();
  17774. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(checkNode)))
  17775. {
  17776. if ((mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->mBaseType != NULL))
  17777. autoComplete->SetDefinitionLocation(mModule->mCurTypeInstance->mBaseType->mTypeDef->GetRefNode());
  17778. }
  17779. return true;
  17780. }
  17781. bool BfExprEvaluator::CheckModifyResult(BfTypedValue& typedVal, BfAstNode* refNode, const char* modifyType, bool onlyNeedsMut, bool emitWarning, bool skipCopyOnMutate)
  17782. {
  17783. if (typedVal.mType->IsVar())
  17784. {
  17785. // Allow without error
  17786. return true;
  17787. }
  17788. BfLocalVariable* localVar = NULL;
  17789. bool isCapturedLocal = false;
  17790. if (mResultLocalVar != NULL)
  17791. {
  17792. localVar = mResultLocalVar;
  17793. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  17794. }
  17795. else if (typedVal.IsThis())
  17796. {
  17797. localVar = mModule->GetThisVariable();
  17798. }
  17799. else if (typedVal.IsSplat())
  17800. {
  17801. for (auto checkLocal : mModule->mCurMethodState->mLocals)
  17802. {
  17803. if (checkLocal->mAddr == typedVal.mValue)
  17804. {
  17805. localVar = checkLocal;
  17806. break;
  17807. }
  17808. }
  17809. }
  17810. else if (typedVal.mValue.IsArg())
  17811. {
  17812. auto methodState = mModule->mCurMethodState->GetNonCaptureState();
  17813. localVar = methodState->mLocals[typedVal.mValue.mId];
  17814. }
  17815. if ((typedVal.mKind == BfTypedValueKind_MutableValue) && (onlyNeedsMut))
  17816. {
  17817. return true;
  17818. }
  17819. bool canModify = typedVal.CanModify();
  17820. if (((typedVal.mKind == BfTypedValueKind_TempAddr) || (typedVal.mKind == BfTypedValueKind_CopyOnMutateAddr_Derived)) &&
  17821. (strcmp(modifyType, "assign to") == 0))
  17822. mModule->Warn(0, "Assigning to temporary copy of a value. Consider using 'ref' in value source declaration.", refNode);
  17823. auto _Fail = [&](const StringImpl& error, BfAstNode* refNode)
  17824. {
  17825. if (emitWarning)
  17826. return mModule->Warn(BfWarning_BF4204_AddressOfReadOnly, error, refNode);
  17827. else
  17828. return mModule->Fail(error, refNode);
  17829. };
  17830. if (localVar != NULL)
  17831. {
  17832. if (!canModify)
  17833. {
  17834. BfError* error = NULL;
  17835. if (localVar->mIsThis)
  17836. {
  17837. bool isClosure = false;
  17838. BfTypeInstance* checkTypeInst = localVar->mResolvedType->ToTypeInstance();
  17839. int fieldIdx = mResultLocalVarField - 1;
  17840. if ((!isCapturedLocal) && (mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mClosureType != NULL))
  17841. {
  17842. isClosure = true;
  17843. auto closureThis = mModule->mCurMethodState->mClosureState->mClosureType;
  17844. closureThis = checkTypeInst->mFieldInstances[0].mResolvedType->ToTypeInstance();
  17845. if (fieldIdx >= -1)
  17846. {
  17847. checkTypeInst = closureThis;
  17848. }
  17849. else
  17850. {
  17851. fieldIdx = -fieldIdx - 2;
  17852. isCapturedLocal = true;
  17853. }
  17854. }
  17855. if (fieldIdx < 0)
  17856. {
  17857. if (isClosure)
  17858. {
  17859. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  17860. error = _Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType), refNode);
  17861. else
  17862. error = _Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType), refNode);
  17863. }
  17864. else if (localVar->mResolvedType->IsValueType())
  17865. {
  17866. error = _Fail(StrFormat("Cannot %s 'this' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  17867. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17868. }
  17869. else
  17870. {
  17871. error = _Fail(StrFormat("Cannot %s 'this' because '%s' is a reference type.", modifyType,
  17872. mModule->TypeToString(localVar->mResolvedType).c_str()), refNode);
  17873. }
  17874. return false;
  17875. }
  17876. else if (mResultFieldInstance != NULL)
  17877. {
  17878. if (isCapturedLocal)
  17879. {
  17880. error = _Fail(StrFormat("Cannot %s read-only captured local variable '%s'. Consider adding by-reference capture specifier [&] to lambda and ensuring that captured value is not read-only.", modifyType,
  17881. mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  17882. }
  17883. else if (isClosure)
  17884. {
  17885. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  17886. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType,
  17887. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  17888. else
  17889. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType,
  17890. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  17891. }
  17892. else if (mResultFieldInstance->GetFieldDef()->mIsReadOnly)
  17893. {
  17894. error = _Fail(StrFormat("Cannot %s readonly field '%s.%s' within method '%s'", modifyType,
  17895. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  17896. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17897. }
  17898. else if (mResultFieldInstance->GetFieldDef()->mIsAppend)
  17899. {
  17900. error = _Fail(StrFormat("Cannot %s append field '%s.%s' within method '%s'", modifyType,
  17901. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  17902. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17903. }
  17904. else if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(mResultFieldInstance->GetFieldDef()->mFieldDeclaration))
  17905. {
  17906. String propNam;
  17907. if (propertyDeclaration->mNameNode != NULL)
  17908. propertyDeclaration->mNameNode->ToString(propNam);
  17909. error = _Fail(StrFormat("Cannot %s auto-implemented property '%s.%s' without set accessor", modifyType,
  17910. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), propNam.c_str()), refNode);
  17911. }
  17912. else
  17913. {
  17914. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  17915. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  17916. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17917. }
  17918. return false;
  17919. }
  17920. }
  17921. else if (localVar->IsParam())
  17922. {
  17923. if (!mModule->mCurMethodInstance->IsMixin())
  17924. {
  17925. if (mModule->mCurMethodState->mMixinState != NULL)
  17926. {
  17927. error = _Fail(StrFormat("Cannot %s mixin parameter '%s'", modifyType,
  17928. localVar->mName.c_str()), refNode);
  17929. }
  17930. else if ((onlyNeedsMut) && (localVar->mResolvedType != NULL) && (localVar->mResolvedType->IsGenericParam()))
  17931. {
  17932. if (emitWarning)
  17933. error = _Fail(StrFormat("The address of '%s' may be temporary or immutable. Consider adding 'mut' or 'ref' specifier to parameter or declaring 'var %s;' to create a mutable copy.",
  17934. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  17935. else
  17936. error = _Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'mut' or 'ref' specifier to parameter or declaring 'var %s;' to create a mutable copy.", modifyType,
  17937. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  17938. }
  17939. else
  17940. {
  17941. if (emitWarning)
  17942. error = _Fail(StrFormat("The address of '%s' may be temporary or immutable. Consider adding 'ref' specifier to parameter or declaring 'var %s;' to create a mutable copy.",
  17943. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  17944. else
  17945. error = _Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'ref' specifier to parameter or declaring 'var %s;' to create a mutable copy.", modifyType,
  17946. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  17947. }
  17948. return false;
  17949. }
  17950. }
  17951. else
  17952. {
  17953. if ((mResultLocalVarField != 0) && (!localVar->mIsReadOnly))
  17954. {
  17955. auto typeInst = localVar->mResolvedType->ToTypeInstance();
  17956. int dataIdx = mResultLocalVarField - 1;
  17957. if (typeInst != NULL)
  17958. {
  17959. for (auto& field : typeInst->mFieldInstances)
  17960. {
  17961. if (field.mDataIdx == dataIdx)
  17962. {
  17963. error = _Fail(StrFormat("Cannot %s readonly field '%s.%s'.", modifyType,
  17964. mModule->TypeToString(typeInst).c_str(),
  17965. field.GetFieldDef()->mName.c_str()), refNode);
  17966. break;
  17967. }
  17968. }
  17969. }
  17970. }
  17971. if (error == NULL)
  17972. {
  17973. error = _Fail(StrFormat("Cannot %s read-only local variable '%s'.", modifyType,
  17974. localVar->mName.c_str()), refNode);
  17975. }
  17976. return false;
  17977. }
  17978. }
  17979. else
  17980. {
  17981. // When we are capturing, we need to note that we require capturing by reference here
  17982. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  17983. }
  17984. }
  17985. if ((mResultFieldInstance != NULL) && (mResultFieldInstance->GetFieldDef()->mIsReadOnly) && (!canModify))
  17986. {
  17987. if (mModule->mCurMethodInstance != NULL)
  17988. {
  17989. auto error = _Fail(StrFormat("Cannot %s static readonly field '%s.%s' within method '%s'", modifyType,
  17990. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  17991. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17992. }
  17993. return false;
  17994. }
  17995. if ((!skipCopyOnMutate) && (typedVal.IsCopyOnMutate()))
  17996. typedVal = mModule->CopyValue(typedVal);
  17997. if ((emitWarning) && (typedVal.IsReadOnly()))
  17998. {
  17999. mModule->Warn(0, StrFormat("Cannot %s read-only variable", modifyType), refNode);
  18000. return true;
  18001. }
  18002. return mModule->CheckModifyValue(typedVal, refNode, modifyType);
  18003. }
  18004. void BfExprEvaluator::Visit(BfConditionalExpression* condExpr)
  18005. {
  18006. static int sCallCount = 0;
  18007. sCallCount++;
  18008. auto condResult = mModule->CreateValueFromExpression(condExpr->mConditionExpression, mModule->GetPrimitiveType(BfTypeCode_Boolean), (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  18009. if (!condResult)
  18010. return;
  18011. if (condExpr->mTrueExpression == NULL)
  18012. {
  18013. mModule->AssertErrorState();
  18014. return;
  18015. }
  18016. if (condExpr->mFalseExpression == NULL)
  18017. {
  18018. mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, BfEvalExprFlags_NoCast);
  18019. mModule->AssertErrorState();
  18020. return;
  18021. }
  18022. bool isConstBranch = false;
  18023. bool constResult = false;
  18024. bool constResultUndef = false;
  18025. if (condResult.mValue.IsConst())
  18026. {
  18027. auto constValue = mModule->mBfIRBuilder->GetConstant(condResult.mValue);
  18028. if (constValue->mTypeCode == BfTypeCode_Boolean)
  18029. {
  18030. isConstBranch = true;
  18031. constResult = constValue->mBool;
  18032. }
  18033. else if (constValue->mConstType == BfConstType_Undef)
  18034. {
  18035. isConstBranch = true;
  18036. constResultUndef = true;
  18037. }
  18038. }
  18039. if (isConstBranch)
  18040. {
  18041. BfExpression* actualExpr = (constResult) ? condExpr->mTrueExpression : condExpr->mFalseExpression;
  18042. BfExpression* ignoredExpr = (constResult) ? condExpr->mFalseExpression : condExpr->mTrueExpression;
  18043. BfTypedValue actualValue = mModule->CreateValueFromExpression(actualExpr, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  18044. BfTypedValue ignoredValue;
  18045. //
  18046. {
  18047. auto curBlock = mModule->mBfIRBuilder->GetInsertBlock();
  18048. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  18049. SetAndRestoreValue<bool> prevInConstIgnore(mModule->mCurMethodState->mCurScope->mInConstIgnore, true);
  18050. ignoredValue = mModule->CreateValueFromExpression(ignoredExpr, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  18051. mModule->mBfIRBuilder->SetInsertPoint(curBlock);
  18052. }
  18053. if (!actualValue)
  18054. return;
  18055. if ((ignoredValue) && (ignoredValue.mType != actualValue.mType) && (!ignoredValue.mType->IsVar()))
  18056. {
  18057. // Cast to more specific 'ignored' type if applicable
  18058. if (mModule->CanCast(actualValue, ignoredValue.mType))
  18059. {
  18060. actualValue = mModule->Cast(actualExpr, actualValue, ignoredValue.mType);
  18061. }
  18062. else if (!mModule->CanCast(ignoredValue, actualValue.mType))
  18063. {
  18064. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  18065. mModule->TypeToString(actualValue.mType).c_str(), mModule->TypeToString(ignoredValue.mType).c_str()), condExpr);
  18066. }
  18067. }
  18068. mResult = actualValue;
  18069. if (constResultUndef)
  18070. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Undef);
  18071. return;
  18072. }
  18073. auto trueBB = mModule->mBfIRBuilder->CreateBlock("cond.then");
  18074. auto falseBB = mModule->mBfIRBuilder->CreateBlock("cond.else");
  18075. auto endBB = mModule->mBfIRBuilder->CreateBlock("cond.end");
  18076. auto contBB = mModule->mBfIRBuilder->CreateBlock("cond.cont");
  18077. mModule->mBfIRBuilder->CreateCondBr(condResult.mValue, trueBB, falseBB);
  18078. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mCurScope->mInnerIsConditional, true);
  18079. bool wantExpectingCast = (mExpectingType != NULL) && ((mBfEvalExprFlags & BfEvalExprFlags_NoCast) == 0);
  18080. mModule->AddBasicBlock(trueBB);
  18081. auto trueValue = mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  18082. if ((wantExpectingCast) && (trueValue) && (trueValue.mType != mExpectingType))
  18083. {
  18084. // In some cases like typed primitives - we CAN individually cast each value which it's a constant still, but not after the merging
  18085. // IE: Color c = isOver ? 0xFF000000 : 0xFFFFFFFF;
  18086. // Otherwise the resulting value would just be 'int' which cannot implicitly convert to Color, but each of those ints can be
  18087. // a uint32 if converted separately
  18088. auto checkTrueValue = mModule->Cast(condExpr->mTrueExpression, trueValue, mExpectingType, BfCastFlags_SilentFail);
  18089. if (checkTrueValue)
  18090. trueValue = checkTrueValue;
  18091. mModule->FixIntUnknown(trueValue);
  18092. }
  18093. auto trueBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  18094. mModule->AddBasicBlock(falseBB);
  18095. auto falseValue = mModule->CreateValueFromExpression(condExpr->mFalseExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  18096. auto falseBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  18097. if ((wantExpectingCast) && (falseValue) && (falseValue.mType != mExpectingType))
  18098. {
  18099. auto checkFalseValue = mModule->Cast(condExpr->mFalseExpression, falseValue, mExpectingType, BfCastFlags_SilentFail);
  18100. if (checkFalseValue)
  18101. falseValue = checkFalseValue;
  18102. mModule->FixIntUnknown(falseValue);
  18103. }
  18104. bool isValid = trueValue && falseValue;
  18105. if (isValid)
  18106. {
  18107. BfTypedValue falseToTrue;
  18108. {
  18109. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  18110. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  18111. falseToTrue = mModule->Cast(condExpr->mFalseExpression, falseValue, trueValue.mType);
  18112. }
  18113. if (falseToTrue)
  18114. {
  18115. falseValue = falseToTrue;
  18116. }
  18117. else
  18118. {
  18119. BfTypedValue trueToFalse;
  18120. {
  18121. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  18122. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  18123. trueToFalse = mModule->Cast(condExpr->mTrueExpression, trueValue, falseValue.mType);
  18124. }
  18125. if (!trueToFalse)
  18126. {
  18127. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  18128. mModule->TypeToString(trueValue.mType).c_str(), mModule->TypeToString(falseValue.mType).c_str()), condExpr);
  18129. //return;
  18130. isValid = false;
  18131. }
  18132. else
  18133. trueValue = trueToFalse;
  18134. }
  18135. }
  18136. prevInCondBlock.Restore();
  18137. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  18138. if (isValid)
  18139. trueValue = mModule->LoadValue(trueValue);
  18140. mModule->mBfIRBuilder->CreateBr(endBB);
  18141. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  18142. if (isValid)
  18143. falseValue = mModule->LoadValue(falseValue);
  18144. mModule->mBfIRBuilder->CreateBr(endBB);
  18145. mModule->AddBasicBlock(endBB, false);
  18146. if (!isValid)
  18147. return;
  18148. mModule->mBfIRBuilder->SetInsertPoint(endBB);
  18149. BfIRValue phi;
  18150. if (!trueValue.mType->IsValuelessType())
  18151. {
  18152. if (trueValue.mType->IsVar())
  18153. {
  18154. phi = mModule->mBfIRBuilder->GetFakeVal();
  18155. }
  18156. else
  18157. {
  18158. mModule->mBfIRBuilder->PopulateType(trueValue.mType);
  18159. phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(trueValue.mType), 2);
  18160. mModule->mBfIRBuilder->AddPhiIncoming(phi, trueValue.mValue, trueBlockPos);
  18161. mModule->mBfIRBuilder->AddPhiIncoming(phi, falseValue.mValue, falseBlockPos);
  18162. }
  18163. }
  18164. mModule->mBfIRBuilder->CreateBr(contBB);
  18165. mModule->AddBasicBlock(contBB);
  18166. mResult = BfTypedValue(phi, trueValue.mType);
  18167. }
  18168. void BfExprEvaluator::PopulateDeferrredTupleAssignData(BfTupleExpression* tupleExpr, DeferredTupleAssignData& deferredTupleAssignData)
  18169. {
  18170. BfTypeVector fieldTypes;
  18171. Array<String> fieldNames;
  18172. // We need to evaluate each LHS tuple component in a separate BfExprEvaluator because each one
  18173. // could be a property and the 'mPropDef' target info is tied to a single evaluator
  18174. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  18175. {
  18176. DeferredTupleAssignData::Entry entry;
  18177. entry.mExprEvaluator = NULL;
  18178. entry.mInnerTuple = NULL;
  18179. entry.mVarType = NULL;
  18180. entry.mVarNameNode = NULL;
  18181. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  18182. entry.mExpr = valueExpr;
  18183. BfType* fieldType = NULL;
  18184. BfType* resultType = NULL;
  18185. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(valueExpr))
  18186. {
  18187. entry.mInnerTuple = new DeferredTupleAssignData();
  18188. PopulateDeferrredTupleAssignData(innerTupleExpr, *entry.mInnerTuple);
  18189. resultType = entry.mInnerTuple->mTupleType;
  18190. }
  18191. else
  18192. {
  18193. BfExprEvaluator* exprEvaluator = new BfExprEvaluator(mModule);
  18194. entry.mExprEvaluator = exprEvaluator;
  18195. if (valueExpr->IsA<BfUninitializedExpression>())
  18196. {
  18197. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  18198. }
  18199. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(valueExpr))
  18200. {
  18201. if ((varDecl->mTypeRef->IsA<BfLetTypeReference>()) || (varDecl->mTypeRef->IsA<BfVarTypeReference>()))
  18202. {
  18203. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  18204. }
  18205. else
  18206. {
  18207. resultType = ResolveTypeRef(varDecl->mTypeRef);
  18208. if (resultType == NULL)
  18209. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  18210. }
  18211. entry.mVarType = resultType;
  18212. }
  18213. if (auto binOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>(valueExpr))
  18214. {
  18215. if (binOpExpr->mOp == BfBinaryOp_Multiply)
  18216. {
  18217. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  18218. auto resolvedType = mModule->ResolveTypeRef(binOpExpr->mLeft, NULL);
  18219. prevIgnoreError.Restore();
  18220. if (resolvedType != NULL)
  18221. {
  18222. resultType = mModule->CreatePointerType(resolvedType);
  18223. entry.mVarType = resultType;
  18224. entry.mVarNameNode = binOpExpr->mRight;
  18225. }
  18226. }
  18227. }
  18228. if (resultType == NULL)
  18229. {
  18230. exprEvaluator->VisitChild(valueExpr);
  18231. if ((!exprEvaluator->mResult) && (exprEvaluator->mPropDef == NULL))
  18232. exprEvaluator->mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  18233. resultType = exprEvaluator->mResult.mType;
  18234. }
  18235. if ((resultType == NULL) && (exprEvaluator->mPropDef != NULL) && (exprEvaluator->mPropTarget.mType != NULL))
  18236. {
  18237. auto propTypeInst = exprEvaluator->mPropTarget.mType->ToTypeInstance();
  18238. if ((propTypeInst == NULL) && (exprEvaluator->mPropTarget.mType->IsPointer()))
  18239. {
  18240. BfPointerType* pointerType = (BfPointerType*)exprEvaluator->mPropTarget.mType;
  18241. propTypeInst = pointerType->mElementType->ToTypeInstance();
  18242. }
  18243. auto setMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  18244. if (setMethod != NULL)
  18245. {
  18246. auto methodInstance = mModule->GetMethodInstance(propTypeInst, setMethod, BfTypeVector());
  18247. resultType = methodInstance.mMethodInstance->GetParamType(0);
  18248. }
  18249. else
  18250. {
  18251. auto getMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  18252. if (getMethod != NULL)
  18253. {
  18254. auto methodInstance = mModule->GetMethodInstance(propTypeInst, getMethod, BfTypeVector());
  18255. auto retType = methodInstance.mMethodInstance->mReturnType;
  18256. if (retType->IsRef())
  18257. resultType = retType->GetUnderlyingType();
  18258. }
  18259. }
  18260. }
  18261. }
  18262. if (resultType == NULL)
  18263. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  18264. deferredTupleAssignData.mChildren.push_back(entry);
  18265. fieldTypes.push_back(resultType);
  18266. }
  18267. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  18268. {
  18269. if (requestedName == NULL)
  18270. fieldNames.push_back("");
  18271. else
  18272. fieldNames.push_back(requestedName->mNameNode->ToString());
  18273. }
  18274. BfTypeInstance* tupleType = mModule->CreateTupleType(fieldTypes, fieldNames, true);
  18275. deferredTupleAssignData.mTupleType = tupleType;
  18276. }
  18277. void BfExprEvaluator::AssignDeferrredTupleAssignData(BfAssignmentExpression* assignExpr, DeferredTupleAssignData& deferredTupleAssignData, BfTypedValue rightValue)
  18278. {
  18279. BF_ASSERT(rightValue.mType->IsTuple());
  18280. auto tupleType = (BfTypeInstance*)rightValue.mType;
  18281. for (int valueIdx = 0; valueIdx < (int)deferredTupleAssignData.mChildren.size(); valueIdx++)
  18282. {
  18283. auto& child = deferredTupleAssignData.mChildren[valueIdx];
  18284. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[valueIdx];
  18285. BfTypedValue elementValue;
  18286. if (fieldInstance->mDataIdx >= 0)
  18287. {
  18288. rightValue = mModule->LoadOrAggregateValue(rightValue);
  18289. mModule->mBfIRBuilder->PopulateType(rightValue.mType);
  18290. auto extractedValue = mModule->mBfIRBuilder->CreateExtractValue(rightValue.mValue, fieldInstance->mDataIdx);
  18291. elementValue = BfTypedValue(extractedValue, fieldInstance->GetResolvedType());
  18292. if (child.mInnerTuple != NULL)
  18293. {
  18294. AssignDeferrredTupleAssignData(assignExpr, *child.mInnerTuple, elementValue);
  18295. delete child.mInnerTuple;
  18296. child.mInnerTuple = NULL;
  18297. }
  18298. else
  18299. {
  18300. if (child.mExprEvaluator->HasResult())
  18301. {
  18302. child.mExprEvaluator->mBfEvalExprFlags = (BfEvalExprFlags)(child.mExprEvaluator->mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete);
  18303. child.mExprEvaluator->PerformAssignment(assignExpr, true, elementValue);
  18304. }
  18305. }
  18306. }
  18307. if (child.mVarType != NULL)
  18308. {
  18309. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(child.mExpr))
  18310. {
  18311. if (!elementValue)
  18312. elementValue = mModule->GetDefaultTypedValue(fieldInstance->GetResolvedType());
  18313. mModule->HandleVariableDeclaration(varDecl, elementValue);
  18314. }
  18315. else
  18316. {
  18317. // This handles the 'a*b' disambiguated variable decl case
  18318. mModule->HandleVariableDeclaration(child.mVarType, child.mVarNameNode, elementValue);
  18319. }
  18320. }
  18321. }
  18322. }
  18323. void BfExprEvaluator::DoTupleAssignment(BfAssignmentExpression* assignExpr)
  18324. {
  18325. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(assignExpr->mLeft);
  18326. DeferredTupleAssignData deferredTupleAssignData;
  18327. PopulateDeferrredTupleAssignData(tupleExpr, deferredTupleAssignData);
  18328. BfTypeInstance* tupleType = deferredTupleAssignData.mTupleType;
  18329. BfTypedValue rightValue;
  18330. if (assignExpr->mRight != NULL)
  18331. {
  18332. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, tupleType);
  18333. }
  18334. if (!rightValue)
  18335. {
  18336. tupleType = mModule->SantizeTupleType(tupleType);
  18337. rightValue = mModule->GetDefaultTypedValue(tupleType);
  18338. }
  18339. rightValue = mModule->LoadValue(rightValue);
  18340. AssignDeferrredTupleAssignData(assignExpr, deferredTupleAssignData, rightValue);
  18341. mResult = rightValue;
  18342. }
  18343. BfTypedValue BfExprEvaluator::PerformAssignment_CheckOp(BfAssignmentExpression* assignExpr, bool deferBinop, BfTypedValue& leftValue, BfTypedValue& rightValue, bool& evaluatedRight)
  18344. {
  18345. BfResolvedArgs argValues;
  18346. auto checkTypeInst = leftValue.mType->ToTypeInstance();
  18347. while (checkTypeInst != NULL)
  18348. {
  18349. for (auto operatorDef : checkTypeInst->mTypeDef->mOperators)
  18350. {
  18351. if (operatorDef->mOperatorDeclaration->mAssignOp != assignExpr->mOp)
  18352. continue;
  18353. auto methodInst = mModule->GetRawMethodInstanceAtIdx(checkTypeInst, operatorDef->mIdx);
  18354. if (methodInst == NULL)
  18355. continue;
  18356. if (methodInst->GetParamCount() != 1)
  18357. continue;
  18358. auto paramType = methodInst->GetParamType(0);
  18359. if (deferBinop)
  18360. {
  18361. if (argValues.mArguments == NULL)
  18362. {
  18363. SizedArray<BfExpression*, 2> argExprs;
  18364. argExprs.push_back(assignExpr->mRight);
  18365. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  18366. argValues.Init(&sizedArgExprs);
  18367. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  18368. }
  18369. evaluatedRight = true;
  18370. rightValue = ResolveArgValue(argValues.mResolvedArgs[0], paramType);
  18371. if (!rightValue)
  18372. continue;
  18373. }
  18374. else
  18375. {
  18376. if (!mModule->CanCast(rightValue, paramType))
  18377. continue;
  18378. rightValue = mModule->Cast(assignExpr->mLeft, rightValue, paramType);
  18379. BF_ASSERT(rightValue);
  18380. }
  18381. mModule->SetElementType(assignExpr->mOpToken, BfSourceElementType_Method);
  18382. auto autoComplete = GetAutoComplete();
  18383. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mOpToken)))
  18384. {
  18385. if (operatorDef->mOperatorDeclaration != NULL)
  18386. autoComplete->SetDefinitionLocation(operatorDef->mOperatorDeclaration->mOpTypeToken);
  18387. }
  18388. auto moduleMethodInstance = mModule->GetMethodInstance(checkTypeInst, operatorDef, BfTypeVector());
  18389. BfExprEvaluator exprEvaluator(mModule);
  18390. SizedArray<BfIRValue, 1> args;
  18391. exprEvaluator.PushThis(assignExpr->mLeft, leftValue, moduleMethodInstance.mMethodInstance, args);
  18392. exprEvaluator.PushArg(rightValue, args);
  18393. exprEvaluator.CreateCall(assignExpr, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, args);
  18394. return leftValue;
  18395. }
  18396. checkTypeInst = mModule->GetBaseType(checkTypeInst);
  18397. }
  18398. return BfTypedValue();
  18399. }
  18400. void BfExprEvaluator::PerformAssignment(BfAssignmentExpression* assignExpr, bool evaluatedLeft, BfTypedValue rightValue, BfTypedValue* outCascadeValue)
  18401. {
  18402. auto binaryOp = BfAssignOpToBinaryOp(assignExpr->mOp);
  18403. BfExpression* targetNode = assignExpr->mLeft;
  18404. if ((BfNodeIsA<BfMixinExpression>(targetNode)) && (!mModule->mCurMethodInstance->mIsUnspecialized))
  18405. {
  18406. // If we have a "mixin = <X>" but there's no mixin target then ignore the assignment
  18407. int mixinVar = GetMixinVariable();
  18408. if (mixinVar == -1)
  18409. {
  18410. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  18411. return;
  18412. }
  18413. }
  18414. BfAutoComplete* autoComplete = GetAutoComplete();
  18415. bool deferredFixits = false;
  18416. //TODO: Why was this needed? This breaks fixits on target nodes (ie: 'using' field fixit for 'fully quality')
  18417. /*if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetFixits))
  18418. {
  18419. SetAndRestoreValue<bool> ignoreFixits(autoComplete->mIgnoreFixits, true);
  18420. VisitChild(targetNode);
  18421. deferredFixits = true;
  18422. }
  18423. else*/
  18424. if (!evaluatedLeft)
  18425. {
  18426. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(targetNode))
  18427. {
  18428. DoMemberReference(memberReferenceExpr, outCascadeValue);
  18429. }
  18430. else
  18431. VisitChild(targetNode);
  18432. }
  18433. if ((!mResult) && (mPropDef == NULL))
  18434. {
  18435. if (assignExpr->mRight != NULL)
  18436. {
  18437. auto result = mModule->CreateValueFromExpression(assignExpr->mRight);
  18438. if (deferredFixits)
  18439. {
  18440. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  18441. mExpectingType = result.mType;
  18442. VisitChild(targetNode);
  18443. mResult = BfTypedValue();
  18444. }
  18445. }
  18446. return;
  18447. }
  18448. ResolveGenericType();
  18449. auto ptr = mModule->RemoveRef(mResult);
  18450. mResult = BfTypedValue();
  18451. if (mPropDef != NULL)
  18452. {
  18453. bool hasLeftVal = false;
  18454. auto propDef = mPropDef;
  18455. auto propTarget = mPropTarget;
  18456. auto setMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  18457. if (setMethod == NULL)
  18458. {
  18459. // Allow for a ref return on the getter to be used if a setter is not available
  18460. GetResult();
  18461. if ((mResult) && (mResult.mKind == BfTypedValueKind_Addr))
  18462. {
  18463. ptr = mResult;
  18464. mResult = BfTypedValue();
  18465. hasLeftVal = true;
  18466. }
  18467. else
  18468. {
  18469. mModule->Fail("Property has no setter", mPropSrc);
  18470. if (assignExpr->mRight != NULL)
  18471. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, BfEvalExprFlags_NoCast);
  18472. return;
  18473. }
  18474. }
  18475. if (!hasLeftVal)
  18476. {
  18477. auto methodInstance = GetPropertyMethodInstance(setMethod);
  18478. if (methodInstance.mMethodInstance == NULL)
  18479. return;
  18480. //BF_ASSERT(methodInstance.mMethodInstance->mMethodDef == setMethod);
  18481. CheckPropFail(setMethod, methodInstance.mMethodInstance, (mPropGetMethodFlags & BfGetMethodInstanceFlag_Friend) == 0);
  18482. auto autoComplete = GetAutoComplete();
  18483. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(mPropSrc)) && (autoComplete->mResolveType == BfResolveType_GetResultString))
  18484. {
  18485. autoComplete->mResultString = ":";
  18486. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetParamType(0));
  18487. autoComplete->mResultString += " ";
  18488. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetOwner());
  18489. autoComplete->mResultString += ".";
  18490. autoComplete->mResultString += mPropDef->mName;
  18491. }
  18492. bool handled = false;
  18493. BfTypedValue convVal;
  18494. if (binaryOp != BfBinaryOp_None)
  18495. {
  18496. BfTypedValue leftValue = mModule->CreateValueFromExpression(assignExpr->mLeft, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  18497. if (!leftValue)
  18498. return;
  18499. bool evaluatedRight = false;
  18500. auto opResult = PerformAssignment_CheckOp(assignExpr, true, leftValue, rightValue, evaluatedRight);
  18501. if (opResult)
  18502. {
  18503. mResult = opResult;
  18504. return;
  18505. }
  18506. else
  18507. {
  18508. if (evaluatedRight)
  18509. {
  18510. if (!rightValue)
  18511. return;
  18512. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType, leftValue, rightValue);
  18513. }
  18514. else
  18515. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType, leftValue);
  18516. if (!mResult)
  18517. return;
  18518. convVal = mResult;
  18519. mResult = BfTypedValue();
  18520. if (!convVal)
  18521. return;
  18522. }
  18523. }
  18524. else
  18525. {
  18526. auto wantType = methodInstance.mMethodInstance->GetParamType(0);
  18527. if (rightValue)
  18528. {
  18529. convVal = mModule->Cast(assignExpr->mRight, rightValue, wantType);
  18530. }
  18531. else
  18532. {
  18533. if (assignExpr->mRight == NULL)
  18534. {
  18535. mModule->AssertErrorState();
  18536. return;
  18537. }
  18538. BfEvalExprFlags exprFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_PendingPropSet);
  18539. if (wantType->IsRef())
  18540. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AllowRefExpr);
  18541. convVal = mModule->CreateValueFromExpression(assignExpr->mRight, wantType, exprFlags);
  18542. }
  18543. if (!convVal)
  18544. {
  18545. mPropDef = NULL;
  18546. return;
  18547. }
  18548. }
  18549. if (!handled)
  18550. {
  18551. if (mPropSrc != NULL)
  18552. mModule->UpdateExprSrcPos(mPropSrc);
  18553. BfResolvedArg valueArg;
  18554. valueArg.mTypedValue = convVal;
  18555. mIndexerValues.Insert(0, valueArg);
  18556. if (!setMethod->mIsStatic)
  18557. {
  18558. auto owner = methodInstance.mMethodInstance->GetOwner();
  18559. if ((mPropTarget.mType != owner) ||
  18560. ((mPropTarget.mValue.IsFake()) && (!mOrigPropTarget.mValue.IsFake())))
  18561. {
  18562. if ((mPropDefBypassVirtual) || (!mPropTarget.mType->IsInterface()))
  18563. {
  18564. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, owner);
  18565. if (!mPropTarget)
  18566. {
  18567. mModule->Fail("Internal property error", mPropSrc);
  18568. return;
  18569. }
  18570. }
  18571. }
  18572. }
  18573. auto callFlags = mPropDefBypassVirtual ? BfCreateCallFlags_BypassVirtual : BfCreateCallFlags_None;
  18574. mResult = CreateCall(mPropSrc, mPropTarget, mOrigPropTarget, setMethod, methodInstance, callFlags, mIndexerValues, NULL);
  18575. mPropDef = NULL;
  18576. mResult = convVal;
  18577. mIndexerValues.Clear();
  18578. return;
  18579. }
  18580. }
  18581. }
  18582. auto toType = ptr.mType;
  18583. if (toType->IsRef())
  18584. {
  18585. auto refType = (BfRefType*)toType;
  18586. toType = refType->mElementType;
  18587. }
  18588. if (toType->IsIntUnknown())
  18589. toType = mModule->FixIntUnknown(toType);
  18590. if ((autoComplete != NULL) && (assignExpr->mOpToken != NULL) && (toType != NULL))
  18591. autoComplete->CheckEmptyStart(assignExpr->mOpToken, toType);
  18592. BfExpression* rightExpr = assignExpr->mRight;
  18593. if (rightExpr == NULL)
  18594. {
  18595. mModule->AssertErrorState();
  18596. return;
  18597. }
  18598. bool alreadyWritten = false;
  18599. BfTypedValue convVal;
  18600. if (binaryOp != BfBinaryOp_None)
  18601. {
  18602. CheckResultForReading(ptr);
  18603. BfTypedValue leftValue = ptr;
  18604. bool deferBinop = false;
  18605. BfDeferEvalChecker deferEvalChecker;
  18606. deferEvalChecker.mDeferLiterals = false;
  18607. assignExpr->mRight->Accept(&deferEvalChecker);
  18608. if (deferEvalChecker.mNeedsDeferEval)
  18609. deferBinop = true;
  18610. if (binaryOp == BfBinaryOp_NullCoalesce)
  18611. {
  18612. deferBinop = true;
  18613. }
  18614. if (!deferBinop)
  18615. {
  18616. auto expectedType = ptr.mType;
  18617. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  18618. expectedType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  18619. if ((!rightValue) && (assignExpr->mRight != NULL))
  18620. {
  18621. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, expectedType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  18622. }
  18623. }
  18624. BfResolvedArgs argValues;
  18625. if ((rightValue) || (deferBinop))
  18626. {
  18627. bool evaluatedRight = false;
  18628. auto opResult = PerformAssignment_CheckOp(assignExpr, deferBinop, leftValue, rightValue, evaluatedRight);
  18629. if (opResult)
  18630. {
  18631. mResult = opResult;
  18632. return;
  18633. }
  18634. else
  18635. {
  18636. auto flags = BfBinOpFlag_ForceLeftType;
  18637. if (deferBinop)
  18638. flags = (BfBinOpFlags)(flags | BfBinOpFlag_DeferRight);
  18639. leftValue = mModule->LoadValue(leftValue);
  18640. if (binaryOp == BfBinaryOp_NullCoalesce)
  18641. {
  18642. if (!CheckModifyResult(ptr, assignExpr->mOpToken, "assign to", false, false, true))
  18643. {
  18644. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  18645. mResult = leftValue;
  18646. return;
  18647. }
  18648. if (PerformBinaryOperation_NullCoalesce(assignExpr->mOpToken, assignExpr->mLeft, assignExpr->mRight, leftValue, leftValue.mType, &ptr))
  18649. return;
  18650. }
  18651. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, flags, leftValue, rightValue);
  18652. }
  18653. }
  18654. convVal = mResult;
  18655. mResult = BfTypedValue();
  18656. if (!convVal)
  18657. return;
  18658. }
  18659. else
  18660. {
  18661. convVal = rightValue;
  18662. if (!convVal)
  18663. {
  18664. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(rightExpr))
  18665. {
  18666. if (mResultLocalVar != NULL)
  18667. {
  18668. MarkResultAssigned();
  18669. return;
  18670. }
  18671. }
  18672. // In the cases like "structVal = GetVal()", the allowDirectStructRetWrite optimization allows us to pass the
  18673. // address of structVal into the sret. We only allow that if structVal is a local, because if it's globally
  18674. // visible then we could see the results of a partially-modified structVal
  18675. //bool allowDirectStructRetWrite = mResultLocalVarIdx != -1;
  18676. // ALTHOUGH- we can only allow this optimization if we can be sure the local value is not aliased- we could
  18677. // have the backend ensure that this local value never gets its address taken.
  18678. bool allowDirectStructWrite = false;
  18679. BfExprEvaluator exprEvaluator(mModule);
  18680. exprEvaluator.mExpectingType = toType;
  18681. if (allowDirectStructWrite)
  18682. exprEvaluator.mReceivingValue = &ptr;
  18683. exprEvaluator.Evaluate(rightExpr, false, false, true);
  18684. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  18685. convVal = exprEvaluator.GetResult();
  18686. mModule->FixIntUnknown(convVal);
  18687. alreadyWritten = (allowDirectStructWrite) && (exprEvaluator.mReceivingValue == NULL);
  18688. if (!convVal)
  18689. convVal = mModule->GetDefaultTypedValue(toType);
  18690. // Did we use mReceivingValue as a mixin result?
  18691. if ((convVal.mValue) && (convVal.mValue == ptr.mValue))
  18692. {
  18693. mResult = convVal;
  18694. return;
  18695. }
  18696. }
  18697. }
  18698. if (!CheckModifyResult(ptr, assignExpr->mOpToken, "assign to", false, false, true))
  18699. {
  18700. mResult = convVal;
  18701. return;
  18702. }
  18703. if (ptr.mKind == BfTypedValueKind_CopyOnMutateAddr)
  18704. ptr.mKind = BfTypedValueKind_Addr;
  18705. else if (ptr.IsCopyOnMutate())
  18706. ptr = mModule->CopyValue(ptr);
  18707. BF_ASSERT(convVal);
  18708. if ((convVal) && (convVal.mType->IsNull()) && (ptr.mType->IsNullable()))
  18709. {
  18710. // Allow this to pass through so we can catch it in the memset later in this function
  18711. }
  18712. else
  18713. {
  18714. if (!convVal.mType->IsComposite())
  18715. convVal = mModule->LoadValue(convVal);
  18716. convVal = mModule->Cast(rightExpr, convVal, toType);
  18717. if (!convVal)
  18718. return;
  18719. convVal = mModule->LoadValue(convVal);
  18720. }
  18721. if (ptr.mType->IsVar())
  18722. {
  18723. mResult = ptr;
  18724. MarkResultAssigned();
  18725. return;
  18726. }
  18727. if (convVal.mValue)
  18728. {
  18729. if ((ptr.mType->IsStruct()) && (!ptr.mType->IsValuelessType()) && (convVal.mValue.IsConst()))
  18730. {
  18731. auto constant = mModule->mBfIRBuilder->GetConstant(convVal.mValue);
  18732. if ((constant->mTypeCode == BfTypeCode_NullPtr) || (constant->mConstType == BfConstType_AggZero))
  18733. {
  18734. auto type = ptr.mType;
  18735. mModule->mBfIRBuilder->CreateMemSet(ptr.mValue, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  18736. mModule->GetConstValue(type->mSize), type->mAlign);
  18737. mResult = ptr;
  18738. MarkResultAssigned();
  18739. return;
  18740. }
  18741. }
  18742. // if (ptr.mType->IsMethodRef())
  18743. // {
  18744. // auto methodRefType = (BfMethodRefType*)ptr.mType;
  18745. // auto methodInstance = methodRefType->mMethodInstance;
  18746. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  18747. // for (int implicitParamIdx = methodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  18748. // {
  18749. // bool failed = false;
  18750. // auto destPtr = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericTypeMember_Addr);
  18751. // auto srcVal = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericMethodMember);
  18752. // if ((destPtr) && (srcVal))
  18753. // {
  18754. // srcVal = mModule->AggregateSplat(srcVal);
  18755. // mModule->mBfIRBuilder->CreateStore(srcVal.mValue, destPtr.mValue);
  18756. // }
  18757. // }
  18758. // }
  18759. // else
  18760. {
  18761. mModule->mBfIRBuilder->PopulateType(ptr.mType);
  18762. if (convVal.IsSplat())
  18763. {
  18764. //convVal = mModule->AggregateSplat(convVal);
  18765. mModule->AggregateSplatIntoAddr(convVal, ptr.mValue);
  18766. }
  18767. else
  18768. {
  18769. if (ptr.mType->IsOpaque())
  18770. {
  18771. mModule->Fail(StrFormat("Unable to assign to opaque type '%s'", mModule->TypeToString(ptr.mType).c_str()), assignExpr);
  18772. }
  18773. else if (ptr.mType->IsValuelessType())
  18774. {
  18775. mModule->EmitEnsureInstructionAt();
  18776. }
  18777. else if (!alreadyWritten)
  18778. {
  18779. if ((mModule->mIsComptimeModule) && (mModule->mCompiler->mCeMachine->mDebugger != NULL) && (mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  18780. {
  18781. auto ceDbgState = mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState;
  18782. bool success = false;
  18783. if ((convVal.mValue.IsConst()) && (ptr.mValue.IsConst()))
  18784. {
  18785. auto constant = mModule->mBfIRBuilder->GetConstant(ptr.mValue);
  18786. auto valConstant = mModule->mBfIRBuilder->GetConstant(convVal.mValue);
  18787. auto ceTypedVal = mModule->mCompiler->mCeMachine->mDebugger->GetAddr(constant);
  18788. if (!ceTypedVal)
  18789. {
  18790. mModule->Fail("Invalid assignment address", assignExpr);
  18791. return;
  18792. }
  18793. auto ceContext = mModule->mCompiler->mCeMachine->mCurContext;
  18794. if (ceContext->CheckMemory((addr_ce)ceTypedVal.mAddr, convVal.mType->mSize))
  18795. {
  18796. if ((ceDbgState->mDbgExpressionFlags & DwEvalExpressionFlag_AllowSideEffects) != 0)
  18797. {
  18798. ceDbgState->mHadSideEffects = true;
  18799. if (ceContext->WriteConstant(mModule, (addr_ce)ceTypedVal.mAddr, valConstant, convVal.mType))
  18800. success = true;
  18801. }
  18802. else
  18803. {
  18804. ceDbgState->mBlockedSideEffects = true;
  18805. success = true;
  18806. }
  18807. }
  18808. }
  18809. if (!success)
  18810. {
  18811. mModule->Fail("Assignment failed", assignExpr);
  18812. return;
  18813. }
  18814. }
  18815. if (!alreadyWritten)
  18816. {
  18817. //ptr = mModule->LoadValue(ptr);
  18818. BF_ASSERT(ptr.IsAddr());
  18819. convVal = mModule->LoadValue(convVal);
  18820. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(convVal.mValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  18821. }
  18822. }
  18823. }
  18824. }
  18825. }
  18826. else
  18827. {
  18828. BF_ASSERT(convVal.mType->IsValuelessType());
  18829. }
  18830. mResult = convVal;
  18831. MarkResultAssigned();
  18832. }
  18833. void BfExprEvaluator::Visit(BfAssignmentExpression* assignExpr)
  18834. {
  18835. if (assignExpr->mLeft->IsA<BfTupleExpression>())
  18836. {
  18837. DoTupleAssignment(assignExpr);
  18838. return;
  18839. }
  18840. BfAutoParentNodeEntry autoParentNodeEntry(mModule, assignExpr);
  18841. BfTypedValue cascadeValue;
  18842. PerformAssignment(assignExpr, false, BfTypedValue(), &cascadeValue);
  18843. if (cascadeValue)
  18844. mResult = cascadeValue;
  18845. }
  18846. void BfExprEvaluator::Visit(BfParenthesizedExpression* parenExpr)
  18847. {
  18848. VisitChild(parenExpr->mExpression);
  18849. MakeResultAsValue();
  18850. }
  18851. void BfExprEvaluator::InitializedSizedArray(BfSizedArrayType* arrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, BfTypedValue* receivingValue)
  18852. {
  18853. struct InitValue
  18854. {
  18855. BfTypedValue mValue;
  18856. bool mIsUninitialized;
  18857. bool mIsDefaultInitializer;
  18858. bool mIsDeferred;
  18859. InitValue()
  18860. {
  18861. mIsUninitialized = false;
  18862. mIsDefaultInitializer = false;
  18863. mIsDeferred = false;
  18864. }
  18865. };
  18866. SizedArray<InitValue, 8> values;
  18867. {
  18868. //bool hasFailed = false;
  18869. HashSet<int> failedAt;
  18870. bool isAllConst = true;
  18871. //bool endUninitialzied = false;
  18872. int depth = 0;
  18873. std::function<void(BfSizedArrayType*, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*, bool)>
  18874. _GetValues = [&](BfSizedArrayType* checkArrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, bool ignore)
  18875. {
  18876. int64 initCountDiff = (int)valueExprs.size() - checkArrayType->mElementCount;
  18877. if ((initCountDiff != 0) && (!valueExprs.IsEmpty()) && (!failedAt.Contains(depth)))
  18878. {
  18879. if (checkArrayType->mElementCount == -1)
  18880. {
  18881. // mModule->Fail("Initializers not supported for unknown-sized arrays", valueExprs[0]);
  18882. // failedAt.Add(depth);
  18883. }
  18884. else if (initCountDiff > 0)
  18885. {
  18886. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[BF_MAX((int)checkArrayType->mElementCount, 0)]);
  18887. failedAt.Add(depth);
  18888. }
  18889. else
  18890. {
  18891. // If it ends with ", ?) or ",)" then allow unsized
  18892. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  18893. ((commas.size() < valueExprs.size()) || (valueExprs.size() == 0)))
  18894. {
  18895. BfAstNode* refNode = closeToken;
  18896. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  18897. refNode = mModule->mParentNodeEntry->mNode;
  18898. BF_ASSERT(refNode != NULL);
  18899. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  18900. failedAt.Add(depth);
  18901. }
  18902. }
  18903. }
  18904. for (int idx = 0; idx < BF_MAX(checkArrayType->mElementCount, valueExprs.size()); idx++)
  18905. {
  18906. BfTypedValue elementValue;
  18907. bool deferredValue = false;
  18908. BfExpression* expr = NULL;
  18909. if (idx < (int)valueExprs.size())
  18910. {
  18911. expr = valueExprs[idx];
  18912. if (expr == NULL)
  18913. {
  18914. if (idx == 0)
  18915. mModule->FailAfter("Expression expected", openToken);
  18916. else
  18917. mModule->FailAfter("Expression expected", commas[idx - 1]);
  18918. }
  18919. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  18920. {
  18921. isAllConst = false;
  18922. break;
  18923. }
  18924. if (checkArrayType->mElementType->IsSizedArray())
  18925. {
  18926. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  18927. {
  18928. depth++;
  18929. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen, ignore);
  18930. depth--;
  18931. continue;
  18932. }
  18933. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  18934. {
  18935. depth++;
  18936. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace, ignore);
  18937. depth--;
  18938. continue;
  18939. }
  18940. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  18941. {
  18942. depth++;
  18943. SizedArray<BfExpression*, 1> values;
  18944. values.Add(parenExpr->mExpression);
  18945. SizedArray<BfTokenNode*, 1> commas;
  18946. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, ignore);
  18947. depth--;
  18948. continue;
  18949. }
  18950. }
  18951. if (expr != NULL)
  18952. {
  18953. auto evalFlags = (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags);
  18954. bool tryDefer = false;
  18955. if ((checkArrayType->IsComposite()) &&
  18956. ((expr->IsA<BfInvocationExpression>()) || (expr->IsExact<BfTupleExpression>())))
  18957. {
  18958. // We evaluate with a new scope because this expression may create variables that we don't want to be visible to other
  18959. // non-deferred evaluations (since the value may actually be a FakeVal)
  18960. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  18961. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType, (BfEvalExprFlags)(evalFlags | BfEvalExprFlags_CreateConditionalScope));
  18962. deferredValue = !prevIgnoreWrites.mPrevVal && elementValue.mValue.IsFake();
  18963. }
  18964. else
  18965. {
  18966. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType, evalFlags);
  18967. }
  18968. if (!elementValue)
  18969. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  18970. if ((!elementValue) || (!CheckAllowValue(elementValue, expr)))
  18971. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  18972. // For now, we can't properly create const-valued non-size-aligned composites
  18973. if (!elementValue.mValue.IsConst())
  18974. isAllConst = false;
  18975. if (elementValue.IsAddr())
  18976. isAllConst = false;
  18977. InitValue initValue;
  18978. initValue.mValue = elementValue;
  18979. initValue.mIsDeferred = deferredValue;
  18980. values.push_back(initValue);
  18981. }
  18982. }
  18983. }
  18984. };
  18985. int valueIdx = 0;
  18986. std::function<void(BfTypedValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  18987. _CreateMemArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  18988. {
  18989. BF_ASSERT(arrayValue.mType->IsSizedArray());
  18990. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  18991. int valIdx = 0;
  18992. bool hasUninit = false;
  18993. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  18994. {
  18995. BfExpression* expr = NULL;
  18996. BfTypedValue elementValue;
  18997. if (idx >= (int)valueExprs.size())
  18998. break;
  18999. expr = valueExprs[idx];
  19000. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  19001. {
  19002. hasUninit = true;
  19003. break;
  19004. }
  19005. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  19006. valIdx++;
  19007. if (checkArrayType->mElementType->IsSizedArray())
  19008. {
  19009. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  19010. {
  19011. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen);
  19012. continue;
  19013. }
  19014. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  19015. {
  19016. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace);
  19017. continue;
  19018. }
  19019. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  19020. {
  19021. depth++;
  19022. SizedArray<BfExpression*, 1> values;
  19023. values.Add(parenExpr->mExpression);
  19024. SizedArray<BfTokenNode*, 1> commas;
  19025. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen);
  19026. depth--;
  19027. continue;
  19028. }
  19029. }
  19030. if (expr != NULL)
  19031. {
  19032. InitValue initValue = values[valueIdx++];
  19033. elementValue = initValue.mValue;
  19034. if (initValue.mIsDeferred)
  19035. {
  19036. BfTypedValue elemePtrTypedVal = BfTypedValue(elemPtrValue, checkArrayType->mElementType, BfTypedValueKind_Addr);
  19037. BfExprEvaluator exprEvaluator(mModule);
  19038. exprEvaluator.mExpectingType = checkArrayType->mElementType;
  19039. exprEvaluator.mReceivingValue = &elemePtrTypedVal;
  19040. exprEvaluator.Evaluate(expr);
  19041. exprEvaluator.GetResult();
  19042. if (exprEvaluator.mReceivingValue == NULL)
  19043. {
  19044. // We wrote directly to the array in-place, we're done with this element
  19045. continue;
  19046. }
  19047. elementValue = exprEvaluator.mResult;
  19048. elementValue = mModule->Cast(expr, elementValue, checkArrayType->mElementType);
  19049. if (!elementValue)
  19050. {
  19051. mModule->AssertErrorState();
  19052. continue;
  19053. }
  19054. }
  19055. elementValue = mModule->LoadOrAggregateValue(elementValue);
  19056. // Note that elemPtrValue can be a const GEP on a global variable
  19057. mModule->mBfIRBuilder->CreateAlignedStore(elementValue.mValue, elemPtrValue, checkArrayType->mElementType->mAlign);
  19058. }
  19059. }
  19060. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  19061. if (fillCount > 0)
  19062. {
  19063. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  19064. if (hasUninit)
  19065. {
  19066. if (!mModule->IsOptimized())
  19067. {
  19068. int setSize = std::min(checkArrayType->mElementType->mSize, 128); // Keep it to a reasonable number of bytes to trash
  19069. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0xCC),
  19070. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  19071. }
  19072. }
  19073. else
  19074. {
  19075. int setSize = (int)((checkArrayType->mElementType->GetStride() * (fillCount - 1)) + checkArrayType->mElementType->mSize);
  19076. if (setSize >= 0)
  19077. {
  19078. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0),
  19079. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  19080. }
  19081. }
  19082. }
  19083. };
  19084. std::function<BfIRValue(BfTypedValue, BfTokenNode*, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  19085. _CreateConstArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  19086. {
  19087. SizedArray<BfIRValue, 8> members;
  19088. BF_ASSERT(arrayValue.mType->IsSizedArray());
  19089. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  19090. int valIdx = 0;
  19091. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  19092. {
  19093. BfTypedValue elementValue;
  19094. if (idx >= (int)valueExprs.size())
  19095. break;
  19096. auto expr = valueExprs[idx];
  19097. if (expr == NULL)
  19098. continue;
  19099. valIdx++;
  19100. if (checkArrayType->mElementType->IsSizedArray())
  19101. {
  19102. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  19103. {
  19104. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen));
  19105. continue;
  19106. }
  19107. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  19108. {
  19109. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace));
  19110. continue;
  19111. }
  19112. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  19113. {
  19114. depth++;
  19115. SizedArray<BfExpression*, 1> values;
  19116. values.Add(parenExpr->mExpression);
  19117. SizedArray<BfTokenNode*, 1> commas;
  19118. members.push_back(_CreateConstArray(checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen));
  19119. depth--;
  19120. continue;
  19121. }
  19122. }
  19123. InitValue initValue = values[valueIdx++];
  19124. BF_ASSERT(!initValue.mIsUninitialized);
  19125. elementValue = initValue.mValue;
  19126. members.push_back(elementValue.mValue);
  19127. }
  19128. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  19129. if (fillCount > 0)
  19130. {
  19131. // We just need to insert one default value, it will be duplicated as needed into the backend
  19132. auto defaultVal = mModule->GetDefaultTypedValue(checkArrayType->GetUnderlyingType());
  19133. BF_ASSERT(defaultVal.mValue.IsConst());
  19134. members.push_back(defaultVal.mValue);
  19135. }
  19136. auto allocArrayType = checkArrayType;
  19137. if (checkArrayType->IsUndefSizedArray())
  19138. allocArrayType = mModule->CreateSizedArrayType(checkArrayType->GetUnderlyingType(), (int)members.size());
  19139. return mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(checkArrayType), members);
  19140. };
  19141. _GetValues(arrayType, openToken, valueExprs, commas, closeToken, false);
  19142. if (!failedAt.IsEmpty())
  19143. {
  19144. mResult = mModule->GetDefaultTypedValue(arrayType, false, BfDefaultValueKind_Addr);
  19145. return;
  19146. }
  19147. if (receivingValue != NULL)
  19148. {
  19149. BF_ASSERT(receivingValue->mType == arrayType);
  19150. BF_ASSERT(receivingValue->IsAddr());
  19151. mResult = *receivingValue;
  19152. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  19153. }
  19154. else if (isAllConst)
  19155. {
  19156. mResult = BfTypedValue(_CreateConstArray(arrayType, openToken, valueExprs, commas, closeToken), arrayType, BfTypedValueKind_Value);
  19157. }
  19158. else
  19159. {
  19160. if ((mReceivingValue != NULL) && (mReceivingValue->mType == arrayType) && (mReceivingValue->IsAddr()))
  19161. {
  19162. mResult = *mReceivingValue;
  19163. mReceivingValue = NULL;
  19164. }
  19165. else
  19166. {
  19167. auto arrayValue = mModule->CreateAlloca(arrayType);
  19168. mResult = BfTypedValue(arrayValue, arrayType, BfTypedValueKind_TempAddr);
  19169. }
  19170. if (!arrayType->IsValuelessType())
  19171. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  19172. }
  19173. }
  19174. }
  19175. void BfExprEvaluator::Visit(BfTupleExpression* tupleExpr)
  19176. {
  19177. BfTypeInstance* tupleType = NULL;
  19178. bool hadFullMatch = false;
  19179. if ((mExpectingType != NULL) && (mExpectingType->IsTuple()))
  19180. {
  19181. tupleType = (BfTypeInstance*)mExpectingType;
  19182. hadFullMatch = tupleType->mFieldInstances.size() == tupleExpr->mValues.size();
  19183. }
  19184. struct InitValue
  19185. {
  19186. BfTypedValue mValue;
  19187. bool mIsUninitialized;
  19188. bool mIsDefaultInitializer;
  19189. bool mIsDeferred;
  19190. InitValue()
  19191. {
  19192. mIsUninitialized = false;
  19193. mIsDefaultInitializer = false;
  19194. mIsDeferred = false;
  19195. }
  19196. };
  19197. SizedArray<BfTypedValue, 2> typedValues;
  19198. if ((tupleExpr->mCommas.size() != 0) && (tupleExpr->mCommas.size() >= tupleExpr->mValues.size()))
  19199. {
  19200. // We would normally give this error during syntax parsing, but a TupleExpression can be an array initializer
  19201. mModule->FailAfter("Expression expected", tupleExpr->mCommas.back());
  19202. }
  19203. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  19204. {
  19205. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  19206. BfType* fieldType = NULL;
  19207. BfFieldInstance* fieldInstance = NULL;
  19208. if (tupleType != NULL)
  19209. {
  19210. if (valueIdx < (int)tupleType->mFieldInstances.size())
  19211. {
  19212. fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[valueIdx];
  19213. fieldType = fieldInstance->GetResolvedType();
  19214. if (fieldType->IsVoid())
  19215. {
  19216. typedValues.push_back(BfTypedValue());
  19217. continue;
  19218. }
  19219. if (fieldType->IsVar())
  19220. {
  19221. hadFullMatch = false;
  19222. fieldType = NULL;
  19223. }
  19224. }
  19225. }
  19226. bool tryDefer = false;
  19227. if (((fieldType == NULL) || (fieldType->IsComposite())) &&
  19228. ((valueExpr->IsA<BfInvocationExpression>()) || (valueExpr->IsExact<BfTupleExpression>())))
  19229. {
  19230. tryDefer = true;
  19231. }
  19232. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || tryDefer);
  19233. BfTypedValue value = mModule->CreateValueFromExpression(valueExpr, fieldType);
  19234. if (!value)
  19235. {
  19236. if (fieldType != NULL)
  19237. value = mModule->GetDefaultTypedValue(fieldType);
  19238. else
  19239. value = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  19240. }
  19241. if ((fieldInstance != NULL) && (!fieldInstance->GetFieldDef()->IsUnnamedTupleField()) && (valueIdx < (int)tupleExpr->mNames.size()))
  19242. {
  19243. auto checkName = tupleExpr->mNames[valueIdx];
  19244. if (checkName != NULL)
  19245. {
  19246. if (checkName->ToString() != fieldInstance->GetFieldDef()->mName)
  19247. hadFullMatch = false;
  19248. }
  19249. }
  19250. value = mModule->LoadValue(value);
  19251. typedValues.push_back(value);
  19252. }
  19253. if (!hadFullMatch)
  19254. {
  19255. BfTypeVector fieldTypes;
  19256. Array<String> fieldNames;
  19257. HashSet<String> fieldNameSet;
  19258. for (auto typedVal : typedValues)
  19259. {
  19260. auto type = typedVal.mType;
  19261. if (type != NULL)
  19262. fieldTypes.push_back(type);
  19263. else
  19264. fieldTypes.push_back(mModule->mContext->mBfObjectType);
  19265. }
  19266. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  19267. {
  19268. if (requestedName == NULL)
  19269. fieldNames.push_back("");
  19270. else
  19271. {
  19272. auto fieldName = requestedName->mNameNode->ToString();
  19273. if (!fieldNameSet.TryAdd(fieldName, NULL))
  19274. {
  19275. mModule->Fail(StrFormat("A field named '%s' has already been declared", fieldName.c_str()), requestedName->mNameNode);
  19276. }
  19277. fieldNames.push_back(fieldName);
  19278. }
  19279. }
  19280. tupleType = mModule->CreateTupleType(fieldTypes, fieldNames);
  19281. }
  19282. mModule->mBfIRBuilder->PopulateType(tupleType);
  19283. BfIRValue curTupleValue;
  19284. if ((mReceivingValue != NULL) && (mReceivingValue->mType == tupleType) && (mReceivingValue->IsAddr()))
  19285. {
  19286. mResult = *mReceivingValue;
  19287. mReceivingValue = NULL;
  19288. curTupleValue = mResult.mValue;
  19289. }
  19290. else
  19291. {
  19292. int valueIdx = -1;
  19293. bool isExactConst = true;
  19294. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  19295. {
  19296. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  19297. if (fieldInstance->mDataIdx < 0)
  19298. continue;
  19299. ++valueIdx;
  19300. auto typedValue = typedValues[valueIdx];
  19301. if (typedValue.mType != fieldInstance->mResolvedType)
  19302. {
  19303. isExactConst = false;
  19304. break;
  19305. }
  19306. if (!typedValue.mValue.IsConst())
  19307. {
  19308. isExactConst = false;
  19309. break;
  19310. }
  19311. }
  19312. if (isExactConst)
  19313. {
  19314. mModule->PopulateType(tupleType);
  19315. if (tupleType->IsDataIncomplete())
  19316. return;
  19317. Array<BfIRValue> irValues;
  19318. irValues.Resize(typedValues.mSize + 1);
  19319. irValues[0] = mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(tupleType->mBaseType));
  19320. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  19321. {
  19322. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  19323. if (fieldInstance->mDataIdx < 0)
  19324. continue;
  19325. while (fieldInstance->mDataIdx >= irValues.size())
  19326. irValues.Add(BfIRValue());
  19327. irValues[fieldInstance->mDataIdx] = typedValues[fieldIdx].mValue;
  19328. }
  19329. for (auto& val : irValues)
  19330. {
  19331. if (!val)
  19332. val = mModule->mBfIRBuilder->CreateConstArrayZero(0);
  19333. }
  19334. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(tupleType), irValues), tupleType);
  19335. return;
  19336. }
  19337. curTupleValue = mModule->CreateAlloca(tupleType);
  19338. mResultIsTempComposite = true;
  19339. mResult = BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  19340. }
  19341. int valueIdx = -1;
  19342. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  19343. {
  19344. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  19345. ++valueIdx;
  19346. if (fieldInstance->mResolvedType->IsValuelessType())
  19347. continue;
  19348. auto typedVal = typedValues[valueIdx];
  19349. if (!typedVal)
  19350. {
  19351. mModule->AssertErrorState();
  19352. continue;
  19353. }
  19354. if (fieldInstance->mDataIdx >= 0)
  19355. {
  19356. auto memberVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curTupleValue, 0, fieldInstance->mDataIdx);
  19357. if ((!mModule->mBfIRBuilder->mIgnoreWrites) && (typedVal.mValue.IsFake()))
  19358. {
  19359. // Value was deferred. Allow us to try to init in place
  19360. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  19361. BfTypedValue memberPtrTypedVal = BfTypedValue(memberVal, fieldInstance->mResolvedType, BfTypedValueKind_Addr);
  19362. BfExprEvaluator exprEvaluator(mModule);
  19363. exprEvaluator.mExpectingType = fieldInstance->mResolvedType;
  19364. exprEvaluator.mReceivingValue = &memberPtrTypedVal;
  19365. exprEvaluator.Evaluate(valueExpr);
  19366. exprEvaluator.GetResult();
  19367. if (exprEvaluator.mReceivingValue == NULL)
  19368. {
  19369. // We wrote directly to the array in-place, we're done with this element
  19370. continue;
  19371. }
  19372. typedVal = exprEvaluator.mResult;
  19373. typedVal = mModule->Cast(valueExpr, typedVal, fieldInstance->mResolvedType);
  19374. if (!typedVal)
  19375. {
  19376. mModule->AssertErrorState();
  19377. continue;
  19378. }
  19379. typedVal = mModule->LoadValue(typedVal);
  19380. }
  19381. if (typedVal.mType->IsVar())
  19382. {
  19383. // Do nothing
  19384. }
  19385. else if (typedVal.IsSplat())
  19386. mModule->AggregateSplatIntoAddr(typedVal, memberVal);
  19387. else
  19388. mModule->mBfIRBuilder->CreateAlignedStore(typedVal.mValue, memberVal, typedVal.mType->mAlign);
  19389. }
  19390. }
  19391. }
  19392. BfTypedValue BfExprEvaluator::SetupNullConditional(BfTypedValue thisValue, BfTokenNode* dotToken)
  19393. {
  19394. bool isStaticLookup = (!thisValue) ||
  19395. ((!thisValue.mType->IsValuelessType()) && (!thisValue.mValue));
  19396. if (isStaticLookup)
  19397. {
  19398. mModule->Fail("Null conditional reference not valid for static field references", dotToken);
  19399. return thisValue;
  19400. }
  19401. auto opResult = PerformUnaryOperation_TryOperator(thisValue, NULL, BfUnaryOp_NullConditional, dotToken, BfUnaryOpFlag_None);
  19402. if (opResult)
  19403. thisValue = opResult;
  19404. if (thisValue.mType->IsGenericParam())
  19405. {
  19406. bool isValid = false;
  19407. auto genericParams = mModule->GetGenericParamInstance((BfGenericParamType*)thisValue.mType);
  19408. if (genericParams->mTypeConstraint != NULL)
  19409. {
  19410. if ((genericParams->mTypeConstraint->IsNullable()) ||
  19411. (genericParams->mTypeConstraint->IsPointer()) ||
  19412. (genericParams->mTypeConstraint->IsObjectOrInterface()))
  19413. isValid = true;
  19414. }
  19415. if ((genericParams->mGenericParamFlags & (BfGenericParamFlag_Var | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class)) != 0)
  19416. isValid = true;
  19417. if (isValid)
  19418. return thisValue;
  19419. }
  19420. if ((thisValue.mType->IsNullable()) || (thisValue.mType->IsVar()))
  19421. {
  19422. // Success
  19423. }
  19424. else if ((thisValue.mType->IsPointer()) || (thisValue.mType->IsObjectOrInterface()) || (thisValue.mType->IsFunction()))
  19425. {
  19426. // Also good
  19427. }
  19428. else
  19429. {
  19430. bool canBeNull = false;
  19431. if (thisValue.mType->IsGenericParam())
  19432. canBeNull = true;
  19433. if (!canBeNull)
  19434. mModule->Warn(0, StrFormat("Null conditional reference is unnecessary since value type '%s' can never be null", mModule->TypeToString(thisValue.mType).c_str()), dotToken);
  19435. return thisValue;
  19436. }
  19437. thisValue = mModule->LoadValue(thisValue);
  19438. if (thisValue.mType->IsVar())
  19439. return thisValue;
  19440. BfPendingNullConditional* pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  19441. if (pendingNullCond == NULL)
  19442. {
  19443. pendingNullCond = new BfPendingNullConditional();
  19444. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  19445. }
  19446. if (!pendingNullCond->mPrevBB)
  19447. pendingNullCond->mPrevBB = mModule->mBfIRBuilder->GetInsertBlock();
  19448. if (!pendingNullCond->mDoneBB)
  19449. pendingNullCond->mDoneBB = mModule->mBfIRBuilder->CreateBlock("nullCond.done");
  19450. // We will in the br to checkBB later
  19451. if (!pendingNullCond->mCheckBB)
  19452. {
  19453. pendingNullCond->mCheckBB = mModule->mBfIRBuilder->CreateBlock("nullCond.check");
  19454. mModule->AddBasicBlock(pendingNullCond->mCheckBB);
  19455. }
  19456. BfIRValue isNotNull;
  19457. if (thisValue.mType->IsNullable())
  19458. {
  19459. BfTypeInstance* nullableType = (BfTypeInstance*)thisValue.mType->ToTypeInstance();
  19460. auto elementType = nullableType->GetUnderlyingType();
  19461. if (elementType->IsValuelessType())
  19462. {
  19463. thisValue = mModule->MakeAddressable(thisValue);
  19464. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mHasValue
  19465. isNotNull = mModule->mBfIRBuilder->CreateAlignedLoad(hasValuePtr, 1);
  19466. thisValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), elementType, true);
  19467. }
  19468. else
  19469. {
  19470. thisValue = mModule->MakeAddressable(thisValue);
  19471. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 2); // mHasValue
  19472. isNotNull = mModule->mBfIRBuilder->CreateAlignedLoad(hasValuePtr, 1);
  19473. BfIRValue valuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mValue
  19474. thisValue = BfTypedValue(valuePtr, elementType, true);
  19475. }
  19476. }
  19477. else if (thisValue.mType->IsFunction())
  19478. {
  19479. isNotNull = mModule->mBfIRBuilder->CreateCmpNE(thisValue.mValue, mModule->GetDefaultValue(thisValue.mType));
  19480. }
  19481. else
  19482. isNotNull = mModule->mBfIRBuilder->CreateIsNotNull(thisValue.mValue);
  19483. BfIRBlock notNullBB = mModule->mBfIRBuilder->CreateBlock("nullCond.notNull");
  19484. pendingNullCond->mNotNullBBs.Add(notNullBB);
  19485. mModule->mBfIRBuilder->CreateCondBr(isNotNull, notNullBB, pendingNullCond->mDoneBB);
  19486. mModule->AddBasicBlock(notNullBB);
  19487. return thisValue;
  19488. }
  19489. void BfExprEvaluator::CheckDotToken(BfTokenNode* tokenNode)
  19490. {
  19491. if ((tokenNode != NULL) && (tokenNode->mToken == BfToken_DotDot))
  19492. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", tokenNode);
  19493. }
  19494. void BfExprEvaluator::DoMemberReference(BfMemberReferenceExpression* memberRefExpr, BfTypedValue* outCascadeValue)
  19495. {
  19496. CheckDotToken(memberRefExpr->mDotToken);
  19497. BfAttributeState attributeState;
  19498. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  19499. String findName;
  19500. BfAstNode* nameRefNode = memberRefExpr->mMemberName;
  19501. if (auto attrIdentifierExpr = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpr->mMemberName))
  19502. {
  19503. nameRefNode = attrIdentifierExpr->mIdentifier;
  19504. // Don't validate
  19505. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierExpr->mAttributes, BfAttributeTargets_SkipValidate);
  19506. if (nameRefNode != NULL)
  19507. findName = attrIdentifierExpr->mIdentifier->ToString();
  19508. }
  19509. else if (memberRefExpr->mMemberName != NULL)
  19510. findName = memberRefExpr->mMemberName->ToString();
  19511. else if (memberRefExpr->mDotToken != NULL)
  19512. mModule->FailAfter("Member name expected", memberRefExpr->mDotToken);
  19513. defer
  19514. (
  19515. if (attributeState.mCustomAttributes != NULL)
  19516. {
  19517. if (mPropDef != NULL)
  19518. attributeState.mTarget = (BfAttributeTargets)(attributeState.mTarget | BfAttributeTargets_Invocation);
  19519. mModule->ValidateCustomAttributes(attributeState.mCustomAttributes, attributeState.mTarget);
  19520. }
  19521. );
  19522. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  19523. BfTypeInstance* expectingTypeInst = NULL;
  19524. if (mExpectingType != NULL)
  19525. {
  19526. expectingTypeInst = mExpectingType->ToTypeInstance();
  19527. if (mExpectingType->IsPointer())
  19528. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  19529. else if (mExpectingType->IsNullable())
  19530. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  19531. else if (mExpectingType->IsConstExprValue())
  19532. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  19533. else if (mExpectingType->IsGenericParam())
  19534. {
  19535. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  19536. if (genericParam->mTypeConstraint != NULL)
  19537. expectingTypeInst = genericParam->mTypeConstraint->ToTypeInstance();
  19538. }
  19539. }
  19540. BfAutoComplete* autoComplete = GetAutoComplete();
  19541. if (autoComplete != NULL)
  19542. {
  19543. SetAndRestoreValue<bool> prevFriendSet(autoComplete->mHasFriendSet, (attributeState.mCustomAttributes != NULL) && (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef)));
  19544. if (memberRefExpr->mTarget == NULL)
  19545. {
  19546. String filter;
  19547. if ((mExpectingType != NULL) &&
  19548. (autoComplete->InitAutocomplete(memberRefExpr->mDotToken, memberRefExpr->mMemberName, filter)))
  19549. {
  19550. if (expectingTypeInst != NULL)
  19551. {
  19552. bool allowPrivate = expectingTypeInst == mModule->mCurTypeInstance;
  19553. if (expectingTypeInst->IsEnum())
  19554. autoComplete->AddEnumTypeMembers(expectingTypeInst, filter, false, allowPrivate);
  19555. autoComplete->AddSelfResultTypeMembers(expectingTypeInst, expectingTypeInst, filter, allowPrivate);
  19556. }
  19557. }
  19558. else if ((expectingTypeInst != NULL) && (autoComplete->IsAutocompleteNode(memberRefExpr->mDotToken)) && (autoComplete->mIsGetDefinition))
  19559. {
  19560. if ((autoComplete->mDefType == NULL) &&
  19561. (autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  19562. (autoComplete->mDefProp == NULL) && (expectingTypeInst->mTypeDef->mTypeDeclaration != NULL))
  19563. {
  19564. autoComplete->mDefType = expectingTypeInst->mTypeDef;
  19565. autoComplete->SetDefinitionLocation(expectingTypeInst->mTypeDef->mTypeDeclaration->mNameNode);
  19566. }
  19567. }
  19568. }
  19569. else
  19570. {
  19571. autoComplete->CheckMemberReference(memberRefExpr->mTarget, memberRefExpr->mDotToken, memberRefExpr->mMemberName, false, mExpectingType);
  19572. if (auto objCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(memberRefExpr->mTarget))
  19573. {
  19574. // This handles a weird case where we have "obj a = new\nWhatever().Thing = 123;".
  19575. // That gets parsed as "Whatever()" being the type we want to create, and then referencing
  19576. // the "Thing" member of that new object.
  19577. //if (objCreateExpr->mArraySizeSpecifier == NULL)
  19578. CheckObjectCreateTypeRef(mExpectingType, objCreateExpr->mNewNode);
  19579. }
  19580. }
  19581. }
  19582. if (memberRefExpr->mTarget == NULL)
  19583. {
  19584. if (mExpectingType == NULL)
  19585. {
  19586. if (mModule->PreFail())
  19587. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", nameRefNode);
  19588. return;
  19589. }
  19590. if (mExpectingType->IsVar())
  19591. {
  19592. mResult = mModule->GetDefaultTypedValue(mExpectingType);
  19593. return;
  19594. }
  19595. if (mExpectingType->IsSizedArray())
  19596. {
  19597. expectingTypeInst = mModule->GetWrappedStructType(mExpectingType);
  19598. }
  19599. if (expectingTypeInst == NULL)
  19600. {
  19601. if (mModule->PreFail())
  19602. mModule->Fail(StrFormat("Unqualified dot syntax cannot be used with type '%s'", mModule->TypeToString(mExpectingType).c_str()), nameRefNode);
  19603. return;
  19604. }
  19605. BfTypedValue expectingVal(expectingTypeInst);
  19606. mResult = LookupField(memberRefExpr->mMemberName, expectingVal, findName);
  19607. if ((mResult) || (mPropDef != NULL))
  19608. return;
  19609. }
  19610. bool isNullCondLookup = (memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_QuestionDot);
  19611. bool isCascade = ((memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_DotDot));
  19612. bool isArrowLookup = ((memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_Arrow));
  19613. BfIdentifierNode* nameLeft = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mTarget);
  19614. BfIdentifierNode* nameRight = BfIdentifierCast(memberRefExpr->mMemberName);
  19615. if ((nameLeft != NULL) && (nameRight != NULL) && (!isNullCondLookup) && (!isCascade) && (!isArrowLookup))
  19616. {
  19617. bool hadError = false;
  19618. LookupQualifiedName(memberRefExpr, nameLeft, nameRight, true, &hadError);
  19619. if ((mResult) || (mPropDef != NULL))
  19620. return;
  19621. if (hadError)
  19622. return;
  19623. LookupQualifiedStaticField(memberRefExpr, nameLeft, nameRight, false);
  19624. return;
  19625. }
  19626. BfTypedValue thisValue;
  19627. if (auto exprTarget = BfNodeDynCast<BfExpression>(memberRefExpr->mTarget))
  19628. {
  19629. if (auto typeOfExpr = BfNodeDynCast<BfTypeOfExpression>(memberRefExpr->mTarget))
  19630. {
  19631. if (auto nameIdentifer = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  19632. {
  19633. if (LookupTypeProp(typeOfExpr, nameIdentifer))
  19634. return;
  19635. }
  19636. }
  19637. //Hm, not using VisitChild broke our ability to write to a field for a not-initialized local struct
  19638. VisitChild(memberRefExpr->mTarget);
  19639. GetResult();
  19640. thisValue = mResult;
  19641. if (!thisValue)
  19642. {
  19643. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(exprTarget))
  19644. {
  19645. thisValue = BfTypedValue(mModule->ResolveTypeRef(targetIdentifier, NULL, BfPopulateType_Declaration));
  19646. }
  19647. }
  19648. if (!thisValue.HasType())
  19649. return;
  19650. //thisValue = mResult;
  19651. }
  19652. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpr->mTarget))
  19653. {
  19654. // Look up static field
  19655. thisValue = BfTypedValue(ResolveTypeRef(typeRef));
  19656. }
  19657. if (nameRefNode == NULL)
  19658. {
  19659. mModule->AssertErrorState();
  19660. return;
  19661. }
  19662. if (isNullCondLookup)
  19663. thisValue = SetupNullConditional(thisValue, memberRefExpr->mDotToken);
  19664. if ((isArrowLookup) && (thisValue))
  19665. thisValue = TryArrowLookup(thisValue, memberRefExpr->mDotToken);
  19666. auto nameNode = memberRefExpr->mMemberName;
  19667. if ((thisValue.mType != NULL) && (!thisValue.mType->IsTypeInstance()) && (!thisValue.mType->IsGenericParam()))
  19668. {
  19669. if (thisValue.mType->IsSizedArray())
  19670. {
  19671. if (thisValue.mType->IsValuelessType())
  19672. {
  19673. thisValue.mType = mModule->GetWrappedStructType(thisValue.mType);
  19674. thisValue.mValue = mModule->mBfIRBuilder->GetFakeVal();
  19675. }
  19676. else
  19677. {
  19678. thisValue = mModule->MakeAddressable(thisValue);
  19679. thisValue.mType = mModule->GetWrappedStructType(thisValue.mType);
  19680. thisValue.mValue = mModule->mBfIRBuilder->CreateBitCast(thisValue.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(thisValue.mType->ToTypeInstance()));
  19681. }
  19682. }
  19683. else if (thisValue.mType->IsPointer())
  19684. {
  19685. // Leave alone
  19686. }
  19687. else if (thisValue.mType->IsWrappableType())
  19688. {
  19689. thisValue.mType = mModule->GetWrappedStructType(thisValue.mType);
  19690. }
  19691. }
  19692. BfTypedValue lookupVal = thisValue;
  19693. if (thisValue.mType != NULL)
  19694. {
  19695. auto lookupType = BindGenericType(nameNode, thisValue.mType);
  19696. if ((lookupType->IsGenericParam()) && (!thisValue.mType->IsGenericParam()))
  19697. {
  19698. bool prevUseMixinGenerics = false;
  19699. if (mModule->mCurMethodState->mMixinState != NULL)
  19700. {
  19701. prevUseMixinGenerics = mModule->mCurMethodState->mMixinState->mUseMixinGenerics;
  19702. mModule->mCurMethodState->mMixinState->mUseMixinGenerics = true;
  19703. }
  19704. // Try to lookup from generic binding
  19705. mResult = LookupField(nameRight, BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), lookupType), findName, BfLookupFieldFlag_BindOnly);
  19706. if (mModule->mCurMethodState->mMixinState != NULL)
  19707. mModule->mCurMethodState->mMixinState->mUseMixinGenerics = prevUseMixinGenerics;
  19708. if (mPropDef != NULL)
  19709. {
  19710. mOrigPropTarget = lookupVal;
  19711. return;
  19712. }
  19713. }
  19714. }
  19715. mResult = LookupField(nameRefNode, lookupVal, findName);
  19716. if ((!mResult) && (mPropDef == NULL))
  19717. {
  19718. if (thisValue.mType != NULL)
  19719. {
  19720. BfTypeInstance* typeInst = thisValue.mType->ToTypeInstance();
  19721. auto compiler = mModule->mCompiler;
  19722. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(memberRefExpr->mMemberName)))
  19723. {
  19724. FixitAddMember(typeInst, mExpectingType, findName, !thisValue.mValue);
  19725. }
  19726. }
  19727. if ((!thisValue.mValue) && (thisValue.mType != NULL))
  19728. {
  19729. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  19730. {
  19731. if ((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0)
  19732. {
  19733. auto typeInst = thisValue.mType->ToTypeInstance();
  19734. if ((typeInst != NULL) && (CheckForMethodName(nameRight, typeInst, findName)))
  19735. return;
  19736. }
  19737. mResult.mType = mModule->ResolveInnerType(thisValue.mType, targetIdentifier, BfPopulateType_Declaration);
  19738. }
  19739. }
  19740. if ((memberRefExpr->mTarget == NULL) && (expectingTypeInst != NULL) && (autoComplete != NULL))
  19741. {
  19742. if (autoComplete->CheckFixit(memberRefExpr->mMemberName))
  19743. {
  19744. autoComplete->FixitAddCase(expectingTypeInst, memberRefExpr->mMemberName->ToString(), BfTypeVector());
  19745. }
  19746. }
  19747. if (mResult.mType == NULL)
  19748. {
  19749. if (mModule->PreFail())
  19750. {
  19751. if ((thisValue) && (thisValue.mType->IsPointer()) && (thisValue.mType->GetUnderlyingType()->IsObjectOrInterface()))
  19752. mModule->Fail(StrFormat("Members cannot be referenced on type '%s' because the type is a pointer to a reference type (ie: a double-reference).",
  19753. mModule->TypeToString(thisValue.mType).c_str()), nameRefNode);
  19754. else if (thisValue)
  19755. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", findName.c_str(), mModule->TypeToString(thisValue.mType).c_str()), nameRefNode);
  19756. else
  19757. mModule->Fail("Unable to find member", nameRefNode);
  19758. }
  19759. }
  19760. }
  19761. if ((isNullCondLookup) && (mPropDef == NULL))
  19762. mResult = GetResult();
  19763. if (isCascade)
  19764. {
  19765. if (outCascadeValue != NULL)
  19766. *outCascadeValue = thisValue;
  19767. else if (mModule->PreFail())
  19768. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", memberRefExpr->mDotToken);
  19769. }
  19770. }
  19771. void BfExprEvaluator::Visit(BfMemberReferenceExpression* memberRefExpr)
  19772. {
  19773. DoMemberReference(memberRefExpr, NULL);
  19774. }
  19775. void BfExprEvaluator::Visit(BfIndexerExpression* indexerExpr)
  19776. {
  19777. HandleIndexerExpression(indexerExpr, BfTypedValue());
  19778. }
  19779. void BfExprEvaluator::HandleIndexerExpression(BfIndexerExpression* indexerExpr, BfTypedValue target)
  19780. {
  19781. BfAstNode* refNode = indexerExpr->mOpenBracket;
  19782. if (refNode == NULL)
  19783. refNode = indexerExpr->mTarget;
  19784. bool wantStatic = false;
  19785. // Try first as a non-static indexer, then as a static indexer
  19786. if (!target)
  19787. {
  19788. for (int pass = 0; pass < 2; pass++)
  19789. {
  19790. ///
  19791. {
  19792. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoLookupError | BfEvalExprFlags_AllowBase), pass == 0);
  19793. VisitChild(indexerExpr->mTarget);
  19794. }
  19795. ResolveGenericType();
  19796. target = GetResult(true);
  19797. if (target)
  19798. break;
  19799. if (pass == 0)
  19800. {
  19801. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, (mModule->mIgnoreErrors) || (pass == 0));
  19802. auto staticType = mModule->ResolveTypeRef(indexerExpr->mTarget, {});
  19803. if (staticType != NULL)
  19804. {
  19805. wantStatic = true;
  19806. target.mType = staticType;
  19807. break;
  19808. }
  19809. }
  19810. }
  19811. }
  19812. if (!target.HasType())
  19813. return;
  19814. if (target.mType->IsGenericParam())
  19815. {
  19816. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)target.mType);
  19817. if (genericParamInstance->mTypeConstraint != NULL)
  19818. target.mType = genericParamInstance->mTypeConstraint;
  19819. }
  19820. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  19821. bool isInlined = false;
  19822. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  19823. {
  19824. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  19825. {
  19826. isInlined = true;
  19827. mModule->mAttributeState->mUsed = true;
  19828. }
  19829. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  19830. {
  19831. checkedKind = BfCheckedKind_Checked;
  19832. mModule->mAttributeState->mUsed = true;
  19833. }
  19834. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  19835. {
  19836. checkedKind = BfCheckedKind_Unchecked;
  19837. mModule->mAttributeState->mUsed = true;
  19838. }
  19839. }
  19840. // Avoid attempting to apply the current attributes to the indexer arguments
  19841. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, NULL);
  19842. bool isNullCondLookup = (indexerExpr->mOpenBracket != NULL) && (indexerExpr->mOpenBracket->GetToken() == BfToken_QuestionLBracket);
  19843. if (isNullCondLookup)
  19844. target = SetupNullConditional(target, indexerExpr->mOpenBracket);
  19845. if (target.mType->IsVar())
  19846. {
  19847. mResult = BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  19848. return;
  19849. }
  19850. if ((target.mType->IsTypeInstance()) || (target.mType->IsGenericParam()))
  19851. {
  19852. BfGenericParamInstance* genericParamInstance = NULL;
  19853. if (target.mType->IsGenericParam())
  19854. genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)target.mType);
  19855. mIndexerValues.clear();
  19856. SizedArray<BfExpression*, 2> argExprs;
  19857. BfSizedArray<BfExpression*> sizedArgExprs(indexerExpr->mArguments);
  19858. BfResolvedArgs argValues(&sizedArgExprs);
  19859. ResolveArgValues(argValues, (BfResolveArgsFlags)(BfResolveArgsFlag_DeferParamEval | BfResolveArgsFlag_FromIndexer));
  19860. mIndexerValues = argValues.mResolvedArgs;
  19861. BfMethodMatcher methodMatcher(indexerExpr->mTarget, mModule, "[]", mIndexerValues, BfMethodGenericArguments());
  19862. methodMatcher.mCheckedKind = checkedKind;
  19863. BfMethodDef* methodDef = NULL;
  19864. auto startCheckTypeInst = target.mType->ToTypeInstance();
  19865. auto lookupType = target.mType;
  19866. if (lookupType != NULL)
  19867. {
  19868. lookupType = BindGenericType(refNode, lookupType);
  19869. if (lookupType->IsGenericParam())
  19870. startCheckTypeInst = NULL;
  19871. }
  19872. for (int pass = 0; pass < 2; pass++)
  19873. {
  19874. bool isFailurePass = pass == 1;
  19875. BfPropertyDef* foundProp = NULL;
  19876. BfTypeInstance* foundPropTypeInst = NULL;
  19877. BfBaseClassWalker baseClassWalker(lookupType, NULL, mModule, true);
  19878. while (true)
  19879. {
  19880. auto checkEntry = baseClassWalker.Next();
  19881. auto curCheckType = checkEntry.mTypeInstance;
  19882. if (curCheckType == NULL)
  19883. break;
  19884. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  19885. curCheckType->mTypeDef->PopulateMemberSets();
  19886. BfMemberSetEntry* entry;
  19887. BfPropertyDef* matchedProp = NULL;
  19888. BfPropertyDef* nextProp = NULL;
  19889. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(String("[]"), &entry))
  19890. nextProp = (BfPropertyDef*)entry->mMemberDef;
  19891. while (nextProp != NULL)
  19892. {
  19893. auto prop = nextProp;
  19894. nextProp = nextProp->mNextWithSameName;
  19895. //TODO: Match against setMethod (minus last param) if we have no 'get' method
  19896. for (auto checkMethod : prop->mMethods)
  19897. {
  19898. if (checkMethod->mMethodType != BfMethodType_PropertyGetter)
  19899. continue;
  19900. if (checkMethod->mIsStatic != wantStatic)
  19901. continue;
  19902. if (checkMethod->mExplicitInterface != NULL)
  19903. continue;
  19904. auto autoComplete = GetAutoComplete();
  19905. bool wasCapturingMethodMatchInfo = false;
  19906. if (autoComplete != NULL)
  19907. {
  19908. // Set to false to make sure we don't capture method match info from 'params' array creation
  19909. wasCapturingMethodMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  19910. autoComplete->mIsCapturingMethodMatchInfo = false;
  19911. }
  19912. defer
  19913. (
  19914. if (autoComplete != NULL)
  19915. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMethodMatchInfo;
  19916. );
  19917. if ((!isFailurePass) && (!methodMatcher.WantsCheckMethod(protectionCheckFlags, startCheckTypeInst, curCheckType, checkMethod)))
  19918. continue;
  19919. if (!methodMatcher.IsMemberAccessible(curCheckType, checkMethod->mDeclaringType))
  19920. continue;
  19921. methodMatcher.mCheckedKind = checkedKind;
  19922. methodMatcher.mTarget = target;
  19923. bool hadMatch = methodMatcher.CheckMethod(startCheckTypeInst, curCheckType, checkMethod, false);
  19924. if ((hadMatch) || (methodMatcher.mBackupMethodDef == checkMethod))
  19925. {
  19926. foundPropTypeInst = curCheckType;
  19927. foundProp = prop;
  19928. }
  19929. }
  19930. }
  19931. curCheckType = curCheckType->mBaseType;
  19932. }
  19933. if (foundProp != NULL)
  19934. {
  19935. mPropSrc = indexerExpr->mOpenBracket;
  19936. mPropDef = foundProp;
  19937. if (foundProp->mIsStatic)
  19938. {
  19939. mPropTarget = BfTypedValue(foundPropTypeInst);
  19940. }
  19941. else
  19942. {
  19943. if (target.mType != foundPropTypeInst)
  19944. mPropTarget = mModule->Cast(indexerExpr->mTarget, target, foundPropTypeInst);
  19945. else
  19946. mPropTarget = target;
  19947. }
  19948. mOrigPropTarget = mPropTarget;
  19949. if (isInlined)
  19950. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  19951. mPropCheckedKind = checkedKind;
  19952. if ((target.IsBase()) && (mPropDef->IsVirtual()))
  19953. mPropDefBypassVirtual = true;
  19954. return;
  19955. }
  19956. }
  19957. mModule->Fail("Unable to find indexer property", indexerExpr->mTarget);
  19958. return;
  19959. }
  19960. bool wantsChecks = checkedKind == BfCheckedKind_Checked;
  19961. if (checkedKind == BfCheckedKind_NotSet)
  19962. wantsChecks = mModule->GetDefaultCheckedKind() == BfCheckedKind_Checked;
  19963. if (target.mType->IsVar())
  19964. {
  19965. mResult = target;
  19966. return;
  19967. }
  19968. if ((!target.mType->IsPointer()) && (!target.mType->IsSizedArray()))
  19969. {
  19970. mModule->Fail("Expected pointer or array type", indexerExpr->mTarget);
  19971. return;
  19972. }
  19973. auto _GetDefaultResult = [&]()
  19974. {
  19975. return mModule->GetDefaultTypedValue(target.mType->GetUnderlyingType(), false, BfDefaultValueKind_Addr);
  19976. };
  19977. if (indexerExpr->mArguments.size() != 1)
  19978. {
  19979. mModule->Fail("Expected single index", indexerExpr->mOpenBracket);
  19980. mResult = _GetDefaultResult();
  19981. return;
  19982. }
  19983. if (indexerExpr->mArguments[0] == NULL)
  19984. {
  19985. mModule->AssertErrorState();
  19986. mResult = _GetDefaultResult();
  19987. return;
  19988. }
  19989. bool isUndefIndex = false;
  19990. auto indexArgument = mModule->CreateValueFromExpression(indexerExpr->mArguments[0], mModule->GetPrimitiveType(BfTypeCode_IntPtr), BfEvalExprFlags_NoCast);
  19991. if (!indexArgument)
  19992. return;
  19993. if (!indexArgument.mType->IsIntegral())
  19994. {
  19995. if (indexArgument.mType->IsVar())
  19996. {
  19997. isUndefIndex = true;
  19998. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr), false, BfDefaultValueKind_Undef);
  19999. }
  20000. else
  20001. {
  20002. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  20003. if (!indexArgument)
  20004. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  20005. }
  20006. }
  20007. if (indexArgument.mType->IsPrimitiveType())
  20008. {
  20009. auto primType = (BfPrimitiveType*)indexArgument.mType;
  20010. if ((!primType->IsSigned()) && (primType->mSize < 8))
  20011. {
  20012. // GEP will always do a signed upcast so we need to cast manually if we are unsigned
  20013. indexArgument = BfTypedValue(mModule->mBfIRBuilder->CreateNumericCast(indexArgument.mValue, false, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  20014. }
  20015. }
  20016. mModule->PopulateType(target.mType);
  20017. if (target.mType->IsSizedArray())
  20018. {
  20019. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)target.mType;
  20020. auto underlyingType = sizedArrayType->mElementType;
  20021. if (indexArgument.mValue.IsConst())
  20022. {
  20023. auto indexConst = mModule->mBfIRBuilder->GetConstant(indexArgument.mValue);
  20024. if ((BfIRBuilder::IsIntable(indexConst->mTypeCode)) && (indexConst->mUInt64 >= (uint64)sizedArrayType->mElementCount))
  20025. {
  20026. if ((!mModule->IsInSpecializedSection()) && (checkedKind != BfCheckedKind_Unchecked))
  20027. {
  20028. mModule->Fail(StrFormat("Index '%d' is out of bounds for type '%s'", indexConst->mInt32, mModule->TypeToString(target.mType).c_str()), indexerExpr->mArguments[0]);
  20029. mResult = _GetDefaultResult();
  20030. return;
  20031. }
  20032. else
  20033. {
  20034. // Is this any good?
  20035. mModule->mBfIRBuilder->CreateUnreachable();
  20036. }
  20037. }
  20038. }
  20039. else if (((mModule->HasExecutedOutput()) || (mModule->mIsComptimeModule)) &&
  20040. (wantsChecks))
  20041. {
  20042. if (checkedKind == BfCheckedKind_NotSet)
  20043. checkedKind = mModule->GetDefaultCheckedKind();
  20044. if (checkedKind == BfCheckedKind_Checked)
  20045. {
  20046. auto oobBlock = mModule->mBfIRBuilder->CreateBlock("oob", true);
  20047. auto contBlock = mModule->mBfIRBuilder->CreateBlock("cont", true);
  20048. auto indexType = (BfPrimitiveType*)indexArgument.mType;
  20049. if (!mModule->mSystem->DoesLiteralFit(indexType->mTypeDef->mTypeCode, (int64)sizedArrayType->mElementCount))
  20050. {
  20051. // We need to upsize the index so we can compare it against the larger elementCount
  20052. indexType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  20053. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, indexType);
  20054. }
  20055. auto cmpRes = mModule->mBfIRBuilder->CreateCmpGTE(indexArgument.mValue, mModule->mBfIRBuilder->CreateConst(indexType->mTypeDef->mTypeCode, (uint64)sizedArrayType->mElementCount), false);
  20056. mModule->mBfIRBuilder->CreateCondBr(cmpRes, oobBlock, contBlock);
  20057. mModule->mBfIRBuilder->SetInsertPoint(oobBlock);
  20058. auto internalType = mModule->ResolveTypeDef(mModule->mCompiler->mInternalTypeDef);
  20059. auto oobFunc = mModule->GetMethodByName(internalType->ToTypeInstance(), "ThrowIndexOutOfRange");
  20060. if (oobFunc.mFunc)
  20061. {
  20062. if (mModule->mIsComptimeModule)
  20063. mModule->mCompiler->mCeMachine->QueueMethod(oobFunc.mMethodInstance, oobFunc.mFunc);
  20064. SizedArray<BfIRValue, 1> args;
  20065. args.push_back(mModule->GetConstValue(0));
  20066. mModule->mBfIRBuilder->CreateCall(oobFunc.mFunc, args);
  20067. mModule->mBfIRBuilder->CreateUnreachable();
  20068. }
  20069. else
  20070. {
  20071. mModule->Fail("System.Internal class must contain method 'ThrowIndexOutOfRange'");
  20072. }
  20073. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  20074. }
  20075. }
  20076. // If this is a 'bag of bytes', we should try hard not to have to make this addressable
  20077. if ((!target.IsAddr()) && (!target.mType->IsSizeAligned()))
  20078. mModule->MakeAddressable(target);
  20079. mResult = BfTypedValue();
  20080. mModule->PopulateType(underlyingType);
  20081. if ((sizedArrayType->IsUndefSizedArray()) || (isUndefIndex))
  20082. {
  20083. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  20084. }
  20085. else if (sizedArrayType->IsValuelessType())
  20086. {
  20087. if (underlyingType->IsValuelessType())
  20088. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), underlyingType, true);
  20089. else
  20090. {
  20091. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  20092. }
  20093. }
  20094. else if (target.IsAddr())
  20095. {
  20096. // Handle below
  20097. }
  20098. else
  20099. {
  20100. if ((!target.mValue.IsConst()) && (!indexArgument.mValue.IsConst()))
  20101. {
  20102. target = mModule->MakeAddressable(target);
  20103. }
  20104. else
  20105. {
  20106. mModule->mBfIRBuilder->PopulateType(target.mType);
  20107. auto gepResult = mModule->mBfIRBuilder->CreateExtractValue(target.mValue, indexArgument.mValue);
  20108. if ((underlyingType->IsString()) || (underlyingType->IsPointer()))
  20109. {
  20110. auto resultConst = mModule->mBfIRBuilder->GetConstant(gepResult);
  20111. if ((resultConst != NULL) && (resultConst->mTypeCode == BfTypeCode_Int32))
  20112. {
  20113. int strId = resultConst->mInt32;
  20114. const StringImpl& str = mModule->mContext->mStringObjectIdMap[strId].mString;
  20115. if (underlyingType->IsString())
  20116. gepResult = mModule->GetStringObjectValue(str, false);
  20117. else
  20118. gepResult = mModule->GetStringCharPtr(strId);
  20119. }
  20120. }
  20121. mResult = BfTypedValue(gepResult, underlyingType, BfTypedValueKind_Value);
  20122. }
  20123. }
  20124. if ((!mResult) && (target.IsAddr()))
  20125. {
  20126. if (target.mType->IsSizeAligned())
  20127. {
  20128. auto gepResult = mModule->mBfIRBuilder->CreateInBoundsGEP(target.mValue, mModule->GetConstValue(0), indexArgument.mValue);
  20129. mResult = BfTypedValue(gepResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  20130. }
  20131. else
  20132. {
  20133. auto indexResult = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  20134. mResult = BfTypedValue(indexResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  20135. }
  20136. }
  20137. if (!mResult)
  20138. {
  20139. mModule->Fail("Unable to index value", indexerExpr->mTarget);
  20140. return;
  20141. }
  20142. }
  20143. else
  20144. {
  20145. // We are no longer accessing data within this type
  20146. mResultLocalVar = NULL;
  20147. target = mModule->LoadValue(target);
  20148. BfPointerType* pointerType = (BfPointerType*)target.mType;
  20149. auto underlyingType = pointerType->mElementType;
  20150. mModule->mBfIRBuilder->PopulateType(underlyingType);
  20151. if (underlyingType->IsOpaque())
  20152. {
  20153. mModule->Fail(StrFormat("Unable to index opaque pointer type '%s'", mModule->TypeToString(pointerType).c_str()), indexerExpr);
  20154. }
  20155. else if (isUndefIndex)
  20156. {
  20157. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  20158. }
  20159. else
  20160. {
  20161. BfIRValue result = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  20162. mResult = BfTypedValue(result, underlyingType, true);
  20163. }
  20164. }
  20165. }
  20166. void BfExprEvaluator::Visit(BfUnaryOperatorExpression* unaryOpExpr)
  20167. {
  20168. BfAutoParentNodeEntry autoParentNodeEntry(mModule, unaryOpExpr);
  20169. PerformUnaryOperation(unaryOpExpr->mExpression, unaryOpExpr->mOp, unaryOpExpr->mOpToken, BfUnaryOpFlag_None);
  20170. }
  20171. void BfExprEvaluator::PerformUnaryOperation(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  20172. {
  20173. if ((unaryOpExpr == NULL) && (unaryOp == BfUnaryOp_PartialRangeThrough))
  20174. {
  20175. PerformBinaryOperation(NULL, NULL, BfBinaryOp_ClosedRange, opToken, BfBinOpFlag_None);
  20176. return;
  20177. }
  20178. ///
  20179. {
  20180. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags);
  20181. BfType* prevExpedcting = mExpectingType;
  20182. switch (unaryOp)
  20183. {
  20184. case BfUnaryOp_Ref:
  20185. // Allow
  20186. break;
  20187. case BfUnaryOp_Dereference:
  20188. if (mExpectingType != NULL)
  20189. {
  20190. if (mExpectingType->IsRef())
  20191. mExpectingType = mExpectingType->GetUnderlyingType();
  20192. if (!mExpectingType->IsVar())
  20193. mExpectingType = mModule->CreatePointerType(mExpectingType);
  20194. }
  20195. break;
  20196. case BfUnaryOp_Negate:
  20197. case BfUnaryOp_Positive:
  20198. case BfUnaryOp_InvertBits:
  20199. // If we're expecting an int64 or uint64 then just leave the type as unknown
  20200. if ((mExpectingType != NULL) && (mExpectingType->IsInteger()) && (mExpectingType->mSize == 8))
  20201. mExpectingType = NULL;
  20202. // Otherwise keep expecting type
  20203. break;
  20204. case BfUnaryOp_Params:
  20205. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_InParamsExpr);
  20206. break;
  20207. default:
  20208. mExpectingType = NULL;
  20209. }
  20210. VisitChild(unaryOpExpr);
  20211. mExpectingType = prevExpedcting;
  20212. }
  20213. BfExprEvaluator::PerformUnaryOperation_OnResult(unaryOpExpr, unaryOp, opToken, opFlags);
  20214. }
  20215. BfTypedValue BfExprEvaluator::PerformUnaryOperation_TryOperator(const BfTypedValue& inValue, BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  20216. {
  20217. if ((!inValue.mType->IsTypeInstance()) && (!inValue.mType->IsGenericParam()))
  20218. return BfTypedValue();
  20219. SizedArray<BfResolvedArg, 1> args;
  20220. BfResolvedArg resolvedArg;
  20221. resolvedArg.mTypedValue = inValue;
  20222. args.push_back(resolvedArg);
  20223. BfMethodMatcher methodMatcher(opToken, mModule, "", args, BfMethodGenericArguments());
  20224. methodMatcher.mBfEvalExprFlags = BfEvalExprFlags_NoAutoComplete;
  20225. methodMatcher.mAllowImplicitRef = true;
  20226. BfBaseClassWalker baseClassWalker(inValue.mType, NULL, mModule);
  20227. BfUnaryOp findOp = unaryOp;
  20228. bool isPostOp = false;
  20229. if (findOp == BfUnaryOp_PostIncrement)
  20230. {
  20231. findOp = BfUnaryOp_Increment;
  20232. isPostOp = true;
  20233. }
  20234. if (findOp == BfUnaryOp_PostDecrement)
  20235. {
  20236. findOp = BfUnaryOp_Decrement;
  20237. isPostOp = true;
  20238. }
  20239. bool isConstraintCheck = ((opFlags & BfUnaryOpFlag_IsConstraintCheck) != 0);
  20240. BfType* operatorConstraintReturnType = NULL;
  20241. BfType* bestSelfType = NULL;
  20242. while (true)
  20243. {
  20244. auto entry = baseClassWalker.Next();
  20245. auto checkType = entry.mTypeInstance;
  20246. if (checkType == NULL)
  20247. break;
  20248. for (auto operatorDef : checkType->mTypeDef->mOperators)
  20249. {
  20250. if (operatorDef->mOperatorDeclaration->mUnaryOp == findOp)
  20251. {
  20252. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  20253. continue;
  20254. int prevArgSize = (int)args.mSize;
  20255. if (!operatorDef->mIsStatic)
  20256. {
  20257. // Try without arg
  20258. args.mSize = 0;
  20259. }
  20260. if (isConstraintCheck)
  20261. {
  20262. auto returnType = mModule->CheckOperator(checkType, operatorDef, inValue, BfTypedValue());
  20263. if (returnType != NULL)
  20264. {
  20265. operatorConstraintReturnType = returnType;
  20266. methodMatcher.mBestMethodDef = operatorDef;
  20267. }
  20268. }
  20269. else
  20270. {
  20271. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  20272. methodMatcher.mSelfType = entry.mSrcType;
  20273. }
  20274. args.mSize = prevArgSize;
  20275. }
  20276. }
  20277. }
  20278. methodMatcher.FlushAmbiguityError();
  20279. if (methodMatcher.mBestMethodDef == NULL)
  20280. {
  20281. // Check method generic constraints
  20282. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  20283. {
  20284. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  20285. {
  20286. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  20287. for (auto& opConstraint : genericParam->mOperatorConstraints)
  20288. {
  20289. if (opConstraint.mUnaryOp == findOp)
  20290. {
  20291. if (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType, isConstraintCheck ? BfCastFlags_IsConstraintCheck : BfCastFlags_None))
  20292. {
  20293. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  20294. }
  20295. }
  20296. }
  20297. }
  20298. }
  20299. // Check type generic constraints
  20300. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  20301. {
  20302. auto genericTypeInst = (BfTypeInstance*)mModule->mCurTypeInstance;
  20303. for (int genericParamIdx = 0; genericParamIdx < genericTypeInst->mGenericTypeInfo->mGenericParams.size(); genericParamIdx++)
  20304. {
  20305. auto genericParam = mModule->GetGenericTypeParamInstance(genericParamIdx);
  20306. for (auto& opConstraint : genericParam->mOperatorConstraints)
  20307. {
  20308. if (opConstraint.mUnaryOp == findOp)
  20309. {
  20310. if (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType, isConstraintCheck ? BfCastFlags_IsConstraintCheck : BfCastFlags_None))
  20311. {
  20312. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  20313. }
  20314. }
  20315. }
  20316. }
  20317. }
  20318. return BfTypedValue();
  20319. }
  20320. if ((!baseClassWalker.mMayBeFromInterface) && (opToken != NULL))
  20321. mModule->SetElementType(opToken, BfSourceElementType_Method);
  20322. auto methodDef = methodMatcher.mBestMethodDef;
  20323. auto autoComplete = GetAutoComplete();
  20324. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  20325. {
  20326. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  20327. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  20328. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  20329. }
  20330. SizedArray<BfExpression*, 2> argSrcs;
  20331. argSrcs.push_back(unaryOpExpr);
  20332. BfTypedValue targetVal = args[0].mTypedValue;
  20333. BfTypedValue postOpVal;
  20334. if (isPostOp)
  20335. postOpVal = mModule->LoadValue(targetVal);
  20336. BfTypedValue callTarget;
  20337. if (!methodMatcher.mBestMethodDef->mIsStatic)
  20338. {
  20339. callTarget = targetVal;
  20340. args.Clear();
  20341. }
  20342. BfTypedValue result;
  20343. if (isConstraintCheck)
  20344. {
  20345. result = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), operatorConstraintReturnType);
  20346. }
  20347. else
  20348. {
  20349. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  20350. SetAndRestoreValue<BfDeferCallData*> prevDeferCallRef(mDeferCallData, NULL);
  20351. result = CreateCall(&methodMatcher, callTarget);
  20352. }
  20353. if (!methodMatcher.mBestMethodDef->mIsStatic)
  20354. {
  20355. if (!isPostOp)
  20356. result = mModule->LoadValue(targetVal);
  20357. }
  20358. else if ((result.mType != NULL) && (methodMatcher.mSelfType != NULL) && (result.mType->IsSelf()))
  20359. {
  20360. BF_ASSERT(mModule->IsInGeneric());
  20361. result = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  20362. }
  20363. if ((methodMatcher.mBestMethodInstance) &&
  20364. ((findOp == BfUnaryOp_Increment) || (findOp == BfUnaryOp_Decrement)))
  20365. {
  20366. if (methodMatcher.mBestMethodInstance.mMethodInstance->mIsIntrinsic)
  20367. {
  20368. if (args[0].mTypedValue.IsAddr())
  20369. mModule->mBfIRBuilder->CreateStore(result.mValue, args[0].mTypedValue.mValue);
  20370. else
  20371. {
  20372. mModule->AssertErrorState();
  20373. }
  20374. }
  20375. else
  20376. {
  20377. if (!result.mType->IsValuelessType())
  20378. {
  20379. if (targetVal.IsAddr())
  20380. {
  20381. result = mModule->LoadValue(result);
  20382. mModule->mBfIRBuilder->CreateStore(result.mValue, targetVal.mValue);
  20383. }
  20384. }
  20385. }
  20386. }
  20387. if (postOpVal)
  20388. result = postOpVal;
  20389. return result;
  20390. }
  20391. void BfExprEvaluator::PerformUnaryOperation_OnResult(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  20392. {
  20393. BfAstNode* propSrc = mPropSrc;
  20394. BfTypedValue origPropTarget = mOrigPropTarget;
  20395. BfTypedValue propTarget = mPropTarget;
  20396. BfPropertyDef* propDef = mPropDef;
  20397. SizedArray<BfResolvedArg, 2> indexerVals = mIndexerValues;
  20398. BfTypedValue writeToProp;
  20399. GetResult();
  20400. if (!mResult)
  20401. return;
  20402. mResult = mModule->RemoveRef(mResult);
  20403. if (mResult.mType->IsVar())
  20404. {
  20405. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType);
  20406. return;
  20407. }
  20408. if (BfCanOverloadOperator(unaryOp))
  20409. {
  20410. auto opResult = PerformUnaryOperation_TryOperator(mResult, unaryOpExpr, unaryOp, opToken, opFlags);
  20411. if (opResult)
  20412. {
  20413. mResult = opResult;
  20414. return;
  20415. }
  20416. }
  20417. switch (unaryOp)
  20418. {
  20419. case BfUnaryOp_PostIncrement:
  20420. case BfUnaryOp_Increment:
  20421. case BfUnaryOp_PostDecrement:
  20422. case BfUnaryOp_Decrement:
  20423. {
  20424. if (mResult.mKind == BfTypedValueKind_CopyOnMutateAddr)
  20425. {
  20426. // Support this ops on direct auto-property access without a copy
  20427. mResult.mKind = BfTypedValueKind_Addr;
  20428. }
  20429. }
  20430. break;
  20431. }
  20432. bool numericFail = false;
  20433. switch (unaryOp)
  20434. {
  20435. case BfUnaryOp_Not:
  20436. {
  20437. CheckResultForReading(mResult);
  20438. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  20439. auto value = mModule->LoadValue(mResult);
  20440. value = mModule->Cast(unaryOpExpr, value, boolType);
  20441. if (!value)
  20442. {
  20443. mResult = BfTypedValue();
  20444. return;
  20445. }
  20446. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), boolType);
  20447. }
  20448. break;
  20449. case BfUnaryOp_Positive:
  20450. return;
  20451. case BfUnaryOp_Negate:
  20452. {
  20453. CheckResultForReading(mResult);
  20454. auto value = mModule->LoadValue(mResult);
  20455. if (!value)
  20456. {
  20457. mResult = BfTypedValue();
  20458. return;
  20459. }
  20460. BfType* origType = value.mType;
  20461. if (value.mType->IsTypedPrimitive())
  20462. value.mType = value.mType->GetUnderlyingType();
  20463. if (value.mType->IsIntegral())
  20464. {
  20465. auto primType = (BfPrimitiveType*)value.mType;
  20466. auto wantType = primType;
  20467. auto constant = mModule->mBfIRBuilder->GetConstant(value.mValue);
  20468. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  20469. {
  20470. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (constant->mInt64 == 0x80000000LL))
  20471. {
  20472. mResult = BfTypedValue(mModule->GetConstValue32(-0x80000000LL), mModule->GetPrimitiveType(BfTypeCode_Int32));
  20473. return;
  20474. }
  20475. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt64) && (constant->mInt64 == 0x8000000000000000LL))
  20476. {
  20477. mResult = BfTypedValue(mModule->GetConstValue64(-0x8000000000000000LL), mModule->GetPrimitiveType(BfTypeCode_Int64));
  20478. return;
  20479. }
  20480. }
  20481. /*if (auto constantInt = dyn_cast<ConstantInt>((Value*)value.mValue))
  20482. {
  20483. int64 i64Val = constantInt->getSExtValue();
  20484. // This is a special case where the user entered -0x80000000 (maxint) but we thought "0x80000000" was a uint in the parser
  20485. // which would get upcasted to an int64 for this negate. Properly bring back down to an int32
  20486. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (i64Val == -0x80000000LL))
  20487. {
  20488. mResult = BfTypedValue(mModule->GetConstValue((int)i64Val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  20489. return;
  20490. }
  20491. }*/
  20492. if (!primType->IsSigned())
  20493. {
  20494. if (primType->mSize == 1)
  20495. wantType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  20496. else if (primType->mSize == 2)
  20497. wantType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  20498. else if (primType->mSize == 4)
  20499. wantType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  20500. else
  20501. mModule->Fail("Operator '-' cannot be applied to uint64", opToken);
  20502. }
  20503. if (primType != wantType)
  20504. {
  20505. value = mModule->Cast(unaryOpExpr, value, wantType, BfCastFlags_Explicit);
  20506. if (!value)
  20507. {
  20508. mResult = BfTypedValue();
  20509. return;
  20510. }
  20511. }
  20512. if (origType->mSize == wantType->mSize) // Allow negative of primitive typed but not if we had to upsize
  20513. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  20514. else
  20515. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), wantType);
  20516. }
  20517. else if (value.mType->IsFloat())
  20518. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  20519. else
  20520. {
  20521. ResolveGenericType();
  20522. if (mResult.mType->IsVar())
  20523. break;
  20524. numericFail = true;
  20525. }
  20526. }
  20527. break;
  20528. case BfUnaryOp_InvertBits:
  20529. {
  20530. CheckResultForReading(mResult);
  20531. auto value = mModule->LoadValue(mResult);
  20532. if (!value)
  20533. return;
  20534. bool isInteger = value.mType->IsIntegral();
  20535. if (value.mType->IsTypedPrimitive())
  20536. isInteger = value.mType->GetUnderlyingType()->IsIntegral();
  20537. if (!isInteger)
  20538. {
  20539. mResult = BfTypedValue();
  20540. mModule->Fail("Operator can only be used on integer types", opToken);
  20541. return;
  20542. }
  20543. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), value.mType);
  20544. }
  20545. break;
  20546. case BfUnaryOp_AddressOf:
  20547. {
  20548. MarkResultUsed();
  20549. mModule->FixIntUnknown(mResult);
  20550. mModule->PopulateType(mResult.mType);
  20551. auto ptrType = mModule->CreatePointerType(mResult.mType);
  20552. if ((mResult.mType->IsValuelessType()) && (!mResult.mType->IsOpaque()))
  20553. {
  20554. if (!mModule->IsInSpecializedSection())
  20555. {
  20556. mModule->Warn(0, StrFormat("Operator '&' results in a sentinel address for zero-sized type '%s'",
  20557. mModule->TypeToString(mResult.mType).c_str()), opToken);
  20558. }
  20559. // Sentinel value
  20560. auto val = mModule->mBfIRBuilder->CreateIntToPtr(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mModule->mBfIRBuilder->MapType(ptrType));
  20561. mResult = BfTypedValue(val, ptrType);
  20562. }
  20563. else if (!CheckModifyResult(mResult, unaryOpExpr, "take address of", false, true))
  20564. {
  20565. if (!mResult.IsAddr())
  20566. mResult = mModule->MakeAddressable(mResult, false, true);
  20567. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  20568. }
  20569. else
  20570. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  20571. }
  20572. break;
  20573. case BfUnaryOp_Dereference:
  20574. {
  20575. CheckResultForReading(mResult);
  20576. if (mResult.mType->IsGenericParam())
  20577. {
  20578. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)mResult.mType);
  20579. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsPointer()))
  20580. {
  20581. mResult = mModule->GetDefaultTypedValue(genericParamInstance->mTypeConstraint->GetUnderlyingType(), false, BfDefaultValueKind_Addr);
  20582. break;
  20583. }
  20584. }
  20585. if (!mResult.mType->IsPointer())
  20586. {
  20587. mResult = BfTypedValue();
  20588. mModule->Fail("Cannot dereference non-pointer type", unaryOpExpr);
  20589. return;
  20590. }
  20591. if (mResult.mValue.IsConst())
  20592. {
  20593. auto constant = mModule->mBfIRBuilder->GetConstant(mResult.mValue);
  20594. bool isNull = constant->mTypeCode == BfTypeCode_NullPtr;
  20595. if (constant->mConstType == BfConstType_ExtractValue)
  20596. {
  20597. auto constExtract = (BfConstantExtractValue*)constant;
  20598. auto targetConst = mModule->mBfIRBuilder->GetConstantById(constExtract->mTarget);
  20599. if (targetConst->mConstType == BfConstType_AggZero)
  20600. isNull = true;
  20601. }
  20602. if (isNull)
  20603. {
  20604. mModule->Warn(0, "Cannot dereference a null pointer", unaryOpExpr);
  20605. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Addr);
  20606. mResult = mModule->LoadValue(mResult);
  20607. }
  20608. }
  20609. auto derefTarget = mModule->LoadValue(mResult);
  20610. BfPointerType* pointerType = (BfPointerType*)derefTarget.mType;
  20611. auto resolvedType = pointerType->mElementType;
  20612. mModule->PopulateType(resolvedType);
  20613. if (resolvedType->IsValuelessNonOpaqueType())
  20614. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedType, true);
  20615. else
  20616. mResult = BfTypedValue(derefTarget.mValue, resolvedType, true);
  20617. }
  20618. break;
  20619. case BfUnaryOp_PostIncrement:
  20620. case BfUnaryOp_Increment:
  20621. {
  20622. CheckResultForReading(mResult);
  20623. auto ptr = mResult;
  20624. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  20625. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "increment")))
  20626. return;
  20627. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  20628. BfIRValue origVal = origTypedVal.mValue;
  20629. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  20630. BfIRValue resultValue;
  20631. if (ptr.mType->IsPointer())
  20632. {
  20633. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  20634. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  20635. constValue = mModule->GetConstValue(ptrType->mElementType->GetStride(), intPtrType);
  20636. auto i8PtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  20637. BfIRValue origPtrValue = mModule->mBfIRBuilder->CreateBitCast(origVal, i8PtrType);
  20638. BfIRValue newPtrValue = mModule->mBfIRBuilder->CreateInBoundsGEP(origPtrValue, constValue);
  20639. resultValue = mModule->mBfIRBuilder->CreateBitCast(newPtrValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  20640. }
  20641. else
  20642. {
  20643. constValue = mModule->GetConstValue(1, ptr.mType);
  20644. if (!constValue)
  20645. {
  20646. numericFail = true;
  20647. break;
  20648. }
  20649. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()) || (ptr.mType->IsFloat()))
  20650. {
  20651. resultValue = mModule->mBfIRBuilder->CreateAdd(origVal, constValue/*, "inc"*/);
  20652. }
  20653. else
  20654. {
  20655. numericFail = true;
  20656. break;
  20657. }
  20658. }
  20659. if ((propDef != NULL) && (!ptr.IsAddr()))
  20660. writeToProp = BfTypedValue(resultValue, ptr.mType);
  20661. else
  20662. mModule->mBfIRBuilder->CreateAlignedStore(resultValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  20663. if (unaryOp == BfUnaryOp_PostIncrement)
  20664. mResult = BfTypedValue(origVal, ptr.mType, false);
  20665. else
  20666. mResult = BfTypedValue(resultValue, ptr.mType, false);
  20667. }
  20668. break;
  20669. case BfUnaryOp_PostDecrement:
  20670. case BfUnaryOp_Decrement:
  20671. {
  20672. CheckResultForReading(mResult);
  20673. auto ptr = mResult;
  20674. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  20675. //return;
  20676. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "decrement")))
  20677. return;
  20678. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  20679. BfIRValue origVal = origTypedVal.mValue;
  20680. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  20681. BfIRValue resultValue;
  20682. if (ptr.mType->IsPointer())
  20683. {
  20684. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  20685. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  20686. constValue = mModule->GetConstValue(-ptrType->mElementType->GetStride(), intPtrType);
  20687. auto i8PtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  20688. BfIRValue origPtrValue = mModule->mBfIRBuilder->CreateBitCast(origVal, i8PtrType);
  20689. BfIRValue newPtrValue = mModule->mBfIRBuilder->CreateInBoundsGEP(origPtrValue, constValue);
  20690. resultValue = mModule->mBfIRBuilder->CreateBitCast(newPtrValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  20691. }
  20692. else
  20693. {
  20694. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  20695. if (!constValue)
  20696. {
  20697. numericFail = true;
  20698. break;
  20699. }
  20700. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()))
  20701. {
  20702. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  20703. }
  20704. else if (ptr.mType->IsFloat())
  20705. {
  20706. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  20707. }
  20708. else
  20709. {
  20710. numericFail = true;
  20711. break;
  20712. }
  20713. }
  20714. if ((propDef != NULL) && (!ptr.IsAddr()))
  20715. writeToProp = BfTypedValue(resultValue, ptr.mType);
  20716. else
  20717. mModule->mBfIRBuilder->CreateAlignedStore(resultValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  20718. if (unaryOp == BfUnaryOp_PostDecrement)
  20719. mResult = BfTypedValue(origVal, ptr.mType, false);
  20720. else
  20721. mResult = BfTypedValue(resultValue, ptr.mType, false);
  20722. }
  20723. break;
  20724. case BfUnaryOp_Ref:
  20725. case BfUnaryOp_Mut:
  20726. {
  20727. if (mAllowReadOnlyReference)
  20728. {
  20729. if (mResult.mKind == BfTypedValueKind_ReadOnlyAddr)
  20730. mResult.mKind = BfTypedValueKind_Addr;
  20731. }
  20732. CheckResultForReading(mResult);
  20733. if ((unaryOp == BfUnaryOp_Mut) && (!mResult.mType->IsValueType()) && (!mResult.mType->IsGenericParam()))
  20734. {
  20735. // Non-valuetypes types are already mutable, leave them alone...
  20736. break;
  20737. }
  20738. if ((unaryOp != BfUnaryOp_Mut) || (mResult.mKind != BfTypedValueKind_MutableValue))
  20739. {
  20740. if (!CheckModifyResult(mResult, unaryOpExpr, StrFormat("use '%s' on", BfGetOpName(unaryOp)).c_str()))
  20741. {
  20742. // Just leave the non-ref version in mResult
  20743. return;
  20744. }
  20745. }
  20746. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowRefExpr) == 0)
  20747. {
  20748. mResult = BfTypedValue();
  20749. mModule->Fail(StrFormat("Invalid usage of '%s' expression", BfGetOpName(unaryOp)), opToken);
  20750. return;
  20751. }
  20752. ResolveGenericType();
  20753. if (mResult.mType->IsVar())
  20754. break;
  20755. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, (unaryOp == BfUnaryOp_Ref) ? BfRefType::RefKind_Ref : BfRefType::RefKind_Mut));
  20756. }
  20757. break;
  20758. case BfUnaryOp_Out:
  20759. {
  20760. if (!CheckModifyResult(mResult, unaryOpExpr, "use 'out' on"))
  20761. {
  20762. // Just leave the non-ref version in mResult
  20763. return;
  20764. }
  20765. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowOutExpr) == 0)
  20766. {
  20767. mModule->Fail("Invalid usage of 'out' expression", opToken);
  20768. return;
  20769. }
  20770. if (mInsidePendingNullable)
  20771. {
  20772. // 'out' inside null conditionals never actually causes a definite assignment...
  20773. }
  20774. else
  20775. MarkResultAssigned();
  20776. MarkResultUsed();
  20777. ResolveGenericType();
  20778. if (mResult.mType->IsVar())
  20779. break;
  20780. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, BfRefType::RefKind_Out));
  20781. }
  20782. break;
  20783. case BfUnaryOp_Params:
  20784. {
  20785. bool allowParams = (mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) != 0;
  20786. if (allowParams)
  20787. {
  20788. if ((mResultLocalVar != NULL) && (mResultLocalVar->mCompositeCount >= 0)) // Delegate params
  20789. {
  20790. allowParams = true;
  20791. }
  20792. else
  20793. {
  20794. auto origValue = mResult;
  20795. auto isValid = false;
  20796. for (int pass = 0; pass < 2; pass++)
  20797. {
  20798. auto typeInst = mResult.mType->ToTypeInstance();
  20799. auto genericTypeInst = mResult.mType->ToGenericTypeInstance();
  20800. if ((genericTypeInst != NULL) && (genericTypeInst->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  20801. isValid = true;
  20802. else if ((mResult.mType->IsArray()) || (mResult.mType->IsSizedArray()))
  20803. isValid = true;
  20804. else if ((typeInst != NULL) && (pass == 0))
  20805. {
  20806. BfBaseClassWalker baseClassWalker(typeInst, NULL, mModule);
  20807. BfType* bestCastType = NULL;
  20808. while (true)
  20809. {
  20810. auto entry = baseClassWalker.Next();
  20811. auto checkType = entry.mTypeInstance;
  20812. if (checkType == NULL)
  20813. break;
  20814. for (auto operatorDef : checkType->mTypeDef->mOperators)
  20815. {
  20816. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  20817. {
  20818. if (operatorDef->IsExplicit())
  20819. continue;
  20820. auto methodInstance = mModule->GetRawMethodInstanceAtIdx(typeInst, operatorDef->mIdx);
  20821. auto checkType = methodInstance->mReturnType;
  20822. if (checkType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  20823. bestCastType = checkType;
  20824. else if ((checkType->IsArray()) || (checkType->IsSizedArray()))
  20825. bestCastType = checkType;
  20826. }
  20827. }
  20828. }
  20829. if (bestCastType == NULL)
  20830. break;
  20831. auto castTypedValue = mModule->Cast(opToken, mResult, bestCastType, BfCastFlags_SilentFail);
  20832. if (!castTypedValue)
  20833. break;
  20834. mResult = castTypedValue;
  20835. }
  20836. else
  20837. break;
  20838. }
  20839. if (!isValid)
  20840. {
  20841. mModule->Fail(StrFormat("A 'params' expression cannot be used on type '%s'", mModule->TypeToString(origValue.mType).c_str()), opToken);
  20842. }
  20843. }
  20844. }
  20845. if (allowParams)
  20846. {
  20847. mResult = mModule->LoadValue(mResult);
  20848. if ((mResult.mType != NULL) && (mResult.mType->IsParamsType()))
  20849. mResult.mType = mResult.mType->GetUnderlyingType();
  20850. if (mResult.IsSplat())
  20851. mResult.mKind = BfTypedValueKind_ParamsSplat;
  20852. else
  20853. mResult.mKind = BfTypedValueKind_Params;
  20854. }
  20855. else
  20856. {
  20857. mModule->Fail("Illegal use of 'params' expression", opToken);
  20858. }
  20859. }
  20860. break;
  20861. case BfUnaryOp_Cascade:
  20862. {
  20863. mModule->Fail("Illegal use of argument cascade expression", opToken);
  20864. }
  20865. break;
  20866. case BfUnaryOp_FromEnd:
  20867. {
  20868. CheckResultForReading(mResult);
  20869. auto value = mModule->Cast(unaryOpExpr, mResult, mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  20870. value = mModule->LoadValue(value);
  20871. if (value)
  20872. {
  20873. auto indexType = mModule->ResolveTypeDef(mModule->mCompiler->mIndexTypeDef);
  20874. auto alloca = mModule->CreateAlloca(indexType);
  20875. mModule->mBfIRBuilder->CreateStore(value.mValue, mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->CreateInBoundsGEP(alloca, 0, 1), 0, 1));
  20876. mModule->mBfIRBuilder->CreateStore(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 1), mModule->mBfIRBuilder->CreateInBoundsGEP(alloca, 0, 2));
  20877. mResult = BfTypedValue(alloca, indexType, BfTypedValueKind_Addr);
  20878. }
  20879. }
  20880. break;
  20881. case BfUnaryOp_PartialRangeUpTo:
  20882. PerformBinaryOperation(NULL, unaryOpExpr, BfBinaryOp_Range, opToken, BfBinOpFlag_None);
  20883. break;
  20884. case BfUnaryOp_PartialRangeThrough:
  20885. PerformBinaryOperation(NULL, unaryOpExpr, BfBinaryOp_ClosedRange, opToken, BfBinOpFlag_None);
  20886. break;
  20887. case BfUnaryOp_PartialRangeFrom:
  20888. PerformBinaryOperation(unaryOpExpr, NULL, BfBinaryOp_ClosedRange, opToken, BfBinOpFlag_None);
  20889. break;
  20890. default:
  20891. mModule->Fail(StrFormat("Illegal use of '%s' unary operator", BfGetOpName(unaryOp)), unaryOpExpr);
  20892. break;
  20893. }
  20894. if (numericFail)
  20895. {
  20896. if (opToken == NULL)
  20897. {
  20898. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  20899. }
  20900. else if ((mResult.mType != NULL) && (mResult.mType->IsInterface()))
  20901. {
  20902. mModule->Fail(
  20903. StrFormat("Operator '%s' cannot be used on interface '%s'. Consider rewriting using generics and use this interface as a generic constraint.",
  20904. BfTokenToString(opToken->mToken), mModule->TypeToString(mResult.mType).c_str()), opToken);
  20905. }
  20906. else
  20907. {
  20908. mModule->Fail(
  20909. StrFormat("Operator '%s' cannot be used because type '%s' is neither a numeric type nor does it define an applicable operator overload",
  20910. BfTokenToString(opToken->mToken), mModule->TypeToString(mResult.mType).c_str()), opToken);
  20911. }
  20912. mResult = BfTypedValue();
  20913. }
  20914. if (writeToProp)
  20915. {
  20916. auto setMethod = GetPropertyMethodDef(propDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  20917. if (setMethod == NULL)
  20918. {
  20919. mModule->Fail("Property has no setter", propSrc);
  20920. return;
  20921. }
  20922. auto methodInstance = GetPropertyMethodInstance(setMethod);
  20923. if (!methodInstance.mFunc)
  20924. return;
  20925. if (propSrc != NULL)
  20926. mModule->UpdateExprSrcPos(propSrc);
  20927. SizedArray<BfIRValue, 4> args;
  20928. if (!setMethod->mIsStatic)
  20929. {
  20930. auto usePropTarget = propTarget;
  20931. if (origPropTarget.mType == methodInstance.mMethodInstance->GetOwner())
  20932. usePropTarget = origPropTarget;
  20933. else
  20934. BF_ASSERT(propTarget.mType == methodInstance.mMethodInstance->GetOwner());
  20935. PushThis(propSrc, usePropTarget, methodInstance.mMethodInstance, args);
  20936. }
  20937. for (int paramIdx = 0; paramIdx < (int)indexerVals.size(); paramIdx++)
  20938. {
  20939. auto val = mModule->Cast(propSrc, indexerVals[paramIdx].mTypedValue, methodInstance.mMethodInstance->GetParamType(paramIdx));
  20940. if (!val)
  20941. return;
  20942. PushArg(val, args);
  20943. }
  20944. PushArg(writeToProp, args);
  20945. CreateCall(opToken, methodInstance.mMethodInstance, methodInstance.mFunc, false, args);
  20946. }
  20947. }
  20948. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue)
  20949. {
  20950. BfTypedValue rightValue;
  20951. if (rightExpression == NULL)
  20952. {
  20953. mModule->AssertErrorState();
  20954. return;
  20955. }
  20956. if (!leftValue)
  20957. {
  20958. if (!rightValue)
  20959. mModule->CreateValueFromExpression(rightExpression, mExpectingType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  20960. return;
  20961. }
  20962. if (leftValue.mType->IsRef())
  20963. leftValue.mType = leftValue.mType->GetUnderlyingType();
  20964. if ((binaryOp == BfBinaryOp_ConditionalAnd) || (binaryOp == BfBinaryOp_ConditionalOr))
  20965. {
  20966. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  20967. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  20968. if (mModule->mCurMethodState->mCurScope->mScopeKind == BfScopeKind_StatementTarget)
  20969. mModule->mCurMethodState->mCurScope->mScopeKind = BfScopeKind_StatementTarget_Conditional;
  20970. bool isAnd = binaryOp == BfBinaryOp_ConditionalAnd;
  20971. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  20972. leftValue = mModule->Cast(leftExpression, leftValue, boolType);
  20973. if (!leftValue)
  20974. {
  20975. mModule->CreateValueFromExpression(rightExpression);
  20976. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Undef);
  20977. return;
  20978. }
  20979. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  20980. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mInConditionalBlock, true);
  20981. // The RHS is not guaranteed to be executed
  20982. if ((mModule->mCurMethodState->mDeferredLocalAssignData != NULL) &&
  20983. (mModule->mCurMethodState->mDeferredLocalAssignData->mIsIfCondition))
  20984. mModule->mCurMethodState->mDeferredLocalAssignData->mIfMayBeSkipped = true;
  20985. if (isAnd)
  20986. {
  20987. bool isConstBranch = false;
  20988. bool constResult = false;
  20989. if (leftValue.mValue.IsConst())
  20990. {
  20991. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  20992. if (constValue->mTypeCode == BfTypeCode_Boolean)
  20993. {
  20994. isConstBranch = true;
  20995. constResult = constValue->mBool;
  20996. }
  20997. }
  20998. if (isConstBranch)
  20999. {
  21000. if ((constResult) || (HasVariableDeclaration(rightExpression)))
  21001. {
  21002. // Only right side
  21003. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  21004. mResult = rightValue;
  21005. }
  21006. else
  21007. {
  21008. // Always false
  21009. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  21010. SetAndRestoreValue<bool> prevInConstIgnore(mModule->mCurMethodState->mCurScope->mInConstIgnore, true);
  21011. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  21012. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolType);
  21013. }
  21014. }
  21015. else
  21016. {
  21017. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("land.rhs");
  21018. auto endBB = mModule->mBfIRBuilder->CreateBlock("land.end");
  21019. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, rhsBB, endBB);
  21020. mModule->AddBasicBlock(rhsBB);
  21021. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_CreateConditionalScope));
  21022. mModule->mBfIRBuilder->CreateBr(endBB);
  21023. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  21024. mModule->AddBasicBlock(endBB);
  21025. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  21026. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(0, boolType), prevBB);
  21027. if (rightValue)
  21028. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  21029. mResult = BfTypedValue(phi, boolType);
  21030. }
  21031. }
  21032. else
  21033. {
  21034. // Put variables in here into a 'possibly assigned' but never commit it.
  21035. // Because if we had "if ((Get(out a)) || (GetOther(out a))" then the LHS would already set it as defined, so
  21036. // the RHS is inconsequential
  21037. BfDeferredLocalAssignData deferredLocalAssignData;
  21038. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData, false);
  21039. deferredLocalAssignData.mVarIdBarrier = mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  21040. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mModule->mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  21041. bool isConstBranch = false;
  21042. bool constResult = false;
  21043. if (leftValue.mValue.IsConst())
  21044. {
  21045. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  21046. if (constValue->mTypeCode == BfTypeCode_Boolean)
  21047. {
  21048. isConstBranch = true;
  21049. constResult = constValue->mBool;
  21050. }
  21051. }
  21052. if (isConstBranch)
  21053. {
  21054. if ((constResult) && (!HasVariableDeclaration(rightExpression)))
  21055. {
  21056. // Always true
  21057. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  21058. SetAndRestoreValue<bool> prevInConstIgnore(mModule->mCurMethodState->mCurScope->mInConstIgnore, true);
  21059. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  21060. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  21061. }
  21062. else
  21063. {
  21064. // Only right side
  21065. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  21066. mResult = rightValue;
  21067. }
  21068. }
  21069. else
  21070. {
  21071. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("lor.rhs");
  21072. auto endBB = mModule->mBfIRBuilder->CreateBlock("lor.end");
  21073. // This makes any 'scope' allocs be dyn since we aren't sure if this will be short-circuited
  21074. SetAndRestoreValue<bool> prevIsConditional(mModule->mCurMethodState->mCurScope->mIsConditional, true);
  21075. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, endBB, rhsBB);
  21076. mModule->AddBasicBlock(rhsBB);
  21077. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  21078. mModule->mBfIRBuilder->CreateBr(endBB);
  21079. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  21080. mModule->AddBasicBlock(endBB);
  21081. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  21082. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(1, boolType), prevBB);
  21083. if (rightValue)
  21084. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  21085. mResult = BfTypedValue(phi, boolType);
  21086. }
  21087. }
  21088. return;
  21089. }
  21090. BfType* wantType = leftValue.mType;
  21091. BfType* origWantType = wantType;
  21092. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  21093. wantType = NULL; // Don't presume
  21094. wantType = mModule->FixIntUnknown(wantType);
  21095. if ((binaryOp == BfBinaryOp_NullCoalesce) && (PerformBinaryOperation_NullCoalesce(opToken, leftExpression, rightExpression, leftValue, wantType, NULL)))
  21096. return;
  21097. BfType* rightWantType = wantType;
  21098. if (origWantType->IsIntUnknown())
  21099. rightWantType = NULL;
  21100. else if ((mExpectingType != NULL) && (wantType != NULL) && (mExpectingType->IsIntegral()) && (wantType->IsIntegral()) && (mExpectingType->mSize > wantType->mSize) &&
  21101. ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_Multiply)))
  21102. rightWantType = mExpectingType;
  21103. rightValue = mModule->CreateValueFromExpression(rightExpression, rightWantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  21104. if ((rightWantType != wantType) && (rightValue.mType == rightWantType))
  21105. wantType = rightWantType;
  21106. if ((!leftValue) || (!rightValue))
  21107. return;
  21108. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue);
  21109. }
  21110. bool BfExprEvaluator::PerformBinaryOperation_NullCoalesce(BfTokenNode* opToken, BfExpression* leftExpression, BfExpression* rightExpression, BfTypedValue leftValue, BfType* wantType, BfTypedValue* assignTo)
  21111. {
  21112. if ((leftValue) && ((leftValue.mType->IsPointer()) || (leftValue.mType->IsFunction()) || (leftValue.mType->IsObject())) || (leftValue.mType->IsNullable()))
  21113. {
  21114. leftValue = mModule->LoadOrAggregateValue(leftValue);
  21115. mModule->mBfIRBuilder->PopulateType(leftValue.mType);
  21116. BfType* nullableElementType = NULL;
  21117. BfIRValue nullableHasValue;
  21118. BfTypedValue nullableExtractedLeftValue;
  21119. if (leftValue.mType->IsNullable())
  21120. {
  21121. nullableElementType = leftValue.mType->GetUnderlyingType();
  21122. nullableHasValue = mModule->mBfIRBuilder->CreateExtractValue(leftValue.mValue, nullableElementType->IsValuelessType() ? 1 : 2); // has_value
  21123. if (!nullableElementType->IsValuelessType())
  21124. nullableExtractedLeftValue = BfTypedValue(mModule->mBfIRBuilder->CreateExtractValue(leftValue.mValue, 1), nullableElementType); // value
  21125. else
  21126. nullableExtractedLeftValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), nullableElementType);
  21127. }
  21128. if (leftValue.mValue.IsConst())
  21129. {
  21130. auto constant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  21131. if (constant->IsNull())
  21132. {
  21133. mResult = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  21134. return true;
  21135. }
  21136. // Already have a value, we don't need the right side
  21137. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  21138. SetAndRestoreValue<bool> prevInConstIgnore(mModule->mCurMethodState->mCurScope->mInConstIgnore, true);
  21139. mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_CreateConditionalScope));
  21140. mResult = leftValue;
  21141. return true;
  21142. }
  21143. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  21144. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("nullc.rhs");
  21145. auto endBB = mModule->mBfIRBuilder->CreateBlock("nullc.end");
  21146. auto lhsBB = endBB;
  21147. auto endLhsBB = prevBB;
  21148. BfIRValue isNull;
  21149. if (nullableHasValue)
  21150. isNull = mModule->mBfIRBuilder->CreateCmpEQ(nullableHasValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0));
  21151. else if (leftValue.mType->IsFunction())
  21152. isNull = mModule->mBfIRBuilder->CreateIsNull(
  21153. mModule->mBfIRBuilder->CreateIntToPtr(leftValue.mValue, mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_NullPtr))));
  21154. else
  21155. isNull = mModule->mBfIRBuilder->CreateIsNull(leftValue.mValue);
  21156. mModule->AddBasicBlock(rhsBB);
  21157. BfTypedValue rightValue;
  21158. if (assignTo != NULL)
  21159. rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_CreateConditionalScope));
  21160. else
  21161. rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  21162. if (!rightValue)
  21163. {
  21164. mModule->AssertErrorState();
  21165. return true;
  21166. }
  21167. if ((assignTo == NULL) && (leftValue.mType->IsNullable()) && (!rightValue.mType->IsNullable()))
  21168. {
  21169. if (wantType == leftValue.mType)
  21170. wantType = nullableElementType;
  21171. leftValue = nullableExtractedLeftValue;
  21172. }
  21173. rightValue = mModule->LoadValue(rightValue);
  21174. if (assignTo == NULL)
  21175. {
  21176. auto rightToLeftValue = mModule->CastToValue(rightExpression, rightValue, leftValue.mType, BfCastFlags_SilentFail);
  21177. if (rightToLeftValue)
  21178. {
  21179. rightValue = BfTypedValue(rightToLeftValue, leftValue.mType);
  21180. }
  21181. else
  21182. {
  21183. lhsBB = mModule->mBfIRBuilder->CreateBlock("nullc.lhs", true);
  21184. mModule->mBfIRBuilder->SetInsertPoint(lhsBB);
  21185. auto leftToRightValue = mModule->CastToValue(leftExpression, leftValue, rightValue.mType, BfCastFlags_SilentFail);
  21186. if (leftToRightValue)
  21187. {
  21188. leftValue = BfTypedValue(leftToRightValue, rightValue.mType);
  21189. }
  21190. else
  21191. {
  21192. // Note: Annoying trigraph split for '??'
  21193. mModule->Fail(StrFormat("Operator '?" "?' cannot be applied to operands of type '%s' and '%s'",
  21194. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  21195. leftValue = mModule->GetDefaultTypedValue(rightValue.mType);
  21196. }
  21197. mModule->mBfIRBuilder->CreateBr(endBB);
  21198. endLhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  21199. mModule->mBfIRBuilder->SetInsertPoint(rhsBB);
  21200. }
  21201. }
  21202. if (assignTo != NULL)
  21203. mModule->mBfIRBuilder->CreateStore(rightValue.mValue, assignTo->mValue);
  21204. mModule->mBfIRBuilder->CreateBr(endBB);
  21205. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  21206. // Actually add CondBr at start
  21207. mModule->mBfIRBuilder->SetInsertPoint(prevBB);
  21208. mModule->mBfIRBuilder->CreateCondBr(isNull, rhsBB, lhsBB);
  21209. mModule->AddBasicBlock(endBB);
  21210. if (assignTo != NULL)
  21211. {
  21212. mResult = *assignTo;
  21213. }
  21214. else
  21215. {
  21216. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(leftValue.mType), 2);
  21217. if (!leftValue.mType->IsValuelessType())
  21218. mModule->mBfIRBuilder->AddPhiIncoming(phi, leftValue.mValue, endLhsBB);
  21219. if (!rightValue.mType->IsValuelessType())
  21220. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  21221. mResult = BfTypedValue(phi, leftValue.mType);
  21222. }
  21223. return true;
  21224. }
  21225. return false;
  21226. }
  21227. bool BfExprEvaluator::PerformBinaryOperation_Numeric(BfAstNode* leftExpression, BfAstNode* rightExpression, BfBinaryOp binaryOp, BfAstNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue, BfTypedValue rightValue)
  21228. {
  21229. switch (binaryOp)
  21230. {
  21231. case BfBinaryOp_Add:
  21232. case BfBinaryOp_Subtract:
  21233. case BfBinaryOp_Multiply:
  21234. case BfBinaryOp_Divide:
  21235. case BfBinaryOp_Modulus:
  21236. break;
  21237. default:
  21238. return false;
  21239. }
  21240. auto wantType = mExpectingType;
  21241. if ((wantType == NULL) ||
  21242. ((!wantType->IsFloat()) && (!wantType->IsIntegral())))
  21243. wantType = NULL;
  21244. auto leftType = mModule->GetClosestNumericCastType(leftValue, mExpectingType);
  21245. auto rightType = mModule->GetClosestNumericCastType(rightValue, mExpectingType);
  21246. if (leftType != NULL)
  21247. {
  21248. if ((rightType == NULL) || (mModule->CanCast(mModule->GetFakeTypedValue(rightType), leftType)))
  21249. wantType = leftType;
  21250. else if ((rightType != NULL) && (mModule->CanCast(mModule->GetFakeTypedValue(leftType), rightType)))
  21251. wantType = rightType;
  21252. }
  21253. else if (rightType != NULL)
  21254. wantType = rightType;
  21255. if (wantType == NULL)
  21256. wantType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  21257. auto convLeftValue = mModule->Cast(opToken, leftValue, wantType, BfCastFlags_SilentFail);
  21258. if (!convLeftValue)
  21259. return false;
  21260. auto convRightValue = mModule->Cast(opToken, rightValue, wantType, BfCastFlags_SilentFail);
  21261. if (!convRightValue)
  21262. return false;
  21263. mResult = BfTypedValue();
  21264. // Let the error come from here, if any - so we always return 'true' to avoid a second error
  21265. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, convLeftValue, convRightValue);
  21266. return true;
  21267. }
  21268. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags)
  21269. {
  21270. if ((binaryOp == BfBinaryOp_Range) || (binaryOp == BfBinaryOp_ClosedRange))
  21271. {
  21272. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  21273. bool isIndexExpr = false;
  21274. BfTypeDef* typeDef = NULL;
  21275. if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(leftExpression))
  21276. if (unaryOpExpr->mOp == BfUnaryOp_FromEnd)
  21277. isIndexExpr = true;
  21278. if (rightExpression == NULL)
  21279. isIndexExpr = true;
  21280. if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(rightExpression))
  21281. if (unaryOpExpr->mOp == BfUnaryOp_FromEnd)
  21282. isIndexExpr = true;
  21283. if (isIndexExpr)
  21284. typeDef = mModule->mCompiler->mIndexRangeTypeDef;
  21285. else
  21286. typeDef = (binaryOp == BfBinaryOp_Range) ? mModule->mCompiler->mRangeTypeDef : mModule->mCompiler->mClosedRangeTypeDef;
  21287. auto allocType = mModule->ResolveTypeDef(typeDef)->ToTypeInstance();
  21288. auto alloca = mModule->CreateAlloca(allocType);
  21289. BfTypedValueExpression leftTypedValueExpr;
  21290. BfTypedValueExpression rightTypedValueExpr;
  21291. BfTypedValueExpression isClosedTypedValueExpr;
  21292. SizedArray<BfExpression*, 2> argExprs;
  21293. if (leftExpression != NULL)
  21294. {
  21295. argExprs.Add(leftExpression);
  21296. }
  21297. else
  21298. {
  21299. leftTypedValueExpr.mRefNode = opToken;
  21300. leftTypedValueExpr.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  21301. argExprs.Add(&leftTypedValueExpr);
  21302. }
  21303. if (rightExpression != NULL)
  21304. {
  21305. argExprs.Add(rightExpression);
  21306. }
  21307. else
  21308. {
  21309. // Add as a `^1`
  21310. auto indexType = mModule->ResolveTypeDef(mModule->mCompiler->mIndexTypeDef)->ToTypeInstance();
  21311. mModule->PopulateType(indexType->mBaseType);
  21312. BF_ASSERT_REL(indexType->mBaseType->mBaseType != NULL);
  21313. rightTypedValueExpr.mRefNode = opToken;
  21314. auto valueTypeEmpty = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType->mBaseType->mBaseType), {});
  21315. SizedArray<BfIRValue, 8> tupleEmptyMembers;
  21316. tupleEmptyMembers.Add(valueTypeEmpty);
  21317. auto tupleTypeEmpty = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(mModule->ResolveTypeDef(mModule->mCompiler->mTupleTypeDef)), tupleEmptyMembers);
  21318. SizedArray<BfIRValue, 8> enumMembers;
  21319. enumMembers.Add(valueTypeEmpty);
  21320. auto enumValue = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType->mBaseType), enumMembers);
  21321. SizedArray<BfIRValue, 8> tupleMembers;
  21322. tupleMembers.Add(tupleTypeEmpty);
  21323. tupleMembers.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  21324. auto tupleValue = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType->mFieldInstances[0].mResolvedType), tupleMembers);
  21325. SizedArray<BfIRValue, 8> indexMembers;
  21326. indexMembers.Add(enumValue);
  21327. indexMembers.Add(tupleValue);
  21328. indexMembers.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 1));
  21329. auto indexValue = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType), indexMembers);
  21330. rightTypedValueExpr.mTypedValue = BfTypedValue(indexValue, indexType);
  21331. argExprs.Add(&rightTypedValueExpr);
  21332. }
  21333. if (isIndexExpr)
  21334. {
  21335. isClosedTypedValueExpr.mRefNode = opToken;
  21336. isClosedTypedValueExpr.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (binaryOp == BfBinaryOp_ClosedRange) ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21337. argExprs.Add(&isClosedTypedValueExpr);
  21338. }
  21339. BfSizedArray<BfExpression*> args = argExprs;
  21340. BfResolvedArgs argValues;
  21341. argValues.Init(&args);
  21342. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  21343. mResult = BfTypedValue(alloca, allocType, true);
  21344. auto result = MatchConstructor(opToken, NULL, mResult, allocType, argValues, true, BfMethodGenericArguments(), BfAllowAppendKind_No);
  21345. if ((result) && (!result.mType->IsVoid()))
  21346. mResult = result;
  21347. return;
  21348. }
  21349. BfTypedValue leftValue;
  21350. if (leftExpression != NULL)
  21351. {
  21352. leftValue = mModule->CreateValueFromExpression(leftExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  21353. }
  21354. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue);
  21355. }
  21356. bool BfExprEvaluator::CheckConstCompare(BfBinaryOp binaryOp, BfAstNode* opToken, const BfTypedValue& leftValue, const BfTypedValue& rightValue)
  21357. {
  21358. if ((binaryOp < BfBinaryOp_Equality) || (binaryOp > BfBinaryOp_LessThanOrEqual))
  21359. return false;
  21360. // LHS is expected to be a value and RHS is expected to be a const
  21361. if (!leftValue.mType->IsIntegral())
  21362. return false;
  21363. BF_ASSERT(rightValue.mValue.IsConst());
  21364. auto rightConst = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  21365. if (!mModule->mBfIRBuilder->IsInt(rightConst->mTypeCode))
  21366. return false;
  21367. BfType* checkType = leftValue.mType;
  21368. if (checkType->IsTypedPrimitive())
  21369. checkType = checkType->GetUnderlyingType();
  21370. if (!checkType->IsPrimitiveType())
  21371. return false;
  21372. BfTypeCode typeCode = ((BfPrimitiveType*)checkType)->mTypeDef->mTypeCode;
  21373. int64 minValue = 0;
  21374. int64 maxValue = 0;
  21375. switch (typeCode)
  21376. {
  21377. case BfTypeCode_Int8:
  21378. minValue = -0x80;
  21379. maxValue = 0x7F;
  21380. break;
  21381. case BfTypeCode_Int16:
  21382. minValue = -0x8000;
  21383. maxValue = 0x7FFF;
  21384. break;
  21385. case BfTypeCode_Int32:
  21386. minValue = -0x80000000LL;
  21387. maxValue = 0x7FFFFFFF;
  21388. break;
  21389. case BfTypeCode_Int64:
  21390. minValue = -0x8000000000000000LL;
  21391. maxValue = 0x7FFFFFFFFFFFFFFFLL;
  21392. break;
  21393. case BfTypeCode_UInt8:
  21394. maxValue = 0xFF;
  21395. break;
  21396. case BfTypeCode_UInt16:
  21397. maxValue = 0xFFFF;
  21398. break;
  21399. case BfTypeCode_UInt32:
  21400. maxValue = 0xFFFFFFFF;
  21401. break;
  21402. default:
  21403. return false;
  21404. }
  21405. int constResult = -1;
  21406. if (typeCode == BfTypeCode_UInt64)
  21407. {
  21408. switch (binaryOp)
  21409. {
  21410. case BfBinaryOp_Equality:
  21411. case BfBinaryOp_StrictEquality:
  21412. if (rightConst->mInt64 < minValue)
  21413. constResult = 0;
  21414. break;
  21415. case BfBinaryOp_InEquality:
  21416. case BfBinaryOp_StrictInEquality:
  21417. if (rightConst->mInt64 < minValue)
  21418. constResult = 1;
  21419. break;
  21420. case BfBinaryOp_LessThan:
  21421. if (rightConst->mInt64 <= minValue)
  21422. constResult = 0;
  21423. break;
  21424. case BfBinaryOp_LessThanOrEqual:
  21425. if (rightConst->mInt64 < minValue)
  21426. constResult = 0;
  21427. break;
  21428. default: break;
  21429. }
  21430. return false;
  21431. }
  21432. else
  21433. {
  21434. switch (binaryOp)
  21435. {
  21436. case BfBinaryOp_Equality:
  21437. case BfBinaryOp_StrictEquality:
  21438. if (rightConst->mInt64 < minValue)
  21439. constResult = 0;
  21440. else if (rightConst->mInt64 > maxValue)
  21441. constResult = 0;
  21442. break;
  21443. case BfBinaryOp_InEquality:
  21444. case BfBinaryOp_StrictInEquality:
  21445. if (rightConst->mInt64 < minValue)
  21446. constResult = 1;
  21447. else if (rightConst->mInt64 > maxValue)
  21448. constResult = 1;
  21449. break;
  21450. case BfBinaryOp_LessThan:
  21451. if (rightConst->mInt64 <= minValue)
  21452. constResult = 0;
  21453. else if (rightConst->mInt64 > maxValue)
  21454. constResult = 1;
  21455. break;
  21456. case BfBinaryOp_LessThanOrEqual:
  21457. if (rightConst->mInt64 < minValue)
  21458. constResult = 0;
  21459. else if (rightConst->mInt64 >= maxValue)
  21460. constResult = 1;
  21461. break;
  21462. case BfBinaryOp_GreaterThan:
  21463. if (rightConst->mInt64 >= maxValue)
  21464. constResult = 0;
  21465. else if (rightConst->mInt64 < minValue)
  21466. constResult = 1;
  21467. break;
  21468. case BfBinaryOp_GreaterThanOrEqual:
  21469. if (rightConst->mInt64 > maxValue)
  21470. constResult = 0;
  21471. else if (rightConst->mInt64 <= minValue)
  21472. constResult = 1;
  21473. break;
  21474. default: break;
  21475. }
  21476. }
  21477. if (constResult == 0)
  21478. {
  21479. mModule->Warn(0, "The result of this operation is always 'false'", opToken);
  21480. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21481. return true;
  21482. }
  21483. else if (constResult == 1)
  21484. {
  21485. mModule->Warn(0, "The result of this operation is always 'true'", opToken);
  21486. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21487. return true;
  21488. }
  21489. return false;
  21490. }
  21491. void BfExprEvaluator::AddStrings(const BfTypedValue& leftValue, const BfTypedValue& rightValue, BfAstNode* refNode)
  21492. {
  21493. if ((leftValue.mValue.IsConst()) && (rightValue.mValue.IsConst()))
  21494. {
  21495. String* lhsStr = mModule->GetStringPoolString(leftValue.mValue, mModule->mBfIRBuilder);
  21496. String* rhsStr = mModule->GetStringPoolString(rightValue.mValue, mModule->mBfIRBuilder);
  21497. if ((lhsStr != NULL) && (rhsStr != NULL))
  21498. {
  21499. String resultStr = *lhsStr + *rhsStr;
  21500. BfVariant variant;
  21501. variant.mTypeCode = BfTypeCode_CharPtr;
  21502. variant.mString = &resultStr;
  21503. GetLiteral(refNode, variant);
  21504. return;
  21505. }
  21506. }
  21507. mModule->Fail("Strings can only be added when they are constants. Consider allocating a string and using Concat.", refNode);
  21508. return;
  21509. }
  21510. void BfExprEvaluator::PerformBinaryOperation(BfAstNode* leftExpression, BfAstNode* rightExpression, BfBinaryOp binaryOp, BfAstNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue, BfTypedValue rightValue)
  21511. {
  21512. bool noClassify = (flags & BfBinOpFlag_NoClassify) != 0;
  21513. bool forceRightType = (flags & BfBinOpFlag_ForceRightType) != 0;
  21514. bool forceLeftType = (flags & BfBinOpFlag_ForceLeftType) != 0;
  21515. bool deferRight = (flags & BfBinOpFlag_DeferRight) != 0;
  21516. if (deferRight)
  21517. {
  21518. rightValue = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  21519. }
  21520. if ((rightValue.mValue.IsConst()) && (!leftValue.mValue.IsConst()))
  21521. {
  21522. if (CheckConstCompare(binaryOp, opToken, leftValue, rightValue))
  21523. return;
  21524. }
  21525. else if ((leftValue.mValue.IsConst()) && (!rightValue.mValue.IsConst()))
  21526. {
  21527. if (CheckConstCompare(BfGetOppositeBinaryOp(binaryOp), opToken, rightValue, leftValue))
  21528. return;
  21529. }
  21530. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  21531. {
  21532. forceLeftType = true;
  21533. mModule->FixIntUnknown(leftValue);
  21534. }
  21535. if (rightValue.mType->IsRef())
  21536. rightValue.mType = rightValue.mType->GetUnderlyingType();
  21537. BfType* origLeftType = leftValue.mType;
  21538. BfType* origRightType = rightValue.mType;
  21539. mModule->FixIntUnknown(leftValue, rightValue);
  21540. // Prefer floats, prefer chars
  21541. int leftCompareSize = leftValue.mType->mSize;
  21542. if (leftValue.mType->IsFloat())
  21543. leftCompareSize += 0x10;
  21544. if (leftValue.mType->IsChar())
  21545. leftCompareSize += 0x100;
  21546. if (!leftValue.mType->IsPrimitiveType())
  21547. leftCompareSize += 0x1000;
  21548. int rightCompareSize = rightValue.mType->mSize;
  21549. if (rightValue.mType->IsFloat())
  21550. rightCompareSize += 0x10;
  21551. if (rightValue.mType->IsChar())
  21552. rightCompareSize += 0x100;
  21553. if (!rightValue.mType->IsPrimitiveType())
  21554. rightCompareSize += 0x1000;
  21555. if ((leftValue.mType->IsTypeInstance()) && (rightValue.mType->IsTypeInstance()))
  21556. {
  21557. int leftInheritDepth = leftValue.mType->ToTypeInstance()->mInheritDepth;
  21558. int rightInheritDepth = rightValue.mType->ToTypeInstance()->mInheritDepth;
  21559. if (leftInheritDepth < rightInheritDepth)
  21560. {
  21561. // If both are type instances then choose the type with the lowest inherit depth
  21562. // so we will choose the base type when applicable
  21563. forceLeftType = true;
  21564. }
  21565. }
  21566. auto resultType = leftValue.mType;
  21567. if (forceRightType)
  21568. {
  21569. resultType = rightValue.mType;
  21570. }
  21571. else if (!forceLeftType)
  21572. {
  21573. bool handled = false;
  21574. BfType* expectingType = mExpectingType;
  21575. if (leftValue.mType == rightValue.mType)
  21576. {
  21577. // All good
  21578. handled = true;
  21579. }
  21580. else if ((expectingType != NULL) &&
  21581. (mModule->CanCast(leftValue, expectingType, BfCastFlags_NoBox)) &&
  21582. (mModule->CanCast(rightValue, expectingType, BfCastFlags_NoBox)) &&
  21583. (!leftValue.mType->IsVar()) && (!rightValue.mType->IsVar()))
  21584. {
  21585. resultType = expectingType;
  21586. handled = true;
  21587. }
  21588. else
  21589. {
  21590. // If one of these is a constant that can be converted into a smaller type, then do that
  21591. if (rightValue.mValue.IsConst())
  21592. {
  21593. if (mModule->CanCast(rightValue, leftValue.mType, BfCastFlags_NoBox))
  21594. {
  21595. resultType = leftValue.mType;
  21596. handled = true;
  21597. }
  21598. }
  21599. // If left is an IntUnknown, allow the right to inform the type
  21600. if (leftValue.mType->IsIntUnknown())
  21601. {
  21602. if (leftValue.mValue.IsConst())
  21603. {
  21604. if (mModule->CanCast(leftValue, rightValue.mType))
  21605. {
  21606. resultType = rightValue.mType;
  21607. handled = true;
  21608. }
  21609. }
  21610. }
  21611. if ((leftValue.mType->IsPointer()) &&
  21612. (rightValue.mType->IsPointer()))
  21613. {
  21614. BfPointerType* leftPointerType = (BfPointerType*)leftValue.mType;
  21615. BfPointerType* rightPointerType = (BfPointerType*)rightValue.mType;
  21616. // If one is a pointer to a sized array then use the other type
  21617. if (leftPointerType->mElementType->IsSizedArray())
  21618. {
  21619. resultType = rightPointerType;
  21620. handled = true;
  21621. }
  21622. else if (rightPointerType->mElementType->IsSizedArray())
  21623. {
  21624. resultType = leftPointerType;
  21625. handled = true;
  21626. }
  21627. }
  21628. }
  21629. if (!handled)
  21630. {
  21631. if ((resultType->IsNull()) ||
  21632. (rightCompareSize > leftCompareSize) ||
  21633. (((rightCompareSize == leftCompareSize) && (!rightValue.mType->IsSigned()))) ||
  21634. (rightValue.mType->IsTypedPrimitive()))
  21635. {
  21636. // Select the type with the "most information"
  21637. if (!rightValue.mType->IsNull())
  21638. resultType = rightValue.mType;
  21639. }
  21640. if ((!resultType->IsPointer()) && (rightValue.mType->IsPointer()))
  21641. resultType = rightValue.mType;
  21642. }
  21643. }
  21644. bool explicitCast = false;
  21645. BfTypedValue* resultTypedValue;
  21646. BfTypedValue* otherTypedValue;
  21647. BfType* otherType;
  21648. BfAstNode* resultTypeSrc;
  21649. BfAstNode* otherTypeSrc;
  21650. if (resultType == leftValue.mType)
  21651. {
  21652. resultTypedValue = &leftValue;
  21653. resultTypeSrc = leftExpression;
  21654. otherTypedValue = &rightValue;
  21655. otherTypeSrc = rightExpression;
  21656. otherType = otherTypedValue->mType;
  21657. }
  21658. else
  21659. {
  21660. resultTypedValue = &rightValue;
  21661. resultTypeSrc = rightExpression;
  21662. otherTypedValue = &leftValue;
  21663. otherTypeSrc = leftExpression;
  21664. otherType = otherTypedValue->mType;
  21665. }
  21666. auto _OpFail = [&]()
  21667. {
  21668. if ((rightValue.mType != NULL) && (leftValue.mType != NULL))
  21669. {
  21670. if (rightValue.mType != leftValue.mType)
  21671. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between types '%s' and '%s'",
  21672. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  21673. else
  21674. {
  21675. if (leftValue.mType->IsInterface())
  21676. {
  21677. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between two instances of interface '%s'. Consider rewriting using generics and use this interface as a generic constraint.",
  21678. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  21679. }
  21680. else
  21681. {
  21682. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between two instances of type '%s'",
  21683. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  21684. }
  21685. }
  21686. }
  21687. else
  21688. mModule->Fail(StrFormat("Cannot perform binary operation '%s'", BfGetOpName(binaryOp)), opToken);
  21689. };
  21690. // This case fixes cases like "c == 0" where "0" is technically an int but can be reduced
  21691. if (BfBinOpEqualityCheck(binaryOp))
  21692. {
  21693. if ((resultType != otherType) && (resultTypedValue->mValue.IsConst()) && (mModule->CanCast(*resultTypedValue, otherType)))
  21694. {
  21695. std::swap(resultTypedValue, otherTypedValue);
  21696. std::swap(resultTypeSrc, otherTypeSrc);
  21697. std::swap(resultType, otherType);
  21698. }
  21699. }
  21700. BfIRValue convLeftValue;
  21701. BfIRValue convRightValue;
  21702. if (((resultType->IsVar()) || (otherType->IsVar())) && (!deferRight))
  21703. {
  21704. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  21705. if (isComparison)
  21706. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Boolean), false, BfDefaultValueKind_Addr);
  21707. else if (mExpectingType != NULL)
  21708. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  21709. else
  21710. mResult = mModule->GetDefaultTypedValue(resultType, false, BfDefaultValueKind_Addr);
  21711. return;
  21712. }
  21713. if ((otherType->IsNull()) && (BfBinOpEqualityCheck(binaryOp)))
  21714. {
  21715. bool isEquality = (binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality);
  21716. if ((resultType->IsValueType()) && (!resultType->IsFunction()))
  21717. {
  21718. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  21719. if (resultType->IsNullable())
  21720. {
  21721. auto elementType = resultType->GetUnderlyingType();
  21722. mModule->PopulateType(elementType);
  21723. if (elementType->IsValuelessType())
  21724. {
  21725. mModule->mBfIRBuilder->PopulateType(resultType);
  21726. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  21727. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 1);
  21728. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateAlignedLoad(hasValuePtr, 1);
  21729. if (isEquality)
  21730. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  21731. mResult = BfTypedValue(hasValueValue, boolType);
  21732. }
  21733. else
  21734. {
  21735. mModule->mBfIRBuilder->PopulateType(resultType);
  21736. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  21737. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 2);
  21738. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateAlignedLoad(hasValuePtr, 1);
  21739. if (isEquality)
  21740. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  21741. mResult = BfTypedValue(hasValueValue, boolType);
  21742. }
  21743. return;
  21744. }
  21745. if (resultType->IsNull())
  21746. {
  21747. // Null always equals null
  21748. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 1 : 0, boolType), boolType);
  21749. return;
  21750. }
  21751. if (!mModule->IsInSpecializedSection())
  21752. {
  21753. //CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type '<null>'
  21754. mModule->Warn(BfWarning_CS0472_ValueTypeNullCompare,
  21755. StrFormat("The result of the expression is always '%s' since a value of type '%s' can never be null",
  21756. isEquality ? "false" : "true", mModule->TypeToString(resultType).c_str()), otherTypeSrc);
  21757. }
  21758. // Valuetypes never equal null
  21759. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 0 : 1, boolType), boolType);
  21760. return;
  21761. }
  21762. }
  21763. // Check for constant equality checks (mostly for strings)
  21764. if (BfBinOpEqualityCheck(binaryOp))
  21765. {
  21766. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  21767. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  21768. if ((leftConstant != NULL) && (rightConstant != NULL))
  21769. {
  21770. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  21771. int leftStringPoolIdx = mModule->GetStringPoolIdx(leftValue.mValue, mModule->mBfIRBuilder);
  21772. if (leftStringPoolIdx != -1)
  21773. {
  21774. int rightStringPoolIdx = mModule->GetStringPoolIdx(rightValue.mValue, mModule->mBfIRBuilder);
  21775. if (rightStringPoolIdx != -1)
  21776. {
  21777. bool isEqual = leftStringPoolIdx == rightStringPoolIdx;
  21778. if ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  21779. isEqual = !isEqual;
  21780. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  21781. return;
  21782. }
  21783. }
  21784. int eqResult = mModule->mBfIRBuilder->CheckConstEquality(leftValue.mValue, rightValue.mValue);
  21785. if (eqResult != -1)
  21786. {
  21787. bool isEqual = eqResult == 1;
  21788. if ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  21789. isEqual = !isEqual;
  21790. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  21791. return;
  21792. }
  21793. }
  21794. }
  21795. if ((leftValue.mType->IsTypeInstance()) || (leftValue.mType->IsGenericParam()) ||
  21796. (rightValue.mType->IsTypeInstance()) || (rightValue.mType->IsGenericParam()))
  21797. {
  21798. // As an optimization, we don't call user operator overloads for null checks
  21799. bool skipOpOverload = false;
  21800. if ((binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  21801. skipOpOverload = true;
  21802. else if (BfBinOpEqualityCheck(binaryOp))
  21803. {
  21804. if (!leftValue.IsAddr())
  21805. {
  21806. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  21807. if ((leftConstant != NULL) && (leftConstant->IsNull()))
  21808. skipOpOverload = true;
  21809. }
  21810. if (!rightValue.IsAddr())
  21811. {
  21812. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  21813. if ((rightConstant != NULL) && (rightConstant->IsNull()))
  21814. skipOpOverload = true;
  21815. }
  21816. }
  21817. if ((binaryOp == BfBinaryOp_Add) && (resultType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  21818. {
  21819. // Allow failover to constant string addition
  21820. if ((leftValue.mValue.IsConst()) && (rightValue.mValue.IsConst()))
  21821. skipOpOverload = true;
  21822. }
  21823. if (!skipOpOverload)
  21824. {
  21825. BfBinaryOp findBinaryOp = binaryOp;
  21826. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  21827. for (int pass = 0; pass < 2; pass++)
  21828. {
  21829. BfBinaryOp oppositeBinaryOp = BfGetOppositeBinaryOp(findBinaryOp);
  21830. BfBinaryOp overflowBinaryOp = BfBinaryOp_None;
  21831. if (findBinaryOp == BfBinaryOp_OverflowAdd)
  21832. overflowBinaryOp = BfBinaryOp_Add;
  21833. else if (findBinaryOp == BfBinaryOp_OverflowSubtract)
  21834. overflowBinaryOp = BfBinaryOp_Subtract;
  21835. else if (findBinaryOp == BfBinaryOp_OverflowMultiply)
  21836. overflowBinaryOp = BfBinaryOp_Multiply;
  21837. bool foundOp = false;
  21838. BfResolvedArg leftArg;
  21839. leftArg.mExpression = leftExpression;
  21840. leftArg.mTypedValue = leftValue;
  21841. BfResolvedArg rightArg;
  21842. rightArg.mExpression = rightExpression;
  21843. rightArg.mTypedValue = rightValue;
  21844. if (deferRight)
  21845. {
  21846. BfResolvedArgs argValues;
  21847. SizedArray<BfExpression*, 2> argExprs;
  21848. argExprs.push_back(BfNodeDynCast<BfExpression>(rightExpression));
  21849. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  21850. argValues.Init(&sizedArgExprs);
  21851. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  21852. rightArg = argValues.mResolvedArgs[0];
  21853. }
  21854. SizedArray<BfResolvedArg, 2> args;
  21855. if (pass == 0)
  21856. {
  21857. args.push_back(leftArg);
  21858. args.push_back(rightArg);
  21859. }
  21860. else
  21861. {
  21862. args.push_back(rightArg);
  21863. args.push_back(leftArg);
  21864. }
  21865. auto checkLeftType = leftValue.mType;
  21866. auto checkRightType = rightValue.mType;
  21867. BfMethodMatcher methodMatcher(opToken, mModule, "", args, BfMethodGenericArguments());
  21868. methodMatcher.mAllowImplicitRef = true;
  21869. methodMatcher.mBfEvalExprFlags = BfEvalExprFlags_NoAutoComplete;
  21870. BfBaseClassWalker baseClassWalker(checkLeftType, checkRightType, mModule);
  21871. bool invertResult = false;
  21872. BfType* operatorConstraintReturnType = NULL;
  21873. bool wasTransformedUsage = (pass == 1);
  21874. while (true)
  21875. {
  21876. auto entry = baseClassWalker.Next();
  21877. auto checkType = entry.mTypeInstance;
  21878. if (checkType == NULL)
  21879. break;
  21880. bool foundExactMatch = false;
  21881. SizedArray<BfOperatorDef*, 8> oppositeOperatorDefs;
  21882. for (auto operatorDef : checkType->mTypeDef->mOperators)
  21883. {
  21884. bool allowOp = operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp;
  21885. if ((isComparison) && (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare))
  21886. allowOp = true;
  21887. if (allowOp)
  21888. {
  21889. foundOp = true;
  21890. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  21891. continue;
  21892. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  21893. {
  21894. if (operatorDef->mGenericParams.IsEmpty())
  21895. {
  21896. // Fast check
  21897. auto returnType = mModule->CheckOperator(checkType, operatorDef, args[0].mTypedValue, args[1].mTypedValue);
  21898. if (returnType != NULL)
  21899. {
  21900. operatorConstraintReturnType = returnType;
  21901. methodMatcher.mBestMethodDef = operatorDef;
  21902. methodMatcher.mBestMethodTypeInstance = checkType;
  21903. foundExactMatch = true;
  21904. }
  21905. }
  21906. else
  21907. {
  21908. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  21909. {
  21910. auto rawMethodInstance = mModule->GetRawMethodInstance(checkType, operatorDef);
  21911. auto returnType = mModule->ResolveGenericType(rawMethodInstance->mReturnType, NULL, &methodMatcher.mBestMethodGenericArguments,
  21912. mModule->mCurTypeInstance);
  21913. if (returnType != NULL)
  21914. {
  21915. operatorConstraintReturnType = returnType;
  21916. foundExactMatch = true;
  21917. }
  21918. }
  21919. }
  21920. }
  21921. else
  21922. {
  21923. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  21924. {
  21925. methodMatcher.mSelfType = entry.mSrcType;
  21926. if (operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp)
  21927. foundExactMatch = true;
  21928. }
  21929. }
  21930. }
  21931. else if ((operatorDef->mOperatorDeclaration->mBinOp == oppositeBinaryOp) || (operatorDef->mOperatorDeclaration->mBinOp == overflowBinaryOp))
  21932. oppositeOperatorDefs.Add(operatorDef);
  21933. }
  21934. if ((((methodMatcher.mBestMethodDef == NULL) && (operatorConstraintReturnType == NULL)) || (!foundExactMatch)) && (!oppositeOperatorDefs.IsEmpty()))
  21935. {
  21936. foundOp = true;
  21937. for (auto oppositeOperatorDef : oppositeOperatorDefs)
  21938. {
  21939. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  21940. {
  21941. if (oppositeOperatorDef->mGenericParams.IsEmpty())
  21942. {
  21943. // Fast check
  21944. auto returnType = mModule->CheckOperator(checkType, oppositeOperatorDef, args[0].mTypedValue, args[1].mTypedValue);
  21945. if (returnType != NULL)
  21946. {
  21947. operatorConstraintReturnType = returnType;
  21948. methodMatcher.mBestMethodDef = oppositeOperatorDef;
  21949. methodMatcher.mBestMethodTypeInstance = checkType;
  21950. methodMatcher.mSelfType = entry.mSrcType;
  21951. if (oppositeBinaryOp != BfBinaryOp_None)
  21952. wasTransformedUsage = true;
  21953. }
  21954. }
  21955. else
  21956. {
  21957. if (methodMatcher.CheckMethod(NULL, checkType, oppositeOperatorDef, false))
  21958. {
  21959. auto rawMethodInstance = mModule->GetRawMethodInstance(checkType, oppositeOperatorDef);
  21960. auto returnType = mModule->ResolveGenericType(rawMethodInstance->mReturnType, NULL, &methodMatcher.mBestMethodGenericArguments,
  21961. mModule->mCurTypeInstance);
  21962. if (returnType != NULL)
  21963. {
  21964. operatorConstraintReturnType = returnType;
  21965. methodMatcher.mSelfType = entry.mSrcType;
  21966. if (oppositeBinaryOp != BfBinaryOp_None)
  21967. wasTransformedUsage = true;
  21968. }
  21969. }
  21970. }
  21971. }
  21972. else
  21973. {
  21974. if (methodMatcher.CheckMethod(NULL, checkType, oppositeOperatorDef, false))
  21975. {
  21976. methodMatcher.mSelfType = entry.mSrcType;
  21977. if (oppositeBinaryOp != BfBinaryOp_None)
  21978. wasTransformedUsage = true;
  21979. }
  21980. }
  21981. }
  21982. }
  21983. }
  21984. bool hadMatch = (methodMatcher.mBestMethodDef != NULL);
  21985. if ((methodMatcher.mBestMethodDef != NULL) && ((flags & BfBinOpFlag_IgnoreOperatorWithWrongResult) != 0))
  21986. {
  21987. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  21988. methodMatcher.mBestMethodInstance = GetSelectedMethod(methodMatcher.mTargetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  21989. if ((methodMatcher.mBestMethodInstance.mMethodInstance->mReturnType != mExpectingType) &&
  21990. ((matchedOp == binaryOp) || (matchedOp == oppositeBinaryOp)))
  21991. {
  21992. if (binaryOp == BfBinaryOp_Equality)
  21993. binaryOp = BfBinaryOp_StrictEquality;
  21994. if (binaryOp == BfBinaryOp_InEquality)
  21995. binaryOp = BfBinaryOp_StrictEquality;
  21996. hadMatch = false;
  21997. break;
  21998. }
  21999. }
  22000. if (hadMatch)
  22001. {
  22002. methodMatcher.FlushAmbiguityError();
  22003. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  22004. bool invertResult = matchedOp == oppositeBinaryOp;
  22005. auto methodDef = methodMatcher.mBestMethodDef;
  22006. auto autoComplete = GetAutoComplete();
  22007. bool wasCapturingMethodInfo = false;
  22008. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  22009. {
  22010. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  22011. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  22012. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  22013. }
  22014. if ((wasTransformedUsage) && (methodDef->mCommutableKind != BfCommutableKind_Operator))
  22015. {
  22016. auto error = mModule->Warn(BfWarning_BF4206_OperatorCommutableUsage, "Transformed operator usage requires 'Commutable' attribute to be added to the operator declaration", opToken);
  22017. if ((error != NULL) && (methodDef->GetRefNode() != NULL))
  22018. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See operator declaration"), methodDef->GetRefNode());
  22019. }
  22020. if (opToken != NULL)
  22021. {
  22022. if ((opToken->IsA<BfTokenNode>()) && (!noClassify) && (!baseClassWalker.mMayBeFromInterface))
  22023. mModule->SetElementType(opToken, BfSourceElementType_Method);
  22024. }
  22025. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  22026. {
  22027. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), operatorConstraintReturnType);
  22028. }
  22029. else
  22030. {
  22031. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  22032. mResult = CreateCall(&methodMatcher, BfTypedValue());
  22033. }
  22034. if ((mResult.mType != NULL) && (methodMatcher.mSelfType != NULL) && (mResult.mType->IsSelf()))
  22035. {
  22036. BF_ASSERT(mModule->IsInGeneric());
  22037. mResult = mModule->GetDefaultTypedValue(methodMatcher.mSelfType, false, BfDefaultValueKind_Value);
  22038. }
  22039. if ((invertResult) && (mResult.mType == mModule->GetPrimitiveType(BfTypeCode_Boolean)))
  22040. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  22041. if (pass == 1)
  22042. {
  22043. if (findBinaryOp == BfBinaryOp_Compare)
  22044. {
  22045. mResult = mModule->LoadValue(mResult);
  22046. if (mResult.mType->IsIntegral())
  22047. mResult.mValue = mModule->mBfIRBuilder->CreateNeg(mResult.mValue);
  22048. }
  22049. }
  22050. if ((isComparison) && (matchedOp == BfBinaryOp_Compare))
  22051. {
  22052. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  22053. mResult = mModule->LoadValue(mResult);
  22054. if (mResult.mType != intType)
  22055. mResult = mModule->GetDefaultTypedValue(intType);
  22056. auto zeroVal = mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  22057. auto useBinaryOp = binaryOp;
  22058. if (pass == 1)
  22059. useBinaryOp = BfGetFlippedBinaryOp(useBinaryOp);
  22060. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  22061. switch (useBinaryOp)
  22062. {
  22063. case BfBinaryOp_Equality:
  22064. case BfBinaryOp_StrictEquality:
  22065. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mResult.mValue, zeroVal), boolType);
  22066. break;
  22067. case BfBinaryOp_InEquality:
  22068. case BfBinaryOp_StrictInEquality:
  22069. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mResult.mValue, zeroVal), boolType);
  22070. break;
  22071. case BfBinaryOp_GreaterThan:
  22072. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(mResult.mValue, zeroVal, true), boolType);
  22073. break;
  22074. case BfBinaryOp_LessThan:
  22075. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(mResult.mValue, zeroVal, true), boolType);
  22076. break;
  22077. case BfBinaryOp_GreaterThanOrEqual:
  22078. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(mResult.mValue, zeroVal, true), boolType);
  22079. break;
  22080. case BfBinaryOp_LessThanOrEqual:
  22081. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(mResult.mValue, zeroVal, true), boolType);
  22082. break;
  22083. default: break;
  22084. }
  22085. }
  22086. return;
  22087. }
  22088. auto _CheckBinaryOp = [&](BfGenericParamInstance* genericParam)
  22089. {
  22090. for (auto& opConstraint : genericParam->mOperatorConstraints)
  22091. {
  22092. BfType* returnType = genericParam->mExternType;
  22093. bool works = false;
  22094. if (opConstraint.mBinaryOp == findBinaryOp)
  22095. {
  22096. if (((args[0].mTypedValue) && (mModule->CanCast(args[0].mTypedValue, opConstraint.mLeftType))) &&
  22097. ((args[1].mTypedValue) && (mModule->CanCast(args[1].mTypedValue, opConstraint.mRightType))))
  22098. {
  22099. works = true;
  22100. }
  22101. }
  22102. if ((isComparison) && (opConstraint.mBinaryOp == BfBinaryOp_Compare))
  22103. {
  22104. if (((args[0].mTypedValue) && (mModule->CanCast(args[0].mTypedValue, opConstraint.mLeftType))) &&
  22105. ((args[1].mTypedValue) && (mModule->CanCast(args[1].mTypedValue, opConstraint.mRightType))))
  22106. {
  22107. works = true;
  22108. }
  22109. else if (((args[0].mTypedValue) && (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType))) &&
  22110. ((args[1].mTypedValue) && (mModule->CanCast(args[1].mTypedValue, opConstraint.mLeftType))))
  22111. {
  22112. works = true;
  22113. }
  22114. if (works)
  22115. {
  22116. returnType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  22117. }
  22118. }
  22119. if (works)
  22120. {
  22121. BF_ASSERT(genericParam->mExternType != NULL);
  22122. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  22123. return true;
  22124. }
  22125. }
  22126. return false;
  22127. };
  22128. // Check method generic constraints
  22129. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  22130. {
  22131. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  22132. {
  22133. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  22134. if (_CheckBinaryOp(genericParam))
  22135. return;
  22136. }
  22137. }
  22138. // Check type generic constraints
  22139. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  22140. {
  22141. SizedArray<BfGenericParamInstance*, 4> genericParams;
  22142. mModule->GetActiveTypeGenericParamInstances(genericParams);
  22143. for (auto genericParam : genericParams)
  22144. {
  22145. if (_CheckBinaryOp(genericParam))
  22146. return;
  22147. }
  22148. }
  22149. if (pass == 1)
  22150. break;
  22151. auto flippedBinaryOp = BfGetFlippedBinaryOp(findBinaryOp);
  22152. if (flippedBinaryOp != BfBinaryOp_None)
  22153. findBinaryOp = flippedBinaryOp;
  22154. }
  22155. bool resultHandled = false;
  22156. if (((origLeftType != NULL) && (origLeftType->IsIntUnknown())) ||
  22157. ((origRightType != NULL) && (origRightType->IsIntUnknown())))
  22158. {
  22159. if (!resultType->IsPrimitiveType())
  22160. {
  22161. BfType* numericCastType = mModule->GetClosestNumericCastType(*resultTypedValue, mExpectingType);
  22162. if (numericCastType != NULL)
  22163. {
  22164. resultHandled = true;
  22165. resultType = numericCastType;
  22166. }
  22167. }
  22168. }
  22169. if (!resultHandled)
  22170. {
  22171. auto prevResultType = resultType;
  22172. if ((leftValue.mType->IsPrimitiveType()) && (!origLeftType->IsIntUnknown()) && (!rightValue.mType->IsTypedPrimitive()))
  22173. resultType = leftValue.mType;
  22174. if ((rightValue.mType->IsPrimitiveType()) && (!origRightType->IsIntUnknown()) && (!leftValue.mType->IsTypedPrimitive()))
  22175. resultType = rightValue.mType;
  22176. }
  22177. }
  22178. }
  22179. if (deferRight)
  22180. {
  22181. auto expectedType = resultType;
  22182. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  22183. expectedType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  22184. rightValue = mModule->CreateValueFromExpression(BfNodeDynCast<BfExpression>(rightExpression), expectedType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  22185. if (rightValue)
  22186. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, (BfBinOpFlags)(flags & ~BfBinOpFlag_DeferRight), leftValue, rightValue);
  22187. return;
  22188. }
  22189. if (mModule->IsUnboundGeneric(resultType))
  22190. {
  22191. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  22192. return;
  22193. }
  22194. if (resultType->IsPointer() && otherType->IsPointer())
  22195. {
  22196. if ((binaryOp == BfBinaryOp_Add) && (resultType == otherType) &&
  22197. (resultType->GetUnderlyingType() == mModule->GetPrimitiveType(BfTypeCode_Char8)))
  22198. {
  22199. AddStrings(leftValue, rightValue, opToken);
  22200. return;
  22201. }
  22202. //TODO: Allow all pointer comparisons, but only allow SUBTRACTION between equal pointer types
  22203. if ((binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowSubtract))
  22204. {
  22205. if (!mModule->CanCast(*otherTypedValue, resultType))
  22206. {
  22207. mModule->Fail(StrFormat("Operands '%s' and '%s' are not comparable types.",
  22208. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()),
  22209. opToken);
  22210. return;
  22211. }
  22212. BfPointerType* resultPointerType = (BfPointerType*)resultType;
  22213. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  22214. if (resultPointerType->mElementType->mSize == 0)
  22215. {
  22216. if (!mModule->IsInSpecializedSection())
  22217. mModule->Warn(0, "Subtracting pointers to zero-sized elements will always result in zero", opToken);
  22218. mResult = mModule->GetDefaultTypedValue(intPtrType);
  22219. }
  22220. else
  22221. {
  22222. convLeftValue = mModule->CastToValue(leftExpression, leftValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  22223. convRightValue = mModule->CastToValue(rightExpression, rightValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  22224. BfIRValue diffValue = mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue);
  22225. diffValue = mModule->mBfIRBuilder->CreateDiv(diffValue, mModule->GetConstValue(resultPointerType->mElementType->GetStride(), intPtrType), true);
  22226. mResult = BfTypedValue(diffValue, intPtrType);
  22227. }
  22228. return;
  22229. }
  22230. else if ((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_StrictEquality) &&
  22231. (binaryOp != BfBinaryOp_InEquality) && (binaryOp != BfBinaryOp_StrictInEquality) &&
  22232. (binaryOp != BfBinaryOp_LessThan) && (binaryOp != BfBinaryOp_LessThanOrEqual) &&
  22233. (binaryOp != BfBinaryOp_GreaterThan) && (binaryOp != BfBinaryOp_GreaterThanOrEqual))
  22234. {
  22235. if (mModule->PreFail())
  22236. mModule->Fail("Invalid operation on pointers", opToken);
  22237. return;
  22238. }
  22239. if ((!BfBinOpEqualityCheck(binaryOp)) || (resultType != otherType))
  22240. {
  22241. resultType = mModule->GetPrimitiveType(BfTypeCode_UIntPtr);
  22242. explicitCast = true;
  22243. }
  22244. }
  22245. else if (resultType->IsPointer())
  22246. {
  22247. if (otherType->IsNull())
  22248. {
  22249. if (!BfBinOpEqualityCheck(binaryOp))
  22250. {
  22251. if (mModule->PreFail())
  22252. mModule->Fail(StrFormat("Invalid operation between '%s' and null", mModule->TypeToString(resultType).c_str()), opToken);
  22253. return;
  22254. }
  22255. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  22256. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22257. else
  22258. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22259. return;
  22260. }
  22261. // One pointer
  22262. if ((!otherType->IsIntegral()) ||
  22263. ((binaryOp != BfBinaryOp_Add) && (binaryOp != BfBinaryOp_Subtract) && (binaryOp != BfBinaryOp_OverflowAdd) && (binaryOp != BfBinaryOp_OverflowSubtract)))
  22264. {
  22265. _OpFail();
  22266. return;
  22267. }
  22268. auto underlyingType = resultType->GetUnderlyingType();
  22269. if ((underlyingType->IsSizedArray()) && (!mModule->IsInSpecializedSection()))
  22270. mModule->Warn(0, "Performing arithmetic on a pointer to a sized array. Consider performing arithmetic on an element pointer if this is not intended.", resultTypeSrc);
  22271. BfIRValue addValue = otherTypedValue->mValue;
  22272. if ((!otherTypedValue->mType->IsSigned()) && (otherTypedValue->mType->mSize < mModule->mSystem->mPtrSize))
  22273. addValue = mModule->mBfIRBuilder->CreateNumericCast(addValue, false, BfTypeCode_UIntPtr);
  22274. if ((binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowSubtract))
  22275. {
  22276. if (resultTypeSrc == rightExpression)
  22277. mModule->Fail("Cannot subtract a pointer from an integer", resultTypeSrc);
  22278. addValue = mModule->mBfIRBuilder->CreateNeg(addValue);
  22279. }
  22280. mModule->PopulateType(underlyingType);
  22281. if (underlyingType->IsValuelessType())
  22282. {
  22283. if (!mModule->IsInSpecializedSection())
  22284. mModule->Warn(0, "Adding to a pointer to a zero-sized element has no effect", opToken);
  22285. mResult = *resultTypedValue;
  22286. return;
  22287. }
  22288. mModule->mBfIRBuilder->PopulateType(underlyingType);
  22289. mResult = BfTypedValue(mModule->CreateIndexedValue(underlyingType, resultTypedValue->mValue, addValue), resultType);
  22290. return;
  22291. }
  22292. if ((resultType->IsFunction()) || (resultType->IsPointer()) || (resultType->IsObject()) || (resultType->IsInterface()) || (resultType->IsGenericParam()))
  22293. {
  22294. if ((binaryOp == BfBinaryOp_Add) &&
  22295. (resultType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)) &&
  22296. (otherType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  22297. {
  22298. AddStrings(leftValue, rightValue, opToken);
  22299. return;
  22300. }
  22301. if (!BfGetBinaryOpPrecendence(binaryOp))
  22302. {
  22303. //mModule->Fail("Invalid operation for objects", opToken);
  22304. _OpFail();
  22305. return;
  22306. }
  22307. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  22308. {
  22309. leftValue = mModule->LoadOrAggregateValue(leftValue);
  22310. rightValue = mModule->LoadOrAggregateValue(rightValue);
  22311. if (resultType->IsInterface())
  22312. {
  22313. // Compare as objects instead
  22314. resultType = mModule->mContext->mBfObjectType;
  22315. *resultTypedValue = mModule->Cast(resultTypeSrc, *resultTypedValue, resultType);
  22316. }
  22317. if (otherType->IsNull())
  22318. {
  22319. if (resultType->IsFunction())
  22320. {
  22321. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  22322. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22323. else
  22324. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22325. }
  22326. else
  22327. {
  22328. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  22329. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22330. else
  22331. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22332. }
  22333. }
  22334. else
  22335. {
  22336. auto convertedValue = mModule->Cast(otherTypeSrc, *otherTypedValue, resultType, BfCastFlags_NoBox);
  22337. if (!convertedValue)
  22338. return;
  22339. convertedValue = mModule->LoadValue(convertedValue);
  22340. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  22341. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(resultTypedValue->mValue, convertedValue.mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22342. else
  22343. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(resultTypedValue->mValue, convertedValue.mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22344. }
  22345. return;
  22346. }
  22347. }
  22348. if (resultType->IsTypedPrimitive())
  22349. {
  22350. bool needsOtherCast = true;
  22351. if (otherType != resultType)
  22352. {
  22353. if ((otherType->IsPrimitiveType()) && (!otherType->IsValuelessType()))
  22354. {
  22355. // Allow zero comparisons to match all typed primitives
  22356. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  22357. {
  22358. auto constant = mModule->mBfIRBuilder->GetConstant(otherTypedValue->mValue);
  22359. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 == 0))
  22360. needsOtherCast = false;
  22361. }
  22362. // Allow integer offsetting
  22363. if ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowAdd) || (binaryOp == BfBinaryOp_OverflowSubtract))
  22364. {
  22365. if (otherType->IsIntegral())
  22366. needsOtherCast = false;
  22367. }
  22368. }
  22369. if (needsOtherCast)
  22370. {
  22371. BfCastFlags castFlags = (BfCastFlags)((explicitCast ? BfCastFlags_Explicit : BfCastFlags_None) | BfCastFlags_SilentFail);
  22372. BfIRValue otherCastResult = mModule->CastToValue(otherTypeSrc, *otherTypedValue, resultType, castFlags);
  22373. if (!otherCastResult)
  22374. {
  22375. // We picked the wrong type, try the other one...
  22376. if (mModule->CanCast(*resultTypedValue, otherType))
  22377. {
  22378. BfBinOpFlags newFlags = flags;
  22379. if (otherTypedValue == &leftValue)
  22380. newFlags = (BfBinOpFlags)(flags | BfBinOpFlag_ForceLeftType & ~BfBinOpFlag_ForceRightType & ~BfBinOpFlag_DeferRight);
  22381. else
  22382. newFlags = (BfBinOpFlags)(flags | BfBinOpFlag_ForceRightType & ~BfBinOpFlag_ForceLeftType & ~BfBinOpFlag_DeferRight);
  22383. return PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, newFlags, leftValue, rightValue);
  22384. }
  22385. // Do again but with an error
  22386. castFlags = (BfCastFlags)(castFlags & ~BfCastFlags_SilentFail);
  22387. otherCastResult = mModule->CastToValue(otherTypeSrc, *otherTypedValue, resultType, castFlags);
  22388. }
  22389. }
  22390. }
  22391. auto underlyingType = resultType->GetUnderlyingType();
  22392. if ((binaryOp == BfBinaryOp_Subtract) && (otherTypedValue->mType == resultType))
  22393. {
  22394. intptr maxDist = 0;
  22395. auto resultTypeInstance = resultType->ToTypeInstance();
  22396. if ((resultTypeInstance != NULL) && (resultTypeInstance->mTypeInfoEx != NULL))
  22397. maxDist = resultTypeInstance->mTypeInfoEx->mMaxValue - resultTypeInstance->mTypeInfoEx->mMinValue;
  22398. if (maxDist >= 0x80000000UL)
  22399. resultType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  22400. else if (maxDist >= 0x8000)
  22401. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  22402. else if (maxDist >= 0x80)
  22403. resultType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  22404. else
  22405. resultType = mModule->GetPrimitiveType(BfTypeCode_Int8);
  22406. underlyingType = resultType;
  22407. }
  22408. BfIRValue convResultValue;
  22409. if (resultTypedValue->mType == resultType)
  22410. convResultValue = mModule->LoadValue(*resultTypedValue).mValue;
  22411. else
  22412. convResultValue = mModule->CastToValue(resultTypeSrc, *resultTypedValue, underlyingType, BfCastFlags_Explicit);
  22413. BfIRValue convOtherValue;
  22414. if (otherTypedValue->mType == resultType)
  22415. convOtherValue = mModule->LoadValue(*otherTypedValue).mValue;
  22416. else
  22417. convOtherValue = mModule->CastToValue(otherTypeSrc, *otherTypedValue, underlyingType, BfCastFlags_Explicit);
  22418. if ((!underlyingType->IsValuelessType()) && ((!convResultValue) || (!convOtherValue)))
  22419. return;
  22420. if (resultTypedValue == &leftValue)
  22421. PerformBinaryOperation(underlyingType, convResultValue, convOtherValue, binaryOp, opToken);
  22422. else
  22423. PerformBinaryOperation(underlyingType, convOtherValue, convResultValue, binaryOp, opToken);
  22424. if (mResult.mType == underlyingType)
  22425. mResult.mType = resultType;
  22426. return;
  22427. }
  22428. auto _CallValueTypeEquals = [&]()
  22429. {
  22430. BfModuleMethodInstance moduleMethodInstance;
  22431. auto typeInst = leftValue.mType->ToTypeInstance();
  22432. if (typeInst != NULL)
  22433. {
  22434. if ((binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  22435. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_STRICT_EQUALS);
  22436. else
  22437. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_EQUALS);
  22438. }
  22439. else
  22440. {
  22441. BF_ASSERT(leftValue.mType->IsSizedArray() || leftValue.mType->IsMethodRef());
  22442. auto valueTypeInst = mModule->ResolveTypeDef(mModule->mCompiler->mValueTypeTypeDef)->ToTypeInstance();
  22443. BfMethodDef* equalsMethodDef = mModule->mCompiler->mValueTypeTypeDef->GetMethodByName("Equals");
  22444. BfTypeVector typeVec;
  22445. typeVec.push_back(leftValue.mType);
  22446. moduleMethodInstance = mModule->GetMethodInstance(valueTypeInst, equalsMethodDef, typeVec);
  22447. }
  22448. if (moduleMethodInstance)
  22449. {
  22450. if ((opToken != NULL) && (!noClassify))
  22451. mModule->SetElementType(opToken, BfSourceElementType_Method);
  22452. SizedArray<BfResolvedArg, 4> argValues;
  22453. BfResolvedArg resolvedArg;
  22454. resolvedArg.mTypedValue = leftValue;
  22455. argValues.push_back(resolvedArg);
  22456. resolvedArg.mTypedValue = rightValue;
  22457. argValues.push_back(resolvedArg);
  22458. mResult = CreateCall(opToken, BfTypedValue(), BfTypedValue(), moduleMethodInstance.mMethodInstance->mMethodDef, moduleMethodInstance, BfCreateCallFlags_None, argValues);
  22459. if ((mResult) &&
  22460. ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality)))
  22461. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  22462. return true;
  22463. }
  22464. return false;
  22465. };
  22466. //if (((leftValue.mType->IsComposite()) || (leftValue.mType->IsObject())))
  22467. if (((resultType->IsComposite()) || (resultType->IsObject())))
  22468. {
  22469. bool areEquivalentTuples = false;
  22470. if ((leftValue.mType->IsTuple()) && (rightValue.mType->IsTuple()))
  22471. {
  22472. auto leftTupleType = (BfTypeInstance*)leftValue.mType;
  22473. auto rightTupleType = (BfTypeInstance*)rightValue.mType;
  22474. // We only do this for tuples, because we would allow an implicit struct
  22475. // truncation if we allow it for all structs, which would result in only
  22476. // the base class's fields being compared
  22477. if (mModule->CanCast(rightValue, leftValue.mType))
  22478. rightValue = mModule->Cast(opToken, rightValue, leftValue.mType, BfCastFlags_Explicit);
  22479. else if (mModule->CanCast(leftValue, rightValue.mType))
  22480. leftValue = mModule->Cast(opToken, leftValue, rightValue.mType, BfCastFlags_Explicit);
  22481. }
  22482. if (leftValue.mType == rightValue.mType)
  22483. {
  22484. if (BfBinOpEqualityCheck(binaryOp))
  22485. {
  22486. auto intCoercibleType = mModule->GetIntCoercibleType(leftValue.mType);
  22487. if (intCoercibleType != NULL)
  22488. {
  22489. auto intLHS = mModule->GetIntCoercible(leftValue);
  22490. auto intRHS = mModule->GetIntCoercible(rightValue);
  22491. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  22492. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  22493. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(intLHS.mValue, intRHS.mValue), boolType);
  22494. else
  22495. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(intLHS.mValue, intRHS.mValue), boolType);
  22496. return;
  22497. }
  22498. // Valueless types always compare as 'equal' if we can ensure no members could have an equality operator overload
  22499. if (leftValue.mType->IsComposite())
  22500. {
  22501. mModule->PopulateType(leftValue.mType);
  22502. if (leftValue.mType->IsValuelessType())
  22503. {
  22504. bool mayHaveEqualOverload = false;
  22505. auto leftTypeInst = leftValue.mType->ToTypeInstance();
  22506. if (leftTypeInst != NULL)
  22507. {
  22508. std::function<bool(BfType*)> _HasTypeInstance = [&](BfType* type)
  22509. {
  22510. if (type == NULL)
  22511. return false;
  22512. if (type->IsTypeInstance())
  22513. return true;
  22514. if (type->IsSizedArray())
  22515. return _HasTypeInstance(((BfSizedArrayType*)type)->mElementType);
  22516. return false;
  22517. };
  22518. for (auto& fieldInstance : leftTypeInst->mFieldInstances)
  22519. {
  22520. if (_HasTypeInstance(fieldInstance.mResolvedType))
  22521. mayHaveEqualOverload = true;
  22522. }
  22523. }
  22524. if (!mayHaveEqualOverload)
  22525. {
  22526. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  22527. bool isEqual = (binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality);
  22528. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  22529. return;
  22530. }
  22531. }
  22532. }
  22533. if (_CallValueTypeEquals())
  22534. return;
  22535. }
  22536. if (PerformBinaryOperation_Numeric(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue))
  22537. return;
  22538. if (mModule->PreFail())
  22539. {
  22540. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s'",
  22541. BfGetOpName(binaryOp),
  22542. mModule->TypeToString(leftValue.mType).c_str()), opToken);
  22543. }
  22544. return;
  22545. }
  22546. else
  22547. {
  22548. bool handled = false;
  22549. for (int pass = 0; pass < 2; pass++)
  22550. {
  22551. BfTypedValue& fromValue = (pass == 0) ? leftValue : rightValue;
  22552. BfType* toType = (pass == 0) ? rightValue.mType : leftValue.mType;
  22553. if (mModule->CanCast(fromValue, toType))
  22554. {
  22555. auto result = mModule->Cast(opToken, fromValue, toType);
  22556. if (result)
  22557. {
  22558. resultType = toType;
  22559. fromValue = result;
  22560. handled = true;
  22561. break;
  22562. }
  22563. }
  22564. }
  22565. if (!handled)
  22566. {
  22567. if ((leftValue.mType->IsUndefSizedArray()) || (rightValue.mType->IsUndefSizedArray()))
  22568. {
  22569. if ((leftValue.mType->IsSizedArray()) && (rightValue.mType->IsSizedArray() &&
  22570. (leftValue.mType->GetUnderlyingType() == rightValue.mType->GetUnderlyingType())))
  22571. {
  22572. if (BfBinOpEqualityCheck(binaryOp))
  22573. {
  22574. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  22575. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Undef);
  22576. return;
  22577. }
  22578. }
  22579. }
  22580. if (PerformBinaryOperation_Numeric(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue))
  22581. return;
  22582. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s' and '%s'",
  22583. BfGetOpName(binaryOp),
  22584. mModule->TypeToString(leftValue.mType).c_str(),
  22585. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  22586. return;
  22587. }
  22588. }
  22589. }
  22590. if (resultType->IsMethodRef() && otherType->IsMethodRef())
  22591. {
  22592. if (BfBinOpEqualityCheck(binaryOp))
  22593. {
  22594. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  22595. BfMethodRefType* lhsMethodRefType = (BfMethodRefType*)leftValue.mType;
  22596. BfMethodRefType* rhsMethodRefType = (BfMethodRefType*)rightValue.mType;
  22597. if (lhsMethodRefType->mMethodRef != rhsMethodRefType->mMethodRef)
  22598. {
  22599. mResult = BfTypedValue(mModule->GetConstValue(((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality)) ? 0 : 1, boolType), boolType);
  22600. return;
  22601. }
  22602. if (_CallValueTypeEquals())
  22603. return;
  22604. }
  22605. }
  22606. if (resultType->IsIntegral())
  22607. {
  22608. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  22609. {
  22610. if (rightValue.mValue.IsConst())
  22611. {
  22612. auto constVal = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  22613. if ((constVal->mInt64 < 0) || (constVal->mInt64 >= 8 * resultType->mSize))
  22614. {
  22615. mModule->Fail(StrFormat("Shift value '%lld' is out of range for type '%s'", constVal->mInt64, mModule->TypeToString(resultType).c_str()), opToken);
  22616. }
  22617. }
  22618. }
  22619. // We're trying a simplified scheme that doesn't always try to up-convert into an 'int'
  22620. if (leftValue.mType != rightValue.mType)
  22621. {
  22622. bool isBitwiseExpr =
  22623. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  22624. (binaryOp == BfBinaryOp_BitwiseOr) ||
  22625. (binaryOp == BfBinaryOp_ExclusiveOr) ||
  22626. (binaryOp == BfBinaryOp_LeftShift) ||
  22627. (binaryOp == BfBinaryOp_RightShift) ||
  22628. (binaryOp == BfBinaryOp_Equality) ||
  22629. (binaryOp == BfBinaryOp_InEquality) ||
  22630. (binaryOp == BfBinaryOp_StrictEquality) ||
  22631. (binaryOp == BfBinaryOp_StrictInEquality);
  22632. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  22633. {
  22634. // For shifts we have more lenient rules - shifts are naturally limited so any int type is equally valid
  22635. if (rightValue.mType->IsIntegral())
  22636. explicitCast = true;
  22637. }
  22638. else if (((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowAdd) || (binaryOp == BfBinaryOp_OverflowSubtract)) && (resultType->IsChar()) && (otherType->IsInteger()))
  22639. {
  22640. // charVal += intVal;
  22641. explicitCast = true;
  22642. }
  22643. else if ((!resultType->IsSigned()) && (otherType->IsSigned()))
  22644. {
  22645. if (mModule->CanCast(*otherTypedValue, resultType))
  22646. {
  22647. // If we can convert the 'other' value implicitly then it's a convertible literal, leave as uint
  22648. }
  22649. else
  22650. {
  22651. mModule->Fail(StrFormat("Operator cannot be applied to operands of type '%s' and '%s'",
  22652. mModule->TypeToString(leftValue.mType).c_str(),
  22653. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  22654. return;
  22655. }
  22656. }
  22657. else if ((isBitwiseExpr) && (otherType->IsIntegral()) && (resultType->mSize == otherType->mSize))
  22658. {
  22659. // Forget about signed/unsigned mismatches for bitwise operations
  22660. explicitCast = true;
  22661. }
  22662. else
  22663. {
  22664. if (((binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowSubtract)) &&
  22665. (resultType->IsChar()) && (otherType->IsChar()))
  22666. {
  22667. // "wchar - char" subtraction will always fit into int32, because of unicode range
  22668. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  22669. explicitCast = true;
  22670. }
  22671. else if ((otherType->IsChar()) &&
  22672. ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowAdd) || (binaryOp == BfBinaryOp_OverflowSubtract)))
  22673. {
  22674. mModule->Fail(StrFormat("Cannot perform operation between types '%s' and '%s'",
  22675. mModule->TypeToString(leftValue.mType).c_str(),
  22676. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  22677. }
  22678. }
  22679. }
  22680. else if ((!resultType->IsSigned()) && (binaryOp == BfBinaryOp_Subtract) && (!forceLeftType))
  22681. {
  22682. if ((mExpectingType == NULL) || (mExpectingType->IsSigned()) || (resultType->IsChar()))
  22683. {
  22684. if ((resultType->IsChar()) && (resultType->mSize == 4))
  22685. {
  22686. // "wchar - wchar" subtraction will always fit into int32, because of unicode range
  22687. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  22688. }
  22689. else
  22690. {
  22691. // The result of uint8 - uint8 is int16 (for example)
  22692. switch (resultType->mSize)
  22693. {
  22694. case 1:
  22695. resultType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  22696. break;
  22697. case 2:
  22698. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  22699. break;
  22700. case 4:
  22701. resultType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  22702. break;
  22703. }
  22704. }
  22705. explicitCast = true;
  22706. }
  22707. }
  22708. else if (resultType->IsChar())
  22709. {
  22710. bool canDoOp =
  22711. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  22712. (binaryOp == BfBinaryOp_BitwiseOr) ||
  22713. ((binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_Compare));
  22714. if (!canDoOp)
  22715. {
  22716. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  22717. return;
  22718. }
  22719. }
  22720. }
  22721. if (!convLeftValue)
  22722. convLeftValue = mModule->CastToValue(leftExpression, leftValue, resultType,
  22723. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  22724. if (!convRightValue)
  22725. convRightValue = mModule->CastToValue(rightExpression, rightValue, resultType,
  22726. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  22727. PerformBinaryOperation(resultType, convLeftValue, convRightValue, binaryOp, opToken);
  22728. }
  22729. void BfExprEvaluator::PerformBinaryOperation(BfType* resultType, BfIRValue convLeftValue, BfIRValue convRightValue, BfBinaryOp binaryOp, BfAstNode* opToken)
  22730. {
  22731. if (resultType->IsValuelessType())
  22732. {
  22733. switch (binaryOp)
  22734. {
  22735. case BfBinaryOp_Equality:
  22736. case BfBinaryOp_StrictEquality:
  22737. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1),
  22738. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22739. return;
  22740. case BfBinaryOp_InEquality:
  22741. case BfBinaryOp_StrictInEquality:
  22742. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0),
  22743. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22744. return;
  22745. default:
  22746. break;
  22747. }
  22748. }
  22749. if ((!convLeftValue) || (!convRightValue))
  22750. return;
  22751. if (resultType->IsPrimitiveType())
  22752. {
  22753. auto primType = (BfPrimitiveType*)resultType;
  22754. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  22755. {
  22756. bool passThrough = false;
  22757. switch (binaryOp)
  22758. {
  22759. case BfBinaryOp_Equality:
  22760. case BfBinaryOp_StrictEquality:
  22761. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  22762. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22763. break;
  22764. case BfBinaryOp_InEquality:
  22765. case BfBinaryOp_StrictInEquality:
  22766. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  22767. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22768. break;
  22769. case BfBinaryOp_BitwiseAnd:
  22770. case BfBinaryOp_ConditionalAnd:
  22771. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue),
  22772. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22773. break;
  22774. case BfBinaryOp_BitwiseOr:
  22775. case BfBinaryOp_ConditionalOr:
  22776. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue),
  22777. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22778. break;
  22779. case BfBinaryOp_ExclusiveOr:
  22780. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue),
  22781. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22782. break;
  22783. case BfBinaryOp_Compare:
  22784. passThrough = true;
  22785. break;
  22786. default:
  22787. if (mModule->PreFail())
  22788. mModule->Fail("Invalid operation for booleans", opToken);
  22789. break;
  22790. }
  22791. if (!passThrough)
  22792. return;
  22793. }
  22794. }
  22795. if ((!resultType->IsIntegralOrBool()) && (!resultType->IsFloat()))
  22796. {
  22797. if (mModule->PreFail())
  22798. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  22799. return;
  22800. }
  22801. if (resultType->IsIntegral())
  22802. {
  22803. switch (binaryOp)
  22804. {
  22805. case BfBinaryOp_BitwiseAnd:
  22806. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue), resultType);
  22807. return;
  22808. case BfBinaryOp_BitwiseOr:
  22809. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue), resultType);
  22810. return;
  22811. case BfBinaryOp_ExclusiveOr:
  22812. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue), resultType);
  22813. return;
  22814. case BfBinaryOp_LeftShift:
  22815. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShl(convLeftValue, convRightValue), resultType);
  22816. mModule->CheckRangeError(resultType, opToken);
  22817. return;
  22818. case BfBinaryOp_RightShift:
  22819. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShr(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  22820. return;
  22821. default: break;
  22822. }
  22823. }
  22824. if ((resultType->IsChar()) &&
  22825. ((binaryOp == BfBinaryOp_Multiply) ||
  22826. (binaryOp == BfBinaryOp_OverflowMultiply) ||
  22827. (binaryOp == BfBinaryOp_Divide) ||
  22828. (binaryOp == BfBinaryOp_Modulus)))
  22829. {
  22830. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  22831. return;
  22832. }
  22833. auto _GetOverflowKind = [&](bool wantOverflow)
  22834. {
  22835. if (resultType->IsFloat())
  22836. return BfOverflowCheckKind_None;
  22837. if (!wantOverflow)
  22838. return BfOverflowCheckKind_None;
  22839. if (mModule->GetDefaultCheckedKind() != BfCheckedKind_Checked)
  22840. return BfOverflowCheckKind_None;
  22841. bool arithmeticChecks = mModule->mCompiler->mOptions.mArithmeticChecks;
  22842. auto typeOptions = mModule->GetTypeOptions();
  22843. if (typeOptions != NULL)
  22844. arithmeticChecks = typeOptions->Apply(arithmeticChecks, BfOptionFlags_ArithmeticCheck);
  22845. if (!arithmeticChecks)
  22846. return BfOverflowCheckKind_None;
  22847. BfOverflowCheckKind overflowCheckKind = (resultType->IsSigned()) ? BfOverflowCheckKind_Signed : BfOverflowCheckKind_Unsigned;
  22848. if (!mModule->IsOptimized())
  22849. overflowCheckKind = (BfOverflowCheckKind)(overflowCheckKind | BfOverflowCheckKind_Flag_UseAsm);
  22850. return overflowCheckKind;
  22851. };
  22852. switch (binaryOp)
  22853. {
  22854. case BfBinaryOp_Add:
  22855. case BfBinaryOp_OverflowAdd:
  22856. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAdd(convLeftValue, convRightValue, _GetOverflowKind(binaryOp == BfBinaryOp_Add)), resultType);
  22857. if (binaryOp != BfBinaryOp_OverflowAdd)
  22858. mModule->CheckRangeError(resultType, opToken);
  22859. break;
  22860. case BfBinaryOp_Subtract:
  22861. case BfBinaryOp_OverflowSubtract:
  22862. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue, _GetOverflowKind(binaryOp == BfBinaryOp_Subtract)), resultType);
  22863. if (binaryOp != BfBinaryOp_OverflowSubtract)
  22864. mModule->CheckRangeError(resultType, opToken);
  22865. break;
  22866. case BfBinaryOp_Multiply:
  22867. case BfBinaryOp_OverflowMultiply:
  22868. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateMul(convLeftValue, convRightValue, _GetOverflowKind(binaryOp == BfBinaryOp_Multiply)), resultType);
  22869. if (binaryOp != BfBinaryOp_OverflowMultiply)
  22870. mModule->CheckRangeError(resultType, opToken);
  22871. break;
  22872. case BfBinaryOp_Divide:
  22873. {
  22874. bool isZero = false;
  22875. if (convRightValue.IsConst())
  22876. {
  22877. auto constVal = mModule->mBfIRBuilder->GetConstant(convRightValue);
  22878. if (BfIRBuilder::IsInt(constVal->mTypeCode))
  22879. isZero = constVal->mInt64 == 0;
  22880. }
  22881. if (isZero)
  22882. {
  22883. mModule->Fail("Divide by zero", opToken);
  22884. mResult = mModule->GetDefaultTypedValue(resultType);
  22885. }
  22886. else
  22887. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateDiv(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  22888. }
  22889. break;
  22890. case BfBinaryOp_Modulus:
  22891. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateRem(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  22892. break;
  22893. case BfBinaryOp_Equality:
  22894. case BfBinaryOp_StrictEquality:
  22895. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  22896. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22897. break;
  22898. case BfBinaryOp_InEquality:
  22899. case BfBinaryOp_StrictInEquality:
  22900. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  22901. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22902. break;
  22903. case BfBinaryOp_LessThan:
  22904. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned()),
  22905. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22906. break;
  22907. case BfBinaryOp_LessThanOrEqual:
  22908. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(convLeftValue, convRightValue, resultType->IsSigned()),
  22909. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22910. break;
  22911. case BfBinaryOp_GreaterThan:
  22912. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned()),
  22913. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22914. break;
  22915. case BfBinaryOp_GreaterThanOrEqual:
  22916. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(convLeftValue, convRightValue, resultType->IsSigned()),
  22917. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22918. break;
  22919. case BfBinaryOp_Compare:
  22920. {
  22921. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  22922. if ((convLeftValue.IsConst()) && (convRightValue.IsConst()))
  22923. {
  22924. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned());
  22925. auto ltConstant = mModule->mBfIRBuilder->GetConstant(cmpLtVal);
  22926. if (ltConstant->mBool)
  22927. {
  22928. mResult = BfTypedValue(mModule->GetConstValue(-1, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  22929. }
  22930. else
  22931. {
  22932. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned());
  22933. auto rtConstant = mModule->mBfIRBuilder->GetConstant(cmpGtVal);
  22934. if (rtConstant->mBool)
  22935. mResult = BfTypedValue(mModule->GetConstValue(1, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  22936. else
  22937. mResult = BfTypedValue(mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  22938. }
  22939. }
  22940. else if ((resultType->IsIntegralOrBool()) && (resultType->mSize < intType->mSize))
  22941. {
  22942. auto leftIntValue = mModule->mBfIRBuilder->CreateNumericCast(convLeftValue, resultType->IsSigned(), BfTypeCode_IntPtr);
  22943. auto rightIntValue = mModule->mBfIRBuilder->CreateNumericCast(convRightValue, resultType->IsSigned(), BfTypeCode_IntPtr);
  22944. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(leftIntValue, rightIntValue), intType);
  22945. }
  22946. else
  22947. {
  22948. BfIRBlock checkGtBlock = mModule->mBfIRBuilder->CreateBlock("cmpCheckGt");
  22949. BfIRBlock eqBlock = mModule->mBfIRBuilder->CreateBlock("cmpEq");
  22950. BfIRBlock endBlock = mModule->mBfIRBuilder->CreateBlock("cmpEnd");
  22951. auto startBlock = mModule->mBfIRBuilder->GetInsertBlock();
  22952. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned());
  22953. mModule->mBfIRBuilder->CreateCondBr(cmpLtVal, endBlock, checkGtBlock);
  22954. mModule->mBfIRBuilder->AddBlock(checkGtBlock);
  22955. mModule->mBfIRBuilder->SetInsertPoint(checkGtBlock);
  22956. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned());
  22957. mModule->mBfIRBuilder->CreateCondBr(cmpGtVal, endBlock, eqBlock);
  22958. mModule->mBfIRBuilder->AddBlock(eqBlock);
  22959. mModule->mBfIRBuilder->SetInsertPoint(eqBlock);
  22960. mModule->mBfIRBuilder->CreateBr(endBlock);
  22961. mModule->mBfIRBuilder->AddBlock(endBlock);
  22962. mModule->mBfIRBuilder->SetInsertPoint(endBlock);
  22963. auto phiVal = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(intType), 3);
  22964. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, -1), startBlock);
  22965. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), checkGtBlock);
  22966. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), eqBlock);
  22967. mResult = BfTypedValue(phiVal, intType);
  22968. }
  22969. }
  22970. break;
  22971. default:
  22972. if (mModule->PreFail())
  22973. mModule->Fail("Invalid operation", opToken);
  22974. break;
  22975. }
  22976. }
  22977. void BfExprEvaluator::Visit(BfBinaryOperatorExpression* binOpExpr)
  22978. {
  22979. BfAutoParentNodeEntry autoParentNodeEntry(mModule, binOpExpr);
  22980. // There are a few binary operations that could actually be casts followed by an unary operation
  22981. // We can't determine that until we know whether the identifier in the parens is a typename or not
  22982. // (double)-1.0 (intptr)&val (BaseStruct)*val
  22983. BfUnaryOp unaryOp = BfUnaryOp_None;
  22984. switch (binOpExpr->mOp)
  22985. {
  22986. case BfBinaryOp_Add: unaryOp = BfUnaryOp_Positive; break;
  22987. case BfBinaryOp_Subtract: unaryOp = BfUnaryOp_Negate; break;
  22988. case BfBinaryOp_Multiply: unaryOp = BfUnaryOp_Dereference; break;
  22989. case BfBinaryOp_BitwiseAnd: unaryOp = BfUnaryOp_AddressOf; break;
  22990. default: break;
  22991. }
  22992. if (unaryOp != BfUnaryOp_None)
  22993. {
  22994. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(binOpExpr->mLeft))
  22995. {
  22996. if (auto castTypeExpr = BfNodeDynCast<BfIdentifierNode>(parenExpr->mExpression))
  22997. {
  22998. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  22999. auto resolvedType = mModule->ResolveTypeRef(castTypeExpr, NULL);
  23000. prevIgnoreError.Restore();
  23001. if (resolvedType != NULL)
  23002. {
  23003. if (auto rightBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>(binOpExpr->mRight))
  23004. {
  23005. int leftPrecedence = BfGetBinaryOpPrecendence(binOpExpr->mOp);
  23006. int rightPrecedence = BfGetBinaryOpPrecendence(rightBinOpExpr->mOp);
  23007. // Do we have a precedence order issue due to mis-parsing this?
  23008. // An example is: "(int)-5.5 * 10"
  23009. if (rightPrecedence > leftPrecedence)
  23010. {
  23011. mModule->FailAfter("Cast target must be wrapped in parentheses", binOpExpr->mLeft);
  23012. }
  23013. }
  23014. PerformUnaryOperation(binOpExpr->mRight, unaryOp, binOpExpr->mOpToken, BfUnaryOpFlag_None);
  23015. if (mResult)
  23016. {
  23017. mResult = mModule->LoadValue(mResult);
  23018. mResult = mModule->Cast(binOpExpr, mResult, resolvedType, BfCastFlags_Explicit);
  23019. }
  23020. return;
  23021. }
  23022. }
  23023. }
  23024. }
  23025. if ((binOpExpr->mOp == BfBinaryOp_LeftShift) || (binOpExpr->mOp == BfBinaryOp_RightShift) ||
  23026. (binOpExpr->mOp == BfBinaryOp_BitwiseAnd) || (binOpExpr->mOp == BfBinaryOp_BitwiseOr) ||
  23027. (binOpExpr->mOp == BfBinaryOp_ExclusiveOr))
  23028. {
  23029. for (int side = 0; side < 2; side++)
  23030. {
  23031. if (auto innerBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>((side == 0) ? binOpExpr->mLeft : binOpExpr->mRight))
  23032. {
  23033. if ((innerBinOpExpr->mOp == BfBinaryOp_Add) || (innerBinOpExpr->mOp == BfBinaryOp_Subtract))
  23034. {
  23035. mModule->Warn(BfWarning_C4554_PossiblePrecedenceError, "Check operator precedence for possible error. Consider using parentheses to clarify precedence", innerBinOpExpr);
  23036. }
  23037. }
  23038. }
  23039. }
  23040. if (binOpExpr->mRight == NULL)
  23041. {
  23042. // We visit the children for autocompletion only
  23043. if (binOpExpr->mLeft != NULL)
  23044. VisitChild(binOpExpr->mLeft);
  23045. if (mResult)
  23046. {
  23047. auto autoComplete = GetAutoComplete();
  23048. if (autoComplete != NULL)
  23049. autoComplete->CheckEmptyStart(binOpExpr->mOpToken, mResult.mType);
  23050. }
  23051. if (binOpExpr->mRight != NULL)
  23052. VisitChild(binOpExpr->mRight);
  23053. return;
  23054. }
  23055. PerformBinaryOperation(binOpExpr->mLeft, binOpExpr->mRight, binOpExpr->mOp, binOpExpr->mOpToken, BfBinOpFlag_None);
  23056. }