BfExprEvaluator.cpp 892 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211
  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. mDeferCallRef = NULL;
  2932. mDeferScopeAlloc = NULL;
  2933. mPrefixedAttributeState = NULL;
  2934. mResolveGenericParam = true;
  2935. mNoBind = false;
  2936. mResultLocalVar = NULL;
  2937. mResultFieldInstance = NULL;
  2938. mResultLocalVarField = 0;
  2939. mResultLocalVarFieldCount = 0;
  2940. mResultLocalVarRefNode = NULL;
  2941. mIsVolatileReference = false;
  2942. mIsHeapReference = false;
  2943. mResultIsTempComposite = false;
  2944. mAllowReadOnlyReference = false;
  2945. mInsidePendingNullable = false;
  2946. mReceivingValue = NULL;
  2947. }
  2948. BfExprEvaluator::~BfExprEvaluator()
  2949. {
  2950. }
  2951. BfAutoComplete* BfExprEvaluator::GetAutoComplete()
  2952. {
  2953. if (mModule->mCompiler->mResolvePassData == NULL)
  2954. return NULL;
  2955. if ((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) != 0)
  2956. return NULL;
  2957. // For local methods- only process autocomplete on capture phase
  2958. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  2959. return NULL;
  2960. // if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod))
  2961. // return NULL;
  2962. return mModule->mCompiler->mResolvePassData->mAutoComplete;
  2963. }
  2964. bool BfExprEvaluator::IsComptime()
  2965. {
  2966. return (mModule->mIsComptimeModule) || ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  2967. }
  2968. bool BfExprEvaluator::IsConstEval()
  2969. {
  2970. return ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  2971. }
  2972. bool BfExprEvaluator::IsComptimeEntry()
  2973. {
  2974. if (mModule->mIsComptimeModule)
  2975. return false;
  2976. return ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  2977. }
  2978. int BfExprEvaluator::GetStructRetIdx(BfMethodInstance* methodInstance, bool forceStatic)
  2979. {
  2980. if (IsComptime())
  2981. return -1;
  2982. return methodInstance->GetStructRetIdx(forceStatic);
  2983. }
  2984. BfType* BfExprEvaluator::BindGenericType(BfAstNode* node, BfType* bindType)
  2985. {
  2986. if ((mModule->mCurMethodState == NULL) || (mModule->mCurMethodInstance == NULL) || (bindType == NULL))
  2987. return bindType;
  2988. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  2989. return bindType;
  2990. if ((mBfEvalExprFlags & BfEvalExprFlags_DeclType) != 0)
  2991. return bindType;
  2992. BF_ASSERT((!mModule->mCurMethodInstance->mIsUnspecializedVariation) || (mModule->mIsComptimeModule));
  2993. auto parser = node->GetSourceData()->ToParserData();
  2994. if (parser == NULL)
  2995. return bindType;
  2996. int64 nodeId = ((int64)parser->mDataId << 32) + node->GetSrcStart();
  2997. auto genericTypeBindings = mModule->mCurMethodState->GetRootMethodState()->mGenericTypeBindings;
  2998. auto methodInstance = mModule->mCurMethodInstance;
  2999. bool isMixinBind = false;
  3000. if (mModule->mCurMethodState->mMixinState != NULL)
  3001. {
  3002. auto mixinMethodInstance = mModule->mCurMethodState->mMixinState->mMixinMethodInstance;
  3003. if (!mixinMethodInstance->mMethodDef->mGenericParams.IsEmpty())
  3004. {
  3005. auto unspecMixinMethodInstance = mModule->GetUnspecializedMethodInstance(mixinMethodInstance, false);
  3006. if (!unspecMixinMethodInstance->mHasBeenProcessed)
  3007. {
  3008. // Make sure the unspecialized method is processed so we can take its bindings
  3009. // Clear mCurMethodState so we don't think we're in a local method
  3010. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mModule->mCurMethodState, NULL);
  3011. if (unspecMixinMethodInstance->mMethodProcessRequest == NULL)
  3012. unspecMixinMethodInstance->mDeclModule->mIncompleteMethodCount++;
  3013. mModule->mContext->ProcessMethod(unspecMixinMethodInstance);
  3014. }
  3015. isMixinBind = true;
  3016. methodInstance = mixinMethodInstance;
  3017. genericTypeBindings = &unspecMixinMethodInstance->mMethodInfoEx->mGenericTypeBindings;
  3018. }
  3019. }
  3020. if ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation))
  3021. {
  3022. if (isMixinBind)
  3023. return bindType;
  3024. if (!bindType->IsGenericParam())
  3025. return bindType;
  3026. if (genericTypeBindings == NULL)
  3027. return bindType;
  3028. (*genericTypeBindings)[nodeId] = bindType;
  3029. return bindType;
  3030. }
  3031. else
  3032. {
  3033. if (genericTypeBindings == NULL)
  3034. return bindType;
  3035. BfType** typePtr = NULL;
  3036. if (genericTypeBindings->TryGetValue(nodeId, &typePtr))
  3037. return *typePtr;
  3038. return bindType;
  3039. }
  3040. }
  3041. BfType * BfExprEvaluator::ResolveTypeRef(BfTypeReference* typeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  3042. {
  3043. if (mExpectingType != NULL)
  3044. {
  3045. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(typeRef))
  3046. {
  3047. if (namedTypeRef->ToString() == "ExpectedType")
  3048. {
  3049. return mModule->ResolveTypeResult(typeRef, mExpectingType, populateType, resolveFlags);
  3050. }
  3051. }
  3052. }
  3053. return mModule->ResolveTypeRef(typeRef, populateType, resolveFlags);
  3054. }
  3055. void BfExprEvaluator::ResolveGenericType()
  3056. {
  3057. if (mResult)
  3058. {
  3059. if (mModule->IsUnboundGeneric(mResult.mType))
  3060. mResult.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  3061. //mResult.mType = mModule->ResolveGenericType(mResult.mType, true);
  3062. }
  3063. }
  3064. void BfExprEvaluator::Evaluate(BfAstNode* astNode, bool propogateNullConditional, bool ignoreNullConditional, bool allowSplat)
  3065. {
  3066. BP_ZONE("BfExprEvaluator::Evaluate");
  3067. // ParenthesizedExpression breaks null conditional chain
  3068. if (astNode->IsExact<BfParenthesizedExpression>())
  3069. propogateNullConditional = false;
  3070. bool scopeWasConditional = false;
  3071. BfPendingNullConditional* pendingNullCond = NULL;
  3072. mInsidePendingNullable = false;
  3073. if (mModule->mCurMethodState != NULL)
  3074. {
  3075. scopeWasConditional = mModule->mCurMethodState->mCurScope->mIsConditional;
  3076. pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  3077. if (!propogateNullConditional)
  3078. mModule->mCurMethodState->mPendingNullConditional = NULL;
  3079. if (pendingNullCond != NULL)
  3080. {
  3081. mInsidePendingNullable = true;
  3082. mModule->mCurMethodState->mCurScope->mIsConditional = true;
  3083. }
  3084. }
  3085. astNode->Accept(this);
  3086. GetResult();
  3087. if ((mResultIsTempComposite) && (mResult.IsAddr()))
  3088. mResult.mKind = BfTypedValueKind_TempAddr;
  3089. if ((!allowSplat) && (mResult.IsSplat()))
  3090. mResult = mModule->AggregateSplat(mResult);
  3091. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowIntUnknown) == 0)
  3092. mModule->FixIntUnknown(mResult);
  3093. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  3094. {
  3095. if (mResult.mValue.IsConst())
  3096. {
  3097. auto constant = mModule->mBfIRBuilder->GetConstant(mResult.mValue);
  3098. if (constant->mConstType == BfConstType_TypeOf)
  3099. {
  3100. auto typeOfConst = (BfTypeOf_Const*)constant;
  3101. mResult.mValue = mModule->CreateTypeDataRef(typeOfConst->mType);
  3102. }
  3103. }
  3104. }
  3105. if (mModule->mCurMethodState != NULL)
  3106. {
  3107. if (mInsidePendingNullable)
  3108. mModule->mCurMethodState->mCurScope->mIsConditional = scopeWasConditional;
  3109. if (!propogateNullConditional)
  3110. {
  3111. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  3112. mResult = mModule->FlushNullConditional(mResult, ignoreNullConditional);
  3113. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  3114. }
  3115. }
  3116. }
  3117. void BfExprEvaluator::Visit(BfErrorNode* errorNode)
  3118. {
  3119. mModule->Fail("Invalid token", errorNode);
  3120. auto autoComplete = GetAutoComplete();
  3121. if (autoComplete != NULL)
  3122. {
  3123. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(errorNode->mRefNode))
  3124. return;
  3125. autoComplete->CheckIdentifier(errorNode->mRefNode, true);
  3126. }
  3127. }
  3128. void BfExprEvaluator::Visit(BfTypeReference* typeRef)
  3129. {
  3130. mResult.mType = ResolveTypeRef(typeRef, BfPopulateType_Declaration);
  3131. }
  3132. void BfExprEvaluator::Visit(BfAttributedExpression* attribExpr)
  3133. {
  3134. BfAttributeState attributeState;
  3135. attributeState.mSrc = attribExpr->mAttributes;
  3136. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  3137. if (auto block = BfNodeDynCast<BfBlock>(attribExpr->mExpression))
  3138. attributeState.mTarget = BfAttributeTargets_Block;
  3139. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attribExpr->mAttributes, attributeState.mTarget);
  3140. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  3141. if (auto ignoreErrorsAttrib = attributeState.mCustomAttributes->Get(mModule->mCompiler->mIgnoreErrorsAttributeTypeDef))
  3142. {
  3143. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  3144. if (!ignoreErrorsAttrib->mCtorArgs.IsEmpty())
  3145. {
  3146. auto constant = mModule->mCurTypeInstance->mConstHolder->GetConstant(ignoreErrorsAttrib->mCtorArgs[0]);
  3147. if (constant->mBool)
  3148. attributeState.mFlags = BfAttributeState::Flag_StopOnError;
  3149. }
  3150. VisitChild(attribExpr->mExpression);
  3151. attributeState.mUsed = true;
  3152. if ((!mResult) ||
  3153. ((mResult) && (mResult.mType->IsVar())))
  3154. {
  3155. if (!mResult)
  3156. mModule->Fail("Expression did not result in a value", attribExpr->mExpression);
  3157. // Make empty or 'var' resolve as 'false' because var is only valid if we threw errors
  3158. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Boolean));
  3159. }
  3160. }
  3161. else if (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mConstSkipAttributeTypeDef))
  3162. {
  3163. if ((mModule->mCurMethodState == NULL) || (mModule->mCurMethodState->mCurScope == NULL) || (!mModule->mCurMethodState->mCurScope->mInConstIgnore))
  3164. {
  3165. VisitChild(attribExpr->mExpression);
  3166. }
  3167. else
  3168. {
  3169. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  3170. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  3171. }
  3172. attributeState.mUsed = true;
  3173. }
  3174. else
  3175. {
  3176. VisitChild(attribExpr->mExpression);
  3177. }
  3178. mModule->FinishAttributeState(&attributeState);
  3179. }
  3180. void BfExprEvaluator::Visit(BfNamedExpression* namedExpr)
  3181. {
  3182. if (namedExpr->mExpression != NULL)
  3183. VisitChild(namedExpr->mExpression);
  3184. }
  3185. void BfExprEvaluator::Visit(BfBlock* blockExpr)
  3186. {
  3187. if (mModule->mCurMethodState == NULL)
  3188. {
  3189. mModule->Fail("Illegal use of block expression", blockExpr);
  3190. return;
  3191. }
  3192. auto autoComplete = GetAutoComplete();
  3193. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(blockExpr)))
  3194. {
  3195. // Don't show outer method match info when our cursor is inside a block (being passed as a parameter)
  3196. autoComplete->RemoveMethodMatchInfo();
  3197. }
  3198. if (blockExpr->mChildArr.IsEmpty())
  3199. {
  3200. mModule->Fail("An empty block cannot be used as an expression", blockExpr);
  3201. return;
  3202. }
  3203. bool lastWasResultExpr = false;
  3204. if (auto lastExpr = BfNodeDynCast<BfExpressionStatement>(blockExpr->mChildArr.GetLast()))
  3205. {
  3206. if (!lastExpr->IsMissingSemicolon())
  3207. mModule->Fail("Expression blocks must end in an expression which is missing its terminating semicolon", lastExpr->mTrailingSemicolon);
  3208. }
  3209. else if (blockExpr->mChildArr.GetLast()->IsExpression())
  3210. {
  3211. // Expression
  3212. }
  3213. else
  3214. {
  3215. mModule->Fail("Expression blocks must end with an expression", blockExpr);
  3216. }
  3217. mModule->VisitEmbeddedStatement(blockExpr, this, BfNodeIsA<BfUnscopedBlock>(blockExpr) ? BfEmbeddedStatementFlags_Unscoped : BfEmbeddedStatementFlags_None);
  3218. }
  3219. bool BfExprEvaluator::CheckVariableDeclaration(BfAstNode* checkNode, bool requireSimpleIfExpr, bool exprMustBeTrue, bool silentFail)
  3220. {
  3221. if (BfNodeIsA<BfUninitializedExpression>(checkNode))
  3222. return true;
  3223. BfAstNode* checkChild = checkNode;
  3224. bool childWasAndRHS = false;
  3225. bool foundIf = false;
  3226. auto parentNodeEntry = mModule->mParentNodeEntry;
  3227. if (parentNodeEntry != NULL)
  3228. {
  3229. if (BfNodeIsA<BfInvocationExpression>(parentNodeEntry->mNode))
  3230. {
  3231. checkChild = parentNodeEntry->mNode;
  3232. parentNodeEntry = parentNodeEntry->mPrev;
  3233. }
  3234. }
  3235. auto _Fail = [&](const StringImpl& errorStr, BfAstNode* node)
  3236. {
  3237. if (!silentFail)
  3238. {
  3239. auto error = mModule->Fail(errorStr, node);
  3240. if ((error != NULL) && (node != checkNode))
  3241. {
  3242. mModule->mCompiler->mPassInstance->MoreInfo("See variable declaration", checkNode);
  3243. }
  3244. }
  3245. return false;
  3246. };
  3247. while (parentNodeEntry != NULL)
  3248. {
  3249. BfAstNode* checkParent = parentNodeEntry->mNode;
  3250. if (auto binOpExpr = BfNodeDynCastExact<BfBinaryOperatorExpression>(checkParent))
  3251. {
  3252. if (binOpExpr->mOp == BfBinaryOp_ConditionalAnd)
  3253. {
  3254. // This is always okay
  3255. childWasAndRHS = (binOpExpr->mRight != NULL) && (binOpExpr->mRight->Contains(checkChild));
  3256. }
  3257. else if ((binOpExpr->mOp == BfBinaryOp_ConditionalOr) && (!exprMustBeTrue))
  3258. {
  3259. if ((binOpExpr->mRight != NULL) && (binOpExpr->mRight->Contains(checkChild)))
  3260. {
  3261. return _Fail("Conditional short-circuiting may skip variable initialization", binOpExpr->mOpToken);
  3262. }
  3263. }
  3264. else
  3265. {
  3266. if (exprMustBeTrue)
  3267. {
  3268. return _Fail("Operator cannot be used with variable initialization", binOpExpr->mOpToken);
  3269. }
  3270. }
  3271. }
  3272. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkParent))
  3273. {
  3274. // This is okay
  3275. }
  3276. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkParent))
  3277. {
  3278. if (exprMustBeTrue)
  3279. {
  3280. return _Fail("Operator cannot be used with variable initialization", unaryOp->mOpToken);
  3281. return false;
  3282. }
  3283. if (childWasAndRHS)
  3284. {
  3285. return _Fail("Operator may allow conditional short-circuiting to skip variable initialization", unaryOp->mOpToken);
  3286. }
  3287. }
  3288. else if (auto ifStmt = BfNodeDynCast<BfIfStatement>(checkParent))
  3289. {
  3290. // Done
  3291. foundIf = true;
  3292. break;
  3293. }
  3294. else
  3295. {
  3296. if (requireSimpleIfExpr)
  3297. {
  3298. return _Fail("Variable declaration expression can only be contained in simple 'if' expressions", checkNode);
  3299. }
  3300. break;
  3301. }
  3302. checkChild = parentNodeEntry->mNode;
  3303. parentNodeEntry = parentNodeEntry->mPrev;
  3304. }
  3305. return foundIf;
  3306. }
  3307. bool BfExprEvaluator::HasVariableDeclaration(BfAstNode* checkNode)
  3308. {
  3309. BfVarDeclChecker checker;
  3310. checker.VisitChild(checkNode);
  3311. return checker.mHasVarDecl;
  3312. }
  3313. void BfExprEvaluator::Visit(BfVariableDeclaration* varDecl)
  3314. {
  3315. mModule->UpdateExprSrcPos(varDecl);
  3316. if ((mModule->mCurMethodState == NULL) || (!mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations))
  3317. {
  3318. mModule->Fail("Variable declarations are not allowed in this context", varDecl);
  3319. if (varDecl->mInitializer != NULL)
  3320. {
  3321. VisitChild(varDecl->mInitializer);
  3322. }
  3323. return;
  3324. }
  3325. CheckVariableDeclaration(varDecl, true, false, false);
  3326. if (varDecl->mInitializer == NULL)
  3327. {
  3328. mModule->Fail("Variable declarations used as expressions must have an initializer", varDecl);
  3329. }
  3330. BfTupleExpression* tupleVariableDeclaration = BfNodeDynCast<BfTupleExpression>(varDecl->mNameNode);
  3331. if (tupleVariableDeclaration != NULL)
  3332. {
  3333. mModule->Fail("Tuple variable declarations cannot be used as expressions", varDecl);
  3334. mModule->HandleTupleVariableDeclaration(varDecl);
  3335. }
  3336. else
  3337. mModule->HandleVariableDeclaration(varDecl, this);
  3338. }
  3339. void BfExprEvaluator::DoCaseExpression(BfTypedValue caseValAddr, BfCaseExpression* caseExpr)
  3340. {
  3341. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  3342. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  3343. if (auto bindExpr = BfNodeDynCast<BfEnumCaseBindExpression>(caseExpr->mCaseExpression))
  3344. {
  3345. if (caseValAddr)
  3346. {
  3347. BfTypedValue enumTagVal;
  3348. if (caseValAddr.mType->IsPayloadEnum())
  3349. {
  3350. int dscrDataIdx;
  3351. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  3352. enumTagVal = BfTypedValue(mModule->ExtractValue(caseValAddr, dscrDataIdx), dscrType);
  3353. }
  3354. else
  3355. enumTagVal = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Int32));
  3356. mResult = mModule->HandleCaseBind(caseValAddr, enumTagVal, bindExpr);
  3357. return;
  3358. }
  3359. }
  3360. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  3361. bool isPayloadEnum = (caseValAddr.mType != NULL) && (caseValAddr.mType->IsPayloadEnum());
  3362. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(caseExpr->mCaseExpression);
  3363. if ((caseValAddr) &&
  3364. ((isPayloadEnum) || (tupleExpr != NULL)))
  3365. {
  3366. bool hasVariable = false;
  3367. bool hasOut = false;
  3368. bool clearOutOnMismatch = false;
  3369. if (auto invocateExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression))
  3370. {
  3371. for (auto arg : invocateExpr->mArguments)
  3372. {
  3373. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(arg))
  3374. {
  3375. hasVariable = true;
  3376. }
  3377. else if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(arg))
  3378. {
  3379. if ((unaryOpExpr->mOpToken != NULL) && (unaryOpExpr->mOpToken->mToken == BfToken_Out))
  3380. {
  3381. hasOut = true;
  3382. }
  3383. }
  3384. }
  3385. }
  3386. if (hasVariable)
  3387. {
  3388. CheckVariableDeclaration(caseExpr, false, false, false);
  3389. }
  3390. // We can avoid clearing on mismatch if we can be sure we ONLY enter the true block on a match.
  3391. // An example of requiring clearing is: if ((result case .Ok(out val)) || (force))
  3392. if (hasOut)
  3393. clearOutOnMismatch = !CheckVariableDeclaration(caseExpr, true, true, true);
  3394. bool hadConditional = false;
  3395. if (isPayloadEnum)
  3396. {
  3397. int dscrDataIdx;
  3398. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  3399. auto enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  3400. int uncondTagId = -1;
  3401. mResult = mModule->TryCaseEnumMatch(caseValAddr, enumTagVal, caseExpr->mCaseExpression, NULL, NULL, NULL, uncondTagId, hadConditional, clearOutOnMismatch, false);
  3402. }
  3403. else
  3404. {
  3405. mResult = mModule->TryCaseTupleMatch(caseValAddr, tupleExpr, NULL, NULL, NULL, hadConditional, clearOutOnMismatch, false);
  3406. }
  3407. if (mResult)
  3408. return;
  3409. }
  3410. if ((caseValAddr) && (IsVar(caseValAddr.mType)))
  3411. {
  3412. auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression);
  3413. if (invocationExpr != NULL)
  3414. {
  3415. for (auto expr : invocationExpr->mArguments)
  3416. {
  3417. if (expr == NULL)
  3418. continue;
  3419. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(expr))
  3420. {
  3421. auto localVar = mModule->HandleVariableDeclaration(varDecl, BfTypedValue());
  3422. if (localVar != NULL)
  3423. localVar->mReadFromId = 0;
  3424. }
  3425. }
  3426. }
  3427. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  3428. mResult = mModule->GetDefaultTypedValue(boolType);
  3429. return;
  3430. }
  3431. BfTypedValue caseMatch;
  3432. if (caseExpr->mCaseExpression != NULL)
  3433. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, caseValAddr.mType, BfEvalExprFlags_AllowEnumId);
  3434. if ((!caseMatch) || (!caseValAddr))
  3435. {
  3436. mResult = mModule->GetDefaultTypedValue(boolType);
  3437. return;
  3438. }
  3439. if (caseValAddr.mType == caseMatch.mType)
  3440. {
  3441. if (((caseValAddr.mType->IsEnum()) && (caseValAddr.mType->IsStruct())) &&
  3442. ((caseMatch) && (caseMatch.mType->IsPayloadEnum()) && (caseMatch.mValue.IsConst())))
  3443. {
  3444. BfTypedValue enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  3445. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(enumTagVal.mValue, caseMatch.mValue), boolType);
  3446. return;
  3447. }
  3448. }
  3449. else
  3450. {
  3451. // We need to get rid of the int-const for the 'scalar match'. We get a full payload enum value so we can
  3452. // possibly use it in a user-defined comparison operator
  3453. if ((caseMatch.mType->IsStruct()) && (caseMatch.mValue.IsConst()))
  3454. {
  3455. // Is it possible this could throw an error twice? Hope not.
  3456. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  3457. }
  3458. }
  3459. PerformBinaryOperation(caseExpr->mCaseExpression, caseExpr->mValueExpression, BfBinaryOp_Equality, caseExpr->mEqualsNode, BfBinOpFlag_None, caseValAddr, caseMatch);
  3460. }
  3461. void BfExprEvaluator::Visit(BfCaseExpression* caseExpr)
  3462. {
  3463. if (caseExpr->mEqualsNode != NULL)
  3464. {
  3465. mModule->Warn(0, "Deprecated case syntax", caseExpr->mEqualsNode);
  3466. }
  3467. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  3468. BfTypedValue caseValAddr;
  3469. if (caseExpr->mValueExpression != NULL)
  3470. caseValAddr = mModule->CreateValueFromExpression(caseExpr->mValueExpression, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  3471. if ((caseValAddr.mType != NULL) && (caseValAddr.mType->IsPointer()))
  3472. {
  3473. caseValAddr = mModule->LoadValue(caseValAddr);
  3474. caseValAddr = BfTypedValue(caseValAddr.mValue, caseValAddr.mType->GetUnderlyingType(), true);
  3475. }
  3476. BfIRValue hasValueValue;
  3477. if (caseValAddr.mType != NULL)
  3478. mModule->mBfIRBuilder->PopulateType(caseValAddr.mType);
  3479. if ((caseValAddr.mType != NULL) && (caseValAddr.mType->IsNullable()))
  3480. {
  3481. auto nullableElementType = caseValAddr.mType->GetUnderlyingType();
  3482. hasValueValue = mModule->ExtractValue(caseValAddr, nullableElementType->IsValuelessType() ? 1 : 2);
  3483. if (!nullableElementType->IsValuelessType())
  3484. caseValAddr = BfTypedValue(mModule->ExtractValue(caseValAddr, 1), nullableElementType); // value
  3485. else
  3486. caseValAddr = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), nullableElementType);
  3487. }
  3488. BfIRBlock nullBB;
  3489. BfIRBlock endBB;
  3490. if (hasValueValue)
  3491. {
  3492. auto caseBB = mModule->mBfIRBuilder->CreateBlock("caseexpr.case");
  3493. endBB = mModule->mBfIRBuilder->CreateBlock("caseexpr.end");
  3494. mModule->mBfIRBuilder->CreateCondBr(hasValueValue, caseBB, endBB);
  3495. nullBB = mModule->mBfIRBuilder->GetInsertBlock();
  3496. mModule->mBfIRBuilder->AddBlock(caseBB);
  3497. mModule->mBfIRBuilder->SetInsertPoint(caseBB);
  3498. }
  3499. DoCaseExpression(caseValAddr, caseExpr);
  3500. if (!mResult)
  3501. mResult = mModule->GetDefaultTypedValue(boolType);
  3502. else
  3503. {
  3504. BF_ASSERT(mResult.mType == boolType);
  3505. }
  3506. if (hasValueValue)
  3507. {
  3508. auto endCaseBB = mModule->mBfIRBuilder->GetInsertBlock();
  3509. mModule->mBfIRBuilder->CreateBr(endBB);
  3510. mModule->mBfIRBuilder->AddBlock(endBB);
  3511. mModule->mBfIRBuilder->SetInsertPoint(endBB);
  3512. auto phiValue = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  3513. mModule->mBfIRBuilder->AddPhiIncoming(phiValue, mModule->GetDefaultValue(boolType), nullBB);
  3514. mModule->mBfIRBuilder->AddPhiIncoming(phiValue, mResult.mValue, endCaseBB);
  3515. mResult = BfTypedValue(phiValue, boolType);
  3516. }
  3517. if (caseExpr->mNotToken != NULL)
  3518. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  3519. }
  3520. void BfExprEvaluator::Visit(BfTypedValueExpression* typedValueExpr)
  3521. {
  3522. mResult = typedValueExpr->mTypedValue;
  3523. }
  3524. static bool IsCharType(BfTypeCode typeCode)
  3525. {
  3526. switch (typeCode)
  3527. {
  3528. case BfTypeCode_Char8:
  3529. case BfTypeCode_Char16:
  3530. case BfTypeCode_Char32:
  3531. return true;
  3532. default:
  3533. return false;
  3534. }
  3535. }
  3536. bool BfExprEvaluator::CheckForMethodName(BfAstNode* refNode, BfTypeInstance* typeInst, const StringImpl& findName)
  3537. {
  3538. BF_ASSERT((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0);
  3539. auto autoComplete = GetAutoComplete();
  3540. while (typeInst != NULL)
  3541. {
  3542. auto typeDef = typeInst->mTypeDef;
  3543. typeDef->PopulateMemberSets();
  3544. BfMemberSetEntry* memberSetEntry;
  3545. if (typeDef->mMethodSet.TryGetWith(findName, &memberSetEntry))
  3546. {
  3547. if (mModule->mCompiler->mResolvePassData != NULL)
  3548. mModule->mCompiler->mResolvePassData->HandleMethodReference(refNode, typeDef, (BfMethodDef*)memberSetEntry->mMemberDef);
  3549. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(refNode)))
  3550. {
  3551. autoComplete->SetDefinitionLocation(((BfMethodDef*)memberSetEntry->mMemberDef)->GetRefNode());
  3552. if ((autoComplete->mResolveType == BfResolveType_GetSymbolInfo) && (autoComplete->mDefType == NULL))
  3553. {
  3554. autoComplete->mDefType = typeDef;
  3555. autoComplete->mDefMethod = (BfMethodDef*)memberSetEntry->mMemberDef;
  3556. }
  3557. }
  3558. if (mModule->mCompiler->mResolvePassData != NULL)
  3559. {
  3560. if (auto sourceClassifier = mModule->mCompiler->mResolvePassData->GetSourceClassifier(refNode))
  3561. sourceClassifier->SetElementType(refNode, BfSourceElementType_Method);
  3562. }
  3563. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NameOfSuccess);
  3564. return true;
  3565. }
  3566. typeInst = typeInst->mBaseType;
  3567. }
  3568. return false;
  3569. }
  3570. bool BfExprEvaluator::IsVar(BfType* type, bool forceIgnoreWrites)
  3571. {
  3572. if (type->IsVar())
  3573. return true;
  3574. if ((type->IsGenericParam()) && (!forceIgnoreWrites) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  3575. {
  3576. BF_ASSERT(mModule->mIsComptimeModule);
  3577. return true;
  3578. }
  3579. return false;
  3580. }
  3581. void BfExprEvaluator::GetLiteral(BfAstNode* refNode, const BfVariant& variant, BfType* type)
  3582. {
  3583. switch (variant.mTypeCode)
  3584. {
  3585. case BfTypeCode_NullPtr:
  3586. {
  3587. auto nullType = mModule->ResolveTypeDef(mModule->mSystem->mTypeNullPtr);
  3588. /*mResult = BfTypedValue(ConstantPointerNull::get((PointerType*) nullType->mIRType), nullType);*/
  3589. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstNull(), nullType);
  3590. }
  3591. break;
  3592. case BfTypeCode_CharPtr:
  3593. {
  3594. if ((mExpectingType != NULL) && (mExpectingType->IsSizedArray()))
  3595. {
  3596. auto sizedArray = (BfSizedArrayType*)mExpectingType;
  3597. if (sizedArray->mElementType == mModule->GetPrimitiveType(BfTypeCode_Char8))
  3598. {
  3599. if (sizedArray->IsUndefSizedArray())
  3600. sizedArray = mModule->CreateSizedArrayType(sizedArray->mElementType, variant.mString->GetLength());
  3601. if (variant.mString->GetLength() > sizedArray->mElementCount)
  3602. {
  3603. mModule->Fail(StrFormat("String literal is too long to fit into '%s'", mModule->TypeToString(sizedArray).c_str()), refNode);
  3604. }
  3605. Array<BfIRValue> charValues;
  3606. for (int i = 0; i < (int)BF_MIN(variant.mString->GetLength(), sizedArray->mElementCount); i++)
  3607. {
  3608. char c = (*variant.mString)[i];
  3609. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)(uint8)c));
  3610. }
  3611. if (sizedArray->mElementCount > charValues.size())
  3612. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, 0));
  3613. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(sizedArray), charValues), sizedArray);
  3614. return;
  3615. }
  3616. }
  3617. if ((mExpectingType == NULL) || (!mExpectingType->IsPointer()))
  3618. {
  3619. mResult = BfTypedValue(mModule->GetStringObjectValue(*variant.mString),
  3620. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  3621. }
  3622. else
  3623. {
  3624. auto charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  3625. auto charPtrType = mModule->CreatePointerType(charType);
  3626. mResult = BfTypedValue(mModule->GetStringCharPtr(*variant.mString),
  3627. charPtrType);
  3628. }
  3629. }
  3630. break;
  3631. case BfTypeCode_Boolean:
  3632. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  3633. break;
  3634. case BfTypeCode_Char8:
  3635. case BfTypeCode_Char16:
  3636. case BfTypeCode_Char32:
  3637. case BfTypeCode_Int8:
  3638. case BfTypeCode_UInt8:
  3639. case BfTypeCode_Int16:
  3640. case BfTypeCode_UInt16:
  3641. case BfTypeCode_Int32:
  3642. case BfTypeCode_UInt32:
  3643. case BfTypeCode_Int64:
  3644. case BfTypeCode_UInt64:
  3645. case BfTypeCode_IntPtr:
  3646. case BfTypeCode_UIntPtr:
  3647. case BfTypeCode_IntUnknown:
  3648. case BfTypeCode_UIntUnknown:
  3649. if ((mExpectingType != NULL) && (mExpectingType->IsIntegral()) && (mExpectingType->IsChar() == IsCharType(variant.mTypeCode)))
  3650. {
  3651. auto primType = (BfPrimitiveType*)mExpectingType;
  3652. if (mModule->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, variant.mUInt64))
  3653. {
  3654. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, variant.mUInt64), mExpectingType);
  3655. break;
  3656. }
  3657. }
  3658. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  3659. break;
  3660. case BfTypeCode_Float:
  3661. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mSingle), mModule->GetPrimitiveType(variant.mTypeCode));
  3662. break;
  3663. case BfTypeCode_Double:
  3664. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mDouble), mModule->GetPrimitiveType(variant.mTypeCode));
  3665. break;
  3666. case BfTypeCode_StringId:
  3667. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  3668. break;
  3669. case BfTypeCode_Let:
  3670. if (mExpectingType != NULL)
  3671. {
  3672. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(mExpectingType)), mExpectingType);
  3673. break;
  3674. }
  3675. mModule->Fail("Invalid undef literal", refNode);
  3676. break;
  3677. case BfTypeCode_Struct:
  3678. if (type != NULL)
  3679. {
  3680. BfVariant::StructData* structData = (BfVariant::StructData*)variant.mPtr;
  3681. mResult = BfTypedValue(mModule->mBfIRBuilder->ReadConstant(structData->mData, type), type);
  3682. }
  3683. break;
  3684. default:
  3685. mModule->Fail("Invalid literal", refNode);
  3686. break;
  3687. }
  3688. }
  3689. void BfExprEvaluator::Visit(BfLiteralExpression* literalExpr)
  3690. {
  3691. switch (literalExpr->mValue.mWarnType)
  3692. {
  3693. case BfWarning_BF4201_Only7Hex:
  3694. mModule->Warn(BfWarning_BF4201_Only7Hex, "Only 7 hex digits specified. Add a leading zero to clarify intention.", literalExpr);
  3695. break;
  3696. case BfWarning_BF4202_TooManyHexForInt:
  3697. 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);
  3698. break;
  3699. }
  3700. GetLiteral(literalExpr, literalExpr->mValue);
  3701. }
  3702. void BfExprEvaluator::Visit(BfStringInterpolationExpression* stringInterpolationExpression)
  3703. {
  3704. if ((mBfEvalExprFlags & BfEvalExprFlags_StringInterpolateFormat) != 0)
  3705. {
  3706. BfVariant variant;
  3707. variant.mTypeCode = BfTypeCode_CharPtr;
  3708. variant.mString = stringInterpolationExpression->mString;
  3709. GetLiteral(stringInterpolationExpression, variant);
  3710. return;
  3711. }
  3712. //
  3713. {
  3714. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlag(mBfEvalExprFlags);
  3715. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mConstEvalAttributeTypeDef)))
  3716. {
  3717. mModule->mAttributeState->mUsed = true;
  3718. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  3719. }
  3720. if (IsConstEval())
  3721. {
  3722. auto stringType = mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef);
  3723. if (stringType != NULL)
  3724. {
  3725. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, true);
  3726. SizedArray<BfExpression*, 2> argExprs;
  3727. argExprs.Add(stringInterpolationExpression);
  3728. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  3729. BfResolvedArgs argValues(&sizedArgExprs);
  3730. ResolveArgValues(argValues, BfResolveArgsFlag_InsideStringInterpolationAlloc);
  3731. auto result = MatchMethod(stringInterpolationExpression, NULL, BfTypedValue(stringType), false, false, "ConstF", argValues, BfMethodGenericArguments());
  3732. if (result.mType == stringType)
  3733. {
  3734. mResult = result;
  3735. return;
  3736. }
  3737. }
  3738. mModule->Fail("Const evaluation of string interpolation not allowed", stringInterpolationExpression);
  3739. }
  3740. }
  3741. if (stringInterpolationExpression->mAllocNode != NULL)
  3742. {
  3743. auto stringType = mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef)->ToTypeInstance();
  3744. BfTokenNode* newToken = NULL;
  3745. BfAllocTarget allocTarget;
  3746. ResolveAllocTarget(allocTarget, stringInterpolationExpression->mAllocNode, newToken);
  3747. //
  3748. {
  3749. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  3750. CreateObject(NULL, stringInterpolationExpression->mAllocNode, stringType, NULL);
  3751. }
  3752. BfTypedValue newString = mResult;
  3753. BF_ASSERT(newString);
  3754. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, true);
  3755. SizedArray<BfExpression*, 2> argExprs;
  3756. argExprs.Add(stringInterpolationExpression);
  3757. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  3758. BfResolvedArgs argValues(&sizedArgExprs);
  3759. ResolveArgValues(argValues, BfResolveArgsFlag_InsideStringInterpolationAlloc);
  3760. MatchMethod(stringInterpolationExpression, NULL, newString, false, false, "AppendF", argValues, BfMethodGenericArguments());
  3761. mResult = newString;
  3762. return;
  3763. }
  3764. mModule->Fail("Invalid use of string interpolation expression. Consider adding an allocation specifier such as 'scope'.", stringInterpolationExpression);
  3765. for (auto block : stringInterpolationExpression->mExpressions)
  3766. {
  3767. VisitChild(block);
  3768. }
  3769. }
  3770. BfTypedValue BfExprEvaluator::LoadLocal(BfLocalVariable* varDecl, bool allowRef)
  3771. {
  3772. if (!mModule->mIsInsideAutoComplete)
  3773. varDecl->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  3774. // The Beef backend prefers readonly addrs since that reduces register pressure, whereas
  3775. // LLVM prefers values to avoid memory loads. This only applies to primitive types...
  3776. bool preferValue = (varDecl->mResolvedType->IsPrimitiveType()) && (!mModule->IsTargetingBeefBackend());
  3777. BfTypedValue localResult;
  3778. if (varDecl->mIsThis)
  3779. {
  3780. return mModule->GetThis();
  3781. }
  3782. else if (varDecl->mConstValue)
  3783. {
  3784. localResult = BfTypedValue(varDecl->mConstValue, varDecl->mResolvedType, false);
  3785. }
  3786. else if (varDecl->mIsSplat)
  3787. {
  3788. if (!varDecl->mResolvedType->IsValuelessType())
  3789. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  3790. else if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3791. {
  3792. BF_ASSERT(varDecl->mResolvedType->IsValuelessType());
  3793. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType->GetUnderlyingType());
  3794. }
  3795. else
  3796. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType);
  3797. //BF_ASSERT(varDecl->mValue.IsArg());
  3798. }
  3799. else if ((varDecl->mValue) && ((varDecl->mIsReadOnly && preferValue) || (!varDecl->mAddr)))
  3800. {
  3801. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3802. {
  3803. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3804. BfType* innerType = refType->mElementType;
  3805. if (innerType->IsGenericParam())
  3806. {
  3807. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3808. {
  3809. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_MutableValue);
  3810. return localResult;
  3811. }
  3812. else
  3813. {
  3814. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_Addr);
  3815. return localResult;
  3816. }
  3817. }
  3818. localResult = BfTypedValue(varDecl->mValue, innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3819. }
  3820. else
  3821. {
  3822. BfTypedValueKind kind;
  3823. if ((varDecl->mResolvedType->IsComposite()) && (varDecl->mValue.IsArg()))
  3824. {
  3825. kind = varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr;
  3826. }
  3827. else
  3828. kind = BfTypedValueKind_Value;
  3829. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, kind);
  3830. }
  3831. }
  3832. else if (varDecl->mAddr)
  3833. {
  3834. if ((!mModule->mBfIRBuilder->mIgnoreWrites) && (varDecl->mAddr.IsFake()) && (!varDecl->mResolvedType->IsValuelessType()))
  3835. {
  3836. // In an ignore case match we can may need to create a fake "out" when someone tries to read it
  3837. auto defaultTypedValue = mModule->GetDefaultTypedValue(varDecl->mResolvedType, true, BfDefaultValueKind_Addr);
  3838. varDecl->mAddr = defaultTypedValue.mValue;
  3839. }
  3840. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3841. {
  3842. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3843. BfType* innerType = refType->mElementType;
  3844. if (innerType->IsValuelessNonOpaqueType())
  3845. {
  3846. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3847. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, BfTypedValueKind_MutableValue);
  3848. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3849. }
  3850. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3851. {
  3852. if (innerType->IsGenericParam())
  3853. {
  3854. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, BfTypedValueKind_MutableValue);
  3855. return localResult;
  3856. }
  3857. }
  3858. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3859. }
  3860. else if (varDecl->mHasLocalStructBacking)
  3861. {
  3862. // varDecl->mAddr is a "struct**"
  3863. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3864. }
  3865. else
  3866. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3867. }
  3868. else if ((varDecl->mResolvedType->IsModifiedTypeType()) && (((BfModifiedTypeType*)varDecl->mResolvedType)->mModifiedKind == BfToken_Params))
  3869. {
  3870. localResult = BfTypedValue(BfIRValue(), varDecl->mResolvedType);
  3871. }
  3872. else if (varDecl->mResolvedType->IsValuelessNonOpaqueType())
  3873. {
  3874. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3875. {
  3876. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3877. BfType* innerType = refType->mElementType;
  3878. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, true);
  3879. return localResult;
  3880. }
  3881. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), varDecl->mResolvedType, true);
  3882. }
  3883. else if (varDecl->mCompositeCount >= 0)
  3884. {
  3885. if ((mBfEvalExprFlags & BfEvalExprFlags_InParamsExpr) != 0)
  3886. {
  3887. localResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  3888. }
  3889. else if (!varDecl->mAddr)
  3890. {
  3891. bool isValid = true;
  3892. Array<BfTypedValue> argVals;
  3893. auto methodState = mModule->mCurMethodState->GetMethodStateForLocal(varDecl);
  3894. for (int compositeIdx = 0; compositeIdx < varDecl->mCompositeCount; compositeIdx++)
  3895. {
  3896. BfResolvedArg compositeResolvedArg;
  3897. auto compositeLocalVar = methodState->mLocals[varDecl->mLocalVarIdx + compositeIdx + 1];
  3898. auto argValue = LoadLocal(compositeLocalVar, true);
  3899. if (argValue)
  3900. {
  3901. if (!argValue.mType->IsStruct())
  3902. argValue = mModule->LoadValue(argValue, NULL, mIsVolatileReference);
  3903. argVals.Add(argValue);
  3904. }
  3905. else
  3906. isValid = false;
  3907. }
  3908. if (isValid)
  3909. {
  3910. BfTypeInstance* tupleType = NULL;
  3911. if (varDecl->mResolvedType->IsTuple())
  3912. tupleType = (BfTupleType*)varDecl->mResolvedType;
  3913. else if ((varDecl->mResolvedType->IsDelegateOrFunction()))
  3914. {
  3915. auto invokeFunction = mModule->GetDelegateInvokeMethod(varDecl->mResolvedType->ToTypeInstance());
  3916. if (invokeFunction != NULL)
  3917. {
  3918. BfTypeVector fieldTypes;
  3919. SubstituteList fieldNames;
  3920. for (int paramIdx = 0; paramIdx < invokeFunction->GetParamCount(); paramIdx++)
  3921. {
  3922. fieldNames.Add(invokeFunction->GetParamName(paramIdx));
  3923. fieldTypes.Add(invokeFunction->GetParamType(paramIdx));
  3924. }
  3925. tupleType = mModule->CreateTupleType(fieldTypes, fieldNames);
  3926. }
  3927. }
  3928. if (tupleType == NULL)
  3929. {
  3930. isValid = false;
  3931. }
  3932. else if (tupleType->IsValuelessType())
  3933. {
  3934. localResult = mModule->GetDefaultTypedValue(tupleType);
  3935. }
  3936. else
  3937. {
  3938. BF_ASSERT(tupleType->mFieldInstances.mSize == argVals.mSize);
  3939. auto instAlloca = mModule->CreateAlloca(tupleType);
  3940. for (int i = 0; i < argVals.mSize; i++)
  3941. {
  3942. auto& fieldInstance = tupleType->mFieldInstances[i];
  3943. if (fieldInstance.mDataIdx >= 0)
  3944. {
  3945. auto val = mModule->Cast(varDecl->mNameNode, argVals[i], fieldInstance.mResolvedType);
  3946. if (val)
  3947. {
  3948. val = mModule->LoadOrAggregateValue(val);
  3949. if (!val.mType->IsValuelessType())
  3950. {
  3951. auto elemPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(instAlloca, 0, fieldInstance.mDataIdx);
  3952. mModule->mBfIRBuilder->CreateStore(val.mValue, elemPtr);
  3953. }
  3954. }
  3955. }
  3956. }
  3957. varDecl->mResolvedType = tupleType;
  3958. varDecl->mAddr = instAlloca;
  3959. varDecl->mIsReadOnly = true;
  3960. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_ReadOnlyAddr);
  3961. }
  3962. }
  3963. if (!isValid)
  3964. {
  3965. localResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTupleTypeDef));
  3966. }
  3967. }
  3968. }
  3969. else
  3970. {
  3971. BF_ASSERT((mModule->mCurMethodState->mClosureState != NULL) || (mModule->mBfIRBuilder->mIgnoreWrites));
  3972. // Just temporary
  3973. auto varType = varDecl->mResolvedType;
  3974. auto allocType = varType;
  3975. if (varType->IsRef())
  3976. {
  3977. BfRefType* refType = (BfRefType*)varType;
  3978. allocType = refType->mElementType;
  3979. }
  3980. auto declType = varDecl->mResolvedType;
  3981. if (declType->IsRef())
  3982. {
  3983. BfRefType* refType = (BfRefType*)declType;
  3984. declType = refType->mElementType;
  3985. }
  3986. mModule->PopulateType(allocType);
  3987. varDecl->mAddr = mModule->mBfIRBuilder->CreateAlloca(mModule->mBfIRBuilder->MapType(allocType));
  3988. localResult = BfTypedValue(varDecl->mAddr, declType, true);
  3989. return localResult;
  3990. }
  3991. if ((varDecl->mIsThis) && (localResult.mKind == BfTypedValueKind_Value))
  3992. localResult.mKind = BfTypedValueKind_ThisValue;
  3993. return localResult;
  3994. }
  3995. BfTypedValue BfExprEvaluator::LookupIdentifier(BfAstNode* refNode, const StringImpl& findName, bool ignoreInitialError, bool* hadError)
  3996. {
  3997. int varSkipCount = 0;
  3998. StringT<128> wantName;
  3999. wantName.Reference(findName);
  4000. if (findName.StartsWith('@'))
  4001. {
  4002. wantName = findName;
  4003. while (wantName.StartsWith("@"))
  4004. {
  4005. if (wantName != "@return")
  4006. varSkipCount++;
  4007. wantName.Remove(0);
  4008. }
  4009. }
  4010. if (wantName.IsEmpty())
  4011. {
  4012. mModule->Fail("Shadowed variable name expected after '@'", refNode);
  4013. }
  4014. if ((mModule->mCompiler->mCeMachine != NULL) && (mModule->mCompiler->mCeMachine->mDebugger != NULL) && (mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  4015. {
  4016. auto ceDebugger = mModule->mCompiler->mCeMachine->mDebugger;
  4017. auto ceContext = ceDebugger->mCurDbgState->mCeContext;
  4018. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  4019. if (activeFrame->mFunction->mDbgInfo != NULL)
  4020. {
  4021. int varSkipCountLeft = varSkipCount;
  4022. int instIdx = activeFrame->GetInstIdx();
  4023. for (int i = activeFrame->mFunction->mDbgInfo->mVariables.mSize - 1; i >= 0; i--)
  4024. {
  4025. auto& dbgVar = activeFrame->mFunction->mDbgInfo->mVariables[i];
  4026. if (dbgVar.mName == wantName)
  4027. {
  4028. if (varSkipCountLeft > 0)
  4029. {
  4030. varSkipCountLeft--;
  4031. }
  4032. else if ((dbgVar.mValue.mKind == CeOperandKind_AllocaAddr) || (dbgVar.mValue.mKind == CeOperandKind_FrameOfs))
  4033. {
  4034. if ((instIdx >= dbgVar.mStartCodePos) && (instIdx < dbgVar.mEndCodePos))
  4035. {
  4036. return BfTypedValue(mModule->mBfIRBuilder->CreateConstAggCE(mModule->mBfIRBuilder->MapType(dbgVar.mType), activeFrame->mFrameAddr + dbgVar.mValue.mFrameOfs),
  4037. dbgVar.mType, dbgVar.mIsConst ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  4038. }
  4039. }
  4040. }
  4041. }
  4042. }
  4043. if (findName == "FR")
  4044. {
  4045. auto ptrType = mModule->CreatePointerType(mModule->GetPrimitiveType(BfTypeCode_UInt8));
  4046. auto intVal = mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, activeFrame->mFrameAddr);
  4047. auto ptrVal = mModule->mBfIRBuilder->CreateIntToPtr(intVal, mModule->mBfIRBuilder->MapType(ptrType));
  4048. return BfTypedValue(ptrVal, ptrType);
  4049. }
  4050. }
  4051. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(refNode);
  4052. if (mModule->mCurMethodState != NULL)
  4053. {
  4054. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  4055. auto checkMethodState = mModule->mCurMethodState;
  4056. bool isMixinOuterVariablePass = false;
  4057. while (checkMethodState != NULL)
  4058. {
  4059. BP_ZONE("LookupIdentifier:LocalVar");
  4060. BfTypeInstance* closureTypeInst = NULL;
  4061. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  4062. {
  4063. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  4064. }
  4065. int varSkipCountLeft = varSkipCount;
  4066. BfLocalVarEntry* entry;
  4067. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(wantName, &entry))
  4068. {
  4069. auto varDecl = entry->mLocalVar;
  4070. if (varDecl != NULL)
  4071. varSkipCountLeft -= varDecl->mNamePrefixCount;
  4072. while ((varSkipCountLeft > 0) && (varDecl != NULL))
  4073. {
  4074. varDecl = varDecl->mShadowedLocal;
  4075. varSkipCountLeft--;
  4076. }
  4077. if ((varDecl != NULL) && (varDecl->mNotCaptured))
  4078. {
  4079. mModule->Fail("Local variable is not captured", refNode);
  4080. }
  4081. if ((varSkipCountLeft == 0) && (varDecl != NULL))
  4082. {
  4083. if ((closureTypeInst != NULL) && (wantName == "this"))
  4084. break;
  4085. if (varDecl->mResolvedType->IsVoid())
  4086. {
  4087. if ((varDecl->mIsReadOnly) && (varDecl->mParamIdx == -2) && (varDecl->mParamFailed))
  4088. {
  4089. BF_ASSERT(mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  4090. 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);
  4091. }
  4092. }
  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. return BfTypedValue(mModule->mBfIRBuilder->CreateLoad(thisLocal->mAddr), thisLocal->mResolvedType);
  4365. }
  4366. }
  4367. }
  4368. return result;
  4369. }
  4370. BfTypedValue BfExprEvaluator::LookupIdentifier(BfIdentifierNode* identifierNode, bool ignoreInitialError, bool* hadError)
  4371. {
  4372. auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode);
  4373. if (qualifiedNameNode != NULL)
  4374. {
  4375. LookupQualifiedName(qualifiedNameNode, ignoreInitialError, hadError);
  4376. auto qualifiedResult = mResult;
  4377. mResult = BfTypedValue();
  4378. return qualifiedResult;
  4379. }
  4380. StringT<128> identifierStr;
  4381. identifierNode->ToString(identifierStr);
  4382. return LookupIdentifier(identifierNode, identifierStr, ignoreInitialError, hadError);
  4383. }
  4384. void BfExprEvaluator::Visit(BfIdentifierNode* identifierNode)
  4385. {
  4386. auto autoComplete = GetAutoComplete();
  4387. if (autoComplete != NULL)
  4388. autoComplete->CheckIdentifier(identifierNode, true);
  4389. mResult = LookupIdentifier(identifierNode);
  4390. if ((!mResult) && (mPropDef == NULL))
  4391. {
  4392. mModule->CheckTypeRefFixit(identifierNode);
  4393. if ((autoComplete != NULL) && (autoComplete->CheckFixit(identifierNode)))
  4394. {
  4395. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  4396. {
  4397. // During this phase we don't have lambda and local method params available so they would result in erroneous fixits
  4398. }
  4399. else if (mModule->mCurMethodInstance != NULL)
  4400. {
  4401. BfType* fieldType = mExpectingType;
  4402. if (fieldType == NULL)
  4403. fieldType = mModule->mContext->mBfObjectType;
  4404. autoComplete->FixitAddMember(mModule->mCurTypeInstance, fieldType, identifierNode->ToString(), true, mModule->mCurTypeInstance);
  4405. if (!mModule->mCurMethodInstance->mMethodDef->mIsStatic)
  4406. autoComplete->FixitAddMember(mModule->mCurTypeInstance, fieldType, identifierNode->ToString(), false, mModule->mCurTypeInstance);
  4407. for (auto typeDef : mModule->mSystem->mTypeDefs)
  4408. {
  4409. if (!typeDef->mIsCombinedPartial)
  4410. continue;
  4411. if (!typeDef->IsGlobalsContainer())
  4412. continue;
  4413. typeDef->PopulateMemberSets();
  4414. String findName = identifierNode->ToString();
  4415. BfMemberSetEntry* memberSetEntry;
  4416. if ((typeDef->mMethodSet.TryGetWith(findName, &memberSetEntry)) ||
  4417. (typeDef->mFieldSet.TryGetWith(findName, &memberSetEntry)) ||
  4418. (typeDef->mPropertySet.TryGetWith(findName, &memberSetEntry)))
  4419. {
  4420. if (mModule->GetActiveTypeDef()->mProject->ContainsReference(typeDef->mProject))
  4421. autoComplete->FixitAddNamespace(identifierNode, typeDef->mNamespace.ToString());
  4422. }
  4423. }
  4424. }
  4425. }
  4426. if (((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0) && (mModule->mCurTypeInstance != NULL) && (CheckForMethodName(identifierNode, mModule->mCurTypeInstance, identifierNode->ToString())))
  4427. return;
  4428. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  4429. mModule->Fail("Identifier not found", identifierNode);
  4430. }
  4431. }
  4432. void BfExprEvaluator::Visit(BfAttributedIdentifierNode* attrIdentifierNode)
  4433. {
  4434. if ((mModule->mAttributeState != NULL))
  4435. {
  4436. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  4437. VisitChild(attrIdentifierNode->mIdentifier);
  4438. }
  4439. else
  4440. {
  4441. BfAttributeState attributeState;
  4442. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  4443. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  4444. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  4445. VisitChild(attrIdentifierNode->mIdentifier);
  4446. }
  4447. }
  4448. static int gPropIdx = 0;
  4449. void BfExprEvaluator::FixitAddMember(BfTypeInstance* typeInst, BfType* fieldType, const StringImpl& fieldName, bool isStatic)
  4450. {
  4451. if (fieldType == NULL)
  4452. {
  4453. fieldType = mExpectingType;
  4454. }
  4455. if (fieldType != NULL)
  4456. {
  4457. if (fieldType->IsRef())
  4458. fieldType = fieldType->GetUnderlyingType();
  4459. }
  4460. mModule->mCompiler->mResolvePassData->mAutoComplete->FixitAddMember(typeInst, fieldType, fieldName, isStatic, mModule->mCurTypeInstance);
  4461. }
  4462. BfTypedValue BfExprEvaluator::TryArrowLookup(BfTypedValue typedValue, BfTokenNode* arrowToken)
  4463. {
  4464. auto arrowValue = PerformUnaryOperation_TryOperator(typedValue, NULL, BfUnaryOp_Arrow, arrowToken, BfUnaryOpFlag_None);
  4465. if (arrowValue)
  4466. return arrowValue;
  4467. if (mModule->PreFail())
  4468. mModule->Fail(StrFormat("Type '%s' does not contain a '->' operator", mModule->TypeToString(typedValue.mType).c_str()), arrowToken);
  4469. return typedValue;
  4470. }
  4471. BfTypedValue BfExprEvaluator::LoadProperty(BfAstNode* targetSrc, BfTypedValue target, BfTypeInstance* typeInstance, BfPropertyDef* prop, BfLookupFieldFlags flags, BfCheckedKind checkedKind, bool isInlined)
  4472. {
  4473. BfTypedValue origTarget = target;
  4474. if ((target.mType != NULL) && (target.mType->IsStructPtr()))
  4475. {
  4476. target = mModule->LoadValue(target);
  4477. target = BfTypedValue(target.mValue, target.mType->GetUnderlyingType(), target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  4478. }
  4479. if ((flags & BfLookupFieldFlag_IsAnonymous) == 0)
  4480. mModule->SetElementType(targetSrc, BfSourceElementType_Method);
  4481. if ((!prop->mIsStatic) && ((flags & BfLookupFieldFlag_IsImplicitThis) != 0))
  4482. mModule->MarkUsingThis();
  4483. mPropSrc = targetSrc;
  4484. mPropDef = prop;
  4485. mPropCheckedKind = checkedKind;
  4486. if (isInlined)
  4487. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  4488. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  4489. {
  4490. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef))
  4491. {
  4492. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_Friend);
  4493. mModule->mAttributeState->mUsed = true;
  4494. }
  4495. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  4496. {
  4497. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_DisableObjectAccessChecks);
  4498. mModule->mAttributeState->mUsed = true;
  4499. }
  4500. }
  4501. if (mPropDef->mIsStatic)
  4502. {
  4503. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!typeInstance->mTypeDef->IsGlobalsContainer()))
  4504. {
  4505. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  4506. mModule->Fail(StrFormat("Property '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  4507. mModule->TypeToString(typeInstance).c_str(), mPropDef->mName.c_str()), targetSrc);
  4508. }
  4509. }
  4510. bool isBaseLookup = (target.mType) && (typeInstance != target.mType);
  4511. if ((isBaseLookup) && (target.mType->IsWrappableType()))
  4512. isBaseLookup = false;
  4513. if (prop->mIsStatic)
  4514. mPropTarget = BfTypedValue(typeInstance);
  4515. else if (isBaseLookup)
  4516. {
  4517. if (target.mValue.IsFake())
  4518. {
  4519. mPropTarget = BfTypedValue(target.mValue, typeInstance, target.mKind);
  4520. }
  4521. else
  4522. {
  4523. mPropTarget = mModule->Cast(targetSrc, target, typeInstance);
  4524. BF_ASSERT(mPropTarget);
  4525. }
  4526. }
  4527. else
  4528. mPropTarget = target;
  4529. mOrigPropTarget = mPropTarget;
  4530. if (prop->mIsStatic)
  4531. mOrigPropTarget = target;
  4532. #ifdef _DEBUG
  4533. if (mPropTarget)
  4534. {
  4535. auto propTargetTypeInst = mPropTarget.mType->ToTypeInstance();
  4536. if (propTargetTypeInst != NULL)
  4537. {
  4538. BF_ASSERT(prop->mDeclaringType->mFullNameEx == propTargetTypeInst->mTypeDef->mFullNameEx);
  4539. }
  4540. }
  4541. #endif
  4542. if ((flags & BfLookupFieldFlag_IsAnonymous) == 0)
  4543. {
  4544. auto autoComplete = GetAutoComplete();
  4545. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  4546. if (((autoComplete != NULL) && (autoComplete->mIsGetDefinition)) ||
  4547. ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Property)))
  4548. {
  4549. BfPropertyDef* basePropDef = mPropDef;
  4550. BfTypeInstance* baseTypeInst = typeInstance;
  4551. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  4552. resolvePassData->HandlePropertyReference(targetSrc, baseTypeInst->mTypeDef, basePropDef);
  4553. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetSrc)))
  4554. {
  4555. if (autoComplete->mIsGetDefinition)
  4556. {
  4557. //NOTE: passing 'force=true' in here causes https://github.com/beefytech/Beef/issues/1064
  4558. autoComplete->SetDefinitionLocation(basePropDef->GetRefNode());
  4559. }
  4560. autoComplete->mDefProp = basePropDef;
  4561. autoComplete->mDefType = baseTypeInst->mTypeDef;
  4562. }
  4563. }
  4564. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)))
  4565. {
  4566. BfPropertyDef* basePropDef = mPropDef;
  4567. BfTypeInstance* baseTypeInst = typeInstance;
  4568. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  4569. autoComplete->mResultString = ":";
  4570. autoComplete->mResultString += mModule->TypeToString(baseTypeInst);
  4571. autoComplete->mResultString += ".";
  4572. autoComplete->mResultString += basePropDef->mName;
  4573. }
  4574. }
  4575. // Check for direct auto-property access
  4576. if ((target.mType == mModule->mCurTypeInstance) && ((flags & BfLookupFieldFlag_BindOnly) == 0))
  4577. {
  4578. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(mPropDef->mFieldDeclaration))
  4579. {
  4580. if ((typeInstance->mTypeDef->HasAutoProperty(propertyDeclaration)) && (propertyDeclaration->mVirtualSpecifier == NULL))
  4581. {
  4582. BfMethodDef* getter = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, BfCheckedKind_NotSet, mPropTarget);
  4583. BfMethodDef* setter = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, BfCheckedKind_NotSet, mPropTarget);
  4584. bool optAllowed = true;
  4585. if ((getter != NULL) && (getter->mBody != NULL))
  4586. optAllowed = false;
  4587. if ((setter != NULL) && (setter->mBody != NULL))
  4588. optAllowed = false;
  4589. if (optAllowed)
  4590. {
  4591. auto autoFieldName = typeInstance->mTypeDef->GetAutoPropertyName(propertyDeclaration);
  4592. auto result = LookupField(targetSrc, target, autoFieldName, (BfLookupFieldFlags)(BfLookupFieldFlag_IgnoreProtection | BfLookupFieldFlag_IsImplicitThis));
  4593. if (result)
  4594. {
  4595. bool needsCopy = true;
  4596. if (BfNodeIsA<BfRefTypeRef>(prop->mTypeRef))
  4597. {
  4598. // Allow full ref
  4599. }
  4600. else
  4601. {
  4602. if (setter == NULL)
  4603. {
  4604. if (((mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)) &&
  4605. (target.mType == mModule->mCurTypeInstance))
  4606. {
  4607. // Allow writing inside ctor
  4608. }
  4609. else
  4610. {
  4611. result.MakeReadOnly();
  4612. needsCopy = false;
  4613. }
  4614. }
  4615. if (result.mKind == BfTypedValueKind_Addr)
  4616. result.mKind = BfTypedValueKind_CopyOnMutateAddr;
  4617. }
  4618. mPropDef = NULL;
  4619. mPropSrc = NULL;
  4620. mOrigPropTarget = BfTypedValue();
  4621. return result;
  4622. }
  4623. }
  4624. }
  4625. }
  4626. }
  4627. SetAndRestoreValue<BfTypedValue> prevResult(mResult, target);
  4628. CheckResultForReading(mResult);
  4629. return BfTypedValue();
  4630. }
  4631. BfTypedValue BfExprEvaluator::LoadField(BfAstNode* targetSrc, BfTypedValue target, BfTypeInstance* typeInstance, BfFieldDef* fieldDef, BfLookupFieldFlags flags)
  4632. {
  4633. if (fieldDef->mIsProperty)
  4634. {
  4635. BfPropertyDef* propDef = (BfPropertyDef*)fieldDef;
  4636. return LoadProperty(targetSrc, target, typeInstance, propDef, flags, BfCheckedKind_NotSet, false);
  4637. }
  4638. bool isFailurePass = (flags & BfLookupFieldFlag_IsFailurePass) != 0;
  4639. auto fieldInstance = &typeInstance->mFieldInstances[fieldDef->mIdx];
  4640. bool isResolvingFields = typeInstance->mResolvingConstField || typeInstance->mResolvingVarField;
  4641. if (fieldDef->mIsVolatile)
  4642. mIsVolatileReference = true;
  4643. if (fieldInstance->mCustomAttributes != NULL)
  4644. mModule->CheckErrorAttributes(fieldInstance->mOwner, NULL, fieldInstance, fieldInstance->mCustomAttributes, targetSrc);
  4645. if (isFailurePass)
  4646. {
  4647. if (mModule->GetCeDbgState() == NULL)
  4648. mModule->Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", mModule->TypeToString(typeInstance).c_str(), fieldDef->mName.c_str()), targetSrc);
  4649. }
  4650. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  4651. if ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field) && ((flags & BfLookupFieldFlag_IsAnonymous) == 0))
  4652. {
  4653. resolvePassData->HandleFieldReference(targetSrc, typeInstance->mTypeDef, fieldDef);
  4654. }
  4655. if ((!typeInstance->mTypeFailed) && (!isResolvingFields) && (typeInstance->IsIncomplete()))
  4656. {
  4657. if ((fieldInstance->mResolvedType == NULL) ||
  4658. (!fieldDef->mIsStatic))
  4659. {
  4660. mModule->PopulateType(typeInstance, BfPopulateType_Data);
  4661. // Update fieldInstance pointer as it may have moved
  4662. fieldInstance = &typeInstance->mFieldInstances[fieldDef->mIdx];
  4663. }
  4664. }
  4665. if (fieldInstance->mResolvedType == NULL)
  4666. {
  4667. if (mModule->mCompiler->EnsureCeUnpaused(typeInstance))
  4668. {
  4669. BF_ASSERT((typeInstance->mTypeFailed) || (isResolvingFields));
  4670. }
  4671. return BfTypedValue();
  4672. }
  4673. if (fieldInstance->mFieldIdx == -1)
  4674. {
  4675. mModule->AssertErrorState();
  4676. return BfTypedValue();
  4677. }
  4678. if ((!fieldDef->mIsStatic) && ((flags & BfLookupFieldFlag_IsImplicitThis) != 0))
  4679. mModule->MarkUsingThis();
  4680. mResultFieldInstance = fieldInstance;
  4681. // Are we accessing a 'var' field that has not yet been resolved?
  4682. if (IsVar(fieldInstance->mResolvedType))
  4683. {
  4684. // This can happen if we have one var field referencing another var field
  4685. fieldInstance->mResolvedType = mModule->ResolveVarFieldType(typeInstance, fieldInstance, fieldDef);
  4686. if (fieldInstance->mResolvedType == NULL)
  4687. return BfTypedValue();
  4688. }
  4689. auto resolvedFieldType = fieldInstance->mResolvedType;
  4690. if (fieldInstance->mIsEnumPayloadCase)
  4691. {
  4692. resolvedFieldType = typeInstance;
  4693. }
  4694. mModule->PopulateType(resolvedFieldType, BfPopulateType_Data);
  4695. mModule->AddDependency(typeInstance, mModule->mCurTypeInstance, fieldDef->mIsConst ? BfDependencyMap::DependencyFlag_ConstValue : BfDependencyMap::DependencyFlag_ReadFields);
  4696. if (fieldInstance->mHadConstEval)
  4697. {
  4698. mModule->AddDependency(typeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ConstEvalConstField);
  4699. if ((mModule->mContext->mCurTypeState != NULL) && (mModule->mContext->mCurTypeState->mCurFieldDef != NULL))
  4700. {
  4701. // If we're initializing another const field then also set it as having const eval
  4702. auto resolvingFieldInstance = &mModule->mContext->mCurTypeState->mType->ToTypeInstance()->mFieldInstances[mModule->mContext->mCurTypeState->mCurFieldDef->mIdx];
  4703. if (resolvingFieldInstance->GetFieldDef()->mIsConst)
  4704. resolvingFieldInstance->mHadConstEval = true;
  4705. }
  4706. }
  4707. if ((flags & BfLookupFieldFlag_IsAnonymous) == 0)
  4708. {
  4709. auto autoComplete = GetAutoComplete();
  4710. if (autoComplete != NULL)
  4711. {
  4712. autoComplete->CheckFieldRef(BfNodeDynCast<BfIdentifierNode>(targetSrc), fieldInstance);
  4713. if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)))
  4714. {
  4715. autoComplete->mResultString = ":";
  4716. autoComplete->mResultString += mModule->TypeToString(fieldInstance->mResolvedType);
  4717. autoComplete->mResultString += " ";
  4718. autoComplete->mResultString += mModule->TypeToString(typeInstance);
  4719. autoComplete->mResultString += ".";
  4720. autoComplete->mResultString += fieldDef->mName;
  4721. if (fieldInstance->mConstIdx != -1)
  4722. {
  4723. String constStr = autoComplete->ConstantToString(typeInstance->mConstHolder, BfTypedValue(BfIRValue(BfIRValueFlags_Const, fieldInstance->mConstIdx), fieldInstance->mResolvedType));
  4724. if (!constStr.IsEmpty())
  4725. {
  4726. autoComplete->mResultString += " = ";
  4727. if (constStr.StartsWith(':'))
  4728. autoComplete->mResultString.Append(StringView(constStr, 1, constStr.mLength - 1));
  4729. else
  4730. autoComplete->mResultString += constStr;
  4731. }
  4732. }
  4733. auto fieldDecl = fieldInstance->GetFieldDef()->GetFieldDeclaration();
  4734. if ((fieldDecl != NULL) && (fieldDecl->mDocumentation != NULL))
  4735. {
  4736. String docString;
  4737. fieldDecl->mDocumentation->GetDocString(docString);
  4738. autoComplete->mResultString += "\x03";
  4739. autoComplete->mResultString += docString;
  4740. }
  4741. }
  4742. }
  4743. }
  4744. if (fieldDef->mIsStatic)
  4745. {
  4746. if (target)
  4747. {
  4748. //BF_ASSERT((flags & BfLookupFieldFlag_HasInstance) != 0);
  4749. flags = (BfLookupFieldFlags)(flags | BfLookupFieldFlag_HasInstance);
  4750. }
  4751. if (((flags & BfLookupFieldFlag_HasInstance) != 0) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!typeInstance->mTypeDef->IsGlobalsContainer()))
  4752. {
  4753. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  4754. mModule->Fail(StrFormat("Member '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  4755. mModule->TypeToString(typeInstance).c_str(), fieldDef->mName.c_str()), targetSrc);
  4756. }
  4757. // Target must be an implicit 'this', or an error (accessing a static with a non-static target).
  4758. // Not actually needed in either case since this is a static lookup.
  4759. mResultLocalVar = NULL;
  4760. }
  4761. bool isConst = false;
  4762. if (fieldDef->mIsConst)
  4763. {
  4764. isConst = true;
  4765. auto fieldDef = fieldInstance->GetFieldDef();
  4766. if ((resolvedFieldType->IsPointer()) && (fieldDef->mIsExtern))
  4767. isConst = false;
  4768. }
  4769. if (isConst)
  4770. {
  4771. if (fieldInstance->mIsEnumPayloadCase)
  4772. {
  4773. auto dscrType = typeInstance->GetDiscriminatorType();
  4774. mModule->mBfIRBuilder->PopulateType(typeInstance);
  4775. int tagIdx = -fieldInstance->mDataIdx - 1;
  4776. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowEnumId) != 0)
  4777. {
  4778. return BfTypedValue(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), fieldInstance->mOwner);
  4779. }
  4780. mModule->PopulateType(fieldInstance->mOwner, BfPopulateType_Data);
  4781. if (auto fieldTypeInstance = fieldInstance->mResolvedType->ToTypeInstance())
  4782. {
  4783. bool hasFields = false;
  4784. for (auto& fieldInstance : fieldTypeInstance->mFieldInstances)
  4785. {
  4786. if (!fieldInstance.mResolvedType->IsVoid())
  4787. hasFields = true;
  4788. }
  4789. if (hasFields)
  4790. mModule->FailAfter("Enum payload arguments expected", targetSrc);
  4791. }
  4792. SizedArray<BfIRValue, 3> values;
  4793. values.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(typeInstance->mBaseType)));
  4794. values.Add(mModule->GetDefaultValue(typeInstance->GetUnionInnerType()));
  4795. values.Add(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx));
  4796. return BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(typeInstance), values), typeInstance);
  4797. }
  4798. if (fieldInstance->mConstIdx == -1)
  4799. {
  4800. if ((mBfEvalExprFlags & BfEvalExprFlags_DeclType) != 0)
  4801. {
  4802. // We don't need a real value
  4803. return BfTypedValue(mModule->GetDefaultValue(resolvedFieldType), resolvedFieldType);
  4804. }
  4805. typeInstance->mModule->ResolveConstField(typeInstance, fieldInstance, fieldDef);
  4806. if (fieldInstance->mConstIdx == -1)
  4807. return BfTypedValue(mModule->GetDefaultValue(resolvedFieldType), resolvedFieldType);
  4808. }
  4809. BF_ASSERT(fieldInstance->mConstIdx != -1);
  4810. auto foreignConst = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4811. auto retVal = mModule->ConstantToCurrent(foreignConst, typeInstance->mConstHolder, resolvedFieldType);
  4812. return BfTypedValue(retVal, resolvedFieldType);
  4813. }
  4814. else if (fieldDef->mIsStatic)
  4815. {
  4816. if ((mModule->mAttributeState == NULL) || (mModule->mAttributeState->mCustomAttributes == NULL) ||
  4817. (!mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoStaticCtorAttributeTypeDef)))
  4818. {
  4819. mModule->CheckStaticAccess(typeInstance);
  4820. }
  4821. auto retVal = mModule->ReferenceStaticField(fieldInstance);
  4822. bool isStaticCtor = (mModule->mCurMethodInstance != NULL) &&
  4823. (mModule->mCurMethodInstance->mMethodDef->IsCtorOrInit()) &&
  4824. (mModule->mCurMethodInstance->mMethodDef->mIsStatic);
  4825. if ((mModule->mCompiler->mOptions.mRuntimeChecks) && (fieldInstance->IsAppendedObject()) && (!fieldDef->mIsStatic) && (!mModule->mBfIRBuilder->mIgnoreWrites) &&
  4826. (!mModule->IsSkippingExtraResolveChecks()))
  4827. {
  4828. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  4829. auto intPtrType = mModule->CreatePointerType(intType);
  4830. auto intPtrVal = mModule->mBfIRBuilder->CreateBitCast(retVal.mValue, mModule->mBfIRBuilder->MapType(intPtrType));
  4831. auto intVal = mModule->mBfIRBuilder->CreateLoad(intPtrVal);
  4832. auto oobBlock = mModule->mBfIRBuilder->CreateBlock("oob", true);
  4833. auto contBlock = mModule->mBfIRBuilder->CreateBlock("cont", true);
  4834. auto cmpRes = mModule->mBfIRBuilder->CreateCmpEQ(intVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4835. mModule->mBfIRBuilder->CreateCondBr(cmpRes, oobBlock, contBlock);
  4836. mModule->mBfIRBuilder->SetInsertPoint(oobBlock);
  4837. auto internalType = mModule->ResolveTypeDef(mModule->mCompiler->mInternalTypeDef);
  4838. auto oobFunc = mModule->GetMethodByName(internalType->ToTypeInstance(), "ThrowObjectNotInitialized");
  4839. if (oobFunc.mFunc)
  4840. {
  4841. if (mModule->mIsComptimeModule)
  4842. mModule->mCompiler->mCeMachine->QueueMethod(oobFunc.mMethodInstance, oobFunc.mFunc);
  4843. SizedArray<BfIRValue, 1> args;
  4844. args.push_back(mModule->GetConstValue(0));
  4845. mModule->mBfIRBuilder->CreateCall(oobFunc.mFunc, args);
  4846. mModule->mBfIRBuilder->CreateUnreachable();
  4847. }
  4848. else
  4849. {
  4850. mModule->Fail("System.Internal class must contain method 'ThrowObjectNotInitialized'", fieldDef->GetRefNode());
  4851. }
  4852. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  4853. }
  4854. if ((fieldDef->mIsReadOnly) && (!isStaticCtor))
  4855. {
  4856. if (retVal.IsAddr())
  4857. retVal.mKind = BfTypedValueKind_ReadOnlyAddr;
  4858. }
  4859. else
  4860. mIsHeapReference = true;
  4861. return retVal;
  4862. }
  4863. else if (!target)
  4864. {
  4865. if (((mBfEvalExprFlags & BfEvalExprFlags_NameOf) == 0) && (mModule->PreFail()))
  4866. {
  4867. if ((flags & BfLookupFieldFlag_CheckingOuter) != 0)
  4868. 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()),
  4869. targetSrc);
  4870. else if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  4871. {
  4872. if ((mBfEvalExprFlags & BfEvalExprFlags_DeclType) == 0)
  4873. mModule->Fail(StrFormat("Cannot reference field '%s' before append allocations", fieldDef->mName.c_str()), targetSrc);
  4874. }
  4875. else
  4876. mModule->Fail(StrFormat("Cannot reference non-static field '%s' from a static method", fieldDef->mName.c_str()), targetSrc);
  4877. }
  4878. return mModule->GetDefaultTypedValue(resolvedFieldType, false, BfDefaultValueKind_Addr);
  4879. }
  4880. if (resolvedFieldType->IsValuelessType())
  4881. {
  4882. return BfTypedValue(BfIRValue::sValueless, resolvedFieldType, true);
  4883. }
  4884. if ((mResultLocalVar != NULL) && (fieldInstance->mMergedDataIdx != -1))
  4885. {
  4886. if (mResultLocalVarFieldCount != 1)
  4887. {
  4888. fieldInstance->GetDataRange(mResultLocalVarField, mResultLocalVarFieldCount);
  4889. mResultLocalVarRefNode = targetSrc;
  4890. }
  4891. }
  4892. if ((typeInstance->IsIncomplete()) && (!typeInstance->mNeedsMethodProcessing))
  4893. {
  4894. BF_ASSERT(typeInstance->mTypeFailed || (mModule->mCurMethodState == NULL) || (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCompiler->IsAutocomplete()));
  4895. return mModule->GetDefaultTypedValue(resolvedFieldType);
  4896. }
  4897. bool isTemporary = target.IsTempAddr();
  4898. bool wantsLoadValue = false;
  4899. bool wantsReadOnly = false;
  4900. if ((fieldDef->mIsReadOnly) && (mModule->mCurMethodInstance != NULL) && ((!mModule->mCurMethodInstance->mMethodDef->IsCtorOrInit()) || (!target.IsThis())))
  4901. wantsReadOnly = true;
  4902. bool isComposite = target.mType->IsComposite();
  4903. if ((isComposite) && (!target.mType->IsTypedPrimitive()) && (!target.IsAddr()))
  4904. isTemporary = true;
  4905. if ((isComposite) && (!target.IsAddr()))
  4906. wantsLoadValue = true;
  4907. if ((target.mType->IsWrappableType()) && (!target.mType->IsPointer()))
  4908. {
  4909. BfTypeInstance* primStructType = mModule->GetWrappedStructType(target.mType);
  4910. BfIRValue allocaInst = mModule->CreateAlloca(primStructType, true, "tmpStruct");
  4911. BfIRValue elementAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  4912. mModule->mBfIRBuilder->CreateStore(target.mValue, elementAddr);
  4913. target = BfTypedValue(allocaInst, primStructType, true);
  4914. }
  4915. BfTypedValue targetValue;
  4916. if ((target.mType != typeInstance) && (!target.IsSplat()))
  4917. {
  4918. if ((!isComposite) || (target.IsAddr()))
  4919. targetValue = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  4920. else
  4921. {
  4922. BfIRValue curVal = target.mValue;
  4923. auto baseCheckType = target.mType->ToTypeInstance();
  4924. while (baseCheckType != typeInstance)
  4925. {
  4926. curVal = mModule->mBfIRBuilder->CreateExtractValue(curVal, 0);
  4927. baseCheckType = baseCheckType->mBaseType;
  4928. }
  4929. targetValue = BfTypedValue(curVal, typeInstance);
  4930. }
  4931. }
  4932. else
  4933. targetValue = target;
  4934. bool doAccessCheck = true;
  4935. if ((flags & BfLookupFieldFlag_BindOnly) != 0)
  4936. doAccessCheck = false;
  4937. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  4938. doAccessCheck = false;
  4939. if (target.IsThis())
  4940. {
  4941. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  4942. doAccessCheck = false;
  4943. }
  4944. if (doAccessCheck)
  4945. mModule->EmitObjectAccessCheck(target);
  4946. if (fieldInstance->mDataIdx < 0)
  4947. {
  4948. mModule->mCompiler->RequestExtraCompile();
  4949. mModule->InternalError("LoadField field DataIdx<0 where InstSize>0");
  4950. mModule->DeferRebuildType(typeInstance);
  4951. return mModule->GetDefaultTypedValue(resolvedFieldType);
  4952. }
  4953. BfTypedValue retVal;
  4954. if (targetValue.IsSplat())
  4955. {
  4956. retVal = mModule->ExtractValue(targetValue, fieldInstance, fieldInstance->mDataIdx);
  4957. }
  4958. else if ((target.mType->IsStruct()) && (!target.IsAddr()))
  4959. {
  4960. mModule->mBfIRBuilder->PopulateType(targetValue.mType);
  4961. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateExtractValue(targetValue.mValue, fieldInstance->mDataIdx/*, fieldDef->mName*/),
  4962. resolvedFieldType);
  4963. }
  4964. else
  4965. {
  4966. mModule->mBfIRBuilder->PopulateType(typeInstance);
  4967. if ((targetValue.IsAddr()) && (!typeInstance->IsValueType()))
  4968. targetValue = mModule->LoadValue(targetValue);
  4969. if (fieldInstance->IsAppendedObject())
  4970. {
  4971. auto elemPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(targetValue.mValue, 0, fieldInstance->mDataIdx);
  4972. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(elemPtr, mModule->mBfIRBuilder->MapType(resolvedFieldType)), resolvedFieldType);
  4973. }
  4974. else
  4975. {
  4976. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(targetValue.mValue, 0, fieldInstance->mDataIdx/*, fieldDef->mName*/),
  4977. resolvedFieldType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  4978. }
  4979. }
  4980. if (typeInstance->mIsUnion)
  4981. {
  4982. auto unionInnerType = typeInstance->GetUnionInnerType();
  4983. if (unionInnerType != resolvedFieldType)
  4984. {
  4985. BfTypedValue unionTypedValue = retVal;
  4986. unionTypedValue.mType = unionInnerType;
  4987. if (!unionTypedValue.IsAddr())
  4988. unionTypedValue = mModule->MakeAddressable(unionTypedValue);
  4989. BfIRType llvmPtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(resolvedFieldType));
  4990. retVal.mValue = mModule->mBfIRBuilder->CreateBitCast(unionTypedValue.mValue, llvmPtrType);
  4991. retVal.mKind = unionTypedValue.mKind;
  4992. }
  4993. }
  4994. if ((fieldDef->mIsVolatile) && (retVal.IsAddr()))
  4995. retVal.mKind = BfTypedValueKind_VolatileAddr;
  4996. if (wantsLoadValue)
  4997. retVal = mModule->LoadValue(retVal, NULL, mIsVolatileReference);
  4998. else
  4999. {
  5000. if ((wantsReadOnly) && (retVal.IsAddr()) && (!retVal.IsReadOnly()))
  5001. retVal.mKind = BfTypedValueKind_ReadOnlyAddr;
  5002. else if ((target.IsCopyOnMutate()) && (retVal.IsAddr()))
  5003. retVal.mKind = BfTypedValueKind_CopyOnMutateAddr_Derived;
  5004. mIsHeapReference = true;
  5005. }
  5006. if (isTemporary)
  5007. {
  5008. if (retVal.IsAddr())
  5009. retVal.mKind = BfTypedValueKind_TempAddr;
  5010. }
  5011. return retVal;
  5012. }
  5013. BfTypedValue BfExprEvaluator::LookupField(BfAstNode* targetSrc, BfTypedValue target, const StringImpl& fieldName, BfLookupFieldFlags flags)
  5014. {
  5015. if (target)
  5016. flags = (BfLookupFieldFlags)(flags | BfLookupFieldFlag_HasInstance);
  5017. if ((target.mType != NULL && (target.mType->IsGenericParam())))
  5018. {
  5019. auto genericParamType = (BfGenericParamType*)target.mType;
  5020. auto genericParamInst = mModule->GetGenericParamInstance(genericParamType);
  5021. if (target.mValue)
  5022. {
  5023. for (auto iface : genericParamInst->mInterfaceConstraints)
  5024. {
  5025. auto result = LookupField(targetSrc, BfTypedValue(target.mValue, iface), fieldName, flags);
  5026. if ((result) || (mPropDef != NULL))
  5027. {
  5028. return result;
  5029. }
  5030. }
  5031. }
  5032. bool isUnspecializedSection = false;
  5033. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  5034. isUnspecializedSection = (mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized);
  5035. else
  5036. isUnspecializedSection = (mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->IsUnspecializedType());
  5037. if (isUnspecializedSection)
  5038. {
  5039. auto origTarget = target;
  5040. if (genericParamInst->mTypeConstraint != NULL)
  5041. {
  5042. target.mType = genericParamInst->mTypeConstraint;
  5043. }
  5044. else
  5045. target.mType = mModule->mContext->mBfObjectType;
  5046. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  5047. {
  5048. target.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  5049. }
  5050. if (origTarget.mType->IsTypeGenericParam())
  5051. {
  5052. // Check for extern constraint in method generic params
  5053. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  5054. {
  5055. for (auto genericParam : mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams)
  5056. {
  5057. if (genericParam->mExternType == origTarget.mType)
  5058. {
  5059. if (genericParam->mTypeConstraint != NULL)
  5060. {
  5061. target.mType = genericParam->mTypeConstraint;
  5062. break;
  5063. }
  5064. }
  5065. }
  5066. }
  5067. }
  5068. if (target.mType->IsWrappableType())
  5069. target.mType = mModule->GetWrappedStructType(target.mType);
  5070. }
  5071. else
  5072. {
  5073. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  5074. {
  5075. //target.mType = mModule->ResolveGenericType(mResult.mType);
  5076. }
  5077. else if (genericParamInst->mTypeConstraint != NULL)
  5078. {
  5079. target = mModule->Cast(targetSrc, target, genericParamInst->mTypeConstraint);
  5080. BF_ASSERT(target);
  5081. }
  5082. else
  5083. {
  5084. // This shouldn't occur - this would infer that we are accessing a member of Object or something...
  5085. //target.mType = mModule->ResolveGenericType(mResult.mType);
  5086. }
  5087. }
  5088. }
  5089. if ((target.mType != NULL) && (IsVar(target.mType, (flags & BfLookupFieldFlag_BindOnly) != 0)))
  5090. return BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  5091. BfTypeInstance* startCheckType = mModule->mCurTypeInstance;
  5092. mPropDef = NULL;
  5093. mPropDefBypassVirtual = false;
  5094. if (target)
  5095. {
  5096. if ((!target.mType->IsValueType()) && (target.IsAddr()))
  5097. target = mModule->LoadValue(target);
  5098. if (target.mType->IsPrimitiveType())
  5099. {
  5100. auto primType = (BfPrimitiveType*)target.mType;
  5101. startCheckType = mModule->GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  5102. }
  5103. else
  5104. {
  5105. startCheckType = target.mType->ToTypeInstance();
  5106. if ((startCheckType == NULL) && (target.mType->IsPointer()))
  5107. {
  5108. startCheckType = ((BfPointerType*)target.mType)->mElementType->ToTypeInstance();
  5109. if ((startCheckType != NULL) && (!startCheckType->IsValueType()))
  5110. return BfTypedValue();
  5111. }
  5112. }
  5113. //BF_ASSERT(startCheckType != NULL);
  5114. }
  5115. else if (target.mType != NULL)
  5116. {
  5117. startCheckType = target.mType->ToTypeInstance();
  5118. }
  5119. if ((startCheckType != NULL) && (startCheckType->mBaseType == NULL))
  5120. {
  5121. if (startCheckType->mDefineState == BfTypeDefineState_ResolvingBaseType)
  5122. {
  5123. // Fixes cases where we have something like 'Base[Value]' as a base typeref
  5124. return BfTypedValue();
  5125. }
  5126. mModule->PopulateType(startCheckType, BfPopulateType_BaseType);
  5127. }
  5128. String findName;
  5129. int varSkipCount = 0;
  5130. if (fieldName.StartsWith('@'))
  5131. {
  5132. findName = fieldName;
  5133. while (findName.StartsWith('@'))
  5134. {
  5135. findName.Remove(0);
  5136. varSkipCount++;
  5137. }
  5138. }
  5139. else
  5140. findName.Reference(fieldName);
  5141. auto activeTypeDef = mModule->GetActiveTypeDef();
  5142. for (int pass = 0; pass < 2; pass++)
  5143. {
  5144. auto curCheckType = startCheckType;
  5145. bool isFailurePass = pass == 1;
  5146. if (isFailurePass)
  5147. flags = (BfLookupFieldFlags)(flags | BfLookupFieldFlag_IsFailurePass);
  5148. bool isBaseLookup = false;
  5149. while (curCheckType != NULL)
  5150. {
  5151. if (((flags & BfLookupFieldFlag_CheckingOuter) != 0) && ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0))
  5152. {
  5153. // Don't fully populateType for CheckingOuter - it carries a risk of an inadvertent data cycle
  5154. // Avoiding this could cause issues finding emitted statics/constants
  5155. }
  5156. else
  5157. {
  5158. bool isPopulatingType = false;
  5159. auto checkTypeState = mModule->mContext->mCurTypeState;
  5160. while (checkTypeState != NULL)
  5161. {
  5162. if (curCheckType == checkTypeState->mType)
  5163. {
  5164. isPopulatingType = true;
  5165. if (checkTypeState->mResolveKind == BfTypeState::ResolveKind_Attributes)
  5166. {
  5167. // Don't allow lookups yet
  5168. return BfTypedValue();
  5169. }
  5170. }
  5171. checkTypeState = checkTypeState->mPrevState;
  5172. }
  5173. if ((!isPopulatingType) && (curCheckType->mDefineState < Beefy::BfTypeDefineState_Defined))
  5174. {
  5175. // We MAY have emitted fields so we need to do this
  5176. mModule->mContext->mUnreifiedModule->PopulateType(curCheckType, Beefy::BfPopulateType_Interfaces_All);
  5177. }
  5178. }
  5179. curCheckType->mTypeDef->PopulateMemberSets();
  5180. BfFieldDef* nextField = NULL;
  5181. BfMemberSetEntry* entry;
  5182. if (curCheckType->mTypeDef->mFieldSet.TryGetWith(findName, &entry))
  5183. nextField = (BfFieldDef*)entry->mMemberDef;
  5184. if (nextField != NULL)
  5185. varSkipCount -= nextField->mNamePrefixCount;
  5186. while ((varSkipCount > 0) && (nextField != NULL))
  5187. {
  5188. nextField = nextField->mNextWithSameName;
  5189. varSkipCount--;
  5190. }
  5191. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  5192. if (target)
  5193. {
  5194. if ((flags & (BfLookupFieldFlag_IsImplicitThis | BfLookupFieldFlag_BaseLookup)) != 0)
  5195. {
  5196. // Not an "instance lookup"
  5197. }
  5198. else
  5199. {
  5200. protectionCheckFlags = (BfProtectionCheckFlags)(protectionCheckFlags | BfProtectionCheckFlag_InstanceLookup);
  5201. }
  5202. }
  5203. BfFieldDef* matchedField = NULL;
  5204. while (nextField != NULL)
  5205. {
  5206. if ((flags & BfLookupFieldFlag_BindOnly) != 0)
  5207. break;
  5208. auto field = nextField;
  5209. nextField = nextField->mNextWithSameName;
  5210. auto checkProtection = field->mProtection;
  5211. if (checkProtection == BfProtection_Hidden)
  5212. {
  5213. // Allow accessing hidden fields
  5214. checkProtection = BfProtection_Private;
  5215. }
  5216. if (((flags & BfLookupFieldFlag_IgnoreProtection) == 0) && (!isFailurePass) &&
  5217. (!mModule->CheckProtection(protectionCheckFlags, curCheckType, field->mDeclaringType->mProject, checkProtection, startCheckType)))
  5218. {
  5219. continue;
  5220. }
  5221. bool isResolvingFields = curCheckType->mResolvingConstField || curCheckType->mResolvingVarField;
  5222. if (curCheckType->mFieldInstances.IsEmpty())
  5223. {
  5224. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  5225. }
  5226. if (field->mIdx >= (int)curCheckType->mFieldInstances.size())
  5227. {
  5228. if (mModule->mCompiler->EnsureCeUnpaused(curCheckType))
  5229. {
  5230. BF_DBG_FATAL("OOB in DoLookupField");
  5231. }
  5232. return mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  5233. }
  5234. BF_ASSERT(field->mIdx < (int)curCheckType->mFieldInstances.size());
  5235. auto fieldInstance = &curCheckType->mFieldInstances[field->mIdx];
  5236. if (!fieldInstance->mFieldIncluded)
  5237. continue;
  5238. if (curCheckType->IsUnspecializedType())
  5239. {
  5240. // The check for non-unspecialized types is already handled in mFieldIncluded
  5241. if (!curCheckType->IsTypeMemberIncluded(field->mDeclaringType, activeTypeDef, mModule))
  5242. continue;
  5243. }
  5244. if (!mModule->IsInSpecializedSection())
  5245. {
  5246. if (!curCheckType->IsTypeMemberAccessible(field->mDeclaringType, activeTypeDef))
  5247. continue;
  5248. }
  5249. if (matchedField != NULL)
  5250. {
  5251. auto error = mModule->Fail(StrFormat("Ambiguous reference to field '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  5252. if (error != NULL)
  5253. {
  5254. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", matchedField->mDeclaringType->mProject->mName.c_str()), matchedField->mFieldDeclaration);
  5255. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", field->mDeclaringType->mProject->mName.c_str()), field->mFieldDeclaration);
  5256. break;
  5257. }
  5258. }
  5259. matchedField = field;
  5260. }
  5261. if (matchedField != NULL)
  5262. return LoadField(targetSrc, target, curCheckType, matchedField, flags);
  5263. BfPropertyDef* nextProp = NULL;
  5264. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(fieldName, &entry))
  5265. nextProp = (BfPropertyDef*)entry->mMemberDef;
  5266. if (nextProp != NULL)
  5267. {
  5268. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  5269. bool isInlined = false;
  5270. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  5271. {
  5272. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  5273. {
  5274. isInlined = true;
  5275. mModule->mAttributeState->mUsed = true;
  5276. }
  5277. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  5278. {
  5279. checkedKind = BfCheckedKind_Checked;
  5280. mModule->mAttributeState->mUsed = true;
  5281. }
  5282. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  5283. {
  5284. checkedKind = BfCheckedKind_Unchecked;
  5285. mModule->mAttributeState->mUsed = true;
  5286. }
  5287. }
  5288. BfPropertyDef* matchedProp = NULL;
  5289. while (nextProp != NULL)
  5290. {
  5291. auto prop = nextProp;
  5292. nextProp = nextProp->mNextWithSameName;
  5293. if ((!isFailurePass) && ((mBfEvalExprFlags & BfEvalExprFlags_NameOf) == 0) && (!mModule->CheckProtection(protectionCheckFlags, curCheckType, prop->mDeclaringType->mProject, prop->mProtection, startCheckType)))
  5294. {
  5295. continue;
  5296. }
  5297. if (!prop->mMethods.IsEmpty())
  5298. {
  5299. BfMethodDef* checkMethod = prop->mMethods[0];
  5300. // Properties with explicit interfaces or marked as overrides can only be called indirectly
  5301. if ((checkMethod->mExplicitInterface != NULL) || (checkMethod->mIsOverride))
  5302. continue;
  5303. }
  5304. if ((!target.IsStatic()) || (prop->mIsStatic) || ((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0))
  5305. {
  5306. if (!curCheckType->IsTypeMemberIncluded(prop->mDeclaringType, activeTypeDef, mModule))
  5307. continue;
  5308. if (!mModule->IsInSpecializedSection())
  5309. {
  5310. if (!curCheckType->IsTypeMemberAccessible(prop->mDeclaringType, mModule->GetVisibleProjectSet()))
  5311. continue;
  5312. }
  5313. if (matchedProp != NULL)
  5314. {
  5315. if ((matchedProp->mDeclaringType->IsExtension()) && (!prop->mDeclaringType->IsExtension()))
  5316. {
  5317. // Prefer non-extension
  5318. continue;
  5319. }
  5320. else
  5321. {
  5322. if (mModule->PreFail())
  5323. {
  5324. auto error = mModule->Fail(StrFormat("Ambiguous reference to property '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  5325. if (error != NULL)
  5326. {
  5327. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", matchedProp->mDeclaringType->mProject->mName.c_str()), matchedProp->mFieldDeclaration);
  5328. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", prop->mDeclaringType->mProject->mName.c_str()), prop->mFieldDeclaration);
  5329. break;
  5330. }
  5331. }
  5332. }
  5333. }
  5334. matchedProp = prop;
  5335. }
  5336. }
  5337. if (matchedProp != NULL)
  5338. return LoadProperty(targetSrc, target, curCheckType, matchedProp, flags, checkedKind, isInlined);
  5339. }
  5340. if (curCheckType->mTypeDef->mHasUsingFields)
  5341. mModule->PopulateUsingFieldData(curCheckType);
  5342. ///
  5343. {
  5344. Array<SizedArray<BfUsingFieldData::MemberRef, 1>*> foundLists;
  5345. auto _CheckUsingData = [&](BfUsingFieldData* usingData)
  5346. {
  5347. BfUsingFieldData::Entry* entry = NULL;
  5348. if (!usingData->mEntries.TryGetValue(findName, &entry))
  5349. return;
  5350. for (int listIdx = 0; listIdx < entry->mLookups.mSize; listIdx++)
  5351. {
  5352. bool passesProtection = true;
  5353. auto& entryList = entry->mLookups[listIdx];
  5354. for (int entryIdx = 0; entryIdx < entryList.mSize; entryIdx++)
  5355. {
  5356. auto& entry = entryList[entryIdx];
  5357. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  5358. if (!mModule->CheckProtection(protectionCheckFlags, entry.mTypeInstance, entry.GetDeclaringType(mModule)->mProject,
  5359. (entryIdx < entryList.mSize - 1) ? entry.GetUsingProtection() : entry.GetProtection(), curCheckType))
  5360. {
  5361. passesProtection = false;
  5362. break;
  5363. }
  5364. }
  5365. if (!passesProtection)
  5366. continue;
  5367. if (foundLists.mSize == 0)
  5368. {
  5369. foundLists.Add(&entryList);
  5370. }
  5371. else
  5372. {
  5373. if (entryList.mSize < foundLists[0]->mSize)
  5374. {
  5375. // New is shorter
  5376. foundLists.Clear();
  5377. foundLists.Add(&entryList);
  5378. }
  5379. else if (entryList.mSize > foundLists[0]->mSize)
  5380. {
  5381. // Ignore longer
  5382. }
  5383. else
  5384. {
  5385. foundLists.Add(&entryList);
  5386. }
  5387. }
  5388. }
  5389. };
  5390. if ((curCheckType->mTypeInfoEx != NULL) && (curCheckType->mTypeInfoEx->mUsingFieldData != NULL))
  5391. _CheckUsingData(curCheckType->mTypeInfoEx->mUsingFieldData);
  5392. if (!foundLists.IsEmpty())
  5393. {
  5394. auto foundList = foundLists[0];
  5395. if (foundLists.mSize > 1)
  5396. {
  5397. BfError* error = mModule->Fail("Ambiguous 'using' field reference", targetSrc);
  5398. if (error != NULL)
  5399. {
  5400. for (auto checkList : foundLists)
  5401. {
  5402. String errorStr = "'";
  5403. for (int entryIdx = 0; entryIdx < checkList->mSize; entryIdx++)
  5404. {
  5405. if (entryIdx == 0)
  5406. errorStr += (*checkList)[entryIdx].GetFullName(mModule);
  5407. else
  5408. {
  5409. errorStr += ".";
  5410. errorStr += (*checkList)[entryIdx].GetName(mModule);
  5411. }
  5412. }
  5413. errorStr += "' is a candidate";
  5414. mModule->mCompiler->mPassInstance->MoreInfo(errorStr, (*checkList)[0].GetRefNode(mModule));
  5415. }
  5416. }
  5417. }
  5418. BfTypedValue curResult = target;
  5419. for (int entryIdx = 0; entryIdx < foundList->mSize; entryIdx++)
  5420. {
  5421. if ((entryIdx == 0) && (foundList->back().IsStatic()))
  5422. entryIdx = (int)foundList->mSize - 1;
  5423. auto& entry = (*foundList)[entryIdx];
  5424. if (mPropDef != NULL)
  5425. {
  5426. SetAndRestoreValue<BfTypedValue> prevResult(mResult, BfTypedValue());
  5427. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_Friend);
  5428. curResult = GetResult();
  5429. if (!curResult)
  5430. return curResult;
  5431. }
  5432. auto useFlags = flags;
  5433. if (entryIdx < foundList->mSize - 1)
  5434. useFlags = (BfLookupFieldFlags)(flags | BfLookupFieldFlag_IsAnonymous);
  5435. if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Field)
  5436. {
  5437. curResult = LoadField(targetSrc, curResult, entry.mTypeInstance, entry.mTypeInstance->mTypeDef->mFields[entry.mIdx], useFlags);
  5438. }
  5439. else if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Property)
  5440. {
  5441. curResult = LoadProperty(targetSrc, curResult, entry.mTypeInstance, entry.mTypeInstance->mTypeDef->mProperties[entry.mIdx], useFlags, BfCheckedKind_NotSet, false);
  5442. }
  5443. else if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Local)
  5444. {
  5445. auto localDef = mModule->mCurMethodState->mLocals[entry.mIdx];
  5446. curResult = LoadLocal(localDef);
  5447. }
  5448. if ((!curResult) && (mPropDef == NULL))
  5449. return curResult;
  5450. if (entryIdx == foundList->mSize - 1)
  5451. {
  5452. auto autoComplete = GetAutoComplete();
  5453. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetSrc)))
  5454. autoComplete->SetDefinitionLocation(entry.GetRefNode(mModule));
  5455. if ((autoComplete != NULL) && (autoComplete->CheckFixit(targetSrc)))
  5456. autoComplete->FixitAddFullyQualify(targetSrc, findName, *foundList);
  5457. }
  5458. }
  5459. return curResult;
  5460. }
  5461. }
  5462. isBaseLookup = true;
  5463. curCheckType = curCheckType->mBaseType;
  5464. }
  5465. }
  5466. auto outerTypeDef = mModule->GetOuterType(startCheckType);
  5467. if (outerTypeDef != NULL)
  5468. {
  5469. BfLookupFieldFlags newFlags = BfLookupFieldFlag_CheckingOuter;
  5470. if (((flags & BfLookupFieldFlag_HasInstance) != 0) &&
  5471. ((flags & BfLookupFieldFlag_IsImplicitThis) == 0))
  5472. newFlags = (BfLookupFieldFlags)(newFlags | BfLookupFieldFlag_HasInstance);
  5473. // Check statics in outer type
  5474. return LookupField(targetSrc, BfTypedValue(outerTypeDef), fieldName, newFlags);
  5475. }
  5476. return BfTypedValue();
  5477. }
  5478. void BfExprEvaluator::ResolveArgValues(BfResolvedArgs& resolvedArgs, BfResolveArgsFlags flags)
  5479. {
  5480. static int idx = 0;
  5481. idx++;
  5482. int curIdx = idx;
  5483. if (resolvedArgs.mArguments == NULL)
  5484. return;
  5485. int argCount = (int)resolvedArgs.mArguments->size();
  5486. if ((resolvedArgs.mCommas != NULL) && (resolvedArgs.mCommas->size() != 0) && (resolvedArgs.mCommas->size() >= resolvedArgs.mArguments->size()))
  5487. {
  5488. //mModule->FailAfter("Expression expected", resolvedArgs.mCommas->back());
  5489. argCount++;
  5490. }
  5491. BfAutoComplete* autoComplete = GetAutoComplete();
  5492. bool hadIgnoredFixits = false;
  5493. if (autoComplete != NULL)
  5494. {
  5495. hadIgnoredFixits = autoComplete->mIgnoreFixits;
  5496. if (flags & BfResolveArgsFlag_DeferFixits)
  5497. autoComplete->mIgnoreFixits = true;
  5498. }
  5499. int deferredArgIdx = 0;
  5500. SizedArray<BfExpression*, 8> deferredArgs;
  5501. int argIdx = 0;
  5502. while (true)
  5503. {
  5504. //printf("Args: %p %p %d\n", resolvedArgs.mArguments, resolvedArgs.mArguments->mVals, resolvedArgs.mArguments->mSize);
  5505. BfExpression* argExpr = NULL;
  5506. bool isDeferredArg = false;
  5507. int curArgIdx = -1;
  5508. if (deferredArgIdx < deferredArgs.size())
  5509. {
  5510. argExpr = deferredArgs[deferredArgIdx++];
  5511. isDeferredArg = true;
  5512. }
  5513. else if (argIdx >= argCount)
  5514. {
  5515. break;
  5516. }
  5517. else
  5518. {
  5519. curArgIdx = argIdx++;
  5520. if (curArgIdx < resolvedArgs.mArguments->size())
  5521. argExpr = (*resolvedArgs.mArguments)[curArgIdx];
  5522. }
  5523. if (argExpr == NULL)
  5524. {
  5525. if (curArgIdx == 0)
  5526. {
  5527. if (resolvedArgs.mOpenToken != NULL)
  5528. mModule->FailAfter("Expression expected", resolvedArgs.mOpenToken);
  5529. }
  5530. else if (resolvedArgs.mCommas != NULL)
  5531. mModule->FailAfter("Expression expected", (*resolvedArgs.mCommas)[curArgIdx - 1]);
  5532. }
  5533. if (auto typedValueExpr = BfNodeDynCast<BfTypedValueExpression>(argExpr))
  5534. {
  5535. BfResolvedArg resolvedArg;
  5536. resolvedArg.mTypedValue = typedValueExpr->mTypedValue;
  5537. if (resolvedArg.mTypedValue.IsParams())
  5538. resolvedArg.mArgFlags = BfArgFlag_ParamsExpr;
  5539. resolvedArg.mExpression = typedValueExpr->mRefNode;
  5540. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  5541. continue;
  5542. }
  5543. BfResolvedArg resolvedArg;
  5544. if (isDeferredArg)
  5545. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_StringInterpolateArg);
  5546. BfExprEvaluator exprEvaluator(mModule);
  5547. exprEvaluator.mResolveGenericParam = (flags & BfResolveArgsFlag_AllowUnresolvedTypes) == 0;
  5548. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr |
  5549. (mBfEvalExprFlags & (BfEvalExprFlags_Comptime)));
  5550. bool handled = false;
  5551. bool evaluated = false;
  5552. if (auto namedExpression = BfNodeDynCastExact<BfNamedExpression>(argExpr))
  5553. {
  5554. resolvedArg.mNameNode = namedExpression->mNameNode;
  5555. argExpr = namedExpression->mExpression;
  5556. }
  5557. if (auto interpolateExpr = BfNodeDynCastExact<BfStringInterpolationExpression>(argExpr))
  5558. {
  5559. if ((interpolateExpr->mAllocNode == NULL) || ((flags & BfResolveArgsFlag_InsideStringInterpolationAlloc) != 0))
  5560. {
  5561. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_StringInterpolateFormat);
  5562. for (auto innerExpr : interpolateExpr->mExpressions)
  5563. deferredArgs.Add(innerExpr);
  5564. }
  5565. }
  5566. if (auto unaryOpExpr = BfNodeDynCastExact<BfUnaryOperatorExpression>(argExpr))
  5567. {
  5568. if ((unaryOpExpr->mOp == BfUnaryOp_Cascade) && ((flags & BfResolveArgsFlag_FromIndexer) == 0))
  5569. {
  5570. if ((mBfEvalExprFlags & BfEvalExprFlags_InCascade) != 0)
  5571. mModule->Fail("Cascade already specified on call target", unaryOpExpr->mOpToken);
  5572. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_Cascade);
  5573. argExpr = unaryOpExpr->mExpression;
  5574. }
  5575. }
  5576. bool deferParamEval = false;
  5577. if ((flags & BfResolveArgsFlag_DeferParamEval) != 0)
  5578. {
  5579. if (argExpr != NULL)
  5580. {
  5581. BfDeferEvalChecker deferEvalChecker;
  5582. if ((flags & BfResolveArgsFlag_DeferStrings) != 0)
  5583. deferEvalChecker.mDeferStrings = true;
  5584. deferEvalChecker.mDeferDelegateBind = false;
  5585. deferEvalChecker.Check(argExpr);
  5586. deferParamEval = deferEvalChecker.mNeedsDeferEval;
  5587. }
  5588. }
  5589. if (deferParamEval)
  5590. {
  5591. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredEval);
  5592. handled = true;
  5593. }
  5594. else if (auto delegateBindExpression = BfNodeDynCast<BfDelegateBindExpression>(argExpr))
  5595. {
  5596. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DelegateBindAttempt);
  5597. handled = true;
  5598. }
  5599. else if (auto lambdaBindExpression = BfNodeDynCast<BfLambdaBindExpression>(argExpr))
  5600. {
  5601. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_LambdaBindAttempt);
  5602. handled = true;
  5603. }
  5604. else if (auto defaultExpr = BfNodeDynCast<BfDefaultExpression>(argExpr))
  5605. {
  5606. if (defaultExpr->mTypeRef == NULL)
  5607. {
  5608. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UntypedDefault);
  5609. handled = true;
  5610. }
  5611. }
  5612. else if (auto varDeclExpr = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  5613. {
  5614. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  5615. handled = true;
  5616. }
  5617. else if (auto unaryExpr = BfNodeDynCast<BfUnaryOperatorExpression>(argExpr))
  5618. {
  5619. if (unaryExpr->mOp == BfUnaryOp_Params)
  5620. {
  5621. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ParamsExpr);
  5622. }
  5623. }
  5624. else if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(argExpr))
  5625. {
  5626. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UninitializedExpr);
  5627. handled = true;
  5628. }
  5629. if (!handled)
  5630. {
  5631. BfAstNode* checkArgExpr = argExpr;
  5632. while (checkArgExpr != NULL)
  5633. {
  5634. if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(checkArgExpr))
  5635. {
  5636. if (memberRef->mTarget == NULL)
  5637. {
  5638. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  5639. handled = true;
  5640. break;
  5641. }
  5642. else
  5643. checkArgExpr = memberRef->mTarget;
  5644. }
  5645. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(checkArgExpr))
  5646. {
  5647. checkArgExpr = invokeExpr->mTarget;
  5648. }
  5649. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkArgExpr))
  5650. {
  5651. checkArgExpr = parenExpr->mExpression;
  5652. }
  5653. else
  5654. break;
  5655. }
  5656. }
  5657. if ((argExpr != NULL) && (!handled))
  5658. {
  5659. bool deferParamValues = (flags & BfResolveArgsFlag_DeferParamValues) != 0;
  5660. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || deferParamValues);
  5661. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  5662. if (deferParamValues)
  5663. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredValue);
  5664. if (!evaluated)
  5665. {
  5666. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  5667. if ((resolvedArg.mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  5668. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_StringInterpolateFormat);
  5669. int lastLocalVarIdx = (mModule->mCurMethodState != NULL) ? mModule->mCurMethodState->mLocals.mSize : 0;
  5670. exprEvaluator.Evaluate(argExpr, false, false, true);
  5671. if ((deferParamValues) && (mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mLocals.mSize > lastLocalVarIdx))
  5672. {
  5673. // Remove any ignored locals
  5674. mModule->RestoreScoreState_LocalVariables(lastLocalVarIdx);
  5675. }
  5676. }
  5677. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  5678. {
  5679. auto localVar = exprEvaluator.mResultLocalVar;
  5680. int fieldIdx = mResultLocalVarField - 1;
  5681. auto methodState = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  5682. if (localVar->mCompositeCount >= 0)
  5683. {
  5684. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) != 0)
  5685. {
  5686. for (int compositeIdx = 0; compositeIdx < localVar->mCompositeCount; compositeIdx++)
  5687. {
  5688. BfResolvedArg compositeResolvedArg;
  5689. auto compositeLocalVar = methodState->mLocals[localVar->mLocalVarIdx + compositeIdx + 1];
  5690. auto argValue = exprEvaluator.LoadLocal(compositeLocalVar, true);
  5691. if (argValue)
  5692. {
  5693. if (!argValue.mType->IsStruct())
  5694. argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  5695. }
  5696. resolvedArg.mTypedValue = argValue;
  5697. resolvedArg.mExpression = argExpr;
  5698. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_FromParamComposite);
  5699. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  5700. exprEvaluator.mIsVolatileReference = false;
  5701. }
  5702. if ((localVar->mResolvedType->IsModifiedTypeType()) && (((BfModifiedTypeType*)localVar->mResolvedType)->mModifiedKind == BfToken_Params))
  5703. {
  5704. // Is a 'params'
  5705. }
  5706. else
  5707. continue;
  5708. }
  5709. else
  5710. exprEvaluator.mResult = mModule->LoadOrAggregateValue(exprEvaluator.mResult);
  5711. }
  5712. }
  5713. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  5714. auto argValue = exprEvaluator.mResult;
  5715. if (argValue)
  5716. {
  5717. mModule->mBfIRBuilder->PopulateType(argValue.mType);
  5718. resolvedArg.mResolvedType = argValue.mType;
  5719. if (resolvedArg.mResolvedType->IsRef())
  5720. argValue.mKind = BfTypedValueKind_Value;
  5721. if (exprEvaluator.mIsVolatileReference)
  5722. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_Volatile);
  5723. }
  5724. resolvedArg.mUncastedTypedValue = argValue;
  5725. resolvedArg.mTypedValue = argValue;
  5726. if (deferParamValues)
  5727. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  5728. }
  5729. resolvedArg.mExpression = argExpr;
  5730. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  5731. }
  5732. if (autoComplete != NULL)
  5733. autoComplete->mIgnoreFixits = hadIgnoredFixits;
  5734. }
  5735. void BfExprEvaluator::PerformCallChecks(BfMethodInstance* methodInstance, BfAstNode* targetSrc)
  5736. {
  5737. BfCustomAttributes* customAttributes = methodInstance->GetCustomAttributes();
  5738. if (customAttributes != NULL)
  5739. mModule->CheckErrorAttributes(methodInstance->GetOwner(), methodInstance, NULL, customAttributes, targetSrc);
  5740. }
  5741. void BfExprEvaluator::CheckSkipCall(BfAstNode* targetSrc, SizedArrayImpl<BfResolvedArg>& argValues)
  5742. {
  5743. for (auto& argValue : argValues)
  5744. {
  5745. if ((!argValue.IsDeferredValue()) && (argValue.mExpression != NULL))
  5746. {
  5747. mModule->Fail("Illegal SkipCall invocation", targetSrc);
  5748. return;
  5749. }
  5750. }
  5751. }
  5752. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, BfMethodInstance* methodInstance, BfIRValue func, bool bypassVirtual, SizedArrayImpl<BfIRValue>& irArgs, BfTypedValue* sret, BfCreateCallFlags callFlags, BfType* origTargetType)
  5753. {
  5754. // static int sCallIdx = 0;
  5755. // if (!mModule->mCompiler->mIsResolveOnly)
  5756. // sCallIdx++;
  5757. // int callIdx = sCallIdx;
  5758. // if (callIdx == 0x000000E8)
  5759. // {
  5760. // NOP;
  5761. // }
  5762. auto methodDef = methodInstance->mMethodDef;
  5763. BfIRValue funcCallInst = func;
  5764. auto importCallKind = methodInstance->GetImportCallKind();
  5765. if ((funcCallInst) && (importCallKind != BfImportCallKind_None))
  5766. {
  5767. if ((funcCallInst.IsFake()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  5768. {
  5769. mModule->mFuncReferences.TryGetValue(methodInstance, &funcCallInst);
  5770. }
  5771. if ((importCallKind == BfImportCallKind_GlobalVar) &&
  5772. (methodInstance->mHotMethod == NULL) &&
  5773. (mModule->mCompiler->IsHotCompile()))
  5774. {
  5775. // This may actually be a BfImportCallKind_GlobalVar_Hot, so check it...
  5776. mModule->CheckHotMethod(methodInstance, "");
  5777. importCallKind = methodInstance->GetImportCallKind();
  5778. }
  5779. if (importCallKind == BfImportCallKind_GlobalVar_Hot)
  5780. {
  5781. //TODO: Check against NULL for calling BfLoadSharedLibraries
  5782. auto checkVal = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  5783. BfIRBlock nullBlock = mModule->mBfIRBuilder->CreateBlock("importNull");
  5784. BfIRBlock doneBlock = mModule->mBfIRBuilder->CreateBlock("importLoad");
  5785. auto condVal = mModule->mBfIRBuilder->CreateIsNull(checkVal);
  5786. mModule->mBfIRBuilder->CreateCondBr(condVal, nullBlock, doneBlock);
  5787. mModule->mBfIRBuilder->AddBlock(nullBlock);
  5788. mModule->mBfIRBuilder->SetInsertPoint(nullBlock);
  5789. auto loadSharedLibsFunc = mModule->GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  5790. mModule->mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  5791. mModule->mBfIRBuilder->CreateBr(doneBlock);
  5792. mModule->mBfIRBuilder->AddBlock(doneBlock);
  5793. mModule->mBfIRBuilder->SetInsertPoint(doneBlock);
  5794. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  5795. }
  5796. else
  5797. {
  5798. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  5799. }
  5800. }
  5801. if ((methodInstance->GetOwner()->IsInstanceOf(mModule->mCompiler->mDeferredCallTypeDef)) &&
  5802. (methodInstance->mMethodDef->mName == "Cancel"))
  5803. {
  5804. if (mModule->mCurMethodState != NULL)
  5805. mModule->mCurMethodState->mCancelledDeferredCall = true;
  5806. }
  5807. if ((methodDef->mIsNoReturn) && ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) == 0))
  5808. {
  5809. mModule->mCurMethodState->SetHadReturn(true);
  5810. mModule->mCurMethodState->mLeftBlockUncond = true;
  5811. mModule->MarkScopeLeft(&mModule->mCurMethodState->mHeadScope, true);
  5812. }
  5813. if (mModule->mCurTypeInstance != NULL)
  5814. {
  5815. bool isVirtual = (methodInstance->mVirtualTableIdx != -1) && (!bypassVirtual);
  5816. mModule->AddDependency(methodInstance->mMethodInstanceGroup->mOwner, mModule->mCurTypeInstance, isVirtual ? BfDependencyMap::DependencyFlag_VirtualCall : BfDependencyMap::DependencyFlag_Calls);
  5817. mModule->AddCallDependency(methodInstance, bypassVirtual);
  5818. }
  5819. if (methodInstance->GetOwner()->IsUnspecializedType())
  5820. {
  5821. BF_ASSERT((!methodInstance->mIRFunction) || (methodInstance == mModule->mCurMethodInstance) || (methodInstance->mMethodDef->mIsLocalMethod));
  5822. }
  5823. if (mFunctionBindResult != NULL)
  5824. {
  5825. BF_ASSERT(mFunctionBindResult->mMethodInstance == NULL);
  5826. mFunctionBindResult->mMethodInstance = methodInstance;
  5827. for (auto arg : irArgs)
  5828. mFunctionBindResult->mIRArgs.push_back(arg);
  5829. }
  5830. BfType* origReturnType = methodInstance->mReturnType;
  5831. /*if (origReturnType->IsSelf())
  5832. {
  5833. origReturnType = methodInstance->GetOwner();
  5834. BF_ASSERT(origReturnType->IsInterface());
  5835. }*/
  5836. BfType* returnType = origReturnType;
  5837. BfTypedValue sretVal;
  5838. auto _GetDefaultReturnValue = [&]()
  5839. {
  5840. if (methodInstance->mVirtualTableIdx == -1)
  5841. {
  5842. if (methodInstance->GetOwner()->IsInterface())
  5843. {
  5844. // We're attempting to directly invoke a non-virtual interface method, if we're return an interface then
  5845. // it is a concrete interface
  5846. if (returnType->IsInterface())
  5847. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  5848. }
  5849. }
  5850. if ((returnType->IsVar()) && (mExpectingType != NULL))
  5851. returnType = mExpectingType;
  5852. if (returnType->IsRef())
  5853. {
  5854. auto result = mModule->GetDefaultTypedValue(returnType->GetUnderlyingType(), true, BfDefaultValueKind_Addr);
  5855. if (methodDef->mIsReadOnly)
  5856. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  5857. return result;
  5858. }
  5859. else
  5860. {
  5861. auto val = mModule->GetDefaultTypedValue(returnType, true, (GetStructRetIdx(methodInstance) != -1) ? BfDefaultValueKind_Addr : BfDefaultValueKind_Value);
  5862. if (val.mKind == BfTypedValueKind_Addr)
  5863. val.mKind = BfTypedValueKind_RestrictedTempAddr;
  5864. return val;
  5865. }
  5866. };
  5867. mModule->PopulateType(origReturnType, BfPopulateType_Data);
  5868. if (GetStructRetIdx(methodInstance) != -1)
  5869. {
  5870. // We need to ensure that mReceivingValue has the correct type, otherwise it's possible that a conversion operator needs to be applied
  5871. // This happens for returning Result<T>'s with a 'T' value
  5872. if ((sret == NULL) && (mReceivingValue != NULL) && (mReceivingValue->mType == returnType))
  5873. {
  5874. sretVal = *mReceivingValue;
  5875. sret = &sretVal;
  5876. auto ptrType = mModule->CreatePointerType(returnType);
  5877. if (returnType != sret->mType)
  5878. {
  5879. sret->mValue = mModule->mBfIRBuilder->CreateBitCast(sret->mValue, mModule->mBfIRBuilder->MapType(ptrType));
  5880. sret->mType = returnType;
  5881. }
  5882. mReceivingValue = NULL;
  5883. }
  5884. if (sret == NULL)
  5885. {
  5886. sretVal = BfTypedValue(mModule->CreateAlloca(returnType), returnType, BfTypedValueKind_RestrictedTempAddr);
  5887. sret = &sretVal;
  5888. }
  5889. }
  5890. else
  5891. {
  5892. BF_ASSERT(sret == NULL);
  5893. }
  5894. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  5895. {
  5896. if ((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0)
  5897. {
  5898. // We need to perform call such as Compiler.Mixin and String.ConstF
  5899. }
  5900. else
  5901. return _GetDefaultReturnValue();
  5902. }
  5903. BF_ASSERT(!methodInstance->mDisallowCalling);
  5904. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mAutoComplete != NULL))
  5905. {
  5906. bool wantQuickEval = true;
  5907. if (IsComptime())
  5908. {
  5909. auto autoComplete = mModule->mCompiler->mResolvePassData->mAutoComplete;
  5910. wantQuickEval =
  5911. ((autoComplete->mResolveType != BfResolveType_Autocomplete) &&
  5912. (autoComplete->mResolveType != BfResolveType_Autocomplete_HighPri) &&
  5913. (autoComplete->mResolveType != BfResolveType_GetResultString));
  5914. for (auto& entry : mModule->mCompiler->mResolvePassData->mEmitEmbedEntries)
  5915. {
  5916. if (entry.mValue.mCursorIdx >= 0)
  5917. {
  5918. // Needed for Go To Definition in Compiler.Mixin
  5919. wantQuickEval = false;
  5920. }
  5921. }
  5922. }
  5923. if (wantQuickEval)
  5924. {
  5925. // In an autocomplete pass we may have stale method references that need to be resolved
  5926. // in the full classify pass, and in the full classify pass while just refreshing internals, we
  5927. // may have NULL funcs temporarily. We simply skip generating the method call here.
  5928. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  5929. {
  5930. if (methodInstance->mReturnType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  5931. {
  5932. if ((mExpectingType != NULL) && (mExpectingType->IsSizedArray()))
  5933. {
  5934. return BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(mExpectingType)), mExpectingType);
  5935. }
  5936. }
  5937. auto returnType = methodInstance->mReturnType;
  5938. if ((returnType->IsVar()) && (mExpectingType != NULL))
  5939. returnType = mExpectingType;
  5940. if (methodInstance->mReturnType->IsValuelessType())
  5941. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  5942. return BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(returnType)), returnType);
  5943. }
  5944. BfTypedValue result;
  5945. if (sret != NULL)
  5946. result = *sret;
  5947. else
  5948. result = _GetDefaultReturnValue();
  5949. return result;
  5950. }
  5951. }
  5952. bool forceBind = false;
  5953. if (mModule->mCompiler->mCeMachine != NULL)
  5954. {
  5955. bool doConstReturn = false;
  5956. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  5957. {
  5958. if (mFunctionBindResult != NULL)
  5959. {
  5960. forceBind = true;
  5961. }
  5962. else if ((mBfEvalExprFlags & BfEvalExprFlags_InCascade) != 0)
  5963. {
  5964. mModule->Fail("Const evaluation not allowed with cascade operator", targetSrc);
  5965. }
  5966. else if (((methodInstance->mComptimeFlags & BfComptimeFlag_OnlyFromComptime) != 0) && (!mModule->mIsComptimeModule))
  5967. {
  5968. // This either generated an error already or this is just the non-const type check pass for a comptime-only method
  5969. doConstReturn = true;
  5970. }
  5971. else if ((mBfEvalExprFlags & BfEvalExprFlags_DisallowComptime) != 0)
  5972. {
  5973. doConstReturn = true;
  5974. }
  5975. else if (((callFlags & BfCreateCallFlags_GenericParamThis) != 0) && (methodInstance->GetOwner()->IsInterface()))
  5976. {
  5977. mModule->Warn(0, "Concrete method may fail to comptime during specialization", targetSrc);
  5978. doConstReturn = true;
  5979. }
  5980. else if (methodDef->mIsVirtual)
  5981. {
  5982. // This could only really be the case for a Type, since no other 'this' could qualify as const
  5983. }
  5984. else
  5985. {
  5986. CeEvalFlags evalFlags = CeEvalFlags_None;
  5987. if ((mBfEvalExprFlags & BfEvalExprFlags_NoCeRebuildFlags) != 0)
  5988. evalFlags = (CeEvalFlags)(evalFlags | CeEvalFlags_NoRebuild);
  5989. if ((mModule->mIsComptimeModule) && (mModule->mCompiler->mCeMachine->mDebugger != NULL) && (mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  5990. {
  5991. auto ceDbgState = mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState;
  5992. if ((ceDbgState->mDbgExpressionFlags & DwEvalExpressionFlag_AllowCalls) != 0)
  5993. {
  5994. ceDbgState->mHadSideEffects = true;
  5995. //SetAndRestoreValue<CeDebugger*> prevDebugger(mModule->mCompiler->mCeMachine->mDebugger, NULL);
  5996. evalFlags = (CeEvalFlags)(evalFlags | CeEvalFlags_DbgCall);
  5997. auto result = ceDbgState->mCeContext->Call(targetSrc, mModule, methodInstance, irArgs, evalFlags, mExpectingType);
  5998. if (result)
  5999. return result;
  6000. }
  6001. else
  6002. {
  6003. ceDbgState->mBlockedSideEffects = true;
  6004. }
  6005. }
  6006. else
  6007. {
  6008. CeCallSource ceCallSource(targetSrc);
  6009. ceCallSource.mOrigCalleeType = origTargetType;
  6010. auto constRet = mModule->mCompiler->mCeMachine->Call(ceCallSource, mModule, methodInstance, irArgs, evalFlags, mExpectingType);
  6011. if (constRet)
  6012. {
  6013. auto constant = mModule->mBfIRBuilder->GetConstant(constRet.mValue);
  6014. BF_ASSERT(!constRet.mType->IsVar());
  6015. return constRet;
  6016. }
  6017. if (mModule->mCompiler->mFastFinish)
  6018. {
  6019. if ((mModule->mCurMethodInstance == NULL) || (!mModule->mCurMethodInstance->mIsAutocompleteMethod))
  6020. {
  6021. // We didn't properly resolve this so queue for a rebuild later
  6022. mModule->DeferRebuildType(mModule->mCurTypeInstance);
  6023. }
  6024. }
  6025. doConstReturn = true;
  6026. }
  6027. }
  6028. }
  6029. else if (mModule->mIsComptimeModule)
  6030. {
  6031. //TODO: This meant that unspecialized types were not even allowed to have Init methods that called into themselves
  6032. // if (methodInstance->mIsUnspecialized)
  6033. // {
  6034. // doConstReturn = true;
  6035. // }
  6036. // else
  6037. {
  6038. mModule->mCompiler->mCeMachine->QueueMethod(methodInstance, func);
  6039. }
  6040. }
  6041. if (doConstReturn)
  6042. {
  6043. if ((returnType->IsVar()) && (mExpectingType != NULL))
  6044. returnType = mExpectingType;
  6045. if (returnType->IsRef())
  6046. {
  6047. return _GetDefaultReturnValue();
  6048. }
  6049. else
  6050. {
  6051. if (returnType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  6052. {
  6053. if ((mExpectingType != NULL) && (mExpectingType->IsUndefSizedArray()))
  6054. {
  6055. if (returnType->GetUnderlyingType() == mExpectingType->GetUnderlyingType())
  6056. return mModule->GetDefaultTypedValue(mExpectingType, true, BfDefaultValueKind_Undef);
  6057. }
  6058. }
  6059. if (methodInstance->mReturnType->IsValuelessType())
  6060. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  6061. return mModule->GetDefaultTypedValue(returnType, true, BfDefaultValueKind_Undef);
  6062. }
  6063. return _GetDefaultReturnValue();
  6064. }
  6065. }
  6066. if (!forceBind)
  6067. {
  6068. if (((!func) && (methodInstance->mIsUnspecialized)) || (mModule->mBfIRBuilder->mIgnoreWrites))
  6069. {
  6070. // We don't actually submit method calls for unspecialized methods
  6071. // - this includes all methods in unspecialized types
  6072. return _GetDefaultReturnValue();
  6073. }
  6074. }
  6075. if (methodInstance->mVirtualTableIdx != -1)
  6076. {
  6077. if ((!bypassVirtual) && (mDeferCallRef == NULL))
  6078. {
  6079. if ((methodDef->mIsOverride) && (mModule->mCurMethodInstance->mIsReified))
  6080. {
  6081. // Ensure that declaring method gets referenced
  6082. auto typeInstance = methodInstance->GetOwner();
  6083. auto& vEntry = typeInstance->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  6084. BfMethodInstance* declaringMethodInstance = vEntry.mDeclaringMethod;
  6085. if ((declaringMethodInstance->mMethodInstanceGroup->mOnDemandKind < BfMethodOnDemandKind_InWorkList) || (!declaringMethodInstance->mIsReified))
  6086. mModule->GetMethodInstance(declaringMethodInstance);
  6087. }
  6088. auto funcType = mModule->mBfIRBuilder->MapMethod(methodInstance);
  6089. auto funcPtrType1 = mModule->mBfIRBuilder->GetPointerTo(funcType);
  6090. auto funcPtrType2 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType1);
  6091. auto funcPtrType3 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType2);
  6092. auto funcPtrType4 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType3);
  6093. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  6094. {
  6095. if (mModule->mIsComptimeModule)
  6096. {
  6097. funcCallInst = mModule->mBfIRBuilder->Comptime_GetInterfaceFunc(irArgs[0], methodInstance->mMethodInstanceGroup->mOwner->mTypeId, methodInstance->mMethodDef->mIdx, funcPtrType1);
  6098. }
  6099. else
  6100. {
  6101. // IFace dispatch
  6102. auto ifaceTypeInst = methodInstance->mMethodInstanceGroup->mOwner;
  6103. BfIRValue slotOfs = mModule->GetInterfaceSlotNum(methodInstance->mMethodInstanceGroup->mOwner);
  6104. auto vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  6105. auto vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  6106. auto ifacePtrPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  6107. auto ifacePtr = mModule->mBfIRBuilder->CreateLoad(ifacePtrPtr);
  6108. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(ifacePtr, methodInstance->mVirtualTableIdx/*, "vfn"*/);
  6109. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  6110. }
  6111. }
  6112. else if (mModule->mIsComptimeModule)
  6113. {
  6114. funcCallInst = mModule->mBfIRBuilder->Comptime_GetVirtualFunc(irArgs[0], methodInstance->mVirtualTableIdx, funcPtrType1);
  6115. }
  6116. else
  6117. {
  6118. mModule->HadSlotCountDependency();
  6119. // Virtual dispatch
  6120. // int vDataIdx = 0;
  6121. // vDataIdx += 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots;
  6122. BfIRValue vDataPtr;
  6123. BfIRValue vDataIdx;
  6124. if ((mModule->mCompiler->mOptions.mHasVDataExtender) && (mModule->mCompiler->IsHotCompile()))
  6125. {
  6126. auto typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  6127. int extMethodIdx = (methodInstance->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  6128. if (extMethodIdx >= 0)
  6129. {
  6130. BF_ASSERT(mModule->mCompiler->IsHotCompile());
  6131. // We have grown outside our original virtual table, Load the new vdataPtr from the mHasVDataExtender
  6132. // vDataPtr = obj.vtable.extension.entry[curVersion]
  6133. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  6134. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr));
  6135. // The offset of the vExt is one past the base vtable. When a base class extends its virtual table, an entry
  6136. // for that new method is inserted in mVirtualMethodTable (thus increasing the index relative to GetBaseVTableSize()),
  6137. // but the actual written vtable position doesn't change, hence offsetting from GetOrigBaseVTableSize()
  6138. #ifdef _DEBUG
  6139. int vExtIdx = typeInst->GetImplBaseVTableSize();
  6140. BF_ASSERT(typeInst->mVirtualMethodTable[vExtIdx].mDeclaringMethod.mMethodNum == -1); // A type entry with a -1 mMethodNum means it's a vtable ext slot
  6141. #endif
  6142. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  6143. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, mModule->mCompiler->GetVDataPrefixDataCount() + mModule->mCompiler->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  6144. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, vExtOfs));
  6145. BfIRValue extendPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx);
  6146. vDataPtr = mModule->mBfIRBuilder->CreateLoad(extendPtr);
  6147. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, extMethodIdx);
  6148. }
  6149. else
  6150. {
  6151. // Map this new virtual index back to the original index
  6152. // Find the type instance that declared the original method
  6153. auto declTypeInst = typeInst;
  6154. while (declTypeInst->mBaseType != NULL)
  6155. {
  6156. mModule->PopulateType(declTypeInst->mBaseType, BfPopulateType_DataAndMethods);
  6157. if (methodInstance->mVirtualTableIdx >= declTypeInst->mBaseType->mVirtualMethodTableSize)
  6158. break;
  6159. BF_ASSERT(methodInstance->mMethodDef->mIsOverride);
  6160. declTypeInst = declTypeInst->mBaseType;
  6161. }
  6162. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  6163. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32,
  6164. (methodInstance->mVirtualTableIdx - declTypeInst->GetImplBaseVTableSize()) + declTypeInst->GetOrigImplBaseVTableSize()));
  6165. }
  6166. }
  6167. else
  6168. {
  6169. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  6170. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, methodInstance->mVirtualTableIdx));
  6171. }
  6172. if (!vDataPtr)
  6173. {
  6174. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType3);
  6175. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  6176. }
  6177. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx/*, "vfn"*/);
  6178. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  6179. }
  6180. }
  6181. }
  6182. else // non-virtual
  6183. {
  6184. if (methodInstance->GetOwner()->IsInterface())
  6185. {
  6186. // We're attempting to directly invoke a non-virtual interface method, this will happen during the unspecialized pass
  6187. // OR if we had an error and didn't find an implementing member in the actual target
  6188. if (((mModule->mCurMethodInstance == NULL) || (!mModule->mCurMethodInstance->mIsUnspecialized)) &&
  6189. (!mModule->mCurTypeInstance->IsInterface()))
  6190. mModule->AssertErrorState();
  6191. if (returnType->IsInterface())
  6192. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  6193. return _GetDefaultReturnValue();
  6194. }
  6195. }
  6196. if (mFunctionBindResult != NULL)
  6197. {
  6198. mFunctionBindResult->mFunc = funcCallInst;
  6199. if (irArgs.size() != 0)
  6200. {
  6201. auto targetType = methodInstance->mMethodInstanceGroup->mOwner;
  6202. if ((targetType->IsValueType()) && (targetType->IsSplattable()) && (!methodDef->HasNoThisSplat()) && (!IsComptime()))
  6203. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, BfTypedValueKind_SplatHead);
  6204. else
  6205. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, targetType->IsComposite() ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  6206. }
  6207. else
  6208. {
  6209. mFunctionBindResult->mTarget = BfTypedValue();
  6210. }
  6211. return BfTypedValue();
  6212. }
  6213. if (methodInstance->mReturnType == NULL)
  6214. {
  6215. mModule->AssertErrorState();
  6216. return BfTypedValue();
  6217. }
  6218. if (((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized)) && (mModule->mBfIRBuilder->mIgnoreWrites))
  6219. {
  6220. // Don't actually do the call - our target may be a generic param
  6221. return _GetDefaultReturnValue();
  6222. }
  6223. if (mDeferCallRef != NULL)
  6224. {
  6225. mModule->AddDeferredCall(BfModuleMethodInstance(methodInstance, func), irArgs, mDeferScopeAlloc, mDeferCallRef, bypassVirtual);
  6226. return mModule->GetFakeTypedValue(returnType);
  6227. }
  6228. if (!funcCallInst)
  6229. {
  6230. if ((mModule->HasCompiledOutput()) || (mModule->mCompiler->mOptions.mExtraResolveChecks))
  6231. {
  6232. // This can happen either from an error, or from the resolver while doing Internals_Changed processing
  6233. mModule->AssertErrorState();
  6234. }
  6235. return _GetDefaultReturnValue();
  6236. }
  6237. bool hasResult = !methodInstance->mReturnType->IsValuelessType();
  6238. BfIRValue firstArg;
  6239. if (irArgs.size() != 0)
  6240. firstArg = irArgs[0];
  6241. auto methodInstOwner = methodInstance->GetOwner();
  6242. auto expectCallingConvention = mModule->GetIRCallingConvention(methodInstance);
  6243. if ((methodInstOwner->IsFunction()) && (methodInstance->GetParamCount() > 0) && (methodInstance->GetParamName(0) == "this"))
  6244. {
  6245. auto paramType = methodInstance->GetParamType(0);
  6246. if (!paramType->IsValueType())
  6247. expectCallingConvention = BfIRCallingConv_ThisCall;
  6248. }
  6249. if ((methodInstance->mAlwaysInline) && (mModule->mCompiler->mOptions.mEmitLineInfo))
  6250. {
  6251. // Emit a NOP so we always have a "step over" point
  6252. mModule->EmitEnsureInstructionAt();
  6253. }
  6254. if (returnType->IsComposite())
  6255. mModule->mBfIRBuilder->PopulateType(returnType);
  6256. methodInstance->mMethodInstanceGroup->mHasEmittedReference = true;
  6257. BfIRValue callInst;
  6258. int callIRArgCount = (int)irArgs.size();
  6259. if (sret != NULL)
  6260. {
  6261. SizedArray<BfIRValue, 8> sretIRArgs;
  6262. int sretIdx = GetStructRetIdx(methodInstance);
  6263. int inIdx = 0;
  6264. for (int outIdx = 0; outIdx < irArgs.size() + 1; outIdx++)
  6265. {
  6266. if (outIdx == sretIdx)
  6267. {
  6268. sretIRArgs.Add(sret->mValue);
  6269. continue;
  6270. }
  6271. sretIRArgs.Add(irArgs[inIdx++]);
  6272. }
  6273. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, sretIRArgs);
  6274. callIRArgCount++;
  6275. }
  6276. else
  6277. {
  6278. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, irArgs);
  6279. if ((hasResult) && (!methodDef->mName.IsEmpty()) && (!methodInstance->mIsIntrinsic))
  6280. mModule->mBfIRBuilder->SetName(callInst, methodDef->mName);
  6281. }
  6282. if ((expectCallingConvention != BfIRCallingConv_CDecl) && (!methodInstance->mIsIntrinsic))
  6283. mModule->mBfIRBuilder->SetCallCallingConv(callInst, expectCallingConvention);
  6284. if ((methodDef->mIsNoReturn) && (!methodInstance->mIsIntrinsic))
  6285. mModule->mBfIRBuilder->Call_AddAttribute(callInst, -1, BfIRAttribute_NoReturn);
  6286. bool hadAttrs = false;
  6287. int paramIdx = 0;
  6288. bool doingThis = methodInstance->HasThis();
  6289. int argIdx = 0;
  6290. if (methodDef->mHasExplicitThis)
  6291. paramIdx++;
  6292. int paramCount = methodInstance->GetParamCount();
  6293. for ( ; argIdx < callIRArgCount ; )
  6294. {
  6295. if (methodInstance->mIsIntrinsic)
  6296. break;
  6297. if (argIdx == GetStructRetIdx(methodInstance))
  6298. {
  6299. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_StructRet);
  6300. argIdx++;
  6301. continue;
  6302. }
  6303. auto _HandleParamType = [&] (BfType* paramType)
  6304. {
  6305. if (paramType->IsStruct())
  6306. {
  6307. if ((!doingThis) || (!methodDef->mIsMutating && methodInstance->AllowsSplatting(paramIdx)))
  6308. {
  6309. BfTypeCode loweredTypeCode = BfTypeCode_None;
  6310. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  6311. if (paramType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  6312. {
  6313. argIdx++;
  6314. if (loweredTypeCode2 != BfTypeCode_None)
  6315. argIdx++;
  6316. return; // Lowering never requires attributes
  6317. }
  6318. }
  6319. }
  6320. int addDeref = -1;
  6321. if (paramType->IsRef())
  6322. {
  6323. auto refType = (BfRefType*)paramType;
  6324. auto elementType = refType->mElementType;
  6325. mModule->PopulateType(elementType, BfPopulateType_Data);
  6326. addDeref = elementType->mSize;
  6327. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  6328. mModule->AssertErrorState();
  6329. }
  6330. if ((paramType->IsComposite()) && (!paramType->IsTypedPrimitive()))
  6331. {
  6332. if (mModule->mCompiler->mOptions.mAllowStructByVal)
  6333. {
  6334. //byval
  6335. }
  6336. else
  6337. {
  6338. mModule->PopulateType(paramType, BfPopulateType_Data);
  6339. auto typeInst = paramType->ToTypeInstance();
  6340. if ((typeInst != NULL) && (typeInst->mIsCRepr) && (typeInst->IsSplattable()) && (!IsComptime()))
  6341. {
  6342. // We're splatting
  6343. }
  6344. else
  6345. {
  6346. if (doingThis)
  6347. {
  6348. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_NoCapture);
  6349. addDeref = paramType->mSize;
  6350. }
  6351. else if (methodInstance->WantsStructsAttribByVal(paramType))
  6352. {
  6353. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ByVal, mModule->mSystem->mPtrSize);
  6354. }
  6355. }
  6356. }
  6357. }
  6358. else if (paramType->IsPrimitiveType())
  6359. {
  6360. auto primType = (BfPrimitiveType*)paramType;
  6361. if ((primType->mTypeDef->mTypeCode == BfTypeCode_Boolean) && (!methodInstance->mIsIntrinsic))
  6362. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ZExt);
  6363. }
  6364. if (addDeref >= 0)
  6365. {
  6366. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  6367. }
  6368. argIdx++;
  6369. };
  6370. BfType* paramType = NULL;
  6371. if (doingThis)
  6372. {
  6373. int thisIdx = methodInstance->GetThisIdx();
  6374. paramType = methodInstance->GetThisType();
  6375. if (paramType->IsValuelessType())
  6376. {
  6377. doingThis = false;
  6378. continue;
  6379. }
  6380. bool isSplatted = methodInstance->GetParamIsSplat(thisIdx) && (!IsComptime()); // (resolvedTypeRef->IsSplattable()) && (!methodDef->mIsMutating);
  6381. if (isSplatted)
  6382. {
  6383. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  6384. doingThis = false;
  6385. continue;
  6386. }
  6387. else
  6388. _HandleParamType(paramType);
  6389. }
  6390. else
  6391. {
  6392. if (paramIdx >= methodInstance->GetParamCount())
  6393. break;
  6394. paramType = methodInstance->GetParamType(paramIdx);
  6395. BfTypeCode loweredTypeCode = BfTypeCode_None;
  6396. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  6397. if (paramType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  6398. {
  6399. argIdx++;
  6400. paramIdx++;
  6401. if (loweredTypeCode2 != BfTypeCode_None)
  6402. argIdx++;
  6403. continue;
  6404. }
  6405. if ((paramType->IsValuelessType()) && (!paramType->IsMethodRef()))
  6406. {
  6407. paramIdx++;
  6408. continue;
  6409. }
  6410. if ((methodInstance->GetParamIsSplat(paramIdx)) && (!IsComptime()))
  6411. {
  6412. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  6413. paramIdx++;
  6414. continue;
  6415. }
  6416. else
  6417. _HandleParamType(methodInstance->GetParamType(paramIdx));
  6418. }
  6419. if (doingThis)
  6420. doingThis = false;
  6421. else
  6422. paramIdx++;
  6423. //argIdx++;
  6424. }
  6425. if ((callFlags & BfCreateCallFlags_TailCall) != 0)
  6426. mModule->mBfIRBuilder->SetTailCall(callInst);
  6427. if (methodDef->mIsNoReturn)
  6428. {
  6429. mModule->mBfIRBuilder->CreateUnreachable();
  6430. // For debuggability when looking back at stack trace
  6431. //mModule->ExtendLocalLifetimes(0);
  6432. if (mModule->IsTargetingBeefBackend())
  6433. {
  6434. auto checkScope = mModule->mCurMethodState->mCurScope;
  6435. while (checkScope != NULL)
  6436. {
  6437. mModule->EmitLifetimeEnds(checkScope);
  6438. checkScope = checkScope->mPrevScope;
  6439. }
  6440. // This 'fake' branch extends lifetimes of outer variable scopes
  6441. if (mModule->mCurMethodState->mIRExitBlock)
  6442. mModule->mBfIRBuilder->CreateBr_Fake(mModule->mCurMethodState->mIRExitBlock);
  6443. }
  6444. }
  6445. else
  6446. {
  6447. if (mModule->mCurMethodState != NULL)
  6448. mModule->mCurMethodState->mMayNeedThisAccessCheck = true;
  6449. }
  6450. BfTypedValue result;
  6451. if (sret != NULL)
  6452. result = *sret;
  6453. else if (hasResult)
  6454. {
  6455. BfTypeCode loweredRetType = BfTypeCode_None;
  6456. BfTypeCode loweredRetType2 = BfTypeCode_None;
  6457. if ((!IsComptime()) && (methodInstance->GetLoweredReturnType(&loweredRetType, &loweredRetType2)) && (loweredRetType != BfTypeCode_None))
  6458. {
  6459. auto retVal = mModule->CreateAlloca(methodInstance->mReturnType);
  6460. BfIRType loweredIRType = mModule->GetIRLoweredType(loweredRetType, loweredRetType2);
  6461. loweredIRType = mModule->mBfIRBuilder->GetPointerTo(loweredIRType);
  6462. auto castedRetVal = mModule->mBfIRBuilder->CreateBitCast(retVal, loweredIRType);
  6463. mModule->mBfIRBuilder->CreateStore(callInst, castedRetVal);
  6464. result = BfTypedValue(retVal, methodInstance->mReturnType, BfTypedValueKind_RestrictedTempAddr);
  6465. }
  6466. else
  6467. result = BfTypedValue(callInst, methodInstance->mReturnType);
  6468. }
  6469. else
  6470. result = mModule->GetFakeTypedValue(methodInstance->mReturnType);
  6471. if (result.mType->IsRef())
  6472. {
  6473. result = mModule->RemoveRef(result);
  6474. if (methodDef->mIsReadOnly)
  6475. {
  6476. if (result.mKind == BfTypedValueKind_Addr)
  6477. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  6478. }
  6479. }
  6480. return result;
  6481. }
  6482. BfTypedValue BfExprEvaluator::CreateCall(BfMethodMatcher* methodMatcher, BfTypedValue target)
  6483. {
  6484. auto moduleMethodInstance = GetSelectedMethod(*methodMatcher);
  6485. if (moduleMethodInstance.mMethodInstance == NULL)
  6486. return BfTypedValue();
  6487. if ((target) && (target.mType != moduleMethodInstance.mMethodInstance->GetOwner()))
  6488. {
  6489. auto castedTarget = mModule->Cast(methodMatcher->mTargetSrc, target, moduleMethodInstance.mMethodInstance->GetOwner());
  6490. BF_ASSERT(castedTarget);
  6491. target = castedTarget;
  6492. }
  6493. PerformCallChecks(moduleMethodInstance.mMethodInstance, methodMatcher->mTargetSrc);
  6494. BfCreateCallFlags callFlags = BfCreateCallFlags_None;
  6495. if (methodMatcher->mAllowImplicitRef)
  6496. callFlags = (BfCreateCallFlags)(callFlags | BfCreateCallFlags_AllowImplicitRef);
  6497. return CreateCall(methodMatcher->mTargetSrc, target, BfTypedValue(), methodMatcher->mBestMethodDef, moduleMethodInstance, callFlags, methodMatcher->mArguments);
  6498. }
  6499. void BfExprEvaluator::MakeBaseConcrete(BfTypedValue& typedValue)
  6500. {
  6501. if (typedValue.IsBase())
  6502. {
  6503. auto baseType = mModule->mCurTypeInstance->mBaseType;
  6504. if (baseType == NULL)
  6505. baseType = mModule->mContext->mBfObjectType;
  6506. mModule->PopulateType(baseType, BfPopulateType_Data);
  6507. typedValue = mModule->Cast(NULL, typedValue, baseType, BfCastFlags_Explicit);
  6508. }
  6509. }
  6510. void BfExprEvaluator::SplatArgs(BfTypedValue value, SizedArrayImpl<BfIRValue>& irArgs)
  6511. {
  6512. if (value.IsSplat())
  6513. {
  6514. int componentIdx = 0;
  6515. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->ExtractSplatValue(value, componentIdx++, checkType)); }, value.mType);
  6516. return;
  6517. }
  6518. mModule->mBfIRBuilder->PopulateType(value.mType);
  6519. std::function<void(BfTypedValue)> checkTypeLambda = [&](BfTypedValue curValue)
  6520. {
  6521. BfType* checkType = curValue.mType;
  6522. if (checkType->IsStruct())
  6523. {
  6524. auto checkTypeInstance = checkType->ToTypeInstance();
  6525. if (checkTypeInstance->mBaseType != NULL)
  6526. mModule->PopulateType(checkTypeInstance->mBaseType);
  6527. if ((checkTypeInstance->mBaseType != NULL) && (!checkTypeInstance->mBaseType->IsValuelessType()))
  6528. {
  6529. BfTypedValue baseValue;
  6530. if (curValue.IsAddr())
  6531. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, 0), checkTypeInstance->mBaseType, true);
  6532. else
  6533. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateExtractValue(curValue.mValue, 0), checkTypeInstance->mBaseType);
  6534. checkTypeLambda(baseValue);
  6535. }
  6536. if (checkTypeInstance->mIsUnion)
  6537. {
  6538. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  6539. if (!unionInnerType->IsValuelessType())
  6540. {
  6541. BfTypedValue unionValue = mModule->ExtractValue(curValue, NULL, 1);
  6542. checkTypeLambda(unionValue);
  6543. }
  6544. if (checkTypeInstance->IsEnum())
  6545. {
  6546. BfTypedValue dscrValue = mModule->ExtractValue(curValue, NULL, 2);
  6547. checkTypeLambda(dscrValue);
  6548. }
  6549. }
  6550. else
  6551. {
  6552. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  6553. {
  6554. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  6555. if (fieldInstance->mDataIdx >= 0)
  6556. {
  6557. BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  6558. checkTypeLambda(fieldValue);
  6559. }
  6560. }
  6561. }
  6562. }
  6563. else if (checkType->IsMethodRef())
  6564. {
  6565. BF_ASSERT(curValue.IsAddr());
  6566. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  6567. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6568. {
  6569. auto checkType = methodRefType->GetCaptureType(dataIdx);
  6570. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6571. {
  6572. BF_ASSERT(dataIdx == 0);
  6573. auto ptrType = mModule->CreatePointerType(checkType);
  6574. auto elemPtr = mModule->mBfIRBuilder->CreateBitCast(curValue.mValue, mModule->mBfIRBuilder->MapType(ptrType));
  6575. checkTypeLambda(BfTypedValue(elemPtr, checkType, BfTypedValueKind_Addr));
  6576. //BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  6577. //checkTypeLambda(fieldValue);
  6578. }
  6579. else
  6580. {
  6581. auto elemVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, dataIdx);
  6582. if (!checkType->IsComposite())
  6583. elemVal = mModule->mBfIRBuilder->CreateLoad(elemVal);
  6584. irArgs.Add(elemVal);
  6585. //irArgs.Add(mModule->ExtractValue(curValue, dataIdx));
  6586. }
  6587. }
  6588. }
  6589. else if (!checkType->IsValuelessType())
  6590. {
  6591. auto loadedVal = mModule->LoadValue(curValue);
  6592. loadedVal = mModule->PrepareConst(loadedVal);
  6593. irArgs.push_back(loadedVal.mValue);
  6594. }
  6595. };
  6596. checkTypeLambda(value);
  6597. }
  6598. void BfExprEvaluator::PushArg(BfTypedValue argVal, SizedArrayImpl<BfIRValue>& irArgs, bool disableSplat, bool disableLowering, bool isIntrinsic, bool createCompositeCopy)
  6599. {
  6600. MakeBaseConcrete(argVal);
  6601. if (IsVar(argVal.mType))
  6602. {
  6603. argVal = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  6604. }
  6605. if (argVal.mType->IsValuelessNonOpaqueType())
  6606. return;
  6607. bool wantSplat = false;
  6608. if ((argVal.mType->IsSplattable()) && (!disableSplat) && (!IsComptime()))
  6609. {
  6610. disableLowering = true;
  6611. auto argTypeInstance = argVal.mType->ToTypeInstance();
  6612. if (!disableSplat)
  6613. {
  6614. if ((argTypeInstance != NULL) && (argTypeInstance->mIsCRepr))
  6615. wantSplat = true;
  6616. else if ((int)irArgs.size() + argVal.mType->GetSplatCount() <= mModule->mCompiler->mOptions.mMaxSplatRegs)
  6617. wantSplat = true;
  6618. }
  6619. }
  6620. if (wantSplat)
  6621. {
  6622. SplatArgs(argVal, irArgs);
  6623. }
  6624. else
  6625. {
  6626. if (argVal.mType->IsComposite())
  6627. {
  6628. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  6629. {
  6630. // Const eval entry - we want any incoming consts as they are
  6631. }
  6632. else if (isIntrinsic)
  6633. {
  6634. // We can handle composites either by value or not
  6635. }
  6636. else
  6637. argVal = mModule->MakeAddressable(argVal);
  6638. if ((!IsComptime()) && (!disableLowering) && (!isIntrinsic))
  6639. {
  6640. BfTypeCode loweredTypeCode = BfTypeCode_None;
  6641. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  6642. if (argVal.mType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  6643. {
  6644. BfIRValue argPtrVal = argVal.mValue;
  6645. int loweredSize = mModule->mBfIRBuilder->GetSize(loweredTypeCode) + mModule->mBfIRBuilder->GetSize(loweredTypeCode2);
  6646. if (argVal.mType->mSize < loweredSize)
  6647. {
  6648. auto allocaVal = mModule->CreateAlloca(mModule->GetPrimitiveType(BfTypeCode_UInt8), true, NULL, mModule->GetConstValue(loweredSize));
  6649. mModule->mBfIRBuilder->SetAllocaAlignment(allocaVal,
  6650. BF_MAX(argVal.mType->mAlign,
  6651. BF_MAX(mModule->mBfIRBuilder->GetSize(loweredTypeCode), mModule->mBfIRBuilder->GetSize(loweredTypeCode2))));
  6652. auto castedPtr = mModule->mBfIRBuilder->CreateBitCast(allocaVal, mModule->mBfIRBuilder->MapType(mModule->CreatePointerType(argVal.mType)));
  6653. auto argIRVal = mModule->mBfIRBuilder->CreateAlignedLoad(argVal.mValue, argVal.mType->mAlign);
  6654. mModule->mBfIRBuilder->CreateAlignedStore(argIRVal, castedPtr, argVal.mType->mAlign);
  6655. argPtrVal = castedPtr;
  6656. }
  6657. auto primType = mModule->mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  6658. auto ptrType = mModule->mBfIRBuilder->GetPointerTo(primType);
  6659. BfIRValue primPtrVal = mModule->mBfIRBuilder->CreateBitCast(argPtrVal, ptrType);
  6660. auto primVal = mModule->mBfIRBuilder->CreateLoad(primPtrVal);
  6661. irArgs.push_back(primVal);
  6662. if (loweredTypeCode2 != BfTypeCode_None)
  6663. {
  6664. auto primType2 = mModule->mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  6665. auto ptrType2 = mModule->mBfIRBuilder->GetPointerTo(primType2);
  6666. BfIRValue primPtrVal2;
  6667. if (mModule->mBfIRBuilder->GetSize(loweredTypeCode) < mModule->mBfIRBuilder->GetSize(loweredTypeCode2))
  6668. primPtrVal2 = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->CreateBitCast(primPtrVal, ptrType2), 1);
  6669. else
  6670. primPtrVal2 = mModule->mBfIRBuilder->CreateBitCast(mModule->mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), ptrType2);
  6671. auto primVal2 = mModule->mBfIRBuilder->CreateLoad(primPtrVal2);
  6672. irArgs.Add(primVal2);
  6673. }
  6674. return;
  6675. }
  6676. }
  6677. if ((createCompositeCopy) && (!argVal.IsTempAddr()))
  6678. {
  6679. // Non-Beef calling conventions require copies of composites
  6680. auto copyAddr = mModule->CreateAlloca(argVal.mType);
  6681. mModule->mBfIRBuilder->CreateStore(mModule->LoadValue(argVal).mValue, copyAddr);
  6682. argVal = BfTypedValue(copyAddr, argVal.mType, BfTypedValueKind_TempAddr);
  6683. }
  6684. }
  6685. else
  6686. argVal = mModule->LoadValue(argVal);
  6687. irArgs.Add(argVal.mValue);
  6688. }
  6689. }
  6690. void BfExprEvaluator::PushThis(BfAstNode* targetSrc, BfTypedValue argVal, BfMethodInstance* methodInstance, SizedArrayImpl<BfIRValue>& irArgs, bool skipMutCheck)
  6691. {
  6692. MakeBaseConcrete(argVal);
  6693. auto methodDef = methodInstance->mMethodDef;
  6694. if (methodInstance->IsSkipCall())
  6695. return;
  6696. if (!argVal)
  6697. {
  6698. //BF_ASSERT(mFunctionBindResult != NULL);
  6699. return;
  6700. }
  6701. if (methodDef->mIsMutating)
  6702. {
  6703. bool checkMut = false;
  6704. if (argVal.mType->IsGenericParam())
  6705. {
  6706. // For capturing mutability
  6707. if (mResultLocalVar != NULL)
  6708. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  6709. }
  6710. if (((argVal.mType->IsComposite()) || (argVal.mType->IsTypedPrimitive())))
  6711. {
  6712. if (argVal.IsCopyOnMutate())
  6713. argVal = mModule->CopyValue(argVal);
  6714. if ((argVal.IsReadOnly()) || (!argVal.IsAddr()))
  6715. {
  6716. if (!skipMutCheck)
  6717. {
  6718. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(methodInstance).c_str());
  6719. CheckModifyResult(argVal, targetSrc, err.c_str());
  6720. }
  6721. if (argVal.IsSplat())
  6722. {
  6723. argVal = mModule->AggregateSplat(argVal);
  6724. argVal = mModule->MakeAddressable(argVal);
  6725. }
  6726. }
  6727. else
  6728. {
  6729. if (mResultLocalVar != NULL)
  6730. {
  6731. // When we are capturing, we need to note that we require capturing by reference here
  6732. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  6733. }
  6734. }
  6735. }
  6736. }
  6737. if (argVal.mType->IsValuelessNonOpaqueType())
  6738. return;
  6739. auto owner = methodInstance->GetOwner();
  6740. bool allowThisSplatting;
  6741. if (mModule->mIsComptimeModule)
  6742. allowThisSplatting = owner->IsTypedPrimitive() || owner->IsValuelessNonOpaqueType();
  6743. else
  6744. allowThisSplatting = methodInstance->AllowsSplatting(-1);
  6745. if ((!allowThisSplatting) || (methodDef->mIsMutating) || (methodInstance->mCallingConvention == BfCallingConvention_Cdecl))
  6746. {
  6747. argVal = mModule->MakeAddressable(argVal);
  6748. irArgs.push_back(argVal.mValue);
  6749. return;
  6750. }
  6751. auto thisType = methodInstance->GetThisType();
  6752. PushArg(argVal, irArgs, !methodInstance->AllowsSplatting(-1), thisType->IsPointer());
  6753. }
  6754. void BfExprEvaluator::FinishDeferredEvals(SizedArrayImpl<BfResolvedArg>& argValues)
  6755. {
  6756. for (int argIdx = 0; argIdx < argValues.size(); argIdx++)
  6757. {
  6758. auto& argValue = argValues[argIdx].mTypedValue;
  6759. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  6760. {
  6761. if (!argValue)
  6762. {
  6763. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  6764. if (expr != NULL)
  6765. argValue = mModule->CreateValueFromExpression(expr, argValues[argIdx].mExpectedType, BfEvalExprFlags_NoCast);
  6766. }
  6767. }
  6768. }
  6769. }
  6770. void BfExprEvaluator::FinishDeferredEvals(BfResolvedArgs& argValues)
  6771. {
  6772. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  6773. {
  6774. auto& argValue = argValues.mResolvedArgs[argIdx].mTypedValue;
  6775. if ((argValues.mResolvedArgs[argIdx].mArgFlags & (BfArgFlag_VariableDeclaration)) != 0)
  6776. {
  6777. auto variableDeclaration = BfNodeDynCast<BfVariableDeclaration>((*argValues.mArguments)[argIdx]);
  6778. if ((variableDeclaration != NULL) && (variableDeclaration->mNameNode != NULL))
  6779. {
  6780. if (mModule->mCurMethodState == NULL)
  6781. {
  6782. mModule->Fail("Illegal local variable", variableDeclaration);
  6783. }
  6784. else
  6785. {
  6786. BfLocalVariable* localVar = new BfLocalVariable();
  6787. localVar->mName = variableDeclaration->mNameNode->ToString();
  6788. localVar->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_Var);
  6789. localVar->mAddr = mModule->mBfIRBuilder->GetFakeVal();
  6790. localVar->mReadFromId = 0;
  6791. localVar->mWrittenToId = 0;
  6792. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  6793. mModule->CheckVariableDef(localVar);
  6794. localVar->Init();
  6795. mModule->AddLocalVariableDef(localVar, true);
  6796. auto curScope = mModule->mCurMethodState->mCurScope;
  6797. if (curScope->mScopeKind == BfScopeKind_StatementTarget)
  6798. {
  6799. // Move this variable into the parent scope
  6800. curScope->mLocalVarStart = (int)mModule->mCurMethodState->mLocals.size();
  6801. }
  6802. }
  6803. }
  6804. }
  6805. }
  6806. FinishDeferredEvals(argValues.mResolvedArgs);
  6807. }
  6808. void BfExprEvaluator::AddCallDependencies(BfMethodInstance* methodInstance)
  6809. {
  6810. if (methodInstance->mReturnType != NULL)
  6811. mModule->AddDependency(methodInstance->mReturnType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  6812. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  6813. {
  6814. auto paramType = methodInstance->GetParamType(paramIdx);
  6815. mModule->AddDependency(paramType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  6816. }
  6817. if (methodInstance->mMethodInfoEx != NULL)
  6818. {
  6819. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  6820. {
  6821. if (genericArg->IsWrappableType())
  6822. genericArg = mModule->GetWrappedStructType(genericArg);
  6823. if (genericArg != NULL)
  6824. mModule->AddDependency(genericArg, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  6825. }
  6826. }
  6827. }
  6828. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, const BfTypedValue& inTarget, const BfTypedValue& origTarget, BfMethodDef* methodDef, BfModuleMethodInstance moduleMethodInstance, BfCreateCallFlags callFlags, SizedArrayImpl<BfResolvedArg>& argValues, BfTypedValue* argCascade)
  6829. {
  6830. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlag(mBfEvalExprFlags);
  6831. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mConstEvalAttributeTypeDef)))
  6832. {
  6833. mModule->mAttributeState->mUsed = true;
  6834. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  6835. }
  6836. else if ((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0)
  6837. {
  6838. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  6839. }
  6840. else if (((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_Comptime) != 0) && (!mModule->mIsComptimeModule))
  6841. {
  6842. if ((mModule->mCurMethodInstance == NULL) || (mModule->mCurMethodInstance->mComptimeFlags == BfComptimeFlag_None))
  6843. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  6844. }
  6845. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || IsConstEval());
  6846. if (((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_OnlyFromComptime) != 0) &&
  6847. ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) &&
  6848. ((mModule->mCurMethodInstance == NULL) || (mModule->mCurMethodInstance->mComptimeFlags == BfComptimeFlag_None)) &&
  6849. (!mModule->mIsComptimeModule))
  6850. {
  6851. 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);
  6852. }
  6853. bool bypassVirtual = (callFlags & BfCreateCallFlags_BypassVirtual) != 0;
  6854. bool skipThis = (callFlags & BfCreateCallFlags_SkipThis) != 0;;
  6855. static int sCallIdx = 0;
  6856. if (!mModule->mCompiler->mIsResolveOnly)
  6857. sCallIdx++;
  6858. int callIdx = sCallIdx;
  6859. if (callIdx == 0x000015CB)
  6860. {
  6861. NOP;
  6862. }
  6863. // Temporarily disable so we don't capture calls in params
  6864. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  6865. SetAndRestoreValue<bool> prevAllowVariableDeclarations;
  6866. if (mModule->mCurMethodState != NULL)
  6867. prevAllowVariableDeclarations.Init(mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations, false);
  6868. BfMethodInstance* methodInstance = moduleMethodInstance.mMethodInstance;
  6869. SizedArray<BfIRValue, 4> irArgs;
  6870. if ((methodDef->mIsAbstract) && (bypassVirtual))
  6871. {
  6872. mModule->Fail(StrFormat("Abstract base method '%s' cannot be invoked", mModule->MethodToString(methodInstance).c_str()), targetSrc);
  6873. }
  6874. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  6875. BfType* returnType = methodInstance->mReturnType;
  6876. /*if (returnType->IsSelf())
  6877. {
  6878. returnType = methodInstance->GetOwner();
  6879. BF_ASSERT(returnType->IsInterface());
  6880. }*/
  6881. Array<BfTypedValue> argCascades;
  6882. BfTypedValue target = inTarget;
  6883. if (!skipThis)
  6884. {
  6885. if ((target) && (target.mType->IsFunction()) && (methodInstance->GetOwner() == target.mType))
  6886. {
  6887. CheckResultForReading(target);
  6888. target = mModule->LoadValue(target);
  6889. auto funcType = mModule->mBfIRBuilder->MapMethod(moduleMethodInstance.mMethodInstance);
  6890. auto funcPtrType = mModule->mBfIRBuilder->GetPointerTo(funcType);
  6891. moduleMethodInstance.mFunc = mModule->mBfIRBuilder->CreateIntToPtr(target.mValue, funcPtrType);
  6892. }
  6893. else if (!methodDef->mIsStatic)
  6894. {
  6895. if ((!target) && (prevBindResult.mPrevVal != NULL))
  6896. {
  6897. auto bindResult = prevBindResult.mPrevVal;
  6898. if (bindResult->mBindType != NULL)
  6899. {
  6900. // Allow binding a function to a 'this' type even if no target is specified
  6901. auto delegateInfo = bindResult->mBindType->GetDelegateInfo();
  6902. if (delegateInfo != NULL)
  6903. {
  6904. if (delegateInfo->mHasExplicitThis)
  6905. {
  6906. target = mModule->GetDefaultTypedValue(delegateInfo->mParams[0], false, BfDefaultValueKind_Addr);
  6907. bypassVirtual = true;
  6908. }
  6909. }
  6910. else if (bindResult->mBindType->IsFunction())
  6911. {
  6912. BfMethodInstance* invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(bindResult->mBindType->ToTypeInstance(), 0, "Invoke");
  6913. if (!invokeMethodInstance->mMethodDef->mIsStatic)
  6914. {
  6915. target = mModule->GetDefaultTypedValue(invokeMethodInstance->GetThisType(), false, BfDefaultValueKind_Addr);
  6916. }
  6917. }
  6918. }
  6919. }
  6920. if (!target)
  6921. {
  6922. FinishDeferredEvals(argValues);
  6923. auto error = mModule->Fail(StrFormat("An instance reference is required to %s the non-static method '%s'",
  6924. (prevBindResult.mPrevVal != NULL) ? "bind" : "invoke",
  6925. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  6926. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  6927. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  6928. return mModule->GetDefaultTypedValue(returnType);
  6929. }
  6930. auto prevResult = mResult;
  6931. mResult = target;
  6932. CheckResultForReading(mResult);
  6933. mResult = prevResult;
  6934. if (methodDef->mMethodType != BfMethodType_Ctor)
  6935. {
  6936. bool doAccessCheck = true;
  6937. if (target.IsThis())
  6938. {
  6939. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  6940. doAccessCheck = false;
  6941. }
  6942. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  6943. doAccessCheck = false;
  6944. if ((doAccessCheck) && (!isSkipCall) && (prevBindResult.mPrevVal == NULL))
  6945. mModule->EmitObjectAccessCheck(target);
  6946. }
  6947. if (((prevBindResult.mPrevVal == NULL) || (!prevBindResult.mPrevVal->mSkipThis)) &&
  6948. (!isSkipCall))
  6949. {
  6950. bool skipMutCheck = false;
  6951. if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mSkipMutCheck))
  6952. {
  6953. // If we are binding a delegate, then we will end up making a copy of the target anyway
  6954. // so we don't need to do a mutability check
  6955. skipMutCheck = true;
  6956. }
  6957. if (methodDef->mMethodType == BfMethodType_Extension)
  6958. PushArg(target, irArgs);
  6959. else
  6960. PushThis(targetSrc, target, moduleMethodInstance.mMethodInstance, irArgs, skipMutCheck);
  6961. }
  6962. }
  6963. else if (methodDef->mMethodType == BfMethodType_Extension)
  6964. {
  6965. // Handled in args
  6966. }
  6967. else
  6968. {
  6969. if (prevBindResult.mPrevVal == NULL)
  6970. {
  6971. if ((mModule->mAttributeState == NULL) || (mModule->mAttributeState->mCustomAttributes == NULL) ||
  6972. (!mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoStaticCtorAttributeTypeDef)))
  6973. {
  6974. mModule->CheckStaticAccess(methodInstance->mMethodInstanceGroup->mOwner);
  6975. }
  6976. }
  6977. if (target)
  6978. {
  6979. FinishDeferredEvals(argValues);
  6980. mModule->Fail(StrFormat("Method '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  6981. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  6982. return mModule->GetDefaultTypedValue(returnType);
  6983. }
  6984. }
  6985. }
  6986. if (isSkipCall)
  6987. {
  6988. CheckSkipCall(targetSrc, argValues);
  6989. FinishDeferredEvals(argValues);
  6990. mModule->EmitEnsureInstructionAt();
  6991. return mModule->GetDefaultTypedValue(returnType);
  6992. }
  6993. bool hasNamedArgs = false;
  6994. for (auto& arg : argValues)
  6995. if (arg.mNameNode != NULL)
  6996. hasNamedArgs = true;
  6997. if (hasNamedArgs)
  6998. {
  6999. methodDef->BuildParamNameMap();
  7000. BfIdentifierNode* outOfPlaceName = NULL;
  7001. int curParamIdx = 0;
  7002. SizedArrayImpl<BfResolvedArg> origArgValues = argValues;
  7003. argValues.Clear();
  7004. for (int argIdx = 0; argIdx < origArgValues.mSize; argIdx++)
  7005. {
  7006. int paramIdx = curParamIdx;
  7007. auto& argValue = origArgValues[argIdx];
  7008. if (argValue.mNameNode != NULL)
  7009. {
  7010. int namedParamIdx = -1;
  7011. if (methodDef->mParamNameMap->TryGetValue(argValue.mNameNode->ToStringView(), &namedParamIdx))
  7012. {
  7013. paramIdx = namedParamIdx;
  7014. }
  7015. else
  7016. {
  7017. if (mModule->PreFail())
  7018. {
  7019. mModule->Fail(StrFormat("The best overload for '%s' does not have a parameter named '%s'", methodInstance->mMethodDef->mName.c_str(),
  7020. argValue.mNameNode->ToString().c_str()), argValue.mNameNode);
  7021. }
  7022. }
  7023. if (paramIdx != curParamIdx)
  7024. outOfPlaceName = argValue.mNameNode;
  7025. }
  7026. else if (outOfPlaceName != NULL)
  7027. {
  7028. if (mModule->PreFail())
  7029. mModule->Fail(StrFormat("Named argument '%s' is used out-of-position but is followed by an unnamed argument", outOfPlaceName->ToString().c_str()), outOfPlaceName);
  7030. outOfPlaceName = NULL;
  7031. }
  7032. if ((paramIdx < methodInstance->GetParamCount()) && (paramIdx != argIdx))
  7033. {
  7034. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_Normal)
  7035. {
  7036. auto wantType = methodInstance->GetParamType(paramIdx);
  7037. auto resolvedValue = ResolveArgValue(argValue, wantType);
  7038. if (resolvedValue)
  7039. {
  7040. argValue.mTypedValue = resolvedValue;
  7041. argValue.mArgFlags = (BfArgFlags)(argValue.mArgFlags | BfArgFlag_Finalized);
  7042. }
  7043. }
  7044. }
  7045. while (paramIdx >= argValues.mSize)
  7046. argValues.Add(BfResolvedArg());
  7047. if (argValues[paramIdx].mExpression != NULL)
  7048. {
  7049. if (argValue.mNameNode != NULL)
  7050. {
  7051. if (mModule->PreFail())
  7052. mModule->Fail(StrFormat("Named argument '%s' cannot be specified multiple times", argValue.mNameNode->ToString().c_str()), argValue.mNameNode);
  7053. }
  7054. }
  7055. argValues[paramIdx] = argValue;
  7056. curParamIdx++;
  7057. }
  7058. }
  7059. int argIdx = 0;
  7060. int paramIdx = 0;
  7061. BfIRValue expandedParamAlloca;
  7062. BfTypedValue expandedParamsArray;
  7063. BfType* expandedParamsElementType = NULL;
  7064. bool hadDelegateParamIdx = false;
  7065. int extendedParamIdx = 0;
  7066. AddCallDependencies(methodInstance);
  7067. bool wasCapturingMatchInfo = false;
  7068. auto autoComplete = GetAutoComplete();
  7069. if (autoComplete != NULL)
  7070. {
  7071. // Set to false to make sure we don't capture method match info from 'params' array creation
  7072. wasCapturingMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  7073. autoComplete->mIsCapturingMethodMatchInfo = false;
  7074. }
  7075. defer(
  7076. {
  7077. if (autoComplete != NULL)
  7078. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMatchInfo;
  7079. });
  7080. BfScopeData* boxScopeData = mDeferScopeAlloc;
  7081. if ((boxScopeData == NULL) && (mModule->mCurMethodState != NULL))
  7082. boxScopeData = mModule->mCurMethodState->mCurScope;
  7083. bool failed = false;
  7084. while (true)
  7085. {
  7086. int argExprIdx = argIdx;
  7087. if (methodDef->mMethodType == BfMethodType_Extension)
  7088. argExprIdx--;
  7089. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  7090. bool isDirectPass = false;
  7091. if (paramIdx >= (int)methodInstance->GetParamCount())
  7092. {
  7093. if (methodInstance->IsVarArgs())
  7094. {
  7095. if (argExprIdx >= (int)argValues.size())
  7096. break;
  7097. BfTypedValue argValue = ResolveArgValue(argValues[argExprIdx], NULL);
  7098. if (argValue)
  7099. {
  7100. auto typeInst = argValue.mType->ToTypeInstance();
  7101. if (argValue.mType == mModule->GetPrimitiveType(BfTypeCode_Float))
  7102. argValue = mModule->Cast(argValues[argExprIdx].mExpression, argValue, mModule->GetPrimitiveType(BfTypeCode_Double));
  7103. if ((typeInst != NULL) && (typeInst->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  7104. {
  7105. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  7106. BfType* charPtrType = mModule->CreatePointerType(charType);
  7107. argValue = mModule->Cast(argValues[argExprIdx].mExpression, argValue, charPtrType);
  7108. }
  7109. PushArg(argValue, irArgs, true, false);
  7110. }
  7111. argIdx++;
  7112. continue;
  7113. }
  7114. if (argExprIdx < (int)argValues.size())
  7115. {
  7116. if (mModule->PreFail())
  7117. {
  7118. BfAstNode* errorRef = argValues[argExprIdx].mExpression;
  7119. if (errorRef == NULL)
  7120. errorRef = targetSrc;
  7121. BfError* error;
  7122. if ((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0)
  7123. {
  7124. int checkIdx = argExprIdx - 1;
  7125. while (checkIdx >= 0)
  7126. {
  7127. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  7128. {
  7129. errorRef = argValues[checkIdx].mExpression;
  7130. break;
  7131. }
  7132. checkIdx--;
  7133. }
  7134. error = mModule->Fail("Expanded string interpolation generates too many arguments. If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  7135. }
  7136. else if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mBindType != NULL))
  7137. 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);
  7138. else
  7139. error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", (int)argValues.size() - argExprIdx), errorRef);
  7140. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  7141. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  7142. }
  7143. failed = true;
  7144. break;
  7145. }
  7146. break;
  7147. }
  7148. // Only create actual params if we're not just trying to bind the function
  7149. if ((prevBindResult.mPrevVal != NULL) && (!prevBindResult.mPrevVal->mWantsArgs))
  7150. break;
  7151. BfType* wantType = NULL;
  7152. bool wantsSplat = false;
  7153. if (expandedParamsElementType != NULL)
  7154. {
  7155. wantType = expandedParamsElementType;
  7156. }
  7157. else
  7158. {
  7159. wantsSplat = methodInstance->GetParamIsSplat(paramIdx) && (!IsComptime());
  7160. if (methodInstance->IsImplicitCapture(paramIdx))
  7161. {
  7162. auto paramType = methodInstance->GetParamType(paramIdx);
  7163. if (mModule->mCurMethodInstance->IsMixin())
  7164. {
  7165. // Don't bother, also- can fail on captures
  7166. }
  7167. else
  7168. {
  7169. // static int captureIdx = 0;
  7170. // captureIdx++;
  7171. // int curCaptureIdx = captureIdx;
  7172. //
  7173. // if (curCaptureIdx == 0x91)
  7174. // {
  7175. // NOP;
  7176. // }
  7177. auto lookupVal = DoImplicitArgCapture(targetSrc, methodInstance, paramIdx, failed, BfImplicitParamKind_General, origTarget);
  7178. if (lookupVal)
  7179. {
  7180. if (wantsSplat)
  7181. {
  7182. SplatArgs(lookupVal, irArgs);
  7183. }
  7184. else if (paramType->IsRef())
  7185. {
  7186. irArgs.push_back(lookupVal.mValue);
  7187. }
  7188. else
  7189. PushArg(lookupVal, irArgs, true);
  7190. }
  7191. }
  7192. paramIdx++;
  7193. continue;
  7194. }
  7195. wantType = methodInstance->GetParamType(paramIdx);
  7196. if (!mModule->mCurTypeInstance->IsInterface())
  7197. {
  7198. // Resolve `Self` types
  7199. if (wantType->IsUnspecializedTypeVariation())
  7200. {
  7201. wantType = mModule->ResolveSelfType(wantType, methodInstance->GetOwner());
  7202. }
  7203. }
  7204. if (IsVar(wantType))
  7205. {
  7206. // Case happens when we can't find the argument type
  7207. failed = true;
  7208. }
  7209. BfParamKind paramKind = methodInstance->GetParamKind(paramIdx);
  7210. if (paramKind == BfParamKind_Params)
  7211. {
  7212. //TODO: Check to see if it's a direct array pass
  7213. if (argIdx < (int)argValues.size())
  7214. {
  7215. auto argValue = argValues[argIdx].mTypedValue;
  7216. if ((argValue.IsParams()) /*&& (mModule->CanCast(argValue, wantType))*/)
  7217. isDirectPass = true;
  7218. }
  7219. if (!isDirectPass)
  7220. {
  7221. int numElements = BF_MAX((int)argValues.size() - argIdx, 0);
  7222. if (methodDef->mMethodType == BfMethodType_Extension)
  7223. numElements++;
  7224. if (IsConstEval())
  7225. {
  7226. if ((wantType->IsArray()) || (wantType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  7227. {
  7228. auto genericTypeInst = wantType->ToGenericTypeInstance();
  7229. expandedParamsElementType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  7230. auto irSizedArrayType = mModule->mBfIRBuilder->GetSizedArrayType(mModule->mBfIRBuilder->MapType(expandedParamsElementType), numElements);
  7231. Array<BfIRValue> values;
  7232. for (int i = 0; i < numElements; i++)
  7233. values.Add(mModule->mBfIRBuilder->GetFakeVal());
  7234. expandedParamsArray = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(irSizedArrayType, values), wantType);
  7235. PushArg(expandedParamsArray, irArgs);
  7236. continue;
  7237. }
  7238. }
  7239. else if (wantType->IsArray())
  7240. {
  7241. BfArrayType* arrayType = (BfArrayType*)wantType;
  7242. mModule->PopulateType(arrayType, BfPopulateType_DataAndMethods);
  7243. expandedParamsElementType = arrayType->mGenericTypeInfo->mTypeGenericArguments[0];
  7244. int arrayClassSize = arrayType->mInstSize - expandedParamsElementType->mSize;
  7245. expandedParamsArray = BfTypedValue(mModule->AllocFromType(arrayType->GetUnderlyingType(), boxScopeData, BfIRValue(), mModule->GetConstValue(numElements), 1, BfAllocFlags_None),
  7246. arrayType, false);
  7247. BfResolvedArgs resolvedArgs;
  7248. MatchConstructor(targetSrc, NULL, expandedParamsArray, arrayType, resolvedArgs, false, BfMethodGenericArguments(), BfAllowAppendKind_No);
  7249. //TODO: Assert 'length' var is at slot 1
  7250. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(expandedParamsArray.mValue, mModule->mBfIRBuilder->MapType(arrayType->mBaseType));
  7251. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  7252. if (arrayLengthBitCount == 0)
  7253. {
  7254. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", targetSrc);
  7255. return BfTypedValue();
  7256. }
  7257. auto& fieldInstance = arrayType->mBaseType->mFieldInstances[0];
  7258. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, fieldInstance.mDataIdx);
  7259. if (arrayLengthBitCount == 64)
  7260. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue64(numElements), addr, 8);
  7261. else
  7262. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue32(numElements), addr, 4);
  7263. PushArg(expandedParamsArray, irArgs);
  7264. continue;
  7265. }
  7266. else if (wantType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  7267. {
  7268. mModule->PopulateType(wantType);
  7269. mModule->mBfIRBuilder->PopulateType(wantType);
  7270. auto genericTypeInst = wantType->ToGenericTypeInstance();
  7271. expandedParamsElementType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  7272. expandedParamsArray = BfTypedValue(mModule->CreateAlloca(wantType), wantType, true);
  7273. expandedParamAlloca = mModule->CreateAlloca(genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0], true, NULL, mModule->GetConstValue(numElements));
  7274. mModule->mBfIRBuilder->CreateAlignedStore(expandedParamAlloca, mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 1), mModule->mSystem->mPtrSize);
  7275. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue(numElements), mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 2), mModule->mSystem->mPtrSize);
  7276. PushArg(expandedParamsArray, irArgs, !wantsSplat);
  7277. continue;
  7278. }
  7279. else if (wantType->IsSizedArray())
  7280. {
  7281. mModule->PopulateType(wantType);
  7282. mModule->mBfIRBuilder->PopulateType(wantType);
  7283. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)wantType;
  7284. expandedParamsElementType = wantType->GetUnderlyingType();
  7285. if (numElements != sizedArrayType->mElementCount)
  7286. {
  7287. BfAstNode* refNode = targetSrc;
  7288. if (argExprIdx < (int)argValues.size())
  7289. refNode = argValues[argExprIdx].mExpression;
  7290. mModule->Fail(StrFormat("Incorrect number of arguments to match params type '%s'", mModule->TypeToString(wantType).c_str()), refNode);
  7291. }
  7292. expandedParamsArray = BfTypedValue(mModule->CreateAlloca(wantType), wantType, true);
  7293. expandedParamAlloca = mModule->mBfIRBuilder->CreateBitCast(expandedParamsArray.mValue, mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(expandedParamsElementType)));
  7294. PushArg(expandedParamsArray, irArgs, !wantsSplat);
  7295. continue;
  7296. }
  7297. }
  7298. }
  7299. else if (paramKind == BfParamKind_DelegateParam)
  7300. hadDelegateParamIdx = true;
  7301. }
  7302. BfAstNode* arg = NULL;
  7303. bool hadMissingArg = false;
  7304. if (argExprIdx == -1)
  7305. arg = targetSrc;
  7306. if (argExprIdx >= 0)
  7307. {
  7308. if (argExprIdx < (int)argValues.size())
  7309. {
  7310. arg = argValues[argExprIdx].mExpression;
  7311. if (((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0) && (!expandedParamsArray) && (!hadDelegateParamIdx))
  7312. {
  7313. BfAstNode* errorRef = arg;
  7314. int checkIdx = argExprIdx - 1;
  7315. while (checkIdx >= 0)
  7316. {
  7317. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  7318. {
  7319. errorRef = argValues[checkIdx].mExpression;
  7320. break;
  7321. }
  7322. checkIdx--;
  7323. }
  7324. 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);
  7325. }
  7326. // if ((arg == NULL) && (argValues[argExprIdx].mExpression != NULL))
  7327. // hadMissingArg = true;
  7328. if ((arg == NULL) && (!argValues[argExprIdx].mTypedValue))
  7329. hadMissingArg = true;
  7330. }
  7331. else
  7332. hadMissingArg = true;
  7333. }
  7334. BfTypedValue argValue;
  7335. if (hadMissingArg)
  7336. {
  7337. if (expandedParamsArray)
  7338. break;
  7339. if ((argIdx >= (int) methodInstance->mDefaultValues.size()) || (!methodInstance->mDefaultValues[argIdx]))
  7340. {
  7341. BfAstNode* refNode = targetSrc;
  7342. if (argValues.size() > 0)
  7343. {
  7344. auto checkExpr = argValues.back().mExpression;
  7345. if (checkExpr != NULL)
  7346. refNode = checkExpr;
  7347. }
  7348. BfAstNode* prevNode = NULL;
  7349. if (targetSrc == NULL)
  7350. {
  7351. // We must be in BfModule::EmitCtorBody
  7352. }
  7353. else if (auto tupleExpr = BfNodeDynCastExact<BfTupleExpression>(targetSrc))
  7354. {
  7355. if (tupleExpr->mCommas.size() > 0)
  7356. prevNode = tupleExpr->mCommas.back();
  7357. else
  7358. prevNode = tupleExpr->mOpenParen;
  7359. if (tupleExpr->mCloseParen != NULL)
  7360. refNode = tupleExpr->mCloseParen;
  7361. }
  7362. else if (mModule->mParentNodeEntry != NULL)
  7363. {
  7364. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(mModule->mParentNodeEntry->mNode))
  7365. {
  7366. if (objectCreateExpr->mCommas.size() > 0)
  7367. prevNode = objectCreateExpr->mCommas.back();
  7368. else
  7369. prevNode = objectCreateExpr->mOpenToken;
  7370. if (objectCreateExpr->mCloseToken != NULL)
  7371. refNode = objectCreateExpr->mCloseToken;
  7372. if (auto newNode = BfNodeDynCast<BfNewNode>(objectCreateExpr->mNewNode))
  7373. {
  7374. if (newNode->mAllocNode == targetSrc)
  7375. refNode = targetSrc;
  7376. }
  7377. }
  7378. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  7379. {
  7380. if (invokeExpr->mCommas.size() > 0)
  7381. prevNode = invokeExpr->mCommas.back();
  7382. else
  7383. prevNode = invokeExpr->mOpenParen;
  7384. if (invokeExpr->mCloseParen != NULL)
  7385. refNode = invokeExpr->mCloseParen;
  7386. }
  7387. }
  7388. if (refNode == NULL)
  7389. refNode = methodInstance->GetOwner()->mTypeDef->GetRefNode();
  7390. if ((autoComplete != NULL) && (prevNode != NULL))
  7391. autoComplete->CheckEmptyStart(prevNode, wantType);
  7392. BfError* error = NULL;
  7393. if (mModule->mParentNodeEntry != NULL)
  7394. {
  7395. bool showCtorError = false;
  7396. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(mModule->mParentNodeEntry->mNode))
  7397. {
  7398. if (ctorDeclaration->mInitializer == NULL)
  7399. showCtorError = true;
  7400. }
  7401. if (auto typerDecl = BfNodeDynCast<BfTypeDeclaration>(mModule->mParentNodeEntry->mNode))
  7402. showCtorError = true;
  7403. if (showCtorError)
  7404. {
  7405. if (mModule->PreFail())
  7406. {
  7407. error = mModule->Fail(StrFormat("No parameterless constructor is available for base class. Consider calling base constructor '%s'.",
  7408. mModule->MethodToString(methodInstance).c_str()), refNode);
  7409. }
  7410. auto srcNode = mModule->mCurMethodInstance->mMethodDef->GetRefNode();
  7411. if ((autoComplete != NULL) && (autoComplete->CheckFixit(srcNode)))
  7412. autoComplete->FixitAddConstructor(mModule->mCurTypeInstance);
  7413. }
  7414. }
  7415. if (mModule->PreFail())
  7416. {
  7417. if (error == NULL)
  7418. {
  7419. if (hasNamedArgs)
  7420. error = mModule->Fail(StrFormat("There is no argument given that corresponds to the required formal parameter '%s' of '%s'.",
  7421. methodInstance->GetParamName(paramIdx).c_str(), mModule->MethodToString(methodInstance).c_str()), refNode);
  7422. else
  7423. error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", methodInstance->GetParamCount() - paramIdx), refNode);
  7424. }
  7425. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  7426. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  7427. }
  7428. failed = true;
  7429. break;
  7430. }
  7431. auto foreignDefaultVal = methodInstance->mDefaultValues[argIdx];
  7432. auto foreignConst = methodInstance->GetOwner()->mConstHolder->GetConstant(foreignDefaultVal.mValue);
  7433. if (foreignConst->mConstType == BfConstType_AggZero)
  7434. {
  7435. // Allow this
  7436. }
  7437. else if (foreignConst->mTypeCode == BfTypeCode_NullPtr)
  7438. {
  7439. if (wantType->IsNullable())
  7440. {
  7441. argValue = mModule->GetDefaultTypedValue(wantType, false, BfDefaultValueKind_Addr);
  7442. }
  7443. }
  7444. else if (foreignConst->mConstType == BfConstType_GlobalVar)
  7445. {
  7446. auto globalVar = (BfGlobalVar*)foreignConst;
  7447. if (globalVar->mName[0] == '#')
  7448. {
  7449. if (strcmp(globalVar->mName, "#CallerLineNum") == 0)
  7450. {
  7451. argValue = BfTypedValue(mModule->GetConstValue(mModule->mCurFilePosition.mCurLine + 1), mModule->GetPrimitiveType(BfTypeCode_Int32));
  7452. }
  7453. else if (strcmp(globalVar->mName, "#CallerFilePath") == 0)
  7454. {
  7455. String filePath = "";
  7456. if (mModule->mCurFilePosition.mFileInstance != NULL)
  7457. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  7458. argValue = BfTypedValue(mModule->GetStringObjectValue(filePath),
  7459. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7460. }
  7461. else if (strcmp(globalVar->mName, "#CallerFileName") == 0)
  7462. {
  7463. String filePath = "";
  7464. if (mModule->mCurFilePosition.mFileInstance != NULL)
  7465. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  7466. argValue = BfTypedValue(mModule->GetStringObjectValue(GetFileName(filePath)),
  7467. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7468. }
  7469. else if (strcmp(globalVar->mName, "#CallerFileDir") == 0)
  7470. {
  7471. String filePath = "";
  7472. if (mModule->mCurFilePosition.mFileInstance != NULL)
  7473. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  7474. argValue = BfTypedValue(mModule->GetStringObjectValue(GetFileDir(filePath)),
  7475. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7476. }
  7477. else if (strcmp(globalVar->mName, "#CallerTypeName") == 0)
  7478. {
  7479. String typeName = "";
  7480. if (mModule->mCurTypeInstance != NULL)
  7481. typeName = mModule->TypeToString(mModule->mCurTypeInstance);
  7482. argValue = BfTypedValue(mModule->GetStringObjectValue(typeName),
  7483. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7484. }
  7485. else if (strcmp(globalVar->mName, "#CallerType") == 0)
  7486. {
  7487. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  7488. BfType* type = mModule->mCurTypeInstance;
  7489. if (type != NULL)
  7490. {
  7491. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7492. argValue = BfTypedValue(mModule->CreateTypeDataRef(type), typeType);
  7493. }
  7494. }
  7495. else if (strcmp(globalVar->mName, "#CallerMemberName") == 0)
  7496. {
  7497. String memberName = "";
  7498. if (mModule->mCurMethodInstance != NULL)
  7499. memberName = mModule->MethodToString(mModule->mCurMethodInstance);
  7500. argValue = BfTypedValue(mModule->GetStringObjectValue(memberName),
  7501. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7502. }
  7503. else if (strcmp(globalVar->mName, "#CallerProject") == 0)
  7504. {
  7505. String projectName = "";
  7506. if (mModule->mCurMethodInstance != NULL)
  7507. projectName = mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mProject->mName;
  7508. argValue = BfTypedValue(mModule->GetStringObjectValue(projectName),
  7509. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7510. }
  7511. else if (strcmp(globalVar->mName, "#ProjectName") == 0)
  7512. {
  7513. String projectName = methodInstance->mMethodDef->mDeclaringType->mProject->mName;
  7514. argValue = BfTypedValue(mModule->GetStringObjectValue(projectName),
  7515. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7516. }
  7517. else
  7518. {
  7519. argValue = mModule->GetCompilerFieldValue(globalVar->mName);
  7520. }
  7521. }
  7522. }
  7523. else if (foreignConst->mConstType == BfConstType_GEP32_2)
  7524. {
  7525. auto constGep32_2 = (BfConstantGEP32_2*)foreignConst;
  7526. auto gepTarget = methodInstance->GetOwner()->mConstHolder->GetConstantById(constGep32_2->mTarget);
  7527. if (gepTarget->mConstType == BfConstType_GlobalVar)
  7528. {
  7529. auto globalVar = (BfGlobalVar*)gepTarget;
  7530. if (globalVar->mName[0] == '#')
  7531. {
  7532. if (strcmp(globalVar->mName, "#CallerExpression") == 0)
  7533. {
  7534. int exprIdx = constGep32_2->mIdx1;
  7535. if ((exprIdx >= 0) && (exprIdx < (int)argValues.size()))
  7536. {
  7537. auto expr = argValues[exprIdx].mExpression;
  7538. if (expr != NULL)
  7539. {
  7540. argValue = BfTypedValue(mModule->GetStringObjectValue(expr->ToString()),
  7541. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7542. }
  7543. }
  7544. else
  7545. {
  7546. mModule->Fail("CallerExpression index out of bounds", targetSrc);
  7547. argValue = BfTypedValue(mModule->GetStringObjectValue(""),
  7548. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7549. }
  7550. }
  7551. }
  7552. }
  7553. }
  7554. if (!argValue)
  7555. {
  7556. argValue = mModule->GetTypedValueFromConstant(foreignConst, methodInstance->GetOwner()->mConstHolder, foreignDefaultVal.mType);
  7557. if (!argValue)
  7558. mModule->Fail("Default parameter value failed", targetSrc);
  7559. mModule->mBfIRBuilder->PopulateType(foreignDefaultVal.mType);
  7560. }
  7561. }
  7562. else
  7563. {
  7564. if (argExprIdx == -1)
  7565. argValue = target;
  7566. else
  7567. argValue = argValues[argExprIdx].mTypedValue;
  7568. if ((argValue.IsParams()) && (!isDirectPass))
  7569. {
  7570. BfAstNode* refNode = arg;
  7571. if (auto unaryOperatorExpr = BfNodeDynCast<BfUnaryOperatorExpression>(refNode))
  7572. refNode = unaryOperatorExpr->mOpToken;
  7573. mModule->Warn(0, "Unused 'params' expression", refNode);
  7574. }
  7575. if (wantType->IsMethodRef())
  7576. {
  7577. auto expr = argValues[argExprIdx].mExpression;
  7578. if (expr != NULL)
  7579. SetMethodElementType(expr);
  7580. if (!argValue)
  7581. argValue = mModule->CreateValueFromExpression(BfNodeDynCast<BfExpression>(arg), wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  7582. // Add any implicit captures now
  7583. auto methodRefType = (BfMethodRefType*)wantType;
  7584. BfMethodInstance* useMethodInstance = methodRefType->mMethodRef;
  7585. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  7586. {
  7587. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  7588. auto lookupVal = DoImplicitArgCapture(arg, useMethodInstance, paramIdx, failed, BfImplicitParamKind_General, argValue);
  7589. if (lookupVal)
  7590. {
  7591. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  7592. SplatArgs(lookupVal, irArgs);
  7593. else
  7594. {
  7595. if (lookupVal.mType->IsComposite())
  7596. lookupVal = mModule->MakeAddressable(lookupVal, false);
  7597. irArgs.push_back(lookupVal.mValue);
  7598. }
  7599. }
  7600. }
  7601. paramIdx++;
  7602. argIdx++;
  7603. continue;
  7604. }
  7605. else if (argExprIdx >= 0)
  7606. {
  7607. BfParamKind paramKind = BfParamKind_Normal;
  7608. BfIdentifierNode* paramNameNode = NULL;
  7609. if (paramIdx < methodInstance->GetParamCount())
  7610. {
  7611. paramKind = methodInstance->GetParamKind(paramIdx);
  7612. paramNameNode = methodInstance->GetParamNameNode(paramIdx);
  7613. }
  7614. argValues[argExprIdx].mExpectedType = wantType;
  7615. argValue = ResolveArgValue(argValues[argExprIdx], wantType, NULL, paramKind, paramNameNode);
  7616. }
  7617. }
  7618. if (!argValue)
  7619. {
  7620. failed = true;
  7621. }
  7622. if ((arg != NULL) && (autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(arg)))
  7623. {
  7624. if (!autoComplete->mResultString.Contains('\r'))
  7625. {
  7626. String str;
  7627. str += methodInstance->GetParamName(paramIdx);
  7628. str += " @ ";
  7629. bool isCtor = methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor;
  7630. if (isCtor)
  7631. str += methodInstance->GetOwner()->mTypeDef->mName->ToString();
  7632. else
  7633. str += methodInstance->mMethodDef->mName;
  7634. str += "(";
  7635. for (int i = isCtor ? 1 : 0; i < methodInstance->GetParamCount(); i++)
  7636. {
  7637. if (i > (isCtor ? 1 : 0))
  7638. str += ",";
  7639. if (i == paramIdx)
  7640. {
  7641. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_Params)
  7642. str += "params ";
  7643. str += mModule->TypeToString(methodInstance->GetParamType(paramIdx));
  7644. }
  7645. }
  7646. str += ")";
  7647. if (!autoComplete->mResultString.StartsWith(":"))
  7648. autoComplete->mResultString.Clear();
  7649. int crPos = (int)autoComplete->mResultString.IndexOf('\n');
  7650. if (crPos == -1)
  7651. crPos = autoComplete->mResultString.mLength;
  7652. int insertPos = BF_MAX(1, crPos);
  7653. if (autoComplete->mResultString.IsEmpty())
  7654. autoComplete->mResultString += ":";
  7655. if (insertPos > 1)
  7656. str.Insert(0, '\r');
  7657. autoComplete->mResultString.Insert(insertPos, str);
  7658. }
  7659. }
  7660. if (argValue)
  7661. {
  7662. if ((isThis) && (argValue.mType->IsRef()))
  7663. {
  7664. // Convert a 'ref this' to a 'this*'
  7665. argValue.mType = mModule->CreatePointerType(argValue.mType->GetUnderlyingType());
  7666. }
  7667. BfAstNode* refNode = arg;
  7668. if (refNode == NULL)
  7669. refNode = targetSrc;
  7670. if ((wantType->IsRef()) && (!argValue.mType->IsRef()) &&
  7671. (((callFlags & BfCreateCallFlags_AllowImplicitRef) != 0) || (wantType->IsIn())))
  7672. {
  7673. auto underlyingType = wantType->GetUnderlyingType();
  7674. if (mModule->mCurMethodState != NULL)
  7675. {
  7676. SetAndRestoreValue<BfScopeData*> prevScopeData(mModule->mCurMethodState->mOverrideScope, boxScopeData);
  7677. argValue = mModule->Cast(refNode, argValue, underlyingType);
  7678. }
  7679. else
  7680. argValue = mModule->Cast(refNode, argValue, underlyingType, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  7681. if (argValue)
  7682. argValue = mModule->ToRef(argValue, (BfRefType*)wantType);
  7683. }
  7684. else
  7685. {
  7686. if (mModule->mCurMethodState != NULL)
  7687. {
  7688. SetAndRestoreValue<BfScopeData*> prevScopeData(mModule->mCurMethodState->mOverrideScope, boxScopeData);
  7689. argValue = mModule->Cast(refNode, argValue, wantType, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  7690. }
  7691. else
  7692. argValue = mModule->Cast(refNode, argValue, wantType, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  7693. }
  7694. if (!argValue)
  7695. {
  7696. if ((argExprIdx < (int)argValues.size()) && ((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0))
  7697. {
  7698. BfAstNode* errorRef = NULL;
  7699. int checkIdx = argExprIdx - 1;
  7700. while (checkIdx >= 0)
  7701. {
  7702. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  7703. {
  7704. errorRef = argValues[checkIdx].mExpression;
  7705. break;
  7706. }
  7707. checkIdx--;
  7708. }
  7709. if (errorRef != NULL)
  7710. mModule->Warn(0, "If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  7711. }
  7712. failed = true;
  7713. }
  7714. else if ((wantType->IsComposite()) && (!expandedParamsArray))
  7715. {
  7716. if (methodInstance->mIsIntrinsic)
  7717. {
  7718. // Intrinsics can handle structs either by value or address
  7719. }
  7720. else
  7721. {
  7722. // We need to make a temp and get the addr of that
  7723. if ((!wantsSplat) && (!argValue.IsValuelessType()) && (!argValue.IsAddr()) && (!IsConstEval()))
  7724. {
  7725. argValue = mModule->MakeAddressable(argValue);
  7726. }
  7727. }
  7728. }
  7729. else if (!wantType->IsRef())
  7730. argValue = mModule->LoadValue(argValue);
  7731. }
  7732. if ((argExprIdx != -1) && (argExprIdx < (int)argValues.size()) && ((argValues[argExprIdx].mArgFlags & BfArgFlag_Cascade) != 0))
  7733. {
  7734. mUsedAsStatement = true;
  7735. if (argValues[argExprIdx].mUncastedTypedValue)
  7736. argCascades.Add(argValues[argExprIdx].mUncastedTypedValue);
  7737. else
  7738. argCascades.Add(argValue);
  7739. }
  7740. if (expandedParamsArray)
  7741. {
  7742. if (argValue)
  7743. {
  7744. if (argValue.mValue.IsFake())
  7745. {
  7746. if ((!mModule->IsInUnspecializedGeneric()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  7747. mModule->InternalError("Invalid expandedParamsArray value");
  7748. }
  7749. else if (IsConstEval())
  7750. {
  7751. auto constant = mModule->mBfIRBuilder->GetConstant(expandedParamsArray.mValue);
  7752. BF_ASSERT(constant->mConstType == BfConstType_Agg);
  7753. auto constAgg = (BfConstantAgg*)constant;
  7754. constAgg->mValues[extendedParamIdx] = argValue.mValue;
  7755. }
  7756. else if (expandedParamAlloca)
  7757. {
  7758. argValue = mModule->LoadOrAggregateValue(argValue);
  7759. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamAlloca, extendedParamIdx);
  7760. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, addr, argValue.mType->mAlign);
  7761. }
  7762. else
  7763. {
  7764. auto firstElem = mModule->GetFieldByName(expandedParamsArray.mType->ToTypeInstance(), "mFirstElement");
  7765. if (firstElem != NULL)
  7766. {
  7767. argValue = mModule->LoadValue(argValue);
  7768. auto firstAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, firstElem->mDataIdx);
  7769. auto indexedAddr = mModule->CreateIndexedValue(argValue.mType, firstAddr, extendedParamIdx);
  7770. if (argValue.IsSplat())
  7771. mModule->AggregateSplatIntoAddr(argValue, indexedAddr);
  7772. else
  7773. mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, indexedAddr, argValue.mType->mAlign);
  7774. }
  7775. }
  7776. }
  7777. extendedParamIdx++;
  7778. }
  7779. else
  7780. {
  7781. if ((paramIdx == 0) && (methodInstance->GetParamName(paramIdx) == "this") && (wantType->IsPointer()))
  7782. {
  7783. auto underlyingType = wantType->GetUnderlyingType();
  7784. mModule->PopulateType(underlyingType, BfPopulateType_Data);
  7785. if ((underlyingType->IsValuelessType()) && (!underlyingType->IsVoid()))
  7786. {
  7787. // We don't actually pass a 'this' pointer for mut methods on valueless structs
  7788. argIdx++;
  7789. paramIdx++;
  7790. continue;
  7791. }
  7792. }
  7793. if (argValue)
  7794. {
  7795. if (isThis)
  7796. PushThis(targetSrc, argValue, methodInstance, irArgs);
  7797. else if (wantsSplat)
  7798. SplatArgs(argValue, irArgs);
  7799. else
  7800. PushArg(argValue, irArgs, true, false, methodInstance->mIsIntrinsic, methodInstance->mCallingConvention != BfCallingConvention_Unspecified);
  7801. }
  7802. paramIdx++;
  7803. }
  7804. argIdx++;
  7805. }
  7806. if (failed)
  7807. {
  7808. // Process the other unused arguments
  7809. while (argIdx < argValues.size())
  7810. {
  7811. mModule->AssertErrorState();
  7812. auto argValue = argValues[argIdx].mTypedValue;
  7813. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval | BfArgFlag_VariableDeclaration | BfArgFlag_UninitializedExpr)) != 0)
  7814. {
  7815. if (!argValue)
  7816. {
  7817. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  7818. if (expr != NULL)
  7819. argValue = mModule->CreateValueFromExpression(expr);
  7820. }
  7821. }
  7822. argIdx++;
  7823. }
  7824. prevIgnoreWrites.Restore();
  7825. return mModule->GetDefaultTypedValue(returnType, false, BfDefaultValueKind_Addr);
  7826. }
  7827. prevBindResult.Restore();
  7828. if (!methodDef->mIsStatic)
  7829. {
  7830. bool ignoreVirtualError = (mModule->mBfIRBuilder->mIgnoreWrites) && (mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef);
  7831. if ((methodInstance->GetOwner()->IsInterface()) && (!target.mType->IsGenericParam()) && (!target.mType->IsConcreteInterfaceType()) &&
  7832. (!mModule->mCurTypeInstance->IsInterface()) && (!ignoreVirtualError))
  7833. {
  7834. if (methodInstance->mVirtualTableIdx == -1)
  7835. {
  7836. mModule->PopulateType(methodInstance->GetOwner(), BfPopulateType_DataAndMethods);
  7837. }
  7838. if (methodInstance->mVirtualTableIdx == -1)
  7839. {
  7840. if (methodInstance->mMethodDef->mIsConcrete)
  7841. {
  7842. 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);
  7843. }
  7844. else if (methodInstance->HasSelf())
  7845. {
  7846. 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);
  7847. }
  7848. else
  7849. {
  7850. if ((bypassVirtual) && (mModule->mCurTypeInstance->IsInterface()))
  7851. {
  7852. // Allow a base call to be defined
  7853. }
  7854. else if ((methodInstance->IsSpecializedGenericMethod()) && (origTarget) && (!origTarget.mType->IsInterface()))
  7855. {
  7856. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  7857. mModule->AssertErrorState();
  7858. }
  7859. else if ((!mModule->mCurMethodInstance->mIsUnspecialized))
  7860. {
  7861. // Compiler error?
  7862. String errorString = "Unable to dynamically dispatch '%s'";
  7863. if (methodInstance->IsSpecializedGenericMethod())
  7864. errorString = "Unable to dynamically dispatch '%s' because generic methods can only be directly dispatched";
  7865. if (methodInstance->mReturnType->IsConcreteInterfaceType())
  7866. errorString = "Unable to dynamically dispatch '%s' because the concrete return type is unknown";
  7867. mModule->Fail(StrFormat(errorString.c_str(), mModule->MethodToString(methodInstance).c_str()), targetSrc);
  7868. }
  7869. //BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  7870. }
  7871. if (mFunctionBindResult != NULL)
  7872. {
  7873. mFunctionBindResult->mMethodInstance = methodInstance;
  7874. mFunctionBindResult->mTarget = target;
  7875. mFunctionBindResult->mFunc = moduleMethodInstance.mFunc;
  7876. for (auto arg : irArgs)
  7877. mFunctionBindResult->mIRArgs.push_back(arg);
  7878. }
  7879. prevIgnoreWrites.Restore();
  7880. return mModule->GetDefaultTypedValue(returnType);
  7881. }
  7882. }
  7883. }
  7884. else
  7885. {
  7886. //BF_ASSERT(!methodInstance->GetOwner()->IsInterface());
  7887. }
  7888. prevIgnoreWrites.Restore();
  7889. if (target.mType != NULL)
  7890. {
  7891. // When we call a method from a static ctor, that method could access static fields so we need to make sure
  7892. // the type has been initialized
  7893. auto targetTypeInst = target.mType->ToTypeInstance();
  7894. if (targetTypeInst != NULL)
  7895. {
  7896. if (prevBindResult.mPrevVal == NULL)
  7897. {
  7898. if ((mModule->mAttributeState == NULL) || (mModule->mAttributeState->mCustomAttributes == NULL) ||
  7899. (!mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoStaticCtorAttributeTypeDef)))
  7900. {
  7901. mModule->CheckStaticAccess(targetTypeInst);
  7902. }
  7903. }
  7904. }
  7905. }
  7906. if (methodInstance->mReturnType == NULL)
  7907. {
  7908. mModule->AssertErrorState();
  7909. mModule->Fail("Circular reference in method instance", targetSrc);
  7910. return BfTypedValue();
  7911. }
  7912. BfCreateCallFlags physCallFlags = BfCreateCallFlags_None;
  7913. if ((origTarget.mType != NULL) && (origTarget.mType->IsGenericParam()))
  7914. physCallFlags = (BfCreateCallFlags)(physCallFlags | BfCreateCallFlags_GenericParamThis);
  7915. auto func = moduleMethodInstance.mFunc;
  7916. BfTypedValue callResult = CreateCall(targetSrc, methodInstance, func, bypassVirtual, irArgs, NULL, physCallFlags, origTarget.mType);
  7917. prevIgnoreWrites.Restore();
  7918. if ((methodInstance->mMethodDef->mIsNoReturn) && ((mBfEvalExprFlags & BfEvalExprFlags_IsExpressionBody) != 0) &&
  7919. (mExpectingType != NULL) && (callResult.mType != mExpectingType))
  7920. {
  7921. callResult = mModule->GetDefaultTypedValue(mExpectingType);
  7922. }
  7923. // This gets triggered for non-sret (ie: comptime) composite returns so they aren't considered readonly
  7924. if ((callResult.mKind == BfTypedValueKind_Value) && (!callResult.mValue.IsConst()) &&
  7925. (!callResult.mType->IsValuelessType()) && (callResult.mType->IsComposite()) && (!methodInstance->GetLoweredReturnType()))
  7926. {
  7927. bool makeAddressable = true;
  7928. auto typeInstance = callResult.mType->ToTypeInstance();
  7929. if ((typeInstance != NULL) && (typeInstance->mHasUnderlyingArray))
  7930. makeAddressable = false;
  7931. if (makeAddressable)
  7932. {
  7933. callResult = mModule->MakeAddressable(callResult, true);
  7934. }
  7935. }
  7936. if (argCascades.mSize == 1)
  7937. {
  7938. if (argCascade == NULL)
  7939. return argCascades[0];
  7940. *argCascade = argCascades[0];
  7941. }
  7942. if (argCascades.mSize > 1)
  7943. {
  7944. if (argCascade == NULL)
  7945. return mModule->CreateTuple(argCascades, {});
  7946. *argCascade = mModule->CreateTuple(argCascades, {});
  7947. }
  7948. return callResult;
  7949. }
  7950. BfTypedValue BfExprEvaluator::MatchConstructor(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, BfTypeInstance* targetType, BfResolvedArgs& argValues, bool callCtorBodyOnly,
  7951. const BfMethodGenericArguments& methodGenericArguments, BfAllowAppendKind allowAppendKind, BfTypedValue* appendIndexValue)
  7952. {
  7953. // Temporarily disable so we don't capture calls in params
  7954. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  7955. auto origAllowAppendKind = allowAppendKind;
  7956. if (allowAppendKind == BfAllowAppendKind_Infer)
  7957. allowAppendKind = targetType->IsZeroGap() ? BfAllowAppendKind_ZeroGap : BfAllowAppendKind_Yes;
  7958. static int sCtorCount = 0;
  7959. sCtorCount++;
  7960. BfMethodMatcher methodMatcher(targetSrc, mModule, "", argValues.mResolvedArgs, methodGenericArguments);
  7961. methodMatcher.mAllowAppendKind = allowAppendKind;
  7962. methodMatcher.mBfEvalExprFlags = mBfEvalExprFlags;
  7963. BfTypeVector typeGenericArguments;
  7964. auto curTypeInst = targetType;
  7965. auto curTypeDef = targetType->mTypeDef;
  7966. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  7967. auto activeTypeDef = mModule->GetActiveTypeDef();
  7968. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  7969. bool isFailurePass = false;
  7970. for (int pass = 0; pass < 2; pass++)
  7971. {
  7972. isFailurePass = pass == 1;
  7973. curTypeDef->PopulateMemberSets();
  7974. BfMethodDef* nextMethodDef = NULL;
  7975. BfMemberSetEntry* entry;
  7976. if (curTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  7977. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  7978. while (nextMethodDef != NULL)
  7979. {
  7980. auto checkMethod = nextMethodDef;
  7981. nextMethodDef = nextMethodDef->mNextWithSameName;
  7982. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  7983. continue; // Don't match private default ctor if there's a user-defined one
  7984. if (checkMethod->mIsStatic)
  7985. continue;
  7986. if ((checkMethod->mDeclaringType->IsExtension()) && (mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) &&
  7987. (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoExtensionAttributeTypeDef)))
  7988. {
  7989. mModule->mAttributeState->mUsed = true;
  7990. continue;
  7991. }
  7992. if (!mModule->IsInSpecializedSection())
  7993. {
  7994. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  7995. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, visibleProjectSet)))
  7996. continue;
  7997. }
  7998. auto checkProt = checkMethod->mProtection;
  7999. if (!isFailurePass)
  8000. {
  8001. if (callCtorBodyOnly)
  8002. {
  8003. if (curTypeDef != mModule->mCurTypeInstance->mTypeDef)
  8004. {
  8005. // We're calling the base class's ctor from a derived class
  8006. if (checkProt <= BfProtection_Private)
  8007. continue;
  8008. }
  8009. }
  8010. else
  8011. {
  8012. if ((checkProt == BfProtection_Protected) || (checkProt == BfProtection_ProtectedInternal)) // Treat protected constructors as private
  8013. checkProt = BfProtection_Private;
  8014. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkMethod->mDeclaringType->mProject, checkProt, curTypeInst))
  8015. continue;
  8016. }
  8017. }
  8018. methodMatcher.CheckMethod(NULL, curTypeInst, checkMethod, isFailurePass);
  8019. }
  8020. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  8021. break;
  8022. }
  8023. if (methodMatcher.mBestMethodDef == NULL)
  8024. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8025. if (methodMatcher.mBestMethodDef == NULL)
  8026. {
  8027. mModule->Fail("No constructor available", targetSrc);
  8028. return BfTypedValue();
  8029. }
  8030. auto methodDef = methodMatcher.mBestMethodDef;
  8031. if (mModule->mCompiler->mResolvePassData != NULL)
  8032. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetSrc, curTypeInst->mTypeDef->GetDefinition(), methodDef);
  8033. // There should always be a constructor
  8034. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  8035. //auto moduleMethodInstance = mModule->GetMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher.mBestMethodGenericArguments);
  8036. auto moduleMethodInstance = GetSelectedMethod(methodMatcher);
  8037. if (!moduleMethodInstance)
  8038. return BfTypedValue();
  8039. if (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc))
  8040. return BfTypedValue();
  8041. BfAutoComplete* autoComplete = GetAutoComplete();
  8042. if (autoComplete != NULL)
  8043. {
  8044. BfTypeInstance* resolvedTypeInstance = target.mType->ToTypeInstance();
  8045. auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(methodDef->mMethodDeclaration);
  8046. if ((autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(targetSrc)) && (!BfNodeIsA<BfDelegateBindExpression>(targetSrc)))
  8047. {
  8048. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  8049. (autoComplete->mDefProp == NULL)
  8050. && ((autoComplete->mDefType == NULL) || (autoComplete->mDefType == resolvedTypeInstance->mTypeDef)))
  8051. {
  8052. // Do we need to do this mDefType setting? If we do, then make sure we only get the element type of generics and such
  8053. //autoComplete->mDefType = resolvedTypeInstance->mTypeDef;
  8054. if (ctorDecl != NULL)
  8055. autoComplete->SetDefinitionLocation(ctorDecl->mThisToken, true);
  8056. else if (resolvedTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  8057. autoComplete->SetDefinitionLocation(resolvedTypeInstance->mTypeDef->mTypeDeclaration->mNameNode, true);
  8058. }
  8059. }
  8060. else if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)) &&
  8061. (moduleMethodInstance.mMethodInstance != NULL))
  8062. {
  8063. autoComplete->mResultString = ":";
  8064. autoComplete->mResultString += mModule->MethodToString(moduleMethodInstance.mMethodInstance);
  8065. }
  8066. }
  8067. BfConstructorDeclaration* ctorDecl = (BfConstructorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration;
  8068. if ((methodMatcher.mBestMethodDef->HasAppend()) && (targetType->IsObject()))
  8069. {
  8070. if (allowAppendKind == BfAllowAppendKind_No)
  8071. {
  8072. if (mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration == NULL)
  8073. mModule->Fail("Constructors with append allocations cannot be called from a default constructor. Considering adding an explicit default constructor with the [AllowAppend] specifier.", targetSrc);
  8074. else
  8075. mModule->Fail("Constructors with append allocations cannot be called from a constructor without [AllowAppend] specified.", targetSrc);
  8076. }
  8077. else
  8078. {
  8079. if ((allowAppendKind == BfAllowAppendKind_Yes) && (methodMatcher.mBestMethodDef->mAppendKind == BfAllowAppendKind_ZeroGap))
  8080. {
  8081. BfError* error;
  8082. if (origAllowAppendKind == BfAllowAppendKind_Infer)
  8083. error = mModule->Fail(StrFormat("Cannot call ZeroGap constructor for type '%s' because of fields added from type extensions", mModule->TypeToString(targetType).c_str()), targetSrc);
  8084. else
  8085. error = mModule->Fail(StrFormat("Cannot call ZeroGap constructor for type '%s' from here", mModule->TypeToString(targetType).c_str()), targetSrc);
  8086. if ((error != NULL) && (methodMatcher.mBestMethodDef->mMethodDeclaration != NULL))
  8087. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodMatcher.mBestMethodDef->GetRefNode());
  8088. }
  8089. BfResolvedArg resolvedArg;
  8090. if (appendIndexValue != NULL)
  8091. {
  8092. resolvedArg.mTypedValue = *appendIndexValue;
  8093. }
  8094. else
  8095. {
  8096. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  8097. auto intPtrRefType = mModule->CreateRefType(intPtrType);
  8098. if (target.mValue.IsFake())
  8099. {
  8100. resolvedArg.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), intPtrRefType);
  8101. }
  8102. else
  8103. {
  8104. BFMODULE_FATAL(mModule, "Bad");
  8105. }
  8106. }
  8107. methodMatcher.mArguments.Insert(0, resolvedArg);
  8108. }
  8109. }
  8110. if (methodMatcher.mAutoFlushAmbiguityErrors)
  8111. methodMatcher.FlushAmbiguityError(true);
  8112. if (isFailurePass)
  8113. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  8114. prevBindResult.Restore();
  8115. return CreateCall(methodMatcher.mTargetSrc, target, BfTypedValue(), methodMatcher.mBestMethodDef, moduleMethodInstance, BfCreateCallFlags_None, methodMatcher.mArguments);
  8116. }
  8117. static int sInvocationIdx = 0;
  8118. BfTypedValue BfExprEvaluator::ResolveArgValue(BfResolvedArg& resolvedArg, BfType* wantType, BfTypedValue* receivingValue, BfParamKind paramKind, BfIdentifierNode* paramNameNode)
  8119. {
  8120. BfTypedValue argValue = resolvedArg.mTypedValue;
  8121. if ((resolvedArg.mArgFlags & BfArgFlag_Finalized) != 0)
  8122. return argValue;
  8123. if ((resolvedArg.mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  8124. {
  8125. if ((!argValue) || (argValue.mValue.IsFake()) || (resolvedArg.mWantsRecalc))
  8126. {
  8127. resolvedArg.mWantsRecalc = false;
  8128. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  8129. if (expr != NULL)
  8130. {
  8131. BfExprEvaluator exprEvaluator(mModule);
  8132. exprEvaluator.mReceivingValue = receivingValue;
  8133. BfEvalExprFlags flags = (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr);
  8134. if ((paramKind == BfParamKind_Params) || (paramKind == BfParamKind_DelegateParam))
  8135. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowParamsExpr);
  8136. argValue = mModule->CreateValueFromExpression(exprEvaluator, expr, wantType, flags);
  8137. if ((argValue) && (argValue.mType != wantType) && (wantType != NULL))
  8138. {
  8139. if ((mDeferScopeAlloc != NULL) && (wantType == mModule->mContext->mBfObjectType))
  8140. {
  8141. BfAllocTarget allocTarget(mDeferScopeAlloc);
  8142. argValue = mModule->BoxValue(expr, argValue, wantType, allocTarget, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  8143. }
  8144. else
  8145. argValue = mModule->Cast(expr, argValue, wantType, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  8146. }
  8147. }
  8148. }
  8149. }
  8150. else if ((resolvedArg.mArgFlags & (BfArgFlag_DeferredValue)) != 0)
  8151. {
  8152. // We should have already had an error on the first call
  8153. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, mModule->mHadBuildError);
  8154. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  8155. BF_ASSERT(expr != NULL);
  8156. argValue = mModule->CreateValueFromExpression(expr, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr));
  8157. resolvedArg.mUncastedTypedValue = argValue;
  8158. if ((argValue) && (wantType != NULL))
  8159. argValue = mModule->Cast(expr, argValue, wantType);
  8160. }
  8161. else if ((resolvedArg.mArgFlags & (BfArgFlag_UntypedDefault)) != 0)
  8162. {
  8163. argValue = mModule->GetDefaultTypedValue(wantType);
  8164. }
  8165. else if ((resolvedArg.mArgFlags & (BfArgFlag_VariableDeclaration | BfArgFlag_UninitializedExpr)) != 0)
  8166. {
  8167. auto variableDeclaration = BfNodeDynCast<BfVariableDeclaration>(resolvedArg.mExpression);
  8168. auto variableType = wantType;
  8169. bool isLet = (variableDeclaration != NULL) && (variableDeclaration->mTypeRef->IsExact<BfLetTypeReference>());
  8170. bool isVar = (variableDeclaration == NULL) || (variableDeclaration->mTypeRef->IsExact<BfVarTypeReference>());
  8171. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  8172. {
  8173. mModule->Fail("Variables cannot be declared in method arguments inside null conditional expressions", variableDeclaration);
  8174. }
  8175. if ((!isLet) && (!isVar))
  8176. {
  8177. if (variableType->IsVar())
  8178. {
  8179. auto resolvedType = mModule->ResolveTypeRef(variableDeclaration->mTypeRef);
  8180. if (resolvedType != NULL)
  8181. variableType = resolvedType;
  8182. }
  8183. else
  8184. {
  8185. mModule->Fail("Only 'ref' or 'var' variables can be declared in method arguments", variableDeclaration);
  8186. auto autoComplete = GetAutoComplete();
  8187. if (autoComplete != NULL)
  8188. autoComplete->CheckTypeRef(variableDeclaration->mTypeRef, true, true);
  8189. }
  8190. }
  8191. else
  8192. {
  8193. if (variableType->IsVar())
  8194. {
  8195. mModule->Fail("Variable type required for 'var' parameter types", variableDeclaration);
  8196. }
  8197. }
  8198. if (wantType->IsRef())
  8199. {
  8200. auto refType = (BfRefType*)wantType;
  8201. variableType = refType->mElementType;
  8202. }
  8203. if ((variableDeclaration != NULL) && (variableDeclaration->mInitializer != NULL))
  8204. {
  8205. mModule->Fail("Initializers cannot be used when declaring variables for 'out' parameters", variableDeclaration->mEqualsNode);
  8206. mModule->CreateValueFromExpression(variableDeclaration->mInitializer, variableType, BfEvalExprFlags_NoCast);
  8207. }
  8208. BfLocalVariable* localVar = new BfLocalVariable();
  8209. if ((variableDeclaration != NULL) && (variableDeclaration->mNameNode != NULL))
  8210. {
  8211. localVar->mName = variableDeclaration->mNameNode->ToString();
  8212. localVar->mNameNode = BfNodeDynCast<BfIdentifierNode>(variableDeclaration->mNameNode);
  8213. }
  8214. else
  8215. {
  8216. if (paramNameNode != NULL)
  8217. {
  8218. localVar->mName = "__";
  8219. paramNameNode->ToString(localVar->mName);
  8220. localVar->mName += "_";
  8221. localVar->mName += StrFormat("%d", mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  8222. }
  8223. else
  8224. localVar->mName = "__" + StrFormat("%d", mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  8225. }
  8226. localVar->mResolvedType = variableType;
  8227. mModule->PopulateType(variableType);
  8228. if (!variableType->IsValuelessType())
  8229. localVar->mAddr = mModule->CreateAlloca(variableType);
  8230. localVar->mIsReadOnly = isLet;
  8231. localVar->mReadFromId = 0;
  8232. localVar->mWrittenToId = 0;
  8233. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  8234. mModule->CheckVariableDef(localVar);
  8235. localVar->Init();
  8236. mModule->AddLocalVariableDef(localVar, true);
  8237. CheckVariableDeclaration(resolvedArg.mExpression, false, false, false);
  8238. argValue = BfTypedValue(localVar->mAddr, mModule->CreateRefType(variableType, BfRefType::RefKind_Out));
  8239. auto curScope = mModule->mCurMethodState->mCurScope;
  8240. if (curScope->mScopeKind == BfScopeKind_StatementTarget)
  8241. {
  8242. // Move this variable into the parent scope
  8243. curScope->mLocalVarStart = (int)mModule->mCurMethodState->mLocals.size();
  8244. }
  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. methodDef = invokeMethodInstance->mMethodDef;
  9367. methodMatcher.mBestMethodInstance = invokeMethodInstance;
  9368. methodMatcher.mBestMethodTypeInstance = invokeMethodInstance->GetOwner();
  9369. methodMatcher.mBestMethodDef = invokeMethodInstance->mMethodDef;
  9370. target = mModule->GetDefaultTypedValue(methodMatcher.mBestMethodTypeInstance);
  9371. isFailurePass = false;
  9372. isIndirectMethodCall = true;
  9373. }
  9374. }
  9375. else if (fieldVal.mType->IsMethodRef())
  9376. {
  9377. auto functionBindResults = prevBindResult.mPrevVal;
  9378. if (functionBindResults != NULL)
  9379. {
  9380. functionBindResults->mOrigTarget = fieldVal;
  9381. }
  9382. origTarget = fieldVal;
  9383. auto methodRefType = (BfMethodRefType*)fieldVal.mType;
  9384. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  9385. methodDef = methodInstance->mMethodDef;
  9386. if (methodDef->mIsLocalMethod)
  9387. {
  9388. methodMatcher.mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodInstance);
  9389. }
  9390. else
  9391. {
  9392. BfTypeVector methodGenericArguments;
  9393. if (methodInstance->mMethodInfoEx != NULL)
  9394. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  9395. methodMatcher.mBestMethodInstance = mModule->GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, methodGenericArguments);
  9396. }
  9397. if (methodInstance->mMethodInfoEx != NULL)
  9398. {
  9399. methodMatcher.mBestMethodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  9400. }
  9401. methodMatcher.mBestMethodTypeInstance = methodInstance->GetOwner();
  9402. if (methodInstance->HasThis())
  9403. {
  9404. bool failed = false;
  9405. target = DoImplicitArgCapture(targetSrc, methodInstance, -1, failed, BfImplicitParamKind_General, origTarget);
  9406. }
  9407. else if (!methodDef->mIsStatic)
  9408. {
  9409. auto thisType = methodInstance->GetParamType(-1);
  9410. BF_ASSERT(thisType->IsValuelessType());
  9411. target = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodMatcher.mBestMethodTypeInstance);
  9412. }
  9413. else
  9414. target = BfTypedValue(methodMatcher.mBestMethodTypeInstance);
  9415. methodMatcher.mBypassVirtual = true;
  9416. bypassVirtual = true;
  9417. isFailurePass = false;
  9418. isIndirectMethodCall = true;
  9419. }
  9420. if (methodDef == NULL)
  9421. {
  9422. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  9423. return BfTypedValue();
  9424. }
  9425. }
  9426. }
  9427. if (methodDef == NULL)
  9428. {
  9429. }
  9430. // This will flush out any new ambiguity errors from extension methods
  9431. methodMatcher.FlushAmbiguityError();
  9432. if (methodDef == NULL)
  9433. {
  9434. FinishDeferredEvals(argValues);
  9435. auto compiler = mModule->mCompiler;
  9436. if ((autoComplete != NULL) && (autoComplete->CheckFixit(targetSrc)))
  9437. {
  9438. mModule->CheckTypeRefFixit(targetSrc);
  9439. bool wantStatic = !target.mValue;
  9440. if ((targetType == NULL) && (allowImplicitThis))
  9441. {
  9442. targetType = mModule->mCurTypeInstance;
  9443. if (mModule->mCurMethodInstance != NULL)
  9444. wantStatic = mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  9445. }
  9446. if (targetType != NULL)
  9447. {
  9448. auto typeInst = targetType->ToTypeInstance();
  9449. if ((typeInst != NULL) && (!methodName.IsEmpty()))
  9450. {
  9451. BfTypeVector paramTypes;
  9452. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  9453. {
  9454. auto& resolvedArg = argValues.mResolvedArgs[argIdx];
  9455. paramTypes.Add(resolvedArg.mTypedValue.mType);
  9456. }
  9457. autoComplete->FixitAddMethod(typeInst, methodName, mExpectingType, paramTypes, wantStatic);
  9458. }
  9459. }
  9460. }
  9461. if (methodName.IsEmpty())
  9462. {
  9463. // Would have caused a parsing error
  9464. }
  9465. else if ((target.mType != NULL) && (origTarget.mType != NULL))
  9466. {
  9467. if (mModule->PreFail())
  9468. {
  9469. if ((origTarget.mType->IsPointer()) && (origTarget.mType->GetUnderlyingType()->IsObjectOrInterface()))
  9470. {
  9471. mModule->Fail(StrFormat("Methods cannot be called on type '%s' because the type is a pointer to a reference type (ie: a double-reference).",
  9472. mModule->TypeToString(origTarget.mType).c_str()), targetSrc);
  9473. }
  9474. else
  9475. mModule->Fail(StrFormat("Method '%s' does not exist in type '%s'", methodName.c_str(), mModule->TypeToString(target.mType).c_str()), targetSrc);
  9476. }
  9477. }
  9478. else
  9479. {
  9480. if (mModule->PreFail())
  9481. mModule->Fail(StrFormat("Method '%s' does not exist", methodName.c_str()), targetSrc);
  9482. }
  9483. return BfTypedValue();
  9484. }
  9485. if ((prevBindResult.mPrevVal != NULL) && (methodMatcher.mMethodCheckCount > 1))
  9486. prevBindResult.mPrevVal->mCheckedMultipleMethods = true;
  9487. BfType* overrideReturnType = NULL;
  9488. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, curTypeInst, methodDef, methodMatcher, &overrideReturnType);
  9489. if ((mModule->mAttributeState != NULL) && ((mModule->mAttributeState->mFlags & (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)) ==
  9490. (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)))
  9491. {
  9492. FinishDeferredEvals(argValues);
  9493. return BfTypedValue();
  9494. }
  9495. if ((moduleMethodInstance.mMethodInstance != NULL) && (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc)))
  9496. {
  9497. FinishDeferredEvals(argValues);
  9498. return BfTypedValue();
  9499. }
  9500. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  9501. {
  9502. if (methodMatcher.mHasVarArguments)
  9503. {
  9504. BfType* retType = mModule->GetPrimitiveType(BfTypeCode_Var);
  9505. if ((!methodMatcher.mHadVarConflictingReturnType) && (methodMatcher.mBestRawMethodInstance != NULL) && (!methodMatcher.mBestRawMethodInstance->mReturnType->IsUnspecializedTypeVariation()) &&
  9506. (prevBindResult.mPrevVal == NULL))
  9507. {
  9508. if ((!methodMatcher.mBestRawMethodInstance->mReturnType->IsGenericParam()) ||
  9509. (((BfGenericParamType*)methodMatcher.mBestRawMethodInstance->mReturnType)->mGenericParamKind != BfGenericParamKind_Method))
  9510. retType = methodMatcher.mBestRawMethodInstance->mReturnType;
  9511. }
  9512. return mModule->GetDefaultTypedValue(retType, true, BfDefaultValueKind_Addr);
  9513. }
  9514. }
  9515. if ((bypassVirtual) && (!target.mValue) && (target.mType->IsInterface()))
  9516. {
  9517. target = mModule->GetThis();
  9518. }
  9519. if (!moduleMethodInstance)
  9520. {
  9521. FinishDeferredEvals(argValues);
  9522. if (mModule->IsInUnspecializedGeneric())
  9523. return mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  9524. return BfTypedValue();
  9525. }
  9526. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  9527. if ((moduleMethodInstance.mMethodInstance->IsOrInUnspecializedVariation()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  9528. {
  9529. // Invalid methods such as types with a HasVar tuple generic arg will be marked as mIsUnspecializedVariation and shouldn't actually be called
  9530. FinishDeferredEvals(argValues);
  9531. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  9532. }
  9533. if (methodDef->IsEmptyPartial())
  9534. {
  9535. // Ignore call
  9536. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  9537. }
  9538. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mIsStatic) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  9539. {
  9540. bool isConstrained = false;
  9541. if (target.mType != NULL)
  9542. isConstrained = target.mType->IsGenericParam();
  9543. if ((target.mType == NULL) && ((mModule->mCurMethodInstance->mIsForeignMethodDef) || (mModule->mCurTypeInstance->IsInterface())))
  9544. isConstrained = true;
  9545. // If mIgnoreWrites is off then we skip devirtualization, so allow this
  9546. if ((target.mType != NULL) && (!target.mType->IsInterface()) && (mModule->mBfIRBuilder->mIgnoreWrites))
  9547. isConstrained = true;
  9548. if (!isConstrained)
  9549. {
  9550. if (mModule->mCurTypeInstance->IsInterface())
  9551. {
  9552. if (methodDef->mBody == NULL)
  9553. mModule->Fail(StrFormat("Interface method '%s' must provide a body to be explicitly invoked", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  9554. }
  9555. else
  9556. 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);
  9557. FinishDeferredEvals(argValues);
  9558. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  9559. }
  9560. }
  9561. // 'base' could really mean 'this' if we're in an extension
  9562. if ((target.IsBase()) && (targetTypeInst == mModule->mCurTypeInstance))
  9563. target.ToThis();
  9564. else
  9565. MakeBaseConcrete(target);
  9566. BfType* callTargetType = curTypeInst;
  9567. if (methodDef->mMethodType == BfMethodType_Extension)
  9568. {
  9569. callTargetType = moduleMethodInstance.mMethodInstance->GetParamType(0);
  9570. if ((callTargetType->IsRef()) && (target.IsAddr()) && (!target.IsReadOnly()) && (target.mType->IsValueType()))
  9571. {
  9572. auto refType = (BfRefType*)callTargetType;
  9573. target = BfTypedValue(target.mValue, mModule->CreateRefType(target.mType, refType->mRefKind));
  9574. }
  9575. }
  9576. BfTypedValue callTarget;
  9577. if (isSkipCall)
  9578. {
  9579. // Just a fake value so we can continue on without generating any code (boxing, conversion, etc)
  9580. if (target)
  9581. {
  9582. if (((target.mType->IsComposite()) || (target.mType->IsTypedPrimitive())))
  9583. {
  9584. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mIsMutating) &&
  9585. ((target.IsReadOnly()) || (!target.IsAddr())))
  9586. {
  9587. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str());
  9588. CheckModifyResult(target, targetSrc, err.c_str());
  9589. }
  9590. }
  9591. callTarget = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), targetTypeInst);
  9592. }
  9593. }
  9594. else if (targetTypeInst == callTargetType)
  9595. {
  9596. if ((target) && (methodDef->HasNoThisSplat()))
  9597. {
  9598. callTarget = mModule->MakeAddressable(target);
  9599. }
  9600. else
  9601. callTarget = target;
  9602. if ((callTarget) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  9603. {
  9604. auto wantThis = moduleMethodInstance.mMethodInstance->GetParamType(-1);
  9605. if ((callTarget.mType != wantThis) && (wantThis->IsInterface()))
  9606. callTarget = mModule->Cast(targetSrc, callTarget, wantThis, BfCastFlags_Explicit);
  9607. }
  9608. }
  9609. else if (target)
  9610. {
  9611. if (methodMatcher.mFakeConcreteTarget)
  9612. {
  9613. BF_ASSERT(callTargetType->IsInterface());
  9614. callTarget = mModule->GetDefaultTypedValue(mModule->CreateConcreteInterfaceType(callTargetType->ToTypeInstance()));
  9615. }
  9616. else if (((target.mType->IsGenericParam()) || (target.mType->IsConcreteInterfaceType())) && (callTargetType->IsInterface()))
  9617. {
  9618. // Leave as generic
  9619. callTarget = target;
  9620. }
  9621. else
  9622. {
  9623. bool handled = false;
  9624. if ((target.mType->IsTypedPrimitive()) && (callTargetType->IsTypedPrimitive()))
  9625. {
  9626. handled = true;
  9627. callTarget = target;
  9628. }
  9629. else if ((target.mType->IsStructOrStructPtr()) || (target.mType->IsTypedPrimitive()))
  9630. {
  9631. //BF_ASSERT(target.IsAddr());
  9632. if (callTargetType->IsObjectOrInterface())
  9633. {
  9634. // Box it
  9635. callTarget = mModule->Cast(targetSrc, target, callTargetType, BfCastFlags_Explicit);
  9636. handled = true;
  9637. }
  9638. else
  9639. {
  9640. //BF_ASSERT(target.IsAddr() || target.IsSplat() || target.mType->IsPointer());
  9641. }
  9642. }
  9643. else
  9644. target = mModule->LoadValue(target);
  9645. if (!handled)
  9646. {
  9647. // Could we have just unconditionally done this?
  9648. callTarget = mModule->Cast(targetSrc, target, callTargetType, BfCastFlags_Explicit);
  9649. }
  9650. }
  9651. }
  9652. if (isFailurePass)
  9653. {
  9654. BfError* error;
  9655. if (methodMatcher.mMatchFailKind == BfMethodMatcher::MatchFailKind_CheckedMismatch)
  9656. 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);
  9657. else
  9658. error = mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  9659. if (error != NULL)
  9660. {
  9661. if ((error != NULL) && (moduleMethodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL))
  9662. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), moduleMethodInstance.mMethodInstance->mMethodDef->GetRefNode());
  9663. }
  9664. }
  9665. if ((mModule->mCompiler->mResolvePassData != NULL) && (methodDef != NULL))
  9666. {
  9667. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  9668. while (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode))
  9669. identifierNode = qualifiedNameNode->mRight;
  9670. if ((identifierNode != NULL) && (methodDef->mIdx >= 0) && (!isIndirectMethodCall) &&
  9671. ((targetTypeInst == NULL) || (!targetTypeInst->IsDelegateOrFunction())))
  9672. {
  9673. auto refMethodInstance = moduleMethodInstance.mMethodInstance;
  9674. if (refMethodInstance->mVirtualTableIdx != -1)
  9675. {
  9676. auto& virtualEntry = refMethodInstance->GetOwner()->mVirtualMethodTable[refMethodInstance->mVirtualTableIdx];
  9677. refMethodInstance = virtualEntry.mDeclaringMethod;
  9678. }
  9679. mModule->mCompiler->mResolvePassData->HandleMethodReference(identifierNode, refMethodInstance->GetOwner()->mTypeDef, refMethodInstance->mMethodDef);
  9680. auto autoComplete = GetAutoComplete();
  9681. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  9682. {
  9683. autoComplete->SetDefinitionLocation(methodDef->GetRefNode(), true);
  9684. int virtualIdx = moduleMethodInstance.mMethodInstance->mVirtualTableIdx;
  9685. if ((autoComplete->mResolveType == BfResolveType_GoToDefinition) &&
  9686. (virtualIdx != -1) && (targetTypeInst != NULL) && (!targetTypeInst->IsStruct()) && (!targetTypeInst->IsTypedPrimitive()) && (!targetTypeInst->IsInterface()) &&
  9687. // 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
  9688. (targetTypeInst->mVirtualMethodTable.size() != 0))
  9689. {
  9690. auto methodEntry = targetTypeInst->mVirtualMethodTable[virtualIdx];
  9691. if (methodEntry.mImplementingMethod.mMethodNum != -1)
  9692. {
  9693. BfMethodInstance* callingMethodInstance = methodEntry.mImplementingMethod;
  9694. if (callingMethodInstance != NULL)
  9695. {
  9696. auto callingMethodDef = callingMethodInstance->mMethodDef;
  9697. auto callingMethodDeclaration = callingMethodDef->GetMethodDeclaration();
  9698. if ((callingMethodDeclaration != NULL) && (callingMethodDeclaration->mNameNode != NULL))
  9699. autoComplete->SetDefinitionLocation(callingMethodDeclaration->mNameNode, true);
  9700. }
  9701. }
  9702. }
  9703. if (autoComplete->mDefType == NULL)
  9704. {
  9705. autoComplete->mDefMethod = refMethodInstance->mMethodDef;
  9706. autoComplete->mDefType = refMethodInstance->GetOwner()->mTypeDef;
  9707. }
  9708. if (autoComplete->mResolveType == BfResolveType_GetResultString)
  9709. {
  9710. autoComplete->mResultString = ":";
  9711. autoComplete->mResultString += mModule->MethodToString(moduleMethodInstance.mMethodInstance);
  9712. auto methodDecl = moduleMethodInstance.mMethodInstance->mMethodDef->GetMethodDeclaration();
  9713. if ((methodDecl != NULL) && (methodDecl->mDocumentation != NULL))
  9714. {
  9715. autoComplete->mResultString += "\x03";
  9716. methodDecl->mDocumentation->GetDocString(autoComplete->mResultString);
  9717. }
  9718. }
  9719. }
  9720. }
  9721. }
  9722. // This was causing forward-backward-forward steps when we just used 'targetSrc'. Using closeParen is undesirable because most of the time
  9723. // we DO just want it to just go to the targetSrc... do we even need this?
  9724. /*if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(targetSrc->mParent))
  9725. {
  9726. // We set the srcPos to the close paren right before the call so we keep a forward progression of src positions in the case
  9727. // where some of the params are method calls and such
  9728. if (invokeExpr->mCloseParen != NULL)
  9729. mModule->UpdateExprSrcPos(invokeExpr->mCloseParen);
  9730. else
  9731. mModule->UpdateExprSrcPos(targetSrc);
  9732. }
  9733. else
  9734. mModule->UpdateExprSrcPos(targetSrc);*/
  9735. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  9736. {
  9737. //BF_ASSERT(!callTarget.mValue.IsFake());
  9738. }
  9739. prevBindResult.Restore();
  9740. // Check mut
  9741. if ((callTarget.mType != NULL) &&
  9742. (callTarget.mType->IsGenericParam()) &&
  9743. ((!callTarget.IsAddr()) || (callTarget.IsReadOnly())) &&
  9744. (callTarget.mKind != BfTypedValueKind_MutableValue) &&
  9745. (moduleMethodInstance.mMethodInstance->mMethodDef->mIsMutating))
  9746. {
  9747. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)callTarget.mType);
  9748. bool needsMut = true;
  9749. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class | BfGenericParamFlag_Var)) != 0)
  9750. needsMut = false;
  9751. if (genericParamInstance->mTypeConstraint != NULL)
  9752. {
  9753. auto typeConstaintTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  9754. if ((typeConstaintTypeInstance != NULL) && (!typeConstaintTypeInstance->IsComposite()))
  9755. needsMut = false;
  9756. }
  9757. if ((mFunctionBindResult != NULL) && (mFunctionBindResult->mSkipMutCheck))
  9758. needsMut = false;
  9759. if (needsMut)
  9760. {
  9761. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str());
  9762. CheckModifyResult(callTarget, targetSrc, err.c_str(), true);
  9763. }
  9764. }
  9765. // Check mut on interface
  9766. if ((callTarget.mType != NULL) &&
  9767. (callTarget.mType->IsInterface()) &&
  9768. (target.IsThis()) &&
  9769. (mModule->mCurTypeInstance) &&
  9770. (!mModule->mCurMethodInstance->mMethodDef->mIsMutating) &&
  9771. (methodDef->mIsMutating))
  9772. {
  9773. mModule->Fail(StrFormat("Cannot call mutating method '%s' within default interface method '%s'. Consider adding 'mut' specifier to this method.",
  9774. mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), targetSrc);
  9775. }
  9776. BfTypedValue result;
  9777. BfTypedValue argCascade;
  9778. BfCreateCallFlags subCallFlags = BfCreateCallFlags_None;
  9779. if (bypassVirtual)
  9780. subCallFlags = (BfCreateCallFlags)(subCallFlags | BfCreateCallFlags_BypassVirtual);
  9781. if (skipThis)
  9782. subCallFlags = (BfCreateCallFlags)(subCallFlags | BfCreateCallFlags_SkipThis);
  9783. result = CreateCall(targetSrc, callTarget, origTarget, methodDef, moduleMethodInstance, subCallFlags, argValues.mResolvedArgs, &argCascade);
  9784. if (overrideReturnType != NULL)
  9785. {
  9786. BF_ASSERT(moduleMethodInstance.mMethodInstance->mIsUnspecializedVariation);
  9787. result = mModule->GetDefaultTypedValue(overrideReturnType, false, BfDefaultValueKind_Addr);
  9788. }
  9789. if (result)
  9790. {
  9791. if (result.mType->IsRef())
  9792. result = mModule->RemoveRef(result);
  9793. }
  9794. PerformCallChecks(moduleMethodInstance.mMethodInstance, targetSrc);
  9795. if (result)
  9796. {
  9797. bool discardedReturnValue = mUsedAsStatement;
  9798. if (discardedReturnValue)
  9799. {
  9800. auto _ShowDiscardWaring = [&](const String& text, BfCustomAttributes* customAttributes, BfIRConstHolder* constHolder, BfAstNode* refNode)
  9801. {
  9802. if (customAttributes != NULL)
  9803. {
  9804. auto customAttribute = customAttributes->Get(mModule->mCompiler->mNoDiscardAttributeTypeDef);
  9805. if (!customAttribute->mCtorArgs.IsEmpty())
  9806. {
  9807. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  9808. if ((str != NULL) && (!str->IsEmpty()))
  9809. {
  9810. mModule->Warn(0, text + ": " + *str, targetSrc);
  9811. return;
  9812. }
  9813. }
  9814. }
  9815. mModule->Warn(0, text, targetSrc);
  9816. };
  9817. bool showedWarning = false;
  9818. if (moduleMethodInstance.mMethodInstance->mMethodDef->mIsNoDiscard)
  9819. {
  9820. _ShowDiscardWaring("Discarding return value of method with [NoDiscard] attribute", moduleMethodInstance.mMethodInstance->GetCustomAttributes(),
  9821. moduleMethodInstance.mMethodInstance->GetOwner()->mConstHolder, targetSrc);
  9822. showedWarning = true;
  9823. }
  9824. auto typeInst = result.mType->ToTypeInstance();
  9825. if (typeInst != NULL)
  9826. {
  9827. if ((typeInst->mTypeDef->mIsNoDiscard) && (!showedWarning))
  9828. {
  9829. _ShowDiscardWaring("Discarding return value whose type has [NoDiscard] attribute", typeInst->mCustomAttributes, typeInst->mConstHolder, targetSrc);
  9830. }
  9831. BfModuleMethodInstance moduleMethodInstance = mModule->GetMethodByName(typeInst, "ReturnValueDiscarded", 0, true);
  9832. if (moduleMethodInstance)
  9833. {
  9834. bool wasCapturingMethodMatchInfo = false;
  9835. if (autoComplete != NULL)
  9836. {
  9837. wasCapturingMethodMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  9838. autoComplete->mIsCapturingMethodMatchInfo = false;
  9839. }
  9840. defer
  9841. (
  9842. if (autoComplete != NULL)
  9843. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMethodMatchInfo;
  9844. );
  9845. auto wasGetDefinition = (autoComplete != NULL) && (autoComplete->mIsGetDefinition);
  9846. if (wasGetDefinition)
  9847. autoComplete->mIsGetDefinition = false;
  9848. result = mModule->MakeAddressable(result);
  9849. BfResolvedArgs resolvedArgs;
  9850. MatchMethod(targetSrc, NULL, result, false, false, "ReturnValueDiscarded", resolvedArgs, BfMethodGenericArguments());
  9851. if (wasGetDefinition)
  9852. autoComplete->mIsGetDefinition = true;
  9853. }
  9854. }
  9855. }
  9856. }
  9857. if (argCascade)
  9858. {
  9859. if (argCascade.mType->IsRef())
  9860. argCascade = mModule->RemoveRef(argCascade);
  9861. result = argCascade;
  9862. }
  9863. if (result)
  9864. {
  9865. if ((result.mType->IsUnspecializedTypeVariation()) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  9866. {
  9867. BfType* selfType = NULL;
  9868. if (methodMatcher.mSelfType != NULL)
  9869. {
  9870. BF_ASSERT(mModule->IsInGeneric());
  9871. selfType = methodMatcher.mSelfType;
  9872. }
  9873. else
  9874. {
  9875. // Will be an error
  9876. selfType = methodMatcher.mBestMethodTypeInstance;
  9877. }
  9878. if ((selfType != NULL) && (!selfType->IsInterface()))
  9879. {
  9880. auto resolvedType = mModule->ResolveSelfType(result.mType, selfType);
  9881. if ((resolvedType != NULL) && (resolvedType != result.mType))
  9882. result = mModule->GetDefaultTypedValue(resolvedType);
  9883. }
  9884. }
  9885. }
  9886. return result;
  9887. }
  9888. void BfExprEvaluator::LookupQualifiedName(BfQualifiedNameNode* nameNode, bool ignoreInitialError, bool* hadError)
  9889. {
  9890. BfIdentifierNode* nameLeft = nameNode->mLeft;
  9891. BfIdentifierNode* nameRight = nameNode->mRight;
  9892. StringT<64> fieldName;
  9893. if (nameNode->mRight != NULL)
  9894. nameNode->mRight->ToString(fieldName);
  9895. bool wasBaseLookup = false;
  9896. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  9897. {
  9898. if (CheckIsBase(qualifiedLeftName->mRight))
  9899. {
  9900. wasBaseLookup = true;
  9901. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  9902. if (type == NULL)
  9903. return;
  9904. auto fieldName = nameNode->mRight->ToString();
  9905. auto target = mModule->GetThis();
  9906. target.mType = type;
  9907. mResult = LookupField(nameNode->mRight, target, fieldName);
  9908. if ((mPropDef != NULL) && (mPropDef->IsVirtual()))
  9909. mPropDefBypassVirtual = true;
  9910. return;
  9911. }
  9912. }
  9913. if (!wasBaseLookup)
  9914. mResult = LookupIdentifier(nameNode->mLeft, ignoreInitialError, hadError);
  9915. GetResult();
  9916. if (!mResult)
  9917. {
  9918. if (!ignoreInitialError)
  9919. mModule->Fail("Identifier not found", nameNode->mLeft);
  9920. return;
  9921. }
  9922. if (mResult.mType->IsObject())
  9923. {
  9924. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  9925. }
  9926. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  9927. {
  9928. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  9929. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  9930. mResult.mType = structPtrType->mElementType;
  9931. if (mResult.mKind == BfTypedValueKind_ThisValue)
  9932. mResult.mKind = BfTypedValueKind_ThisAddr;
  9933. else
  9934. mResult.mKind = BfTypedValueKind_Addr;
  9935. }
  9936. mIsVolatileReference = false;
  9937. mIsHeapReference = false;
  9938. if (!mResult)
  9939. return;
  9940. auto origResult = mResult;
  9941. auto lookupType = BindGenericType(nameNode, mResult.mType);
  9942. if (IsVar(mResult.mType))
  9943. {
  9944. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType, true);
  9945. return;
  9946. }
  9947. if ((!mResult.mType->IsTypeInstance()) && (!mResult.mType->IsGenericParam()))
  9948. {
  9949. if (hadError != NULL)
  9950. *hadError = true;
  9951. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  9952. mResult = BfTypedValue();
  9953. return;
  9954. }
  9955. BfTypedValue lookupVal = mResult;
  9956. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  9957. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  9958. {
  9959. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType, true);
  9960. SizedArray<BfTypeInstance*, 8> searchConstraints;
  9961. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  9962. {
  9963. if (!searchConstraints.Contains(ifaceConstraint))
  9964. {
  9965. searchConstraints.push_back(ifaceConstraint);
  9966. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  9967. {
  9968. auto innerIFace = innerIFaceEntry.mInterfaceType;
  9969. if (!searchConstraints.Contains(innerIFace))
  9970. {
  9971. searchConstraints.push_back(innerIFace);
  9972. }
  9973. }
  9974. }
  9975. }
  9976. BfTypedValue prevTarget;
  9977. BfPropertyDef* prevDef = NULL;
  9978. for (auto ifaceConstraint : searchConstraints)
  9979. {
  9980. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  9981. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  9982. if (mPropDef != NULL)
  9983. {
  9984. if (prevDef != NULL)
  9985. {
  9986. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  9987. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  9988. if ((isWorse) && (!isBetter))
  9989. continue;
  9990. if (isBetter == isWorse)
  9991. {
  9992. auto error = mModule->Fail("Ambiguous property reference", nameNode->mRight);
  9993. if (error != NULL)
  9994. {
  9995. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  9996. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  9997. }
  9998. }
  9999. }
  10000. prevDef = mPropDef;
  10001. prevTarget = mPropTarget;
  10002. }
  10003. }
  10004. /*if ((mResult) || (mPropDef != NULL))
  10005. break;*/
  10006. }
  10007. if (mPropDef != NULL)
  10008. {
  10009. mOrigPropTarget = origResult;
  10010. if (((CheckIsBase(nameNode->mLeft)) || (wasBaseLookup)) && (mPropDef->IsVirtual()))
  10011. mPropDefBypassVirtual = true;
  10012. }
  10013. if ((mResult) || (mPropDef != NULL))
  10014. return;
  10015. if (hadError != NULL)
  10016. *hadError = true;
  10017. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  10018. auto compiler = mModule->mCompiler;
  10019. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  10020. {
  10021. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), false);
  10022. }
  10023. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(lookupType).c_str()), nameNode->mRight);
  10024. }
  10025. void BfExprEvaluator::LookupQualifiedName(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreInitialError, bool* hadError)
  10026. {
  10027. String fieldName;
  10028. if (nameRight != NULL)
  10029. fieldName = nameRight->ToString();
  10030. bool wasBaseLookup = false;
  10031. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  10032. {
  10033. if (CheckIsBase(qualifiedLeftName->mRight))
  10034. {
  10035. wasBaseLookup = true;
  10036. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  10037. if (type == NULL)
  10038. return;
  10039. auto fieldName = nameRight->ToString();
  10040. auto target = mModule->GetThis();
  10041. target.mType = type;
  10042. mResult = LookupField(nameRight, target, fieldName);
  10043. if ((mPropDef != NULL) && (mPropDef->IsVirtual()))
  10044. mPropDefBypassVirtual = true;
  10045. return;
  10046. }
  10047. }
  10048. if (!wasBaseLookup)
  10049. {
  10050. mResult = LookupIdentifier(nameLeft, ignoreInitialError, hadError);
  10051. if ((mResult) && (!mResult.mType->IsComposite()))
  10052. CheckResultForReading(mResult);
  10053. }
  10054. GetResult();
  10055. if (!mResult)
  10056. {
  10057. if (!ignoreInitialError)
  10058. mModule->Fail("Identifier not found", nameLeft);
  10059. return;
  10060. }
  10061. if (mResult.mType->IsObject())
  10062. {
  10063. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  10064. }
  10065. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  10066. {
  10067. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  10068. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  10069. mResult.mType = structPtrType->mElementType;
  10070. if (mResult.mKind == BfTypedValueKind_ThisValue)
  10071. mResult.mKind = BfTypedValueKind_ThisAddr;
  10072. else
  10073. mResult.mKind = BfTypedValueKind_Addr;
  10074. }
  10075. mIsVolatileReference = false;
  10076. mIsHeapReference = false;
  10077. if (!mResult)
  10078. return;
  10079. if (mResult.mType->IsAllocType())
  10080. mResult.mType = mResult.mType->GetUnderlyingType();
  10081. auto origResult = mResult;
  10082. if (IsVar(mResult.mType))
  10083. {
  10084. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  10085. mResult = BfTypedValue(mModule->GetDefaultValue(varType), varType, true);
  10086. return;
  10087. }
  10088. if ((!mResult.mType->IsTypeInstance()) && (!mResult.mType->IsGenericParam()))
  10089. {
  10090. if (mResult.mType->IsSizedArray())
  10091. {
  10092. if (mResult.mType->IsValuelessType())
  10093. {
  10094. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  10095. mResult.mValue = mModule->mBfIRBuilder->GetFakeVal();
  10096. }
  10097. else
  10098. {
  10099. mResult = mModule->MakeAddressable(mResult);
  10100. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  10101. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  10102. }
  10103. }
  10104. else if (mResult.mType->IsWrappableType())
  10105. {
  10106. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  10107. }
  10108. else
  10109. {
  10110. if (hadError != NULL)
  10111. *hadError = true;
  10112. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  10113. mResult = BfTypedValue();
  10114. return;
  10115. }
  10116. }
  10117. BfTypedValue lookupVal = mResult;
  10118. auto lookupType = BindGenericType(nameNode, mResult.mType);
  10119. if ((lookupType->IsGenericParam()) && (!mResult.mType->IsGenericParam()))
  10120. {
  10121. bool prevUseMixinGenerics = false;
  10122. if (mModule->mCurMethodState->mMixinState != NULL)
  10123. {
  10124. prevUseMixinGenerics = mModule->mCurMethodState->mMixinState->mUseMixinGenerics;
  10125. mModule->mCurMethodState->mMixinState->mUseMixinGenerics = true;
  10126. }
  10127. // Try to lookup from generic binding
  10128. mResult = LookupField(nameRight, BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), lookupType), fieldName, BfLookupFieldFlag_BindOnly);
  10129. if (mModule->mCurMethodState->mMixinState != NULL)
  10130. mModule->mCurMethodState->mMixinState->mUseMixinGenerics = prevUseMixinGenerics;
  10131. if (mPropDef != NULL)
  10132. {
  10133. mOrigPropTarget = lookupVal;
  10134. return;
  10135. }
  10136. }
  10137. if (mPropDef == NULL)
  10138. mResult = LookupField(nameRight, lookupVal, fieldName, CheckIsBase(nameLeft) ? BfLookupFieldFlag_BaseLookup : BfLookupFieldFlag_None);
  10139. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  10140. {
  10141. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType, true);
  10142. SizedArray<BfTypeInstance*, 8> searchConstraints;
  10143. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  10144. {
  10145. if (!searchConstraints.Contains(ifaceConstraint))
  10146. {
  10147. searchConstraints.push_back(ifaceConstraint);
  10148. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  10149. {
  10150. auto innerIFace = innerIFaceEntry.mInterfaceType;
  10151. if (!searchConstraints.Contains(innerIFace))
  10152. {
  10153. searchConstraints.push_back(innerIFace);
  10154. }
  10155. }
  10156. }
  10157. }
  10158. BfTypedValue prevTarget;
  10159. BfPropertyDef* prevDef = NULL;
  10160. for (auto ifaceConstraint : searchConstraints)
  10161. {
  10162. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  10163. mResult = LookupField(nameRight, lookupVal, fieldName);
  10164. if (mPropDef != NULL)
  10165. {
  10166. if (prevDef != NULL)
  10167. {
  10168. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  10169. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  10170. if ((isWorse) && (!isBetter))
  10171. continue;
  10172. if (isBetter == isWorse)
  10173. {
  10174. auto error = mModule->Fail("Ambiguous property reference", nameRight);
  10175. if (error != NULL)
  10176. {
  10177. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  10178. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  10179. }
  10180. }
  10181. }
  10182. prevDef = mPropDef;
  10183. prevTarget = mPropTarget;
  10184. }
  10185. }
  10186. if ((mPropDef == NULL) && (genericParamInst->IsEnum()))
  10187. {
  10188. if ((fieldName == "Underlying") || (fieldName == "UnderlyingRef"))
  10189. {
  10190. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  10191. return;
  10192. }
  10193. }
  10194. }
  10195. if (mPropDef != NULL)
  10196. {
  10197. mOrigPropTarget = origResult;
  10198. if ((CheckIsBase(nameLeft)) || (wasBaseLookup))
  10199. {
  10200. if (mPropDef->IsVirtual())
  10201. mPropDefBypassVirtual = true;
  10202. }
  10203. }
  10204. if ((mResult) || (mPropDef != NULL))
  10205. return;
  10206. if (hadError != NULL)
  10207. *hadError = true;
  10208. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  10209. auto compiler = mModule->mCompiler;
  10210. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  10211. {
  10212. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), false);
  10213. }
  10214. if (((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0) && (typeInst != NULL) && (CheckForMethodName(nameRight, typeInst, fieldName)))
  10215. return;
  10216. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(lookupType).c_str()), nameRight);
  10217. }
  10218. void BfExprEvaluator::LookupQualifiedStaticField(BfQualifiedNameNode* nameNode, bool ignoreIdentifierNotFoundError)
  10219. {
  10220. // Lookup left side as a type
  10221. {
  10222. BfType* type = NULL;
  10223. {
  10224. type = mModule->ResolveTypeRef(nameNode->mLeft, NULL, BfPopulateType_Data, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_AllowRef | BfResolveTypeRefFlag_IgnoreLookupError));
  10225. mModule->CheckTypeRefFixit(nameNode->mLeft);
  10226. }
  10227. if (type != NULL)
  10228. {
  10229. BfTypedValue lookupType;
  10230. if (type->IsWrappableType())
  10231. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  10232. else
  10233. lookupType = BfTypedValue(type);
  10234. auto findName = nameNode->mRight->ToString();
  10235. /*if (findName == "base")
  10236. {
  10237. mResult = BfTypedValue(lookupType);
  10238. return;
  10239. }*/
  10240. mResult = LookupField(nameNode->mRight, lookupType, findName);
  10241. if ((mResult) || (mPropDef != NULL))
  10242. return;
  10243. if (lookupType.mType != NULL)
  10244. {
  10245. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  10246. auto compiler = mModule->mCompiler;
  10247. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  10248. {
  10249. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), true);
  10250. }
  10251. }
  10252. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  10253. mModule->Fail("Field not found", nameNode->mRight);
  10254. return;
  10255. }
  10256. }
  10257. String fieldName = nameNode->mRight->ToString();
  10258. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  10259. LookupQualifiedStaticField(qualifiedLeftName, true);
  10260. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameNode->mLeft))
  10261. {
  10262. mResult = LookupIdentifier(leftName);
  10263. }
  10264. GetResult();
  10265. if (!mResult)
  10266. {
  10267. if (!ignoreIdentifierNotFoundError)
  10268. mModule->Fail("Identifier not found", nameNode->mLeft);
  10269. return;
  10270. }
  10271. if (mResult.mType->IsObject())
  10272. {
  10273. mResult = mModule->LoadValue(mResult);
  10274. }
  10275. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  10276. {
  10277. BfPointerType* structPtrType = (BfPointerType*) mResult.mType;
  10278. mResult = mModule->LoadValue(mResult);
  10279. mResult.mType = structPtrType->mElementType;
  10280. }
  10281. if (!mResult)
  10282. return;
  10283. if (!mResult.mType->IsTypeInstance())
  10284. {
  10285. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  10286. return;
  10287. }
  10288. auto leftResult = mResult;
  10289. mResult = LookupField(nameNode->mRight, leftResult, fieldName);
  10290. if ((mResult) || (mPropDef != NULL))
  10291. return;
  10292. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(leftResult.mType).c_str()), nameNode->mRight);
  10293. }
  10294. void BfExprEvaluator::LookupQualifiedStaticField(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreIdentifierNotFoundError)
  10295. {
  10296. // Lookup left side as a type
  10297. {
  10298. BfType* type = mModule->ResolveTypeRef(nameLeft, NULL, BfPopulateType_Declaration, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_IgnoreLookupError | BfResolveTypeRefFlag_AllowGlobalContainer));
  10299. if ((type != NULL) && (type->IsVar()) && (nameLeft->Equals("var")))
  10300. type = NULL;
  10301. if (type != NULL)
  10302. {
  10303. BfTypedValue lookupType;
  10304. if (type->IsWrappableType())
  10305. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  10306. else
  10307. lookupType = BfTypedValue(type);
  10308. auto findName = nameRight->ToString();
  10309. if ((lookupType.mType != NULL) && (lookupType.mType->IsGenericParam()))
  10310. {
  10311. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType.mType);
  10312. if (genericParamInstance->mTypeConstraint != NULL)
  10313. {
  10314. mResult = LookupField(nameRight, BfTypedValue(genericParamInstance->mTypeConstraint), findName);
  10315. if ((mResult) || (mPropDef != NULL))
  10316. {
  10317. mOrigPropTarget = lookupType;
  10318. return;
  10319. }
  10320. }
  10321. for (auto constraint : genericParamInstance->mInterfaceConstraints)
  10322. {
  10323. mResult = LookupField(nameRight, BfTypedValue(constraint), findName);
  10324. if ((mResult) || (mPropDef != NULL))
  10325. {
  10326. mOrigPropTarget = lookupType;
  10327. return;
  10328. }
  10329. }
  10330. }
  10331. /*if (findName == "base")
  10332. {
  10333. mResult = BfTypedValue(lookupType);
  10334. return;
  10335. }*/
  10336. mResult = LookupField(nameRight, lookupType, findName);
  10337. if ((mResult) || (mPropDef != NULL))
  10338. return;
  10339. if (lookupType.mType != NULL)
  10340. {
  10341. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  10342. auto compiler = mModule->mCompiler;
  10343. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  10344. {
  10345. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), true);
  10346. }
  10347. }
  10348. if ((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0)
  10349. {
  10350. auto typeInst = lookupType.mType->ToTypeInstance();
  10351. if ((typeInst != NULL) && (CheckForMethodName(nameRight, typeInst, findName)))
  10352. return;
  10353. }
  10354. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  10355. mModule->Fail("Field not found", nameRight);
  10356. return;
  10357. }
  10358. }
  10359. String fieldName = nameRight->ToString();
  10360. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  10361. LookupQualifiedStaticField(qualifiedLeftName, qualifiedLeftName->mLeft, qualifiedLeftName->mRight, true);
  10362. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameLeft))
  10363. {
  10364. mResult = LookupIdentifier(leftName);
  10365. }
  10366. GetResult();
  10367. if (!mResult)
  10368. {
  10369. if (!ignoreIdentifierNotFoundError)
  10370. mModule->Fail("Identifier not found", nameLeft);
  10371. return;
  10372. }
  10373. if (mResult.mType->IsObject())
  10374. {
  10375. mResult = mModule->LoadValue(mResult);
  10376. }
  10377. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  10378. {
  10379. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  10380. mResult = mModule->LoadValue(mResult);
  10381. mResult = BfTypedValue(mResult.mValue, structPtrType->mElementType, true);
  10382. }
  10383. if (!mResult)
  10384. return;
  10385. if (!mResult.mType->IsTypeInstance())
  10386. {
  10387. if (mResult.mType->IsSizedArray())
  10388. {
  10389. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  10390. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  10391. }
  10392. else if (mResult.mType->IsWrappableType())
  10393. {
  10394. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  10395. }
  10396. else
  10397. {
  10398. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  10399. return;
  10400. }
  10401. }
  10402. auto leftResult = mResult;
  10403. mResult = LookupField(nameRight, leftResult, fieldName);
  10404. if ((mResult) || (mPropDef != NULL))
  10405. return;
  10406. mModule->CheckTypeRefFixit(nameLeft);
  10407. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(leftResult.mType).c_str()), nameRight);
  10408. }
  10409. void BfExprEvaluator::Visit(BfQualifiedNameNode* nameNode)
  10410. {
  10411. auto autoComplete = GetAutoComplete();
  10412. if (autoComplete != NULL)
  10413. {
  10414. autoComplete->CheckMemberReference(nameNode->mLeft, nameNode->mDot, nameNode->mRight);
  10415. }
  10416. bool hadError = false;
  10417. LookupQualifiedName(nameNode, nameNode->mLeft, nameNode->mRight, true, &hadError);
  10418. if ((mResult) || (mPropDef != NULL))
  10419. return;
  10420. if (hadError)
  10421. return;
  10422. LookupQualifiedStaticField(nameNode, nameNode->mLeft, nameNode->mRight, false);
  10423. }
  10424. void BfExprEvaluator::Visit(BfThisExpression* thisExpr)
  10425. {
  10426. mResult = mModule->GetThis();
  10427. if (!mResult)
  10428. {
  10429. mModule->Fail("Static methods don't have 'this'", thisExpr);
  10430. return;
  10431. }
  10432. auto autoComplete = GetAutoComplete();
  10433. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(thisExpr)))
  10434. autoComplete->SetDefinitionLocation(mModule->mCurTypeInstance->mTypeDef->GetRefNode());
  10435. mResultLocalVar = mModule->GetThisVariable();
  10436. mResultFieldInstance = NULL;
  10437. }
  10438. void BfExprEvaluator::Visit(BfBaseExpression* baseExpr)
  10439. {
  10440. mResult = mModule->GetThis();
  10441. if (!mResult)
  10442. {
  10443. mModule->Fail("Static methods don't have 'base'", baseExpr);
  10444. return;
  10445. }
  10446. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowBase) == 0)
  10447. mModule->Fail("Use of keyword 'base' is not valid in this context", baseExpr);
  10448. auto baseType = mModule->mCurTypeInstance->mBaseType;
  10449. if (baseType == NULL)
  10450. baseType = mModule->mContext->mBfObjectType;
  10451. auto autoComplete = GetAutoComplete();
  10452. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(baseExpr)))
  10453. autoComplete->SetDefinitionLocation(baseType->mTypeDef->GetRefNode());
  10454. mModule->PopulateType(baseType, BfPopulateType_Data);
  10455. mResult = mModule->Cast(baseExpr, mResult, baseType, BfCastFlags_Explicit);
  10456. if (mResult.IsSplat())
  10457. mResult.mKind = BfTypedValueKind_BaseSplatHead;
  10458. else if (mResult.IsAddr())
  10459. mResult.mKind = BfTypedValueKind_BaseAddr;
  10460. else if (mResult)
  10461. mResult.mKind = BfTypedValueKind_BaseValue;
  10462. }
  10463. void BfExprEvaluator::Visit(BfMixinExpression* mixinExpr)
  10464. {
  10465. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  10466. {
  10467. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  10468. auto newVar = mModule->AllocFromType(varType, mModule->mCurMethodState->mCurScope);
  10469. mResult = BfTypedValue(newVar, varType, true);
  10470. return;
  10471. }
  10472. auto curMethodState = mModule->mCurMethodState;
  10473. if (curMethodState->mMixinState == NULL)
  10474. {
  10475. mModule->Fail("Mixin references can only be used within mixins", mixinExpr);
  10476. return;
  10477. }
  10478. int localIdx = GetMixinVariable();
  10479. if (localIdx != -1)
  10480. {
  10481. auto varDecl = curMethodState->mLocals[localIdx];
  10482. if (varDecl != NULL)
  10483. {
  10484. BfTypedValue localResult = LoadLocal(varDecl);
  10485. mResult = localResult;
  10486. mResultLocalVar = varDecl;
  10487. mResultFieldInstance = NULL;
  10488. mResultLocalVarRefNode = mixinExpr;
  10489. return;
  10490. }
  10491. }
  10492. if (mModule->mCurMethodInstance->mIsUnspecialized)
  10493. {
  10494. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  10495. return;
  10496. }
  10497. mModule->Fail("Mixin value cannot be inferred", mixinExpr);
  10498. }
  10499. void BfExprEvaluator::Visit(BfSizedArrayCreateExpression* createExpr)
  10500. {
  10501. auto type = mModule->ResolveTypeRef(createExpr->mTypeRef, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowInferredSizedArray);
  10502. if (type == NULL)
  10503. return;
  10504. if (type->IsArray())
  10505. {
  10506. // If we have a case like 'int[] (1, 2)' then we infer the sized array size from the initializer
  10507. auto arrayType = (BfArrayType*)type;
  10508. if (arrayType->mDimensions == 1)
  10509. {
  10510. int arraySize = 0;
  10511. if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(createExpr->mInitializer))
  10512. {
  10513. arraySize = (int)arrayInitExpr->mValues.size();
  10514. }
  10515. type = mModule->CreateSizedArrayType(arrayType->GetUnderlyingType(), arraySize);
  10516. }
  10517. }
  10518. if (!type->IsSizedArray())
  10519. {
  10520. mModule->Fail("Sized array expected", createExpr->mTypeRef);
  10521. return;
  10522. }
  10523. if (type->IsUndefSizedArray())
  10524. {
  10525. int arraySize = 0;
  10526. if (createExpr->mInitializer != NULL)
  10527. arraySize = (int)createExpr->mInitializer->mValues.size();
  10528. type = mModule->CreateSizedArrayType(type->GetUnderlyingType(), arraySize);
  10529. }
  10530. BfSizedArrayType* arrayType = (BfSizedArrayType*)type;
  10531. if (createExpr->mInitializer == NULL)
  10532. {
  10533. mModule->AssertErrorState();
  10534. mResult = mModule->GetDefaultTypedValue(arrayType);
  10535. return;
  10536. }
  10537. InitializedSizedArray(arrayType, createExpr->mInitializer->mOpenBrace, createExpr->mInitializer->mValues, createExpr->mInitializer->mCommas, createExpr->mInitializer->mCloseBrace);
  10538. }
  10539. void BfExprEvaluator::Visit(BfInitializerExpression* initExpr)
  10540. {
  10541. uint64 unassignedFieldFlags = 0;
  10542. if (auto typeRef = BfNodeDynCast<BfTypeReference>(initExpr->mTarget))
  10543. {
  10544. BfType* type = NULL;
  10545. if (auto typeRef = BfNodeDynCast<BfDotTypeReference>(initExpr->mTarget))
  10546. {
  10547. type = mExpectingType;
  10548. }
  10549. if (type == NULL)
  10550. type = mModule->ResolveTypeRef(typeRef);
  10551. if (type != NULL)
  10552. {
  10553. if (type->IsValueType())
  10554. {
  10555. if ((mReceivingValue != NULL) && (mReceivingValue->mType == type) && (mReceivingValue->IsAddr()))
  10556. {
  10557. mResult = *mReceivingValue;
  10558. mReceivingValue = NULL;
  10559. }
  10560. else
  10561. {
  10562. mResult = BfTypedValue(mModule->CreateAlloca(type), type, true);
  10563. }
  10564. auto typeInstance = type->ToTypeInstance();
  10565. if (typeInstance != NULL)
  10566. unassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  10567. }
  10568. else
  10569. {
  10570. mModule->Fail("Initializer expressions can only be used on value types or allocated values", initExpr->mTarget);
  10571. }
  10572. }
  10573. }
  10574. else if (auto objCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(initExpr->mTarget))
  10575. {
  10576. CreateObject(objCreateExpr, objCreateExpr->mNewNode, NULL, initExpr->mInlineTypeRef);
  10577. }
  10578. else
  10579. VisitChild(initExpr->mTarget);
  10580. if (!mResult)
  10581. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  10582. BfIRBlock initBlock = BfIRBlock();
  10583. if (unassignedFieldFlags != 0)
  10584. {
  10585. initBlock = mModule->mBfIRBuilder->CreateBlock("initStart", true);
  10586. mModule->mBfIRBuilder->CreateBr(initBlock);
  10587. mModule->mBfIRBuilder->SetInsertPoint(initBlock);
  10588. }
  10589. BfTypedValue origInitValue = GetResult(true);
  10590. BfTypedValue initValue = origInitValue;
  10591. if ((initValue) && (initValue.mType->IsRef()))
  10592. initValue = mModule->RemoveRef(initValue, false);
  10593. bool isFirstAdd = true;
  10594. SetAndRestoreValue<BfTypeInstance*> prevPrivateTypeInstance(mModule->mCurMethodState->mPrivateTypeInstance);
  10595. BfScopeData newScope;
  10596. if (initExpr->mInlineTypeRef != NULL)
  10597. mModule->mCurMethodState->mPrivateTypeInstance = initValue.mType->ToTypeInstance();
  10598. newScope.mAllowTargeting = false;
  10599. newScope.mInnerIsConditional = true;
  10600. newScope.mCloseNode = initExpr->mCloseBrace;
  10601. mModule->mCurMethodState->AddScope(&newScope);
  10602. mModule->NewScopeState();
  10603. BfLocalVariable* localDef = new BfLocalVariable();
  10604. localDef->mName = "_";
  10605. localDef->mResolvedType = initValue.mType;
  10606. localDef->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  10607. if (initValue.IsAddr())
  10608. {
  10609. localDef->mAddr = initValue.mValue;
  10610. }
  10611. else
  10612. {
  10613. localDef->mValue = initValue.mValue;
  10614. localDef->mIsSplat = initValue.IsSplat();
  10615. }
  10616. if (!localDef->mResolvedType->IsVar())
  10617. mModule->AddLocalVariableDef(localDef, true, true);
  10618. for (auto elementExpr : initExpr->mValues)
  10619. {
  10620. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  10621. {
  10622. mModule->Fail("Comptime cannot evaluate initializer expressions", elementExpr);
  10623. break;
  10624. }
  10625. bool wasValidInitKind = false;
  10626. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(elementExpr))
  10627. {
  10628. BfTypedValue fieldResult;
  10629. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(assignExpr->mLeft))
  10630. {
  10631. StringT<128> findName;
  10632. identifierNode->ToString(findName);
  10633. mResultFieldInstance = NULL;
  10634. fieldResult = LookupField(identifierNode, initValue, findName, BfLookupFieldFlag_IsImplicitThis);
  10635. if ((fieldResult.mKind == BfTypedValueKind_TempAddr) || (fieldResult.mKind == BfTypedValueKind_RestrictedTempAddr))
  10636. fieldResult.mKind = BfTypedValueKind_Addr;
  10637. if ((mResultFieldInstance != NULL) && (mResultFieldInstance->mMergedDataIdx != -1))
  10638. {
  10639. int resultLocalVarField = 0;
  10640. int resultLocalVarFieldCount = 0;
  10641. mResultFieldInstance->GetDataRange(resultLocalVarField, resultLocalVarFieldCount);
  10642. for (int i = 0; i < resultLocalVarFieldCount; i++)
  10643. unassignedFieldFlags &= ~((int64)1 << (resultLocalVarField - 1 + i));
  10644. }
  10645. wasValidInitKind = true;
  10646. if ((fieldResult) || (mPropDef != NULL))
  10647. {
  10648. if (mResultFieldInstance != NULL)
  10649. {
  10650. auto autoComplete = GetAutoComplete();
  10651. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  10652. {
  10653. auto fieldDef = mResultFieldInstance->GetFieldDef();
  10654. if (fieldDef != NULL)
  10655. autoComplete->SetDefinitionLocation(fieldDef->GetRefNode());
  10656. }
  10657. }
  10658. mResult = fieldResult;
  10659. PerformAssignment(assignExpr, true, BfTypedValue());
  10660. mResult = BfTypedValue();
  10661. }
  10662. else
  10663. {
  10664. mModule->Fail(StrFormat("'%s' does not contain a definition for '%s'", mModule->TypeToString(initValue.mType).c_str(),
  10665. findName.c_str()), identifierNode);
  10666. }
  10667. }
  10668. else if (auto indexerExpression = BfNodeDynCast<BfIndexerExpression>(assignExpr->mLeft))
  10669. {
  10670. if (indexerExpression->mTarget == NULL)
  10671. {
  10672. if ((initValue.mType->IsValueType()) && (!initValue.IsAddr()))
  10673. {
  10674. initValue = mModule->MakeAddressable(initValue, true, true);
  10675. }
  10676. mResult = BfTypedValue();
  10677. HandleIndexerExpression(indexerExpression, initValue);
  10678. wasValidInitKind = true;
  10679. if ((mPropDef) || (mResult))
  10680. {
  10681. PerformAssignment(assignExpr, true, BfTypedValue());
  10682. mResult = BfTypedValue();
  10683. }
  10684. }
  10685. }
  10686. }
  10687. else
  10688. {
  10689. BfBlock* block = BfNodeDynCast<BfBlock>(elementExpr);
  10690. auto autoComplete = GetAutoComplete();
  10691. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(elementExpr)))
  10692. {
  10693. if (auto identiferNode = BfNodeDynCast<BfIdentifierNode>(elementExpr))
  10694. {
  10695. auto typeInstance = initValue.mType->ToTypeInstance();
  10696. if (typeInstance != NULL)
  10697. {
  10698. String filter;
  10699. identiferNode->ToString(filter);
  10700. autoComplete->AddTypeMembers(typeInstance, false, true, filter, typeInstance, false, true, false);
  10701. }
  10702. }
  10703. }
  10704. if ((block != NULL) && (!block->IsExpression()))
  10705. {
  10706. mModule->VisitCodeBlock(block);
  10707. }
  10708. else
  10709. {
  10710. BfExprEvaluator exprEvaluator(mModule);
  10711. SizedArray<BfExpression*, 2> argExprs;
  10712. argExprs.push_back(elementExpr);
  10713. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  10714. BfResolvedArgs argValues(&sizedArgExprs);
  10715. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  10716. exprEvaluator.MatchMethod(elementExpr, NULL, initValue, false, false, "Add", argValues, BfMethodGenericArguments());
  10717. }
  10718. wasValidInitKind = true;
  10719. }
  10720. if (!wasValidInitKind)
  10721. {
  10722. mModule->Fail("Invalid initializer member declarator", initExpr);
  10723. }
  10724. }
  10725. mModule->RestoreScopeState();
  10726. if (initExpr->mValues.IsEmpty())
  10727. {
  10728. // When we are first typing out 'override', we
  10729. if (initExpr->mInlineTypeRef != NULL)
  10730. {
  10731. if (auto defineBlock = BfNodeDynCast<BfBlock>(initExpr->mInlineTypeRef->mTypeDeclaration->mDefineNode))
  10732. {
  10733. if (defineBlock->mChildArr.mSize == 1)
  10734. {
  10735. auto lastNode = defineBlock->mChildArr[0];
  10736. if (lastNode->Equals("override"))
  10737. {
  10738. auto autoComplete = mModule->mCompiler->GetAutoComplete();
  10739. if (autoComplete != NULL)
  10740. {
  10741. int cursorIdx = autoComplete->GetCursorIdx(lastNode);
  10742. if ((autoComplete->IsAutocompleteNode(lastNode, 1)) && (cursorIdx == lastNode->GetSrcEnd()))
  10743. {
  10744. auto typeInst = initValue.mType->ToTypeInstance();
  10745. if (typeInst != NULL)
  10746. {
  10747. SetAndRestoreValue<BfTypeInstance*> prevTypeInst(mModule->mCurTypeInstance, typeInst);
  10748. SetAndRestoreValue<BfMethodInstance*> prevMethodInst(mModule->mCurMethodInstance, NULL);
  10749. autoComplete->AddOverrides("", true);
  10750. autoComplete->mInsertStartIdx = lastNode->mSrcStart;
  10751. autoComplete->mInsertEndIdx = lastNode->mSrcEnd;
  10752. }
  10753. }
  10754. }
  10755. }
  10756. }
  10757. }
  10758. }
  10759. }
  10760. else
  10761. {
  10762. auto lastNode = initExpr->mValues.back();
  10763. if (auto lastIdentifier = BfNodeDynCast<BfIdentifierNode>(lastNode))
  10764. {
  10765. auto autoComplete = mModule->mCompiler->GetAutoComplete();
  10766. if (autoComplete != NULL)
  10767. {
  10768. autoComplete->CheckIdentifier(lastIdentifier, false, false);
  10769. }
  10770. }
  10771. }
  10772. if (unassignedFieldFlags != 0)
  10773. {
  10774. auto curBlock = mModule->mBfIRBuilder->GetInsertBlock();
  10775. mModule->mBfIRBuilder->SetInsertPointAtStart(initBlock);
  10776. mModule->mBfIRBuilder->CreateMemSet(initValue.mValue, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  10777. mModule->GetConstValue(initValue.mType->mSize), initValue.mType->mAlign);
  10778. mModule->mBfIRBuilder->SetInsertPoint(curBlock);
  10779. }
  10780. mResult = origInitValue;
  10781. }
  10782. void BfExprEvaluator::Visit(BfCollectionInitializerExpression* arrayInitExpr)
  10783. {
  10784. mModule->Fail("Collection initializer not usable here", arrayInitExpr);
  10785. }
  10786. void BfExprEvaluator::Visit(BfTypeOfExpression* typeOfExpr)
  10787. {
  10788. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  10789. auto autoComplete = GetAutoComplete();
  10790. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  10791. {
  10792. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  10793. }
  10794. BfType* type;
  10795. if ((typeOfExpr->mTypeRef != NULL) && (typeOfExpr->mTypeRef->IsA<BfVarTypeReference>()))
  10796. {
  10797. type = mModule->GetPrimitiveType(BfTypeCode_Var);
  10798. }
  10799. else
  10800. {
  10801. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_AllowGlobalsSelf | BfResolveTypeRefFlag_AllowUnboundGeneric));
  10802. }
  10803. if (type == NULL)
  10804. {
  10805. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  10806. return;
  10807. }
  10808. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10809. mResult = BfTypedValue(mModule->CreateTypeDataRef(type), typeType);
  10810. }
  10811. bool BfExprEvaluator::LookupTypeProp(BfTypeOfExpression* typeOfExpr, BfIdentifierNode* propName)
  10812. {
  10813. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  10814. BfType* type;
  10815. //
  10816. {
  10817. // We ignore errors because we go through the normal Visit(BfTypeOfExpression) if this fails, which will throw the error again
  10818. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  10819. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeOfExpr->mTypeRef))
  10820. {
  10821. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  10822. type = mModule->ResolveTypeRefAllowUnboundGenerics(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  10823. }
  10824. else
  10825. {
  10826. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_IgnoreLookupError);
  10827. }
  10828. }
  10829. if (type == NULL)
  10830. {
  10831. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  10832. return false;
  10833. }
  10834. bool success = true;
  10835. defer(
  10836. {
  10837. if (success)
  10838. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_TypeSignature);
  10839. });
  10840. // We want to try to avoid triggering OnTypeInit for basic info
  10841. mModule->PopulateType(type, BfPopulateType_Interfaces_Direct);
  10842. auto typeInstance = type->ToTypeInstance();
  10843. auto _BoolResult = [&](bool val)
  10844. {
  10845. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, val ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  10846. };
  10847. auto _Int32Result = [&](int32 val)
  10848. {
  10849. mResult = BfTypedValue(mModule->GetConstValue32(val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  10850. };
  10851. String memberName;
  10852. propName->ToString(memberName);
  10853. bool handled = true;
  10854. if (memberName == "IsTypedPrimitive")
  10855. _BoolResult(type->IsPrimitiveType());
  10856. else if (memberName == "IsObject")
  10857. _BoolResult(type->IsObject());
  10858. else if (memberName == "IsValueType")
  10859. _BoolResult(type->IsValueType());
  10860. else if (memberName == "IsPrimitive")
  10861. _BoolResult(type->IsPrimitiveType());
  10862. else if (memberName == "IsInteger")
  10863. _BoolResult(type->IsInteger());
  10864. else if (memberName == "IsIntegral")
  10865. _BoolResult(type->IsIntegral());
  10866. else if (memberName == "IsSigned")
  10867. _BoolResult(type->IsSigned());
  10868. else if (memberName == "IsFloatingPoint")
  10869. _BoolResult(type->IsFloat());
  10870. else if (memberName == "IsPointer")
  10871. _BoolResult(type->IsPointer());
  10872. else if (memberName == "IsStruct")
  10873. _BoolResult(type->IsStruct());
  10874. else if (memberName == "IsSplattable")
  10875. _BoolResult(type->IsSplattable());
  10876. else if (memberName == "IsUnion")
  10877. _BoolResult(type->IsUnion());
  10878. else if (memberName == "IsBoxed")
  10879. _BoolResult(type->IsBoxed());
  10880. else if (memberName == "IsEnum")
  10881. _BoolResult(type->IsEnum());
  10882. else if (memberName == "IsTuple")
  10883. _BoolResult(type->IsTuple());
  10884. else if (memberName == "IsNullable")
  10885. _BoolResult(type->IsNullable());
  10886. else if (memberName == "IsGenericType")
  10887. _BoolResult(type->IsGenericTypeInstance());
  10888. else if (memberName == "IsGenericParam")
  10889. _BoolResult(type->IsGenericParam());
  10890. else if (memberName == "IsArray")
  10891. _BoolResult(type->IsArray());
  10892. else if (memberName == "IsSizedArray")
  10893. _BoolResult(type->IsSizedArray());
  10894. else if (memberName == "TypeId")
  10895. {
  10896. _Int32Result(type->mTypeId);
  10897. mResult.mType = mModule->ResolveTypeDef(mModule->mCompiler->mReflectTypeIdTypeDef);
  10898. }
  10899. else if (memberName == "GenericParamCount")
  10900. {
  10901. auto genericTypeInst = type->ToGenericTypeInstance();
  10902. _Int32Result((genericTypeInst != NULL) ? (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size() : 0);
  10903. }
  10904. else
  10905. {
  10906. // We need full data
  10907. mModule->PopulateType(type, BfPopulateType_Data);
  10908. if (memberName == "Size")
  10909. _Int32Result(type->mSize);
  10910. else if (memberName == "Align")
  10911. _Int32Result(type->mAlign);
  10912. else if (memberName == "Stride")
  10913. _Int32Result(type->GetStride());
  10914. else if (memberName == "InstanceSize")
  10915. _Int32Result((typeInstance != NULL) ? typeInstance->mInstSize : type->mSize);
  10916. else if (memberName == "InstanceAlign")
  10917. _Int32Result((typeInstance != NULL) ? typeInstance->mInstAlign : type->mSize);
  10918. else if (memberName == "InstanceStride")
  10919. _Int32Result((typeInstance != NULL) ? typeInstance->GetInstStride() : type->GetStride());
  10920. else if (memberName == "UnderlyingType")
  10921. {
  10922. bool handled = false;
  10923. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  10924. if (type->IsGenericParam())
  10925. {
  10926. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)type);
  10927. if (genericParamInstance->IsEnum())
  10928. {
  10929. handled = true;
  10930. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(typeType)), typeType);
  10931. }
  10932. }
  10933. else if (type->IsEnum())
  10934. {
  10935. if (type->IsDataIncomplete())
  10936. mModule->PopulateType(type);
  10937. auto underlyingType = type->GetUnderlyingType();
  10938. if (underlyingType != NULL)
  10939. {
  10940. handled = true;
  10941. mModule->AddDependency(underlyingType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10942. mResult = BfTypedValue(mModule->CreateTypeDataRef(underlyingType), typeType);
  10943. }
  10944. }
  10945. if (!handled)
  10946. mResult = BfTypedValue(mModule->CreateTypeDataRef(mModule->GetPrimitiveType(BfTypeCode_None)), typeType);
  10947. }
  10948. else if (memberName == "BitSize")
  10949. {
  10950. auto int32Type = mModule->GetPrimitiveType(BfTypeCode_Int32);
  10951. BfType* checkType = type;
  10952. if (checkType->IsTypedPrimitive())
  10953. checkType = checkType->GetUnderlyingType();
  10954. if (checkType->IsGenericParam())
  10955. {
  10956. mResult = mModule->GetDefaultTypedValue(int32Type, false, Beefy::BfDefaultValueKind_Undef);
  10957. return true;
  10958. }
  10959. if ((typeInstance != NULL) && (typeInstance->IsEnum()))
  10960. {
  10961. if (typeInstance->mTypeInfoEx != NULL)
  10962. {
  10963. int64 minValue = typeInstance->mTypeInfoEx->mMinValue;
  10964. if (minValue < 0)
  10965. minValue = ~minValue;
  10966. int64 maxValue = typeInstance->mTypeInfoEx->mMaxValue;
  10967. if (maxValue < 0)
  10968. maxValue = ~maxValue;
  10969. uint64 value = (uint64)minValue | (uint64)maxValue;
  10970. int bitCount = 1;
  10971. if (typeInstance->mTypeInfoEx->mMinValue < 0)
  10972. bitCount++;
  10973. while (value >>= 1)
  10974. bitCount++;
  10975. mModule->AddDependency(typeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  10976. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, bitCount), int32Type);
  10977. return true;
  10978. }
  10979. }
  10980. int bitSize = checkType->mSize * 8;
  10981. if (checkType->GetTypeCode() == BfTypeCode_Boolean)
  10982. bitSize = 1;
  10983. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, bitSize), int32Type);
  10984. return true;
  10985. }
  10986. else if ((memberName == "MinValue") || (memberName == "MaxValue"))
  10987. {
  10988. bool isMin = memberName == "MinValue";
  10989. bool isBitSize = memberName == "BitSize";
  10990. BfType* checkType = type;
  10991. if (checkType->IsTypedPrimitive())
  10992. checkType = checkType->GetUnderlyingType();
  10993. if (checkType->IsGenericParam())
  10994. {
  10995. bool foundMatch = false;
  10996. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)checkType);
  10997. if (((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Enum) != 0) ||
  10998. ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsInstanceOf(mModule->mCompiler->mEnumTypeDef))))
  10999. foundMatch = true;
  11000. else
  11001. {
  11002. for (auto constraint : genericParamInstance->mInterfaceConstraints)
  11003. {
  11004. if (constraint->IsInstanceOf(mModule->mCompiler->mIIntegerTypeDef))
  11005. foundMatch = true;
  11006. }
  11007. }
  11008. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  11009. {
  11010. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  11011. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  11012. {
  11013. genericParamInstance = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  11014. if (genericParamInstance->mExternType == type)
  11015. {
  11016. if (((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Enum) != 0) ||
  11017. ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsInstanceOf(mModule->mCompiler->mEnumTypeDef))))
  11018. foundMatch = true;
  11019. }
  11020. }
  11021. }
  11022. if (foundMatch)
  11023. {
  11024. mResult = mModule->GetDefaultTypedValue(type, false, Beefy::BfDefaultValueKind_Undef);
  11025. return true;
  11026. }
  11027. }
  11028. if (checkType->IsPrimitiveType())
  11029. {
  11030. auto primType = (BfPrimitiveType*)checkType;
  11031. if ((typeInstance != NULL) && (typeInstance->IsEnum()))
  11032. {
  11033. if (typeInstance->mTypeInfoEx != NULL)
  11034. {
  11035. mModule->AddDependency(typeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  11036. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)typeInstance->mTypeInfoEx->mMinValue : (uint64)typeInstance->mTypeInfoEx->mMaxValue), typeInstance);
  11037. return true;
  11038. }
  11039. }
  11040. else
  11041. {
  11042. switch (primType->mTypeDef->mTypeCode)
  11043. {
  11044. case BfTypeCode_Int8:
  11045. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x80 : 0x7F), primType);
  11046. return true;
  11047. case BfTypeCode_Int16:
  11048. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x8000 : 0x7FFF), primType);
  11049. return true;
  11050. case BfTypeCode_Int32:
  11051. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x80000000LL : 0x7FFFFFFF), primType);
  11052. return true;
  11053. case BfTypeCode_Int64:
  11054. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x8000000000000000LL : (uint64)0x7FFFFFFFFFFFFFFFLL), primType);
  11055. return true;
  11056. case BfTypeCode_UInt8:
  11057. case BfTypeCode_Char8:
  11058. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFF), primType);
  11059. return true;
  11060. case BfTypeCode_UInt16:
  11061. case BfTypeCode_Char16:
  11062. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFFFF), primType);
  11063. return true;
  11064. case BfTypeCode_UInt32:
  11065. case BfTypeCode_Char32:
  11066. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFLL), primType);
  11067. return true;
  11068. case BfTypeCode_UInt64:
  11069. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFFFFFFFFFLL), primType);
  11070. return true;
  11071. case BfTypeCode_IntPtr:
  11072. if (mModule->mSystem->mPtrSize == 8)
  11073. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x8000000000000000LL : (uint64)0x7FFFFFFFFFFFFFFFLL), primType);
  11074. else
  11075. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x80000000LL : 0x7FFFFFFF), primType);
  11076. return true;
  11077. case BfTypeCode_UIntPtr:
  11078. if (mModule->mSystem->mPtrSize == 8)
  11079. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFFFFFFFFFLL), primType);
  11080. else
  11081. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFLL), primType);
  11082. return true;
  11083. default: break;
  11084. }
  11085. }
  11086. }
  11087. if (type->IsEnum())
  11088. {
  11089. mModule->Fail(StrFormat("'MinValue' cannot be used on enum with payload '%s'", mModule->TypeToString(type).c_str()), propName);
  11090. }
  11091. else
  11092. {
  11093. mModule->Fail(StrFormat("'%s' cannot be used on type '%s'", memberName.c_str(), mModule->TypeToString(type).c_str()), propName);
  11094. }
  11095. }
  11096. else
  11097. {
  11098. success = false;
  11099. return false;
  11100. }
  11101. }
  11102. if ((type->IsGenericParam()) && (!mModule->mIsComptimeModule))
  11103. {
  11104. if (mResult.mType != NULL)
  11105. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, Beefy::BfDefaultValueKind_Undef);
  11106. }
  11107. auto autoComplete = GetAutoComplete();
  11108. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  11109. {
  11110. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  11111. }
  11112. return true;
  11113. }
  11114. void BfExprEvaluator::DoTypeIntAttr(BfTypeReference* typeRef, BfTokenNode* commaToken, BfIdentifierNode* memberName, BfToken token)
  11115. {
  11116. auto autoComplete = GetAutoComplete();
  11117. auto type = mModule->ResolveTypeRef(typeRef, BfPopulateType_Data, BfResolveTypeRefFlag_AutoComplete);
  11118. if (type == NULL)
  11119. return;
  11120. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage); // Local usage ensures it changes when the type data changes
  11121. auto typeInst = type->ToTypeInstance();
  11122. if ((typeInst != NULL) && (typeInst->mTypeDef->mIsOpaque))
  11123. {
  11124. mModule->Fail(StrFormat("Unable to determine attributes for opaque type '%s'", mModule->TypeToString(type).c_str()), typeRef);
  11125. }
  11126. BfType* sizeType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  11127. int attrVal = 0;
  11128. switch (token)
  11129. {
  11130. case BfToken_SizeOf: attrVal = type->mSize; break;
  11131. case BfToken_AlignOf: attrVal = type->mAlign; break;
  11132. case BfToken_StrideOf: attrVal = type->GetStride(); break;
  11133. default: break;
  11134. }
  11135. if (token == BfToken_OffsetOf)
  11136. {
  11137. bool found = false;
  11138. String findName;
  11139. if (memberName != NULL)
  11140. findName = memberName->ToString();
  11141. BfAstNode* refNode = typeRef;
  11142. if (memberName != NULL)
  11143. refNode = memberName;
  11144. auto checkTypeInst = typeInst;
  11145. while (checkTypeInst != NULL)
  11146. {
  11147. checkTypeInst->mTypeDef->PopulateMemberSets();
  11148. String filter;
  11149. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(commaToken, memberName, filter)))
  11150. {
  11151. auto activeTypeDef = mModule->GetActiveTypeDef();
  11152. mModule->PopulateType(checkTypeInst);
  11153. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  11154. for (auto fieldDef : checkTypeInst->mTypeDef->mFields)
  11155. {
  11156. if (fieldDef->mIsStatic)
  11157. continue;
  11158. if (!mModule->CheckProtection(protectionCheckFlags, typeInst, fieldDef->mDeclaringType->mProject, fieldDef->mProtection, typeInst))
  11159. continue;
  11160. if ((!typeInst->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, mModule)) ||
  11161. (!typeInst->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  11162. continue;
  11163. auto& fieldInst = checkTypeInst->mFieldInstances[fieldDef->mIdx];
  11164. autoComplete->AddField(checkTypeInst, fieldDef, &fieldInst, filter);
  11165. }
  11166. }
  11167. BfMemberSetEntry* memberSetEntry = NULL;
  11168. if (checkTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  11169. {
  11170. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  11171. if (fieldDef != NULL)
  11172. {
  11173. if (fieldDef->mIsStatic)
  11174. mModule->Fail(StrFormat("Cannot generate an offset from static field '%s.%s'", mModule->TypeToString(type).c_str(), fieldDef->mName.c_str()), refNode);
  11175. mModule->PopulateType(checkTypeInst);
  11176. auto& fieldInst = checkTypeInst->mFieldInstances[fieldDef->mIdx];
  11177. attrVal = fieldInst.mDataOffset;
  11178. found = true;
  11179. break;
  11180. }
  11181. }
  11182. checkTypeInst = checkTypeInst->mBaseType;
  11183. }
  11184. if (!found)
  11185. {
  11186. mModule->Fail(StrFormat("Unable to locate field '%s.%s'", mModule->TypeToString(type).c_str(), findName.c_str()), refNode);
  11187. }
  11188. }
  11189. bool isUndefVal = false;
  11190. if (type->IsGenericParam())
  11191. isUndefVal = true;
  11192. if (type->IsSizedArray())
  11193. {
  11194. auto sizedArray = (BfSizedArrayType*)type;
  11195. if (sizedArray->mElementCount == -1)
  11196. isUndefVal = true;
  11197. }
  11198. if (isUndefVal)
  11199. {
  11200. // We do this so we know it's a constant but we can't assume anything about its value
  11201. // We make the value an Int32 which doesn't match the IntPtr type, but it allows us to
  11202. // assume it can be implicitly cased to int32
  11203. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(sizeType)), sizeType);
  11204. }
  11205. else
  11206. mResult = BfTypedValue(mModule->GetConstValue(attrVal, sizeType), sizeType);
  11207. }
  11208. void BfExprEvaluator::Visit(BfSizeOfExpression* sizeOfExpr)
  11209. {
  11210. DoTypeIntAttr(sizeOfExpr->mTypeRef, NULL, NULL, BfToken_SizeOf);
  11211. }
  11212. void BfExprEvaluator::Visit(BfAlignOfExpression* alignOfExpr)
  11213. {
  11214. DoTypeIntAttr(alignOfExpr->mTypeRef, NULL, NULL, BfToken_AlignOf);
  11215. }
  11216. void BfExprEvaluator::Visit(BfStrideOfExpression* strideOfExpr)
  11217. {
  11218. DoTypeIntAttr(strideOfExpr->mTypeRef, NULL, NULL, BfToken_StrideOf);
  11219. }
  11220. void BfExprEvaluator::Visit(BfOffsetOfExpression* offsetOfExpr)
  11221. {
  11222. DoTypeIntAttr(offsetOfExpr->mTypeRef, offsetOfExpr->mCommaToken, offsetOfExpr->mMemberName, BfToken_OffsetOf);
  11223. }
  11224. void BfExprEvaluator::Visit(BfNameOfExpression* nameOfExpr)
  11225. {
  11226. String name;
  11227. if (mModule->IsInSpecializedGeneric())
  11228. {
  11229. if (auto identifierNode = BfNodeDynCastExact<BfIdentifierNode>(nameOfExpr->mTarget))
  11230. {
  11231. // This is necessary so we don't resolve 'T' to the actual generic argument type
  11232. name = identifierNode->ToString();
  11233. }
  11234. }
  11235. if (name.IsEmpty())
  11236. {
  11237. auto type = mModule->ResolveTypeRef(nameOfExpr->mTarget, {}, BfPopulateType_IdentityNoRemapAlias,
  11238. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_AllowUnboundGeneric | BfResolveTypeRefFlag_IgnoreLookupError | BfResolveTypeRefFlag_IgnoreProtection));
  11239. if (type != NULL)
  11240. {
  11241. auto typeInst = type->ToTypeInstance();
  11242. if (typeInst != NULL)
  11243. name = typeInst->mTypeDef->mName->ToString();
  11244. else
  11245. name = mModule->TypeToString(type);
  11246. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  11247. // Just do this for autocomplete
  11248. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  11249. VisitChild(nameOfExpr->mTarget);
  11250. }
  11251. }
  11252. if (name.IsEmpty())
  11253. {
  11254. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(nameOfExpr->mTarget))
  11255. {
  11256. String targetStr = nameOfExpr->mTarget->ToString();
  11257. BfAtomComposite targetComposite;
  11258. bool isValid = mModule->mSystem->ParseAtomComposite(targetStr, targetComposite);
  11259. bool namespaceExists = false;
  11260. BfProject* bfProject = NULL;
  11261. auto activeTypeDef = mModule->GetActiveTypeDef();
  11262. if (activeTypeDef != NULL)
  11263. bfProject = activeTypeDef->mProject;
  11264. auto _CheckProject = [&](BfProject* project)
  11265. {
  11266. if ((isValid) && (project->mNamespaces.ContainsKey(targetComposite)))
  11267. namespaceExists = true;
  11268. };
  11269. if (bfProject != NULL)
  11270. {
  11271. for (int depIdx = -1; depIdx < (int)bfProject->mDependencies.size(); depIdx++)
  11272. {
  11273. BfProject* depProject = (depIdx == -1) ? bfProject : bfProject->mDependencies[depIdx];
  11274. _CheckProject(depProject);
  11275. }
  11276. }
  11277. else
  11278. {
  11279. for (auto project : mModule->mSystem->mProjects)
  11280. _CheckProject(project);
  11281. }
  11282. if (namespaceExists)
  11283. {
  11284. if (mModule->mCompiler->mResolvePassData != NULL)
  11285. {
  11286. if (auto sourceClassifier = mModule->mCompiler->mResolvePassData->GetSourceClassifier(nameOfExpr->mTarget))
  11287. {
  11288. BfAstNode* checkIdentifier = identifer;
  11289. while (true)
  11290. {
  11291. auto qualifiedIdentifier = BfNodeDynCast<BfQualifiedNameNode>(checkIdentifier);
  11292. if (qualifiedIdentifier == NULL)
  11293. break;
  11294. sourceClassifier->SetElementType(qualifiedIdentifier->mRight, BfSourceElementType_Namespace);
  11295. checkIdentifier = qualifiedIdentifier->mLeft;
  11296. }
  11297. sourceClassifier->SetElementType(checkIdentifier, BfSourceElementType_Namespace);
  11298. }
  11299. }
  11300. name = targetComposite.mParts[targetComposite.mSize - 1]->ToString();
  11301. }
  11302. }
  11303. }
  11304. if (name.IsEmpty())
  11305. {
  11306. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NameOf));
  11307. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mBfIRBuilder->mIgnoreWrites, true);
  11308. VisitChild(nameOfExpr->mTarget);
  11309. if ((mBfEvalExprFlags & BfEvalExprFlags_NameOfSuccess) != 0)
  11310. {
  11311. BfAstNode* nameNode = nameOfExpr->mTarget;
  11312. if (auto attributedIdentifierNode = BfNodeDynCast<BfAttributedIdentifierNode>(nameNode))
  11313. nameNode = attributedIdentifierNode->mIdentifier;
  11314. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(nameNode))
  11315. nameNode = memberReferenceExpr->mMemberName;
  11316. if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(nameNode))
  11317. nameNode = qualifiedNameNode->mRight;
  11318. name = nameNode->ToString();
  11319. }
  11320. else if (mResultFieldInstance != NULL)
  11321. {
  11322. auto fieldDef = mResultFieldInstance->GetFieldDef();
  11323. if (fieldDef != NULL)
  11324. name = fieldDef->mName;
  11325. }
  11326. else if (mResultLocalVar != NULL)
  11327. {
  11328. name = mResultLocalVar->mName;
  11329. }
  11330. else if (mPropDef != NULL)
  11331. {
  11332. name = mPropDef->mName;
  11333. }
  11334. }
  11335. if ((name.IsEmpty()) && (nameOfExpr->mTarget != NULL))
  11336. mModule->Fail("Expression does not have a name", nameOfExpr->mTarget);
  11337. mResult = BfTypedValue(mModule->GetStringObjectValue(name), mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  11338. }
  11339. void BfExprEvaluator::Visit(BfIsConstExpression* isConstExpr)
  11340. {
  11341. if (isConstExpr->mExpression == NULL)
  11342. {
  11343. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  11344. return;
  11345. }
  11346. BfMethodState methodState;
  11347. SetAndRestoreValue<BfMethodState*> prevMethodState(mModule->mCurMethodState, &methodState, false);
  11348. if (mModule->mCurMethodState == NULL)
  11349. prevMethodState.Set();
  11350. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  11351. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  11352. SetAndRestoreValue<bool> allowUninitReads(mModule->mCurMethodState->mAllowUinitReads, true);
  11353. BfEvalExprFlags exprFlags = BfEvalExprFlags_None;
  11354. auto result = mModule->CreateValueFromExpression(isConstExpr->mExpression, NULL, BfEvalExprFlags_DeclType);
  11355. bool isConst = mModule->mBfIRBuilder->IsConstValue(result.mValue);
  11356. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, isConst ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  11357. }
  11358. void BfExprEvaluator::Visit(BfDefaultExpression* defaultExpr)
  11359. {
  11360. auto autoComplete = GetAutoComplete();
  11361. if (autoComplete != NULL)
  11362. autoComplete->CheckTypeRef(defaultExpr->mTypeRef, false, true);
  11363. BfType* type = NULL;
  11364. if (defaultExpr->mOpenParen == NULL)
  11365. {
  11366. if (mExpectingType)
  11367. {
  11368. type = mExpectingType;
  11369. }
  11370. else
  11371. {
  11372. mModule->Fail("Type cannot be inferred, consider adding explicit type name", defaultExpr);
  11373. return;
  11374. }
  11375. }
  11376. else
  11377. type = mModule->ResolveTypeRef(defaultExpr->mTypeRef);
  11378. if (type == NULL)
  11379. return;
  11380. BfDefaultValueKind defaultKind = BfDefaultValueKind_Const;
  11381. if (type->IsRef())
  11382. {
  11383. mModule->Fail(StrFormat("There is no default value for type '%s'", mModule->TypeToString(type).c_str()), defaultExpr);
  11384. defaultKind = BfDefaultValueKind_Addr;
  11385. }
  11386. mModule->ValidateAllocation(type, defaultExpr->mTypeRef);
  11387. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  11388. mResult = mModule->GetDefaultTypedValue(type, true, defaultKind);
  11389. }
  11390. void BfExprEvaluator::Visit(BfUninitializedExpression* uninitialziedExpr)
  11391. {
  11392. mModule->Fail("Invalid use of the '?' uninitialized specifier", uninitialziedExpr);
  11393. }
  11394. void BfExprEvaluator::Visit(BfCheckTypeExpression* checkTypeExpr)
  11395. {
  11396. auto targetValue = mModule->CreateValueFromExpression(checkTypeExpr->mTarget, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  11397. if (!targetValue)
  11398. return;
  11399. if (checkTypeExpr->mTypeRef == NULL)
  11400. {
  11401. mModule->AssertErrorState();
  11402. return;
  11403. }
  11404. auto autoComplete = GetAutoComplete();
  11405. if (autoComplete != NULL)
  11406. autoComplete->CheckTypeRef(checkTypeExpr->mTypeRef, false, true);
  11407. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  11408. if (checkTypeExpr->mTypeRef->IsA<BfVarTypeReference>())
  11409. {
  11410. bool isVar = false;
  11411. if ((targetValue.mType != NULL) && (targetValue.mType->IsVar()))
  11412. {
  11413. auto irb = mModule->mBfIRBuilder;
  11414. BfIRValue boolResult = mModule->CreateAlloca(boolType);
  11415. irb->CreateAlignedStore(irb->CreateConst(BfTypeCode_Boolean, 1), boolResult, 1);
  11416. mResult = BfTypedValue(irb->CreateAlignedLoad(boolResult, 1), boolType);
  11417. }
  11418. else
  11419. mResult = BfTypedValue(mModule->GetConstValue(0, boolType), boolType);
  11420. return;
  11421. }
  11422. auto targetType = mModule->ResolveTypeRef(checkTypeExpr->mTypeRef, BfPopulateType_Declaration);
  11423. if (!targetType)
  11424. {
  11425. mModule->AssertErrorState();
  11426. return;
  11427. }
  11428. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  11429. if (targetValue.mType->IsVar())
  11430. {
  11431. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Undef);
  11432. return;
  11433. }
  11434. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  11435. {
  11436. auto typeInstance = targetValue.mType->ToTypeInstance();
  11437. if (targetValue.mType->IsWrappableType())
  11438. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  11439. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  11440. if (!matches)
  11441. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  11442. if (!typeInstance->IsGenericParam())
  11443. {
  11444. if (matches)
  11445. mModule->Warn(0, "The result of this operation is always 'true'", checkTypeExpr->mIsToken);
  11446. else
  11447. mModule->Warn(0, "The result of this operation is always 'false'", checkTypeExpr->mIsToken);
  11448. }
  11449. mResult = BfTypedValue(mModule->GetConstValue(matches ? 1 : 0, boolType), boolType);
  11450. return;
  11451. }
  11452. if (targetType->IsValueType())
  11453. {
  11454. if ((targetValue.mType != mModule->mContext->mBfObjectType) && (!targetValue.mType->IsInterface()))
  11455. {
  11456. mResult = BfTypedValue(mModule->GetConstValue(0, boolType), boolType);
  11457. return;
  11458. }
  11459. }
  11460. int wantTypeId = 0;
  11461. if (!targetType->IsGenericParam())
  11462. wantTypeId = targetType->mTypeId;
  11463. auto objectType = mModule->mContext->mBfObjectType;
  11464. mModule->PopulateType(objectType, BfPopulateType_Full);
  11465. targetValue = mModule->LoadValue(targetValue);
  11466. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  11467. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  11468. bool wasGenericParamType = false;
  11469. if ((srcTypeInstance != NULL) && (targetTypeInstance != NULL))
  11470. {
  11471. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  11472. {
  11473. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  11474. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  11475. // it may be a "necessary cast" indeed
  11476. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  11477. {
  11478. if (srcTypeInstance == targetType)
  11479. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary check, the value is already type '%s'",
  11480. mModule->TypeToString(srcTypeInstance).c_str()), checkTypeExpr->mIsToken);
  11481. else
  11482. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary check, '%s' is a subtype of '%s'",
  11483. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), checkTypeExpr->mIsToken);
  11484. }
  11485. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  11486. return;
  11487. }
  11488. else if ((!targetType->IsInterface()) && (srcTypeInstance != mModule->mContext->mBfObjectType) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  11489. {
  11490. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  11491. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), checkTypeExpr->mIsToken);
  11492. }
  11493. }
  11494. if (mModule->mCompiler->IsAutocomplete())
  11495. {
  11496. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Addr);
  11497. return;
  11498. }
  11499. auto irb = mModule->mBfIRBuilder;
  11500. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  11501. auto matchBB = mModule->mBfIRBuilder->CreateBlock("is.match");
  11502. auto endBB = mModule->mBfIRBuilder->CreateBlock("is.done");
  11503. BfIRValue boolResult = mModule->CreateAlloca(boolType);
  11504. irb->CreateAlignedStore(irb->CreateConst(BfTypeCode_Boolean, 0), boolResult, 1);
  11505. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBB, endBB);
  11506. mModule->AddBasicBlock(matchBB);
  11507. irb->CreateAlignedStore(irb->CreateConst(BfTypeCode_Boolean, 1), boolResult, 1);
  11508. irb->CreateBr(endBB);
  11509. mModule->AddBasicBlock(endBB);
  11510. mResult = BfTypedValue(irb->CreateAlignedLoad(boolResult, 1), boolType);
  11511. }
  11512. void BfExprEvaluator::Visit(BfDynamicCastExpression* dynCastExpr)
  11513. {
  11514. auto targetValue = mModule->CreateValueFromExpression(dynCastExpr->mTarget);
  11515. auto targetType = mModule->ResolveTypeRefAllowUnboundGenerics(dynCastExpr->mTypeRef, BfPopulateType_Data, BfResolveTypeRefFlag_None, false);
  11516. auto autoComplete = GetAutoComplete();
  11517. if (autoComplete != NULL)
  11518. {
  11519. autoComplete->CheckTypeRef(dynCastExpr->mTypeRef, false, true);
  11520. }
  11521. auto origTargetType = targetType;
  11522. if (!targetValue)
  11523. return;
  11524. if (!targetType)
  11525. {
  11526. mModule->AssertErrorState();
  11527. return;
  11528. }
  11529. bool wasGenericParamType = false;
  11530. if (targetType->IsGenericParam())
  11531. {
  11532. //targetType = mModule->ResolveGenericType(targetType);
  11533. //wasGenericParamType = true;
  11534. }
  11535. if ((targetValue.mType->IsMethodRef()) || (targetType->IsMethodRef()))
  11536. {
  11537. // We can never cast a MethodRef to any class type
  11538. mResult = mModule->GetDefaultTypedValue(targetType);
  11539. return;
  11540. }
  11541. if (mModule->mContext->mResolvingVarField)
  11542. {
  11543. mResult = mModule->GetDefaultTypedValue(targetType);
  11544. return;
  11545. }
  11546. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  11547. if (targetType->IsGenericParam())
  11548. {
  11549. wasGenericParamType = true;
  11550. BfGenericParamInstance* origGenericParam = NULL;
  11551. int pass = 0;
  11552. while ((targetType != NULL) && (targetType->IsGenericParam()))
  11553. {
  11554. auto genericParamType = (BfGenericParamType*)targetType;
  11555. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  11556. if (pass == 0)
  11557. origGenericParam = genericParam;
  11558. auto typeConstraint = genericParam->mTypeConstraint;
  11559. if ((typeConstraint == NULL) && (genericParam->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Interface)))
  11560. typeConstraint = mModule->mContext->mBfObjectType;
  11561. targetType = typeConstraint;
  11562. if (++pass >= 100) // Sanity - but we should have caught circular error before
  11563. break;
  11564. }
  11565. if ((targetType == NULL) || (!targetType->IsObjectOrInterface()))
  11566. {
  11567. 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",
  11568. origGenericParam->GetGenericParamDef()->mName.c_str()), dynCastExpr->mTypeRef);
  11569. return;
  11570. }
  11571. }
  11572. if (targetType->IsVar())
  11573. {
  11574. mResult = mModule->GetDefaultTypedValue(targetType);
  11575. return;
  11576. }
  11577. if ((!targetType->IsObjectOrInterface()) && (!targetType->IsNullable()))
  11578. {
  11579. mModule->Fail(StrFormat("The as operator must be used with a reference type or nullable type ('%s' is a non-nullable value type)",
  11580. mModule->TypeToString(origTargetType).c_str()), dynCastExpr->mTypeRef);
  11581. return;
  11582. }
  11583. if (targetValue.mType->IsGenericParam())
  11584. {
  11585. auto genericParamType = (BfGenericParamType*)targetValue.mType;
  11586. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  11587. auto typeConstraint = genericParam->mTypeConstraint;
  11588. if (typeConstraint == NULL)
  11589. typeConstraint = mModule->mContext->mBfObjectType;
  11590. if ((typeConstraint->IsDelegate()) && (typeConstraint == targetType))
  11591. {
  11592. // Delegate constraints may be matched by valueless method references, so this won't always match (don't warn)
  11593. mResult = mModule->GetDefaultTypedValue(targetType);
  11594. return;
  11595. }
  11596. targetValue = mModule->GetDefaultTypedValue(typeConstraint);
  11597. }
  11598. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  11599. auto _CheckResult = [&]()
  11600. {
  11601. if ((mResult) && (origTargetType->IsGenericParam()))
  11602. mResult = mModule->GetDefaultTypedValue(origTargetType, false, BfDefaultValueKind_Undef);
  11603. };
  11604. if ((targetValue.mType->IsNullable()) && (targetType->IsInterface()))
  11605. {
  11606. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_SilentFail);
  11607. if (!mResult)
  11608. {
  11609. mModule->Warn(0, StrFormat("Conversion from '%s' to '%s' will always be null",
  11610. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(origTargetType).c_str()), dynCastExpr->mAsToken);
  11611. mResult = BfTypedValue(mModule->GetDefaultValue(origTargetType), origTargetType);
  11612. }
  11613. _CheckResult();
  11614. return;
  11615. }
  11616. if (targetValue.mType->IsVar())
  11617. {
  11618. mResult = mModule->GetDefaultTypedValue(targetType, false, BfDefaultValueKind_Undef);
  11619. return;
  11620. }
  11621. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  11622. {
  11623. mModule->Warn(0, StrFormat("Type '%s' is not applicable for dynamic casting",
  11624. mModule->TypeToString(targetValue.mType).c_str()), dynCastExpr->mAsToken);
  11625. auto typeInstance = targetValue.mType->ToTypeInstance();
  11626. if (targetValue.mType->IsWrappableType())
  11627. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  11628. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  11629. if (targetType->IsNullable())
  11630. {
  11631. auto elementType = targetType->GetUnderlyingType();
  11632. if (elementType == targetValue.mType)
  11633. {
  11634. mModule->mBfIRBuilder->PopulateType(targetType);
  11635. // We match nullable element
  11636. auto allocaInst = mModule->CreateAlloca(targetType);
  11637. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 2); // has_value
  11638. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  11639. hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // value
  11640. mModule->mBfIRBuilder->CreateStore(targetValue.mValue, hasValueAddr);
  11641. mResult = BfTypedValue(allocaInst, targetType, true);
  11642. _CheckResult();
  11643. return;
  11644. }
  11645. }
  11646. if (!matches)
  11647. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  11648. if (matches)
  11649. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_Explicit);
  11650. else if (targetType->IsNullable())
  11651. {
  11652. auto allocaInst = mModule->CreateAlloca(targetType);
  11653. auto allocaBits = mModule->mBfIRBuilder->CreateBitCast(allocaInst, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  11654. mModule->mBfIRBuilder->CreateMemSet(allocaBits, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  11655. mModule->GetConstValue(targetType->mSize), targetType->mAlign);
  11656. mResult = BfTypedValue(allocaInst, targetType, true);
  11657. }
  11658. else
  11659. mResult = BfTypedValue(mModule->GetDefaultValue(targetType), targetType);
  11660. _CheckResult();
  11661. return;
  11662. }
  11663. if (targetType->IsNullable())
  11664. {
  11665. if (autoComplete != NULL)
  11666. {
  11667. mResult = mModule->GetDefaultTypedValue(targetType);
  11668. return;
  11669. }
  11670. auto elementType = targetType->GetUnderlyingType();
  11671. auto allocaInst = mModule->CreateAlloca(targetType);
  11672. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, elementType->IsValuelessType() ? 1 : 2); // has_value
  11673. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(0, boolType), hasValueAddr);
  11674. auto objectType = mModule->mContext->mBfObjectType;
  11675. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  11676. auto matchBB = mModule->mBfIRBuilder->CreateBlock("as.match");
  11677. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  11678. mModule->EmitDynamicCastCheck(targetValue, elementType, matchBB, endBB);
  11679. BfBoxedType* boxedType = mModule->CreateBoxedType(elementType);
  11680. mModule->AddBasicBlock(matchBB);
  11681. if (elementType->IsValuelessType())
  11682. {
  11683. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  11684. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  11685. }
  11686. else
  11687. {
  11688. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 2); // has_value
  11689. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  11690. auto nullableValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // value
  11691. auto srcBoxedType = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(boxedType, BfIRPopulateType_Full));
  11692. auto boxedValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(srcBoxedType, 0, 1); // mValue
  11693. auto boxedValue = mModule->mBfIRBuilder->CreateLoad(boxedValueAddr);
  11694. mModule->mBfIRBuilder->CreateStore(boxedValue, nullableValueAddr);
  11695. }
  11696. mModule->mBfIRBuilder->CreateBr(endBB);
  11697. mModule->AddBasicBlock(endBB);
  11698. mResult = BfTypedValue(allocaInst, targetType, true);
  11699. _CheckResult();
  11700. return;
  11701. }
  11702. targetValue = mModule->LoadValue(targetValue);
  11703. if (targetType->IsValueType())
  11704. {
  11705. mModule->Fail("Invalid dynamic cast type", dynCastExpr->mTypeRef);
  11706. return;
  11707. }
  11708. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  11709. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  11710. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  11711. {
  11712. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  11713. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  11714. // it may be a "necessary cast" indeed
  11715. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  11716. {
  11717. if (srcTypeInstance == targetType)
  11718. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, the value is already type '%s'",
  11719. mModule->TypeToString(srcTypeInstance).c_str()), dynCastExpr->mAsToken);
  11720. else
  11721. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, '%s' is a subtype of '%s'",
  11722. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), dynCastExpr->mAsToken);
  11723. }
  11724. auto castedValue = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetTypeInstance));
  11725. mResult = BfTypedValue(castedValue, targetTypeInstance);
  11726. _CheckResult();
  11727. return;
  11728. }
  11729. else if ((!targetType->IsInterface()) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  11730. {
  11731. if (!mModule->IsInSpecializedSection())
  11732. {
  11733. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  11734. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), dynCastExpr->mAsToken);
  11735. }
  11736. mResult = mModule->GetDefaultTypedValue(targetType);
  11737. return;
  11738. }
  11739. if (autoComplete != NULL)
  11740. {
  11741. mResult = mModule->GetDefaultTypedValue(targetType, false, BfDefaultValueKind_Addr);
  11742. _CheckResult();
  11743. return;
  11744. }
  11745. auto irb = mModule->mBfIRBuilder;
  11746. auto objectType = mModule->mContext->mBfObjectType;
  11747. mModule->PopulateType(objectType, BfPopulateType_Full);
  11748. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  11749. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  11750. auto matchBlock = irb->CreateBlock("as.match");
  11751. BfIRValue targetVal = mModule->CreateAlloca(targetType);
  11752. irb->CreateAlignedStore(irb->CreateConstNull(irb->MapType(targetType)), targetVal, targetType->mAlign);
  11753. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBlock, endBB);
  11754. mModule->AddBasicBlock(matchBlock);
  11755. BfIRValue castedCallResult = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetType));
  11756. irb->CreateAlignedStore(castedCallResult, targetVal, targetValue.mType->mAlign);
  11757. irb->CreateBr(endBB);
  11758. mModule->AddBasicBlock(endBB);
  11759. mResult = BfTypedValue(irb->CreateAlignedLoad(targetVal, targetType->mAlign), targetType);
  11760. _CheckResult();
  11761. }
  11762. void BfExprEvaluator::Visit(BfCastExpression* castExpr)
  11763. {
  11764. auto autoComplete = GetAutoComplete();
  11765. if ((autoComplete != NULL) && (castExpr->mTypeRef != NULL))
  11766. {
  11767. // 'mayBeIdentifier' because this may be a misidentified cast - it could be a parenthesized expression
  11768. autoComplete->CheckTypeRef(castExpr->mTypeRef, true, true);
  11769. }
  11770. BfType* resolvedType = NULL;
  11771. if ((BfNodeDynCastExact<BfDotTypeReference>(castExpr->mTypeRef) != NULL) && (mExpectingType != NULL))
  11772. {
  11773. //mModule->SetElementType(castExpr->mTypeRef, BfSourceElementType_TypeRef);
  11774. resolvedType = mExpectingType;
  11775. }
  11776. else
  11777. resolvedType = ResolveTypeRef(castExpr->mTypeRef);
  11778. if (resolvedType != NULL)
  11779. mModule->AddDependency(resolvedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  11780. // If resolvedType is NULL then that's okay- we just leave the following expression uncasted
  11781. if (castExpr->mExpression == NULL)
  11782. {
  11783. mModule->AssertErrorState();
  11784. return;
  11785. }
  11786. auto exprFlags = (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) | BfEvalExprFlags_ExplicitCast);
  11787. mResult = mModule->CreateValueFromExpression(castExpr->mExpression, resolvedType, exprFlags);
  11788. }
  11789. bool BfExprEvaluator::IsExactMethodMatch(BfMethodInstance* methodA, BfMethodInstance* methodB, bool ignoreImplicitParams)
  11790. {
  11791. if (methodA->mReturnType != methodB->mReturnType)
  11792. return false;
  11793. int implicitParamCountA = methodA->GetImplicitParamCount();
  11794. if (methodA->HasExplicitThis())
  11795. implicitParamCountA++;
  11796. int implicitParamCountB = methodB->GetImplicitParamCount();
  11797. if (methodB->HasExplicitThis())
  11798. implicitParamCountB++;
  11799. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  11800. return false;
  11801. for (int i = 0; i < (int)methodA->GetParamCount() - implicitParamCountA; i++)
  11802. {
  11803. auto paramA = methodA->GetParamType(i + implicitParamCountA);
  11804. auto paramB = methodB->GetParamType(i + implicitParamCountB);
  11805. if (paramA != paramB)
  11806. return false;
  11807. }
  11808. return true;
  11809. }
  11810. void BfExprEvaluator::ConstResolve(BfExpression* expr)
  11811. {
  11812. BfConstResolver constResolver(mModule);
  11813. constResolver.Resolve(expr);
  11814. mResult = constResolver.mResult;
  11815. }
  11816. BfTypeInstance* BfExprEvaluator::VerifyBaseDelegateType(BfTypeInstance* baseDelegateType)
  11817. {
  11818. mModule->PopulateType(baseDelegateType, BfPopulateType_DataAndMethods);
  11819. if (baseDelegateType->mFieldInstances.size() != 2)
  11820. {
  11821. mModule->AssertErrorState();
  11822. return NULL;
  11823. }
  11824. return baseDelegateType;
  11825. }
  11826. bool BfExprEvaluator::CanBindDelegate(BfDelegateBindExpression* delegateBindExpr, BfMethodInstance** boundMethod, BfType* origMethodExpectingType, BfTypeVector* methodGenericArgumentsSubstitute)
  11827. {
  11828. if ((mExpectingType == NULL) && (origMethodExpectingType == NULL))
  11829. {
  11830. return false;
  11831. }
  11832. bool isGenericMatch = mExpectingType == NULL;
  11833. auto expectingType = mExpectingType;
  11834. if (expectingType == NULL)
  11835. expectingType = origMethodExpectingType;
  11836. auto typeInstance = expectingType->ToTypeInstance();
  11837. if ((typeInstance == NULL) ||
  11838. ((!typeInstance->mTypeDef->mIsDelegate) && (!typeInstance->mTypeDef->mIsFunction)))
  11839. return false;
  11840. mModule->PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  11841. auto methodInstance = mModule->GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  11842. if (methodInstance == NULL)
  11843. {
  11844. BF_DBG_FATAL("Invoke not found");
  11845. return false;
  11846. }
  11847. if (delegateBindExpr->mTarget == NULL)
  11848. return false;
  11849. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  11850. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  11851. typedValueExprs.resize(methodInstance->GetParamCount());
  11852. SizedArray<BfExpression*, 4> args;
  11853. args.resize(methodInstance->GetParamCount());
  11854. auto _FixType = [&](BfType* type)
  11855. {
  11856. if (!isGenericMatch)
  11857. return type;
  11858. auto fixedType = mModule->ResolveGenericType(type, NULL, methodGenericArgumentsSubstitute, mModule->mCurTypeInstance);
  11859. if (fixedType != NULL)
  11860. return fixedType;
  11861. return (BfType*)mModule->GetPrimitiveType(BfTypeCode_Var);
  11862. };
  11863. auto _TypeMatches = [&](BfType* lhs, BfType* rhs)
  11864. {
  11865. if (lhs == rhs)
  11866. return true;
  11867. return lhs->IsVar();
  11868. };
  11869. for (int i = 0; i < (int) methodInstance->GetParamCount(); i++)
  11870. {
  11871. auto typedValueExpr = &typedValueExprs[i];
  11872. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  11873. typedValueExpr->mTypedValue.mType = _FixType(methodInstance->GetParamType(i));
  11874. typedValueExpr->mRefNode = NULL;
  11875. args[i] = typedValueExpr;
  11876. }
  11877. BfMethodGenericArguments methodGenericArgs;
  11878. if (delegateBindExpr->mGenericArgs != NULL)
  11879. methodGenericArgs.mArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  11880. BfFunctionBindResult bindResult;
  11881. bindResult.mSkipMutCheck = true; // Allow operating on copies
  11882. bindResult.mBindType = expectingType;
  11883. mFunctionBindResult = &bindResult;
  11884. SetAndRestoreValue<bool> ignoreError(mModule->mIgnoreErrors, true);
  11885. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArgs);
  11886. mFunctionBindResult = NULL;
  11887. if (bindResult.mMethodInstance == NULL)
  11888. return false;
  11889. if (boundMethod != NULL)
  11890. *boundMethod = bindResult.mMethodInstance;
  11891. auto matchedMethod = bindResult.mMethodInstance;
  11892. if (!_TypeMatches(_FixType(methodInstance->mReturnType), matchedMethod->mReturnType))
  11893. return false;
  11894. int implicitParamCountA = methodInstance->GetImplicitParamCount();
  11895. int implicitParamCountB = matchedMethod->GetImplicitParamCount();
  11896. if (methodInstance->GetParamCount() - implicitParamCountA != matchedMethod->GetParamCount() - implicitParamCountB)
  11897. return false;
  11898. for (int i = 0; i < (int)methodInstance->GetParamCount() - implicitParamCountA; i++)
  11899. {
  11900. auto paramA = _FixType(methodInstance->GetParamType(i + implicitParamCountA));
  11901. auto paramB = _FixType(matchedMethod->GetParamType(i + implicitParamCountB));
  11902. if (!_TypeMatches(paramA, paramB))
  11903. return false;
  11904. }
  11905. return true;
  11906. }
  11907. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfIdentifierNode* identifierNode, int shadowIdx)
  11908. {
  11909. String findName = identifierNode->ToString();
  11910. if (mModule->mCurMethodState != NULL)
  11911. {
  11912. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  11913. auto checkMethodState = mModule->mCurMethodState;
  11914. bool isMixinOuterVariablePass = false;
  11915. int shadowSkip = shadowIdx;
  11916. while (checkMethodState != NULL)
  11917. {
  11918. BP_ZONE("LookupIdentifier:DoImplicitArgCapture");
  11919. BfTypeInstance* closureTypeInst = NULL;
  11920. BfClosureInstanceInfo* closureInstanceInfo = NULL;
  11921. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  11922. {
  11923. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  11924. }
  11925. BfLocalVarEntry* entry;
  11926. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(findName, &entry))
  11927. {
  11928. auto varDecl = entry->mLocalVar;
  11929. while (varDecl != NULL)
  11930. {
  11931. if (varDecl->mNameNode == identifierNode)
  11932. {
  11933. if (shadowSkip > 0)
  11934. {
  11935. shadowSkip--;
  11936. }
  11937. else
  11938. {
  11939. BfTypedValue localResult = LoadLocal(varDecl);
  11940. if (!isMixinOuterVariablePass)
  11941. {
  11942. mResultLocalVar = varDecl;
  11943. mResultFieldInstance = NULL;
  11944. mResultLocalVarRefNode = identifierNode;
  11945. }
  11946. return localResult;
  11947. }
  11948. }
  11949. varDecl = varDecl->mShadowedLocal;
  11950. }
  11951. }
  11952. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  11953. if (closureTypeInst != NULL)
  11954. {
  11955. closureTypeInst->mTypeDef->PopulateMemberSets();
  11956. BfMemberSetEntry* memberSetEntry = NULL;
  11957. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  11958. {
  11959. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  11960. while (fieldDef != NULL)
  11961. {
  11962. BfIdentifierNode* fieldNameNode = NULL;
  11963. if (fieldDef->mIdx < (int)checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries.size())
  11964. fieldNameNode = checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries[fieldDef->mIdx].mNameNode;
  11965. if (fieldNameNode == identifierNode)
  11966. {
  11967. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  11968. if (!field.mResolvedType->IsValuelessType())
  11969. {
  11970. if (mModule->mCurMethodState->mClosureState->mCapturing)
  11971. {
  11972. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  11973. return mModule->GetDefaultTypedValue(field.mResolvedType);
  11974. }
  11975. auto localVar = mModule->mCurMethodState->mLocals[0];
  11976. auto thisValue = localVar->mValue;
  11977. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  11978. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  11979. if (field.mResolvedType->IsRef())
  11980. {
  11981. auto refType = (BfRefType*)field.mResolvedType;
  11982. auto underlyingType = refType->GetUnderlyingType();
  11983. result = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(result.mValue, underlyingType->mAlign), underlyingType, true);
  11984. }
  11985. else if (fieldDef->mIsReadOnly)
  11986. result = mModule->LoadValue(result);
  11987. mResultLocalVar = localVar;
  11988. mResultFieldInstance = &field;
  11989. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  11990. return result;
  11991. }
  11992. }
  11993. fieldDef = fieldDef->mNextWithSameName;
  11994. }
  11995. }
  11996. }
  11997. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  11998. {
  11999. checkMethodState = checkMethodState->mPrevMethodState;
  12000. continue;
  12001. }
  12002. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  12003. bool isLocalMixinProcessing = false;
  12004. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  12005. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  12006. isLocalMixinProcessing = true;
  12007. if (!isLocalMixinProcessing)
  12008. break;
  12009. isMixinOuterVariablePass = true;
  12010. checkMethodState = checkMethodState->mPrevMethodState;
  12011. }
  12012. }
  12013. return BfTypedValue();
  12014. }
  12015. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfMethodInstance* methodInstance, int paramIdx, bool& failed, BfImplicitParamKind paramKind, const BfTypedValue& methodRefTarget)
  12016. {
  12017. if ((methodRefTarget) && (methodRefTarget.mValue.mId != BfIRValue::ID_IMPLICIT))
  12018. {
  12019. if (methodRefTarget.mType->IsMethodRef())
  12020. {
  12021. BfMethodRefType* methodRefType = (BfMethodRefType*)methodRefTarget.mType;
  12022. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  12023. BF_ASSERT(methodRefMethodInst == methodInstance);
  12024. auto paramType = methodInstance->GetParamType(paramIdx);
  12025. int dataIdx = methodRefType->GetDataIdxFromParamIdx(paramIdx);
  12026. if (dataIdx == -1)
  12027. {
  12028. BF_ASSERT(paramType->IsValuelessType());
  12029. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), paramType);
  12030. }
  12031. if (methodRefTarget.IsSplat())
  12032. {
  12033. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  12034. {
  12035. BF_ASSERT(paramIdx == -1);
  12036. return BfTypedValue(methodRefTarget.mValue, paramType, BfTypedValueKind_SplatHead);
  12037. }
  12038. else
  12039. {
  12040. int splatIdx = dataIdx;
  12041. if (dataIdx > 0)
  12042. {
  12043. if (methodRefType->WantsDataPassedAsSplat(0))
  12044. splatIdx += methodRefType->GetCaptureType(0)->GetSplatCount() - 1;
  12045. }
  12046. bool isAddr = false;
  12047. BfIRValue value = mModule->ExtractSplatValue(methodRefTarget, splatIdx, paramType, &isAddr);
  12048. // We moved the composite load from ExtractSplatValue to here. Hopefully this is correct.
  12049. // 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)
  12050. // if ((paramType->IsComposite()) && (mModule->IsTargetingBeefBackend()))
  12051. // value = mModule->mBfIRBuilder->CreateLoad(value);
  12052. auto lookupVal = BfTypedValue(value, paramType, isAddr);
  12053. if ((isAddr) && (!lookupVal.mType->IsComposite()))
  12054. lookupVal = mModule->LoadValue(lookupVal);
  12055. return lookupVal;
  12056. }
  12057. }
  12058. if ((paramType->IsComposite()) && (methodRefTarget.IsAddr()))
  12059. return BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefTarget.mValue, 0, dataIdx), paramType, true);
  12060. return BfTypedValue(mModule->ExtractValue(methodRefTarget, dataIdx), paramType);
  12061. }
  12062. }
  12063. // 'Default' implicit arg lookup, by identifier. May match field (for lambda), or local variable
  12064. if (paramKind == BfImplicitParamKind_General)
  12065. {
  12066. if (paramIdx == -1)
  12067. {
  12068. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(refNode))
  12069. {
  12070. BfAstNode* thisNode = NULL;
  12071. BfTypedValue thisValue;
  12072. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(delegateBindExpr->mTarget))
  12073. thisNode = memberReferenceExpr->mTarget;
  12074. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(delegateBindExpr->mTarget))
  12075. thisNode = qualifiedNameNode->mLeft;
  12076. else if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(delegateBindExpr->mTarget))
  12077. {
  12078. // Implicit
  12079. thisValue = mModule->GetThis();
  12080. }
  12081. if (auto thisExpr = BfNodeDynCast<BfExpression>(thisNode))
  12082. {
  12083. thisValue = mModule->CreateValueFromExpression(thisExpr);
  12084. if (!thisValue)
  12085. return BfTypedValue();
  12086. }
  12087. if (thisValue)
  12088. {
  12089. //TODO: handle 'mut', throw error if trying to capture from a non-mut, etc...
  12090. return thisValue;
  12091. }
  12092. }
  12093. }
  12094. String captureName = methodInstance->GetParamName(paramIdx);
  12095. BfIdentifierNode* identifierNode = methodInstance->GetParamNameNode(paramIdx);
  12096. BfTypedValue lookupVal;
  12097. if (identifierNode != NULL)
  12098. {
  12099. lookupVal = DoImplicitArgCapture(refNode, identifierNode, 0);
  12100. }
  12101. else
  12102. {
  12103. lookupVal = LookupIdentifier(NULL, captureName);
  12104. }
  12105. if (lookupVal)
  12106. {
  12107. auto paramType = methodInstance->GetParamType(paramIdx);
  12108. if (paramType->IsRef())
  12109. {
  12110. auto refType = (BfRefType*)paramType;
  12111. if (mResultLocalVar != NULL)
  12112. {
  12113. // When we are capturing, we need to note that we require capturing by reference here
  12114. auto localVar = mResultLocalVar;
  12115. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  12116. }
  12117. bool isValid = false;
  12118. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (lookupVal.mKind == BfTypedValueKind_MutableValue))
  12119. isValid = true;
  12120. if ((lookupVal.mType->IsRef()) || (lookupVal.IsAddr()))
  12121. isValid = true;
  12122. if (!isValid)
  12123. {
  12124. // Is there another way this can fail than to be in a lambda?
  12125. auto error = mModule->Fail(StrFormat("Method '%s' requires that '%s' be captured by reference. Consider adding by-reference capture specifier [&] to lambda.",
  12126. mModule->MethodToString(methodInstance).c_str(), captureName.c_str()), refNode, true);
  12127. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  12128. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  12129. failed = true;
  12130. }
  12131. }
  12132. else
  12133. {
  12134. if (lookupVal.mType->IsRef())
  12135. lookupVal = mModule->RemoveRef(lookupVal);
  12136. if (!lookupVal.mType->IsComposite())
  12137. lookupVal = mModule->LoadValue(lookupVal);
  12138. }
  12139. return lookupVal;
  12140. }
  12141. else
  12142. {
  12143. mModule->Fail(StrFormat("Failed to lookup implicit capture '%s'", captureName.c_str()), refNode, true);
  12144. failed = true;
  12145. return BfTypedValue();
  12146. }
  12147. }
  12148. return BfTypedValue();
  12149. }
  12150. void BfExprEvaluator::Visit(BfDelegateBindExpression* delegateBindExpr)
  12151. {
  12152. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  12153. if (mExpectingType == NULL)
  12154. {
  12155. mModule->Fail("Cannot infer delegate type", delegateBindExpr);
  12156. return;
  12157. }
  12158. BfTokenNode* newToken = NULL;
  12159. BfAllocTarget allocTarget;
  12160. ResolveAllocTarget(allocTarget, delegateBindExpr->mNewToken, newToken);
  12161. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  12162. SizedArray<BfExpression*, 4> args;
  12163. BfTypeInstance* delegateTypeInstance = NULL;
  12164. BfMethodInstance* methodInstance = NULL;
  12165. const char* bindTypeName = NULL;
  12166. bool isMethodRefMatch = false;
  12167. if (mExpectingType->IsMethodRef())
  12168. {
  12169. auto methodRefType = (BfMethodRefType*)mExpectingType;
  12170. BF_ASSERT(delegateBindExpr->mNewToken == NULL);
  12171. methodInstance = methodRefType->mMethodRef;
  12172. isMethodRefMatch = true;
  12173. }
  12174. else
  12175. {
  12176. if (mExpectingType->IsGenericParam())
  12177. {
  12178. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  12179. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsDelegate()))
  12180. {
  12181. delegateTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  12182. }
  12183. }
  12184. else
  12185. delegateTypeInstance = mExpectingType->ToTypeInstance();
  12186. if ((delegateTypeInstance == NULL) ||
  12187. ((!delegateTypeInstance->IsDelegate()) && (!delegateTypeInstance->IsFunction())))
  12188. {
  12189. mModule->Fail(StrFormat("Type '%s' cannot be used for method binding. Only delegate or function types are allowed.", mModule->TypeToString(mExpectingType).c_str()), delegateBindExpr);
  12190. return;
  12191. }
  12192. bindTypeName = (delegateTypeInstance->IsDelegate()) ? "delegate" : "function";
  12193. mModule->PopulateType(delegateTypeInstance, BfPopulateType_DataAndMethods);
  12194. methodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  12195. if (methodInstance == NULL)
  12196. {
  12197. BF_DBG_FATAL("Invoke not found");
  12198. return;
  12199. }
  12200. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(delegateBindExpr->mNewToken))
  12201. {
  12202. if (delegateTypeInstance->IsFunction())
  12203. mModule->Fail("Function bindings are direct assignments, allocation specifier is not applicable", delegateBindExpr->mNewToken);
  12204. else if (tokenNode->GetToken() == BfToken_Append)
  12205. {
  12206. mModule->Fail("Append allocation on delegate bind not supported", delegateBindExpr->mNewToken);
  12207. }
  12208. }
  12209. }
  12210. int paramOffset = methodInstance->HasExplicitThis() ? 1 : 0;
  12211. typedValueExprs.resize(methodInstance->GetParamCount() - paramOffset);
  12212. args.resize(methodInstance->GetParamCount() - paramOffset);
  12213. for (int i = 0; i < (int)methodInstance->GetParamCount() - paramOffset; i++)
  12214. {
  12215. auto typedValueExpr = &typedValueExprs[i];
  12216. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  12217. typedValueExpr->mTypedValue.mType = methodInstance->GetParamType(i + paramOffset);
  12218. if (methodInstance->GetParamKind(i + paramOffset) == BfParamKind_Params)
  12219. typedValueExpr->mTypedValue.mKind = BfTypedValueKind_Params;
  12220. typedValueExpr->mRefNode = NULL;
  12221. args[i] = typedValueExpr;
  12222. }
  12223. BfMethodGenericArguments methodGenericArgs;
  12224. if (delegateBindExpr->mGenericArgs != NULL)
  12225. methodGenericArgs.mArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  12226. if (delegateBindExpr->mTarget == NULL)
  12227. {
  12228. mModule->AssertErrorState();
  12229. return;
  12230. }
  12231. auto autoComplete = GetAutoComplete();
  12232. if (autoComplete != NULL)
  12233. {
  12234. SetAndRestoreValue<bool> prevForceAllowNonStatic(autoComplete->mForceAllowNonStatic, methodInstance->mMethodDef->mHasExplicitThis);
  12235. GetAutoComplete()->CheckNode(delegateBindExpr->mTarget, true);
  12236. }
  12237. if ((!delegateBindExpr->mTarget->IsA<BfIdentifierNode>()) &&
  12238. (!delegateBindExpr->mTarget->IsA<BfMemberReferenceExpression>()))
  12239. {
  12240. mModule->Fail(StrFormat("Invalid %s binding target, %s can only bind to method references. Consider wrapping expression in a lambda.", bindTypeName, bindTypeName), delegateBindExpr->mTarget);
  12241. mModule->CreateValueFromExpression(delegateBindExpr->mTarget);
  12242. return;
  12243. }
  12244. BfFunctionBindResult bindResult;
  12245. bindResult.mSkipMutCheck = true; // Allow operating on copies
  12246. bindResult.mBindType = delegateTypeInstance;
  12247. //
  12248. {
  12249. SetAndRestoreValue<BfType*> prevExpectingType(mExpectingType, methodInstance->mReturnType);
  12250. mFunctionBindResult = &bindResult;
  12251. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArgs);
  12252. mFunctionBindResult = NULL;
  12253. }
  12254. SetMethodElementType(delegateBindExpr->mTarget);
  12255. if (bindResult.mMethodInstance == NULL)
  12256. {
  12257. if ((mResult) && (IsVar(mResult.mType)))
  12258. return;
  12259. mResult = BfTypedValue();
  12260. return;
  12261. }
  12262. if (((bindResult.mMethodInstance->mComptimeFlags & BfComptimeFlag_Comptime) != 0) && ((mModule->mCurMethodInstance->mComptimeFlags & BfComptimeFlag_Comptime) == 0))
  12263. {
  12264. 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);
  12265. }
  12266. auto bindMethodInstance = bindResult.mMethodInstance;
  12267. if (isMethodRefMatch)
  12268. {
  12269. // WTF- this was always false, what was it supposed to catch?
  12270. // if (bindMethodInstance != bindResult.mMethodInstance)
  12271. // {
  12272. // mResult = BfTypedValue();
  12273. // return;
  12274. // }
  12275. }
  12276. else
  12277. {
  12278. bool isExactMethodMatch = IsExactMethodMatch(methodInstance, bindMethodInstance, true);
  12279. if ((mExpectingType != NULL) && (mExpectingType->IsFunction()) && (methodInstance->mMethodDef->mIsMutating != bindMethodInstance->mMethodDef->mIsMutating))
  12280. isExactMethodMatch = false;
  12281. if (!isExactMethodMatch)
  12282. {
  12283. if (bindResult.mCheckedMultipleMethods)
  12284. {
  12285. mModule->Fail(StrFormat("No overload for '%s' matches %s '%s'", bindMethodInstance->mMethodDef->mName.c_str(), bindTypeName,
  12286. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  12287. }
  12288. else
  12289. {
  12290. mModule->Fail(StrFormat("Method '%s' does not match %s '%s'", mModule->MethodToString(bindMethodInstance, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType | BfMethodNameFlag_IncludeMut)).c_str(), bindTypeName,
  12291. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  12292. }
  12293. mResult = BfTypedValue();
  12294. return;
  12295. }
  12296. }
  12297. bool isDirectFunction = false;
  12298. if ((bindResult.mMethodInstance->GetOwner()->IsFunction()) && (bindResult.mFunc))
  12299. isDirectFunction = true;
  12300. if (bindMethodInstance->mIsIntrinsic)
  12301. {
  12302. 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);
  12303. mResult = BfTypedValue();
  12304. return;
  12305. }
  12306. bool hasIncompatibleCallingConventions = !mModule->mSystem->IsCompatibleCallingConvention(methodInstance->mCallingConvention, bindMethodInstance->mCallingConvention);
  12307. auto _GetInvokeMethodName = [&]()
  12308. {
  12309. StringT<512> methodName = "Invoke$";
  12310. methodName += mModule->mCurMethodInstance->mMethodDef->mName;
  12311. int prevSepPos = (int)methodName.LastIndexOf('$');
  12312. if (prevSepPos > 6)
  12313. {
  12314. methodName.RemoveToEnd(prevSepPos);
  12315. }
  12316. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  12317. HashContext hashCtx;
  12318. if (mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mPartialIdx != -1)
  12319. hashCtx.Mixin(mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mPartialIdx);
  12320. if (delegateBindExpr->mFatArrowToken != NULL)
  12321. {
  12322. hashCtx.Mixin(delegateBindExpr->mFatArrowToken->GetStartCharId());
  12323. }
  12324. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  12325. {
  12326. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  12327. {
  12328. StringT<128> genericTypeName;
  12329. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  12330. hashCtx.MixinStr(genericTypeName);
  12331. }
  12332. }
  12333. Val128 hashVal = hashCtx.Finish128();
  12334. methodName += '$';
  12335. methodName += BfTypeUtils::HashEncode64(hashVal.mLow);
  12336. StringT<512> mangledName;
  12337. BfMangler::MangleMethodName(mangledName, mModule->mCompiler->GetMangleKind(), mModule->mCurTypeInstance, methodName);
  12338. return mangledName;
  12339. };
  12340. if ((delegateBindExpr->mNewToken == NULL) || (delegateTypeInstance->IsFunction()))
  12341. {
  12342. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder != NULL))
  12343. {
  12344. BF_ASSERT(bindResult.mMethodInstance->mHotMethod != NULL);
  12345. mModule->mCurMethodState->mHotDataReferenceBuilder->mFunctionPtrs.Add(bindResult.mMethodInstance->mHotMethod);
  12346. }
  12347. if (isDirectFunction)
  12348. {
  12349. //if ((delegateTypeInstance != NULL) && (delegateTypeInstance->IsFunction()))
  12350. if (mExpectingType->IsFunction())
  12351. {
  12352. auto intPtrVal = mModule->mBfIRBuilder->CreatePtrToInt(bindResult.mFunc, BfTypeCode_IntPtr);
  12353. mResult = BfTypedValue(intPtrVal, mExpectingType);
  12354. return;
  12355. }
  12356. }
  12357. if (mExpectingType->IsFunction())
  12358. {
  12359. BfIRValue result;
  12360. if ((hasIncompatibleCallingConventions) && (mModule->HasExecutedOutput()))
  12361. {
  12362. //
  12363. {
  12364. SetAndRestoreValue<bool> prevIgnore(mModule->mBfIRBuilder->mIgnoreWrites, true);
  12365. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mOrigTarget, bindResult.mMethodInstance, mExpectingType);
  12366. }
  12367. if (result)
  12368. {
  12369. String methodName = _GetInvokeMethodName();
  12370. SizedArray<BfIRType, 8> irParamTypes;
  12371. BfIRType irReturnType;
  12372. methodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  12373. int thisFuncParamIdx = methodInstance->GetThisIdx();
  12374. int thisBindParamIdx = methodInstance->GetThisIdx();
  12375. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  12376. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  12377. mModule->mBfIRBuilder->SaveDebugLocation();
  12378. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  12379. auto funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  12380. auto srcCallingConv = mModule->GetIRCallingConvention(methodInstance);
  12381. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  12382. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  12383. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  12384. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  12385. SizedArray<BfIRValue, 8> irArgs;
  12386. for (int paramIdx = 0; paramIdx < irParamTypes.size(); paramIdx++)
  12387. {
  12388. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(paramIdx));
  12389. }
  12390. auto bindFuncVal = bindResult.mFunc;
  12391. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!mModule->mIsComptimeModule))
  12392. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  12393. auto callResult = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  12394. auto destCallingConv = mModule->GetIRCallingConvention(bindMethodInstance);
  12395. if (destCallingConv != BfIRCallingConv_CDecl)
  12396. mModule->mBfIRBuilder->SetCallCallingConv(callResult, destCallingConv);
  12397. if (methodInstance->mReturnType->IsValuelessType())
  12398. mModule->mBfIRBuilder->CreateRetVoid();
  12399. else
  12400. mModule->mBfIRBuilder->CreateRet(callResult);
  12401. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  12402. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  12403. mModule->mBfIRBuilder->RestoreDebugLocation();
  12404. result = mModule->mBfIRBuilder->CreatePtrToInt(funcValue, BfTypeCode_IntPtr);
  12405. }
  12406. }
  12407. else
  12408. {
  12409. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsGenericParam()) && (bindResult.mMethodInstance->GetOwner()->IsInterface()))
  12410. {
  12411. bool matching = true;
  12412. if (methodInstance->HasExplicitThis())
  12413. {
  12414. auto thisType = methodInstance->GetParamType(0);
  12415. if (thisType->IsPointer())
  12416. thisType = thisType->GetUnderlyingType();
  12417. if (thisType->IsRef())
  12418. thisType = thisType->GetUnderlyingType();
  12419. matching = thisType == bindResult.mOrigTarget.mType;
  12420. }
  12421. if (matching)
  12422. {
  12423. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), mExpectingType);
  12424. return;
  12425. }
  12426. }
  12427. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mOrigTarget, bindResult.mMethodInstance, mExpectingType, BfCastFlags_None, bindResult.mFunc);
  12428. }
  12429. if (result)
  12430. mResult = BfTypedValue(result, mExpectingType);
  12431. return;
  12432. }
  12433. if (bindResult.mMethodInstance->mDisallowCalling)
  12434. {
  12435. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  12436. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  12437. return;
  12438. }
  12439. auto methodRefType = mModule->CreateMethodRefType(bindResult.mMethodInstance);
  12440. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12441. mModule->AddCallDependency(bindResult.mMethodInstance);
  12442. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  12443. {
  12444. mResult = bindResult.mOrigTarget;
  12445. }
  12446. else
  12447. {
  12448. if ((bindResult.mMethodInstance->mMethodDef->mIsLocalMethod) || (!bindResult.mTarget))
  12449. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  12450. else
  12451. {
  12452. auto methodRefPtr = mModule->CreateAlloca(methodRefType, "bindResult");
  12453. auto elemPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefPtr, 0, 0);
  12454. BfTypedValue target;
  12455. if (bindResult.mTarget.IsSplat())
  12456. target = mModule->AggregateSplat(bindResult.mTarget, &bindResult.mIRArgs[0]);
  12457. else
  12458. target = bindResult.mTarget;
  12459. mModule->mBfIRBuilder->CreateStore(target.mValue, elemPtr);
  12460. mResult = BfTypedValue(methodRefPtr, methodRefType, true);
  12461. }
  12462. }
  12463. return;
  12464. }
  12465. int implicitParamCount = bindMethodInstance->GetImplicitParamCount();
  12466. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  12467. BfClosureType* closureTypeInst = NULL;
  12468. auto origTarget = bindResult.mOrigTarget;
  12469. auto target = bindResult.mTarget;
  12470. BfTypedValue methodRefTarget;
  12471. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  12472. methodRefTarget = bindResult.mOrigTarget;
  12473. bool isStructTarget = (target) && (target.mType->IsStruct());
  12474. bool bindCapturesThis = bindMethodInstance->HasThis() && !isStructTarget;
  12475. bool needsSplat = (isStructTarget) && (!bindMethodInstance->mMethodDef->mIsMutating) && (bindMethodInstance->AllowsSplatting(-1));
  12476. bool captureThisByValue = isStructTarget;
  12477. if (bindMethodInstance->mMethodDef->mIsLocalMethod)
  12478. {
  12479. // Local method captures always capture 'this' by reference
  12480. captureThisByValue = false;
  12481. }
  12482. if ((origTarget.mType != NULL) &&
  12483. ((origTarget.mType->IsRef()) || (origTarget.mType->IsPointer())))
  12484. {
  12485. captureThisByValue = false;
  12486. }
  12487. if (methodRefTarget)
  12488. BF_ASSERT(methodRefTarget.mType->IsMethodRef());
  12489. if (target.IsSplat())
  12490. target = mModule->AggregateSplat(target, &bindResult.mIRArgs[0]);
  12491. bool hasCaptures = false;
  12492. // Do we need a special delegate type for this?
  12493. if (((captureThisByValue) || (needsSplat) || (implicitParamCount > 0) /*|| (hasIncompatibleCallingConventions)*/) &&
  12494. (mModule->HasExecutedOutput()))
  12495. {
  12496. hasCaptures = true;
  12497. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  12498. if (captureThisByValue)
  12499. target = mModule->LoadValue(target);
  12500. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  12501. HashContext hashCtx;
  12502. hashCtx.MixinStr(delegateTypeName);
  12503. // We mix in the project for reasons described in the lambda binding handler
  12504. hashCtx.MixinStr(curProject->mName);
  12505. String structTargetTypeName;
  12506. String structTargetName;
  12507. // Implicit param separator
  12508. for (int implicitParamIdx = bindMethodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  12509. {
  12510. auto paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  12511. if ((implicitParamIdx == -1) && (captureThisByValue))
  12512. {
  12513. if (paramType->IsPointer())
  12514. paramType = paramType->GetUnderlyingType();
  12515. }
  12516. structTargetTypeName = mModule->TypeToString(paramType);
  12517. structTargetName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  12518. hashCtx.MixinStr(structTargetTypeName);
  12519. hashCtx.MixinStr(structTargetName);
  12520. }
  12521. Val128 hash128 = hashCtx.Finish128();
  12522. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  12523. checkClosureType->mContext = mModule->mContext;
  12524. checkClosureType->mBaseType = delegateTypeInstance;
  12525. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_TypeDef);
  12526. closureTypeInst = (BfClosureType*)resolvedClosureType;
  12527. if (checkClosureType == resolvedClosureType)
  12528. {
  12529. // This is a new closure type
  12530. closureTypeInst->Init(curProject);
  12531. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  12532. {
  12533. String fieldName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  12534. BfType* paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  12535. if ((implicitParamIdx == -1) && (captureThisByValue))
  12536. {
  12537. if (paramType->IsPointer())
  12538. paramType = paramType->GetUnderlyingType();
  12539. }
  12540. if (fieldName == "this")
  12541. fieldName = "__this";
  12542. closureTypeInst->AddField(paramType, fieldName);
  12543. }
  12544. closureTypeInst->Finish();
  12545. mModule->PopulateType(resolvedClosureType, BfPopulateType_Declaration);
  12546. }
  12547. else
  12548. {
  12549. // Already had this entry
  12550. delete checkClosureType;
  12551. }
  12552. useTypeInstance = closureTypeInst;
  12553. }
  12554. mModule->PopulateType(useTypeInstance);
  12555. if (delegateBindExpr->mTarget == NULL)
  12556. {
  12557. mModule->AssertErrorState();
  12558. return;
  12559. }
  12560. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  12561. // Do we need specialized calling code for this?
  12562. BfIRValue funcValue;
  12563. if (((needsSplat) || (implicitParamCount > 0) || (hasIncompatibleCallingConventions)) &&
  12564. (mModule->HasExecutedOutput()))
  12565. {
  12566. int fieldIdx = 0;
  12567. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  12568. {
  12569. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  12570. int gepIdx = fieldInst->mDataIdx;
  12571. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, gepIdx);
  12572. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  12573. if ((implicitParamIdx == -1) && (captureThisByValue))
  12574. {
  12575. if (fieldType->IsPointer())
  12576. fieldType = fieldType->GetUnderlyingType();
  12577. }
  12578. bool failed = false;
  12579. BfTypedValue lookupVal;
  12580. if (implicitParamIdx == -1)
  12581. lookupVal = target;
  12582. else
  12583. lookupVal = DoImplicitArgCapture(delegateBindExpr->mTarget, bindResult.mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_General, methodRefTarget);
  12584. if (!lookupVal)
  12585. continue;
  12586. if ((fieldType->IsPointer()) && (lookupVal.mType != fieldType))
  12587. {
  12588. BF_ASSERT(fieldType->GetUnderlyingType() == lookupVal.mType);
  12589. BF_ASSERT(lookupVal.IsAddr());
  12590. }
  12591. else if (!fieldType->IsRef())
  12592. lookupVal = mModule->LoadOrAggregateValue(lookupVal);
  12593. if (lookupVal)
  12594. mModule->mBfIRBuilder->CreateStore(lookupVal.mValue, fieldPtr);
  12595. fieldIdx++;
  12596. }
  12597. String methodName = _GetInvokeMethodName();
  12598. SizedArray<BfIRType, 8> irParamTypes;
  12599. BfIRType irReturnType;
  12600. bool hasThis = false;
  12601. if (hasCaptures)
  12602. {
  12603. hasThis = true;
  12604. methodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  12605. int thisIdx = 0;
  12606. if (GetStructRetIdx(methodInstance) == 0)
  12607. thisIdx = 1;
  12608. irParamTypes[thisIdx] = mModule->mBfIRBuilder->MapType(useTypeInstance);
  12609. }
  12610. else
  12611. {
  12612. BF_ASSERT(hasIncompatibleCallingConventions);
  12613. bindMethodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  12614. hasThis = bindMethodInstance->HasThis();
  12615. }
  12616. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  12617. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  12618. mModule->mBfIRBuilder->SaveDebugLocation();
  12619. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  12620. funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  12621. if (GetStructRetIdx(methodInstance) != -1)
  12622. {
  12623. mModule->mBfIRBuilder->Func_AddAttribute(funcValue, GetStructRetIdx(methodInstance) + 1, BfIRAttribute_NoAlias);
  12624. mModule->mBfIRBuilder->Func_AddAttribute(funcValue, GetStructRetIdx(methodInstance) + 1, BfIRAttribute_StructRet);
  12625. }
  12626. auto srcCallingConv = mModule->GetIRCallingConvention(methodInstance);
  12627. if ((!hasThis) && (methodInstance->mCallingConvention == BfCallingConvention_Stdcall))
  12628. srcCallingConv = BfIRCallingConv_StdCall;
  12629. else if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  12630. srcCallingConv = BfIRCallingConv_FastCall;
  12631. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  12632. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  12633. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  12634. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  12635. fieldIdx = 0;
  12636. SizedArray<BfIRValue, 8> irArgs;
  12637. int argIdx = 0;
  12638. if (GetStructRetIdx(bindMethodInstance) == 0)
  12639. {
  12640. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(GetStructRetIdx(methodInstance)));
  12641. argIdx++;
  12642. }
  12643. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  12644. {
  12645. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  12646. int gepIdx = fieldInst->mDataIdx;
  12647. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  12648. bool disableSplat = false;
  12649. if ((implicitParamIdx == -1) && (captureThisByValue))
  12650. {
  12651. if (fieldType->IsPointer())
  12652. {
  12653. fieldType = fieldType->GetUnderlyingType();
  12654. disableSplat = true;
  12655. }
  12656. }
  12657. int thisIdx = 0;
  12658. if (GetStructRetIdx(methodInstance) == 0)
  12659. thisIdx = 1;
  12660. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->GetArgument(thisIdx), 0, gepIdx);
  12661. BfTypedValue typedVal(fieldPtr, fieldType, true);
  12662. PushArg(typedVal, irArgs, disableSplat);
  12663. fieldIdx++;
  12664. }
  12665. if (hasThis)
  12666. argIdx++;
  12667. if (GetStructRetIdx(bindMethodInstance) == 1)
  12668. {
  12669. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(GetStructRetIdx(methodInstance)));
  12670. argIdx++;
  12671. }
  12672. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  12673. {
  12674. auto paramType = methodInstance->GetParamType(paramIdx);
  12675. if ((paramType->IsSplattable()) && (!IsComptime()))
  12676. {
  12677. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++)); }, paramType);
  12678. }
  12679. else if (!paramType->IsValuelessType())
  12680. {
  12681. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++));
  12682. }
  12683. }
  12684. auto bindFuncVal = bindResult.mFunc;
  12685. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!mModule->mIsComptimeModule))
  12686. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  12687. auto callInst = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  12688. if (GetStructRetIdx(bindMethodInstance) != -1)
  12689. mModule->mBfIRBuilder->Call_AddAttribute(callInst, GetStructRetIdx(bindMethodInstance) + 1, BfIRAttribute_StructRet);
  12690. auto destCallingConv = mModule->GetIRCallingConvention(bindMethodInstance);
  12691. if (destCallingConv != BfIRCallingConv_CDecl)
  12692. mModule->mBfIRBuilder->SetCallCallingConv(callInst, destCallingConv);
  12693. if ((methodInstance->mReturnType->IsValuelessType()) || (GetStructRetIdx(methodInstance) != -1))
  12694. {
  12695. mModule->mBfIRBuilder->CreateRetVoid();
  12696. }
  12697. else
  12698. {
  12699. mModule->mBfIRBuilder->CreateRet(callInst);
  12700. }
  12701. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  12702. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  12703. mModule->mBfIRBuilder->RestoreDebugLocation();
  12704. }
  12705. else if ((closureTypeInst != NULL) && (captureThisByValue))
  12706. {
  12707. // 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
  12708. int dataIdx = 1;
  12709. if (!closureTypeInst->mFieldInstances.IsEmpty())
  12710. {
  12711. auto& fieldInst = closureTypeInst->mFieldInstances[0];
  12712. BF_ASSERT(fieldInst.GetFieldDef()->mName == "__this");
  12713. dataIdx = fieldInst.mDataIdx;
  12714. }
  12715. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, dataIdx);
  12716. target = mModule->LoadValue(target);
  12717. mModule->mBfIRBuilder->CreateStore(target.mValue, fieldPtr);
  12718. target = BfTypedValue(fieldPtr, target.mType, true);
  12719. }
  12720. BfResolvedArgs resolvedArgs;
  12721. MatchConstructor(delegateBindExpr, delegateBindExpr, mResult, useTypeInstance, resolvedArgs, false, BfMethodGenericArguments(), BfAllowAppendKind_No);
  12722. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  12723. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType, BfIRPopulateType_Full));
  12724. // >> delegate.mTarget = bindResult.mTarget
  12725. BfIRValue valPtr;
  12726. if (mModule->HasExecutedOutput())
  12727. {
  12728. if ((implicitParamCount > 0) || (needsSplat)) // Point back to self, it contains capture data
  12729. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12730. else if (bindResult.mTarget)
  12731. {
  12732. if ((target.mType->IsObjectOrInterface()) &&
  12733. (mModule->mCompiler->mOptions.mObjectHasDebugFlags) && (!mModule->mIsComptimeModule) &&
  12734. (mModule->mCompiler->mSystem->mPtrSize == 8))
  12735. {
  12736. auto numVal = mModule->mBfIRBuilder->CreatePtrToInt(target.mValue, BfTypeCode_UInt64);
  12737. auto orVal = mModule->mBfIRBuilder->CreateOr(numVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_UInt64, (uint64)0x8000000000000000ULL));
  12738. valPtr = mModule->mBfIRBuilder->CreateIntToPtr(orVal, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12739. }
  12740. else
  12741. valPtr = mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12742. }
  12743. else
  12744. valPtr = mModule->GetDefaultValue(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  12745. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 2);
  12746. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  12747. }
  12748. if (!funcValue)
  12749. {
  12750. funcValue = bindResult.mFunc;
  12751. if (!funcValue)
  12752. {
  12753. if ((mModule->HasExecutedOutput()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  12754. mModule->AssertErrorState();
  12755. return;
  12756. }
  12757. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!bindResult.mMethodInstance->mMethodDef->mIsVirtual) && (!mModule->mIsComptimeModule))
  12758. {
  12759. funcValue = mModule->mBfIRBuilder->RemapBindFunction(funcValue);
  12760. }
  12761. }
  12762. // >> delegate.mFuncPtr = bindResult.mFunc
  12763. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  12764. valPtr = mModule->mBfIRBuilder->CreateBitCast(funcValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  12765. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 1);
  12766. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  12767. }
  12768. void BfExprEvaluator::VisitLambdaBodies(BfAstNode* body, BfFieldDtorDeclaration* fieldDtor)
  12769. {
  12770. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  12771. mModule->VisitChild(blockBody);
  12772. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  12773. {
  12774. auto result = mModule->CreateValueFromExpression(bodyExpr);
  12775. if ((result) && (mModule->mCurMethodState->mClosureState != NULL) &&
  12776. (mModule->mCurMethodState->mClosureState->mReturnTypeInferState == BfReturnTypeInferState_Inferring))
  12777. mModule->mCurMethodState->mClosureState->mReturnType = result.mType;
  12778. }
  12779. while (fieldDtor != NULL)
  12780. {
  12781. mModule->mCurMethodState->mLeftBlockUncond = false;
  12782. mModule->VisitChild(fieldDtor->mBody);
  12783. fieldDtor = fieldDtor->mNextFieldDtor;
  12784. }
  12785. }
  12786. BfLambdaInstance* BfExprEvaluator::GetLambdaInstance(BfLambdaBindExpression* lambdaBindExpr, BfAllocTarget& allocTarget)
  12787. {
  12788. if (mModule->mCurMethodState == NULL)
  12789. return NULL;
  12790. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  12791. BfAstNodeList cacheNodeList;
  12792. cacheNodeList.mList.Add(lambdaBindExpr);
  12793. ///
  12794. {
  12795. auto checkMethodState = mModule->mCurMethodState;
  12796. while (checkMethodState != NULL)
  12797. {
  12798. if (checkMethodState->mMixinState != NULL)
  12799. cacheNodeList.mList.Add(checkMethodState->mMixinState->mSource);
  12800. checkMethodState = checkMethodState->mPrevMethodState;
  12801. }
  12802. }
  12803. bool isInferReturnType = (mBfEvalExprFlags & BfEvalExprFlags_InferReturnType) != 0;
  12804. BfLambdaInstance* lambdaInstance = NULL;
  12805. if ((!isInferReturnType) && (rootMethodState->mLambdaCache.TryGetValue(cacheNodeList, &lambdaInstance)))
  12806. return lambdaInstance;
  12807. static int sBindCount = 0;
  12808. sBindCount++;
  12809. bool isFunctionBind = false;
  12810. BfTypeInstance* delegateTypeInstance = NULL;
  12811. BfMethodInstance* invokeMethodInstance = NULL;
  12812. if (mExpectingType == NULL)
  12813. {
  12814. mModule->Fail("Cannot infer delegate type", lambdaBindExpr);
  12815. delegateTypeInstance = mModule->ResolveTypeDef(mModule->mCompiler->mActionTypeDef)->ToTypeInstance();
  12816. }
  12817. else
  12818. {
  12819. delegateTypeInstance = mExpectingType->ToTypeInstance();
  12820. if ((delegateTypeInstance == NULL) ||
  12821. ((!delegateTypeInstance->mTypeDef->mIsDelegate) && (!delegateTypeInstance->mTypeDef->mIsFunction)))
  12822. {
  12823. if (lambdaBindExpr->mFatArrowToken != NULL)
  12824. mModule->Fail("Can only bind lambdas to delegate types", lambdaBindExpr->mFatArrowToken);
  12825. delegateTypeInstance = mModule->ResolveTypeDef(mModule->mCompiler->mActionTypeDef)->ToTypeInstance();
  12826. }
  12827. else
  12828. {
  12829. invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  12830. }
  12831. isFunctionBind = delegateTypeInstance->mTypeDef->mIsFunction;
  12832. }
  12833. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(lambdaBindExpr->mNewToken))
  12834. {
  12835. if (isFunctionBind)
  12836. {
  12837. mModule->Fail("Function lambda binding does not require allocation", lambdaBindExpr->mNewToken);
  12838. }
  12839. else if (tokenNode->GetToken() == BfToken_Append)
  12840. {
  12841. mModule->Fail("Append allocation on delegate bind not supported", lambdaBindExpr->mNewToken);
  12842. }
  12843. }
  12844. if (invokeMethodInstance != NULL)
  12845. {
  12846. if ((int)lambdaBindExpr->mParams.size() < invokeMethodInstance->GetParamCount())
  12847. {
  12848. BfAstNode* refNode = lambdaBindExpr->mCloseParen;
  12849. if (refNode == NULL)
  12850. refNode = lambdaBindExpr;
  12851. mModule->Fail(StrFormat("Not enough parameters for delegate type '%s'. Expected %d more.",
  12852. mModule->TypeToString(delegateTypeInstance).c_str(), invokeMethodInstance->GetParamCount() - lambdaBindExpr->mParams.size()), refNode);
  12853. }
  12854. else if ((int)lambdaBindExpr->mParams.size() > invokeMethodInstance->GetParamCount())
  12855. {
  12856. BfAstNode* refNode = lambdaBindExpr->mParams[invokeMethodInstance->GetParamCount()];
  12857. mModule->Fail(StrFormat("Too many parameters for delegate type '%s'. Expected %d fewer.",
  12858. mModule->TypeToString(delegateTypeInstance).c_str(), lambdaBindExpr->mParams.size() - invokeMethodInstance->GetParamCount()), refNode);
  12859. }
  12860. }
  12861. auto autoComplete = GetAutoComplete();
  12862. bool wasCapturingMethodInfo = false;
  12863. if ((autoComplete != NULL) && (invokeMethodInstance != NULL))
  12864. {
  12865. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  12866. bool isAutocompleteNode = false;
  12867. if (lambdaBindExpr->mFatArrowToken != NULL)
  12868. {
  12869. if (autoComplete->IsAutocompleteNode(lambdaBindExpr, lambdaBindExpr->mFatArrowToken))
  12870. isAutocompleteNode = true;
  12871. }
  12872. else if (autoComplete->IsAutocompleteNode(lambdaBindExpr))
  12873. isAutocompleteNode = true;
  12874. if (isAutocompleteNode)
  12875. autoComplete->CheckInvocation(lambdaBindExpr, lambdaBindExpr->mOpenParen, lambdaBindExpr->mCloseParen, lambdaBindExpr->mCommas);
  12876. if (autoComplete->mIsCapturingMethodMatchInfo)
  12877. {
  12878. autoComplete->mMethodMatchInfo->mInstanceList.Clear();
  12879. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  12880. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  12881. methodMatchEntry.mTypeInstance = invokeMethodInstance->GetOwner();
  12882. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  12883. methodMatchEntry.mMethodDef = invokeMethodInstance->mMethodDef;
  12884. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  12885. methodMatchInfo->mBestIdx = 0;
  12886. methodMatchInfo->mMostParamsMatched = 0;
  12887. int cursorIdx = lambdaBindExpr->GetParser()->mCursorIdx;
  12888. if ((lambdaBindExpr->mCloseParen == NULL) || (cursorIdx <= lambdaBindExpr->mCloseParen->GetSrcStart()))
  12889. {
  12890. int paramIdx = 0;
  12891. for (int commaIdx = 0; commaIdx < (int)lambdaBindExpr->mCommas.size(); commaIdx++)
  12892. {
  12893. auto commaNode = lambdaBindExpr->mCommas[commaIdx];
  12894. if ((commaNode != NULL) && (cursorIdx >= commaNode->GetSrcStart()))
  12895. paramIdx = commaIdx + 1;
  12896. }
  12897. bool isEmpty = true;
  12898. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  12899. {
  12900. auto paramNode = lambdaBindExpr->mParams[paramIdx];
  12901. if (paramNode != NULL)
  12902. isEmpty = false;
  12903. }
  12904. if (isEmpty)
  12905. {
  12906. if (paramIdx < (int)invokeMethodInstance->GetParamCount())
  12907. {
  12908. String paramName = invokeMethodInstance->GetParamName(paramIdx);
  12909. autoComplete->mEntriesSet.Clear();
  12910. if (paramName.IsEmpty())
  12911. paramName += StrFormat("val%d", paramIdx + 1);
  12912. autoComplete->AddEntry(AutoCompleteEntry("paramName", paramName));
  12913. autoComplete->mInsertStartIdx = cursorIdx;
  12914. autoComplete->mInsertEndIdx = cursorIdx;
  12915. if ((paramIdx == 0) && (lambdaBindExpr->mParams.IsEmpty()))
  12916. {
  12917. String totalNames;
  12918. for (int checkIdx = 0; checkIdx < (int)invokeMethodInstance->GetParamCount(); checkIdx++)
  12919. {
  12920. if (!totalNames.IsEmpty())
  12921. totalNames += ", ";
  12922. String paramName = invokeMethodInstance->GetParamName(checkIdx);
  12923. if (paramName.IsEmpty())
  12924. paramName += StrFormat("val%d", checkIdx + 1);
  12925. totalNames += paramName;
  12926. }
  12927. autoComplete->AddEntry(AutoCompleteEntry("paramNames", totalNames));
  12928. }
  12929. }
  12930. }
  12931. }
  12932. }
  12933. }
  12934. defer
  12935. (
  12936. {
  12937. if (autoComplete != NULL)
  12938. autoComplete->mIsCapturingMethodMatchInfo = (wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo != NULL);
  12939. }
  12940. );
  12941. if (lambdaBindExpr->mBody == NULL)
  12942. {
  12943. mModule->AssertErrorState();
  12944. return NULL;
  12945. }
  12946. if ((lambdaBindExpr->mNewToken == NULL) && (isInferReturnType))
  12947. {
  12948. // Method ref, but let this follow infer route
  12949. }
  12950. else if ((lambdaBindExpr->mNewToken == NULL) || (isFunctionBind))
  12951. {
  12952. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  12953. {
  12954. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  12955. VisitLambdaBodies(lambdaBindExpr->mBody, lambdaBindExpr->mDtor);
  12956. }
  12957. if ((lambdaBindExpr->mNewToken != NULL) && (isFunctionBind))
  12958. mModule->Fail("Binds to functions should do not require allocations.", lambdaBindExpr->mNewToken);
  12959. if (lambdaBindExpr->mDtor != NULL)
  12960. {
  12961. mModule->Fail("Valueless method reference cannot contain destructor. Consider either removing destructor or using an allocated lambda.", lambdaBindExpr->mDtor->mTildeToken);
  12962. // Eat it
  12963. auto fieldDtor = lambdaBindExpr->mDtor;
  12964. while (fieldDtor != NULL)
  12965. {
  12966. mModule->VisitEmbeddedStatement(fieldDtor->mBody);
  12967. fieldDtor = fieldDtor->mNextFieldDtor;
  12968. }
  12969. }
  12970. if (invokeMethodInstance != NULL)
  12971. {
  12972. BfLocalMethod* localMethod = new BfLocalMethod();
  12973. localMethod->mMethodName = "anon";
  12974. localMethod->mSystem = mModule->mSystem;
  12975. localMethod->mModule = mModule;
  12976. localMethod->mExpectedFullName = mModule->GetLocalMethodName(localMethod->mMethodName, lambdaBindExpr->mFatArrowToken, mModule->mCurMethodState, mModule->mCurMethodState->mMixinState);
  12977. localMethod->mLambdaInvokeMethodInstance = invokeMethodInstance;
  12978. localMethod->mLambdaBindExpr = lambdaBindExpr;
  12979. localMethod->mDeclMethodState = mModule->mCurMethodState;
  12980. mModule->mContext->mLocalMethodGraveyard.push_back(localMethod);
  12981. auto moduleMethodInstance = mModule->GetLocalMethodInstance(localMethod, BfTypeVector());
  12982. if (moduleMethodInstance.mMethodInstance->mDisallowCalling)
  12983. {
  12984. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  12985. return NULL;
  12986. }
  12987. auto methodRefType = mModule->CreateMethodRefType(moduleMethodInstance.mMethodInstance);
  12988. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12989. mModule->AddCallDependency(moduleMethodInstance.mMethodInstance);
  12990. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  12991. return NULL;
  12992. }
  12993. }
  12994. //SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites);
  12995. SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites || mModule->mCurMethodInstance->mIsUnspecialized);
  12996. BfTypeInstance* outerClosure = NULL;
  12997. if ((mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  12998. outerClosure = mModule->mCurMethodState->mClosureState->mClosureType;
  12999. Val128 val128(delegateTypeInstance->mTypeId);
  13000. bool isConstEval = ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  13001. BfMethodState methodState;
  13002. methodState.mPrevMethodState = mModule->mCurMethodState;
  13003. BfIRFunctionType funcType;
  13004. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  13005. SizedArray<BfIRType, 0> paramTypes;
  13006. funcType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), paramTypes, false);
  13007. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  13008. BF_ASSERT(prevInsertBlock || isConstEval);
  13009. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  13010. mModule->mBfIRBuilder->SaveDebugLocation();
  13011. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  13012. BfDeferredLocalAssignData deferredLocalAssignData;
  13013. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  13014. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData);
  13015. SetAndRestoreValue<BfMethodState*> prevMethodState(mModule->mCurMethodState, &methodState);
  13016. methodState.mIRHeadBlock = mModule->mBfIRBuilder->CreateBlock("head", true);
  13017. methodState.mIRInitBlock = mModule->mBfIRBuilder->CreateBlock("init", true);
  13018. methodState.mIREntryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  13019. methodState.mCurScope->mDIScope = prevMethodState.mPrevVal->mCurScope->mDIScope;//invokeMethodInstance->mDIFunction;
  13020. methodState.mCurLocalVarId = -1;
  13021. methodState.mIRFunction = prevMethodState.mPrevVal->mIRFunction;
  13022. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  13023. mModule->mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  13024. BfClosureState closureState;
  13025. if (delegateTypeInstance->IsDelegate())
  13026. closureState.mReturnType = mModule->GetDelegateReturnType(delegateTypeInstance);
  13027. else
  13028. closureState.mReturnType = mModule->mContext->mBfObjectType;
  13029. closureState.mCapturing = true;
  13030. if (delegateTypeInstance->IsDelegate())
  13031. closureState.mDelegateType = delegateTypeInstance;
  13032. closureState.mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  13033. methodState.mClosureState = &closureState;
  13034. closureState.mClosureType = outerClosure;
  13035. BF_ASSERT(methodState.mCurLocalVarId == -1);
  13036. int outerLocalsCount = (int)methodState.mLocals.size();
  13037. // static int sItrCount = 0;
  13038. // ++sItrCount;
  13039. // int itrCount = sItrCount;
  13040. // if ((itrCount == 8) || (itrCount == 10))
  13041. // {
  13042. // NOP;
  13043. // }
  13044. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  13045. HashContext hashCtx;
  13046. hashCtx.MixinStr(delegateTypeName);
  13047. BfSource* bfSource = delegateTypeInstance->mTypeDef->mSource;
  13048. BfMethodDef* methodDef = new BfMethodDef();
  13049. methodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  13050. Val128 closureMethodHash;
  13051. OwnedVector<BfParameterDeclaration> tempParamDecls;
  13052. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(lambdaBindExpr->mBody)))
  13053. {
  13054. // Don't show outer method match info when our cursor is inside a lambda expression (being passed as a parameter)
  13055. autoComplete->RemoveMethodMatchInfo();
  13056. }
  13057. if (invokeMethodInstance != NULL)
  13058. {
  13059. for (int paramIdx = 0; paramIdx < (int)invokeMethodInstance->GetParamCount(); paramIdx++)
  13060. {
  13061. BfLocalVariable* localVar = new BfLocalVariable();
  13062. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  13063. {
  13064. localVar->mName = lambdaBindExpr->mParams[paramIdx]->ToString();
  13065. localVar->mNameNode = lambdaBindExpr->mParams[paramIdx];
  13066. }
  13067. else
  13068. {
  13069. mModule->AssertErrorState();
  13070. localVar->mName = invokeMethodInstance->GetParamName(paramIdx);
  13071. }
  13072. localVar->mResolvedType = invokeMethodInstance->GetParamType(paramIdx);
  13073. mModule->PopulateType(localVar->mResolvedType);
  13074. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  13075. localVar->mReadFromId = 0;
  13076. auto rootMethodState = methodState.GetRootMethodState();
  13077. localVar->mLocalVarId = rootMethodState->mCurLocalVarId++;
  13078. mModule->DoAddLocalVariable(localVar);
  13079. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  13080. if (resolvePassData != NULL)
  13081. resolvePassData->HandleLocalReference(BfNodeDynCast<BfIdentifierNode>(localVar->mNameNode), mModule->mCurTypeInstance->mTypeDef,
  13082. mModule->mCurMethodInstance->mMethodDef, localVar->mLocalVarId);
  13083. }
  13084. for (int paramIdx = 0; paramIdx < (int)invokeMethodInstance->mMethodDef->mParams.size(); paramIdx++)
  13085. {
  13086. auto invokeParamDef = invokeMethodInstance->mMethodDef->mParams[paramIdx];
  13087. BfParameterDef* paramDef = new BfParameterDef();
  13088. paramDef->mParamDeclaration = tempParamDecls.Alloc();
  13089. BfAstNode::Zero(paramDef->mParamDeclaration);
  13090. paramDef->mTypeRef = invokeParamDef->mTypeRef;
  13091. paramDef->mParamKind = invokeParamDef->mParamKind;
  13092. if ((paramIdx < (int)lambdaBindExpr->mParams.size()) && (invokeMethodInstance->GetParamKind(paramIdx) != BfParamKind_DelegateParam))
  13093. {
  13094. //TODO: Not always correct if we have a 'params'
  13095. paramDef->mParamDeclaration->mNameNode = lambdaBindExpr->mParams[paramIdx];
  13096. paramDef->mName = paramDef->mParamDeclaration->mNameNode->ToString();
  13097. }
  13098. else
  13099. {
  13100. paramDef->mParamDeclaration->mNameNode = NULL;
  13101. paramDef->mName = invokeParamDef->mName;
  13102. }
  13103. methodDef->mParams.push_back(paramDef);
  13104. if (autoComplete != NULL)
  13105. autoComplete->CheckLocalDef(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), methodState.mLocals.back());
  13106. }
  13107. }
  13108. bool isAutocomplete = mModule->mCompiler->IsAutocomplete();
  13109. methodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  13110. methodDef->mBody = lambdaBindExpr->mBody;
  13111. ///
  13112. auto varMethodState = methodState.mPrevMethodState;
  13113. bool hasExplicitCaptureNames = false;
  13114. for (auto& captureEntry : allocTarget.mCaptureInfo->mCaptures)
  13115. {
  13116. if (captureEntry.mNameNode == NULL)
  13117. {
  13118. hasExplicitCaptureNames = false;
  13119. break;
  13120. }
  13121. hasExplicitCaptureNames = true;
  13122. }
  13123. auto _SetNotCapturedFlag = [&](bool notCaptured)
  13124. {
  13125. auto varMethodState = methodState.mPrevMethodState;
  13126. while (varMethodState != NULL)
  13127. {
  13128. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  13129. {
  13130. auto localVar = varMethodState->mLocals[localIdx];
  13131. localVar->mNotCaptured = notCaptured;
  13132. }
  13133. varMethodState = varMethodState->mPrevMethodState;
  13134. if (varMethodState == NULL)
  13135. break;
  13136. if (varMethodState->mMixinState != NULL)
  13137. break;
  13138. if (varMethodState->mClosureState != NULL)
  13139. {
  13140. if (!varMethodState->mClosureState->mCapturing)
  13141. break;
  13142. }
  13143. }
  13144. };
  13145. if (hasExplicitCaptureNames)
  13146. {
  13147. _SetNotCapturedFlag(true);
  13148. auto varMethodState = methodState.mPrevMethodState;
  13149. while (varMethodState != NULL)
  13150. {
  13151. for (auto& captureEntry : allocTarget.mCaptureInfo->mCaptures)
  13152. {
  13153. if (captureEntry.mNameNode != NULL)
  13154. {
  13155. StringT<64> captureName;
  13156. captureEntry.mNameNode->ToString(captureName);
  13157. BfLocalVarEntry* entry;
  13158. if (varMethodState->mLocalVarSet.TryGetWith<StringImpl&>(captureName, &entry))
  13159. {
  13160. auto localVar = entry->mLocalVar;
  13161. while (localVar != NULL)
  13162. {
  13163. if (autoComplete != NULL)
  13164. autoComplete->CheckLocalRef(captureEntry.mNameNode, localVar);
  13165. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  13166. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL))
  13167. {
  13168. if (auto captureIdentifierNode = BfNodeDynCast<BfIdentifierNode>(captureEntry.mNameNode))
  13169. mModule->mCompiler->mResolvePassData->HandleLocalReference(captureIdentifierNode, localVar->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVar->mLocalVarId);
  13170. }
  13171. localVar->mNotCaptured = false;
  13172. localVar = localVar->mShadowedLocal;
  13173. }
  13174. }
  13175. }
  13176. }
  13177. varMethodState = varMethodState->mPrevMethodState;
  13178. if (varMethodState == NULL)
  13179. break;
  13180. if (varMethodState->mMixinState != NULL)
  13181. break;
  13182. if (varMethodState->mClosureState != NULL)
  13183. {
  13184. if (!varMethodState->mClosureState->mCapturing)
  13185. break;
  13186. }
  13187. }
  13188. }
  13189. BfClosureInstanceInfo* closureInstanceInfo = new BfClosureInstanceInfo();
  13190. auto checkInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  13191. closureState.mCaptureStartAccessId = methodState.mPrevMethodState->GetRootMethodState()->mCurAccessId;
  13192. closureState.mCaptureVisitingBody = true;
  13193. closureState.mClosureInstanceInfo = closureInstanceInfo;
  13194. if ((mBfEvalExprFlags & BfEvalExprFlags_InferReturnType) != 0)
  13195. {
  13196. closureState.mReturnType = NULL;
  13197. closureState.mReturnTypeInferState = BfReturnTypeInferState_Inferring;
  13198. }
  13199. VisitLambdaBodies(lambdaBindExpr->mBody, lambdaBindExpr->mDtor);
  13200. if (hasExplicitCaptureNames)
  13201. _SetNotCapturedFlag(false);
  13202. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  13203. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  13204. {
  13205. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  13206. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  13207. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  13208. }
  13209. bool earlyExit = false;
  13210. if (isInferReturnType)
  13211. {
  13212. if ((closureState.mReturnTypeInferState == BfReturnTypeInferState_Fail) ||
  13213. (closureState.mReturnType == NULL))
  13214. {
  13215. mResult = BfTypedValue();
  13216. }
  13217. else
  13218. {
  13219. mResult = BfTypedValue(closureState.mReturnType);
  13220. }
  13221. earlyExit = true;
  13222. }
  13223. else if (mModule->mCurMethodInstance->mIsUnspecialized)
  13224. {
  13225. earlyExit = true;
  13226. mResult = mModule->GetDefaultTypedValue(delegateTypeInstance);
  13227. }
  13228. if (earlyExit)
  13229. {
  13230. prevIgnoreWrites.Restore();
  13231. mModule->mBfIRBuilder->RestoreDebugLocation();
  13232. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  13233. if (!prevInsertBlock.IsFake())
  13234. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  13235. delete methodDef;
  13236. delete closureInstanceInfo;
  13237. return NULL;
  13238. }
  13239. closureState.mCaptureVisitingBody = false;
  13240. prevIgnoreWrites.Restore();
  13241. mModule->mBfIRBuilder->RestoreDebugLocation();
  13242. auto _GetCaptureType = [&](const StringImpl& str, BfCaptureInfo::Entry** captureInfo = NULL)
  13243. {
  13244. if (allocTarget.mCaptureInfo->mCaptures.IsEmpty())
  13245. return BfCaptureType_Copy;
  13246. for (auto& captureEntry : allocTarget.mCaptureInfo->mCaptures)
  13247. {
  13248. if ((captureEntry.mNameNode == NULL) || (captureEntry.mNameNode->Equals(str)))
  13249. {
  13250. if (captureInfo != NULL)
  13251. *captureInfo = &captureEntry;
  13252. captureEntry.mUsed = true;
  13253. return captureEntry.mCaptureType;
  13254. }
  13255. }
  13256. return BfCaptureType_None;
  13257. };
  13258. Array<BfClosureCapturedEntry> capturedEntries;
  13259. bool copyOuterCaptures = false;
  13260. //
  13261. {
  13262. auto varMethodState = methodState.mPrevMethodState;
  13263. while (varMethodState != NULL)
  13264. {
  13265. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  13266. {
  13267. auto localVar = varMethodState->mLocals[localIdx];
  13268. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  13269. {
  13270. if ((localVar->mIsThis) && (outerClosure != NULL))
  13271. {
  13272. continue;
  13273. }
  13274. auto outerLocal = localVar;
  13275. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  13276. {
  13277. closureState.mConstLocals.push_back(*outerLocal);
  13278. continue;
  13279. }
  13280. BfClosureCapturedEntry capturedEntry;
  13281. auto capturedType = outerLocal->mResolvedType;
  13282. bool captureByRef = false;
  13283. BfCaptureInfo::Entry* captureInfoEntry = NULL;
  13284. auto captureType = _GetCaptureType(localVar->mName, &captureInfoEntry);
  13285. if (captureType == BfCaptureType_None)
  13286. {
  13287. continue;
  13288. }
  13289. if (!capturedType->IsRef())
  13290. {
  13291. if (captureType == BfCaptureType_Reference)
  13292. {
  13293. if ((localVar->mIsThis) && (!localVar->mResolvedType->IsValueType()))
  13294. {
  13295. // Just ignore attempting to capture referencetype 'this' by reference
  13296. }
  13297. else
  13298. captureByRef = true;
  13299. }
  13300. else if (captureType == BfCaptureType_Auto)
  13301. {
  13302. if (localVar->mWrittenToId >= closureState.mCaptureStartAccessId)
  13303. captureByRef = true;
  13304. else if ((outerLocal->mResolvedType->mSize > 8) ||
  13305. ((localVar->mIsThis) && (outerLocal->mResolvedType->IsValueType())))
  13306. {
  13307. // Capture "large" values by reference
  13308. captureByRef = true;
  13309. }
  13310. }
  13311. }
  13312. else
  13313. {
  13314. bool allowRef = false;
  13315. if (captureType == BfCaptureType_Reference)
  13316. allowRef = true;
  13317. else if (captureType == BfCaptureType_Auto)
  13318. allowRef = localVar->mWrittenToId < closureState.mCaptureStartAccessId;
  13319. if (!allowRef)
  13320. {
  13321. capturedType = ((BfRefType*)capturedType)->mElementType;
  13322. }
  13323. }
  13324. if (captureByRef)
  13325. {
  13326. capturedType = mModule->CreateRefType(capturedType);
  13327. }
  13328. if (captureType != BfCaptureType_Copy)
  13329. capturedEntry.mExplicitlyByReference = true;
  13330. capturedEntry.mType = capturedType;
  13331. capturedEntry.mNameNode = outerLocal->mNameNode;
  13332. if (outerLocal->mName == "this")
  13333. capturedEntry.mName = "__this";
  13334. else
  13335. {
  13336. capturedEntry.mName = outerLocal->mName;
  13337. BfLocalVarEntry* entry = NULL;
  13338. if (varMethodState->mLocalVarSet.TryGetWith<StringImpl&>(capturedEntry.mName, &entry))
  13339. {
  13340. auto startCheckVar = entry->mLocalVar;
  13341. int shadowIdx = 0;
  13342. auto checkVar = startCheckVar;
  13343. while (checkVar != NULL)
  13344. {
  13345. if (checkVar == outerLocal)
  13346. {
  13347. // We only use mShadowIdx when we have duplicate name nodes (ie: in the case of for looks with iterator vs value)
  13348. auto shadowCheckVar = startCheckVar;
  13349. while (shadowCheckVar != checkVar)
  13350. {
  13351. if (shadowCheckVar->mNameNode == checkVar->mNameNode)
  13352. capturedEntry.mShadowIdx++;
  13353. shadowCheckVar = shadowCheckVar->mShadowedLocal;
  13354. }
  13355. for (int i = 0; i < shadowIdx; i++)
  13356. capturedEntry.mName.Insert(0, '@');
  13357. break;
  13358. }
  13359. shadowIdx++;
  13360. checkVar = checkVar->mShadowedLocal;
  13361. }
  13362. }
  13363. }
  13364. capturedEntries.Add(capturedEntry);
  13365. }
  13366. }
  13367. varMethodState = varMethodState->mPrevMethodState;
  13368. if (varMethodState == NULL)
  13369. break;
  13370. if (varMethodState->mMixinState != NULL)
  13371. break;
  13372. if (varMethodState->mClosureState != NULL)
  13373. {
  13374. if (!varMethodState->mClosureState->mCapturing)
  13375. break;
  13376. }
  13377. }
  13378. }
  13379. for (auto& captureEntry : allocTarget.mCaptureInfo->mCaptures)
  13380. {
  13381. if ((!captureEntry.mUsed) && (captureEntry.mNameNode != NULL))
  13382. mModule->Warn(0, "Capture specifier not used", captureEntry.mNameNode);
  13383. }
  13384. for (auto copyField : closureState.mReferencedOuterClosureMembers)
  13385. {
  13386. auto fieldDef = copyField->GetFieldDef();
  13387. auto captureType = _GetCaptureType(fieldDef->mName);
  13388. BfClosureCapturedEntry capturedEntry;
  13389. capturedEntry.mName = fieldDef->mName;
  13390. capturedEntry.mType = copyField->mResolvedType;
  13391. if ((captureType != BfCaptureType_Copy) && (capturedEntry.mType->IsRef()))
  13392. {
  13393. capturedEntry.mExplicitlyByReference = true;
  13394. }
  13395. else if ((captureType == BfCaptureType_Copy) && (capturedEntry.mType->IsRef()))
  13396. {
  13397. auto refType = (BfRefType*)capturedEntry.mType;
  13398. capturedEntry.mType = refType->mElementType;
  13399. }
  13400. else if ((captureType != BfCaptureType_Copy) && (!capturedEntry.mType->IsRef()) && (!fieldDef->mIsReadOnly))
  13401. {
  13402. capturedEntry.mType = mModule->CreateRefType(capturedEntry.mType);
  13403. }
  13404. }
  13405. std::sort(capturedEntries.begin(), capturedEntries.end());
  13406. bool hasCapture = false;
  13407. BfMethodInstanceGroup methodInstanceGroup;
  13408. methodInstanceGroup.mOwner = mModule->mCurTypeInstance;
  13409. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  13410. BfMethodInstance* methodInstance = new BfMethodInstance();
  13411. methodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13412. methodInstance->GetMethodInfoEx()->mClosureInstanceInfo = closureInstanceInfo;
  13413. if (invokeMethodInstance != NULL)
  13414. methodInstance->mParams = invokeMethodInstance->mParams;
  13415. methodInstance->mIsClosure = true;
  13416. // We want the closure ID to match between hot reloads -- otherwise we wouldn't be able to modify them,
  13417. // so we use the charId from the 'fat arrow' token
  13418. int closureId = 0;
  13419. if (lambdaBindExpr->mFatArrowToken != NULL)
  13420. closureId = lambdaBindExpr->mFatArrowToken->GetStartCharId();
  13421. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  13422. BF_ASSERT(curProject != NULL);
  13423. // We need to make these per-project even though you'd think we might not because we
  13424. // insert generic type specializations in the generic definition's project,
  13425. // BECAUSE: we would need to scan the captured fields the same way we scan the
  13426. // generic arguments to determine if each project can see it or not in the vdata
  13427. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  13428. BfClosureType* closureTypeInst = NULL;
  13429. // 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
  13430. if ((capturedEntries.size() != 0) || (lambdaBindExpr->mDtor != NULL) || (copyOuterCaptures) || (mModule->mCompiler->mOptions.mAllowHotSwapping) || (closureState.mCapturedDelegateSelf))
  13431. {
  13432. hashCtx.MixinStr(curProject->mName);
  13433. if (copyOuterCaptures)
  13434. {
  13435. hashCtx.Mixin(outerClosure->mTypeId);
  13436. }
  13437. for (auto& capturedEntry : capturedEntries)
  13438. {
  13439. hashCtx.Mixin(capturedEntry.mType->mTypeId);
  13440. hashCtx.MixinStr(capturedEntry.mName);
  13441. hashCtx.Mixin(capturedEntry.mExplicitlyByReference);
  13442. }
  13443. if (lambdaBindExpr->mDtor != NULL)
  13444. {
  13445. // Has DTOR thunk
  13446. bool hasDtorThunk = true;
  13447. hashCtx.Mixin(hasDtorThunk);
  13448. }
  13449. Val128 hash128 = hashCtx.Finish128();
  13450. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  13451. checkClosureType->mContext = mModule->mContext;
  13452. checkClosureType->mBaseType = delegateTypeInstance;
  13453. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_TypeDef);
  13454. closureTypeInst = (BfClosureType*)resolvedClosureType;
  13455. if (checkClosureType == resolvedClosureType)
  13456. {
  13457. // This is a new closure type
  13458. closureTypeInst->Init(curProject);
  13459. closureTypeInst->mTypeDef->mProject = curProject;
  13460. auto delegateDirectTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeDefReference>();
  13461. delegateDirectTypeRef->Init(mModule->mCompiler->mDelegateTypeDef);
  13462. closureTypeInst->mDirectAllocNodes.push_back(delegateDirectTypeRef);
  13463. BfMethodDef* methodDef = BfDefBuilder::AddMethod(closureTypeInst->mTypeDef, BfMethodType_Normal, BfProtection_Public, false, "Equals");
  13464. methodDef->mReturnTypeRef = mModule->mSystem->mDirectBoolTypeRef;
  13465. BfDefBuilder::AddParam(methodDef, delegateDirectTypeRef, "val");
  13466. methodDef->mIsVirtual = true;
  13467. methodDef->mIsOverride = true;
  13468. if (copyOuterCaptures)
  13469. {
  13470. for (auto& fieldInstance : outerClosure->mFieldInstances)
  13471. {
  13472. BfFieldDef* origFieldDef = fieldInstance.GetFieldDef();
  13473. BfFieldDef* fieldDef = closureTypeInst->AddField(fieldInstance.mResolvedType, origFieldDef->mName);
  13474. fieldDef->mIsReadOnly = origFieldDef->mIsReadOnly;
  13475. }
  13476. }
  13477. for (auto& capturedEntry : capturedEntries)
  13478. {
  13479. BfFieldDef* fieldDef = closureTypeInst->AddField(capturedEntry.mType, capturedEntry.mName);
  13480. if (!capturedEntry.mExplicitlyByReference)
  13481. fieldDef->mIsReadOnly = true;
  13482. }
  13483. if (lambdaBindExpr->mDtor != NULL)
  13484. {
  13485. auto dtorDef = closureTypeInst->AddDtor();
  13486. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  13487. auto voidPtrType = mModule->CreatePointerType(voidType);
  13488. closureTypeInst->AddField(voidPtrType, "__dtorThunk");
  13489. }
  13490. closureTypeInst->Finish();
  13491. }
  13492. else
  13493. {
  13494. // Already had this entry
  13495. delete checkClosureType;
  13496. }
  13497. useTypeInstance = closureTypeInst;
  13498. }
  13499. mModule->mBfIRBuilder->PopulateType(useTypeInstance);
  13500. mModule->PopulateType(useTypeInstance);
  13501. methodDef->mIsStatic = closureTypeInst == NULL;
  13502. SizedArray<BfIRType, 8> origParamTypes;
  13503. BfIRType origReturnType;
  13504. bool forceStatic = false;
  13505. if (invokeMethodInstance != NULL)
  13506. {
  13507. forceStatic = methodDef->mIsStatic;
  13508. auto invokeFunctionType = mModule->mBfIRBuilder->MapMethod(invokeMethodInstance);
  13509. invokeMethodInstance->GetIRFunctionInfo(mModule, origReturnType, origParamTypes, forceStatic);
  13510. }
  13511. else
  13512. {
  13513. origReturnType = mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_None));
  13514. }
  13515. SizedArray<BfIRType, 3> newTypes;
  13516. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) == 0))
  13517. newTypes.push_back(origParamTypes[0]);
  13518. if (!methodDef->mIsStatic)
  13519. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  13520. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) == 1))
  13521. newTypes.push_back(origParamTypes[1]);
  13522. int paramStartIdx = 0;
  13523. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) != -1))
  13524. paramStartIdx++;
  13525. if (!methodDef->mIsStatic)
  13526. paramStartIdx++;
  13527. for (int i = paramStartIdx; i < (int)origParamTypes.size(); i++)
  13528. newTypes.push_back(origParamTypes[i]);
  13529. auto closureFuncType = mModule->mBfIRBuilder->CreateFunctionType(origReturnType, newTypes, false);
  13530. prevMethodState.Restore();
  13531. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  13532. if ((prevInsertBlock) && (!prevInsertBlock.IsFake()))
  13533. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  13534. // Just a check
  13535. mModule->mBfIRBuilder->GetInsertBlock();
  13536. //auto rootMethodState = mModule->mCurMethodState;
  13537. HashContext closureHashCtx;
  13538. closureHashCtx.Mixin(closureId);
  13539. // When we're a nested lambda, strip off the outer hash and closureTypeInst markers
  13540. methodDef->mName = mModule->mCurMethodInstance->mMethodDef->mName;
  13541. int prevSepPos = (int)methodDef->mName.LastIndexOf('$');
  13542. if (prevSepPos != -1)
  13543. {
  13544. closureHashCtx.Mixin(methodDef->mName.c_str() + prevSepPos, (int)methodDef->mName.length() - prevSepPos);
  13545. methodDef->mName.RemoveToEnd(prevSepPos);
  13546. }
  13547. // Mix in this because this can be emitted multiple times when there's multiple ctors and field initializers with lambdas
  13548. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  13549. {
  13550. if (auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration))
  13551. {
  13552. if (ctorDecl->mThisToken != NULL)
  13553. closureHashCtx.Mixin(ctorDecl->mThisToken->GetStartCharId());
  13554. }
  13555. }
  13556. auto checkMethodState = mModule->mCurMethodState;
  13557. while (checkMethodState != NULL)
  13558. {
  13559. if (checkMethodState->mMethodInstance != NULL)
  13560. {
  13561. if (checkMethodState->mMethodInstance->mMethodInfoEx != NULL)
  13562. {
  13563. for (auto methodGenericArg : checkMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  13564. {
  13565. StringT<128> genericTypeName;
  13566. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  13567. closureHashCtx.MixinStr(genericTypeName);
  13568. }
  13569. }
  13570. }
  13571. checkMethodState = checkMethodState->mPrevMethodState;
  13572. }
  13573. uint64 closureHash = closureHashCtx.Finish64();
  13574. methodDef->mName += "$";
  13575. methodDef->mName += BfTypeUtils::HashEncode64(closureHash);
  13576. methodInstance->mMethodDef = methodDef;
  13577. if (invokeMethodInstance != NULL)
  13578. {
  13579. methodInstance->mParams = invokeMethodInstance->mParams;
  13580. methodInstance->mReturnType = invokeMethodInstance->mReturnType;
  13581. }
  13582. else
  13583. methodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  13584. StringT<128> closureFuncName;
  13585. BfMangler::Mangle(closureFuncName, mModule->mCompiler->GetMangleKind(), methodInstance);
  13586. auto closureFunc = mModule->mBfIRBuilder->CreateFunction(closureFuncType, BfIRLinkageType_External, closureFuncName);
  13587. methodInstance->mIRFunction = closureFunc;
  13588. if (methodInstance->mIsReified)
  13589. mModule->CheckHotMethod(methodInstance, closureFuncName);
  13590. if ((methodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  13591. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(methodInstance->mHotMethod);
  13592. methodState.Reset();
  13593. lambdaInstance = new BfLambdaInstance();
  13594. rootMethodState->mLambdaCache[cacheNodeList] = lambdaInstance;
  13595. lambdaInstance->mDelegateTypeInstance = delegateTypeInstance;
  13596. lambdaInstance->mUseTypeInstance = useTypeInstance;
  13597. lambdaInstance->mClosureTypeInstance = closureTypeInst;
  13598. lambdaInstance->mOuterClosure = outerClosure;
  13599. lambdaInstance->mCopyOuterCaptures = copyOuterCaptures;
  13600. lambdaInstance->mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  13601. lambdaInstance->mIsStatic = methodDef->mIsStatic;
  13602. lambdaInstance->mClosureFunc = closureFunc;
  13603. lambdaInstance->mMethodInstance = methodInstance;
  13604. lambdaInstance->mConstLocals = closureState.mConstLocals;
  13605. lambdaInstance->mParamDecls = tempParamDecls;
  13606. lambdaInstance->mDeclMixinState = mModule->mCurMethodState->mMixinState;
  13607. if (lambdaInstance->mDeclMixinState != NULL)
  13608. lambdaInstance->mDeclMixinState->mHasDeferredUsage = true;
  13609. tempParamDecls.ClearWithoutDeleting();
  13610. closureState.mCapturing = false;
  13611. closureState.mClosureType = useTypeInstance;
  13612. closureInstanceInfo->mThisOverride = useTypeInstance;
  13613. mModule->mIncompleteMethodCount++;
  13614. SetAndRestoreValue<BfClosureState*> prevClosureState(mModule->mCurMethodState->mClosureState, &closureState);
  13615. if (mModule->HasExecutedOutput())
  13616. mModule->SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  13617. // This keeps us from giving errors twice. ProcessMethod can give errors when we capture by value but needed to
  13618. // capture by reference, so we still need to do it for resolve-only
  13619. bool processMethods = (mModule->mCompiler->GetAutoComplete() == NULL) && !mModule->mHadBuildError;
  13620. mModule->mBfIRBuilder->SaveDebugLocation();
  13621. //
  13622. {
  13623. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  13624. if (mModule->mCompiler->mResolvePassData != NULL)
  13625. {
  13626. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  13627. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  13628. }
  13629. if (processMethods)
  13630. {
  13631. // If we are in an always-ignored block, we will have mIgnoreWrites set
  13632. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  13633. // mModule->ProcessMethod(methodInstance);
  13634. }
  13635. if (mModule->mCompiler->mResolvePassData != NULL)
  13636. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  13637. }
  13638. mModule->mBfIRBuilder->RestoreDebugLocation();
  13639. if (mModule->IsSkippingExtraResolveChecks())
  13640. closureFunc = BfIRFunction();
  13641. BfIRFunction dtorFunc;
  13642. if (lambdaBindExpr->mDtor != NULL)
  13643. {
  13644. SizedArray<BfIRType, 1> newTypes;
  13645. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  13646. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  13647. auto dtorFuncType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), newTypes, false);
  13648. BfMethodDef* dtorMethodDef = new BfMethodDef();
  13649. dtorMethodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  13650. dtorMethodDef->mName = "~this$";
  13651. dtorMethodDef->mName += methodDef->mName;
  13652. dtorMethodDef->mMethodType = BfMethodType_Normal;
  13653. dtorMethodDef->mBody = lambdaBindExpr->mDtor;
  13654. dtorMethodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  13655. BfMethodInstance* dtorMethodInstance = new BfMethodInstance();
  13656. dtorMethodInstance->mMethodDef = dtorMethodDef;
  13657. dtorMethodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  13658. dtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13659. StringT<128> dtorMangledName;
  13660. BfMangler::Mangle(dtorMangledName, mModule->mCompiler->GetMangleKind(), dtorMethodInstance);
  13661. dtorFunc = mModule->mBfIRBuilder->CreateFunction(dtorFuncType, BfIRLinkageType_External, dtorMangledName);
  13662. mModule->SetupIRMethod(NULL, dtorFunc, false);
  13663. dtorMethodInstance->mIRFunction = dtorFunc;
  13664. mModule->mIncompleteMethodCount++;
  13665. mModule->mBfIRBuilder->SaveDebugLocation();
  13666. //
  13667. if (processMethods)
  13668. {
  13669. // If we are in an always-ignored block, we will have mIgnoreWrites set
  13670. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  13671. // mModule->ProcessMethod(dtorMethodInstance);
  13672. }
  13673. mModule->mBfIRBuilder->RestoreDebugLocation();
  13674. if (mModule->IsSkippingExtraResolveChecks())
  13675. dtorFunc = BfIRFunction();
  13676. if (dtorMethodInstance->mIsReified)
  13677. mModule->CheckHotMethod(dtorMethodInstance, dtorMangledName);
  13678. if ((dtorMethodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  13679. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(dtorMethodInstance->mHotMethod);
  13680. lambdaInstance->mDtorMethodInstance = dtorMethodInstance;
  13681. lambdaInstance->mDtorFunc = dtorFunc;
  13682. dtorMethodInstance->mMethodInstanceGroup = NULL;
  13683. }
  13684. prevClosureState.Restore();
  13685. if ((prevInsertBlock) && (!prevInsertBlock.IsFake()))
  13686. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  13687. for (auto& capturedEntry : capturedEntries)
  13688. {
  13689. BfLambdaCaptureInfo lambdaCapture;
  13690. if (capturedEntry.mName == "__this")
  13691. lambdaCapture.mName = "this";
  13692. else
  13693. lambdaCapture.mName = capturedEntry.mName;
  13694. lambdaInstance->mCaptures.Add(lambdaCapture);
  13695. closureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  13696. }
  13697. if (processMethods)
  13698. rootMethodState->mDeferredLambdaInstances.Add(lambdaInstance);
  13699. methodInstance->mMethodInstanceGroup = NULL;
  13700. return lambdaInstance;
  13701. }
  13702. void BfExprEvaluator::Visit(BfLambdaBindExpression* lambdaBindExpr)
  13703. {
  13704. BfTokenNode* newToken = NULL;
  13705. BfCaptureInfo captureInfo;
  13706. BfAllocTarget allocTarget;
  13707. allocTarget.mCaptureInfo = &captureInfo;
  13708. ResolveAllocTarget(allocTarget, lambdaBindExpr->mNewToken, newToken);
  13709. if (mModule->mCurMethodInstance == NULL)
  13710. mModule->Fail("Invalid use of lambda bind expression", lambdaBindExpr);
  13711. if (((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mBlindCapturing)) ||
  13712. (mModule->mCurMethodInstance == NULL))
  13713. {
  13714. // We're just capturing. We just need to visit the bodies here. This helps infinite recursion with local methods containing lambdas calling each other
  13715. if (lambdaBindExpr->mBody != NULL)
  13716. mModule->VisitChild(lambdaBindExpr->mBody);
  13717. if ((lambdaBindExpr->mDtor != NULL) && (lambdaBindExpr->mDtor->mBody != NULL))
  13718. mModule->VisitChild(lambdaBindExpr->mDtor->mBody);
  13719. return;
  13720. }
  13721. BfLambdaInstance* lambdaInstance = GetLambdaInstance(lambdaBindExpr, allocTarget);
  13722. if (lambdaInstance == NULL)
  13723. return;
  13724. BfTypeInstance* delegateTypeInstance = lambdaInstance->mDelegateTypeInstance;
  13725. BfTypeInstance* useTypeInstance = lambdaInstance->mUseTypeInstance;
  13726. BfTypeInstance* closureTypeInst = lambdaInstance->mClosureTypeInstance;
  13727. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  13728. if (!delegateTypeInstance->IsDelegate())
  13729. {
  13730. mModule->AssertErrorState();
  13731. return;
  13732. }
  13733. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  13734. if (baseDelegateType == NULL)
  13735. {
  13736. mModule->Fail("Invalid delegate type", lambdaBindExpr);
  13737. return;
  13738. }
  13739. mModule->PopulateType(baseDelegateType);
  13740. auto& funcPtrField = baseDelegateType->mFieldInstances[0];
  13741. auto& targetField = baseDelegateType->mFieldInstances[1];
  13742. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType));
  13743. // >> delegate.mTarget = bindResult.mTarget
  13744. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  13745. BfIRValue valPtr;
  13746. if (!lambdaInstance->mIsStatic)
  13747. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  13748. else
  13749. valPtr = mModule->GetDefaultValue(nullPtrType);
  13750. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, targetField.mDataIdx);
  13751. mModule->mBfIRBuilder->CreateAlignedStore(valPtr, fieldPtr, targetField.mResolvedType->mAlign);
  13752. // >> delegate.mFuncPtr = bindResult.mFunc
  13753. if (lambdaInstance->mClosureFunc)
  13754. {
  13755. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  13756. auto valPtr = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mClosureFunc, mModule->mBfIRBuilder->MapType(nullPtrType));
  13757. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, funcPtrField.mDataIdx);
  13758. mModule->mBfIRBuilder->CreateAlignedStore(valPtr, fieldPtr, funcPtrField.mResolvedType->mAlign);
  13759. }
  13760. mModule->AddDependency(useTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  13761. // Copy captures into the delegate
  13762. if (lambdaInstance->mClosureTypeInstance != NULL)
  13763. {
  13764. int fieldIdx = 0;
  13765. if (lambdaInstance->mCopyOuterCaptures)
  13766. {
  13767. for (auto& fieldInstance : lambdaInstance->mOuterClosure->mFieldInstances)
  13768. {
  13769. if (!fieldInstance.mResolvedType->IsValuelessType())
  13770. {
  13771. BF_ASSERT(fieldInstance.mDataIdx == fieldIdx + 1);
  13772. auto localVar = mModule->mCurMethodState->mLocals[0];
  13773. auto capturedValue = mModule->mBfIRBuilder->CreateInBoundsGEP(localVar->mValue, 0, fieldInstance.mDataIdx);
  13774. capturedValue = mModule->mBfIRBuilder->CreateAlignedLoad(capturedValue, fieldInstance.mResolvedType->mAlign);
  13775. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance.mDataIdx);
  13776. mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  13777. fieldIdx++;
  13778. }
  13779. }
  13780. }
  13781. int captureIdx = 0;
  13782. for (int captureIdx = 0; captureIdx < (int)lambdaInstance->mCaptures.size(); captureIdx++)
  13783. {
  13784. auto& capturedEntry = lambdaInstance->mCaptures[captureIdx];
  13785. auto& closureCaptureEntry = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[captureIdx];
  13786. BfIdentifierNode* identifierNode = closureCaptureEntry.mNameNode;
  13787. BfIRValue capturedValue;
  13788. auto fieldInstance = &closureTypeInst->mFieldInstances[fieldIdx];
  13789. BfTypedValue capturedTypedVal;
  13790. if (identifierNode != NULL)
  13791. capturedTypedVal = DoImplicitArgCapture(NULL, identifierNode, closureCaptureEntry.mShadowIdx);
  13792. else
  13793. capturedTypedVal = LookupIdentifier(NULL, capturedEntry.mName);
  13794. if (!fieldInstance->mResolvedType->IsRef())
  13795. capturedTypedVal = mModule->LoadOrAggregateValue(capturedTypedVal);
  13796. else if (!capturedTypedVal.IsAddr())
  13797. capturedTypedVal = mModule->MakeAddressable(capturedTypedVal, false, true);
  13798. capturedValue = capturedTypedVal.mValue;
  13799. if (capturedValue)
  13800. {
  13801. if (!IsVar(capturedTypedVal.mType))
  13802. {
  13803. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance->mDataIdx);
  13804. mModule->mBfIRBuilder->CreateAlignedStore(capturedValue, fieldPtr, fieldInstance->mResolvedType->mAlign);
  13805. }
  13806. }
  13807. else
  13808. {
  13809. mModule->Fail(StrFormat("Unable to capture '%s'", capturedEntry.mName.c_str()), lambdaBindExpr);
  13810. mModule->AssertErrorState();
  13811. }
  13812. fieldIdx++;
  13813. }
  13814. if (lambdaInstance->mDtorFunc)
  13815. {
  13816. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, closureTypeInst->mFieldInstances[fieldIdx].mDataIdx);
  13817. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  13818. auto voidPtrType = mModule->CreatePointerType(voidType);
  13819. auto dtorThunk = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mDtorFunc, mModule->mBfIRBuilder->MapType(voidPtrType));
  13820. mModule->mBfIRBuilder->CreateAlignedStore(dtorThunk, fieldPtr, mModule->mSystem->mPtrSize);
  13821. fieldIdx++;
  13822. }
  13823. }
  13824. }
  13825. void BfExprEvaluator::ProcessArrayInitializer(BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, int dimensions, SizedArrayImpl<int64>& dimLengths, int dim, bool& hasFailed)
  13826. {
  13827. bool setSize = false;
  13828. if (dim == dimLengths.size())
  13829. {
  13830. dimLengths.push_back((int)valueExprs.size());
  13831. setSize = true;
  13832. }
  13833. else if (dimLengths[dim] == -1)
  13834. {
  13835. dimLengths[dim] = (int)valueExprs.size();
  13836. setSize = true;
  13837. }
  13838. int64 initCountDiff = (int)valueExprs.size() - dimLengths[dim];
  13839. if ((dimLengths[dim] != -1) && (initCountDiff != 0) && (!hasFailed))
  13840. {
  13841. if (initCountDiff > 0)
  13842. {
  13843. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[(int)dimLengths[dim]]);
  13844. hasFailed = true;
  13845. }
  13846. else
  13847. {
  13848. // If it ends with ", ?) or ",)" then allow unsized
  13849. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  13850. (commas.size() < valueExprs.size()))
  13851. {
  13852. BfAstNode* refNode = closeToken;
  13853. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  13854. refNode = mModule->mParentNodeEntry->mNode;
  13855. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  13856. hasFailed = true;
  13857. }
  13858. }
  13859. }
  13860. for (int i = 0; i < (int)valueExprs.size(); i++)
  13861. {
  13862. BfExpression* expr = valueExprs[i];
  13863. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(expr))
  13864. {
  13865. continue;
  13866. }
  13867. auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr);
  13868. if (dim < dimensions - 1)
  13869. {
  13870. if (innerInitExpr == NULL)
  13871. {
  13872. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(expr))
  13873. {
  13874. ProcessArrayInitializer(innerTupleExpr->mOpenParen, innerTupleExpr->mValues, innerTupleExpr->mCommas, innerTupleExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  13875. }
  13876. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  13877. {
  13878. SizedArray<BfExpression*, 1> values;
  13879. values.Add(parenExpr->mExpression);
  13880. SizedArray<BfTokenNode*, 1> commas;
  13881. ProcessArrayInitializer(parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  13882. }
  13883. else
  13884. {
  13885. hasFailed = true;
  13886. mModule->Fail("A nested array initializer is expected", expr);
  13887. continue;
  13888. }
  13889. }
  13890. else
  13891. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  13892. }
  13893. else if (innerInitExpr != NULL)
  13894. {
  13895. hasFailed = true;
  13896. mModule->Fail("Unexpected nested initializer", expr);
  13897. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  13898. }
  13899. else
  13900. {
  13901. //mModule->Fail("Expected initializer", )
  13902. }
  13903. }
  13904. }
  13905. void BfExprEvaluator::CheckObjectCreateTypeRef(BfType* expectingType, BfAstNode* afterNode)
  13906. {
  13907. auto autoComplete = GetAutoComplete();
  13908. if ((autoComplete != NULL) && (afterNode != NULL) && (autoComplete->mIsAutoComplete) &&
  13909. (afterNode->IsFromParser(mModule->mCompiler->mResolvePassData->mParsers[0])) &&
  13910. (afterNode->GetParser()->mCursorIdx == afterNode->GetSrcEnd() + 1))
  13911. {
  13912. BfType* expectingType = mExpectingType;
  13913. BfTypeInstance* expectingTypeInst = NULL;
  13914. if (mExpectingType != NULL)
  13915. {
  13916. expectingTypeInst = mExpectingType->ToTypeInstance();
  13917. }
  13918. if ((mExpectingType != NULL) && (((expectingTypeInst == NULL) || (!expectingTypeInst->mTypeDef->mIsDelegate))))
  13919. {
  13920. // Why were we doing this? It floods the autocomplete with every possible type
  13921. //autoComplete->AddTopLevelTypes(NULL);
  13922. autoComplete->mInsertStartIdx = afterNode->GetSourceData()->ToParser()->mCursorIdx;
  13923. BF_ASSERT(autoComplete->mInsertStartIdx != -1);
  13924. auto expectingType = mExpectingType;
  13925. while (expectingType->IsArray())
  13926. {
  13927. auto arrayType = (BfArrayType*)expectingType;
  13928. expectingType = arrayType->mGenericTypeInfo->mTypeGenericArguments[0];
  13929. }
  13930. auto expectingTypeInst = expectingType->ToTypeInstance();
  13931. if (expectingTypeInst != NULL)
  13932. {
  13933. if (!expectingTypeInst->IsAnonymous())
  13934. autoComplete->AddTypeInstanceEntry(expectingTypeInst);
  13935. }
  13936. else
  13937. autoComplete->mDefaultSelection = mModule->TypeToString(expectingType);
  13938. }
  13939. }
  13940. }
  13941. void BfExprEvaluator::Visit(BfObjectCreateExpression* objCreateExpr)
  13942. {
  13943. CreateObject(objCreateExpr, objCreateExpr->mNewNode, NULL, NULL);
  13944. }
  13945. void BfExprEvaluator::CreateObject(BfObjectCreateExpression* objCreateExpr, BfAstNode* allocNode, BfType* wantAllocType, BfInlineTypeReference* inlineTypeRef)
  13946. {
  13947. auto autoComplete = GetAutoComplete();
  13948. if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mTypeRef != NULL))
  13949. {
  13950. autoComplete->CheckTypeRef(objCreateExpr->mTypeRef, false, true);
  13951. }
  13952. if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mOpenToken != NULL) && (objCreateExpr->mCloseToken != NULL) &&
  13953. (objCreateExpr->mOpenToken->mToken == BfToken_LBrace) && (autoComplete->CheckFixit(objCreateExpr->mOpenToken)))
  13954. {
  13955. auto refNode = objCreateExpr->mOpenToken;
  13956. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  13957. if (parser != NULL)
  13958. {
  13959. autoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("Change initializer braces to parentheses\treformat|%s|%d-1|(\x01|%s|%d-1|)",
  13960. parser->mFileName.c_str(), refNode->mSrcStart,
  13961. parser->mFileName.c_str(), objCreateExpr->mCloseToken->mSrcStart).c_str()));
  13962. }
  13963. }
  13964. BfMethodGenericArguments methodGenericArguments;
  13965. if ((objCreateExpr != NULL) && (objCreateExpr->mCtorExplicit != NULL) && (objCreateExpr->mCtorExplicit->mGenericArgs != NULL))
  13966. methodGenericArguments.mArguments = &objCreateExpr->mCtorExplicit->mGenericArgs->mGenericArgs;
  13967. CheckObjectCreateTypeRef(mExpectingType, allocNode);
  13968. BfAttributeState attributeState;
  13969. attributeState.mTarget = BfAttributeTargets_Alloc;
  13970. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  13971. BfTokenNode* newToken = NULL;
  13972. BfAllocTarget allocTarget;
  13973. ResolveAllocTarget(allocTarget, allocNode, newToken, &attributeState.mCustomAttributes);
  13974. bool isStructAlloc = newToken == NULL;
  13975. bool isScopeAlloc = (newToken != NULL) && (newToken->GetToken() == BfToken_Scope);
  13976. bool isAppendAlloc = (newToken != NULL) && (newToken->GetToken() == BfToken_Append);
  13977. bool isStackAlloc = (isScopeAlloc) || (isStructAlloc);
  13978. bool isArrayAlloc = false;// (objCreateExpr->mArraySizeSpecifier != NULL);
  13979. bool isRawArrayAlloc = (objCreateExpr != NULL) && (objCreateExpr->mStarToken != NULL);
  13980. if ((objCreateExpr != NULL) && (objCreateExpr->mCtorExplicit != NULL) && (objCreateExpr->mCtorExplicit->mThisToken != NULL))
  13981. {
  13982. mModule->SetElementType(objCreateExpr->mCtorExplicit->mThisToken, BfSourceElementType_Method);
  13983. }
  13984. if (isScopeAlloc)
  13985. {
  13986. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  13987. {
  13988. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", allocNode);
  13989. }
  13990. if (allocNode == newToken) // Scope, no target specified
  13991. {
  13992. if (mModule->mParentNodeEntry != NULL)
  13993. {
  13994. if (auto assignExpr = BfNodeDynCastExact<BfAssignmentExpression>(mModule->mParentNodeEntry->mNode))
  13995. {
  13996. if (mModule->mCurMethodState->mCurScope->mCloseNode == NULL)
  13997. {
  13998. // 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
  13999. if ((mBfEvalExprFlags & BfEvalExprFlags_PendingPropSet) == 0)
  14000. mModule->Warn(0, "This allocation will immediately go out of scope. Consider specifying a wider scope target such as 'scope::'", allocNode);
  14001. }
  14002. }
  14003. }
  14004. }
  14005. }
  14006. BfAutoParentNodeEntry autoParentNodeEntry(mModule, objCreateExpr);
  14007. SizedArray<BfAstNode*, 2> dimLengthRefs;
  14008. SizedArray<BfIRValue, 2> dimLengthVals;
  14009. BfArrayType* arrayType = NULL;
  14010. BfType* unresolvedTypeRef = NULL;
  14011. BfType* resolvedTypeRef = NULL;
  14012. if (wantAllocType != NULL)
  14013. {
  14014. unresolvedTypeRef = wantAllocType;
  14015. resolvedTypeRef = wantAllocType;
  14016. }
  14017. else if (objCreateExpr->mTypeRef == NULL)
  14018. {
  14019. if ((!mExpectingType) || (!mExpectingType->IsArray()))
  14020. {
  14021. mModule->Fail("Cannot imply array type. Explicitly state array type or use array in an assignment to an array type.", objCreateExpr);
  14022. resolvedTypeRef = mModule->mContext->mBfObjectType;
  14023. unresolvedTypeRef = resolvedTypeRef;
  14024. }
  14025. else
  14026. {
  14027. auto arrayType = (BfArrayType*)mExpectingType;
  14028. unresolvedTypeRef = arrayType->GetUnderlyingType();
  14029. resolvedTypeRef = unresolvedTypeRef;
  14030. }
  14031. }
  14032. else
  14033. {
  14034. if ((objCreateExpr->mTypeRef->IsExact<BfDotTypeReference>()) && (mExpectingType != NULL))
  14035. {
  14036. //mModule->SetElementType(objCreateExpr->mTypeRef, BfSourceElementType_TypeRef);
  14037. if ((mExpectingType->IsObject()) || (mExpectingType->IsGenericParam()))
  14038. {
  14039. unresolvedTypeRef = mExpectingType;
  14040. if (unresolvedTypeRef->IsArray())
  14041. {
  14042. arrayType = (BfArrayType*)unresolvedTypeRef;
  14043. unresolvedTypeRef = unresolvedTypeRef->GetUnderlyingType();
  14044. isArrayAlloc = true;
  14045. }
  14046. }
  14047. else if (mExpectingType->IsPointer())
  14048. {
  14049. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  14050. }
  14051. else if (mExpectingType->IsStruct())
  14052. {
  14053. unresolvedTypeRef = mExpectingType;
  14054. }
  14055. else if (mExpectingType->IsVar())
  14056. unresolvedTypeRef = mExpectingType;
  14057. }
  14058. if (unresolvedTypeRef == NULL)
  14059. {
  14060. if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  14061. {
  14062. isArrayAlloc = true;
  14063. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  14064. {
  14065. if ((mExpectingType != NULL) &&
  14066. ((mExpectingType->IsArray()) || (mExpectingType->IsPointer()) || (mExpectingType->IsSizedArray())))
  14067. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  14068. }
  14069. if (unresolvedTypeRef == NULL)
  14070. unresolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  14071. if (unresolvedTypeRef == NULL)
  14072. unresolvedTypeRef = mModule->GetPrimitiveType(BfTypeCode_Var);
  14073. int dimensions = 1;
  14074. bool commaExpected = false;
  14075. if (arrayTypeRef->mParams.size() != 0)
  14076. {
  14077. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  14078. for (auto arg : arrayTypeRef->mParams)
  14079. {
  14080. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  14081. {
  14082. if (tokenNode->GetToken() == BfToken_Comma)
  14083. {
  14084. if (isRawArrayAlloc)
  14085. {
  14086. mModule->Fail("Sized arrays cannot be multidimensional.", tokenNode);
  14087. continue;
  14088. }
  14089. dimensions++;
  14090. if (dimensions == 5)
  14091. {
  14092. mModule->Fail("Too many array dimensions, consider using a jagged array.", tokenNode);
  14093. }
  14094. commaExpected = false;
  14095. continue;
  14096. }
  14097. }
  14098. auto expr = BfNodeDynCast<BfExpression>(arg);
  14099. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  14100. {
  14101. mModule->CreateValueFromExpression(expr, intType);
  14102. continue;
  14103. }
  14104. dimLengthRefs.Add(expr);
  14105. BfTypedValue dimLength;
  14106. if (expr == NULL)
  14107. {
  14108. // Not specified
  14109. dimLengthVals.push_back(BfIRValue());
  14110. continue;
  14111. }
  14112. if (arg != NULL)
  14113. {
  14114. dimLength = mModule->CreateValueFromExpression(expr, intType, BfEvalExprFlags_NoCast);
  14115. BfCastFlags castFlags = BfCastFlags_None;
  14116. if ((dimLength) && (dimLength.mType->IsInteger()))
  14117. {
  14118. // Allow uint for size - just force to int
  14119. if (!((BfPrimitiveType*)dimLength.mType)->IsSigned())
  14120. castFlags = BfCastFlags_Explicit;
  14121. }
  14122. if (dimLength)
  14123. dimLength = mModule->Cast(expr, dimLength, intType, castFlags);
  14124. }
  14125. if (commaExpected)
  14126. {
  14127. mModule->AssertErrorState();
  14128. continue;
  14129. }
  14130. if (!dimLength)
  14131. {
  14132. dimLength = mModule->GetDefaultTypedValue(intType);
  14133. }
  14134. dimLengthVals.push_back(dimLength.mValue);
  14135. commaExpected = true;
  14136. }
  14137. }
  14138. if ((arrayTypeRef->mParams.size() == 0) && (objCreateExpr->mOpenToken == NULL))
  14139. mModule->Fail("Array size or array initializer expected", arrayTypeRef->mOpenBracket);
  14140. if (dimensions > 4)
  14141. dimensions = 4;
  14142. if ((!isRawArrayAlloc) && (!unresolvedTypeRef->IsVar()))
  14143. arrayType = mModule->CreateArrayType(unresolvedTypeRef, dimensions);
  14144. }
  14145. if (unresolvedTypeRef == NULL)
  14146. {
  14147. unresolvedTypeRef = ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  14148. }
  14149. }
  14150. resolvedTypeRef = unresolvedTypeRef;
  14151. if ((resolvedTypeRef != NULL) && (IsVar(resolvedTypeRef)))
  14152. resolvedTypeRef = unresolvedTypeRef;
  14153. }
  14154. if (inlineTypeRef != NULL)
  14155. {
  14156. auto inlineType = mModule->ResolveTypeRef(inlineTypeRef);
  14157. if (inlineType != NULL)
  14158. {
  14159. unresolvedTypeRef = inlineType;
  14160. resolvedTypeRef = inlineType;
  14161. }
  14162. }
  14163. if (resolvedTypeRef == NULL)
  14164. {
  14165. unresolvedTypeRef = mModule->GetPrimitiveType(BfTypeCode_Var);
  14166. resolvedTypeRef = unresolvedTypeRef;
  14167. }
  14168. auto resultType = resolvedTypeRef;
  14169. if ((resolvedTypeRef->IsInterface()) && (!isArrayAlloc))
  14170. {
  14171. mModule->Fail("Cannot create an instance of an interface", objCreateExpr->mTypeRef);
  14172. resolvedTypeRef = mModule->mContext->mBfObjectType;
  14173. }
  14174. BfTypeInstance* typeInstance = resolvedTypeRef->ToTypeInstance();
  14175. int elementSize = resolvedTypeRef->mSize;
  14176. int elementAlign = resolvedTypeRef->mAlign;
  14177. BfIRType allocType = mModule->mBfIRBuilder->MapType(resolvedTypeRef);
  14178. if (typeInstance != NULL)
  14179. {
  14180. if (!mModule->mCurTypeInstance->mResolvingVarField)
  14181. mModule->PopulateType(typeInstance);
  14182. if ((typeInstance->mTypeDef->mIsDelegate) && (!isArrayAlloc))
  14183. mModule->Fail("Delegates must be constructed through delegate binding", objCreateExpr->mTypeRef);
  14184. elementSize = BF_MAX(0, typeInstance->mInstSize);
  14185. elementAlign = typeInstance->mInstAlign;
  14186. allocType = mModule->mBfIRBuilder->MapTypeInst(typeInstance);
  14187. }
  14188. if (isAppendAlloc)
  14189. {
  14190. if (!mModule->mCurTypeInstance->IsObject())
  14191. {
  14192. mModule->Fail("Append allocations are only allowed in classes", allocNode);
  14193. isAppendAlloc = false;
  14194. }
  14195. else if ((mBfEvalExprFlags & BfEvalExprFlags_VariableDeclaration) == 0)
  14196. {
  14197. mModule->Fail("Append allocations are only allowed as local variable initializers in constructor body", allocNode);
  14198. isAppendAlloc = false;
  14199. }
  14200. else
  14201. {
  14202. auto methodDef = mModule->mCurMethodInstance->mMethodDef;
  14203. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  14204. {
  14205. mModule->Fail("Append allocations are only allowed as local variable declarations in the main method body", allocNode);
  14206. isAppendAlloc = false;
  14207. }
  14208. else if (!methodDef->HasAppend())
  14209. {
  14210. mModule->Fail("Append allocations can only be used on constructors with [AllowAppend] specified", allocNode);
  14211. isAppendAlloc = false;
  14212. }
  14213. else if (methodDef->mMethodType != BfMethodType_Ctor)
  14214. {
  14215. mModule->Fail("Append allocations are only allowed in constructors", allocNode);
  14216. isAppendAlloc = false;
  14217. }
  14218. else if (methodDef->mIsStatic)
  14219. {
  14220. mModule->Fail("Append allocations are only allowed in non-static constructors", allocNode);
  14221. isAppendAlloc = false;
  14222. }
  14223. }
  14224. }
  14225. if (isArrayAlloc)
  14226. {
  14227. const int MAX_DIMENSIONS = 2;
  14228. int dimensions = 1;
  14229. if (arrayType != NULL)
  14230. {
  14231. dimensions = arrayType->mDimensions;
  14232. mModule->AddDependency(arrayType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  14233. }
  14234. bool zeroMemory = true;
  14235. if (objCreateExpr->mOpenToken != NULL)
  14236. {
  14237. if ((objCreateExpr->mArguments.size() == 1) &&
  14238. (BfNodeDynCastExact<BfUninitializedExpression>(objCreateExpr->mArguments[0]) != NULL))
  14239. {
  14240. // Special case for a single "{ ? }"
  14241. zeroMemory = false;
  14242. }
  14243. else
  14244. {
  14245. SizedArray<int64, 2> dimLengths;
  14246. if (dimLengthVals.size() != 0)
  14247. {
  14248. for (int dim = 0; dim < dimensions; dim++)
  14249. {
  14250. BfIRValue dimLengthVal;
  14251. if (dim < (int)dimLengthVals.size())
  14252. dimLengthVal = dimLengthVals[dim];
  14253. if (!dimLengthVal)
  14254. {
  14255. dimLengths.push_back(-1);
  14256. continue;
  14257. }
  14258. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVal);
  14259. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  14260. {
  14261. int64 dimLength = constant->mInt64;
  14262. if (dimLength < 0)
  14263. {
  14264. mModule->Fail(StrFormat("Invalid array dimension '%lld'", dimLength), dimLengthRefs[dim]);
  14265. dimLength = -1;
  14266. }
  14267. dimLengths.push_back(dimLength);
  14268. }
  14269. else if ((constant != NULL) && (constant->mConstType == BfConstType_Undef))
  14270. {
  14271. dimLengths.push_back(-1);
  14272. }
  14273. else
  14274. {
  14275. mModule->Fail("A constant length is required when using an initializer", dimLengthRefs[dim]);
  14276. dimLengths.push_back(-1);
  14277. }
  14278. }
  14279. }
  14280. // Ending in an ", )" means we need to zero-fill ending
  14281. zeroMemory = objCreateExpr->mCommas.size() >= objCreateExpr->mArguments.size();
  14282. bool hasFailed = false;
  14283. ProcessArrayInitializer(objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, dimensions, dimLengths, 0, hasFailed);
  14284. dimLengthVals.resize(dimLengths.size());
  14285. for (int i = 0; i < (int)dimLengthVals.size(); i++)
  14286. {
  14287. if (!dimLengthVals[i])
  14288. {
  14289. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  14290. dimLengthVals[i] = mModule->GetConstValue(dimLengths[i], intType);
  14291. }
  14292. }
  14293. }
  14294. }
  14295. while ((int)dimLengthVals.size() < dimensions)
  14296. dimLengthVals.push_back(mModule->GetConstValue(0));
  14297. BfTypedValue arrayValue;
  14298. BfIRValue arraySize;
  14299. for (BfIRValue dimSize : dimLengthVals)
  14300. {
  14301. if (!arraySize)
  14302. arraySize = dimSize;
  14303. else
  14304. arraySize = mModule->mBfIRBuilder->CreateMul(arraySize, dimSize);
  14305. }
  14306. BfAllocFlags allocFlags = BfAllocFlags_None;
  14307. if (isRawArrayAlloc)
  14308. allocFlags = (BfAllocFlags)(allocFlags | BfAllocFlags_RawArray);
  14309. int writeIdx = 0;
  14310. struct BfInitContext
  14311. {
  14312. public:
  14313. BfModule* mModule;
  14314. BfType* resultType;
  14315. int dimensions;
  14316. SizedArray<BfIRValue, 2>& dimLengthVals;
  14317. BfIRValue arraySize;
  14318. int& writeIdx;
  14319. BfInitContext(BfModule* module, BfType* resultType, int dimensions, SizedArray<BfIRValue, 2>& dimLengthVals, BfIRValue arraySize, int& writeIdx) :
  14320. mModule(module), resultType(resultType), dimensions(dimensions), dimLengthVals(dimLengthVals), arraySize(arraySize), writeIdx(writeIdx)
  14321. {
  14322. }
  14323. void Handle(BfIRValue addr, int curDim, const BfSizedArray<BfExpression*>& valueExprs)
  14324. {
  14325. int exprIdx = 0;
  14326. int dimWriteIdx = 0;
  14327. bool isUninit = false;
  14328. int dimLength = -1;
  14329. if (dimLengthVals[curDim].IsConst())
  14330. {
  14331. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[curDim]);
  14332. dimLength = constant->mInt32;
  14333. }
  14334. while (exprIdx < (int)valueExprs.size())
  14335. {
  14336. auto initExpr = valueExprs[exprIdx];
  14337. exprIdx++;
  14338. if (!initExpr)
  14339. break;
  14340. if (auto unintExpr = BfNodeDynCastExact<BfUninitializedExpression>(initExpr))
  14341. {
  14342. isUninit = true;
  14343. break;
  14344. }
  14345. if (exprIdx > dimLength)
  14346. break;
  14347. if (curDim < dimensions - 1)
  14348. {
  14349. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(initExpr))
  14350. {
  14351. Handle(addr, curDim + 1, innerTupleExpr->mValues);
  14352. }
  14353. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(initExpr))
  14354. {
  14355. SizedArray<BfExpression*, 1> values;
  14356. values.Add(parenExpr->mExpression);
  14357. Handle(addr, curDim + 1, values);
  14358. }
  14359. else if (auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(initExpr))
  14360. {
  14361. Handle(addr, curDim + 1, innerInitExpr->mValues);
  14362. }
  14363. dimWriteIdx++;
  14364. continue;
  14365. }
  14366. BfIRValue elemAddr;
  14367. if (!resultType->IsValuelessType())
  14368. elemAddr = mModule->CreateIndexedValue(resultType, addr, writeIdx);
  14369. else
  14370. elemAddr = mModule->mBfIRBuilder->GetFakeVal();
  14371. writeIdx++;
  14372. dimWriteIdx++;
  14373. BfTypedValue elemPtrTypedVal = BfTypedValue(elemAddr, resultType, BfTypedValueKind_Addr);
  14374. BfExprEvaluator exprEvaluator(mModule);
  14375. exprEvaluator.mExpectingType = resultType;
  14376. exprEvaluator.mReceivingValue = &elemPtrTypedVal;
  14377. exprEvaluator.Evaluate(initExpr);
  14378. exprEvaluator.GetResult();
  14379. if (exprEvaluator.mReceivingValue == NULL)
  14380. {
  14381. // We wrote directly to the array in-place, we're done with this element
  14382. continue;
  14383. }
  14384. auto storeValue = exprEvaluator.mResult;
  14385. if (!storeValue)
  14386. continue;
  14387. storeValue = mModule->Cast(initExpr, storeValue, resultType);
  14388. if (!storeValue)
  14389. continue;
  14390. if (!resultType->IsValuelessType())
  14391. {
  14392. storeValue = mModule->LoadOrAggregateValue(storeValue);
  14393. mModule->mBfIRBuilder->CreateStore(storeValue.mValue, elemAddr);
  14394. }
  14395. }
  14396. int clearFromIdx = writeIdx;
  14397. int sectionElemCount = 1;
  14398. BfIRValue numElemsLeft = arraySize;
  14399. if (dimLength != -1)
  14400. {
  14401. int clearCount = dimLength - dimWriteIdx;
  14402. if (clearCount > 0)
  14403. {
  14404. for (int checkDim = curDim + 1; checkDim < (int)dimLengthVals.size(); checkDim++)
  14405. {
  14406. if (dimLengthVals[checkDim].IsConst())
  14407. {
  14408. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[checkDim]);
  14409. clearCount *= constant->mInt32;
  14410. sectionElemCount *= constant->mInt32;
  14411. }
  14412. }
  14413. }
  14414. writeIdx += clearCount;
  14415. numElemsLeft = mModule->GetConstValue(clearCount);
  14416. }
  14417. // Actually leave it alone?
  14418. if ((isUninit) &&
  14419. ((mModule->IsOptimized()) || (mModule->mIsComptimeModule) || (mModule->mBfIRBuilder->mIgnoreWrites)))
  14420. return;
  14421. bool doClear = true;
  14422. if (numElemsLeft.IsConst())
  14423. {
  14424. auto constant = mModule->mBfIRBuilder->GetConstant(numElemsLeft);
  14425. doClear = constant->mInt64 > 0;
  14426. }
  14427. if (doClear)
  14428. {
  14429. // We multiply by GetStride. This relies on the fact that we over-allocate on the array allocation -- the last
  14430. // element doesn't need to be padded out to the element alignment, but we do anyway. Otherwise this would be
  14431. // a more complicated computation
  14432. auto clearBytes = mModule->mBfIRBuilder->CreateMul(numElemsLeft, mModule->GetConstValue(resultType->GetStride()));
  14433. if (isUninit)
  14434. {
  14435. // Limit to a reasonable number of bytes to stomp with 0xCC
  14436. int maxStompBytes = BF_MIN(128, resultType->GetStride() * sectionElemCount);
  14437. if (clearBytes.IsConst())
  14438. {
  14439. auto constant = mModule->mBfIRBuilder->GetConstant(clearBytes);
  14440. if (constant->mInt64 > maxStompBytes)
  14441. clearBytes = mModule->GetConstValue(maxStompBytes);
  14442. }
  14443. else
  14444. {
  14445. auto insertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  14446. auto gtBlock = mModule->mBfIRBuilder->CreateBlock("unint.gt");
  14447. auto contBlock = mModule->mBfIRBuilder->CreateBlock("unint.cont");
  14448. auto cmp = mModule->mBfIRBuilder->CreateCmpLTE(clearBytes, mModule->GetConstValue(maxStompBytes), true);
  14449. mModule->mBfIRBuilder->CreateCondBr(cmp, contBlock, gtBlock);
  14450. mModule->mBfIRBuilder->AddBlock(gtBlock);
  14451. mModule->mBfIRBuilder->SetInsertPoint(gtBlock);
  14452. mModule->mBfIRBuilder->CreateBr(contBlock);
  14453. mModule->mBfIRBuilder->AddBlock(contBlock);
  14454. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  14455. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_IntPtr)), 2);
  14456. mModule->mBfIRBuilder->AddPhiIncoming(phi, clearBytes, insertBlock);
  14457. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(maxStompBytes), gtBlock);
  14458. clearBytes = phi;
  14459. }
  14460. }
  14461. mModule->mBfIRBuilder->PopulateType(resultType);
  14462. if ((!resultType->IsValuelessType()) && (!addr.IsConst()))
  14463. {
  14464. mModule->mBfIRBuilder->CreateMemSet(mModule->CreateIndexedValue(resultType, addr, clearFromIdx),
  14465. mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, isUninit ? 0xCC : 0), clearBytes, resultType->mAlign);
  14466. }
  14467. }
  14468. }
  14469. };
  14470. BfInitContext initContext(mModule, resultType, dimensions, dimLengthVals, arraySize, writeIdx);
  14471. if (IsVar(resultType))
  14472. {
  14473. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  14474. mResult = BfTypedValue(BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), mModule->GetPrimitiveType(BfTypeCode_Var)));
  14475. initContext.Handle(mResult.mValue, 0, objCreateExpr->mArguments);
  14476. return;
  14477. }
  14478. if (isRawArrayAlloc)
  14479. {
  14480. // 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
  14481. BfType* ptrType = mModule->CreatePointerType(resultType);
  14482. if (isAppendAlloc)
  14483. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, false), ptrType);
  14484. else
  14485. {
  14486. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), ptrType);
  14487. }
  14488. initContext.Handle(arrayValue.mValue, 0, objCreateExpr->mArguments);
  14489. mResult = arrayValue;
  14490. return;
  14491. }
  14492. if (dimLengthVals.size() > 4)
  14493. {
  14494. dimLengthVals.RemoveRange(4, dimLengthVals.size() - 4);
  14495. mModule->Fail("Too many array dimensions, consider using a jagged array.", objCreateExpr);
  14496. }
  14497. if (arrayType == NULL)
  14498. return;
  14499. if (isAppendAlloc)
  14500. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, zeroMemory), arrayType);
  14501. else
  14502. {
  14503. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), arrayType);
  14504. if (isScopeAlloc)
  14505. {
  14506. // See notes below on "general" SkipObjectAccessCheck usage on why we can do this
  14507. mModule->SkipObjectAccessCheck(arrayValue);
  14508. }
  14509. }
  14510. //mModule->InitTypeInst(arrayValue, scopeData);
  14511. BfAstNode* refNode = objCreateExpr->mTypeRef;
  14512. while (true)
  14513. {
  14514. if (auto arrayRef = BfNodeDynCast<BfElementedTypeRef>(refNode))
  14515. {
  14516. refNode = arrayRef->mElementType;
  14517. continue;
  14518. }
  14519. break;
  14520. }
  14521. BfResolvedArgs resolvedArgs;
  14522. auto rawAutoComplete = mModule->mCompiler->GetAutoComplete();
  14523. if (rawAutoComplete != NULL)
  14524. {
  14525. SetAndRestoreValue<bool> prevCapturing(rawAutoComplete->mIsCapturingMethodMatchInfo, false);
  14526. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, methodGenericArguments, BfAllowAppendKind_No);
  14527. }
  14528. else
  14529. {
  14530. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, methodGenericArguments, BfAllowAppendKind_No);
  14531. }
  14532. //TODO: Assert 'length' var is at slot 1
  14533. mModule->PopulateType(arrayType->mBaseType, BfPopulateType_DataAndMethods);
  14534. mModule->mBfIRBuilder->PopulateType(arrayType);
  14535. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(arrayValue.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(arrayType->mBaseType));
  14536. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  14537. if (arrayLengthBitCount == 0)
  14538. {
  14539. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", objCreateExpr);
  14540. return;
  14541. }
  14542. mResult = arrayValue;
  14543. auto lengthFieldInstance = mModule->GetFieldByName(arrayType->mBaseType->ToTypeInstance(), "mLength");
  14544. if (lengthFieldInstance == NULL)
  14545. return;
  14546. auto firstElementFieldInstance = mModule->GetFieldByName(arrayType->ToTypeInstance(), "mFirstElement");
  14547. if (firstElementFieldInstance == NULL)
  14548. return;
  14549. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, lengthFieldInstance->mDataIdx);
  14550. if (arrayLengthBitCount == 64)
  14551. mModule->mBfIRBuilder->CreateAlignedStore(arraySize, addr, 8);
  14552. else
  14553. {
  14554. auto arraySize32 = mModule->mBfIRBuilder->CreateNumericCast(arraySize, true, BfTypeCode_Int32);
  14555. mModule->mBfIRBuilder->CreateAlignedStore(arraySize32, addr, 4);
  14556. }
  14557. for (int lowerDim = 1; lowerDim < (int)dimLengthVals.size(); lowerDim++)
  14558. {
  14559. auto length1FieldInstance = mModule->GetFieldByName(arrayType->ToTypeInstance(), "mLength1");
  14560. if (length1FieldInstance == NULL)
  14561. return;
  14562. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, length1FieldInstance->mDataIdx + lowerDim - 1);
  14563. auto lowerDimVal = mModule->mBfIRBuilder->CreateNumericCast(dimLengthVals[lowerDim], true, (arrayLengthBitCount == 64) ? BfTypeCode_Int64 : BfTypeCode_Int32);
  14564. mModule->mBfIRBuilder->CreateStore(lowerDimVal, addr);
  14565. }
  14566. if (resultType->IsValuelessType())
  14567. addr = mModule->mBfIRBuilder->GetFakeVal();
  14568. else
  14569. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, firstElementFieldInstance->mDataIdx);
  14570. initContext.Handle(addr, 0, objCreateExpr->mArguments);
  14571. return;
  14572. }
  14573. else
  14574. {
  14575. if (resolvedTypeRef->IsVar())
  14576. {
  14577. // Leave as a var
  14578. }
  14579. else if ((!resolvedTypeRef->IsObjectOrInterface()) && (!resolvedTypeRef->IsGenericParam()))
  14580. {
  14581. resultType = mModule->CreatePointerType(resolvedTypeRef);
  14582. }
  14583. }
  14584. if ((isStackAlloc) && (mModule->mCurMethodState == NULL))
  14585. {
  14586. mModule->Fail("Cannot use 'stack' here", allocNode);
  14587. isStackAlloc = false;
  14588. isScopeAlloc = false;
  14589. }
  14590. bool isGenericParam = unresolvedTypeRef->IsGenericParam();
  14591. if (resolvedTypeRef->IsGenericParam())
  14592. {
  14593. BfGenericParamFlags genericParamFlags = BfGenericParamFlag_None;
  14594. BfType* typeConstraint = NULL;
  14595. auto genericParam = mModule->GetMergedGenericParamData((BfGenericParamType*)resolvedTypeRef, genericParamFlags, typeConstraint);
  14596. if (typeConstraint == NULL)
  14597. {
  14598. if ((genericParamFlags & BfGenericParamFlag_Var) != 0)
  14599. {
  14600. // Allow it
  14601. }
  14602. else
  14603. {
  14604. if ((genericParamFlags & BfGenericParamFlag_New) == 0)
  14605. {
  14606. mModule->Fail(StrFormat("Must add 'where %s : new' constraint to generic parameter to instantiate type", genericParam->GetName().c_str()), objCreateExpr->mTypeRef);
  14607. }
  14608. if (objCreateExpr->mArguments.size() != 0)
  14609. {
  14610. mModule->Fail(StrFormat("Only default parameterless constructors can be called on generic argument '%s'", genericParam->GetName().c_str()), objCreateExpr->mTypeRef);
  14611. }
  14612. }
  14613. }
  14614. if (((typeConstraint != NULL) && (typeConstraint->IsValueType())) ||
  14615. ((genericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0))
  14616. {
  14617. resultType = mModule->CreatePointerType(resolvedTypeRef);
  14618. }
  14619. else if (((typeConstraint != NULL) && (!typeConstraint->IsValueType())) ||
  14620. ((genericParamFlags & (BfGenericParamFlag_Class)) != 0))
  14621. {
  14622. // Leave as 'T'
  14623. resultType = resolvedTypeRef;
  14624. }
  14625. else
  14626. resultType = mModule->CreateModifiedTypeType(resolvedTypeRef, BfToken_AllocType);
  14627. mResult.mType = resultType;
  14628. if (typeInstance == NULL)
  14629. {
  14630. mResult = mModule->GetDefaultTypedValue(resultType);
  14631. return;
  14632. }
  14633. }
  14634. else if (resolvedTypeRef->IsSizedArray())
  14635. {
  14636. // Handle the case of "int[3]* val = new .(1, 2, 3)"
  14637. if (auto dotTypeRef = BfNodeDynCastExact<BfDotTypeReference>(objCreateExpr->mTypeRef))
  14638. {
  14639. BfIRValue allocValue;
  14640. if (isAppendAlloc)
  14641. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, BfIRValue(), 0, BfIRValue(), 0, false, false);
  14642. else
  14643. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None);
  14644. auto result = BfTypedValue(allocValue, resolvedTypeRef, BfTypedValueKind_Addr);
  14645. InitializedSizedArray((BfSizedArrayType*)resolvedTypeRef, objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, &result);
  14646. // Turn from an addr of a sized array to pointer of sized array
  14647. mResult = BfTypedValue(mResult.mValue, resultType);
  14648. return;
  14649. }
  14650. }
  14651. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isGenericParam);
  14652. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  14653. {
  14654. mModule->Fail("Cannot create an instance of an abstract class", objCreateExpr->mTypeRef);
  14655. return;
  14656. }
  14657. BfFunctionBindResult bindResult;
  14658. bindResult.mSkipThis = true;
  14659. bindResult.mWantsArgs = true;
  14660. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, &bindResult);
  14661. BfIRValue appendSizeValue;
  14662. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeRef, resolvedTypeRef->IsStruct());
  14663. BfResolvedArgs argValues;
  14664. if (objCreateExpr != NULL)
  14665. {
  14666. argValues.Init(objCreateExpr->mOpenToken, &objCreateExpr->mArguments, &objCreateExpr->mCommas, objCreateExpr->mCloseToken);
  14667. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval); ////
  14668. }
  14669. if (typeInstance == NULL)
  14670. {
  14671. // No CTOR needed
  14672. if (objCreateExpr->mArguments.size() != 0)
  14673. {
  14674. mModule->Fail(StrFormat("Only default parameterless constructors can be called on primitive type '%s'", mModule->TypeToString(resolvedTypeRef).c_str()), objCreateExpr->mTypeRef);
  14675. }
  14676. }
  14677. else if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mOpenToken != NULL))
  14678. {
  14679. auto wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  14680. autoComplete->CheckInvocation(objCreateExpr, objCreateExpr->mOpenToken, objCreateExpr->mCloseToken, objCreateExpr->mCommas);
  14681. BfAstNode* refNode = objCreateExpr->mTypeRef;
  14682. if ((objCreateExpr->mCtorExplicit != NULL) && (objCreateExpr->mCtorExplicit->mThisToken != NULL))
  14683. refNode = objCreateExpr->mCtorExplicit->mThisToken;
  14684. auto checkTypeInst = typeInstance;
  14685. if (checkTypeInst->IsAnonymousInitializerType())
  14686. checkTypeInst = checkTypeInst->mBaseType;
  14687. MatchConstructor(refNode, objCreateExpr, emtpyThis, checkTypeInst, argValues, false, methodGenericArguments, BfAllowAppendKind_Infer);
  14688. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  14689. {
  14690. if (autoComplete->mMethodMatchInfo != NULL)
  14691. autoComplete->mIsCapturingMethodMatchInfo = true;
  14692. }
  14693. else
  14694. autoComplete->mIsCapturingMethodMatchInfo = false;
  14695. }
  14696. else if (!resolvedTypeRef->IsFunction())
  14697. {
  14698. auto refNode = allocNode;
  14699. if (objCreateExpr != NULL)
  14700. refNode = objCreateExpr->mTypeRef;
  14701. auto checkTypeInst = typeInstance;
  14702. if (checkTypeInst->IsAnonymousInitializerType())
  14703. checkTypeInst = checkTypeInst->mBaseType;
  14704. MatchConstructor(refNode, objCreateExpr, emtpyThis, checkTypeInst, argValues, false, methodGenericArguments, BfAllowAppendKind_Infer);
  14705. }
  14706. if (objCreateExpr != NULL)
  14707. mModule->ValidateAllocation(typeInstance, objCreateExpr->mTypeRef);
  14708. prevBindResult.Restore();
  14709. int allocAlign = resolvedTypeRef->mAlign;
  14710. if (typeInstance != NULL)
  14711. allocAlign = typeInstance->mInstAlign;
  14712. int appendAllocAlign = 0;
  14713. BfAllocFlags allocFlags = BfAllocFlags_None;
  14714. if ((bindResult.mMethodInstance != NULL) && (bindResult.mMethodInstance->mMethodDef->HasAppend()))
  14715. {
  14716. if (!bindResult.mFunc)
  14717. {
  14718. BF_ASSERT((!mModule->HasExecutedOutput()) || (mModule->mBfIRBuilder->mIgnoreWrites));
  14719. appendSizeValue = mModule->GetConstValue(0);
  14720. }
  14721. else
  14722. {
  14723. //auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  14724. BfTypeVector methodGenericArguments;
  14725. if (bindResult.mMethodInstance->mMethodInfoEx != NULL)
  14726. methodGenericArguments = bindResult.mMethodInstance->mMethodInfoEx->mMethodGenericArguments;
  14727. auto methodOwner = bindResult.mMethodInstance->GetOwner();
  14728. auto calcAppendMethodDef = methodOwner->mTypeDef->mMethods[bindResult.mMethodInstance->mMethodDef->mIdx + 1];
  14729. BF_ASSERT(calcAppendMethodDef->mName == BF_METHODNAME_CALCAPPEND);
  14730. auto calcAppendMethodModule = mModule->GetMethodInstance(methodOwner, calcAppendMethodDef, methodGenericArguments);
  14731. SizedArray<BfIRValue, 2> irArgs;
  14732. if (bindResult.mIRArgs.size() > 1)
  14733. irArgs.Insert(0, &bindResult.mIRArgs[1], bindResult.mIRArgs.size() - 1);
  14734. BfTypedValue appendSizeTypedValue = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, irArgs);
  14735. if (!appendSizeTypedValue)
  14736. {
  14737. BF_ASSERT(calcAppendMethodModule.mFunc);
  14738. appendSizeTypedValue = CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, irArgs);
  14739. BF_ASSERT(appendSizeTypedValue.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  14740. }
  14741. appendSizeValue = appendSizeTypedValue.mValue;
  14742. allocAlign = BF_MAX(allocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  14743. appendAllocAlign = calcAppendMethodModule.mMethodInstance->mAppendAllocAlign;
  14744. if (calcAppendMethodModule.mMethodInstance->mHasAppendWantMark)
  14745. allocFlags = (BfAllocFlags)(allocFlags | BfAllocFlags_HasAppendWantMark);
  14746. }
  14747. if (appendAllocAlign != 0)
  14748. {
  14749. int endingAlign = typeInstance->GetEndingInstanceAlignment();
  14750. if (endingAlign % appendAllocAlign != 0)
  14751. {
  14752. int extraSize = appendAllocAlign - (endingAlign % appendAllocAlign);
  14753. appendSizeValue = mModule->mBfIRBuilder->CreateAdd(appendSizeValue, mModule->GetConstValue(extraSize));
  14754. }
  14755. }
  14756. if ((allocFlags & BfAllocFlags_HasAppendWantMark) != 0)
  14757. {
  14758. int markInfoSize = sizeof(intptr) + sizeof(intptr) * 4; // Stack trace, MarkAppendEntry
  14759. appendSizeValue = mModule->mBfIRBuilder->CreateAdd(appendSizeValue, mModule->GetConstValue(markInfoSize));
  14760. }
  14761. }
  14762. // WTF? I'm not even sure this is correct - add more tests
  14763. appendAllocAlign = BF_MAX(appendAllocAlign, allocAlign);
  14764. BfIRValue allocValue;
  14765. if (IsVar(resolvedTypeRef))
  14766. {
  14767. mResult = mModule->GetDefaultTypedValue(resultType);
  14768. return;
  14769. }
  14770. else
  14771. {
  14772. if (isAppendAlloc)
  14773. {
  14774. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, appendSizeValue, appendAllocAlign);
  14775. }
  14776. else
  14777. {
  14778. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, appendSizeValue, BfIRValue(), 0, allocFlags, allocAlign);
  14779. }
  14780. if (((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) && (mModule->mCompiler->mCeMachine != NULL))
  14781. {
  14782. mModule->mCompiler->mCeMachine->SetAppendAllocInfo(mModule, allocValue, appendSizeValue);
  14783. }
  14784. mResult = BfTypedValue(allocValue, resultType);
  14785. }
  14786. if (isScopeAlloc)
  14787. {
  14788. // This allows readonly (ie: 'let') local usage to not require an access check. No matter what scope the alloc is tied to, the
  14789. // lifetime of the local variable will be no longer than that of the allocated value
  14790. mModule->SkipObjectAccessCheck(mResult);
  14791. }
  14792. /*if (typeInstance != NULL)
  14793. {
  14794. mModule->InitTypeInst(mResult, scopeData, true);
  14795. }
  14796. if (isStackAlloc)
  14797. {
  14798. mModule->AddStackAlloc(mResult, objCreateExpr, scopeData);
  14799. }*/
  14800. if (mResult)
  14801. {
  14802. if (bindResult.mMethodInstance == NULL)
  14803. {
  14804. // Why did we have this? It was already zeroed right?
  14805. // Zero
  14806. //mModule->mBfIRBuilder->CreateMemSet(mResult.mValue, mModule->GetConstValue8(0), mModule->GetConstValue(resolvedTypeRef->mSize), resolvedTypeRef->mAlign);
  14807. }
  14808. else if (bindResult.mFunc)
  14809. {
  14810. bool hasRealtimeLeakCheck = (mModule->mCompiler->mOptions.mEnableRealtimeLeakCheck) && (!IsComptime());
  14811. if ((typeInstance->IsObject()) || (typeInstance->IsAnonymousInitializerType()))
  14812. {
  14813. bool wantsCtorClear = true;
  14814. if (hasRealtimeLeakCheck)
  14815. {
  14816. // Dbg_ObjectAlloc clears internally so we don't need to call CtorClear for those
  14817. if ((!isStackAlloc) && (!isAppendAlloc) && (!allocTarget.mCustomAllocator) && (allocTarget.mScopedInvocationTarget == NULL))
  14818. wantsCtorClear = false;
  14819. }
  14820. if (wantsCtorClear)
  14821. {
  14822. auto ctorClear = mModule->GetMethodByName(typeInstance, "__BfCtorClear");
  14823. if (!ctorClear)
  14824. {
  14825. mModule->AssertErrorState();
  14826. }
  14827. else if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) == 0)
  14828. {
  14829. SizedArray<BfIRValue, 1> irArgs;
  14830. irArgs.push_back(mResult.mValue);
  14831. CreateCall(objCreateExpr, ctorClear.mMethodInstance, ctorClear.mFunc, false, irArgs);
  14832. }
  14833. }
  14834. }
  14835. if (typeInstance->IsObject())
  14836. {
  14837. if ((!mModule->mIsComptimeModule) && (isStackAlloc) && (hasRealtimeLeakCheck))
  14838. {
  14839. BfMethodInstance* markMethod = mModule->GetRawMethodByName(mModule->mContext->mBfObjectType, "GCMarkMembers");
  14840. BF_ASSERT(markMethod != NULL);
  14841. if (markMethod != NULL)
  14842. {
  14843. auto& vtableEntry = typeInstance->mVirtualMethodTable[markMethod->mVirtualTableIdx];
  14844. if (vtableEntry.mImplementingMethod.mTypeInstance != mModule->mContext->mBfObjectType)
  14845. {
  14846. auto impMethodInstance = (BfMethodInstance*)vtableEntry.mImplementingMethod;
  14847. bool needsCall = false;
  14848. if (allocFlags & BfAllocFlags_HasAppendWantMark)
  14849. needsCall = true;
  14850. if (!needsCall)
  14851. {
  14852. if (impMethodInstance != NULL)
  14853. {
  14854. needsCall = impMethodInstance->mMethodDef->mBody != NULL;
  14855. }
  14856. else
  14857. {
  14858. needsCall = true;
  14859. BF_ASSERT(vtableEntry.mImplementingMethod.mKind == BfMethodRefKind_AmbiguousRef);
  14860. }
  14861. }
  14862. if (!needsCall)
  14863. {
  14864. if (typeInstance->HasAppendedField(true))
  14865. needsCall = true;
  14866. }
  14867. if (needsCall)
  14868. {
  14869. SizedArray<BfIRValue, 1> irArgs;
  14870. irArgs.push_back(mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(mModule->mContext->mBfObjectType)));
  14871. auto gcType = mModule->ResolveTypeDef(mModule->mCompiler->mGCTypeDef);
  14872. BF_ASSERT(gcType != NULL);
  14873. if (gcType != NULL)
  14874. {
  14875. auto addStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "AddStackMarkableObject", 1);
  14876. BF_ASSERT(addStackObjMethod);
  14877. if (addStackObjMethod)
  14878. {
  14879. mModule->mBfIRBuilder->CreateCall(addStackObjMethod.mFunc, irArgs);
  14880. }
  14881. auto removeStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "RemoveStackMarkableObject", 1);
  14882. BF_ASSERT(removeStackObjMethod);
  14883. if (removeStackObjMethod)
  14884. {
  14885. mModule->AddDeferredCall(removeStackObjMethod, irArgs, allocTarget.mScopeData, allocNode);
  14886. }
  14887. }
  14888. }
  14889. }
  14890. }
  14891. }
  14892. }
  14893. auto origThisTypedValue = mResult;
  14894. auto thisTypedValue = mResult;
  14895. if (inlineTypeRef != NULL)
  14896. {
  14897. BfType* wantType = bindResult.mMethodInstance->GetOwner();
  14898. if (thisTypedValue.mType->IsPointer())
  14899. wantType = mModule->CreatePointerType(wantType);
  14900. thisTypedValue = mModule->Cast(allocNode, thisTypedValue, wantType);
  14901. }
  14902. if ((bindResult.mMethodInstance->mMethodDef->HasAppend()) && (mResult.mType->IsObject()))
  14903. {
  14904. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14905. auto typeInst = mResult.mType->ToTypeInstance();
  14906. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  14907. BfIRValue intPtrVal = mModule->CreateAlloca(intPtrType);
  14908. auto intPtrThisVal = mModule->mBfIRBuilder->CreatePtrToInt(thisTypedValue.mValue, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  14909. auto curValPtr = mModule->mBfIRBuilder->CreateAdd(intPtrThisVal, mModule->GetConstValue(typeInst->mInstSize, intPtrType));
  14910. mModule->mBfIRBuilder->CreateStore(curValPtr, intPtrVal);
  14911. bindResult.mIRArgs[0] = intPtrVal;
  14912. }
  14913. if (!typeInstance->IsValuelessType())
  14914. bindResult.mIRArgs.Insert(0, thisTypedValue.mValue);
  14915. auto result = CreateCall(objCreateExpr, bindResult.mMethodInstance, bindResult.mFunc, false, bindResult.mIRArgs);
  14916. if ((result) && (!result.mType->IsVoid()))
  14917. mResult = result;
  14918. if (origThisTypedValue.mType != thisTypedValue.mType)
  14919. {
  14920. auto origThisType = origThisTypedValue.mType;
  14921. if (origThisType->IsPointer())
  14922. origThisType = origThisType->GetUnderlyingType();
  14923. auto origThisTypeInst = origThisType->ToTypeInstance();
  14924. if (origThisTypeInst != NULL)
  14925. {
  14926. BF_ASSERT(origThisTypeInst->IsAnonymousInitializerType());
  14927. auto ctorMethod = mModule->GetMethodByName(origThisTypeInst, "__BfCtor", 0);
  14928. if (!ctorMethod)
  14929. {
  14930. mModule->AssertErrorState();
  14931. }
  14932. else if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) == 0)
  14933. {
  14934. SizedArray<BfIRValue, 1> irArgs;
  14935. irArgs.push_back(origThisTypedValue.mValue);
  14936. CreateCall(objCreateExpr, ctorMethod.mMethodInstance, ctorMethod.mFunc, false, irArgs);
  14937. }
  14938. }
  14939. }
  14940. }
  14941. }
  14942. if (((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) && (mModule->mCompiler->mCeMachine != NULL))
  14943. {
  14944. mModule->mCompiler->mCeMachine->ClearAppendAllocInfo();
  14945. }
  14946. if ((mResult) && (isStructAlloc))
  14947. {
  14948. if (mResult.mType->IsPointer())
  14949. {
  14950. mResult = mModule->LoadValue(mResult);
  14951. mResult = BfTypedValue(mResult.mValue, mResult.mType->GetUnderlyingType(), true);
  14952. }
  14953. else
  14954. mModule->Fail(StrFormat("Allocation specifier such as 'new' is required for reference type '%s'", mModule->TypeToString(mResult.mType).c_str()), objCreateExpr);
  14955. }
  14956. }
  14957. void BfExprEvaluator::Visit(BfBoxExpression* boxExpr)
  14958. {
  14959. /*if ((boxExpr->mAllocNode == NULL) || (boxExpr->mExpression == NULL))
  14960. {
  14961. mModule->AssertErrorState();
  14962. return;
  14963. }*/
  14964. BfTokenNode* newToken = NULL;
  14965. BfAllocTarget allocTarget;
  14966. ResolveAllocTarget(allocTarget, boxExpr->mAllocNode, newToken);
  14967. if ((boxExpr->mAllocNode != NULL) && (boxExpr->mAllocNode->mToken == BfToken_Scope))
  14968. {
  14969. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  14970. {
  14971. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", boxExpr->mAllocNode);
  14972. }
  14973. }
  14974. if (boxExpr->mExpression == NULL)
  14975. {
  14976. mModule->AssertErrorState();
  14977. return;
  14978. }
  14979. auto exprValue = mModule->CreateValueFromExpression(boxExpr->mExpression);
  14980. if (exprValue)
  14981. {
  14982. bool doFail = false;
  14983. bool doWarn = false;
  14984. BfType* boxedType = NULL;
  14985. if (exprValue.mType->IsGenericParam())
  14986. {
  14987. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  14988. auto genericParamTarget = (BfGenericParamType*)exprValue.mType;
  14989. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  14990. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class)) == BfGenericParamFlag_Class)
  14991. doWarn = true;
  14992. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsObjectOrInterface()))
  14993. doWarn = true;
  14994. boxedType = mModule->mContext->mBfObjectType;
  14995. }
  14996. else
  14997. {
  14998. doFail = !exprValue.mType->IsValueTypeOrValueTypePtr();
  14999. doWarn = exprValue.mType->IsObjectOrInterface();
  15000. }
  15001. if (doWarn)
  15002. {
  15003. mModule->Warn(0, StrFormat("Boxing is unnecessary since type '%s' is already a reference type.", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  15004. mResult = exprValue;
  15005. return;
  15006. }
  15007. if (doFail)
  15008. {
  15009. 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);
  15010. return;
  15011. }
  15012. if (boxedType == NULL)
  15013. boxedType = mModule->CreateBoxedType(exprValue.mType);
  15014. if (boxedType == NULL)
  15015. boxedType = mModule->mContext->mBfObjectType;
  15016. mResult = mModule->BoxValue(boxExpr->mExpression, exprValue, boxedType, allocTarget);
  15017. if (!mResult)
  15018. {
  15019. mModule->Fail(StrFormat("Type '%s' is not boxable", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  15020. return;
  15021. }
  15022. }
  15023. }
  15024. void BfExprEvaluator::ResolveAllocTarget(BfAllocTarget& allocTarget, BfAstNode* allocNode, BfTokenNode*& newToken, BfCustomAttributes** outCustomAttributes)
  15025. {
  15026. auto autoComplete = GetAutoComplete();
  15027. BfAttributeDirective* attributeDirective = NULL;
  15028. allocTarget.mRefNode = allocNode;
  15029. newToken = BfNodeDynCast<BfTokenNode>(allocNode);
  15030. if (allocNode == NULL)
  15031. {
  15032. // Scope
  15033. if (mModule->mCurMethodState != NULL)
  15034. allocTarget.mScopeData = mModule->mCurMethodState->mCurScope->GetTargetable();
  15035. }
  15036. else if (newToken == NULL)
  15037. {
  15038. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(allocNode))
  15039. {
  15040. newToken = scopeNode->mScopeToken;
  15041. allocTarget.mScopeData = mModule->FindScope(scopeNode->mTargetNode, true);
  15042. if (autoComplete != NULL)
  15043. {
  15044. auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(scopeNode->mTargetNode);
  15045. if ((scopeNode->mTargetNode == NULL) || (targetIdentifier != NULL))
  15046. autoComplete->CheckLabel(targetIdentifier, scopeNode->mColonToken, allocTarget.mScopeData);
  15047. }
  15048. attributeDirective = scopeNode->mAttributes;
  15049. }
  15050. if (auto newNode = BfNodeDynCast<BfNewNode>(allocNode))
  15051. {
  15052. newToken = newNode->mNewToken;
  15053. if (auto allocExpr = BfNodeDynCast<BfExpression>(newNode->mAllocNode))
  15054. {
  15055. allocTarget.mCustomAllocator = mModule->CreateValueFromExpression(allocExpr);
  15056. allocTarget.mRefNode = allocExpr;
  15057. }
  15058. else if (auto scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(newNode->mAllocNode))
  15059. {
  15060. allocTarget.mScopedInvocationTarget = scopedInvocationTarget;
  15061. }
  15062. attributeDirective = newNode->mAttributes;
  15063. }
  15064. }
  15065. else if (newToken->GetToken() == BfToken_Scope)
  15066. {
  15067. if (mModule->mCurMethodState != NULL)
  15068. allocTarget.mScopeData = mModule->mCurMethodState->mCurScope->GetTargetable();
  15069. }
  15070. if (attributeDirective != NULL)
  15071. {
  15072. auto customAttrs = mModule->GetCustomAttributes(attributeDirective, BfAttributeTargets_Alloc, BfGetCustomAttributesFlags_AllowNonConstArgs, allocTarget.mCaptureInfo);
  15073. if (customAttrs != NULL)
  15074. {
  15075. for (auto& attrib : customAttrs->mAttributes)
  15076. {
  15077. if (attrib.mType->IsInstanceOf(mModule->mCompiler->mAlignAttributeTypeDef))
  15078. {
  15079. allocTarget.mAlignOverride = 16; // System conservative default
  15080. if (!attrib.mCtorArgs.IsEmpty())
  15081. {
  15082. BfIRConstHolder* constHolder = mModule->mCurTypeInstance->mConstHolder;
  15083. auto constant = constHolder->GetConstant(attrib.mCtorArgs[0]);
  15084. if (constant != NULL)
  15085. {
  15086. int alignOverride = (int)BF_MAX(1, constant->mInt64);
  15087. if ((alignOverride & (alignOverride - 1)) == 0)
  15088. allocTarget.mAlignOverride = alignOverride;
  15089. else
  15090. mModule->Fail("Alignment must be a power of 2", attrib.GetRefNode());
  15091. }
  15092. }
  15093. }
  15094. else if (attrib.mType->IsInstanceOf(mModule->mCompiler->mFriendAttributeTypeDef))
  15095. allocTarget.mIsFriend = true;
  15096. }
  15097. if (outCustomAttributes != NULL)
  15098. *outCustomAttributes = customAttrs;
  15099. else
  15100. delete customAttrs;
  15101. }
  15102. }
  15103. }
  15104. BfTypedValue BfExprEvaluator::MakeCallableTarget(BfAstNode* targetSrc, BfTypedValue target)
  15105. {
  15106. if ((target.mType->IsRef()) || (target.mType->IsPointer()))
  15107. {
  15108. auto underlying = target.mType->GetUnderlyingType();
  15109. bool underlyingIsStruct = underlying->IsStruct();
  15110. if (underlyingIsStruct)
  15111. {
  15112. target = mModule->LoadValue(target);
  15113. target.mType = underlying;
  15114. target.mKind = BfTypedValueKind_Addr;
  15115. }
  15116. }
  15117. if ((target.mType->IsStruct()) && (!target.IsAddr()))
  15118. {
  15119. if (IsConstEval())
  15120. return target;
  15121. target = mModule->MakeAddressable(target);
  15122. }
  15123. if (IsVar(target.mType))
  15124. {
  15125. target.mType = mModule->mContext->mBfObjectType;
  15126. return target;
  15127. }
  15128. if (target.mType->IsWrappableType())
  15129. {
  15130. auto primStructType = mModule->GetWrappedStructType(target.mType);
  15131. if (primStructType != NULL)
  15132. {
  15133. mModule->PopulateType(primStructType);
  15134. if (primStructType->IsTypedPrimitive())
  15135. {
  15136. // Type is already the same
  15137. target.mType = primStructType;
  15138. }
  15139. else if (target.IsAddr())
  15140. {
  15141. auto ptrType = mModule->CreatePointerType(primStructType);
  15142. target = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapType(ptrType)), primStructType, true);
  15143. }
  15144. else if ((primStructType->IsSplattable()) && (target.IsSplat()) && (!IsComptime()))
  15145. {
  15146. target.mType = primStructType;
  15147. target.mKind = BfTypedValueKind_SplatHead;
  15148. }
  15149. else
  15150. {
  15151. auto allocPtr = mModule->CreateAlloca(primStructType);
  15152. auto srcPtrType = mModule->mBfIRBuilder->CreateBitCast(allocPtr, mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(target.mType)));
  15153. mModule->mBfIRBuilder->CreateStore(target.mValue, srcPtrType);
  15154. target = BfTypedValue(allocPtr, primStructType, true);
  15155. }
  15156. }
  15157. return target;
  15158. }
  15159. if (target.mType->IsGenericParam())
  15160. {
  15161. target.mType = mModule->mContext->mBfObjectType;
  15162. return target;
  15163. }
  15164. if ((!target.mType->IsTypeInstance()) && (!target.mType->IsConcreteInterfaceType()))
  15165. {
  15166. mModule->Fail(StrFormat("Methods cannot be called on type '%s'", mModule->TypeToString(target.mType).c_str()), targetSrc);
  15167. return BfTypedValue();
  15168. }
  15169. return target;
  15170. }
  15171. int BfExprEvaluator::GetMixinVariable()
  15172. {
  15173. auto curMethodState = mModule->mCurMethodState;
  15174. for (int localIdx = (int)curMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  15175. {
  15176. auto varDecl = curMethodState->mLocals[localIdx];
  15177. if (varDecl->mName == "mixin")
  15178. return localIdx;
  15179. }
  15180. return -1;
  15181. }
  15182. BfModuleMethodInstance BfExprEvaluator::GetSelectedMethod(BfAstNode* targetSrc, BfTypeInstance* curTypeInst, BfMethodDef* methodDef, BfMethodMatcher& methodMatcher, BfType** overrideReturnType)
  15183. {
  15184. bool failed = false;
  15185. BfTypeVector resolvedGenericArguments;
  15186. BfMethodState* rootMethodState = NULL;
  15187. if (mModule->mCurMethodState != NULL)
  15188. rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  15189. int localInferrableGenericArgCount = -1;
  15190. if ((methodMatcher.mBestMethodGenericArguments.size() == 0) && (!methodMatcher.mExplicitMethodGenericArguments.IsEmpty()))
  15191. {
  15192. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(methodDef);
  15193. int64 genericArgCountDiff = (int)methodMatcher.mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx - (int)methodDef->mGenericParams.size();
  15194. BfInvocationExpression* invocationExpr = NULL;
  15195. if (mModule->mParentNodeEntry != NULL)
  15196. {
  15197. invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode);
  15198. }
  15199. if (genericArgCountDiff > 0)
  15200. {
  15201. BfAstNode* errorNode = targetSrc;
  15202. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL))
  15203. {
  15204. errorNode = invocationExpr->mGenericArgs->mGenericArgs[(int)methodDef->mGenericParams.size()];
  15205. if (errorNode == NULL)
  15206. invocationExpr->mGenericArgs->mCommas.GetSafe((int)methodDef->mGenericParams.size() - 1, errorNode);
  15207. if (errorNode == NULL)
  15208. errorNode = targetSrc;
  15209. }
  15210. mModule->Fail(StrFormat("Too many generic arguments, expected %d fewer", genericArgCountDiff), errorNode);
  15211. }
  15212. else if ((genericArgCountDiff < 0) && (!methodMatcher.mHadOpenGenericArguments))
  15213. {
  15214. BfAstNode* errorNode = targetSrc;
  15215. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL) && (invocationExpr->mGenericArgs->mCloseChevron != NULL))
  15216. errorNode = invocationExpr->mGenericArgs->mCloseChevron;
  15217. mModule->Fail(StrFormat("Too few generic arguments, expected %d more", -genericArgCountDiff), errorNode);
  15218. }
  15219. methodMatcher.mBestMethodGenericArguments.resize(methodDef->mGenericParams.size());
  15220. for (int i = 0; i < std::min(methodDef->mGenericParams.size() - uniqueGenericStartIdx, methodMatcher.mExplicitMethodGenericArguments.size()); i++)
  15221. {
  15222. methodMatcher.mBestMethodGenericArguments[i + uniqueGenericStartIdx] = methodMatcher.mExplicitMethodGenericArguments[i];
  15223. }
  15224. }
  15225. BfMethodInstance* unspecializedMethod = NULL;
  15226. bool hasVarGenerics = false;
  15227. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  15228. {
  15229. BfMethodInstance* outerMethodInstance = NULL;
  15230. auto& genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  15231. if (genericArg == NULL)
  15232. {
  15233. if ((methodDef->mIsLocalMethod) && (checkGenericIdx < mModule->mCurMethodInstance->GetNumGenericArguments()))
  15234. {
  15235. // If the root method is generic and we need that param then use that...
  15236. auto rootMethodInstance = rootMethodState->mMethodInstance;
  15237. if ((rootMethodInstance->mMethodInfoEx != NULL) && (checkGenericIdx < rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size()))
  15238. {
  15239. genericArg = rootMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  15240. }
  15241. else
  15242. {
  15243. if (localInferrableGenericArgCount == -1)
  15244. localInferrableGenericArgCount = mModule->GetLocalInferrableGenericArgCount(methodDef);
  15245. // Otherwise we can only infer generics at the level that the called method was contained
  15246. if (checkGenericIdx < localInferrableGenericArgCount)
  15247. genericArg = mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  15248. }
  15249. }
  15250. }
  15251. if (genericArg == NULL)
  15252. {
  15253. if (unspecializedMethod == NULL)
  15254. unspecializedMethod = mModule->GetRawMethodInstance(curTypeInst, methodDef);
  15255. auto genericParam = unspecializedMethod->mMethodInfoEx->mGenericParams[checkGenericIdx];
  15256. if ((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsDelegate()))
  15257. {
  15258. // The only other option was to bind to a MethodRef
  15259. genericArg = mModule->ResolveGenericType(genericParam->mTypeConstraint, NULL, &methodMatcher.mBestMethodGenericArguments, mModule->mCurTypeInstance);
  15260. }
  15261. else
  15262. {
  15263. if (((genericParam->mGenericParamFlags & BfGenericParamFlag_Const) != 0) && (genericParam->mTypeConstraint != NULL))
  15264. {
  15265. for (int paramIdx = 0; paramIdx < (int)unspecializedMethod->mDefaultValues.size(); paramIdx++)
  15266. {
  15267. auto defaultVal = unspecializedMethod->mDefaultValues[paramIdx];
  15268. if (!defaultVal)
  15269. continue;
  15270. auto& param = unspecializedMethod->mParams[paramIdx];
  15271. if (param.mResolvedType->IsGenericParam())
  15272. {
  15273. auto genericParamType = (BfGenericParamType*)param.mResolvedType;
  15274. if ((genericParamType->mGenericParamKind == BfGenericParamKind_Method) && (genericParamType->mGenericParamIdx == checkGenericIdx))
  15275. {
  15276. BfTypedValue constExprVal;
  15277. constExprVal.mType = genericParam->mTypeConstraint;
  15278. auto constant = curTypeInst->mConstHolder->GetConstant(defaultVal.mValue);
  15279. constExprVal.mValue = mModule->ConstantToCurrent(constant, curTypeInst->mConstHolder, genericParam->mTypeConstraint);
  15280. genericArg = mModule->CreateConstExprValueType(constExprVal);
  15281. }
  15282. }
  15283. }
  15284. }
  15285. }
  15286. if (genericArg == NULL)
  15287. {
  15288. BfGenericInferContext genericInferContext;
  15289. genericInferContext.mModule = mModule;
  15290. genericInferContext.mCheckMethodGenericArguments = &methodMatcher.mBestMethodGenericArguments;
  15291. genericInferContext.InferGenericArguments(unspecializedMethod);
  15292. }
  15293. if (genericArg == NULL)
  15294. {
  15295. failed = true;
  15296. BfError* error = mModule->Fail(StrFormat("Unable to determine generic argument '%s'", methodDef->mGenericParams[checkGenericIdx]->mName.c_str()).c_str(), targetSrc);
  15297. if ((genericParam->mTypeConstraint != NULL) && (!genericParam->mTypeConstraint->IsUnspecializedType()))
  15298. genericArg = genericParam->mTypeConstraint;
  15299. else
  15300. genericArg = mModule->mContext->mBfObjectType;
  15301. if (error != NULL)
  15302. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), unspecializedMethod->mMethodDef->GetRefNode());
  15303. }
  15304. }
  15305. if (genericArg->IsVar())
  15306. {
  15307. //BF_ASSERT(methodMatcher.mHasVarArguments);
  15308. hasVarGenerics = true;
  15309. }
  15310. if (genericArg->IsIntUnknown())
  15311. genericArg = mModule->FixIntUnknown(genericArg);
  15312. auto resolvedGenericArg = genericArg;
  15313. resolvedGenericArguments.push_back(genericArg);
  15314. }
  15315. BfTypeInstance* foreignType = NULL;
  15316. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  15317. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef)))
  15318. {
  15319. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForceInline);
  15320. mModule->mAttributeState->mUsed = true;
  15321. }
  15322. if ((!mModule->mCurTypeInstance->IsInterface()) && (methodDef->mBody != NULL))
  15323. {
  15324. if ((methodMatcher.mBypassVirtual) && (methodMatcher.mBestMethodTypeInstance->IsInterface()))
  15325. {
  15326. // This is an explicit 'base' call to a default interface method. We pull the methodDef into our own concrete type.
  15327. foreignType = curTypeInst;
  15328. curTypeInst = mModule->mCurTypeInstance;
  15329. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  15330. }
  15331. else if ((methodDef->mIsStatic) && (curTypeInst->IsInterface()))
  15332. {
  15333. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  15334. {
  15335. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  15336. foreignType = curTypeInst;
  15337. curTypeInst = mModule->mCurTypeInstance;
  15338. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  15339. }
  15340. }
  15341. }
  15342. if (hasVarGenerics)
  15343. return BfModuleMethodInstance();
  15344. BfModuleMethodInstance moduleMethodInstance;
  15345. if (methodMatcher.mBestMethodInstance)
  15346. {
  15347. moduleMethodInstance = methodMatcher.mBestMethodInstance;
  15348. }
  15349. else
  15350. {
  15351. moduleMethodInstance = mModule->GetMethodInstance(curTypeInst, methodDef, resolvedGenericArguments, flags, foreignType);
  15352. }
  15353. if (mModule->IsSkippingExtraResolveChecks())
  15354. {
  15355. //BF_ASSERT(methodInstance.mFunc == NULL);
  15356. }
  15357. if (moduleMethodInstance.mMethodInstance == NULL)
  15358. return NULL;
  15359. if (methodDef->IsEmptyPartial())
  15360. return moduleMethodInstance;
  15361. if (moduleMethodInstance.mMethodInstance->mMethodInfoEx != NULL)
  15362. {
  15363. for (int checkGenericIdx = 0; checkGenericIdx < (int)moduleMethodInstance.mMethodInstance->mMethodInfoEx->mGenericParams.size(); checkGenericIdx++)
  15364. {
  15365. auto genericParams = moduleMethodInstance.mMethodInstance->mMethodInfoEx->mGenericParams[checkGenericIdx];
  15366. BfTypeVector* checkMethodGenericArgs = NULL;
  15367. BfType* genericArg = NULL;
  15368. if (checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size())
  15369. {
  15370. genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  15371. }
  15372. else
  15373. {
  15374. checkMethodGenericArgs = &methodMatcher.mBestMethodGenericArguments;
  15375. genericArg = genericParams->mExternType;
  15376. auto owner = moduleMethodInstance.mMethodInstance->GetOwner();
  15377. BfTypeVector* typeGenericArguments = NULL;
  15378. if (owner->mGenericTypeInfo != NULL)
  15379. typeGenericArguments = &owner->mGenericTypeInfo->mTypeGenericArguments;
  15380. //genericArg = mModule->ResolveGenericType(genericArg, typeGenericArguments, checkMethodGenericArgs);
  15381. }
  15382. if (genericArg->IsVar())
  15383. continue;
  15384. BfAstNode* paramSrc;
  15385. if (checkGenericIdx >= methodMatcher.mBestMethodGenericArgumentSrcs.size())
  15386. {
  15387. paramSrc = targetSrc;
  15388. }
  15389. else
  15390. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  15391. // Note: don't pass methodMatcher.mBestMethodGenericArguments into here, this method is already specialized
  15392. BfError* error = NULL;
  15393. if (!mModule->CheckGenericConstraints(BfGenericParamSource(moduleMethodInstance.mMethodInstance), genericArg, paramSrc, genericParams, NULL,
  15394. failed ? NULL : &error))
  15395. {
  15396. if (moduleMethodInstance.mMethodInstance->IsSpecializedGenericMethod())
  15397. {
  15398. // We mark this as failed to make sure we don't try to process a method that doesn't even follow the constraints
  15399. moduleMethodInstance.mMethodInstance->mFailedConstraints = true;
  15400. }
  15401. if (moduleMethodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL)
  15402. {
  15403. if (error != NULL)
  15404. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), moduleMethodInstance.mMethodInstance->mMethodDef->GetRefNode());
  15405. }
  15406. }
  15407. }
  15408. }
  15409. else
  15410. BF_ASSERT(methodMatcher.mBestMethodGenericArguments.IsEmpty());
  15411. if ((overrideReturnType != NULL) && (moduleMethodInstance.mMethodInstance->mIsUnspecializedVariation) &&
  15412. ((moduleMethodInstance.mMethodInstance->mReturnType->IsUnspecializedTypeVariation()) || (moduleMethodInstance.mMethodInstance->mReturnType->IsVar())))
  15413. {
  15414. if (unspecializedMethod == NULL)
  15415. unspecializedMethod = mModule->GetRawMethodInstance(curTypeInst, methodDef);
  15416. BfTypeVector* typeGenericArgs = NULL;
  15417. auto typeUnspecMethodInstance = unspecializedMethod;
  15418. if (curTypeInst->IsUnspecializedTypeVariation())
  15419. {
  15420. typeUnspecMethodInstance = mModule->GetUnspecializedMethodInstance(typeUnspecMethodInstance, true);
  15421. typeGenericArgs = &curTypeInst->mGenericTypeInfo->mTypeGenericArguments;
  15422. }
  15423. BfType* specializedReturnType = mModule->ResolveGenericType(typeUnspecMethodInstance->mReturnType, typeGenericArgs, &methodMatcher.mBestMethodGenericArguments,
  15424. mModule->mCurTypeInstance);
  15425. if (specializedReturnType != NULL)
  15426. *overrideReturnType = specializedReturnType;
  15427. }
  15428. return moduleMethodInstance;
  15429. }
  15430. BfModuleMethodInstance BfExprEvaluator::GetSelectedMethod(BfMethodMatcher& methodMatcher)
  15431. {
  15432. if (!methodMatcher.mBestMethodInstance)
  15433. methodMatcher.mBestMethodInstance = GetSelectedMethod(methodMatcher.mTargetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  15434. return methodMatcher.mBestMethodInstance;
  15435. }
  15436. void BfExprEvaluator::CheckLocalMethods(BfAstNode* targetSrc, BfTypeInstance* typeInstance, const StringImpl& methodName, BfMethodMatcher& methodMatcher, BfMethodType methodType)
  15437. {
  15438. auto _GetNodeId = [&]()
  15439. {
  15440. auto parser = targetSrc->GetSourceData()->ToParserData();
  15441. return ((int64)parser->mDataId << 32) + targetSrc->GetSrcStart();
  15442. };
  15443. BfMethodState* ctxMethodState = NULL;
  15444. BfClosureInstanceInfo* ctxClosureInstanceInfo = NULL;
  15445. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL))
  15446. {
  15447. ctxClosureInstanceInfo = mModule->mCurMethodState->mClosureState->mClosureInstanceInfo;
  15448. ctxMethodState = mModule->mCurMethodState;
  15449. }
  15450. bool atCtxMethodState = false;
  15451. auto checkMethodState = mModule->mCurMethodState;
  15452. auto rootMethodState = checkMethodState;
  15453. while (checkMethodState != NULL)
  15454. {
  15455. rootMethodState = checkMethodState;
  15456. if (checkMethodState == ctxMethodState)
  15457. atCtxMethodState = true;
  15458. if ((ctxClosureInstanceInfo != NULL) && (!ctxMethodState->mClosureState->mCapturing))
  15459. {
  15460. BfMethodDef* localMethodDef = NULL;
  15461. if (ctxClosureInstanceInfo->mLocalMethodBindings.TryGetValue(_GetNodeId(), &localMethodDef))
  15462. {
  15463. methodMatcher.CheckMethod(mModule->mCurTypeInstance, mModule->mCurTypeInstance, localMethodDef, true);
  15464. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  15465. return;
  15466. }
  15467. }
  15468. else
  15469. {
  15470. BfLocalMethod* matchedLocalMethod = NULL;
  15471. BfLocalMethod* localMethod = NULL;
  15472. if (checkMethodState->mLocalMethodMap.TryGetValue(methodName, &localMethod))
  15473. {
  15474. auto typeInst = mModule->mCurTypeInstance;
  15475. if (checkMethodState->mMixinState != NULL)
  15476. typeInst = checkMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  15477. while (localMethod != NULL)
  15478. {
  15479. auto methodDef = mModule->GetLocalMethodDef(localMethod);
  15480. if (methodDef->mMethodType == methodType)
  15481. {
  15482. methodMatcher.CheckMethod(mModule->mCurTypeInstance, typeInst, methodDef, true);
  15483. if (methodMatcher.mBestMethodDef == methodDef)
  15484. matchedLocalMethod = localMethod;
  15485. }
  15486. localMethod = localMethod->mNextWithSameName;
  15487. }
  15488. }
  15489. if (matchedLocalMethod != NULL)
  15490. {
  15491. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  15492. {
  15493. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, typeInstance, matchedLocalMethod->mMethodDef, methodMatcher);
  15494. if (moduleMethodInstance)
  15495. {
  15496. auto methodInstance = moduleMethodInstance.mMethodInstance;
  15497. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState != NULL))
  15498. {
  15499. // The called method is calling us from its mLocalMethodRefs set. Stretch our mCaptureStartAccessId back to incorporate its
  15500. // captures as well
  15501. if (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId < mModule->mCurMethodState->mClosureState->mCaptureStartAccessId)
  15502. mModule->mCurMethodState->mClosureState->mCaptureStartAccessId = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId;
  15503. }
  15504. else
  15505. {
  15506. if (methodInstance->mDisallowCalling) // We need to process the captures from this guy
  15507. {
  15508. if (mModule->mCurMethodState->mClosureState->mLocalMethodRefSet.Add(methodInstance))
  15509. mModule->mCurMethodState->mClosureState->mLocalMethodRefs.Add(methodInstance);
  15510. }
  15511. }
  15512. }
  15513. }
  15514. if (ctxClosureInstanceInfo != NULL)
  15515. {
  15516. BF_ASSERT(mModule->mCurMethodState->mClosureState->mCapturing);
  15517. ctxClosureInstanceInfo->mLocalMethodBindings[_GetNodeId()] = methodMatcher.mBestMethodDef;
  15518. }
  15519. break;
  15520. }
  15521. }
  15522. checkMethodState = checkMethodState->mPrevMethodState;
  15523. }
  15524. }
  15525. void BfExprEvaluator::InjectMixin(BfAstNode* targetSrc, BfTypedValue target, bool allowImplicitThis, const StringImpl& name, const BfSizedArray<BfExpression*>& arguments, const BfMethodGenericArguments& methodGenericArgs)
  15526. {
  15527. if (mModule->mCurMethodState == NULL)
  15528. return;
  15529. if (mDeferCallRef != NULL)
  15530. {
  15531. mModule->Fail("Mixins cannot be directly deferred. Consider wrapping in a block.", targetSrc);
  15532. }
  15533. BfAstNode* origTargetSrc = targetSrc;
  15534. BfScopedInvocationTarget* scopedInvocationTarget = NULL;
  15535. if (mModule->mParentNodeEntry != NULL)
  15536. {
  15537. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  15538. {
  15539. scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(invocationExpr->mTarget);
  15540. }
  15541. }
  15542. auto targetNameNode = targetSrc;
  15543. if (scopedInvocationTarget != NULL)
  15544. targetNameNode = scopedInvocationTarget->mTarget;
  15545. while (true)
  15546. {
  15547. if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(targetNameNode))
  15548. {
  15549. targetNameNode = qualifiedNameNode->mRight;
  15550. continue;
  15551. }
  15552. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(targetNameNode))
  15553. {
  15554. targetNameNode = memberRefExpr->mMemberName;
  15555. continue;
  15556. }
  15557. break;
  15558. }
  15559. BfTypeInstance* mixinClass = NULL;
  15560. if (target.mType != NULL)
  15561. mixinClass = target.mType->ToTypeInstance();
  15562. int inLine = mModule->mCurFilePosition.mCurLine;
  15563. SizedArray<BfResolvedArg, 4> args;
  15564. SizedArray<BfExprEvaluator*, 8> argExprEvaluators;
  15565. defer
  15566. (
  15567. {
  15568. for (auto exprEvaluator : argExprEvaluators)
  15569. delete exprEvaluator;
  15570. }
  15571. );
  15572. auto _AddArg = [&](BfExpression* argExpr)
  15573. {
  15574. BfResolvedArg resolvedArg;
  15575. argExprEvaluators.push_back(new BfExprEvaluator(mModule));
  15576. BfExprEvaluator* exprEvaluator = argExprEvaluators.back();
  15577. exprEvaluator->mResolveGenericParam = false;
  15578. exprEvaluator->mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator->mBfEvalExprFlags | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr);
  15579. bool deferExpr = false;
  15580. if (auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  15581. {
  15582. deferExpr = true;
  15583. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  15584. }
  15585. if (deferExpr)
  15586. {
  15587. //
  15588. }
  15589. else if (argExpr != NULL)
  15590. exprEvaluator->Evaluate(argExpr, false, false, true);
  15591. else
  15592. mModule->Fail("Missing argument", targetSrc);
  15593. auto argValue = exprEvaluator->mResult;
  15594. mModule->FixIntUnknown(argValue);
  15595. if (argValue)
  15596. {
  15597. if (argValue.mType->IsRef())
  15598. {
  15599. exprEvaluator->FinishExpressionResult();
  15600. }
  15601. }
  15602. resolvedArg.mTypedValue = argValue;
  15603. resolvedArg.mExpression = argExpr;
  15604. args.push_back(resolvedArg);
  15605. };
  15606. for (BfExpression* argExpr : arguments)
  15607. {
  15608. _AddArg(argExpr);
  15609. }
  15610. auto autoComplete = GetAutoComplete();
  15611. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  15612. autoComplete->mIsCapturingMethodMatchInfo = false;
  15613. BfMethodMatcher methodMatcher(targetSrc, mModule, name, args, methodGenericArgs);
  15614. methodMatcher.mMethodType = BfMethodType_Mixin;
  15615. methodMatcher.mSkipImplicitParams = true;
  15616. auto curTypeInst = mModule->mCurTypeInstance;
  15617. if (mixinClass != NULL)
  15618. curTypeInst = mixinClass;
  15619. if (target.mType == NULL)
  15620. {
  15621. CheckLocalMethods(targetSrc, curTypeInst, name, methodMatcher, BfMethodType_Mixin);
  15622. }
  15623. if (methodMatcher.mBestMethodDef == NULL)
  15624. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  15625. if (methodMatcher.mBestMethodDef == NULL)
  15626. {
  15627. if (mixinClass != NULL)
  15628. methodMatcher.CheckType(mixinClass, BfTypedValue(), false);
  15629. else
  15630. methodMatcher.CheckType(mModule->mCurTypeInstance, BfTypedValue(), false);
  15631. }
  15632. if ((methodMatcher.mBestMethodDef == NULL) && (target.mType == NULL) && (mModule->mContext->mCurTypeState != NULL))
  15633. {
  15634. BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mType);
  15635. BfGlobalLookup globalLookup;
  15636. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  15637. globalLookup.mName = name;
  15638. mModule->PopulateGlobalContainersList(globalLookup);
  15639. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  15640. {
  15641. if (globalContainer.mTypeInst == NULL)
  15642. continue;
  15643. methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false);
  15644. if (methodMatcher.mBestMethodDef != NULL)
  15645. break;
  15646. }
  15647. }
  15648. if (methodMatcher.mBestMethodDef == NULL)
  15649. {
  15650. BfStaticSearch* staticSearch = mModule->GetStaticSearch();
  15651. if (staticSearch != NULL)
  15652. {
  15653. for (auto typeInst : staticSearch->mStaticTypes)
  15654. {
  15655. if (methodMatcher.CheckType(typeInst, BfTypedValue(), false))
  15656. {
  15657. if (methodMatcher.mBestMethodDef != NULL)
  15658. break;
  15659. }
  15660. }
  15661. }
  15662. }
  15663. if (methodMatcher.mBestMethodDef == NULL)
  15664. {
  15665. mModule->Fail("Cannot find mixin", targetSrc);
  15666. return;
  15667. }
  15668. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  15669. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetNameNode)) && (autoComplete->mDefType == NULL))
  15670. {
  15671. autoComplete->mInsertStartIdx = targetNameNode->GetSrcStart();
  15672. autoComplete->mInsertEndIdx = targetNameNode->GetSrcEnd();
  15673. autoComplete->mDefType = methodMatcher.mBestMethodTypeInstance->mTypeDef;
  15674. autoComplete->mDefMethod = methodMatcher.mBestMethodDef;
  15675. autoComplete->SetDefinitionLocation(methodMatcher.mBestMethodDef->GetMethodDeclaration()->mNameNode);
  15676. }
  15677. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method))
  15678. {
  15679. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() - 1);
  15680. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetNameNode, methodMatcher.mBestMethodTypeInstance->mTypeDef, methodMatcher.mBestMethodDef);
  15681. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() + 1);
  15682. }
  15683. auto curMethodState = mModule->mCurMethodState;
  15684. auto moduleMethodInstance = GetSelectedMethod(targetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  15685. if (!moduleMethodInstance)
  15686. {
  15687. if (methodMatcher.mHasVarArguments)
  15688. {
  15689. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  15690. return;
  15691. }
  15692. mModule->Fail("Failed to get selected mixin", targetSrc);
  15693. return;
  15694. }
  15695. if (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc))
  15696. return;
  15697. auto methodInstance = moduleMethodInstance.mMethodInstance;
  15698. PerformCallChecks(methodInstance, targetSrc);
  15699. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  15700. {
  15701. auto& genericParams = methodInstance->mMethodInfoEx->mGenericParams;
  15702. auto genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  15703. if (genericArg->IsVar())
  15704. continue;
  15705. BfAstNode* paramSrc;
  15706. if (methodMatcher.mBestMethodGenericArgumentSrcs.size() == 0)
  15707. paramSrc = targetSrc;
  15708. else
  15709. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  15710. // Note: don't pass methodMatcher.mBestMethodGenericArguments into here, this method is already specialized
  15711. BfError* error = NULL;
  15712. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericArg, paramSrc, genericParams[checkGenericIdx], NULL, &error))
  15713. {
  15714. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  15715. {
  15716. if (error != NULL)
  15717. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15718. }
  15719. }
  15720. }
  15721. if (curMethodState->mCurScope->mMixinDepth >= 128)
  15722. {
  15723. mModule->Fail("Maximum nested mixin depth exceeded", targetSrc);
  15724. return;
  15725. }
  15726. // Check circular ref based on methodInstance. We must check the arg types since we could be making progress in mixin evaluation
  15727. // based on method selection within the mixin dependent on args
  15728. {
  15729. bool hasCircularRef = false;
  15730. BfMixinState* checkMixinState = NULL;
  15731. auto checkMethodState = curMethodState;
  15732. while (checkMethodState != NULL)
  15733. {
  15734. auto curMixinState = checkMethodState->mMixinState;
  15735. while (curMixinState != NULL)
  15736. {
  15737. if ((curMixinState->mDoCircularVarResult) && (curMixinState->mMixinMethodInstance == methodInstance))
  15738. {
  15739. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  15740. return;
  15741. }
  15742. if ((!curMixinState->mCheckedCircularRef) && (curMixinState->mMixinMethodInstance == methodInstance))
  15743. {
  15744. checkMixinState = curMixinState;
  15745. checkMixinState->mCheckedCircularRef = true;
  15746. }
  15747. else if (checkMixinState != NULL)
  15748. {
  15749. if ((curMixinState->mMixinMethodInstance == checkMixinState->mMixinMethodInstance) &&
  15750. (curMixinState->mArgTypes == checkMixinState->mArgTypes) &&
  15751. (curMixinState->mArgConsts.mSize == checkMixinState->mArgConsts.mSize))
  15752. {
  15753. bool constsMatch = true;
  15754. for (int i = 0; i < curMixinState->mArgConsts.mSize; i++)
  15755. {
  15756. if (!mModule->mBfIRBuilder->CheckConstEquality(curMixinState->mArgConsts[i], checkMixinState->mArgConsts[i]))
  15757. {
  15758. constsMatch = false;
  15759. break;
  15760. }
  15761. }
  15762. if (constsMatch)
  15763. hasCircularRef = true;
  15764. }
  15765. }
  15766. curMixinState = curMixinState->mPrevMixinState;
  15767. }
  15768. checkMethodState = checkMethodState->mPrevMethodState;
  15769. }
  15770. if (hasCircularRef)
  15771. {
  15772. for (auto argType : checkMixinState->mArgTypes)
  15773. {
  15774. if (argType->IsVar())
  15775. checkMixinState->mDoCircularVarResult = true;
  15776. }
  15777. if (checkMixinState->mDoCircularVarResult)
  15778. {
  15779. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  15780. return;
  15781. }
  15782. mModule->Fail("Circular reference detected between mixins", targetSrc);
  15783. return;
  15784. }
  15785. }
  15786. AddCallDependencies(methodInstance);
  15787. if (!methodMatcher.mBestMethodDef->mIsStatic)
  15788. {
  15789. if ((!target) && (allowImplicitThis))
  15790. target = mModule->GetThis();
  15791. if (!target)
  15792. {
  15793. BfError* error = mModule->Fail(StrFormat("An instance reference is required to invoke the non-static mixin '%s'",
  15794. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  15795. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  15796. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15797. }
  15798. }
  15799. else
  15800. {
  15801. if (target)
  15802. {
  15803. BfError* error = mModule->Fail(StrFormat("Mixin '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  15804. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  15805. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  15806. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15807. }
  15808. }
  15809. int methodParamCount = (int)methodInstance->GetParamCount();
  15810. // Implicit params are ignored for calling- they should be resolved at the injection site
  15811. int implicitParamCount = methodInstance->GetImplicitParamCount();
  15812. int explicitParamCount = methodParamCount - implicitParamCount;
  15813. while ((int)args.size() < explicitParamCount)
  15814. {
  15815. int argIdx = (int)args.size();
  15816. BfExpression* expr = methodInstance->GetParamInitializer(argIdx);
  15817. if (expr == NULL)
  15818. break;
  15819. _AddArg(expr);
  15820. }
  15821. if ((int)args.size() < explicitParamCount)
  15822. {
  15823. BfError* error = mModule->Fail(StrFormat("Not enough arguments specified, expected %d more.", explicitParamCount - (int)arguments.size()), targetSrc);
  15824. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  15825. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15826. return;
  15827. }
  15828. else if ((int)args.size() > explicitParamCount)
  15829. {
  15830. BfError* error = mModule->Fail(StrFormat("Too many arguments specified, expected %d fewer.", (int)arguments.size() - explicitParamCount), targetSrc);
  15831. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  15832. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15833. return;
  15834. }
  15835. int paramIdx = implicitParamCount;
  15836. auto argExprEvaluatorItr = argExprEvaluators.begin();
  15837. for (int argIdx = 0; argIdx < (int)args.size(); argIdx++)
  15838. {
  15839. auto exprEvaluator = *argExprEvaluatorItr;
  15840. //auto paramType = methodInstance->GetParamKind(paramIdx);
  15841. BfType* wantType = methodInstance->mParams[paramIdx].mResolvedType;
  15842. auto& arg = args[argIdx];
  15843. if ((arg.mArgFlags & BfArgFlag_VariableDeclaration) != 0)
  15844. {
  15845. arg.mTypedValue = ResolveArgValue(arg, wantType);
  15846. }
  15847. if (wantType->IsGenericParam())
  15848. {
  15849. //
  15850. }
  15851. else if (!wantType->IsVar())
  15852. {
  15853. if (arg.mTypedValue.mType == NULL)
  15854. {
  15855. mModule->AssertErrorState();
  15856. return;
  15857. }
  15858. if (arg.mTypedValue.mType != wantType)
  15859. {
  15860. exprEvaluator->FinishExpressionResult();
  15861. arg.mTypedValue = mModule->LoadValue(arg.mTypedValue);
  15862. arg.mTypedValue = mModule->Cast(arg.mExpression, arg.mTypedValue, wantType);
  15863. /*// Do this to generate default implicit cast error
  15864. mModule->Fail(StrFormat("Mixin argument type '%s' must match parameter type '%s'.",
  15865. mModule->TypeToString(arg.mTypedValue.mType).c_str(),
  15866. mModule->TypeToString(wantType).c_str()), arg.mExpression);
  15867. return;*/
  15868. }
  15869. }
  15870. paramIdx++;
  15871. argExprEvaluatorItr++;
  15872. }
  15873. mModule->AddDependency(methodInstance->GetOwner(), mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  15874. auto startBlock = mModule->mBfIRBuilder->CreateBlock("mixinStart");
  15875. mModule->mBfIRBuilder->CreateBr(startBlock);
  15876. mModule->mBfIRBuilder->AddBlock(startBlock);
  15877. mModule->mBfIRBuilder->SetInsertPoint(startBlock);
  15878. //auto prevDebugLoc = mModule->mBfIRBuilder->getCurrentDebugLocation();
  15879. // This is so when we debug we can hit a steppoint on the inlined "call line"
  15880. mModule->EmitEnsureInstructionAt();
  15881. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  15882. BfMixinState* mixinState = rootMethodState->mMixinStates.Alloc();
  15883. mixinState->mInjectFilePosition = mModule->mCurFilePosition;
  15884. mixinState->mPrevMixinState = curMethodState->mMixinState;
  15885. mixinState->mLocalsStartIdx = (int)mModule->mCurMethodState->mLocals.size();
  15886. mixinState->mMixinMethodInstance = methodInstance;
  15887. mixinState->mSource = origTargetSrc;
  15888. mixinState->mCallerScope = mModule->mCurMethodState->mCurScope;
  15889. mixinState->mTargetScope = mixinState->mCallerScope;
  15890. mixinState->mResultExpr = NULL;
  15891. mixinState->mHasDeferredUsage = false;
  15892. mixinState->mUsedInvocationScope = false;
  15893. mixinState->mTarget = target;
  15894. auto checkNode = origTargetSrc;
  15895. if (scopedInvocationTarget != NULL)
  15896. {
  15897. auto targetScope = mModule->FindScope(scopedInvocationTarget->mScopeName, curMethodState->mMixinState);
  15898. if (targetScope != NULL)
  15899. {
  15900. mixinState->mTargetScope = targetScope;
  15901. if (autoComplete != NULL)
  15902. {
  15903. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(scopedInvocationTarget->mScopeName))
  15904. autoComplete->CheckLabel(identifer, NULL, targetScope);
  15905. }
  15906. }
  15907. }
  15908. mModule->mBfIRBuilder->SaveDebugLocation();
  15909. SetAndRestoreValue<BfMixinState*> prevMixinState(curMethodState->mMixinState, mixinState);
  15910. SetAndRestoreValue<BfExprEvaluator*> prevExprEvaluator(curMethodState->mCurScope->mExprEvaluator, NULL);
  15911. SetAndRestoreValue<BfPendingNullConditional*> prevNullConditional(curMethodState->mPendingNullConditional, NULL);
  15912. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  15913. if (mModule->mCompiler->mResolvePassData != NULL)
  15914. {
  15915. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  15916. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  15917. }
  15918. defer
  15919. (
  15920. {
  15921. if (mModule->mCompiler->mResolvePassData != NULL)
  15922. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  15923. }
  15924. );
  15925. auto methodDef = methodInstance->mMethodDef;
  15926. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15927. BfScopeData scopeData;
  15928. scopeData.mCloseNode = methodDeclaration->mBody;
  15929. if (auto block = BfNodeDynCast<BfBlock>(methodDeclaration->mBody))
  15930. {
  15931. if (block->mCloseBrace != NULL)
  15932. scopeData.mCloseNode = block->mCloseBrace;
  15933. }
  15934. curMethodState->AddScope(&scopeData);
  15935. curMethodState->mCurScope->mMixinDepth++;
  15936. // We can't flush scope state because we extend params in as arbitrary values
  15937. mModule->NewScopeState(true, false);
  15938. bool wantsDIData = (mModule->mBfIRBuilder->DbgHasInfo()) && (mModule->mHasFullDebugInfo);
  15939. DISubprogram* diFunction = NULL;
  15940. int startLocalIdx = (int)mModule->mCurMethodState->mLocals.size();
  15941. int endLocalIdx = startLocalIdx;
  15942. if ((wantsDIData) || (mModule->mIsComptimeModule))
  15943. {
  15944. BfIRMDNode diFuncType = mModule->mBfIRBuilder->DbgCreateSubroutineType(methodInstance);
  15945. //int defLine = mModule->mCurFilePosition.mCurLine;
  15946. int flags = 0;
  15947. curMethodState->mCurScope->mDIInlinedAt = mModule->mBfIRBuilder->DbgGetCurrentLocation();
  15948. // 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
  15949. // definitions, so we need to be consistent and use the actual line
  15950. mModule->UpdateSrcPos(methodDeclaration->mNameNode, BfSrcPosFlag_NoSetDebugLoc);
  15951. int defLine = mModule->mCurFilePosition.mCurLine;
  15952. auto diParentType = mModule->mBfIRBuilder->DbgGetTypeInst(methodInstance->GetOwner());
  15953. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  15954. {
  15955. String methodName = methodDef->mName;
  15956. methodName += "!";
  15957. BfMangler::Mangle(methodName, mModule->mCompiler->GetMangleKind(), methodInstance);
  15958. String linkageName;
  15959. if ((mModule->mIsComptimeModule) && (mModule->mCompiler->mCeMachine->mCurBuilder != NULL))
  15960. linkageName = StrFormat("%d", mModule->mCompiler->mCeMachine->mCurBuilder->DbgCreateMethodRef(methodInstance, ""));
  15961. curMethodState->mCurScope->mDIScope = mModule->mBfIRBuilder->DbgCreateFunction(diParentType, methodName, linkageName, mModule->mCurFilePosition.mFileInstance->mDIFile,
  15962. defLine + 1, diFuncType, false, true, mModule->mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  15963. scopeData.mAltDIFile = mModule->mCurFilePosition.mFileInstance->mDIFile;
  15964. }
  15965. }
  15966. if (methodDef->mBody != NULL)
  15967. mModule->UpdateSrcPos(methodDef->mBody);
  15968. mModule->SetIllegalSrcPos();
  15969. auto _AddLocalVariable = [&](BfLocalVariable* newLocalVar, BfExprEvaluator* exprEvaluator)
  15970. {
  15971. mModule->SetIllegalSrcPos();
  15972. bool hasConstValue = newLocalVar->mConstValue;
  15973. if (hasConstValue)
  15974. {
  15975. auto constant = mModule->mBfIRBuilder->GetConstant(newLocalVar->mConstValue);
  15976. hasConstValue = constant->mConstType < BfConstType_GlobalVar;
  15977. }
  15978. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL) && (exprEvaluator->mResultLocalVarField == 0))
  15979. {
  15980. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  15981. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  15982. auto inLocalVar = exprEvaluator->mResultLocalVar;
  15983. newLocalVar->mAssignedKind = inLocalVar->mAssignedKind;
  15984. newLocalVar->mUnassignedFieldFlags = inLocalVar->mUnassignedFieldFlags;
  15985. newLocalVar->mReadFromId = inLocalVar->mReadFromId;
  15986. newLocalVar->mIsReadOnly = inLocalVar->mIsReadOnly;
  15987. if ((newLocalVar->mAssignedKind == BfLocalVarAssignKind_None) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  15988. {
  15989. for (auto deferredAssign : mModule->mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  15990. {
  15991. if (deferredAssign.mLocalVar == inLocalVar)
  15992. newLocalVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15993. }
  15994. }
  15995. }
  15996. else
  15997. {
  15998. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  15999. }
  16000. if ((wantsDIData) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  16001. {
  16002. bool handled = false;
  16003. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  16004. if (hasConstValue)
  16005. {
  16006. // Already handled
  16007. handled = true;
  16008. }
  16009. else if (newLocalVar->mIsSplat)
  16010. {
  16011. bool found = false;
  16012. auto checkMethodState = mModule->mCurMethodState;
  16013. while ((checkMethodState != NULL) && (!found))
  16014. {
  16015. for (auto localVar : checkMethodState->mLocals)
  16016. {
  16017. if (localVar == newLocalVar)
  16018. continue;
  16019. if (!localVar->mIsSplat)
  16020. continue;
  16021. if (newLocalVar->mValue != localVar->mAddr)
  16022. continue;
  16023. bool isDupName = false;
  16024. for (auto param : methodDef->mParams)
  16025. {
  16026. if (param->mName == localVar->mName)
  16027. {
  16028. isDupName = true;
  16029. break;
  16030. }
  16031. }
  16032. if (isDupName)
  16033. {
  16034. auto splatAgg = mModule->AggregateSplat(BfTypedValue(newLocalVar->mValue, newLocalVar->mResolvedType, BfTypedValueKind_SplatHead));
  16035. // Don't allow alias if one of our args has the same name
  16036. newLocalVar->mIsSplat = false;
  16037. newLocalVar->mValue = BfIRValue();
  16038. if (splatAgg.IsAddr())
  16039. newLocalVar->mAddr = splatAgg.mValue;
  16040. else
  16041. newLocalVar->mValue = splatAgg.mValue;
  16042. found = true;
  16043. break;
  16044. }
  16045. String name = "$";
  16046. name += newLocalVar->mName;
  16047. name += "$alias$";
  16048. name += localVar->mName;
  16049. // auto fakeValue = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 0);
  16050. // auto diType = mModule->mBfIRBuilder->DbgGetType(mModule->GetPrimitiveType(BfTypeCode_Int32));
  16051. // auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  16052. // name, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  16053. // mModule->mBfIRBuilder->DbgInsertValueIntrinsic(fakeValue, diVariable);
  16054. auto diType = mModule->mBfIRBuilder->DbgGetType(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  16055. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  16056. name, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  16057. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(mModule->mBfIRBuilder->CreateConstNull(), diVariable);
  16058. handled = true;
  16059. found = true;
  16060. break;
  16061. }
  16062. checkMethodState = checkMethodState->mPrevMethodState;
  16063. }
  16064. }
  16065. if (handled)
  16066. {
  16067. //
  16068. }
  16069. else if ((mModule->IsTargetingBeefBackend()) && (!mModule->mIsComptimeModule))
  16070. {
  16071. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  16072. mModule->SetIllegalSrcPos();
  16073. // With the Beef backend we can assign two variables to the same value, but LLVM does not allow this
  16074. // so we have to create a ref to that variable
  16075. auto diType = mModule->mBfIRBuilder->DbgGetType(newLocalVar->mResolvedType);
  16076. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  16077. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  16078. if (newLocalVar->mIsSplat)
  16079. {
  16080. //TODO: Implement
  16081. }
  16082. else if (newLocalVar->mResolvedType->IsValuelessType())
  16083. {
  16084. // Do nothing
  16085. }
  16086. else
  16087. {
  16088. BfIRValue value = newLocalVar->mValue;
  16089. if (newLocalVar->mAddr)
  16090. value = newLocalVar->mAddr;
  16091. else if (newLocalVar->mConstValue)
  16092. value = newLocalVar->mConstValue;
  16093. auto aliasValue = mModule->mBfIRBuilder->CreateAliasValue(value);
  16094. if (mModule->WantsLifetimes())
  16095. scopeData.mDeferredLifetimeEnds.Add(aliasValue);
  16096. if (newLocalVar->mAddr)
  16097. mModule->mBfIRBuilder->DbgInsertDeclare(aliasValue, diVariable);
  16098. else
  16099. {
  16100. if (newLocalVar->mResolvedType->IsBoolean())
  16101. {
  16102. // Fix case of remote condbr referencing
  16103. newLocalVar->mAddr = mModule->CreateAlloca(newLocalVar->mResolvedType);
  16104. mModule->mBfIRBuilder->CreateStore(newLocalVar->mValue, newLocalVar->mAddr);
  16105. }
  16106. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(aliasValue, diVariable);
  16107. }
  16108. }
  16109. }
  16110. else if (newLocalVar->mAddr)
  16111. {
  16112. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  16113. mModule->SetIllegalSrcPos();
  16114. auto refType = mModule->CreateRefType(newLocalVar->mResolvedType);
  16115. auto allocaVal = mModule->CreateAlloca(refType);
  16116. mModule->mBfIRBuilder->CreateStore(newLocalVar->mAddr, allocaVal);
  16117. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  16118. {
  16119. auto diType = mModule->mBfIRBuilder->DbgGetType(refType);
  16120. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  16121. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  16122. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  16123. }
  16124. }
  16125. else if (newLocalVar->mValue)
  16126. {
  16127. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  16128. mModule->SetIllegalSrcPos();
  16129. auto localVal = LoadLocal(newLocalVar);
  16130. localVal = mModule->LoadValue(localVal);
  16131. localVal = mModule->AggregateSplat(localVal);
  16132. BfType* allocType = localVal.mType;
  16133. if (!allocType->IsValuelessType())
  16134. {
  16135. auto allocaVal = mModule->CreateAlloca(allocType);
  16136. mModule->mBfIRBuilder->CreateStore(localVal.mValue, allocaVal);
  16137. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  16138. {
  16139. if (newLocalVar->mIsSplat)
  16140. {
  16141. //TODO: Implement
  16142. }
  16143. else
  16144. {
  16145. auto diType = mModule->mBfIRBuilder->DbgGetType(allocType);
  16146. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  16147. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  16148. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  16149. }
  16150. }
  16151. }
  16152. }
  16153. }
  16154. newLocalVar->mParamIdx = -3;
  16155. mixinState->mArgTypes.Add(newLocalVar->mResolvedType);
  16156. if (mModule->mBfIRBuilder->IsConstValue(newLocalVar->mConstValue))
  16157. mixinState->mArgConsts.Add(newLocalVar->mConstValue);
  16158. };
  16159. argExprEvaluatorItr = argExprEvaluators.begin();
  16160. for (int argIdx = methodDef->mIsStatic ? 0 : -1; argIdx < (int)explicitParamCount; argIdx++)
  16161. {
  16162. int paramIdx = argIdx;
  16163. auto exprEvaluator = *argExprEvaluatorItr;
  16164. BfTypedValue argValue;
  16165. BfLocalVariable* localVar = new BfLocalVariable();
  16166. if (argIdx == -1)
  16167. {
  16168. argValue = target;
  16169. localVar->mName = "this";
  16170. localVar->mIsThis = true;
  16171. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16172. }
  16173. else
  16174. {
  16175. auto arg = &args[argIdx];
  16176. auto paramDef = methodDef->mParams[paramIdx];
  16177. localVar->mName = paramDef->mName;
  16178. if (!arg->mTypedValue)
  16179. {
  16180. auto wantType = methodInstance->GetParamType(paramIdx);
  16181. if (wantType->IsVar())
  16182. wantType = mModule->mContext->mBfObjectType;
  16183. arg->mTypedValue = mModule->GetDefaultTypedValue(wantType);
  16184. }
  16185. argValue = arg->mTypedValue;
  16186. }
  16187. if (!argValue)
  16188. continue;
  16189. localVar->mResolvedType = argValue.mType;
  16190. if (argValue.mType->IsRef())
  16191. {
  16192. auto refType = (BfRefType*)localVar->mResolvedType;
  16193. localVar->mAddr = mModule->LoadValue(argValue).mValue;
  16194. localVar->mResolvedType = argValue.mType->GetUnderlyingType();
  16195. localVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  16196. }
  16197. else if (argValue.IsAddr())
  16198. localVar->mAddr = argValue.mValue;
  16199. else
  16200. {
  16201. if (!argValue.mValue)
  16202. {
  16203. // Untyped value
  16204. }
  16205. else if (argValue.mValue.IsConst())
  16206. {
  16207. localVar->mConstValue = argValue.mValue;
  16208. }
  16209. else if (argValue.IsSplat())
  16210. {
  16211. localVar->mValue = argValue.mValue;
  16212. localVar->mIsSplat = true;
  16213. }
  16214. else
  16215. {
  16216. if (argValue.IsAddr())
  16217. localVar->mAddr = argValue.mValue;
  16218. else
  16219. localVar->mValue = argValue.mValue;
  16220. }
  16221. localVar->mIsReadOnly = argValue.IsReadOnly();
  16222. }
  16223. if (argValue.IsReadOnly())
  16224. localVar->mIsReadOnly = true;
  16225. if (argIdx == -1)
  16226. {
  16227. _AddLocalVariable(localVar, NULL);
  16228. }
  16229. else
  16230. {
  16231. _AddLocalVariable(localVar, exprEvaluator);
  16232. endLocalIdx++;
  16233. ++argExprEvaluatorItr;
  16234. }
  16235. }
  16236. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  16237. {
  16238. mModule->VisitCodeBlock(blockBody);
  16239. if (mixinState->mResultExpr != NULL)
  16240. {
  16241. if (auto exprNode = BfNodeDynCast<BfExpression>(mixinState->mResultExpr))
  16242. {
  16243. if (!exprNode->IsA<BfBlock>())
  16244. {
  16245. // Mixin expression result
  16246. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_AllowRefExpr));
  16247. mModule->UpdateSrcPos(exprNode);
  16248. VisitChild(exprNode);
  16249. FinishExpressionResult();
  16250. ResolveGenericType();
  16251. }
  16252. }
  16253. }
  16254. GetResult();
  16255. }
  16256. else if (auto expr = BfNodeDynCast<BfExpression>(methodDef->mBody))
  16257. {
  16258. mModule->UpdateSrcPos(expr);
  16259. mResult = mModule->CreateValueFromExpression(expr);
  16260. }
  16261. if (!mResult)
  16262. {
  16263. // If we didn't have an expression body then just make the result "void"
  16264. mResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  16265. }
  16266. mResult = mModule->RemoveRef(mResult);
  16267. if (mResult.IsAddr())
  16268. {
  16269. if (mModule->mCurMethodState->mCurScope->ExtendLifetime(mResult.mValue))
  16270. mModule->mBfIRBuilder->CreateLifetimeSoftEnd(mResult.mValue);
  16271. }
  16272. int localIdx = startLocalIdx;
  16273. argExprEvaluatorItr = argExprEvaluators.begin();
  16274. for (; localIdx < endLocalIdx; localIdx++)
  16275. {
  16276. auto exprEvaluator = *argExprEvaluatorItr;
  16277. BfLocalVariable* localVar = curMethodState->mLocals[localIdx];
  16278. //TODO: Merge unassigned flags together
  16279. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL))
  16280. {
  16281. auto inLocalVar = exprEvaluator->mResultLocalVar;
  16282. if (localVar->mAssignedKind != BfLocalVarAssignKind_None)
  16283. inLocalVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  16284. if (localVar->mReadFromId != -1)
  16285. inLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  16286. }
  16287. ++argExprEvaluatorItr;
  16288. }
  16289. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  16290. {
  16291. if (blockBody->mCloseBrace != NULL)
  16292. mModule->UpdateSrcPos(blockBody->mCloseBrace);
  16293. }
  16294. else if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  16295. {
  16296. if (methodDeclaration->mFatArrowToken != NULL)
  16297. mModule->UpdateSrcPos(methodDeclaration->mFatArrowToken);
  16298. }
  16299. mModule->RestoreScopeState();
  16300. prevMixinState.Restore();
  16301. if ((scopedInvocationTarget != NULL) && (scopedInvocationTarget->mScopeName != NULL) && (!mixinState->mUsedInvocationScope))
  16302. {
  16303. mModule->Warn(0, "Scope specifier was not referenced in mixin", scopedInvocationTarget->mScopeName);
  16304. }
  16305. if (mixinState->mHasDeferredUsage)
  16306. {
  16307. mixinState->mTarget = BfTypedValue();
  16308. // Put deferred mixin states at the front
  16309. BF_ASSERT(rootMethodState->mMixinStates.back() == mixinState);
  16310. rootMethodState->mMixinStates.pop_back();
  16311. rootMethodState->mMixinStates.Insert(0, mixinState);
  16312. }
  16313. else
  16314. {
  16315. BF_ASSERT(rootMethodState->mMixinStates.back() == mixinState);
  16316. rootMethodState->mMixinStates.pop_back();
  16317. delete mixinState;
  16318. }
  16319. mModule->mBfIRBuilder->RestoreDebugLocation();
  16320. mModule->mBfIRBuilder->DupDebugLocation();
  16321. }
  16322. void BfExprEvaluator::SetMethodElementType(BfAstNode* target)
  16323. {
  16324. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(target))
  16325. {
  16326. SetMethodElementType(delegateBindExpr->mTarget);
  16327. return;
  16328. }
  16329. if (auto lambdaBindExpr = BfNodeDynCast<BfLambdaBindExpression>(target))
  16330. {
  16331. return;
  16332. }
  16333. if (auto attributedIdentifierNode = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  16334. {
  16335. if (attributedIdentifierNode->mIdentifier != NULL)
  16336. mModule->SetElementType(attributedIdentifierNode->mIdentifier, BfSourceElementType_Method);
  16337. }
  16338. else if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(target))
  16339. {
  16340. if (memberReferenceExpr->mMemberName != NULL)
  16341. SetMethodElementType(memberReferenceExpr->mMemberName);
  16342. }
  16343. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(target))
  16344. SetMethodElementType(qualifiedNameNode->mRight);
  16345. else
  16346. mModule->SetElementType(target, BfSourceElementType_Method);
  16347. }
  16348. void BfExprEvaluator::DoInvocation(BfAstNode* target, BfMethodBoundExpression* methodBoundExpr, const BfSizedArray<BfExpression*>& args, const BfMethodGenericArguments& methodGenericArgs, BfTypedValue* outCascadeValue)
  16349. {
  16350. auto methodGenericArguments = methodGenericArgs.mArguments;
  16351. // Just a check
  16352. mModule->mBfIRBuilder->GetInsertBlock();
  16353. bool wasCapturingMethodInfo = false;
  16354. auto autoComplete = GetAutoComplete();
  16355. if ((autoComplete != NULL) && (methodGenericArguments != NULL))
  16356. {
  16357. for (BfAstNode* methodGenericArg : *methodGenericArguments)
  16358. {
  16359. autoComplete->CheckNode(methodGenericArg, false, true);
  16360. }
  16361. }
  16362. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  16363. {
  16364. // We don't want to capture a call within the target node
  16365. wasCapturingMethodInfo = true;
  16366. autoComplete->mIsCapturingMethodMatchInfo = false;
  16367. }
  16368. bool allowImplicitThis = false;
  16369. BfAstNode* methodNodeSrc = target;
  16370. BfAttributeState attributeState;
  16371. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  16372. if (auto scopedTarget = BfNodeDynCast<BfScopedInvocationTarget>(target))
  16373. {
  16374. target = scopedTarget->mTarget;
  16375. if (autoComplete != NULL)
  16376. {
  16377. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopedTarget->mScopeName))
  16378. autoComplete->CheckLabel(identifier, scopedTarget->mColonToken, NULL);
  16379. }
  16380. //mModule->FindScope(scopedTarget->mScopeName);
  16381. }
  16382. bool isCascade = false;
  16383. BfAstNode* cascadeOperatorToken = NULL;
  16384. bool bypassVirtual = false;
  16385. bool gaveUnqualifiedDotError = false;
  16386. String targetFunctionName;
  16387. BfTypedValue thisValue;
  16388. //TODO: This may just be a fully qualified static method name, so let's check that also
  16389. if (auto memberRefExpression = BfNodeDynCast<BfMemberReferenceExpression>(target))
  16390. {
  16391. if (autoComplete != NULL)
  16392. {
  16393. if (memberRefExpression->mTarget != NULL)
  16394. autoComplete->CheckMemberReference(memberRefExpression->mTarget, memberRefExpression->mDotToken, memberRefExpression->mMemberName, false, mExpectingType);
  16395. else if (mExpectingType != NULL)
  16396. {
  16397. String filter;
  16398. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(memberRefExpression->mDotToken, memberRefExpression->mMemberName, filter)))
  16399. {
  16400. auto typeInst = mExpectingType->ToTypeInstance();
  16401. if (typeInst != NULL)
  16402. {
  16403. String filter;
  16404. if ((memberRefExpression->mMemberName != NULL) && (autoComplete->IsAutocompleteNode(memberRefExpression->mMemberName)))
  16405. filter = autoComplete->GetFilter(memberRefExpression->mMemberName);
  16406. bool allowPrivate = typeInst == mModule->mCurTypeInstance;
  16407. autoComplete->AddEnumTypeMembers(typeInst, filter, false, allowPrivate);
  16408. autoComplete->AddSelfResultTypeMembers(typeInst, typeInst, filter, allowPrivate);
  16409. }
  16410. }
  16411. }
  16412. }
  16413. if ((memberRefExpression->mTarget == NULL) && (memberRefExpression->mMemberName == NULL))
  16414. {
  16415. auto expectingType = mExpectingType;
  16416. if ((expectingType != NULL) && (expectingType->IsNullable()))
  16417. {
  16418. auto underlyingType = expectingType->GetUnderlyingType();
  16419. expectingType = underlyingType;
  16420. }
  16421. BfType* inRefType = NULL;
  16422. if ((expectingType != NULL) && (expectingType->IsRef()))
  16423. {
  16424. auto refType = (BfRefType*)expectingType;
  16425. if (refType->mRefKind == BfRefType::RefKind_In)
  16426. {
  16427. inRefType = expectingType;
  16428. auto underlyingType = expectingType->GetUnderlyingType();
  16429. expectingType = underlyingType;
  16430. }
  16431. }
  16432. if (expectingType != NULL)
  16433. {
  16434. if (expectingType->IsSizedArray())
  16435. {
  16436. if (mModule->mParentNodeEntry != NULL)
  16437. {
  16438. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  16439. {
  16440. InitializedSizedArray((BfSizedArrayType*)expectingType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen);
  16441. return;
  16442. }
  16443. }
  16444. }
  16445. else if ((expectingType->IsStruct()) || (expectingType->IsTypedPrimitive()))
  16446. {
  16447. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  16448. {
  16449. autoComplete->mIsCapturingMethodMatchInfo = true;
  16450. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  16451. }
  16452. if (mModule->mParentNodeEntry != NULL)
  16453. {
  16454. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  16455. {
  16456. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  16457. BfResolveArgsFlags resolveArgsFlags = BfResolveArgsFlag_DeferParamEval;
  16458. ResolveArgValues(argValues, resolveArgsFlags);
  16459. if ((mReceivingValue != NULL) && (mReceivingValue->mType == expectingType) && (mReceivingValue->IsAddr()))
  16460. {
  16461. mResult = *mReceivingValue;
  16462. mReceivingValue = NULL;
  16463. }
  16464. else
  16465. mResult = BfTypedValue(mModule->CreateAlloca(expectingType), expectingType, BfTypedValueKind_TempAddr);
  16466. auto ctorResult = MatchConstructor(target, methodBoundExpr, mResult, expectingType->ToTypeInstance(), argValues, false, BfMethodGenericArguments(), BfAllowAppendKind_No);
  16467. if ((ctorResult) && (!ctorResult.mType->IsVoid()))
  16468. mResult = ctorResult;
  16469. mModule->ValidateAllocation(expectingType, invocationExpr->mTarget);
  16470. if ((inRefType != NULL) && (mResult.mType == expectingType) && (mResult.IsAddr()))
  16471. {
  16472. // Put back the 'in'
  16473. mResult = BfTypedValue(mResult.mValue, inRefType);
  16474. }
  16475. return;
  16476. }
  16477. }
  16478. }
  16479. else if (expectingType->IsGenericParam())
  16480. {
  16481. if (mModule->mParentNodeEntry != NULL)
  16482. {
  16483. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  16484. {
  16485. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  16486. BfResolveArgsFlags resolveArgsFlags = BfResolveArgsFlag_None;
  16487. ResolveArgValues(argValues, resolveArgsFlags);
  16488. if (!mModule->mCurMethodInstance->mIsUnspecializedVariation)
  16489. CheckGenericCtor((BfGenericParamType*)expectingType, argValues, invocationExpr->mTarget);
  16490. mResult = mModule->GetDefaultTypedValue(expectingType);
  16491. return;
  16492. }
  16493. }
  16494. }
  16495. else if (expectingType->IsVar())
  16496. {
  16497. // Silently allow
  16498. gaveUnqualifiedDotError = true;
  16499. }
  16500. else if (expectingType->IsPrimitiveType())
  16501. {
  16502. // Allow
  16503. }
  16504. else if ((mBfEvalExprFlags & BfEvalExprFlags_AppendFieldInitializer) == 0)
  16505. {
  16506. gaveUnqualifiedDotError = true;
  16507. if (mModule->PreFail())
  16508. mModule->Fail(StrFormat("Cannot use inferred constructor on type '%s'", mModule->TypeToString(expectingType).c_str()), memberRefExpression->mDotToken);
  16509. }
  16510. }
  16511. }
  16512. if (memberRefExpression->IsA<BfBaseExpression>())
  16513. bypassVirtual = true;
  16514. if (memberRefExpression->mMemberName != NULL)
  16515. methodNodeSrc = memberRefExpression->mMemberName;
  16516. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpression->mMemberName))
  16517. {
  16518. if (attrIdentifier->mIdentifier != NULL)
  16519. methodNodeSrc = attrIdentifier->mIdentifier;
  16520. attributeState.mSrc = attrIdentifier->mAttributes;
  16521. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  16522. if (attrIdentifier->mIdentifier != NULL)
  16523. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  16524. }
  16525. else if (memberRefExpression->mMemberName != NULL)
  16526. targetFunctionName = memberRefExpression->mMemberName->ToString();
  16527. if (memberRefExpression->mTarget == NULL)
  16528. {
  16529. if (mExpectingType)
  16530. {
  16531. if (mExpectingType->IsVar())
  16532. {
  16533. }
  16534. mResult = BfTypedValue(mExpectingType);
  16535. }
  16536. else if (!gaveUnqualifiedDotError)
  16537. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", memberRefExpression->mDotToken);
  16538. }
  16539. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpression->mTarget))
  16540. {
  16541. // Static method
  16542. mResult = BfTypedValue(ResolveTypeRef(typeRef));
  16543. }
  16544. if (auto leftIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpression->mTarget))
  16545. {
  16546. bool hadError = false;
  16547. thisValue = LookupIdentifier(leftIdentifier, true, &hadError);
  16548. CheckResultForReading(thisValue);
  16549. if (mPropDef != NULL)
  16550. thisValue = GetResult(true);
  16551. if (hadError)
  16552. {
  16553. mModule->AssertErrorState();
  16554. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16555. }
  16556. if ((!thisValue) && (mPropDef == NULL))
  16557. {
  16558. // Identifier not found. Static method? Just check speculatively don't throw error
  16559. BfType* type;
  16560. {
  16561. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  16562. type = mModule->ResolveTypeRef(leftIdentifier, NULL, BfPopulateType_DataAndMethods, BfResolveTypeRefFlag_NoResolveGenericParam);
  16563. }
  16564. if (type != NULL)
  16565. thisValue = BfTypedValue(type);
  16566. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(leftIdentifier))
  16567. {
  16568. LookupQualifiedStaticField(qualifiedLeft, true);
  16569. thisValue = mResult;
  16570. mResult = BfTypedValue();
  16571. }
  16572. }
  16573. if (mPropDef != NULL)
  16574. thisValue = GetResult(true);
  16575. if (!thisValue.mType)
  16576. {
  16577. mModule->Fail("Identifier not found", leftIdentifier);
  16578. mModule->CheckTypeRefFixit(leftIdentifier);
  16579. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16580. }
  16581. if (mResult)
  16582. CheckResultForReading(mResult);
  16583. mResult = thisValue;
  16584. }
  16585. else if (auto expr = BfNodeDynCast<BfExpression>(memberRefExpression->mTarget))
  16586. {
  16587. BfType* expectingTargetType = NULL;
  16588. if (memberRefExpression->mDotToken->mToken == BfToken_DotDot)
  16589. expectingTargetType = mExpectingType;
  16590. bool handled = false;
  16591. if (auto subMemberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(expr))
  16592. {
  16593. String findName;
  16594. if (subMemberRefExpr->mMemberName != NULL)
  16595. findName = subMemberRefExpr->mMemberName->ToString();
  16596. if (findName == "base") // Generic IFace<T>.base
  16597. {
  16598. thisValue = mModule->GetThis();
  16599. if (thisValue)
  16600. {
  16601. VisitChild(subMemberRefExpr->mTarget);
  16602. if (mResult.HasType())
  16603. {
  16604. if (mResult.mValue)
  16605. {
  16606. mModule->Fail("Type name expected", subMemberRefExpr->mTarget);
  16607. }
  16608. else
  16609. {
  16610. auto type = mResult.mType;
  16611. if (type != NULL)
  16612. {
  16613. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  16614. {
  16615. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  16616. mModule->TypeToString(type).c_str(),
  16617. mModule->TypeToString(thisValue.mType).c_str()), subMemberRefExpr->mTarget);
  16618. }
  16619. else
  16620. {
  16621. if (type->IsInterface())
  16622. {
  16623. thisValue.mType = type;
  16624. }
  16625. else
  16626. {
  16627. auto castedThis = mModule->Cast(subMemberRefExpr->mMemberName, thisValue, type, BfCastFlags_Explicit);
  16628. if (castedThis)
  16629. thisValue = castedThis;
  16630. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  16631. }
  16632. }
  16633. handled = true;
  16634. }
  16635. bypassVirtual = true;
  16636. }
  16637. }
  16638. }
  16639. }
  16640. }
  16641. if (!handled)
  16642. {
  16643. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  16644. auto flags = (BfEvalExprFlags)(BfEvalExprFlags_PropogateNullConditional | BfEvalExprFlags_NoCast);
  16645. if (mFunctionBindResult != NULL)
  16646. {
  16647. if (auto paranExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  16648. {
  16649. // Allow 'ref' on binding, to indicate we want to capture 'this' by reference
  16650. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowRefExpr);
  16651. expr = paranExpr->mExpression;
  16652. }
  16653. }
  16654. if (expr != NULL)
  16655. mResult = mModule->CreateValueFromExpression(expr, expectingTargetType, flags);
  16656. }
  16657. }
  16658. isCascade = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_DotDot);
  16659. if (isCascade)
  16660. cascadeOperatorToken = memberRefExpression->mDotToken;
  16661. bool isNullCondLookup = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_QuestionDot);
  16662. if (isNullCondLookup)
  16663. mResult = SetupNullConditional(mResult, memberRefExpression->mDotToken);
  16664. if ((mResult.mType == NULL) && (memberRefExpression->mTarget != NULL))
  16665. {
  16666. mModule->AssertErrorState();
  16667. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16668. }
  16669. thisValue = mResult;
  16670. mResult = BfTypedValue();
  16671. if ((thisValue) && (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->mToken == BfToken_Arrow))
  16672. thisValue = TryArrowLookup(thisValue, memberRefExpression->mDotToken);
  16673. }
  16674. else if (auto qualifiedName = BfNodeDynCast<BfQualifiedNameNode>(target))
  16675. {
  16676. if (GetAutoComplete() != NULL)
  16677. GetAutoComplete()->CheckMemberReference(qualifiedName->mLeft, qualifiedName->mDot, qualifiedName->mRight);
  16678. if (qualifiedName->mLeft->GetSrcLength() == 4)
  16679. {
  16680. if (CheckIsBase(qualifiedName->mLeft))
  16681. bypassVirtual = true;
  16682. }
  16683. if (qualifiedName->mRight != NULL)
  16684. methodNodeSrc = qualifiedName->mRight;
  16685. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(qualifiedName->mRight))
  16686. {
  16687. if (attrIdentifier->mIdentifier != NULL)
  16688. methodNodeSrc = attrIdentifier->mIdentifier;
  16689. attributeState.mSrc = attrIdentifier->mAttributes;
  16690. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  16691. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  16692. }
  16693. else
  16694. targetFunctionName = qualifiedName->mRight->ToString();
  16695. bool hadError = false;
  16696. thisValue = LookupIdentifier(qualifiedName->mLeft, true, &hadError);
  16697. CheckResultForReading(thisValue);
  16698. if (mPropDef != NULL)
  16699. thisValue = GetResult(true);
  16700. if (hadError)
  16701. {
  16702. mModule->AssertErrorState();
  16703. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16704. }
  16705. if ((!thisValue) && (mPropDef == NULL))
  16706. {
  16707. // Identifier not found. Static method? Just check speculatively don't throw error
  16708. BfType* type;
  16709. {
  16710. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  16711. type = mModule->ResolveTypeRef(qualifiedName->mLeft, NULL, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowGlobalContainer | BfResolveTypeRefFlag_IgnoreLookupError));
  16712. }
  16713. if (type == NULL)
  16714. {
  16715. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  16716. type = mModule->ResolveTypeRef(qualifiedName, methodGenericArguments, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowGlobalContainer | BfResolveTypeRefFlag_IgnoreLookupError));
  16717. if (type != NULL)
  16718. {
  16719. // This is a CTOR call, treat it as such
  16720. targetFunctionName.clear();
  16721. }
  16722. }
  16723. if (type != NULL)
  16724. thisValue = BfTypedValue(type);
  16725. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(qualifiedName->mLeft))
  16726. {
  16727. String findName = qualifiedLeft->mRight->ToString();
  16728. bool handled = false;
  16729. if (findName == "base")
  16730. {
  16731. auto type = mModule->ResolveTypeRef(qualifiedLeft->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  16732. mModule->CheckTypeRefFixit(qualifiedLeft->mLeft);
  16733. thisValue = mModule->GetThis();
  16734. if (type != NULL)
  16735. {
  16736. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  16737. {
  16738. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  16739. mModule->TypeToString(type).c_str(),
  16740. mModule->TypeToString(thisValue.mType).c_str()), qualifiedLeft->mLeft);
  16741. }
  16742. else
  16743. {
  16744. if (type->IsInterface())
  16745. {
  16746. thisValue.mType = type;
  16747. }
  16748. else
  16749. {
  16750. auto castedThis = mModule->Cast(qualifiedLeft->mRight, thisValue, type, BfCastFlags_Explicit);
  16751. if (castedThis)
  16752. thisValue = castedThis;
  16753. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  16754. }
  16755. }
  16756. handled = true;
  16757. }
  16758. bypassVirtual = true;
  16759. }
  16760. if (!handled)
  16761. {
  16762. LookupQualifiedStaticField(qualifiedLeft, true);
  16763. thisValue = mResult;
  16764. mResult = BfTypedValue();
  16765. }
  16766. }
  16767. }
  16768. if (mPropDef != NULL)
  16769. thisValue = GetResult(true);
  16770. if (!thisValue.mType)
  16771. {
  16772. mModule->Fail("Identifier not found", qualifiedName->mLeft);
  16773. mModule->CheckTypeRefFixit(qualifiedName->mLeft);
  16774. mModule->CheckIdentifierFixit(qualifiedName->mLeft);
  16775. thisValue = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  16776. }
  16777. if (mResult)
  16778. CheckResultForReading(mResult);
  16779. mResult = BfTypedValue();
  16780. }
  16781. else if (auto identiferExpr = BfNodeDynCast<BfIdentifierNode>(target))
  16782. {
  16783. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  16784. {
  16785. if (attrIdentifier->mIdentifier != NULL)
  16786. methodNodeSrc = attrIdentifier->mIdentifier;
  16787. attributeState.mSrc = attrIdentifier->mAttributes;
  16788. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  16789. }
  16790. allowImplicitThis = true;
  16791. if (autoComplete != NULL)
  16792. autoComplete->CheckIdentifier(identiferExpr);
  16793. targetFunctionName = target->ToString();
  16794. if (targetFunctionName == "PrintF") // Just directly call that one
  16795. {
  16796. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  16797. BfType* charPtrType = mModule->CreatePointerType(charType);
  16798. auto func = mModule->GetBuiltInFunc(BfBuiltInFuncType_PrintF);
  16799. SizedArray<BfIRValue, 4> irArgs;
  16800. for (BfExpression* arg : args)
  16801. {
  16802. BfTypedValue value;
  16803. if (arg != NULL)
  16804. value = mModule->CreateValueFromExpression(arg);
  16805. if (!value)
  16806. return;
  16807. auto typeInst = value.mType->ToTypeInstance();
  16808. if ((typeInst != NULL) && (typeInst->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  16809. value = mModule->Cast(arg, value, charPtrType);
  16810. if ((value.mType->IsFloat()) && (value.mType->mSize != 8)) // Always cast float to double
  16811. value = mModule->Cast(arg, value, mModule->GetPrimitiveType(BfTypeCode_Double));
  16812. irArgs.push_back(value.mValue);
  16813. }
  16814. if ((targetFunctionName != "PrintF") || (irArgs.size() > 0))
  16815. {
  16816. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCall(func, irArgs/*, targetFunctionName*/),
  16817. mModule->ResolveTypeDef(mModule->mSystem->mTypeInt32));
  16818. }
  16819. return;
  16820. }
  16821. if (auto ceDbgState = mModule->GetCeDbgState())
  16822. {
  16823. if (targetFunctionName.StartsWith("__"))
  16824. {
  16825. auto ceDebugger = mModule->mCompiler->mCeMachine->mDebugger;
  16826. auto _ResolveArg = [&](int argIdx, BfType* type = NULL)
  16827. {
  16828. if ((argIdx < 0) || (argIdx >= args.mSize))
  16829. return BfTypedValue();
  16830. return mModule->CreateValueFromExpression(args[argIdx], type);
  16831. };
  16832. if (targetFunctionName == "__getHighBits")
  16833. {
  16834. auto typedVal = _ResolveArg(0);
  16835. if ((typedVal) && (typedVal.mType->IsPrimitiveType()))
  16836. {
  16837. auto primType = (BfPrimitiveType*)typedVal.mType;
  16838. int64 val = ceDebugger->ValueToInt(typedVal);
  16839. int64 bitCount = ceDebugger->ValueToInt(_ResolveArg(1));
  16840. int64 resultVal = val >> (typedVal.mType->mSize * 8 - bitCount);
  16841. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)resultVal), typedVal.mType);
  16842. return;
  16843. }
  16844. }
  16845. else if (targetFunctionName == "__clearHighBits")
  16846. {
  16847. auto typedVal = _ResolveArg(0);
  16848. if ((typedVal) && (typedVal.mType->IsPrimitiveType()))
  16849. {
  16850. auto primType = (BfPrimitiveType*)typedVal.mType;
  16851. int64 val = ceDebugger->ValueToInt(typedVal);
  16852. int64 bitCount = ceDebugger->ValueToInt(_ResolveArg(1));
  16853. int64 andBits = (0x8000000000000000LL) >> ((typedVal.mType->mSize - 8) * 8 + bitCount - 1);
  16854. int64 resultVal = val & ~andBits;
  16855. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)resultVal), typedVal.mType);
  16856. return;
  16857. }
  16858. }
  16859. else if ((targetFunctionName == "__cast") || (targetFunctionName == "__bitcast"))
  16860. {
  16861. BfType* type = NULL;
  16862. String typeName;
  16863. for (int argIdx = 0; argIdx < args.mSize - 1; argIdx++)
  16864. {
  16865. auto arg = _ResolveArg(argIdx);
  16866. if (!arg)
  16867. continue;
  16868. if (arg.mType->IsInstanceOf(mModule->mCompiler->mStringTypeDef))
  16869. {
  16870. auto strPtr = mModule->GetStringPoolString(arg.mValue, mModule->mBfIRBuilder);
  16871. if (strPtr != NULL)
  16872. {
  16873. if ((type != NULL) && (*strPtr == "*"))
  16874. {
  16875. type = mModule->CreatePointerType(type);
  16876. }
  16877. else
  16878. typeName += *strPtr;
  16879. }
  16880. }
  16881. if (arg.mType->IsInteger())
  16882. {
  16883. int64 intVal = ceDebugger->ValueToInt(arg);
  16884. if (typeName.IsEmpty())
  16885. {
  16886. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef)->ToTypeInstance();
  16887. auto fieldDef = typeType->mTypeDef->GetFieldByName("mTypeId");
  16888. if (fieldDef != NULL)
  16889. {
  16890. int typeId = ceDebugger->ReadMemory<int>((intptr)intVal + typeType->mFieldInstances[fieldDef->mIdx].mDataOffset);
  16891. type = mModule->mContext->FindTypeById(typeId);
  16892. }
  16893. }
  16894. else
  16895. typeName += StrFormat("%lld", intVal);
  16896. }
  16897. }
  16898. auto fromTypedVal = _ResolveArg(args.mSize - 1);
  16899. if (!typeName.IsEmpty())
  16900. type = ceDebugger->FindType(typeName);
  16901. if (type != NULL)
  16902. {
  16903. if (targetFunctionName == "__bitcast")
  16904. {
  16905. if ((type->IsObjectOrInterface()) || (type->IsPointer()))
  16906. {
  16907. auto ceAddrVal = ceDebugger->GetAddr(fromTypedVal);
  16908. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIntToPtr(ceAddrVal.mAddr, mModule->mBfIRBuilder->MapType(type)), type);
  16909. }
  16910. else
  16911. {
  16912. Array<uint8> memArr;
  16913. memArr.Resize(BF_MAX(type->mSize, fromTypedVal.mType->mSize));
  16914. mModule->mBfIRBuilder->WriteConstant(fromTypedVal.mValue, memArr.mVals, fromTypedVal.mType);
  16915. auto newVal = mModule->mBfIRBuilder->ReadConstant(memArr.mVals, type);
  16916. mResult = BfTypedValue(newVal, type);
  16917. }
  16918. }
  16919. else
  16920. mResult = mModule->Cast(target, fromTypedVal, type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  16921. }
  16922. return;
  16923. }
  16924. else if (targetFunctionName == "__stringView")
  16925. {
  16926. auto ptrVal = _ResolveArg(0);
  16927. auto sizeVal = _ResolveArg(1);
  16928. if (ceDbgState->mFormatInfo != NULL)
  16929. ceDbgState->mFormatInfo->mOverrideCount = (int)ceDebugger->ValueToInt(sizeVal);
  16930. mResult = ptrVal;
  16931. return;
  16932. }
  16933. else if ((targetFunctionName == "__funcName") || (targetFunctionName == "__funcTarget"))
  16934. {
  16935. auto addrVal = _ResolveArg(0);
  16936. auto ceAddrVal = ceDebugger->GetAddr(addrVal);
  16937. CeFunction* ceFunction = NULL;
  16938. int functionId = 0;
  16939. if (mModule->mSystem->mPtrSize == 4)
  16940. {
  16941. functionId = (int)addrVal;
  16942. }
  16943. else
  16944. {
  16945. CeFunction* checkCeFunction = (CeFunction*)ceAddrVal.mAddr;
  16946. functionId = checkCeFunction->SafeGetId();
  16947. }
  16948. if (mModule->mCompiler->mCeMachine->mFunctionIdMap.TryGetValue(functionId, &ceFunction))
  16949. {
  16950. BfMethodInstance* methodInstance = ceFunction->mMethodInstance;
  16951. if (methodInstance != NULL)
  16952. {
  16953. if (targetFunctionName == "__funcTarget")
  16954. {
  16955. BfType* targetType = methodInstance->GetOwner();
  16956. if (targetType->IsValueType())
  16957. targetType = mModule->CreatePointerType(targetType);
  16958. auto targetVal = _ResolveArg(1);
  16959. auto ceTargetVal = ceDebugger->GetAddr(targetVal);
  16960. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIntToPtr(ceTargetVal.mAddr, mModule->mBfIRBuilder->MapType(targetType)), targetType);
  16961. return;
  16962. }
  16963. else
  16964. {
  16965. mResult = BfTypedValue(mModule->GetStringObjectValue(mModule->MethodToString(methodInstance)),
  16966. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  16967. return;
  16968. }
  16969. }
  16970. else if ((ceFunction->mCeInnerFunctionInfo != NULL) && (targetFunctionName == "__funcName"))
  16971. {
  16972. mResult = BfTypedValue(mModule->GetStringObjectValue(BfDemangler::Demangle(ceFunction->mCeInnerFunctionInfo->mName, DbgLanguage_Beef)),
  16973. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  16974. return;
  16975. }
  16976. }
  16977. if (targetFunctionName == "__funcTarget")
  16978. mResult = _ResolveArg(1);
  16979. else
  16980. mResult = addrVal;
  16981. return;
  16982. }
  16983. }
  16984. }
  16985. }
  16986. else if (auto expr = BfNodeDynCast<BfExpression>(target))
  16987. {
  16988. auto innerInvocationResult = mModule->CreateValueFromExpression(expr);
  16989. if (!innerInvocationResult)
  16990. {
  16991. mModule->AssertErrorState();
  16992. innerInvocationResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16993. }
  16994. if (innerInvocationResult.mType->IsVar())
  16995. {
  16996. mResult = innerInvocationResult;
  16997. return;
  16998. }
  16999. targetFunctionName = "Invoke";
  17000. if (innerInvocationResult.mType->IsTypeInstance())
  17001. {
  17002. auto invocationTypeInst = innerInvocationResult.mType->ToTypeInstance();
  17003. if ((invocationTypeInst->mTypeDef->mIsDelegate) || (invocationTypeInst->mTypeDef->mIsFunction))
  17004. {
  17005. thisValue = innerInvocationResult;
  17006. }
  17007. }
  17008. if (!thisValue)
  17009. {
  17010. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(innerInvocationResult.mType).c_str()), expr);
  17011. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  17012. }
  17013. }
  17014. else
  17015. {
  17016. mModule->Fail("Invalid invocation target", target);
  17017. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  17018. }
  17019. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  17020. {
  17021. autoComplete->mIsCapturingMethodMatchInfo = true;
  17022. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  17023. }
  17024. SetAndRestoreValue<BfAttributeState*> prevAttributeState;
  17025. if (attributeState.mCustomAttributes != NULL)
  17026. prevAttributeState.Init(mModule->mAttributeState, &attributeState);
  17027. if ((targetFunctionName != "") && (targetFunctionName[targetFunctionName.length() - 1] == '!'))
  17028. {
  17029. targetFunctionName = targetFunctionName.Substring(0, targetFunctionName.length() - 1);
  17030. InjectMixin(methodNodeSrc, thisValue, allowImplicitThis, targetFunctionName, args, methodGenericArgs);
  17031. return;
  17032. }
  17033. if (targetFunctionName.StartsWith('@'))
  17034. targetFunctionName.Remove(0, 1);
  17035. //TODO: We removed this... Messed up with PrimStruct 'this' non-mut errors
  17036. // 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
  17037. /*if (thisValue)
  17038. {
  17039. if ((!thisValue.mType->IsGenericParam()) && (!thisValue.IsSplat()) && (!thisValue.mType->IsVar()))
  17040. thisValue = MakeCallableTarget(target, thisValue);
  17041. }*/
  17042. int methodCount = 0;
  17043. bool mayBeSkipCall = false;
  17044. bool mayBeComptimeCall = false;
  17045. BfTypeInstance* checkTypeInst = NULL;
  17046. if (thisValue.mType != NULL)
  17047. {
  17048. if (thisValue.mType->IsAllocType())
  17049. thisValue.mType = thisValue.mType->GetUnderlyingType();
  17050. checkTypeInst = thisValue.mType->ToTypeInstance();
  17051. }
  17052. else if (allowImplicitThis)
  17053. {
  17054. checkTypeInst = mModule->mCurTypeInstance;
  17055. }
  17056. while (checkTypeInst != NULL)
  17057. {
  17058. checkTypeInst->mTypeDef->PopulateMemberSets();
  17059. BfMemberSetEntry* memberSetEntry;
  17060. if (checkTypeInst->mTypeDef->mMethodSet.TryGetWith(targetFunctionName, &memberSetEntry))
  17061. {
  17062. BfMethodDef* methodDef = (BfMethodDef*)memberSetEntry->mMemberDef;
  17063. while (methodDef != NULL)
  17064. {
  17065. if (methodDef->mIsSkipCall)
  17066. mayBeSkipCall = true;
  17067. if (methodDef->mHasComptime)
  17068. mayBeComptimeCall = true;
  17069. methodDef = methodDef->mNextWithSameName;
  17070. }
  17071. }
  17072. checkTypeInst = checkTypeInst->mBaseType;
  17073. }
  17074. SizedArray<BfExpression*, 8> copiedArgs;
  17075. for (BfExpression* arg : args)
  17076. copiedArgs.push_back(arg);
  17077. BfSizedArray<BfExpression*> sizedCopiedArgs(copiedArgs);
  17078. BfResolvedArgs argValues(&sizedCopiedArgs);
  17079. if (mModule->mParentNodeEntry != NULL)
  17080. {
  17081. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  17082. {
  17083. argValues.mOpenToken = invocationExpr->mOpenParen;
  17084. argValues.mCommas = &invocationExpr->mCommas;
  17085. argValues.mCloseToken = invocationExpr->mCloseParen;
  17086. }
  17087. }
  17088. BfResolveArgsFlags resolveArgsFlags = (BfResolveArgsFlags)(BfResolveArgsFlag_DeferFixits | BfResolveArgsFlag_AllowUnresolvedTypes);
  17089. resolveArgsFlags = (BfResolveArgsFlags)(resolveArgsFlags | BfResolveArgsFlag_DeferParamEval);
  17090. if ((mayBeSkipCall) || (mayBeComptimeCall))
  17091. resolveArgsFlags = (BfResolveArgsFlags)(resolveArgsFlags | BfResolveArgsFlag_DeferParamValues);
  17092. static int sCallIdx = 0;
  17093. sCallIdx++;
  17094. int callIdx = sCallIdx;
  17095. if (callIdx == 1557)
  17096. {
  17097. NOP;
  17098. }
  17099. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  17100. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  17101. {
  17102. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  17103. {
  17104. checkedKind = BfCheckedKind_Checked;
  17105. mModule->mAttributeState->mUsed = true;
  17106. }
  17107. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  17108. {
  17109. checkedKind = BfCheckedKind_Unchecked;
  17110. mModule->mAttributeState->mUsed = true;
  17111. }
  17112. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoStaticCtorAttributeTypeDef))
  17113. {
  17114. mModule->mAttributeState->mUsed = true;
  17115. }
  17116. }
  17117. if ((isCascade) && (cascadeOperatorToken != NULL) && ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0))
  17118. mModule->Fail("Cascade operator cannot be used in const evaluation", cascadeOperatorToken);
  17119. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, mUsedAsStatement || isCascade);
  17120. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlags(mBfEvalExprFlags);
  17121. if (isCascade)
  17122. {
  17123. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_InCascade);
  17124. thisValue = mModule->MakeAddressable(thisValue);
  17125. }
  17126. if (((mayBeComptimeCall) && (!mModule->mIsComptimeModule) && (!mModule->mBfIRBuilder->mIgnoreWrites)) ||
  17127. ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mConstEvalAttributeTypeDef))))
  17128. {
  17129. resolveArgsFlags = (BfResolveArgsFlags)(resolveArgsFlags | BfResolveArgsFlag_DeferParamEval | BfResolveArgsFlag_DeferStrings);
  17130. }
  17131. ResolveArgValues(argValues, resolveArgsFlags);
  17132. //
  17133. {
  17134. // We also apply this right before the actual call, but we need to set the comptime flag earlier
  17135. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlag(mBfEvalExprFlags);
  17136. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mConstEvalAttributeTypeDef)))
  17137. {
  17138. mModule->mAttributeState->mUsed = true;
  17139. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  17140. }
  17141. mResult = MatchMethod(methodNodeSrc, methodBoundExpr, thisValue, allowImplicitThis, bypassVirtual, targetFunctionName, argValues, methodGenericArgs, checkedKind);
  17142. }
  17143. argValues.HandleFixits(mModule);
  17144. if (mModule->mAttributeState == &attributeState)
  17145. mModule->FinishAttributeState(&attributeState);
  17146. if (isCascade)
  17147. {
  17148. if ((outCascadeValue != NULL) && (thisValue.mValue))
  17149. {
  17150. *outCascadeValue = thisValue;
  17151. }
  17152. else
  17153. {
  17154. mModule->Fail("Invalid use of cascade operator", cascadeOperatorToken);
  17155. }
  17156. }
  17157. }
  17158. void BfExprEvaluator::Visit(BfInvocationExpression* invocationExpr)
  17159. {
  17160. DoInvocation(invocationExpr);
  17161. }
  17162. void BfExprEvaluator::DoInvocation(BfInvocationExpression* invocationExpr)
  17163. {
  17164. BfAutoParentNodeEntry autoParentNodeEntry(mModule, invocationExpr);
  17165. // We need to check for sized array constructor like "uint8[2](1, 2)"
  17166. if (BfNodeDynCastExact<BfIndexerExpression>(invocationExpr->mTarget) != NULL)
  17167. {
  17168. auto checkTarget = invocationExpr->mTarget;
  17169. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  17170. {
  17171. checkTarget = indexerExpr->mTarget;
  17172. }
  17173. auto resolvedType = mModule->ResolveTypeRef(checkTarget, NULL, BfPopulateType_Identity, BfResolveTypeRefFlag_IgnoreLookupError);
  17174. if (resolvedType != NULL)
  17175. {
  17176. BfType* curType = resolvedType;
  17177. auto checkTarget = invocationExpr->mTarget;
  17178. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  17179. {
  17180. checkTarget = indexerExpr->mTarget;
  17181. if (indexerExpr->mCommas.size() != 0)
  17182. 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]);
  17183. int arrSize = 0;
  17184. BfTypeState typeState;
  17185. typeState.mArrayInitializerSize = (int)invocationExpr->mArguments.size();
  17186. SetAndRestoreValue<BfTypeState*> prevTypeState(mModule->mContext->mCurTypeState, &typeState);
  17187. if (indexerExpr->mArguments.size() != 0)
  17188. {
  17189. BfConstResolver constResolver(mModule);
  17190. auto arg = indexerExpr->mArguments[0];
  17191. constResolver.mExpectingType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  17192. if (arg != NULL)
  17193. constResolver.Resolve(arg, NULL, BfConstResolveFlag_ArrayInitSize);
  17194. if (constResolver.mResult.mValue.IsConst())
  17195. {
  17196. auto constant = mModule->mBfIRBuilder->GetConstant(constResolver.mResult.mValue);
  17197. if ((mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 >= 0))
  17198. {
  17199. arrSize = constant->mInt32;
  17200. }
  17201. else
  17202. mModule->Fail("Non-negative integer expected", indexerExpr->mArguments[0]);
  17203. }
  17204. }
  17205. else
  17206. arrSize = invocationExpr->mArguments.size();
  17207. curType = mModule->CreateSizedArrayType(curType, arrSize);
  17208. }
  17209. InitializedSizedArray((BfSizedArrayType*)curType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen, NULL);
  17210. return;
  17211. }
  17212. }
  17213. auto autoComplete = GetAutoComplete();
  17214. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  17215. if (autoComplete != NULL)
  17216. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  17217. mModule->UpdateExprSrcPos(invocationExpr);
  17218. BfMethodGenericArguments methodGenericArgs;
  17219. if (invocationExpr->mGenericArgs != NULL)
  17220. {
  17221. methodGenericArgs.mArguments = &invocationExpr->mGenericArgs->mGenericArgs;
  17222. if ((!invocationExpr->mGenericArgs->mCommas.IsEmpty()) && (invocationExpr->mGenericArgs->mCommas.back()->mToken == BfToken_DotDotDot))
  17223. {
  17224. methodGenericArgs.mIsOpen = true;
  17225. methodGenericArgs.mIsPartial = true;
  17226. }
  17227. for (int i = 0; i < (int)methodGenericArgs.mArguments->mSize; i++)
  17228. if (BfNodeIsA<BfUninitializedExpression>((*methodGenericArgs.mArguments)[i]))
  17229. methodGenericArgs.mIsPartial = true;
  17230. }
  17231. SizedArray<BfExpression*, 8> copiedArgs;
  17232. for (BfExpression* arg : invocationExpr->mArguments)
  17233. copiedArgs.push_back(arg);
  17234. BfTypedValue cascadeValue;
  17235. DoInvocation(invocationExpr->mTarget, invocationExpr, copiedArgs, methodGenericArgs, &cascadeValue);
  17236. if (autoComplete != NULL)
  17237. {
  17238. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  17239. {
  17240. if (autoComplete->mMethodMatchInfo != NULL)
  17241. autoComplete->mIsCapturingMethodMatchInfo = true;
  17242. else
  17243. autoComplete->mIsCapturingMethodMatchInfo = false;
  17244. //BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  17245. }
  17246. else
  17247. autoComplete->mIsCapturingMethodMatchInfo = false;
  17248. }
  17249. /// Previous check for discard
  17250. if (cascadeValue)
  17251. mResult = cascadeValue;
  17252. }
  17253. BfMethodDef* BfExprEvaluator::GetPropertyMethodDef(BfPropertyDef* propDef, BfMethodType methodType, BfCheckedKind checkedKind, BfTypedValue propTarget)
  17254. {
  17255. bool allowMut = true;
  17256. if ((propTarget) && (propTarget.mType->IsValueType()))
  17257. {
  17258. if (propTarget.IsReadOnly())
  17259. {
  17260. allowMut = false;
  17261. }
  17262. else if (!propTarget.IsAddr())
  17263. {
  17264. mModule->PopulateType(propTarget.mType);
  17265. if (!propTarget.IsValuelessType())
  17266. allowMut = false;
  17267. }
  17268. }
  17269. int bestPri = -1000;
  17270. BfMethodDef* matchedMethod = NULL;
  17271. for (auto methodDef : propDef->mMethods)
  17272. {
  17273. if (methodDef->mMethodType != methodType)
  17274. continue;
  17275. int curPri = 0;
  17276. if (methodDef->mCheckedKind == checkedKind)
  17277. {
  17278. curPri = 5;
  17279. }
  17280. else if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  17281. curPri = 3;
  17282. else
  17283. curPri = 1;
  17284. if (methodDef->mIsMutating)
  17285. {
  17286. if (allowMut)
  17287. curPri++;
  17288. else
  17289. curPri -= 10;
  17290. }
  17291. if (curPri > bestPri)
  17292. {
  17293. bestPri = curPri;
  17294. matchedMethod = methodDef;
  17295. }
  17296. }
  17297. return matchedMethod;
  17298. /*BfMethodDef* matchedMethod = NULL;
  17299. BfMethodDef* backupMethod = NULL;
  17300. for (auto methodDef : propDef->mMethods)
  17301. {
  17302. if (methodDef->mMethodType != methodType)
  17303. continue;
  17304. if (methodDef->mCheckedKind == checkedKind)
  17305. {
  17306. matchedMethod = methodDef;
  17307. break;
  17308. }
  17309. if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  17310. matchedMethod = methodDef;
  17311. else
  17312. backupMethod = methodDef;
  17313. }
  17314. if (matchedMethod == NULL)
  17315. matchedMethod = backupMethod;
  17316. return matchedMethod;*/
  17317. }
  17318. BfModuleMethodInstance BfExprEvaluator::GetPropertyMethodInstance(BfMethodDef* methodDef)
  17319. {
  17320. if (mPropDefBypassVirtual)
  17321. {
  17322. if (mPropTarget.mType->IsInterface())
  17323. {
  17324. auto curTypeInst = mPropTarget.mType->ToTypeInstance();
  17325. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  17326. {
  17327. if (methodDef->mBody != NULL)
  17328. {
  17329. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  17330. mPropTarget = mModule->GetThis();
  17331. return mModule->GetMethodInstance(mModule->mCurTypeInstance, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_ForeignMethodDef, curTypeInst);
  17332. }
  17333. }
  17334. else
  17335. {
  17336. mModule->Fail("Property is not implemented by this type", mPropSrc);
  17337. return BfModuleMethodInstance();
  17338. }
  17339. }
  17340. else
  17341. {
  17342. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  17343. mModule->PopulateType(propTypeInst, BfPopulateType_DataAndMethods);
  17344. auto rawMethodInstance = mModule->GetRawMethodInstance(propTypeInst, methodDef);
  17345. if (rawMethodInstance->mVirtualTableIdx == -1)
  17346. {
  17347. if (!mModule->mCompiler->mIsResolveOnly)
  17348. {
  17349. // ResolveOnly does not force methods to slot
  17350. BF_ASSERT(rawMethodInstance->mVirtualTableIdx != -1);
  17351. mModule->Fail(StrFormat("Failed to devirtualize %s", mModule->MethodToString(rawMethodInstance).c_str()));
  17352. }
  17353. }
  17354. else
  17355. {
  17356. auto useTypeInst = mOrigPropTarget.mType->ToTypeInstance();
  17357. auto virtualMethod = (BfMethodInstance*)useTypeInst->mVirtualMethodTable[rawMethodInstance->mVirtualTableIdx].mImplementingMethod;
  17358. return mModule->ReferenceExternalMethodInstance(virtualMethod);
  17359. }
  17360. }
  17361. }
  17362. if ((mOrigPropTarget) && (mOrigPropTarget.mType != mPropTarget.mType) &&
  17363. ((!mOrigPropTarget.mType->IsGenericParam()) && (mPropTarget.mType->IsInterface())))
  17364. {
  17365. auto checkType = mOrigPropTarget.mType;
  17366. if ((checkType->IsNullable()) && (!mPropTarget.mType->IsNullable()))
  17367. checkType = checkType->GetUnderlyingType();
  17368. if (checkType->IsPointer())
  17369. checkType = ((BfPointerType*)checkType)->mElementType;
  17370. if (checkType->IsWrappableType())
  17371. checkType = mModule->GetWrappedStructType(checkType);
  17372. if ((checkType != NULL) && (checkType->IsTypeInstance()))
  17373. {
  17374. auto activeTypeDef = mModule->GetActiveTypeDef(NULL, false, true);
  17375. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  17376. bool checkedUnderlying = false;
  17377. auto checkTypeInst = checkType->ToTypeInstance();
  17378. while (checkTypeInst != NULL)
  17379. {
  17380. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  17381. BF_ASSERT((checkTypeInst->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || (mModule->mCompiler->IsAutocomplete()));
  17382. if (checkTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotted)
  17383. break;
  17384. for (auto& iface : checkTypeInst->mInterfaces)
  17385. {
  17386. if (!mModule->IsInSpecializedSection())
  17387. {
  17388. if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  17389. continue;
  17390. }
  17391. if (iface.mInterfaceType == mPropTarget.mType)
  17392. {
  17393. if (bestIFaceEntry == NULL)
  17394. {
  17395. bestIFaceEntry = &iface;
  17396. continue;
  17397. }
  17398. bool isBetter;
  17399. bool isWorse;
  17400. mModule->CompareDeclTypes(NULL, iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  17401. if (isBetter == isWorse)
  17402. {
  17403. // Failed
  17404. }
  17405. else
  17406. {
  17407. if (isBetter)
  17408. bestIFaceEntry = &iface;
  17409. }
  17410. }
  17411. }
  17412. if (bestIFaceEntry != NULL)
  17413. break;
  17414. checkTypeInst = checkTypeInst->mBaseType;
  17415. if (checkTypeInst == NULL)
  17416. {
  17417. if (!checkedUnderlying)
  17418. {
  17419. checkedUnderlying = true;
  17420. if (checkType->HasWrappedRepresentation())
  17421. {
  17422. auto underlyingType = checkType->GetUnderlyingType();
  17423. if (underlyingType != NULL)
  17424. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  17425. }
  17426. }
  17427. }
  17428. }
  17429. if (bestIFaceEntry != NULL)
  17430. {
  17431. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + methodDef->mIdx];
  17432. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  17433. if (bestMethodInstance != NULL)
  17434. {
  17435. mPropTarget = mOrigPropTarget;
  17436. //mPropTarget.mType = checkTypeInst;
  17437. //mPropTarget = mModule->Cast( mOrigPropTarget, checkTypeInst);
  17438. return mModule->GetMethodInstanceAtIdx(ifaceMethodEntry.mMethodRef.mTypeInstance, ifaceMethodEntry.mMethodRef.mMethodNum);
  17439. }
  17440. }
  17441. }
  17442. mModule->AssertErrorState();
  17443. return BfModuleMethodInstance();
  17444. }
  17445. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  17446. if (propTypeInst == NULL)
  17447. {
  17448. propTypeInst = mModule->GetWrappedStructType(mPropTarget.mType);
  17449. }
  17450. if (propTypeInst == NULL)
  17451. {
  17452. mModule->Fail("INTERNAL ERROR: Invalid property target", mPropSrc);
  17453. return BfModuleMethodInstance();
  17454. }
  17455. BF_ASSERT(propTypeInst->mTypeDef->mFullNameEx == methodDef->mDeclaringType->mFullNameEx);
  17456. return mModule->GetMethodInstance(propTypeInst, methodDef, BfTypeVector(), mPropGetMethodFlags);
  17457. }
  17458. void BfExprEvaluator::CheckPropFail(BfMethodDef* propMethodDef, BfMethodInstance* methodInstance, bool checkProt)
  17459. {
  17460. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  17461. // If mExplicitInterface is null then we are implicitly calling through an interface
  17462. if ((checkProt) && (propTypeInst != NULL) && (methodInstance->GetExplicitInterface() == NULL) &&
  17463. (!mModule->CheckAccessMemberProtection(propMethodDef->mProtection, propTypeInst)))
  17464. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(methodInstance).c_str()), mPropSrc);
  17465. else if (mPropCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  17466. {
  17467. bool passes = true;
  17468. if (mPropCheckedKind != BfCheckedKind_NotSet)
  17469. {
  17470. passes = false;
  17471. }
  17472. else
  17473. {
  17474. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  17475. if (defaultCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  17476. passes = false;
  17477. }
  17478. if (!passes)
  17479. {
  17480. 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);
  17481. if (error != NULL)
  17482. {
  17483. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  17484. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  17485. }
  17486. }
  17487. }
  17488. }
  17489. bool BfExprEvaluator::HasResult()
  17490. {
  17491. return (mResult) || (mPropDef != NULL);
  17492. }
  17493. BfTypedValue BfExprEvaluator::GetResult(bool clearResult, bool resolveGenericType)
  17494. {
  17495. if ((!mResult) && (mPropDef != NULL))
  17496. {
  17497. bool handled = false;
  17498. if (mPropTarget.mType->IsGenericTypeInstance())
  17499. {
  17500. auto genericTypeInst = (BfTypeInstance*)mPropTarget.mType;
  17501. if (genericTypeInst->IsInstanceOf(mModule->mCompiler->mSizedArrayTypeDef))
  17502. {
  17503. if (mPropDef->mName == "Count")
  17504. {
  17505. auto sizedType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[1];
  17506. if (sizedType->IsConstExprValue())
  17507. {
  17508. auto constExprType = (BfConstExprValueType*)sizedType;
  17509. mResult = BfTypedValue(mModule->GetConstValue(constExprType->mValue.mInt64), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  17510. handled = true;
  17511. }
  17512. else
  17513. {
  17514. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  17515. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_IntPtr)), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  17516. handled = true;
  17517. }
  17518. }
  17519. }
  17520. }
  17521. if (!handled)
  17522. {
  17523. SetAndRestoreValue<BfFunctionBindResult*> prevFunctionBindResult(mFunctionBindResult, NULL);
  17524. SetAndRestoreValue<BfAstNode*> prevDeferCallRef(mDeferCallRef, NULL);
  17525. BfMethodDef* matchedMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  17526. if (matchedMethod == NULL)
  17527. {
  17528. mModule->Fail("Property has no getter", mPropSrc);
  17529. return mResult;
  17530. }
  17531. auto methodInstance = GetPropertyMethodInstance(matchedMethod);
  17532. if (methodInstance.mMethodInstance == NULL)
  17533. return mResult;
  17534. BF_ASSERT(methodInstance.mMethodInstance->mMethodDef->mName == matchedMethod->mName);
  17535. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  17536. {
  17537. BF_ASSERT(!methodInstance.mFunc.IsFake());
  17538. }
  17539. if (mPropSrc != NULL)
  17540. mModule->UpdateExprSrcPos(mPropSrc);
  17541. auto autoComplete = GetAutoComplete();
  17542. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(mPropSrc)) && (autoComplete->mResolveType == BfResolveType_GetResultString))
  17543. {
  17544. autoComplete->mResultString = ":";
  17545. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->mReturnType);
  17546. autoComplete->mResultString += " ";
  17547. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetOwner());
  17548. autoComplete->mResultString += ".";
  17549. autoComplete->mResultString += mPropDef->mName;
  17550. }
  17551. CheckPropFail(matchedMethod, methodInstance.mMethodInstance, (mPropGetMethodFlags & BfGetMethodInstanceFlag_Friend) == 0);
  17552. PerformCallChecks(methodInstance.mMethodInstance, mPropSrc);
  17553. if (methodInstance.mMethodInstance->IsSkipCall())
  17554. {
  17555. mResult = mModule->GetDefaultTypedValue(methodInstance.mMethodInstance->mReturnType);
  17556. }
  17557. else
  17558. {
  17559. SizedArray<BfIRValue, 4> args;
  17560. if (!matchedMethod->mIsStatic)
  17561. {
  17562. auto owner = methodInstance.mMethodInstance->GetOwner();
  17563. bool isTypeMatch = mPropTarget.mType == owner;
  17564. if (owner->IsTypedPrimitive())
  17565. isTypeMatch |= mPropTarget.mType == owner->GetUnderlyingType();
  17566. if ((!isTypeMatch) ||
  17567. ((mPropTarget.mValue.IsFake()) && (!mOrigPropTarget.mValue.IsFake())))
  17568. {
  17569. auto prevPropTarget = mPropTarget;
  17570. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, owner);
  17571. if (!mPropTarget)
  17572. {
  17573. mModule->Fail("Internal property error", mPropSrc);
  17574. return BfTypedValue();
  17575. }
  17576. }
  17577. if ((mPropGetMethodFlags & BfGetMethodInstanceFlag_DisableObjectAccessChecks) == 0)
  17578. mModule->EmitObjectAccessCheck(mPropTarget);
  17579. }
  17580. auto callFlags = mPropDefBypassVirtual ? BfCreateCallFlags_BypassVirtual : BfCreateCallFlags_None;
  17581. mResult = CreateCall(mPropSrc, mPropTarget, mOrigPropTarget, matchedMethod, methodInstance, callFlags, mIndexerValues, NULL);
  17582. }
  17583. }
  17584. mPropDef = NULL;
  17585. mPropDefBypassVirtual = false;
  17586. mIndexerValues.clear();
  17587. mResultLocalVar = NULL;
  17588. mResultFieldInstance = NULL;
  17589. }
  17590. if (resolveGenericType)
  17591. ResolveGenericType();
  17592. BfTypedValue result = mResult;
  17593. if (clearResult)
  17594. mResult = BfTypedValue();
  17595. return result;
  17596. }
  17597. void BfExprEvaluator::CheckResultForReading(BfTypedValue& typedValue)
  17598. {
  17599. if (mModule->mCurMethodState == NULL)
  17600. return;
  17601. if ((mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCurMethodState->mAllowUinitReads))
  17602. return;
  17603. if ((mModule->mCurTypeInstance->mResolvingVarField) || (mModule->mCurTypeInstance->mResolvingConstField))
  17604. return;
  17605. if ((typedValue) && (typedValue.IsAddr()))
  17606. {
  17607. if ((mResultLocalVar != NULL) && (mResultLocalVarRefNode != NULL))
  17608. {
  17609. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors);
  17610. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  17611. {
  17612. // These errors can only be detected during capture time, so we don't ignore them on this pass
  17613. mModule->mIgnoreErrors = false;
  17614. }
  17615. int fieldIdx = mResultLocalVarField - 1;
  17616. auto localVar = mResultLocalVar;
  17617. /*if (localVar->mCompositeCount > 0)
  17618. {
  17619. mModule->Fail(StrFormat("Cannot read from composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  17620. typedValue = BfTypedValue();
  17621. return;
  17622. }*/
  17623. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  17624. {
  17625. mModule->TryLocalVariableInit(localVar);
  17626. }
  17627. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  17628. {
  17629. auto methodStateForLocal = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  17630. bool isAssigned = false;
  17631. int64 undefinedFieldFlags = localVar->mUnassignedFieldFlags;
  17632. auto deferredLocalAssignData = methodStateForLocal->mDeferredLocalAssignData;
  17633. while ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mIsChained))
  17634. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  17635. if (deferredLocalAssignData != NULL)
  17636. {
  17637. for (auto& assignedVar : deferredLocalAssignData->mAssignedLocals)
  17638. {
  17639. auto assignedLocal = assignedVar.mLocalVar;
  17640. if (assignedLocal == localVar)
  17641. {
  17642. int assignedFieldIdx = assignedVar.mLocalVarField;
  17643. if (assignedFieldIdx >= 0)
  17644. undefinedFieldFlags &= ~((int64)1 << assignedFieldIdx);
  17645. else
  17646. undefinedFieldFlags = 0;
  17647. }
  17648. }
  17649. if (deferredLocalAssignData->mLeftBlockUncond)
  17650. isAssigned = true;
  17651. }
  17652. if (fieldIdx == -1)
  17653. {
  17654. if (undefinedFieldFlags == 0)
  17655. isAssigned = true;
  17656. }
  17657. else
  17658. {
  17659. isAssigned = true;
  17660. for (int i = 0; i < mResultLocalVarFieldCount; i++)
  17661. if ((undefinedFieldFlags & (1LL << (fieldIdx + i))) != 0)
  17662. isAssigned = false;
  17663. }
  17664. if (!isAssigned)
  17665. {
  17666. if ((localVar->mIsThis) && (fieldIdx != -1))
  17667. {
  17668. // When we have initializers for fields, they won't all be processed in the autocomplte case
  17669. if (!mModule->mCompiler->IsAutocomplete())
  17670. {
  17671. auto bfError = mModule->Fail(StrFormat("Use of possibly unassigned field '%s'", mResultLocalVarRefNode->ToString().c_str()), mResultLocalVarRefNode, true);
  17672. }
  17673. }
  17674. else
  17675. {
  17676. mModule->Fail(StrFormat("Use of unassigned local variable '%s'", localVar->mName.c_str()), mResultLocalVarRefNode);
  17677. }
  17678. }
  17679. }
  17680. localVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  17681. }
  17682. }
  17683. }
  17684. void BfExprEvaluator::FinishExpressionResult()
  17685. {
  17686. CheckResultForReading(mResult);
  17687. mResultLocalVar = NULL;
  17688. mResultFieldInstance = NULL;
  17689. }
  17690. bool BfExprEvaluator::CheckAllowValue(const BfTypedValue& typedValue, BfAstNode* refNode)
  17691. {
  17692. return true;
  17693. }
  17694. void BfExprEvaluator::MarkResultUsed()
  17695. {
  17696. if (mResultLocalVar != NULL)
  17697. {
  17698. mResultLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  17699. }
  17700. }
  17701. void BfExprEvaluator::MarkResultAssigned()
  17702. {
  17703. if (mResultLocalVar != NULL)
  17704. {
  17705. //int localIdx = mResultLocalVarIdx;
  17706. //if (localIdx == 0x7FFF)
  17707. //return;
  17708. auto localVar = mResultLocalVar;
  17709. int fieldIdx = mResultLocalVarField - 1;
  17710. int count = mResultLocalVarFieldCount;
  17711. if (fieldIdx == -1)
  17712. count = 1;
  17713. for (int i = 0; i < count; i++)
  17714. mModule->mCurMethodState->GetMethodStateForLocal(localVar)->LocalDefined(localVar, fieldIdx + i);
  17715. //if (localIdx != 0x7FFF)
  17716. {
  17717. if (localVar->mCompositeCount > 0)
  17718. {
  17719. mModule->Fail(StrFormat("Cannot write to composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  17720. }
  17721. }
  17722. }
  17723. }
  17724. void BfExprEvaluator::MakeResultAsValue()
  17725. {
  17726. // Expressions like parens will turn a variable reference into a simple value
  17727. mResultLocalVar = NULL;
  17728. mResultFieldInstance = NULL;
  17729. }
  17730. bool BfExprEvaluator::CheckIsBase(BfAstNode* checkNode)
  17731. {
  17732. if (checkNode == NULL)
  17733. return false;
  17734. if (!checkNode->Equals("base"))
  17735. return false;
  17736. auto autoComplete = GetAutoComplete();
  17737. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(checkNode)))
  17738. {
  17739. if ((mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->mBaseType != NULL))
  17740. autoComplete->SetDefinitionLocation(mModule->mCurTypeInstance->mBaseType->mTypeDef->GetRefNode());
  17741. }
  17742. return true;
  17743. }
  17744. bool BfExprEvaluator::CheckModifyResult(BfTypedValue& typedVal, BfAstNode* refNode, const char* modifyType, bool onlyNeedsMut, bool emitWarning, bool skipCopyOnMutate)
  17745. {
  17746. if (typedVal.mType->IsVar())
  17747. {
  17748. // Allow without error
  17749. return true;
  17750. }
  17751. BfLocalVariable* localVar = NULL;
  17752. bool isCapturedLocal = false;
  17753. if (mResultLocalVar != NULL)
  17754. {
  17755. localVar = mResultLocalVar;
  17756. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  17757. }
  17758. else if (typedVal.IsThis())
  17759. {
  17760. localVar = mModule->GetThisVariable();
  17761. }
  17762. else if (typedVal.IsSplat())
  17763. {
  17764. for (auto checkLocal : mModule->mCurMethodState->mLocals)
  17765. {
  17766. if (checkLocal->mAddr == typedVal.mValue)
  17767. {
  17768. localVar = checkLocal;
  17769. break;
  17770. }
  17771. }
  17772. }
  17773. else if (typedVal.mValue.IsArg())
  17774. {
  17775. auto methodState = mModule->mCurMethodState->GetNonCaptureState();
  17776. localVar = methodState->mLocals[typedVal.mValue.mId];
  17777. }
  17778. if ((typedVal.mKind == BfTypedValueKind_MutableValue) && (onlyNeedsMut))
  17779. {
  17780. return true;
  17781. }
  17782. bool canModify = typedVal.CanModify();
  17783. if (((typedVal.mKind == BfTypedValueKind_TempAddr) || (typedVal.mKind == BfTypedValueKind_CopyOnMutateAddr_Derived)) &&
  17784. (strcmp(modifyType, "assign to") == 0))
  17785. mModule->Warn(0, "Assigning to temporary copy of a value. Consider using 'ref' in value source declaration.", refNode);
  17786. auto _Fail = [&](const StringImpl& error, BfAstNode* refNode)
  17787. {
  17788. if (emitWarning)
  17789. return mModule->Warn(BfWarning_BF4204_AddressOfReadOnly, error, refNode);
  17790. else
  17791. return mModule->Fail(error, refNode);
  17792. };
  17793. if (localVar != NULL)
  17794. {
  17795. if (!canModify)
  17796. {
  17797. BfError* error = NULL;
  17798. if (localVar->mIsThis)
  17799. {
  17800. bool isClosure = false;
  17801. BfTypeInstance* checkTypeInst = localVar->mResolvedType->ToTypeInstance();
  17802. int fieldIdx = mResultLocalVarField - 1;
  17803. if ((!isCapturedLocal) && (mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mClosureType != NULL))
  17804. {
  17805. isClosure = true;
  17806. auto closureThis = mModule->mCurMethodState->mClosureState->mClosureType;
  17807. closureThis = checkTypeInst->mFieldInstances[0].mResolvedType->ToTypeInstance();
  17808. if (fieldIdx >= -1)
  17809. {
  17810. checkTypeInst = closureThis;
  17811. }
  17812. else
  17813. {
  17814. fieldIdx = -fieldIdx - 2;
  17815. isCapturedLocal = true;
  17816. }
  17817. }
  17818. if (fieldIdx < 0)
  17819. {
  17820. if (isClosure)
  17821. {
  17822. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  17823. error = _Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType), refNode);
  17824. else
  17825. error = _Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType), refNode);
  17826. }
  17827. else if (localVar->mResolvedType->IsValueType())
  17828. {
  17829. error = _Fail(StrFormat("Cannot %s 'this' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  17830. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17831. }
  17832. else
  17833. {
  17834. error = _Fail(StrFormat("Cannot %s 'this' because '%s' is a reference type.", modifyType,
  17835. mModule->TypeToString(localVar->mResolvedType).c_str()), refNode);
  17836. }
  17837. return false;
  17838. }
  17839. else if (mResultFieldInstance != NULL)
  17840. {
  17841. if (isCapturedLocal)
  17842. {
  17843. 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,
  17844. mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  17845. }
  17846. else if (isClosure)
  17847. {
  17848. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  17849. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType,
  17850. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  17851. else
  17852. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType,
  17853. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  17854. }
  17855. else if (mResultFieldInstance->GetFieldDef()->mIsReadOnly)
  17856. {
  17857. error = _Fail(StrFormat("Cannot %s readonly field '%s.%s' within method '%s'", modifyType,
  17858. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  17859. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17860. }
  17861. else if (mResultFieldInstance->GetFieldDef()->mIsAppend)
  17862. {
  17863. error = _Fail(StrFormat("Cannot %s append field '%s.%s' within method '%s'", modifyType,
  17864. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  17865. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17866. }
  17867. else if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(mResultFieldInstance->GetFieldDef()->mFieldDeclaration))
  17868. {
  17869. String propNam;
  17870. if (propertyDeclaration->mNameNode != NULL)
  17871. propertyDeclaration->mNameNode->ToString(propNam);
  17872. error = _Fail(StrFormat("Cannot %s auto-implemented property '%s.%s' without set accessor", modifyType,
  17873. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), propNam.c_str()), refNode);
  17874. }
  17875. else
  17876. {
  17877. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  17878. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  17879. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17880. }
  17881. return false;
  17882. }
  17883. }
  17884. else if (localVar->IsParam())
  17885. {
  17886. if (!mModule->mCurMethodInstance->IsMixin())
  17887. {
  17888. if (mModule->mCurMethodState->mMixinState != NULL)
  17889. {
  17890. error = _Fail(StrFormat("Cannot %s mixin parameter '%s'", modifyType,
  17891. localVar->mName.c_str()), refNode);
  17892. }
  17893. else if ((onlyNeedsMut) && (localVar->mResolvedType != NULL) && (localVar->mResolvedType->IsGenericParam()))
  17894. {
  17895. if (emitWarning)
  17896. 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.",
  17897. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  17898. else
  17899. 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,
  17900. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  17901. }
  17902. else
  17903. {
  17904. if (emitWarning)
  17905. 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.",
  17906. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  17907. else
  17908. error = _Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'ref' specifier to parameter or declaring 'var %s;' to create a mutable copy.", modifyType,
  17909. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  17910. }
  17911. return false;
  17912. }
  17913. }
  17914. else
  17915. {
  17916. if ((mResultLocalVarField != 0) && (!localVar->mIsReadOnly))
  17917. {
  17918. auto typeInst = localVar->mResolvedType->ToTypeInstance();
  17919. int dataIdx = mResultLocalVarField - 1;
  17920. if (typeInst != NULL)
  17921. {
  17922. for (auto& field : typeInst->mFieldInstances)
  17923. {
  17924. if (field.mDataIdx == dataIdx)
  17925. {
  17926. error = _Fail(StrFormat("Cannot %s readonly field '%s.%s'.", modifyType,
  17927. mModule->TypeToString(typeInst).c_str(),
  17928. field.GetFieldDef()->mName.c_str()), refNode);
  17929. break;
  17930. }
  17931. }
  17932. }
  17933. }
  17934. if (error == NULL)
  17935. {
  17936. error = _Fail(StrFormat("Cannot %s read-only local variable '%s'.", modifyType,
  17937. localVar->mName.c_str()), refNode);
  17938. }
  17939. return false;
  17940. }
  17941. }
  17942. else
  17943. {
  17944. // When we are capturing, we need to note that we require capturing by reference here
  17945. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  17946. }
  17947. }
  17948. if ((mResultFieldInstance != NULL) && (mResultFieldInstance->GetFieldDef()->mIsReadOnly) && (!canModify))
  17949. {
  17950. auto error = _Fail(StrFormat("Cannot %s static readonly field '%s.%s' within method '%s'", modifyType,
  17951. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  17952. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17953. return false;
  17954. }
  17955. if ((!skipCopyOnMutate) && (typedVal.IsCopyOnMutate()))
  17956. typedVal = mModule->CopyValue(typedVal);
  17957. if ((emitWarning) && (typedVal.IsReadOnly()))
  17958. {
  17959. mModule->Warn(0, StrFormat("Cannot %s read-only variable", modifyType), refNode);
  17960. return true;
  17961. }
  17962. return mModule->CheckModifyValue(typedVal, refNode, modifyType);
  17963. }
  17964. void BfExprEvaluator::Visit(BfConditionalExpression* condExpr)
  17965. {
  17966. static int sCallCount = 0;
  17967. sCallCount++;
  17968. auto condResult = mModule->CreateValueFromExpression(condExpr->mConditionExpression, mModule->GetPrimitiveType(BfTypeCode_Boolean), (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  17969. if (!condResult)
  17970. return;
  17971. if (condExpr->mTrueExpression == NULL)
  17972. {
  17973. mModule->AssertErrorState();
  17974. return;
  17975. }
  17976. if (condExpr->mFalseExpression == NULL)
  17977. {
  17978. mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, BfEvalExprFlags_NoCast);
  17979. mModule->AssertErrorState();
  17980. return;
  17981. }
  17982. bool isConstBranch = false;
  17983. bool constResult = false;
  17984. bool constResultUndef = false;
  17985. if (condResult.mValue.IsConst())
  17986. {
  17987. auto constValue = mModule->mBfIRBuilder->GetConstant(condResult.mValue);
  17988. if (constValue->mTypeCode == BfTypeCode_Boolean)
  17989. {
  17990. isConstBranch = true;
  17991. constResult = constValue->mBool;
  17992. }
  17993. else if (constValue->mConstType == BfConstType_Undef)
  17994. {
  17995. isConstBranch = true;
  17996. constResultUndef = true;
  17997. }
  17998. }
  17999. if (isConstBranch)
  18000. {
  18001. BfExpression* actualExpr = (constResult) ? condExpr->mTrueExpression : condExpr->mFalseExpression;
  18002. BfExpression* ignoredExpr = (constResult) ? condExpr->mFalseExpression : condExpr->mTrueExpression;
  18003. BfTypedValue actualValue = mModule->CreateValueFromExpression(actualExpr, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  18004. BfTypedValue ignoredValue;
  18005. //
  18006. {
  18007. auto curBlock = mModule->mBfIRBuilder->GetInsertBlock();
  18008. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  18009. SetAndRestoreValue<bool> prevInConstIgnore(mModule->mCurMethodState->mCurScope->mInConstIgnore, true);
  18010. ignoredValue = mModule->CreateValueFromExpression(ignoredExpr, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  18011. mModule->mBfIRBuilder->SetInsertPoint(curBlock);
  18012. }
  18013. if (!actualValue)
  18014. return;
  18015. if ((ignoredValue) && (ignoredValue.mType != actualValue.mType) && (!ignoredValue.mType->IsVar()))
  18016. {
  18017. // Cast to more specific 'ignored' type if applicable
  18018. if (mModule->CanCast(actualValue, ignoredValue.mType))
  18019. {
  18020. actualValue = mModule->Cast(actualExpr, actualValue, ignoredValue.mType);
  18021. }
  18022. else if (!mModule->CanCast(ignoredValue, actualValue.mType))
  18023. {
  18024. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  18025. mModule->TypeToString(actualValue.mType).c_str(), mModule->TypeToString(ignoredValue.mType).c_str()), condExpr);
  18026. }
  18027. }
  18028. mResult = actualValue;
  18029. if (constResultUndef)
  18030. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Undef);
  18031. return;
  18032. }
  18033. auto trueBB = mModule->mBfIRBuilder->CreateBlock("cond.then");
  18034. auto falseBB = mModule->mBfIRBuilder->CreateBlock("cond.else");
  18035. auto endBB = mModule->mBfIRBuilder->CreateBlock("cond.end");
  18036. auto contBB = mModule->mBfIRBuilder->CreateBlock("cond.cont");
  18037. mModule->mBfIRBuilder->CreateCondBr(condResult.mValue, trueBB, falseBB);
  18038. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mCurScope->mInnerIsConditional, true);
  18039. bool wantExpectingCast = (mExpectingType != NULL) && ((mBfEvalExprFlags & BfEvalExprFlags_NoCast) == 0);
  18040. mModule->AddBasicBlock(trueBB);
  18041. auto trueValue = mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  18042. if ((wantExpectingCast) && (trueValue) && (trueValue.mType != mExpectingType))
  18043. {
  18044. // In some cases like typed primitives - we CAN individually cast each value which it's a constant still, but not after the merging
  18045. // IE: Color c = isOver ? 0xFF000000 : 0xFFFFFFFF;
  18046. // Otherwise the resulting value would just be 'int' which cannot implicitly convert to Color, but each of those ints can be
  18047. // a uint32 if converted separately
  18048. auto checkTrueValue = mModule->Cast(condExpr->mTrueExpression, trueValue, mExpectingType, BfCastFlags_SilentFail);
  18049. if (checkTrueValue)
  18050. trueValue = checkTrueValue;
  18051. mModule->FixIntUnknown(trueValue);
  18052. }
  18053. auto trueBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  18054. mModule->AddBasicBlock(falseBB);
  18055. auto falseValue = mModule->CreateValueFromExpression(condExpr->mFalseExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  18056. auto falseBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  18057. if ((wantExpectingCast) && (falseValue) && (falseValue.mType != mExpectingType))
  18058. {
  18059. auto checkFalseValue = mModule->Cast(condExpr->mFalseExpression, falseValue, mExpectingType, BfCastFlags_SilentFail);
  18060. if (checkFalseValue)
  18061. falseValue = checkFalseValue;
  18062. mModule->FixIntUnknown(falseValue);
  18063. }
  18064. bool isValid = trueValue && falseValue;
  18065. if (isValid)
  18066. {
  18067. BfTypedValue falseToTrue;
  18068. {
  18069. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  18070. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  18071. falseToTrue = mModule->Cast(condExpr->mFalseExpression, falseValue, trueValue.mType);
  18072. }
  18073. if (falseToTrue)
  18074. {
  18075. falseValue = falseToTrue;
  18076. }
  18077. else
  18078. {
  18079. BfTypedValue trueToFalse;
  18080. {
  18081. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  18082. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  18083. trueToFalse = mModule->Cast(condExpr->mTrueExpression, trueValue, falseValue.mType);
  18084. }
  18085. if (!trueToFalse)
  18086. {
  18087. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  18088. mModule->TypeToString(trueValue.mType).c_str(), mModule->TypeToString(falseValue.mType).c_str()), condExpr);
  18089. //return;
  18090. isValid = false;
  18091. }
  18092. else
  18093. trueValue = trueToFalse;
  18094. }
  18095. }
  18096. prevInCondBlock.Restore();
  18097. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  18098. if (isValid)
  18099. trueValue = mModule->LoadValue(trueValue);
  18100. mModule->mBfIRBuilder->CreateBr(endBB);
  18101. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  18102. if (isValid)
  18103. falseValue = mModule->LoadValue(falseValue);
  18104. mModule->mBfIRBuilder->CreateBr(endBB);
  18105. mModule->AddBasicBlock(endBB, false);
  18106. if (!isValid)
  18107. return;
  18108. mModule->mBfIRBuilder->SetInsertPoint(endBB);
  18109. BfIRValue phi;
  18110. if (!trueValue.mType->IsValuelessType())
  18111. {
  18112. if (trueValue.mType->IsVar())
  18113. {
  18114. phi = mModule->mBfIRBuilder->GetFakeVal();
  18115. }
  18116. else
  18117. {
  18118. mModule->mBfIRBuilder->PopulateType(trueValue.mType);
  18119. phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(trueValue.mType), 2);
  18120. mModule->mBfIRBuilder->AddPhiIncoming(phi, trueValue.mValue, trueBlockPos);
  18121. mModule->mBfIRBuilder->AddPhiIncoming(phi, falseValue.mValue, falseBlockPos);
  18122. }
  18123. }
  18124. mModule->mBfIRBuilder->CreateBr(contBB);
  18125. mModule->AddBasicBlock(contBB);
  18126. mResult = BfTypedValue(phi, trueValue.mType);
  18127. }
  18128. void BfExprEvaluator::PopulateDeferrredTupleAssignData(BfTupleExpression* tupleExpr, DeferredTupleAssignData& deferredTupleAssignData)
  18129. {
  18130. BfTypeVector fieldTypes;
  18131. Array<String> fieldNames;
  18132. // We need to evaluate each LHS tuple component in a separate BfExprEvaluator because each one
  18133. // could be a property and the 'mPropDef' target info is tied to a single evaluator
  18134. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  18135. {
  18136. DeferredTupleAssignData::Entry entry;
  18137. entry.mExprEvaluator = NULL;
  18138. entry.mInnerTuple = NULL;
  18139. entry.mVarType = NULL;
  18140. entry.mVarNameNode = NULL;
  18141. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  18142. entry.mExpr = valueExpr;
  18143. BfType* fieldType = NULL;
  18144. BfType* resultType = NULL;
  18145. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(valueExpr))
  18146. {
  18147. entry.mInnerTuple = new DeferredTupleAssignData();
  18148. PopulateDeferrredTupleAssignData(innerTupleExpr, *entry.mInnerTuple);
  18149. resultType = entry.mInnerTuple->mTupleType;
  18150. }
  18151. else
  18152. {
  18153. BfExprEvaluator* exprEvaluator = new BfExprEvaluator(mModule);
  18154. entry.mExprEvaluator = exprEvaluator;
  18155. if (valueExpr->IsA<BfUninitializedExpression>())
  18156. {
  18157. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  18158. }
  18159. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(valueExpr))
  18160. {
  18161. if ((varDecl->mTypeRef->IsA<BfLetTypeReference>()) || (varDecl->mTypeRef->IsA<BfVarTypeReference>()))
  18162. {
  18163. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  18164. }
  18165. else
  18166. {
  18167. resultType = ResolveTypeRef(varDecl->mTypeRef);
  18168. if (resultType == NULL)
  18169. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  18170. }
  18171. entry.mVarType = resultType;
  18172. }
  18173. if (auto binOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>(valueExpr))
  18174. {
  18175. if (binOpExpr->mOp == BfBinaryOp_Multiply)
  18176. {
  18177. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  18178. auto resolvedType = mModule->ResolveTypeRef(binOpExpr->mLeft, NULL);
  18179. prevIgnoreError.Restore();
  18180. if (resolvedType != NULL)
  18181. {
  18182. resultType = mModule->CreatePointerType(resolvedType);
  18183. entry.mVarType = resultType;
  18184. entry.mVarNameNode = binOpExpr->mRight;
  18185. }
  18186. }
  18187. }
  18188. if (resultType == NULL)
  18189. {
  18190. exprEvaluator->VisitChild(valueExpr);
  18191. if ((!exprEvaluator->mResult) && (exprEvaluator->mPropDef == NULL))
  18192. exprEvaluator->mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  18193. resultType = exprEvaluator->mResult.mType;
  18194. }
  18195. if ((resultType == NULL) && (exprEvaluator->mPropDef != NULL) && (exprEvaluator->mPropTarget.mType != NULL))
  18196. {
  18197. auto propTypeInst = exprEvaluator->mPropTarget.mType->ToTypeInstance();
  18198. if ((propTypeInst == NULL) && (exprEvaluator->mPropTarget.mType->IsPointer()))
  18199. {
  18200. BfPointerType* pointerType = (BfPointerType*)exprEvaluator->mPropTarget.mType;
  18201. propTypeInst = pointerType->mElementType->ToTypeInstance();
  18202. }
  18203. auto setMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  18204. if (setMethod != NULL)
  18205. {
  18206. auto methodInstance = mModule->GetMethodInstance(propTypeInst, setMethod, BfTypeVector());
  18207. resultType = methodInstance.mMethodInstance->GetParamType(0);
  18208. }
  18209. else
  18210. {
  18211. auto getMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  18212. if (getMethod != NULL)
  18213. {
  18214. auto methodInstance = mModule->GetMethodInstance(propTypeInst, getMethod, BfTypeVector());
  18215. auto retType = methodInstance.mMethodInstance->mReturnType;
  18216. if (retType->IsRef())
  18217. resultType = retType->GetUnderlyingType();
  18218. }
  18219. }
  18220. }
  18221. }
  18222. if (resultType == NULL)
  18223. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  18224. deferredTupleAssignData.mChildren.push_back(entry);
  18225. fieldTypes.push_back(resultType);
  18226. }
  18227. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  18228. {
  18229. if (requestedName == NULL)
  18230. fieldNames.push_back("");
  18231. else
  18232. fieldNames.push_back(requestedName->mNameNode->ToString());
  18233. }
  18234. BfTypeInstance* tupleType = mModule->CreateTupleType(fieldTypes, fieldNames, true);
  18235. deferredTupleAssignData.mTupleType = tupleType;
  18236. }
  18237. void BfExprEvaluator::AssignDeferrredTupleAssignData(BfAssignmentExpression* assignExpr, DeferredTupleAssignData& deferredTupleAssignData, BfTypedValue rightValue)
  18238. {
  18239. BF_ASSERT(rightValue.mType->IsTuple());
  18240. auto tupleType = (BfTypeInstance*)rightValue.mType;
  18241. for (int valueIdx = 0; valueIdx < (int)deferredTupleAssignData.mChildren.size(); valueIdx++)
  18242. {
  18243. auto& child = deferredTupleAssignData.mChildren[valueIdx];
  18244. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[valueIdx];
  18245. BfTypedValue elementValue;
  18246. if (fieldInstance->mDataIdx >= 0)
  18247. {
  18248. rightValue = mModule->LoadOrAggregateValue(rightValue);
  18249. mModule->mBfIRBuilder->PopulateType(rightValue.mType);
  18250. auto extractedValue = mModule->mBfIRBuilder->CreateExtractValue(rightValue.mValue, fieldInstance->mDataIdx);
  18251. elementValue = BfTypedValue(extractedValue, fieldInstance->GetResolvedType());
  18252. if (child.mInnerTuple != NULL)
  18253. {
  18254. AssignDeferrredTupleAssignData(assignExpr, *child.mInnerTuple, elementValue);
  18255. delete child.mInnerTuple;
  18256. child.mInnerTuple = NULL;
  18257. }
  18258. else
  18259. {
  18260. if (child.mExprEvaluator->HasResult())
  18261. {
  18262. child.mExprEvaluator->mBfEvalExprFlags = (BfEvalExprFlags)(child.mExprEvaluator->mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete);
  18263. child.mExprEvaluator->PerformAssignment(assignExpr, true, elementValue);
  18264. }
  18265. }
  18266. }
  18267. if (child.mVarType != NULL)
  18268. {
  18269. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(child.mExpr))
  18270. {
  18271. if (!elementValue)
  18272. elementValue = mModule->GetDefaultTypedValue(fieldInstance->GetResolvedType());
  18273. mModule->HandleVariableDeclaration(varDecl, elementValue);
  18274. }
  18275. else
  18276. {
  18277. // This handles the 'a*b' disambiguated variable decl case
  18278. mModule->HandleVariableDeclaration(child.mVarType, child.mVarNameNode, elementValue);
  18279. }
  18280. }
  18281. }
  18282. }
  18283. void BfExprEvaluator::DoTupleAssignment(BfAssignmentExpression* assignExpr)
  18284. {
  18285. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(assignExpr->mLeft);
  18286. DeferredTupleAssignData deferredTupleAssignData;
  18287. PopulateDeferrredTupleAssignData(tupleExpr, deferredTupleAssignData);
  18288. BfTypeInstance* tupleType = deferredTupleAssignData.mTupleType;
  18289. BfTypedValue rightValue;
  18290. if (assignExpr->mRight != NULL)
  18291. {
  18292. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, tupleType);
  18293. }
  18294. if (!rightValue)
  18295. {
  18296. tupleType = mModule->SantizeTupleType(tupleType);
  18297. rightValue = mModule->GetDefaultTypedValue(tupleType);
  18298. }
  18299. rightValue = mModule->LoadValue(rightValue);
  18300. AssignDeferrredTupleAssignData(assignExpr, deferredTupleAssignData, rightValue);
  18301. mResult = rightValue;
  18302. }
  18303. BfTypedValue BfExprEvaluator::PerformAssignment_CheckOp(BfAssignmentExpression* assignExpr, bool deferBinop, BfTypedValue& leftValue, BfTypedValue& rightValue, bool& evaluatedRight)
  18304. {
  18305. BfResolvedArgs argValues;
  18306. auto checkTypeInst = leftValue.mType->ToTypeInstance();
  18307. while (checkTypeInst != NULL)
  18308. {
  18309. for (auto operatorDef : checkTypeInst->mTypeDef->mOperators)
  18310. {
  18311. if (operatorDef->mOperatorDeclaration->mAssignOp != assignExpr->mOp)
  18312. continue;
  18313. auto methodInst = mModule->GetRawMethodInstanceAtIdx(checkTypeInst, operatorDef->mIdx);
  18314. if (methodInst == NULL)
  18315. continue;
  18316. if (methodInst->GetParamCount() != 1)
  18317. continue;
  18318. auto paramType = methodInst->GetParamType(0);
  18319. if (deferBinop)
  18320. {
  18321. if (argValues.mArguments == NULL)
  18322. {
  18323. SizedArray<BfExpression*, 2> argExprs;
  18324. argExprs.push_back(assignExpr->mRight);
  18325. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  18326. argValues.Init(&sizedArgExprs);
  18327. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  18328. }
  18329. evaluatedRight = true;
  18330. rightValue = ResolveArgValue(argValues.mResolvedArgs[0], paramType);
  18331. if (!rightValue)
  18332. continue;
  18333. }
  18334. else
  18335. {
  18336. if (!mModule->CanCast(rightValue, paramType))
  18337. continue;
  18338. rightValue = mModule->Cast(assignExpr->mLeft, rightValue, paramType);
  18339. BF_ASSERT(rightValue);
  18340. }
  18341. mModule->SetElementType(assignExpr->mOpToken, BfSourceElementType_Method);
  18342. auto autoComplete = GetAutoComplete();
  18343. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mOpToken)))
  18344. {
  18345. if (operatorDef->mOperatorDeclaration != NULL)
  18346. autoComplete->SetDefinitionLocation(operatorDef->mOperatorDeclaration->mOpTypeToken);
  18347. }
  18348. auto moduleMethodInstance = mModule->GetMethodInstance(checkTypeInst, operatorDef, BfTypeVector());
  18349. BfExprEvaluator exprEvaluator(mModule);
  18350. SizedArray<BfIRValue, 1> args;
  18351. exprEvaluator.PushThis(assignExpr->mLeft, leftValue, moduleMethodInstance.mMethodInstance, args);
  18352. exprEvaluator.PushArg(rightValue, args);
  18353. exprEvaluator.CreateCall(assignExpr, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, args);
  18354. return leftValue;
  18355. }
  18356. checkTypeInst = mModule->GetBaseType(checkTypeInst);
  18357. }
  18358. return BfTypedValue();
  18359. }
  18360. void BfExprEvaluator::PerformAssignment(BfAssignmentExpression* assignExpr, bool evaluatedLeft, BfTypedValue rightValue, BfTypedValue* outCascadeValue)
  18361. {
  18362. auto binaryOp = BfAssignOpToBinaryOp(assignExpr->mOp);
  18363. BfExpression* targetNode = assignExpr->mLeft;
  18364. if ((BfNodeIsA<BfMixinExpression>(targetNode)) && (!mModule->mCurMethodInstance->mIsUnspecialized))
  18365. {
  18366. // If we have a "mixin = <X>" but there's no mixin target then ignore the assignment
  18367. int mixinVar = GetMixinVariable();
  18368. if (mixinVar == -1)
  18369. {
  18370. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  18371. return;
  18372. }
  18373. }
  18374. BfAutoComplete* autoComplete = GetAutoComplete();
  18375. bool deferredFixits = false;
  18376. //TODO: Why was this needed? This breaks fixits on target nodes (ie: 'using' field fixit for 'fully quality')
  18377. /*if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetFixits))
  18378. {
  18379. SetAndRestoreValue<bool> ignoreFixits(autoComplete->mIgnoreFixits, true);
  18380. VisitChild(targetNode);
  18381. deferredFixits = true;
  18382. }
  18383. else*/
  18384. if (!evaluatedLeft)
  18385. {
  18386. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(targetNode))
  18387. {
  18388. DoMemberReference(memberReferenceExpr, outCascadeValue);
  18389. }
  18390. else
  18391. VisitChild(targetNode);
  18392. }
  18393. if ((!mResult) && (mPropDef == NULL))
  18394. {
  18395. if (assignExpr->mRight != NULL)
  18396. {
  18397. auto result = mModule->CreateValueFromExpression(assignExpr->mRight);
  18398. if (deferredFixits)
  18399. {
  18400. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  18401. mExpectingType = result.mType;
  18402. VisitChild(targetNode);
  18403. mResult = BfTypedValue();
  18404. }
  18405. }
  18406. return;
  18407. }
  18408. ResolveGenericType();
  18409. auto ptr = mModule->RemoveRef(mResult);
  18410. mResult = BfTypedValue();
  18411. if (mPropDef != NULL)
  18412. {
  18413. bool hasLeftVal = false;
  18414. auto propDef = mPropDef;
  18415. auto propTarget = mPropTarget;
  18416. auto setMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  18417. if (setMethod == NULL)
  18418. {
  18419. // Allow for a ref return on the getter to be used if a setter is not available
  18420. GetResult();
  18421. if ((mResult) && (mResult.mKind == BfTypedValueKind_Addr))
  18422. {
  18423. ptr = mResult;
  18424. mResult = BfTypedValue();
  18425. hasLeftVal = true;
  18426. }
  18427. else
  18428. {
  18429. mModule->Fail("Property has no setter", mPropSrc);
  18430. if (assignExpr->mRight != NULL)
  18431. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, BfEvalExprFlags_NoCast);
  18432. return;
  18433. }
  18434. }
  18435. if (!hasLeftVal)
  18436. {
  18437. auto methodInstance = GetPropertyMethodInstance(setMethod);
  18438. if (methodInstance.mMethodInstance == NULL)
  18439. return;
  18440. //BF_ASSERT(methodInstance.mMethodInstance->mMethodDef == setMethod);
  18441. CheckPropFail(setMethod, methodInstance.mMethodInstance, (mPropGetMethodFlags & BfGetMethodInstanceFlag_Friend) == 0);
  18442. auto autoComplete = GetAutoComplete();
  18443. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(mPropSrc)) && (autoComplete->mResolveType == BfResolveType_GetResultString))
  18444. {
  18445. autoComplete->mResultString = ":";
  18446. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetParamType(0));
  18447. autoComplete->mResultString += " ";
  18448. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetOwner());
  18449. autoComplete->mResultString += ".";
  18450. autoComplete->mResultString += mPropDef->mName;
  18451. }
  18452. bool handled = false;
  18453. BfTypedValue convVal;
  18454. if (binaryOp != BfBinaryOp_None)
  18455. {
  18456. BfTypedValue leftValue = mModule->CreateValueFromExpression(assignExpr->mLeft, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  18457. if (!leftValue)
  18458. return;
  18459. bool evaluatedRight = false;
  18460. auto opResult = PerformAssignment_CheckOp(assignExpr, true, leftValue, rightValue, evaluatedRight);
  18461. if (opResult)
  18462. {
  18463. mResult = opResult;
  18464. return;
  18465. }
  18466. else
  18467. {
  18468. if (evaluatedRight)
  18469. {
  18470. if (!rightValue)
  18471. return;
  18472. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType, leftValue, rightValue);
  18473. }
  18474. else
  18475. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType, leftValue);
  18476. if (!mResult)
  18477. return;
  18478. convVal = mResult;
  18479. mResult = BfTypedValue();
  18480. if (!convVal)
  18481. return;
  18482. }
  18483. }
  18484. else
  18485. {
  18486. auto wantType = methodInstance.mMethodInstance->GetParamType(0);
  18487. if (rightValue)
  18488. {
  18489. convVal = mModule->Cast(assignExpr->mRight, rightValue, wantType);
  18490. }
  18491. else
  18492. {
  18493. if (assignExpr->mRight == NULL)
  18494. {
  18495. mModule->AssertErrorState();
  18496. return;
  18497. }
  18498. BfEvalExprFlags exprFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_PendingPropSet);
  18499. if (wantType->IsRef())
  18500. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AllowRefExpr);
  18501. convVal = mModule->CreateValueFromExpression(assignExpr->mRight, wantType, exprFlags);
  18502. }
  18503. if (!convVal)
  18504. {
  18505. mPropDef = NULL;
  18506. return;
  18507. }
  18508. }
  18509. if (!handled)
  18510. {
  18511. if (mPropSrc != NULL)
  18512. mModule->UpdateExprSrcPos(mPropSrc);
  18513. BfResolvedArg valueArg;
  18514. valueArg.mTypedValue = convVal;
  18515. mIndexerValues.Insert(0, valueArg);
  18516. if (!setMethod->mIsStatic)
  18517. {
  18518. auto owner = methodInstance.mMethodInstance->GetOwner();
  18519. if ((mPropTarget.mType != owner) ||
  18520. ((mPropTarget.mValue.IsFake()) && (!mOrigPropTarget.mValue.IsFake())))
  18521. {
  18522. if ((mPropDefBypassVirtual) || (!mPropTarget.mType->IsInterface()))
  18523. {
  18524. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, owner);
  18525. if (!mPropTarget)
  18526. {
  18527. mModule->Fail("Internal property error", mPropSrc);
  18528. return;
  18529. }
  18530. }
  18531. }
  18532. }
  18533. auto callFlags = mPropDefBypassVirtual ? BfCreateCallFlags_BypassVirtual : BfCreateCallFlags_None;
  18534. mResult = CreateCall(mPropSrc, mPropTarget, mOrigPropTarget, setMethod, methodInstance, callFlags, mIndexerValues, NULL);
  18535. mPropDef = NULL;
  18536. mResult = convVal;
  18537. mIndexerValues.Clear();
  18538. return;
  18539. }
  18540. }
  18541. }
  18542. auto toType = ptr.mType;
  18543. if (toType->IsRef())
  18544. {
  18545. auto refType = (BfRefType*)toType;
  18546. toType = refType->mElementType;
  18547. }
  18548. if (toType->IsIntUnknown())
  18549. toType = mModule->FixIntUnknown(toType);
  18550. if ((autoComplete != NULL) && (assignExpr->mOpToken != NULL) && (toType != NULL))
  18551. autoComplete->CheckEmptyStart(assignExpr->mOpToken, toType);
  18552. BfExpression* rightExpr = assignExpr->mRight;
  18553. if (rightExpr == NULL)
  18554. {
  18555. mModule->AssertErrorState();
  18556. return;
  18557. }
  18558. bool alreadyWritten = false;
  18559. BfTypedValue convVal;
  18560. if (binaryOp != BfBinaryOp_None)
  18561. {
  18562. CheckResultForReading(ptr);
  18563. BfTypedValue leftValue = ptr;
  18564. bool deferBinop = false;
  18565. BfDeferEvalChecker deferEvalChecker;
  18566. deferEvalChecker.mDeferLiterals = false;
  18567. assignExpr->mRight->Accept(&deferEvalChecker);
  18568. if (deferEvalChecker.mNeedsDeferEval)
  18569. deferBinop = true;
  18570. if (binaryOp == BfBinaryOp_NullCoalesce)
  18571. {
  18572. deferBinop = true;
  18573. }
  18574. if (!deferBinop)
  18575. {
  18576. auto expectedType = ptr.mType;
  18577. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  18578. expectedType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  18579. if ((!rightValue) && (assignExpr->mRight != NULL))
  18580. {
  18581. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, expectedType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  18582. }
  18583. }
  18584. BfResolvedArgs argValues;
  18585. if ((rightValue) || (deferBinop))
  18586. {
  18587. bool evaluatedRight = false;
  18588. auto opResult = PerformAssignment_CheckOp(assignExpr, deferBinop, leftValue, rightValue, evaluatedRight);
  18589. if (opResult)
  18590. {
  18591. mResult = opResult;
  18592. return;
  18593. }
  18594. else
  18595. {
  18596. auto flags = BfBinOpFlag_ForceLeftType;
  18597. if (deferBinop)
  18598. flags = (BfBinOpFlags)(flags | BfBinOpFlag_DeferRight);
  18599. leftValue = mModule->LoadValue(leftValue);
  18600. if (binaryOp == BfBinaryOp_NullCoalesce)
  18601. {
  18602. if (!CheckModifyResult(ptr, assignExpr->mOpToken, "assign to", false, false, true))
  18603. {
  18604. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  18605. mResult = leftValue;
  18606. return;
  18607. }
  18608. if (PerformBinaryOperation_NullCoalesce(assignExpr->mOpToken, assignExpr->mLeft, assignExpr->mRight, leftValue, leftValue.mType, &ptr))
  18609. return;
  18610. }
  18611. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, flags, leftValue, rightValue);
  18612. }
  18613. }
  18614. convVal = mResult;
  18615. mResult = BfTypedValue();
  18616. if (!convVal)
  18617. return;
  18618. }
  18619. else
  18620. {
  18621. convVal = rightValue;
  18622. if (!convVal)
  18623. {
  18624. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(rightExpr))
  18625. {
  18626. if (mResultLocalVar != NULL)
  18627. {
  18628. MarkResultAssigned();
  18629. return;
  18630. }
  18631. }
  18632. // In the cases like "structVal = GetVal()", the allowDirectStructRetWrite optimization allows us to pass the
  18633. // address of structVal into the sret. We only allow that if structVal is a local, because if it's globally
  18634. // visible then we could see the results of a partially-modified structVal
  18635. //bool allowDirectStructRetWrite = mResultLocalVarIdx != -1;
  18636. // ALTHOUGH- we can only allow this optimization if we can be sure the local value is not aliased- we could
  18637. // have the backend ensure that this local value never gets its address taken.
  18638. bool allowDirectStructWrite = false;
  18639. BfExprEvaluator exprEvaluator(mModule);
  18640. exprEvaluator.mExpectingType = toType;
  18641. if (allowDirectStructWrite)
  18642. exprEvaluator.mReceivingValue = &ptr;
  18643. exprEvaluator.Evaluate(rightExpr, false, false, true);
  18644. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  18645. convVal = exprEvaluator.GetResult();
  18646. mModule->FixIntUnknown(convVal);
  18647. alreadyWritten = (allowDirectStructWrite) && (exprEvaluator.mReceivingValue == NULL);
  18648. if (!convVal)
  18649. convVal = mModule->GetDefaultTypedValue(toType);
  18650. // Did we use mReceivingValue as a mixin result?
  18651. if ((convVal.mValue) && (convVal.mValue == ptr.mValue))
  18652. {
  18653. mResult = convVal;
  18654. return;
  18655. }
  18656. }
  18657. }
  18658. if (!CheckModifyResult(ptr, assignExpr->mOpToken, "assign to", false, false, true))
  18659. {
  18660. mResult = convVal;
  18661. return;
  18662. }
  18663. if (ptr.mKind == BfTypedValueKind_CopyOnMutateAddr)
  18664. ptr.mKind = BfTypedValueKind_Addr;
  18665. else if (ptr.IsCopyOnMutate())
  18666. ptr = mModule->CopyValue(ptr);
  18667. BF_ASSERT(convVal);
  18668. if ((convVal) && (convVal.mType->IsNull()) && (ptr.mType->IsNullable()))
  18669. {
  18670. // Allow this to pass through so we can catch it in the memset later in this function
  18671. }
  18672. else
  18673. {
  18674. if (!convVal.mType->IsComposite())
  18675. convVal = mModule->LoadValue(convVal);
  18676. convVal = mModule->Cast(rightExpr, convVal, toType);
  18677. if (!convVal)
  18678. return;
  18679. convVal = mModule->LoadValue(convVal);
  18680. }
  18681. if (ptr.mType->IsVar())
  18682. {
  18683. mResult = ptr;
  18684. MarkResultAssigned();
  18685. return;
  18686. }
  18687. if (convVal.mValue)
  18688. {
  18689. if ((ptr.mType->IsStruct()) && (!ptr.mType->IsValuelessType()) && (convVal.mValue.IsConst()))
  18690. {
  18691. auto constant = mModule->mBfIRBuilder->GetConstant(convVal.mValue);
  18692. if ((constant->mTypeCode == BfTypeCode_NullPtr) || (constant->mConstType == BfConstType_AggZero))
  18693. {
  18694. auto type = ptr.mType;
  18695. mModule->mBfIRBuilder->CreateMemSet(ptr.mValue, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  18696. mModule->GetConstValue(type->mSize), type->mAlign);
  18697. mResult = ptr;
  18698. MarkResultAssigned();
  18699. return;
  18700. }
  18701. }
  18702. // if (ptr.mType->IsMethodRef())
  18703. // {
  18704. // auto methodRefType = (BfMethodRefType*)ptr.mType;
  18705. // auto methodInstance = methodRefType->mMethodInstance;
  18706. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  18707. // for (int implicitParamIdx = methodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  18708. // {
  18709. // bool failed = false;
  18710. // auto destPtr = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericTypeMember_Addr);
  18711. // auto srcVal = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericMethodMember);
  18712. // if ((destPtr) && (srcVal))
  18713. // {
  18714. // srcVal = mModule->AggregateSplat(srcVal);
  18715. // mModule->mBfIRBuilder->CreateStore(srcVal.mValue, destPtr.mValue);
  18716. // }
  18717. // }
  18718. // }
  18719. // else
  18720. {
  18721. mModule->mBfIRBuilder->PopulateType(ptr.mType);
  18722. if (convVal.IsSplat())
  18723. {
  18724. //convVal = mModule->AggregateSplat(convVal);
  18725. mModule->AggregateSplatIntoAddr(convVal, ptr.mValue);
  18726. }
  18727. else
  18728. {
  18729. if (ptr.mType->IsOpaque())
  18730. {
  18731. mModule->Fail(StrFormat("Unable to assign to opaque type '%s'", mModule->TypeToString(ptr.mType).c_str()), assignExpr);
  18732. }
  18733. else if (ptr.mType->IsValuelessType())
  18734. {
  18735. mModule->EmitEnsureInstructionAt();
  18736. }
  18737. else if (!alreadyWritten)
  18738. {
  18739. if ((mModule->mIsComptimeModule) && (mModule->mCompiler->mCeMachine->mDebugger != NULL) && (mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  18740. {
  18741. auto ceDbgState = mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState;
  18742. bool success = false;
  18743. if ((convVal.mValue.IsConst()) && (ptr.mValue.IsConst()))
  18744. {
  18745. auto constant = mModule->mBfIRBuilder->GetConstant(ptr.mValue);
  18746. auto valConstant = mModule->mBfIRBuilder->GetConstant(convVal.mValue);
  18747. auto ceTypedVal = mModule->mCompiler->mCeMachine->mDebugger->GetAddr(constant);
  18748. if (!ceTypedVal)
  18749. {
  18750. mModule->Fail("Invalid assignment address", assignExpr);
  18751. return;
  18752. }
  18753. auto ceContext = mModule->mCompiler->mCeMachine->mCurContext;
  18754. if (ceContext->CheckMemory((addr_ce)ceTypedVal.mAddr, convVal.mType->mSize))
  18755. {
  18756. if ((ceDbgState->mDbgExpressionFlags & DwEvalExpressionFlag_AllowSideEffects) != 0)
  18757. {
  18758. ceDbgState->mHadSideEffects = true;
  18759. if (ceContext->WriteConstant(mModule, (addr_ce)ceTypedVal.mAddr, valConstant, convVal.mType))
  18760. success = true;
  18761. }
  18762. else
  18763. {
  18764. ceDbgState->mBlockedSideEffects = true;
  18765. success = true;
  18766. }
  18767. }
  18768. }
  18769. if (!success)
  18770. {
  18771. mModule->Fail("Assignment failed", assignExpr);
  18772. return;
  18773. }
  18774. }
  18775. if (!alreadyWritten)
  18776. {
  18777. //ptr = mModule->LoadValue(ptr);
  18778. BF_ASSERT(ptr.IsAddr());
  18779. convVal = mModule->LoadValue(convVal);
  18780. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(convVal.mValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  18781. }
  18782. }
  18783. }
  18784. }
  18785. }
  18786. else
  18787. {
  18788. BF_ASSERT(convVal.mType->IsValuelessType());
  18789. }
  18790. mResult = convVal;
  18791. MarkResultAssigned();
  18792. }
  18793. void BfExprEvaluator::Visit(BfAssignmentExpression* assignExpr)
  18794. {
  18795. if (assignExpr->mLeft->IsA<BfTupleExpression>())
  18796. {
  18797. DoTupleAssignment(assignExpr);
  18798. return;
  18799. }
  18800. BfAutoParentNodeEntry autoParentNodeEntry(mModule, assignExpr);
  18801. BfTypedValue cascadeValue;
  18802. PerformAssignment(assignExpr, false, BfTypedValue(), &cascadeValue);
  18803. if (cascadeValue)
  18804. mResult = cascadeValue;
  18805. }
  18806. void BfExprEvaluator::Visit(BfParenthesizedExpression* parenExpr)
  18807. {
  18808. VisitChild(parenExpr->mExpression);
  18809. MakeResultAsValue();
  18810. }
  18811. void BfExprEvaluator::InitializedSizedArray(BfSizedArrayType* arrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, BfTypedValue* receivingValue)
  18812. {
  18813. struct InitValue
  18814. {
  18815. BfTypedValue mValue;
  18816. bool mIsUninitialized;
  18817. bool mIsDefaultInitializer;
  18818. bool mIsDeferred;
  18819. InitValue()
  18820. {
  18821. mIsUninitialized = false;
  18822. mIsDefaultInitializer = false;
  18823. mIsDeferred = false;
  18824. }
  18825. };
  18826. SizedArray<InitValue, 8> values;
  18827. {
  18828. //bool hasFailed = false;
  18829. HashSet<int> failedAt;
  18830. bool isAllConst = true;
  18831. //bool endUninitialzied = false;
  18832. int depth = 0;
  18833. std::function<void(BfSizedArrayType*, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*, bool)>
  18834. _GetValues = [&](BfSizedArrayType* checkArrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, bool ignore)
  18835. {
  18836. int64 initCountDiff = (int)valueExprs.size() - checkArrayType->mElementCount;
  18837. if ((initCountDiff != 0) && (!valueExprs.IsEmpty()) && (!failedAt.Contains(depth)))
  18838. {
  18839. if (checkArrayType->mElementCount == -1)
  18840. {
  18841. // mModule->Fail("Initializers not supported for unknown-sized arrays", valueExprs[0]);
  18842. // failedAt.Add(depth);
  18843. }
  18844. else if (initCountDiff > 0)
  18845. {
  18846. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[BF_MAX((int)checkArrayType->mElementCount, 0)]);
  18847. failedAt.Add(depth);
  18848. }
  18849. else
  18850. {
  18851. // If it ends with ", ?) or ",)" then allow unsized
  18852. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  18853. ((commas.size() < valueExprs.size()) || (valueExprs.size() == 0)))
  18854. {
  18855. BfAstNode* refNode = closeToken;
  18856. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  18857. refNode = mModule->mParentNodeEntry->mNode;
  18858. BF_ASSERT(refNode != NULL);
  18859. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  18860. failedAt.Add(depth);
  18861. }
  18862. }
  18863. }
  18864. for (int idx = 0; idx < BF_MAX(checkArrayType->mElementCount, valueExprs.size()); idx++)
  18865. {
  18866. BfTypedValue elementValue;
  18867. bool deferredValue = false;
  18868. BfExpression* expr = NULL;
  18869. if (idx < (int)valueExprs.size())
  18870. {
  18871. expr = valueExprs[idx];
  18872. if (expr == NULL)
  18873. {
  18874. if (idx == 0)
  18875. mModule->FailAfter("Expression expected", openToken);
  18876. else
  18877. mModule->FailAfter("Expression expected", commas[idx - 1]);
  18878. }
  18879. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  18880. {
  18881. isAllConst = false;
  18882. break;
  18883. }
  18884. if (checkArrayType->mElementType->IsSizedArray())
  18885. {
  18886. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  18887. {
  18888. depth++;
  18889. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen, ignore);
  18890. depth--;
  18891. continue;
  18892. }
  18893. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  18894. {
  18895. depth++;
  18896. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace, ignore);
  18897. depth--;
  18898. continue;
  18899. }
  18900. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  18901. {
  18902. depth++;
  18903. SizedArray<BfExpression*, 1> values;
  18904. values.Add(parenExpr->mExpression);
  18905. SizedArray<BfTokenNode*, 1> commas;
  18906. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, ignore);
  18907. depth--;
  18908. continue;
  18909. }
  18910. }
  18911. if (expr != NULL)
  18912. {
  18913. auto evalFlags = (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags);
  18914. bool tryDefer = false;
  18915. if ((checkArrayType->IsComposite()) &&
  18916. ((expr->IsA<BfInvocationExpression>()) || (expr->IsExact<BfTupleExpression>())))
  18917. {
  18918. // We evaluate with a new scope because this expression may create variables that we don't want to be visible to other
  18919. // non-deferred evaluations (since the value may actually be a FakeVal)
  18920. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  18921. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType, (BfEvalExprFlags)(evalFlags | BfEvalExprFlags_CreateConditionalScope));
  18922. deferredValue = !prevIgnoreWrites.mPrevVal && elementValue.mValue.IsFake();
  18923. }
  18924. else
  18925. {
  18926. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType, evalFlags);
  18927. }
  18928. if (!elementValue)
  18929. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  18930. if ((!elementValue) || (!CheckAllowValue(elementValue, expr)))
  18931. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  18932. // For now, we can't properly create const-valued non-size-aligned composites
  18933. if (!elementValue.mValue.IsConst())
  18934. isAllConst = false;
  18935. if (elementValue.IsAddr())
  18936. isAllConst = false;
  18937. InitValue initValue;
  18938. initValue.mValue = elementValue;
  18939. initValue.mIsDeferred = deferredValue;
  18940. values.push_back(initValue);
  18941. }
  18942. }
  18943. }
  18944. };
  18945. int valueIdx = 0;
  18946. std::function<void(BfTypedValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  18947. _CreateMemArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  18948. {
  18949. BF_ASSERT(arrayValue.mType->IsSizedArray());
  18950. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  18951. int valIdx = 0;
  18952. bool hasUninit = false;
  18953. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  18954. {
  18955. BfExpression* expr = NULL;
  18956. BfTypedValue elementValue;
  18957. if (idx >= (int)valueExprs.size())
  18958. break;
  18959. expr = valueExprs[idx];
  18960. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  18961. {
  18962. hasUninit = true;
  18963. break;
  18964. }
  18965. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  18966. valIdx++;
  18967. if (checkArrayType->mElementType->IsSizedArray())
  18968. {
  18969. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  18970. {
  18971. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen);
  18972. continue;
  18973. }
  18974. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  18975. {
  18976. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace);
  18977. continue;
  18978. }
  18979. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  18980. {
  18981. depth++;
  18982. SizedArray<BfExpression*, 1> values;
  18983. values.Add(parenExpr->mExpression);
  18984. SizedArray<BfTokenNode*, 1> commas;
  18985. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen);
  18986. depth--;
  18987. continue;
  18988. }
  18989. }
  18990. if (expr != NULL)
  18991. {
  18992. InitValue initValue = values[valueIdx++];
  18993. elementValue = initValue.mValue;
  18994. if (initValue.mIsDeferred)
  18995. {
  18996. BfTypedValue elemePtrTypedVal = BfTypedValue(elemPtrValue, checkArrayType->mElementType, BfTypedValueKind_Addr);
  18997. BfExprEvaluator exprEvaluator(mModule);
  18998. exprEvaluator.mExpectingType = checkArrayType->mElementType;
  18999. exprEvaluator.mReceivingValue = &elemePtrTypedVal;
  19000. exprEvaluator.Evaluate(expr);
  19001. exprEvaluator.GetResult();
  19002. if (exprEvaluator.mReceivingValue == NULL)
  19003. {
  19004. // We wrote directly to the array in-place, we're done with this element
  19005. continue;
  19006. }
  19007. elementValue = exprEvaluator.mResult;
  19008. elementValue = mModule->Cast(expr, elementValue, checkArrayType->mElementType);
  19009. if (!elementValue)
  19010. {
  19011. mModule->AssertErrorState();
  19012. continue;
  19013. }
  19014. }
  19015. elementValue = mModule->LoadOrAggregateValue(elementValue);
  19016. // Note that elemPtrValue can be a const GEP on a global variable
  19017. mModule->mBfIRBuilder->CreateAlignedStore(elementValue.mValue, elemPtrValue, checkArrayType->mElementType->mAlign);
  19018. }
  19019. }
  19020. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  19021. if (fillCount > 0)
  19022. {
  19023. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  19024. if (hasUninit)
  19025. {
  19026. if (!mModule->IsOptimized())
  19027. {
  19028. int setSize = std::min(checkArrayType->mElementType->mSize, 128); // Keep it to a reasonable number of bytes to trash
  19029. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0xCC),
  19030. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  19031. }
  19032. }
  19033. else
  19034. {
  19035. int setSize = (int)((checkArrayType->mElementType->GetStride() * (fillCount - 1)) + checkArrayType->mElementType->mSize);
  19036. if (setSize >= 0)
  19037. {
  19038. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0),
  19039. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  19040. }
  19041. }
  19042. }
  19043. };
  19044. std::function<BfIRValue(BfTypedValue, BfTokenNode*, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  19045. _CreateConstArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  19046. {
  19047. SizedArray<BfIRValue, 8> members;
  19048. BF_ASSERT(arrayValue.mType->IsSizedArray());
  19049. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  19050. int valIdx = 0;
  19051. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  19052. {
  19053. BfTypedValue elementValue;
  19054. if (idx >= (int)valueExprs.size())
  19055. break;
  19056. auto expr = valueExprs[idx];
  19057. if (expr == NULL)
  19058. continue;
  19059. valIdx++;
  19060. if (checkArrayType->mElementType->IsSizedArray())
  19061. {
  19062. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  19063. {
  19064. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen));
  19065. continue;
  19066. }
  19067. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  19068. {
  19069. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace));
  19070. continue;
  19071. }
  19072. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  19073. {
  19074. depth++;
  19075. SizedArray<BfExpression*, 1> values;
  19076. values.Add(parenExpr->mExpression);
  19077. SizedArray<BfTokenNode*, 1> commas;
  19078. members.push_back(_CreateConstArray(checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen));
  19079. depth--;
  19080. continue;
  19081. }
  19082. }
  19083. InitValue initValue = values[valueIdx++];
  19084. BF_ASSERT(!initValue.mIsUninitialized);
  19085. elementValue = initValue.mValue;
  19086. members.push_back(elementValue.mValue);
  19087. }
  19088. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  19089. if (fillCount > 0)
  19090. {
  19091. // We just need to insert one default value, it will be duplicated as needed into the backend
  19092. auto defaultVal = mModule->GetDefaultTypedValue(checkArrayType->GetUnderlyingType());
  19093. BF_ASSERT(defaultVal.mValue.IsConst());
  19094. members.push_back(defaultVal.mValue);
  19095. }
  19096. auto allocArrayType = checkArrayType;
  19097. if (checkArrayType->IsUndefSizedArray())
  19098. allocArrayType = mModule->CreateSizedArrayType(checkArrayType->GetUnderlyingType(), (int)members.size());
  19099. return mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(checkArrayType), members);
  19100. };
  19101. _GetValues(arrayType, openToken, valueExprs, commas, closeToken, false);
  19102. if (!failedAt.IsEmpty())
  19103. {
  19104. mResult = mModule->GetDefaultTypedValue(arrayType, false, BfDefaultValueKind_Addr);
  19105. return;
  19106. }
  19107. if (receivingValue != NULL)
  19108. {
  19109. BF_ASSERT(receivingValue->mType == arrayType);
  19110. BF_ASSERT(receivingValue->IsAddr());
  19111. mResult = *receivingValue;
  19112. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  19113. }
  19114. else if (isAllConst)
  19115. {
  19116. mResult = BfTypedValue(_CreateConstArray(arrayType, openToken, valueExprs, commas, closeToken), arrayType, BfTypedValueKind_Value);
  19117. }
  19118. else
  19119. {
  19120. if ((mReceivingValue != NULL) && (mReceivingValue->mType == arrayType) && (mReceivingValue->IsAddr()))
  19121. {
  19122. mResult = *mReceivingValue;
  19123. mReceivingValue = NULL;
  19124. }
  19125. else
  19126. {
  19127. auto arrayValue = mModule->CreateAlloca(arrayType);
  19128. mResult = BfTypedValue(arrayValue, arrayType, BfTypedValueKind_TempAddr);
  19129. }
  19130. if (!arrayType->IsValuelessType())
  19131. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  19132. }
  19133. }
  19134. }
  19135. void BfExprEvaluator::Visit(BfTupleExpression* tupleExpr)
  19136. {
  19137. BfTypeInstance* tupleType = NULL;
  19138. bool hadFullMatch = false;
  19139. if ((mExpectingType != NULL) && (mExpectingType->IsTuple()))
  19140. {
  19141. tupleType = (BfTypeInstance*)mExpectingType;
  19142. hadFullMatch = tupleType->mFieldInstances.size() == tupleExpr->mValues.size();
  19143. }
  19144. struct InitValue
  19145. {
  19146. BfTypedValue mValue;
  19147. bool mIsUninitialized;
  19148. bool mIsDefaultInitializer;
  19149. bool mIsDeferred;
  19150. InitValue()
  19151. {
  19152. mIsUninitialized = false;
  19153. mIsDefaultInitializer = false;
  19154. mIsDeferred = false;
  19155. }
  19156. };
  19157. SizedArray<BfTypedValue, 2> typedValues;
  19158. if ((tupleExpr->mCommas.size() != 0) && (tupleExpr->mCommas.size() >= tupleExpr->mValues.size()))
  19159. {
  19160. // We would normally give this error during syntax parsing, but a TupleExpression can be an array initializer
  19161. mModule->FailAfter("Expression expected", tupleExpr->mCommas.back());
  19162. }
  19163. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  19164. {
  19165. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  19166. BfType* fieldType = NULL;
  19167. BfFieldInstance* fieldInstance = NULL;
  19168. if (tupleType != NULL)
  19169. {
  19170. if (valueIdx < (int)tupleType->mFieldInstances.size())
  19171. {
  19172. fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[valueIdx];
  19173. fieldType = fieldInstance->GetResolvedType();
  19174. if (fieldType->IsVoid())
  19175. {
  19176. typedValues.push_back(BfTypedValue());
  19177. continue;
  19178. }
  19179. if (fieldType->IsVar())
  19180. {
  19181. hadFullMatch = false;
  19182. fieldType = NULL;
  19183. }
  19184. }
  19185. }
  19186. bool tryDefer = false;
  19187. if (((fieldType == NULL) || (fieldType->IsComposite())) &&
  19188. ((valueExpr->IsA<BfInvocationExpression>()) || (valueExpr->IsExact<BfTupleExpression>())))
  19189. {
  19190. tryDefer = true;
  19191. }
  19192. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || tryDefer);
  19193. BfTypedValue value = mModule->CreateValueFromExpression(valueExpr, fieldType);
  19194. if (!value)
  19195. {
  19196. if (fieldType != NULL)
  19197. value = mModule->GetDefaultTypedValue(fieldType);
  19198. else
  19199. value = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  19200. }
  19201. if ((fieldInstance != NULL) && (!fieldInstance->GetFieldDef()->IsUnnamedTupleField()) && (valueIdx < (int)tupleExpr->mNames.size()))
  19202. {
  19203. auto checkName = tupleExpr->mNames[valueIdx];
  19204. if (checkName != NULL)
  19205. {
  19206. if (checkName->ToString() != fieldInstance->GetFieldDef()->mName)
  19207. hadFullMatch = false;
  19208. }
  19209. }
  19210. value = mModule->LoadValue(value);
  19211. typedValues.push_back(value);
  19212. }
  19213. if (!hadFullMatch)
  19214. {
  19215. BfTypeVector fieldTypes;
  19216. Array<String> fieldNames;
  19217. HashSet<String> fieldNameSet;
  19218. for (auto typedVal : typedValues)
  19219. {
  19220. auto type = typedVal.mType;
  19221. if (type != NULL)
  19222. fieldTypes.push_back(type);
  19223. else
  19224. fieldTypes.push_back(mModule->mContext->mBfObjectType);
  19225. }
  19226. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  19227. {
  19228. if (requestedName == NULL)
  19229. fieldNames.push_back("");
  19230. else
  19231. {
  19232. auto fieldName = requestedName->mNameNode->ToString();
  19233. if (!fieldNameSet.TryAdd(fieldName, NULL))
  19234. {
  19235. mModule->Fail(StrFormat("A field named '%s' has already been declared", fieldName.c_str()), requestedName->mNameNode);
  19236. }
  19237. fieldNames.push_back(fieldName);
  19238. }
  19239. }
  19240. tupleType = mModule->CreateTupleType(fieldTypes, fieldNames);
  19241. }
  19242. mModule->mBfIRBuilder->PopulateType(tupleType);
  19243. BfIRValue curTupleValue;
  19244. if ((mReceivingValue != NULL) && (mReceivingValue->mType == tupleType) && (mReceivingValue->IsAddr()))
  19245. {
  19246. mResult = *mReceivingValue;
  19247. mReceivingValue = NULL;
  19248. curTupleValue = mResult.mValue;
  19249. }
  19250. else
  19251. {
  19252. int valueIdx = -1;
  19253. bool isExactConst = true;
  19254. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  19255. {
  19256. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  19257. if (fieldInstance->mDataIdx < 0)
  19258. continue;
  19259. ++valueIdx;
  19260. auto typedValue = typedValues[valueIdx];
  19261. if (typedValue.mType != fieldInstance->mResolvedType)
  19262. {
  19263. isExactConst = false;
  19264. break;
  19265. }
  19266. if (!typedValue.mValue.IsConst())
  19267. {
  19268. isExactConst = false;
  19269. break;
  19270. }
  19271. }
  19272. if (isExactConst)
  19273. {
  19274. mModule->PopulateType(tupleType);
  19275. if (tupleType->IsDataIncomplete())
  19276. return;
  19277. Array<BfIRValue> irValues;
  19278. irValues.Resize(typedValues.mSize + 1);
  19279. irValues[0] = mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(tupleType->mBaseType));
  19280. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  19281. {
  19282. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  19283. if (fieldInstance->mDataIdx < 0)
  19284. continue;
  19285. while (fieldInstance->mDataIdx >= irValues.size())
  19286. irValues.Add(BfIRValue());
  19287. irValues[fieldInstance->mDataIdx] = typedValues[fieldIdx].mValue;
  19288. }
  19289. for (auto& val : irValues)
  19290. {
  19291. if (!val)
  19292. val = mModule->mBfIRBuilder->CreateConstArrayZero(0);
  19293. }
  19294. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(tupleType), irValues), tupleType);
  19295. return;
  19296. }
  19297. curTupleValue = mModule->CreateAlloca(tupleType);
  19298. mResultIsTempComposite = true;
  19299. mResult = BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  19300. }
  19301. int valueIdx = -1;
  19302. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  19303. {
  19304. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  19305. ++valueIdx;
  19306. if (fieldInstance->mResolvedType->IsValuelessType())
  19307. continue;
  19308. auto typedVal = typedValues[valueIdx];
  19309. if (!typedVal)
  19310. {
  19311. mModule->AssertErrorState();
  19312. continue;
  19313. }
  19314. if (fieldInstance->mDataIdx >= 0)
  19315. {
  19316. auto memberVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curTupleValue, 0, fieldInstance->mDataIdx);
  19317. if ((!mModule->mBfIRBuilder->mIgnoreWrites) && (typedVal.mValue.IsFake()))
  19318. {
  19319. // Value was deferred. Allow us to try to init in place
  19320. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  19321. BfTypedValue memberPtrTypedVal = BfTypedValue(memberVal, fieldInstance->mResolvedType, BfTypedValueKind_Addr);
  19322. BfExprEvaluator exprEvaluator(mModule);
  19323. exprEvaluator.mExpectingType = fieldInstance->mResolvedType;
  19324. exprEvaluator.mReceivingValue = &memberPtrTypedVal;
  19325. exprEvaluator.Evaluate(valueExpr);
  19326. exprEvaluator.GetResult();
  19327. if (exprEvaluator.mReceivingValue == NULL)
  19328. {
  19329. // We wrote directly to the array in-place, we're done with this element
  19330. continue;
  19331. }
  19332. typedVal = exprEvaluator.mResult;
  19333. typedVal = mModule->Cast(valueExpr, typedVal, fieldInstance->mResolvedType);
  19334. if (!typedVal)
  19335. {
  19336. mModule->AssertErrorState();
  19337. continue;
  19338. }
  19339. typedVal = mModule->LoadValue(typedVal);
  19340. }
  19341. if (typedVal.mType->IsVar())
  19342. {
  19343. // Do nothing
  19344. }
  19345. else if (typedVal.IsSplat())
  19346. mModule->AggregateSplatIntoAddr(typedVal, memberVal);
  19347. else
  19348. mModule->mBfIRBuilder->CreateAlignedStore(typedVal.mValue, memberVal, typedVal.mType->mAlign);
  19349. }
  19350. }
  19351. }
  19352. BfTypedValue BfExprEvaluator::SetupNullConditional(BfTypedValue thisValue, BfTokenNode* dotToken)
  19353. {
  19354. bool isStaticLookup = (!thisValue) ||
  19355. ((!thisValue.mType->IsValuelessType()) && (!thisValue.mValue));
  19356. if (isStaticLookup)
  19357. {
  19358. mModule->Fail("Null conditional reference not valid for static field references", dotToken);
  19359. return thisValue;
  19360. }
  19361. auto opResult = PerformUnaryOperation_TryOperator(thisValue, NULL, BfUnaryOp_NullConditional, dotToken, BfUnaryOpFlag_None);
  19362. if (opResult)
  19363. thisValue = opResult;
  19364. if (thisValue.mType->IsGenericParam())
  19365. {
  19366. bool isValid = false;
  19367. auto genericParams = mModule->GetGenericParamInstance((BfGenericParamType*)thisValue.mType);
  19368. if (genericParams->mTypeConstraint != NULL)
  19369. {
  19370. if ((genericParams->mTypeConstraint->IsNullable()) ||
  19371. (genericParams->mTypeConstraint->IsPointer()) ||
  19372. (genericParams->mTypeConstraint->IsObjectOrInterface()))
  19373. isValid = true;
  19374. }
  19375. if ((genericParams->mGenericParamFlags & (BfGenericParamFlag_Var | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class)) != 0)
  19376. isValid = true;
  19377. if (isValid)
  19378. return thisValue;
  19379. }
  19380. if ((thisValue.mType->IsNullable()) || (thisValue.mType->IsVar()))
  19381. {
  19382. // Success
  19383. }
  19384. else if ((thisValue.mType->IsPointer()) || (thisValue.mType->IsObjectOrInterface()) || (thisValue.mType->IsFunction()))
  19385. {
  19386. // Also good
  19387. }
  19388. else
  19389. {
  19390. bool canBeNull = false;
  19391. if (thisValue.mType->IsGenericParam())
  19392. canBeNull = true;
  19393. if (!canBeNull)
  19394. mModule->Warn(0, StrFormat("Null conditional reference is unnecessary since value type '%s' can never be null", mModule->TypeToString(thisValue.mType).c_str()), dotToken);
  19395. return thisValue;
  19396. }
  19397. thisValue = mModule->LoadValue(thisValue);
  19398. if (thisValue.mType->IsVar())
  19399. return thisValue;
  19400. BfPendingNullConditional* pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  19401. if (pendingNullCond == NULL)
  19402. {
  19403. pendingNullCond = new BfPendingNullConditional();
  19404. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  19405. }
  19406. if (!pendingNullCond->mPrevBB)
  19407. pendingNullCond->mPrevBB = mModule->mBfIRBuilder->GetInsertBlock();
  19408. if (!pendingNullCond->mDoneBB)
  19409. pendingNullCond->mDoneBB = mModule->mBfIRBuilder->CreateBlock("nullCond.done");
  19410. // We will in the br to checkBB later
  19411. if (!pendingNullCond->mCheckBB)
  19412. {
  19413. pendingNullCond->mCheckBB = mModule->mBfIRBuilder->CreateBlock("nullCond.check");
  19414. mModule->AddBasicBlock(pendingNullCond->mCheckBB);
  19415. }
  19416. BfIRValue isNotNull;
  19417. if (thisValue.mType->IsNullable())
  19418. {
  19419. BfTypeInstance* nullableType = (BfTypeInstance*)thisValue.mType->ToTypeInstance();
  19420. auto elementType = nullableType->GetUnderlyingType();
  19421. if (elementType->IsValuelessType())
  19422. {
  19423. thisValue = mModule->MakeAddressable(thisValue);
  19424. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mHasValue
  19425. isNotNull = mModule->mBfIRBuilder->CreateAlignedLoad(hasValuePtr, 1);
  19426. thisValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), elementType, true);
  19427. }
  19428. else
  19429. {
  19430. thisValue = mModule->MakeAddressable(thisValue);
  19431. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 2); // mHasValue
  19432. isNotNull = mModule->mBfIRBuilder->CreateAlignedLoad(hasValuePtr, 1);
  19433. BfIRValue valuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mValue
  19434. thisValue = BfTypedValue(valuePtr, elementType, true);
  19435. }
  19436. }
  19437. else if (thisValue.mType->IsFunction())
  19438. {
  19439. isNotNull = mModule->mBfIRBuilder->CreateCmpNE(thisValue.mValue, mModule->GetDefaultValue(thisValue.mType));
  19440. }
  19441. else
  19442. isNotNull = mModule->mBfIRBuilder->CreateIsNotNull(thisValue.mValue);
  19443. BfIRBlock notNullBB = mModule->mBfIRBuilder->CreateBlock("nullCond.notNull");
  19444. pendingNullCond->mNotNullBBs.Add(notNullBB);
  19445. mModule->mBfIRBuilder->CreateCondBr(isNotNull, notNullBB, pendingNullCond->mDoneBB);
  19446. mModule->AddBasicBlock(notNullBB);
  19447. return thisValue;
  19448. }
  19449. void BfExprEvaluator::CheckDotToken(BfTokenNode* tokenNode)
  19450. {
  19451. if ((tokenNode != NULL) && (tokenNode->mToken == BfToken_DotDot))
  19452. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", tokenNode);
  19453. }
  19454. void BfExprEvaluator::DoMemberReference(BfMemberReferenceExpression* memberRefExpr, BfTypedValue* outCascadeValue)
  19455. {
  19456. CheckDotToken(memberRefExpr->mDotToken);
  19457. BfAttributeState attributeState;
  19458. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  19459. String findName;
  19460. BfAstNode* nameRefNode = memberRefExpr->mMemberName;
  19461. if (auto attrIdentifierExpr = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpr->mMemberName))
  19462. {
  19463. nameRefNode = attrIdentifierExpr->mIdentifier;
  19464. // Don't validate
  19465. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierExpr->mAttributes, BfAttributeTargets_SkipValidate);
  19466. if (nameRefNode != NULL)
  19467. findName = attrIdentifierExpr->mIdentifier->ToString();
  19468. }
  19469. else if (memberRefExpr->mMemberName != NULL)
  19470. findName = memberRefExpr->mMemberName->ToString();
  19471. else if (memberRefExpr->mDotToken != NULL)
  19472. mModule->FailAfter("Member name expected", memberRefExpr->mDotToken);
  19473. defer
  19474. (
  19475. if (attributeState.mCustomAttributes != NULL)
  19476. {
  19477. if (mPropDef != NULL)
  19478. attributeState.mTarget = (BfAttributeTargets)(attributeState.mTarget | BfAttributeTargets_Invocation);
  19479. mModule->ValidateCustomAttributes(attributeState.mCustomAttributes, attributeState.mTarget);
  19480. }
  19481. );
  19482. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  19483. BfTypeInstance* expectingTypeInst = NULL;
  19484. if (mExpectingType != NULL)
  19485. {
  19486. expectingTypeInst = mExpectingType->ToTypeInstance();
  19487. if (mExpectingType->IsPointer())
  19488. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  19489. else if (mExpectingType->IsNullable())
  19490. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  19491. else if (mExpectingType->IsConstExprValue())
  19492. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  19493. else if (mExpectingType->IsGenericParam())
  19494. {
  19495. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  19496. if (genericParam->mTypeConstraint != NULL)
  19497. expectingTypeInst = genericParam->mTypeConstraint->ToTypeInstance();
  19498. }
  19499. }
  19500. BfAutoComplete* autoComplete = GetAutoComplete();
  19501. if (autoComplete != NULL)
  19502. {
  19503. SetAndRestoreValue<bool> prevFriendSet(autoComplete->mHasFriendSet, (attributeState.mCustomAttributes != NULL) && (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef)));
  19504. if (memberRefExpr->mTarget == NULL)
  19505. {
  19506. String filter;
  19507. if ((mExpectingType != NULL) &&
  19508. (autoComplete->InitAutocomplete(memberRefExpr->mDotToken, memberRefExpr->mMemberName, filter)))
  19509. {
  19510. if (expectingTypeInst != NULL)
  19511. {
  19512. bool allowPrivate = expectingTypeInst == mModule->mCurTypeInstance;
  19513. if (expectingTypeInst->IsEnum())
  19514. autoComplete->AddEnumTypeMembers(expectingTypeInst, filter, false, allowPrivate);
  19515. autoComplete->AddSelfResultTypeMembers(expectingTypeInst, expectingTypeInst, filter, allowPrivate);
  19516. }
  19517. }
  19518. else if ((expectingTypeInst != NULL) && (autoComplete->IsAutocompleteNode(memberRefExpr->mDotToken)) && (autoComplete->mIsGetDefinition))
  19519. {
  19520. if ((autoComplete->mDefType == NULL) &&
  19521. (autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  19522. (autoComplete->mDefProp == NULL) && (expectingTypeInst->mTypeDef->mTypeDeclaration != NULL))
  19523. {
  19524. autoComplete->mDefType = expectingTypeInst->mTypeDef;
  19525. autoComplete->SetDefinitionLocation(expectingTypeInst->mTypeDef->mTypeDeclaration->mNameNode);
  19526. }
  19527. }
  19528. }
  19529. else
  19530. {
  19531. autoComplete->CheckMemberReference(memberRefExpr->mTarget, memberRefExpr->mDotToken, memberRefExpr->mMemberName, false, mExpectingType);
  19532. if (auto objCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(memberRefExpr->mTarget))
  19533. {
  19534. // This handles a weird case where we have "obj a = new\nWhatever().Thing = 123;".
  19535. // That gets parsed as "Whatever()" being the type we want to create, and then referencing
  19536. // the "Thing" member of that new object.
  19537. //if (objCreateExpr->mArraySizeSpecifier == NULL)
  19538. CheckObjectCreateTypeRef(mExpectingType, objCreateExpr->mNewNode);
  19539. }
  19540. }
  19541. }
  19542. if (memberRefExpr->mTarget == NULL)
  19543. {
  19544. if (mExpectingType == NULL)
  19545. {
  19546. if (mModule->PreFail())
  19547. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", nameRefNode);
  19548. return;
  19549. }
  19550. if (mExpectingType->IsVar())
  19551. {
  19552. mResult = mModule->GetDefaultTypedValue(mExpectingType);
  19553. return;
  19554. }
  19555. if (mExpectingType->IsSizedArray())
  19556. {
  19557. expectingTypeInst = mModule->GetWrappedStructType(mExpectingType);
  19558. }
  19559. if (expectingTypeInst == NULL)
  19560. {
  19561. if (mModule->PreFail())
  19562. mModule->Fail(StrFormat("Unqualified dot syntax cannot be used with type '%s'", mModule->TypeToString(mExpectingType).c_str()), nameRefNode);
  19563. return;
  19564. }
  19565. BfTypedValue expectingVal(expectingTypeInst);
  19566. mResult = LookupField(memberRefExpr->mMemberName, expectingVal, findName);
  19567. if ((mResult) || (mPropDef != NULL))
  19568. return;
  19569. }
  19570. bool isNullCondLookup = (memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_QuestionDot);
  19571. bool isCascade = ((memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_DotDot));
  19572. bool isArrowLookup = ((memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_Arrow));
  19573. BfIdentifierNode* nameLeft = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mTarget);
  19574. BfIdentifierNode* nameRight = BfIdentifierCast(memberRefExpr->mMemberName);
  19575. if ((nameLeft != NULL) && (nameRight != NULL) && (!isNullCondLookup) && (!isCascade) && (!isArrowLookup))
  19576. {
  19577. bool hadError = false;
  19578. LookupQualifiedName(memberRefExpr, nameLeft, nameRight, true, &hadError);
  19579. if ((mResult) || (mPropDef != NULL))
  19580. return;
  19581. if (hadError)
  19582. return;
  19583. LookupQualifiedStaticField(memberRefExpr, nameLeft, nameRight, false);
  19584. return;
  19585. }
  19586. BfTypedValue thisValue;
  19587. if (auto exprTarget = BfNodeDynCast<BfExpression>(memberRefExpr->mTarget))
  19588. {
  19589. if (auto typeOfExpr = BfNodeDynCast<BfTypeOfExpression>(memberRefExpr->mTarget))
  19590. {
  19591. if (auto nameIdentifer = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  19592. {
  19593. if (LookupTypeProp(typeOfExpr, nameIdentifer))
  19594. return;
  19595. }
  19596. }
  19597. //Hm, not using VisitChild broke our ability to write to a field for a not-initialized local struct
  19598. VisitChild(memberRefExpr->mTarget);
  19599. GetResult();
  19600. thisValue = mResult;
  19601. if (!thisValue)
  19602. {
  19603. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(exprTarget))
  19604. {
  19605. thisValue = BfTypedValue(mModule->ResolveTypeRef(targetIdentifier, NULL, BfPopulateType_Declaration));
  19606. }
  19607. }
  19608. if (!thisValue.HasType())
  19609. return;
  19610. //thisValue = mResult;
  19611. }
  19612. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpr->mTarget))
  19613. {
  19614. // Look up static field
  19615. thisValue = BfTypedValue(ResolveTypeRef(typeRef));
  19616. }
  19617. if (nameRefNode == NULL)
  19618. {
  19619. mModule->AssertErrorState();
  19620. return;
  19621. }
  19622. if (isNullCondLookup)
  19623. thisValue = SetupNullConditional(thisValue, memberRefExpr->mDotToken);
  19624. if ((isArrowLookup) && (thisValue))
  19625. thisValue = TryArrowLookup(thisValue, memberRefExpr->mDotToken);
  19626. auto nameNode = memberRefExpr->mMemberName;
  19627. if ((thisValue.mType != NULL) && (!thisValue.mType->IsTypeInstance()) && (!thisValue.mType->IsGenericParam()))
  19628. {
  19629. if (thisValue.mType->IsSizedArray())
  19630. {
  19631. if (thisValue.mType->IsValuelessType())
  19632. {
  19633. thisValue.mType = mModule->GetWrappedStructType(thisValue.mType);
  19634. thisValue.mValue = mModule->mBfIRBuilder->GetFakeVal();
  19635. }
  19636. else
  19637. {
  19638. thisValue = mModule->MakeAddressable(thisValue);
  19639. thisValue.mType = mModule->GetWrappedStructType(thisValue.mType);
  19640. thisValue.mValue = mModule->mBfIRBuilder->CreateBitCast(thisValue.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(thisValue.mType->ToTypeInstance()));
  19641. }
  19642. }
  19643. else if (thisValue.mType->IsPointer())
  19644. {
  19645. // Leave alone
  19646. }
  19647. else if (thisValue.mType->IsWrappableType())
  19648. {
  19649. thisValue.mType = mModule->GetWrappedStructType(thisValue.mType);
  19650. }
  19651. }
  19652. BfTypedValue lookupVal = thisValue;
  19653. if (thisValue.mType != NULL)
  19654. {
  19655. auto lookupType = BindGenericType(nameNode, thisValue.mType);
  19656. if ((lookupType->IsGenericParam()) && (!thisValue.mType->IsGenericParam()))
  19657. {
  19658. bool prevUseMixinGenerics = false;
  19659. if (mModule->mCurMethodState->mMixinState != NULL)
  19660. {
  19661. prevUseMixinGenerics = mModule->mCurMethodState->mMixinState->mUseMixinGenerics;
  19662. mModule->mCurMethodState->mMixinState->mUseMixinGenerics = true;
  19663. }
  19664. // Try to lookup from generic binding
  19665. mResult = LookupField(nameRight, BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), lookupType), findName, BfLookupFieldFlag_BindOnly);
  19666. if (mModule->mCurMethodState->mMixinState != NULL)
  19667. mModule->mCurMethodState->mMixinState->mUseMixinGenerics = prevUseMixinGenerics;
  19668. if (mPropDef != NULL)
  19669. {
  19670. mOrigPropTarget = lookupVal;
  19671. return;
  19672. }
  19673. }
  19674. }
  19675. mResult = LookupField(nameRefNode, lookupVal, findName);
  19676. if ((!mResult) && (mPropDef == NULL))
  19677. {
  19678. if (thisValue.mType != NULL)
  19679. {
  19680. BfTypeInstance* typeInst = thisValue.mType->ToTypeInstance();
  19681. auto compiler = mModule->mCompiler;
  19682. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(memberRefExpr->mMemberName)))
  19683. {
  19684. FixitAddMember(typeInst, mExpectingType, findName, !thisValue.mValue);
  19685. }
  19686. }
  19687. if ((!thisValue.mValue) && (thisValue.mType != NULL))
  19688. {
  19689. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  19690. {
  19691. if ((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0)
  19692. {
  19693. auto typeInst = thisValue.mType->ToTypeInstance();
  19694. if ((typeInst != NULL) && (CheckForMethodName(nameRight, typeInst, findName)))
  19695. return;
  19696. }
  19697. mResult.mType = mModule->ResolveInnerType(thisValue.mType, targetIdentifier, BfPopulateType_Declaration);
  19698. }
  19699. }
  19700. if ((memberRefExpr->mTarget == NULL) && (expectingTypeInst != NULL) && (autoComplete != NULL))
  19701. {
  19702. if (autoComplete->CheckFixit(memberRefExpr->mMemberName))
  19703. {
  19704. autoComplete->FixitAddCase(expectingTypeInst, memberRefExpr->mMemberName->ToString(), BfTypeVector());
  19705. }
  19706. }
  19707. if (mResult.mType == NULL)
  19708. {
  19709. if (mModule->PreFail())
  19710. {
  19711. if ((thisValue) && (thisValue.mType->IsPointer()) && (thisValue.mType->GetUnderlyingType()->IsObjectOrInterface()))
  19712. mModule->Fail(StrFormat("Members cannot be referenced on type '%s' because the type is a pointer to a reference type (ie: a double-reference).",
  19713. mModule->TypeToString(thisValue.mType).c_str()), nameRefNode);
  19714. else if (thisValue)
  19715. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", findName.c_str(), mModule->TypeToString(thisValue.mType).c_str()), nameRefNode);
  19716. else
  19717. mModule->Fail("Unable to find member", nameRefNode);
  19718. }
  19719. }
  19720. }
  19721. if ((isNullCondLookup) && (mPropDef == NULL))
  19722. mResult = GetResult();
  19723. if (isCascade)
  19724. {
  19725. if (outCascadeValue != NULL)
  19726. *outCascadeValue = thisValue;
  19727. else if (mModule->PreFail())
  19728. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", memberRefExpr->mDotToken);
  19729. }
  19730. }
  19731. void BfExprEvaluator::Visit(BfMemberReferenceExpression* memberRefExpr)
  19732. {
  19733. DoMemberReference(memberRefExpr, NULL);
  19734. }
  19735. void BfExprEvaluator::Visit(BfIndexerExpression* indexerExpr)
  19736. {
  19737. HandleIndexerExpression(indexerExpr, BfTypedValue());
  19738. }
  19739. void BfExprEvaluator::HandleIndexerExpression(BfIndexerExpression* indexerExpr, BfTypedValue target)
  19740. {
  19741. BfAstNode* refNode = indexerExpr->mOpenBracket;
  19742. if (refNode == NULL)
  19743. refNode = indexerExpr->mTarget;
  19744. bool wantStatic = false;
  19745. // Try first as a non-static indexer, then as a static indexer
  19746. if (!target)
  19747. {
  19748. for (int pass = 0; pass < 2; pass++)
  19749. {
  19750. ///
  19751. {
  19752. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoLookupError | BfEvalExprFlags_AllowBase), pass == 0);
  19753. VisitChild(indexerExpr->mTarget);
  19754. }
  19755. ResolveGenericType();
  19756. target = GetResult(true);
  19757. if (target)
  19758. break;
  19759. if (pass == 0)
  19760. {
  19761. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, (mModule->mIgnoreErrors) || (pass == 0));
  19762. auto staticType = mModule->ResolveTypeRef(indexerExpr->mTarget, {});
  19763. if (staticType != NULL)
  19764. {
  19765. wantStatic = true;
  19766. target.mType = staticType;
  19767. break;
  19768. }
  19769. }
  19770. }
  19771. }
  19772. if (!target.HasType())
  19773. return;
  19774. if (target.mType->IsGenericParam())
  19775. {
  19776. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)target.mType);
  19777. if (genericParamInstance->mTypeConstraint != NULL)
  19778. target.mType = genericParamInstance->mTypeConstraint;
  19779. }
  19780. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  19781. bool isInlined = false;
  19782. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  19783. {
  19784. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  19785. {
  19786. isInlined = true;
  19787. mModule->mAttributeState->mUsed = true;
  19788. }
  19789. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  19790. {
  19791. checkedKind = BfCheckedKind_Checked;
  19792. mModule->mAttributeState->mUsed = true;
  19793. }
  19794. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  19795. {
  19796. checkedKind = BfCheckedKind_Unchecked;
  19797. mModule->mAttributeState->mUsed = true;
  19798. }
  19799. }
  19800. // Avoid attempting to apply the current attributes to the indexer arguments
  19801. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, NULL);
  19802. bool isNullCondLookup = (indexerExpr->mOpenBracket != NULL) && (indexerExpr->mOpenBracket->GetToken() == BfToken_QuestionLBracket);
  19803. if (isNullCondLookup)
  19804. target = SetupNullConditional(target, indexerExpr->mOpenBracket);
  19805. if (target.mType->IsVar())
  19806. {
  19807. mResult = BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  19808. return;
  19809. }
  19810. if ((target.mType->IsTypeInstance()) || (target.mType->IsGenericParam()))
  19811. {
  19812. BfGenericParamInstance* genericParamInstance = NULL;
  19813. if (target.mType->IsGenericParam())
  19814. genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)target.mType);
  19815. mIndexerValues.clear();
  19816. SizedArray<BfExpression*, 2> argExprs;
  19817. BfSizedArray<BfExpression*> sizedArgExprs(indexerExpr->mArguments);
  19818. BfResolvedArgs argValues(&sizedArgExprs);
  19819. ResolveArgValues(argValues, (BfResolveArgsFlags)(BfResolveArgsFlag_DeferParamEval | BfResolveArgsFlag_FromIndexer));
  19820. mIndexerValues = argValues.mResolvedArgs;
  19821. BfMethodMatcher methodMatcher(indexerExpr->mTarget, mModule, "[]", mIndexerValues, BfMethodGenericArguments());
  19822. methodMatcher.mCheckedKind = checkedKind;
  19823. BfMethodDef* methodDef = NULL;
  19824. auto startCheckTypeInst = target.mType->ToTypeInstance();
  19825. auto lookupType = target.mType;
  19826. if (lookupType != NULL)
  19827. {
  19828. lookupType = BindGenericType(refNode, lookupType);
  19829. if (lookupType->IsGenericParam())
  19830. startCheckTypeInst = NULL;
  19831. }
  19832. for (int pass = 0; pass < 2; pass++)
  19833. {
  19834. bool isFailurePass = pass == 1;
  19835. BfPropertyDef* foundProp = NULL;
  19836. BfTypeInstance* foundPropTypeInst = NULL;
  19837. BfBaseClassWalker baseClassWalker(lookupType, NULL, mModule, true);
  19838. while (true)
  19839. {
  19840. auto checkEntry = baseClassWalker.Next();
  19841. auto curCheckType = checkEntry.mTypeInstance;
  19842. if (curCheckType == NULL)
  19843. break;
  19844. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  19845. curCheckType->mTypeDef->PopulateMemberSets();
  19846. BfMemberSetEntry* entry;
  19847. BfPropertyDef* matchedProp = NULL;
  19848. BfPropertyDef* nextProp = NULL;
  19849. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(String("[]"), &entry))
  19850. nextProp = (BfPropertyDef*)entry->mMemberDef;
  19851. while (nextProp != NULL)
  19852. {
  19853. auto prop = nextProp;
  19854. nextProp = nextProp->mNextWithSameName;
  19855. //TODO: Match against setMethod (minus last param) if we have no 'get' method
  19856. for (auto checkMethod : prop->mMethods)
  19857. {
  19858. if (checkMethod->mMethodType != BfMethodType_PropertyGetter)
  19859. continue;
  19860. if (checkMethod->mIsStatic != wantStatic)
  19861. continue;
  19862. if (checkMethod->mExplicitInterface != NULL)
  19863. continue;
  19864. auto autoComplete = GetAutoComplete();
  19865. bool wasCapturingMethodMatchInfo = false;
  19866. if (autoComplete != NULL)
  19867. {
  19868. // Set to false to make sure we don't capture method match info from 'params' array creation
  19869. wasCapturingMethodMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  19870. autoComplete->mIsCapturingMethodMatchInfo = false;
  19871. }
  19872. defer
  19873. (
  19874. if (autoComplete != NULL)
  19875. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMethodMatchInfo;
  19876. );
  19877. if ((!isFailurePass) && (!methodMatcher.WantsCheckMethod(protectionCheckFlags, startCheckTypeInst, curCheckType, checkMethod)))
  19878. continue;
  19879. if (!methodMatcher.IsMemberAccessible(curCheckType, checkMethod->mDeclaringType))
  19880. continue;
  19881. methodMatcher.mCheckedKind = checkedKind;
  19882. methodMatcher.mTarget = target;
  19883. bool hadMatch = methodMatcher.CheckMethod(startCheckTypeInst, curCheckType, checkMethod, false);
  19884. if ((hadMatch) || (methodMatcher.mBackupMethodDef == checkMethod))
  19885. {
  19886. foundPropTypeInst = curCheckType;
  19887. foundProp = prop;
  19888. }
  19889. }
  19890. }
  19891. curCheckType = curCheckType->mBaseType;
  19892. }
  19893. if (foundProp != NULL)
  19894. {
  19895. mPropSrc = indexerExpr->mOpenBracket;
  19896. mPropDef = foundProp;
  19897. if (foundProp->mIsStatic)
  19898. {
  19899. mPropTarget = BfTypedValue(foundPropTypeInst);
  19900. }
  19901. else
  19902. {
  19903. if (target.mType != foundPropTypeInst)
  19904. mPropTarget = mModule->Cast(indexerExpr->mTarget, target, foundPropTypeInst);
  19905. else
  19906. mPropTarget = target;
  19907. }
  19908. mOrigPropTarget = mPropTarget;
  19909. if (isInlined)
  19910. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  19911. mPropCheckedKind = checkedKind;
  19912. if ((target.IsBase()) && (mPropDef->IsVirtual()))
  19913. mPropDefBypassVirtual = true;
  19914. return;
  19915. }
  19916. }
  19917. mModule->Fail("Unable to find indexer property", indexerExpr->mTarget);
  19918. return;
  19919. }
  19920. bool wantsChecks = checkedKind == BfCheckedKind_Checked;
  19921. if (checkedKind == BfCheckedKind_NotSet)
  19922. wantsChecks = mModule->GetDefaultCheckedKind() == BfCheckedKind_Checked;
  19923. if (target.mType->IsVar())
  19924. {
  19925. mResult = target;
  19926. return;
  19927. }
  19928. if ((!target.mType->IsPointer()) && (!target.mType->IsSizedArray()))
  19929. {
  19930. mModule->Fail("Expected pointer or array type", indexerExpr->mTarget);
  19931. return;
  19932. }
  19933. auto _GetDefaultResult = [&]()
  19934. {
  19935. return mModule->GetDefaultTypedValue(target.mType->GetUnderlyingType(), false, BfDefaultValueKind_Addr);
  19936. };
  19937. if (indexerExpr->mArguments.size() != 1)
  19938. {
  19939. mModule->Fail("Expected single index", indexerExpr->mOpenBracket);
  19940. mResult = _GetDefaultResult();
  19941. return;
  19942. }
  19943. if (indexerExpr->mArguments[0] == NULL)
  19944. {
  19945. mModule->AssertErrorState();
  19946. mResult = _GetDefaultResult();
  19947. return;
  19948. }
  19949. bool isUndefIndex = false;
  19950. auto indexArgument = mModule->CreateValueFromExpression(indexerExpr->mArguments[0], mModule->GetPrimitiveType(BfTypeCode_IntPtr), BfEvalExprFlags_NoCast);
  19951. if (!indexArgument)
  19952. return;
  19953. if (!indexArgument.mType->IsIntegral())
  19954. {
  19955. if (indexArgument.mType->IsVar())
  19956. {
  19957. isUndefIndex = true;
  19958. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr), false, BfDefaultValueKind_Undef);
  19959. }
  19960. else
  19961. {
  19962. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  19963. if (!indexArgument)
  19964. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  19965. }
  19966. }
  19967. if (indexArgument.mType->IsPrimitiveType())
  19968. {
  19969. auto primType = (BfPrimitiveType*)indexArgument.mType;
  19970. if ((!primType->IsSigned()) && (primType->mSize < 8))
  19971. {
  19972. // GEP will always do a signed upcast so we need to cast manually if we are unsigned
  19973. indexArgument = BfTypedValue(mModule->mBfIRBuilder->CreateNumericCast(indexArgument.mValue, false, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  19974. }
  19975. }
  19976. mModule->PopulateType(target.mType);
  19977. if (target.mType->IsSizedArray())
  19978. {
  19979. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)target.mType;
  19980. auto underlyingType = sizedArrayType->mElementType;
  19981. if (indexArgument.mValue.IsConst())
  19982. {
  19983. auto indexConst = mModule->mBfIRBuilder->GetConstant(indexArgument.mValue);
  19984. if ((BfIRBuilder::IsIntable(indexConst->mTypeCode)) && (indexConst->mUInt64 >= (uint64)sizedArrayType->mElementCount))
  19985. {
  19986. if ((!mModule->IsInSpecializedSection()) && (checkedKind != BfCheckedKind_Unchecked))
  19987. {
  19988. mModule->Fail(StrFormat("Index '%d' is out of bounds for type '%s'", indexConst->mInt32, mModule->TypeToString(target.mType).c_str()), indexerExpr->mArguments[0]);
  19989. mResult = _GetDefaultResult();
  19990. return;
  19991. }
  19992. else
  19993. {
  19994. // Is this any good?
  19995. mModule->mBfIRBuilder->CreateUnreachable();
  19996. }
  19997. }
  19998. }
  19999. else if (((mModule->HasExecutedOutput()) || (mModule->mIsComptimeModule)) &&
  20000. (wantsChecks))
  20001. {
  20002. if (checkedKind == BfCheckedKind_NotSet)
  20003. checkedKind = mModule->GetDefaultCheckedKind();
  20004. if (checkedKind == BfCheckedKind_Checked)
  20005. {
  20006. auto oobBlock = mModule->mBfIRBuilder->CreateBlock("oob", true);
  20007. auto contBlock = mModule->mBfIRBuilder->CreateBlock("cont", true);
  20008. auto indexType = (BfPrimitiveType*)indexArgument.mType;
  20009. if (!mModule->mSystem->DoesLiteralFit(indexType->mTypeDef->mTypeCode, (int64)sizedArrayType->mElementCount))
  20010. {
  20011. // We need to upsize the index so we can compare it against the larger elementCount
  20012. indexType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  20013. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, indexType);
  20014. }
  20015. auto cmpRes = mModule->mBfIRBuilder->CreateCmpGTE(indexArgument.mValue, mModule->mBfIRBuilder->CreateConst(indexType->mTypeDef->mTypeCode, (uint64)sizedArrayType->mElementCount), false);
  20016. mModule->mBfIRBuilder->CreateCondBr(cmpRes, oobBlock, contBlock);
  20017. mModule->mBfIRBuilder->SetInsertPoint(oobBlock);
  20018. auto internalType = mModule->ResolveTypeDef(mModule->mCompiler->mInternalTypeDef);
  20019. auto oobFunc = mModule->GetMethodByName(internalType->ToTypeInstance(), "ThrowIndexOutOfRange");
  20020. if (oobFunc.mFunc)
  20021. {
  20022. if (mModule->mIsComptimeModule)
  20023. mModule->mCompiler->mCeMachine->QueueMethod(oobFunc.mMethodInstance, oobFunc.mFunc);
  20024. SizedArray<BfIRValue, 1> args;
  20025. args.push_back(mModule->GetConstValue(0));
  20026. mModule->mBfIRBuilder->CreateCall(oobFunc.mFunc, args);
  20027. mModule->mBfIRBuilder->CreateUnreachable();
  20028. }
  20029. else
  20030. {
  20031. mModule->Fail("System.Internal class must contain method 'ThrowIndexOutOfRange'");
  20032. }
  20033. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  20034. }
  20035. }
  20036. // If this is a 'bag of bytes', we should try hard not to have to make this addressable
  20037. if ((!target.IsAddr()) && (!target.mType->IsSizeAligned()))
  20038. mModule->MakeAddressable(target);
  20039. mResult = BfTypedValue();
  20040. mModule->PopulateType(underlyingType);
  20041. if ((sizedArrayType->IsUndefSizedArray()) || (isUndefIndex))
  20042. {
  20043. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  20044. }
  20045. else if (sizedArrayType->IsValuelessType())
  20046. {
  20047. if (underlyingType->IsValuelessType())
  20048. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), underlyingType, true);
  20049. else
  20050. {
  20051. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  20052. }
  20053. }
  20054. else if (target.IsAddr())
  20055. {
  20056. // Handle below
  20057. }
  20058. else
  20059. {
  20060. if ((!target.mValue.IsConst()) && (!indexArgument.mValue.IsConst()))
  20061. {
  20062. target = mModule->MakeAddressable(target);
  20063. }
  20064. else
  20065. {
  20066. mModule->mBfIRBuilder->PopulateType(target.mType);
  20067. auto gepResult = mModule->mBfIRBuilder->CreateExtractValue(target.mValue, indexArgument.mValue);
  20068. if ((underlyingType->IsString()) || (underlyingType->IsPointer()))
  20069. {
  20070. auto resultConst = mModule->mBfIRBuilder->GetConstant(gepResult);
  20071. if ((resultConst != NULL) && (resultConst->mTypeCode == BfTypeCode_Int32))
  20072. {
  20073. int strId = resultConst->mInt32;
  20074. const StringImpl& str = mModule->mContext->mStringObjectIdMap[strId].mString;
  20075. if (underlyingType->IsString())
  20076. gepResult = mModule->GetStringObjectValue(str, false);
  20077. else
  20078. gepResult = mModule->GetStringCharPtr(strId);
  20079. }
  20080. }
  20081. mResult = BfTypedValue(gepResult, underlyingType, BfTypedValueKind_Value);
  20082. }
  20083. }
  20084. if ((!mResult) && (target.IsAddr()))
  20085. {
  20086. if (target.mType->IsSizeAligned())
  20087. {
  20088. auto gepResult = mModule->mBfIRBuilder->CreateInBoundsGEP(target.mValue, mModule->GetConstValue(0), indexArgument.mValue);
  20089. mResult = BfTypedValue(gepResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  20090. }
  20091. else
  20092. {
  20093. auto indexResult = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  20094. mResult = BfTypedValue(indexResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  20095. }
  20096. }
  20097. if (!mResult)
  20098. {
  20099. mModule->Fail("Unable to index value", indexerExpr->mTarget);
  20100. return;
  20101. }
  20102. }
  20103. else
  20104. {
  20105. // We are no longer accessing data within this type
  20106. mResultLocalVar = NULL;
  20107. target = mModule->LoadValue(target);
  20108. BfPointerType* pointerType = (BfPointerType*)target.mType;
  20109. auto underlyingType = pointerType->mElementType;
  20110. mModule->mBfIRBuilder->PopulateType(underlyingType);
  20111. if (underlyingType->IsOpaque())
  20112. {
  20113. mModule->Fail(StrFormat("Unable to index opaque pointer type '%s'", mModule->TypeToString(pointerType).c_str()), indexerExpr);
  20114. }
  20115. else if (isUndefIndex)
  20116. {
  20117. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  20118. }
  20119. else
  20120. {
  20121. BfIRValue result = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  20122. mResult = BfTypedValue(result, underlyingType, true);
  20123. }
  20124. }
  20125. }
  20126. void BfExprEvaluator::Visit(BfUnaryOperatorExpression* unaryOpExpr)
  20127. {
  20128. BfAutoParentNodeEntry autoParentNodeEntry(mModule, unaryOpExpr);
  20129. PerformUnaryOperation(unaryOpExpr->mExpression, unaryOpExpr->mOp, unaryOpExpr->mOpToken, BfUnaryOpFlag_None);
  20130. }
  20131. void BfExprEvaluator::PerformUnaryOperation(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  20132. {
  20133. if ((unaryOpExpr == NULL) && (unaryOp == BfUnaryOp_PartialRangeThrough))
  20134. {
  20135. PerformBinaryOperation(NULL, NULL, BfBinaryOp_ClosedRange, opToken, BfBinOpFlag_None);
  20136. return;
  20137. }
  20138. ///
  20139. {
  20140. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags);
  20141. BfType* prevExpedcting = mExpectingType;
  20142. switch (unaryOp)
  20143. {
  20144. case BfUnaryOp_Ref:
  20145. // Allow
  20146. break;
  20147. case BfUnaryOp_Dereference:
  20148. if (mExpectingType != NULL)
  20149. {
  20150. if (mExpectingType->IsRef())
  20151. mExpectingType = mExpectingType->GetUnderlyingType();
  20152. if (!mExpectingType->IsVar())
  20153. mExpectingType = mModule->CreatePointerType(mExpectingType);
  20154. }
  20155. break;
  20156. case BfUnaryOp_Negate:
  20157. case BfUnaryOp_Positive:
  20158. case BfUnaryOp_InvertBits:
  20159. // If we're expecting an int64 or uint64 then just leave the type as unknown
  20160. if ((mExpectingType != NULL) && (mExpectingType->IsInteger()) && (mExpectingType->mSize == 8))
  20161. mExpectingType = NULL;
  20162. // Otherwise keep expecting type
  20163. break;
  20164. case BfUnaryOp_Params:
  20165. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_InParamsExpr);
  20166. break;
  20167. default:
  20168. mExpectingType = NULL;
  20169. }
  20170. VisitChild(unaryOpExpr);
  20171. mExpectingType = prevExpedcting;
  20172. }
  20173. BfExprEvaluator::PerformUnaryOperation_OnResult(unaryOpExpr, unaryOp, opToken, opFlags);
  20174. }
  20175. BfTypedValue BfExprEvaluator::PerformUnaryOperation_TryOperator(const BfTypedValue& inValue, BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  20176. {
  20177. if ((!inValue.mType->IsTypeInstance()) && (!inValue.mType->IsGenericParam()))
  20178. return BfTypedValue();
  20179. SizedArray<BfResolvedArg, 1> args;
  20180. BfResolvedArg resolvedArg;
  20181. resolvedArg.mTypedValue = inValue;
  20182. args.push_back(resolvedArg);
  20183. BfMethodMatcher methodMatcher(opToken, mModule, "", args, BfMethodGenericArguments());
  20184. methodMatcher.mBfEvalExprFlags = BfEvalExprFlags_NoAutoComplete;
  20185. methodMatcher.mAllowImplicitRef = true;
  20186. BfBaseClassWalker baseClassWalker(inValue.mType, NULL, mModule);
  20187. BfUnaryOp findOp = unaryOp;
  20188. bool isPostOp = false;
  20189. if (findOp == BfUnaryOp_PostIncrement)
  20190. {
  20191. findOp = BfUnaryOp_Increment;
  20192. isPostOp = true;
  20193. }
  20194. if (findOp == BfUnaryOp_PostDecrement)
  20195. {
  20196. findOp = BfUnaryOp_Decrement;
  20197. isPostOp = true;
  20198. }
  20199. bool isConstraintCheck = ((opFlags & BfUnaryOpFlag_IsConstraintCheck) != 0);
  20200. BfType* operatorConstraintReturnType = NULL;
  20201. BfType* bestSelfType = NULL;
  20202. while (true)
  20203. {
  20204. auto entry = baseClassWalker.Next();
  20205. auto checkType = entry.mTypeInstance;
  20206. if (checkType == NULL)
  20207. break;
  20208. for (auto operatorDef : checkType->mTypeDef->mOperators)
  20209. {
  20210. if (operatorDef->mOperatorDeclaration->mUnaryOp == findOp)
  20211. {
  20212. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  20213. continue;
  20214. int prevArgSize = (int)args.mSize;
  20215. if (!operatorDef->mIsStatic)
  20216. {
  20217. // Try without arg
  20218. args.mSize = 0;
  20219. }
  20220. if (isConstraintCheck)
  20221. {
  20222. auto returnType = mModule->CheckOperator(checkType, operatorDef, inValue, BfTypedValue());
  20223. if (returnType != NULL)
  20224. {
  20225. operatorConstraintReturnType = returnType;
  20226. methodMatcher.mBestMethodDef = operatorDef;
  20227. }
  20228. }
  20229. else
  20230. {
  20231. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  20232. methodMatcher.mSelfType = entry.mSrcType;
  20233. }
  20234. args.mSize = prevArgSize;
  20235. }
  20236. }
  20237. }
  20238. methodMatcher.FlushAmbiguityError();
  20239. if (methodMatcher.mBestMethodDef == NULL)
  20240. {
  20241. // Check method generic constraints
  20242. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  20243. {
  20244. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  20245. {
  20246. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  20247. for (auto& opConstraint : genericParam->mOperatorConstraints)
  20248. {
  20249. if (opConstraint.mUnaryOp == findOp)
  20250. {
  20251. if (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType, isConstraintCheck ? BfCastFlags_IsConstraintCheck : BfCastFlags_None))
  20252. {
  20253. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  20254. }
  20255. }
  20256. }
  20257. }
  20258. }
  20259. // Check type generic constraints
  20260. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  20261. {
  20262. auto genericTypeInst = (BfTypeInstance*)mModule->mCurTypeInstance;
  20263. for (int genericParamIdx = 0; genericParamIdx < genericTypeInst->mGenericTypeInfo->mGenericParams.size(); genericParamIdx++)
  20264. {
  20265. auto genericParam = mModule->GetGenericTypeParamInstance(genericParamIdx);
  20266. for (auto& opConstraint : genericParam->mOperatorConstraints)
  20267. {
  20268. if (opConstraint.mUnaryOp == findOp)
  20269. {
  20270. if (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType, isConstraintCheck ? BfCastFlags_IsConstraintCheck : BfCastFlags_None))
  20271. {
  20272. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  20273. }
  20274. }
  20275. }
  20276. }
  20277. }
  20278. return BfTypedValue();
  20279. }
  20280. if ((!baseClassWalker.mMayBeFromInterface) && (opToken != NULL))
  20281. mModule->SetElementType(opToken, BfSourceElementType_Method);
  20282. auto methodDef = methodMatcher.mBestMethodDef;
  20283. auto autoComplete = GetAutoComplete();
  20284. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  20285. {
  20286. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  20287. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  20288. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  20289. }
  20290. SizedArray<BfExpression*, 2> argSrcs;
  20291. argSrcs.push_back(unaryOpExpr);
  20292. BfTypedValue targetVal = args[0].mTypedValue;
  20293. BfTypedValue postOpVal;
  20294. if (isPostOp)
  20295. postOpVal = mModule->LoadValue(targetVal);
  20296. BfTypedValue callTarget;
  20297. if (!methodMatcher.mBestMethodDef->mIsStatic)
  20298. {
  20299. callTarget = targetVal;
  20300. args.Clear();
  20301. }
  20302. BfTypedValue result;
  20303. if (isConstraintCheck)
  20304. {
  20305. result = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), operatorConstraintReturnType);
  20306. }
  20307. else
  20308. {
  20309. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  20310. SetAndRestoreValue<BfAstNode*> prevDeferCallRef(mDeferCallRef, NULL);
  20311. result = CreateCall(&methodMatcher, callTarget);
  20312. }
  20313. if (!methodMatcher.mBestMethodDef->mIsStatic)
  20314. {
  20315. if (!isPostOp)
  20316. result = mModule->LoadValue(targetVal);
  20317. }
  20318. else if ((result.mType != NULL) && (methodMatcher.mSelfType != NULL) && (result.mType->IsSelf()))
  20319. {
  20320. BF_ASSERT(mModule->IsInGeneric());
  20321. result = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  20322. }
  20323. if ((methodMatcher.mBestMethodInstance) &&
  20324. ((findOp == BfUnaryOp_Increment) || (findOp == BfUnaryOp_Decrement)))
  20325. {
  20326. if (methodMatcher.mBestMethodInstance.mMethodInstance->mIsIntrinsic)
  20327. {
  20328. if (args[0].mTypedValue.IsAddr())
  20329. mModule->mBfIRBuilder->CreateStore(result.mValue, args[0].mTypedValue.mValue);
  20330. else
  20331. {
  20332. mModule->AssertErrorState();
  20333. }
  20334. }
  20335. else
  20336. {
  20337. if (!result.mType->IsValuelessType())
  20338. {
  20339. if (targetVal.IsAddr())
  20340. {
  20341. result = mModule->LoadValue(result);
  20342. mModule->mBfIRBuilder->CreateStore(result.mValue, targetVal.mValue);
  20343. }
  20344. }
  20345. }
  20346. }
  20347. if (postOpVal)
  20348. result = postOpVal;
  20349. return result;
  20350. }
  20351. void BfExprEvaluator::PerformUnaryOperation_OnResult(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  20352. {
  20353. BfAstNode* propSrc = mPropSrc;
  20354. BfTypedValue origPropTarget = mOrigPropTarget;
  20355. BfTypedValue propTarget = mPropTarget;
  20356. BfPropertyDef* propDef = mPropDef;
  20357. SizedArray<BfResolvedArg, 2> indexerVals = mIndexerValues;
  20358. BfTypedValue writeToProp;
  20359. GetResult();
  20360. if (!mResult)
  20361. return;
  20362. mResult = mModule->RemoveRef(mResult);
  20363. if (mResult.mType->IsVar())
  20364. {
  20365. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType);
  20366. return;
  20367. }
  20368. if (BfCanOverloadOperator(unaryOp))
  20369. {
  20370. auto opResult = PerformUnaryOperation_TryOperator(mResult, unaryOpExpr, unaryOp, opToken, opFlags);
  20371. if (opResult)
  20372. {
  20373. mResult = opResult;
  20374. return;
  20375. }
  20376. }
  20377. switch (unaryOp)
  20378. {
  20379. case BfUnaryOp_PostIncrement:
  20380. case BfUnaryOp_Increment:
  20381. case BfUnaryOp_PostDecrement:
  20382. case BfUnaryOp_Decrement:
  20383. {
  20384. if (mResult.mKind == BfTypedValueKind_CopyOnMutateAddr)
  20385. {
  20386. // Support this ops on direct auto-property access without a copy
  20387. mResult.mKind = BfTypedValueKind_Addr;
  20388. }
  20389. }
  20390. break;
  20391. }
  20392. bool numericFail = false;
  20393. switch (unaryOp)
  20394. {
  20395. case BfUnaryOp_Not:
  20396. {
  20397. CheckResultForReading(mResult);
  20398. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  20399. auto value = mModule->LoadValue(mResult);
  20400. value = mModule->Cast(unaryOpExpr, value, boolType);
  20401. if (!value)
  20402. {
  20403. mResult = BfTypedValue();
  20404. return;
  20405. }
  20406. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), boolType);
  20407. }
  20408. break;
  20409. case BfUnaryOp_Positive:
  20410. return;
  20411. case BfUnaryOp_Negate:
  20412. {
  20413. CheckResultForReading(mResult);
  20414. auto value = mModule->LoadValue(mResult);
  20415. if (!value)
  20416. {
  20417. mResult = BfTypedValue();
  20418. return;
  20419. }
  20420. BfType* origType = value.mType;
  20421. if (value.mType->IsTypedPrimitive())
  20422. value.mType = value.mType->GetUnderlyingType();
  20423. if (value.mType->IsIntegral())
  20424. {
  20425. auto primType = (BfPrimitiveType*)value.mType;
  20426. auto wantType = primType;
  20427. auto constant = mModule->mBfIRBuilder->GetConstant(value.mValue);
  20428. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  20429. {
  20430. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (constant->mInt64 == 0x80000000LL))
  20431. {
  20432. mResult = BfTypedValue(mModule->GetConstValue32(-0x80000000LL), mModule->GetPrimitiveType(BfTypeCode_Int32));
  20433. return;
  20434. }
  20435. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt64) && (constant->mInt64 == 0x8000000000000000LL))
  20436. {
  20437. mResult = BfTypedValue(mModule->GetConstValue64(-0x8000000000000000LL), mModule->GetPrimitiveType(BfTypeCode_Int64));
  20438. return;
  20439. }
  20440. }
  20441. /*if (auto constantInt = dyn_cast<ConstantInt>((Value*)value.mValue))
  20442. {
  20443. int64 i64Val = constantInt->getSExtValue();
  20444. // This is a special case where the user entered -0x80000000 (maxint) but we thought "0x80000000" was a uint in the parser
  20445. // which would get upcasted to an int64 for this negate. Properly bring back down to an int32
  20446. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (i64Val == -0x80000000LL))
  20447. {
  20448. mResult = BfTypedValue(mModule->GetConstValue((int)i64Val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  20449. return;
  20450. }
  20451. }*/
  20452. if (!primType->IsSigned())
  20453. {
  20454. if (primType->mSize == 1)
  20455. wantType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  20456. else if (primType->mSize == 2)
  20457. wantType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  20458. else if (primType->mSize == 4)
  20459. wantType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  20460. else
  20461. mModule->Fail("Operator '-' cannot be applied to uint64", opToken);
  20462. }
  20463. if (primType != wantType)
  20464. {
  20465. value = mModule->Cast(unaryOpExpr, value, wantType, BfCastFlags_Explicit);
  20466. if (!value)
  20467. {
  20468. mResult = BfTypedValue();
  20469. return;
  20470. }
  20471. }
  20472. if (origType->mSize == wantType->mSize) // Allow negative of primitive typed but not if we had to upsize
  20473. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  20474. else
  20475. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), wantType);
  20476. }
  20477. else if (value.mType->IsFloat())
  20478. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  20479. else
  20480. {
  20481. ResolveGenericType();
  20482. if (mResult.mType->IsVar())
  20483. break;
  20484. numericFail = true;
  20485. }
  20486. }
  20487. break;
  20488. case BfUnaryOp_InvertBits:
  20489. {
  20490. CheckResultForReading(mResult);
  20491. auto value = mModule->LoadValue(mResult);
  20492. if (!value)
  20493. return;
  20494. bool isInteger = value.mType->IsIntegral();
  20495. if (value.mType->IsTypedPrimitive())
  20496. isInteger = value.mType->GetUnderlyingType()->IsIntegral();
  20497. if (!isInteger)
  20498. {
  20499. mResult = BfTypedValue();
  20500. mModule->Fail("Operator can only be used on integer types", opToken);
  20501. return;
  20502. }
  20503. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), value.mType);
  20504. }
  20505. break;
  20506. case BfUnaryOp_AddressOf:
  20507. {
  20508. MarkResultUsed();
  20509. mModule->FixIntUnknown(mResult);
  20510. mModule->PopulateType(mResult.mType);
  20511. auto ptrType = mModule->CreatePointerType(mResult.mType);
  20512. if ((mResult.mType->IsValuelessType()) && (!mResult.mType->IsOpaque()))
  20513. {
  20514. if (!mModule->IsInSpecializedSection())
  20515. {
  20516. mModule->Warn(0, StrFormat("Operator '&' results in a sentinel address for zero-sized type '%s'",
  20517. mModule->TypeToString(mResult.mType).c_str()), opToken);
  20518. }
  20519. // Sentinel value
  20520. auto val = mModule->mBfIRBuilder->CreateIntToPtr(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mModule->mBfIRBuilder->MapType(ptrType));
  20521. mResult = BfTypedValue(val, ptrType);
  20522. }
  20523. else if (!CheckModifyResult(mResult, unaryOpExpr, "take address of", false, true))
  20524. {
  20525. if (!mResult.IsAddr())
  20526. mResult = mModule->MakeAddressable(mResult, false, true);
  20527. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  20528. }
  20529. else
  20530. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  20531. }
  20532. break;
  20533. case BfUnaryOp_Dereference:
  20534. {
  20535. CheckResultForReading(mResult);
  20536. if (!mResult.mType->IsPointer())
  20537. {
  20538. mResult = BfTypedValue();
  20539. mModule->Fail("Cannot dereference non-pointer type", unaryOpExpr);
  20540. return;
  20541. }
  20542. if (mResult.mValue.IsConst())
  20543. {
  20544. auto constant = mModule->mBfIRBuilder->GetConstant(mResult.mValue);
  20545. bool isNull = constant->mTypeCode == BfTypeCode_NullPtr;
  20546. if (constant->mConstType == BfConstType_ExtractValue)
  20547. {
  20548. auto constExtract = (BfConstantExtractValue*)constant;
  20549. auto targetConst = mModule->mBfIRBuilder->GetConstantById(constExtract->mTarget);
  20550. if (targetConst->mConstType == BfConstType_AggZero)
  20551. isNull = true;
  20552. }
  20553. if (isNull)
  20554. {
  20555. mModule->Warn(0, "Cannot dereference a null pointer", unaryOpExpr);
  20556. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Addr);
  20557. mResult = mModule->LoadValue(mResult);
  20558. }
  20559. }
  20560. auto derefTarget = mModule->LoadValue(mResult);
  20561. BfPointerType* pointerType = (BfPointerType*)derefTarget.mType;
  20562. auto resolvedType = pointerType->mElementType;
  20563. mModule->PopulateType(resolvedType);
  20564. if (resolvedType->IsValuelessNonOpaqueType())
  20565. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedType, true);
  20566. else
  20567. mResult = BfTypedValue(derefTarget.mValue, resolvedType, true);
  20568. }
  20569. break;
  20570. case BfUnaryOp_PostIncrement:
  20571. case BfUnaryOp_Increment:
  20572. {
  20573. CheckResultForReading(mResult);
  20574. auto ptr = mResult;
  20575. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  20576. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "increment")))
  20577. return;
  20578. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  20579. BfIRValue origVal = origTypedVal.mValue;
  20580. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  20581. BfIRValue resultValue;
  20582. if (ptr.mType->IsPointer())
  20583. {
  20584. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  20585. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  20586. constValue = mModule->GetConstValue(ptrType->mElementType->GetStride(), intPtrType);
  20587. auto i8PtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  20588. BfIRValue origPtrValue = mModule->mBfIRBuilder->CreateBitCast(origVal, i8PtrType);
  20589. BfIRValue newPtrValue = mModule->mBfIRBuilder->CreateInBoundsGEP(origPtrValue, constValue);
  20590. resultValue = mModule->mBfIRBuilder->CreateBitCast(newPtrValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  20591. }
  20592. else
  20593. {
  20594. constValue = mModule->GetConstValue(1, ptr.mType);
  20595. if (!constValue)
  20596. {
  20597. numericFail = true;
  20598. break;
  20599. }
  20600. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()) || (ptr.mType->IsFloat()))
  20601. {
  20602. resultValue = mModule->mBfIRBuilder->CreateAdd(origVal, constValue/*, "inc"*/);
  20603. }
  20604. else
  20605. {
  20606. numericFail = true;
  20607. break;
  20608. }
  20609. }
  20610. if ((propDef != NULL) && (!ptr.IsAddr()))
  20611. writeToProp = BfTypedValue(resultValue, ptr.mType);
  20612. else
  20613. mModule->mBfIRBuilder->CreateAlignedStore(resultValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  20614. if (unaryOp == BfUnaryOp_PostIncrement)
  20615. mResult = BfTypedValue(origVal, ptr.mType, false);
  20616. else
  20617. mResult = BfTypedValue(resultValue, ptr.mType, false);
  20618. }
  20619. break;
  20620. case BfUnaryOp_PostDecrement:
  20621. case BfUnaryOp_Decrement:
  20622. {
  20623. CheckResultForReading(mResult);
  20624. auto ptr = mResult;
  20625. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  20626. //return;
  20627. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "decrement")))
  20628. return;
  20629. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  20630. BfIRValue origVal = origTypedVal.mValue;
  20631. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  20632. BfIRValue resultValue;
  20633. if (ptr.mType->IsPointer())
  20634. {
  20635. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  20636. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  20637. constValue = mModule->GetConstValue(-ptrType->mElementType->GetStride(), intPtrType);
  20638. auto i8PtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  20639. BfIRValue origPtrValue = mModule->mBfIRBuilder->CreateBitCast(origVal, i8PtrType);
  20640. BfIRValue newPtrValue = mModule->mBfIRBuilder->CreateInBoundsGEP(origPtrValue, constValue);
  20641. resultValue = mModule->mBfIRBuilder->CreateBitCast(newPtrValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  20642. }
  20643. else
  20644. {
  20645. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  20646. if (!constValue)
  20647. {
  20648. numericFail = true;
  20649. break;
  20650. }
  20651. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()))
  20652. {
  20653. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  20654. }
  20655. else if (ptr.mType->IsFloat())
  20656. {
  20657. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  20658. }
  20659. else
  20660. {
  20661. numericFail = true;
  20662. break;
  20663. }
  20664. }
  20665. if ((propDef != NULL) && (!ptr.IsAddr()))
  20666. writeToProp = BfTypedValue(resultValue, ptr.mType);
  20667. else
  20668. mModule->mBfIRBuilder->CreateAlignedStore(resultValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  20669. if (unaryOp == BfUnaryOp_PostDecrement)
  20670. mResult = BfTypedValue(origVal, ptr.mType, false);
  20671. else
  20672. mResult = BfTypedValue(resultValue, ptr.mType, false);
  20673. }
  20674. break;
  20675. case BfUnaryOp_Ref:
  20676. case BfUnaryOp_Mut:
  20677. {
  20678. if (mAllowReadOnlyReference)
  20679. {
  20680. if (mResult.mKind == BfTypedValueKind_ReadOnlyAddr)
  20681. mResult.mKind = BfTypedValueKind_Addr;
  20682. }
  20683. CheckResultForReading(mResult);
  20684. if ((unaryOp == BfUnaryOp_Mut) && (!mResult.mType->IsValueType()) && (!mResult.mType->IsGenericParam()))
  20685. {
  20686. // Non-valuetypes types are already mutable, leave them alone...
  20687. break;
  20688. }
  20689. if ((unaryOp != BfUnaryOp_Mut) || (mResult.mKind != BfTypedValueKind_MutableValue))
  20690. {
  20691. if (!CheckModifyResult(mResult, unaryOpExpr, StrFormat("use '%s' on", BfGetOpName(unaryOp)).c_str()))
  20692. {
  20693. // Just leave the non-ref version in mResult
  20694. return;
  20695. }
  20696. }
  20697. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowRefExpr) == 0)
  20698. {
  20699. mResult = BfTypedValue();
  20700. mModule->Fail(StrFormat("Invalid usage of '%s' expression", BfGetOpName(unaryOp)), opToken);
  20701. return;
  20702. }
  20703. ResolveGenericType();
  20704. if (mResult.mType->IsVar())
  20705. break;
  20706. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, (unaryOp == BfUnaryOp_Ref) ? BfRefType::RefKind_Ref : BfRefType::RefKind_Mut));
  20707. }
  20708. break;
  20709. case BfUnaryOp_Out:
  20710. {
  20711. if (!CheckModifyResult(mResult, unaryOpExpr, "use 'out' on"))
  20712. {
  20713. // Just leave the non-ref version in mResult
  20714. return;
  20715. }
  20716. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowOutExpr) == 0)
  20717. {
  20718. mModule->Fail("Invalid usage of 'out' expression", opToken);
  20719. return;
  20720. }
  20721. if (mInsidePendingNullable)
  20722. {
  20723. // 'out' inside null conditionals never actually causes a definite assignment...
  20724. }
  20725. else
  20726. MarkResultAssigned();
  20727. MarkResultUsed();
  20728. ResolveGenericType();
  20729. if (mResult.mType->IsVar())
  20730. break;
  20731. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, BfRefType::RefKind_Out));
  20732. }
  20733. break;
  20734. case BfUnaryOp_Params:
  20735. {
  20736. bool allowParams = (mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) != 0;
  20737. if (allowParams)
  20738. {
  20739. if ((mResultLocalVar != NULL) && (mResultLocalVar->mCompositeCount >= 0)) // Delegate params
  20740. {
  20741. allowParams = true;
  20742. }
  20743. else
  20744. {
  20745. auto origValue = mResult;
  20746. auto isValid = false;
  20747. for (int pass = 0; pass < 2; pass++)
  20748. {
  20749. auto typeInst = mResult.mType->ToTypeInstance();
  20750. auto genericTypeInst = mResult.mType->ToGenericTypeInstance();
  20751. if ((genericTypeInst != NULL) && (genericTypeInst->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  20752. isValid = true;
  20753. else if ((mResult.mType->IsArray()) || (mResult.mType->IsSizedArray()))
  20754. isValid = true;
  20755. else if ((typeInst != NULL) && (pass == 0))
  20756. {
  20757. BfBaseClassWalker baseClassWalker(typeInst, NULL, mModule);
  20758. BfType* bestCastType = NULL;
  20759. while (true)
  20760. {
  20761. auto entry = baseClassWalker.Next();
  20762. auto checkType = entry.mTypeInstance;
  20763. if (checkType == NULL)
  20764. break;
  20765. for (auto operatorDef : checkType->mTypeDef->mOperators)
  20766. {
  20767. if (operatorDef->mOperatorDeclaration->mIsConvOperator)
  20768. {
  20769. if (operatorDef->IsExplicit())
  20770. continue;
  20771. auto methodInstance = mModule->GetRawMethodInstanceAtIdx(typeInst, operatorDef->mIdx);
  20772. auto checkType = methodInstance->mReturnType;
  20773. if (checkType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  20774. bestCastType = checkType;
  20775. else if ((checkType->IsArray()) || (checkType->IsSizedArray()))
  20776. bestCastType = checkType;
  20777. }
  20778. }
  20779. }
  20780. if (bestCastType == NULL)
  20781. break;
  20782. auto castTypedValue = mModule->Cast(opToken, mResult, bestCastType, BfCastFlags_SilentFail);
  20783. if (!castTypedValue)
  20784. break;
  20785. mResult = castTypedValue;
  20786. }
  20787. else
  20788. break;
  20789. }
  20790. if (!isValid)
  20791. {
  20792. mModule->Fail(StrFormat("A 'params' expression cannot be used on type '%s'", mModule->TypeToString(origValue.mType).c_str()), opToken);
  20793. }
  20794. }
  20795. }
  20796. if (allowParams)
  20797. {
  20798. mResult = mModule->LoadValue(mResult);
  20799. if ((mResult.mType != NULL) && (mResult.mType->IsParamsType()))
  20800. mResult.mType = mResult.mType->GetUnderlyingType();
  20801. if (mResult.IsSplat())
  20802. mResult.mKind = BfTypedValueKind_ParamsSplat;
  20803. else
  20804. mResult.mKind = BfTypedValueKind_Params;
  20805. }
  20806. else
  20807. {
  20808. mModule->Fail("Illegal use of 'params' expression", opToken);
  20809. }
  20810. }
  20811. break;
  20812. case BfUnaryOp_Cascade:
  20813. {
  20814. mModule->Fail("Illegal use of argument cascade expression", opToken);
  20815. }
  20816. break;
  20817. case BfUnaryOp_FromEnd:
  20818. {
  20819. CheckResultForReading(mResult);
  20820. auto value = mModule->Cast(unaryOpExpr, mResult, mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  20821. value = mModule->LoadValue(value);
  20822. if (value)
  20823. {
  20824. auto indexType = mModule->ResolveTypeDef(mModule->mCompiler->mIndexTypeDef);
  20825. auto alloca = mModule->CreateAlloca(indexType);
  20826. mModule->mBfIRBuilder->CreateStore(value.mValue, mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->CreateInBoundsGEP(alloca, 0, 1), 0, 1));
  20827. mModule->mBfIRBuilder->CreateStore(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 1), mModule->mBfIRBuilder->CreateInBoundsGEP(alloca, 0, 2));
  20828. mResult = BfTypedValue(alloca, indexType, BfTypedValueKind_Addr);
  20829. }
  20830. }
  20831. break;
  20832. case BfUnaryOp_PartialRangeUpTo:
  20833. PerformBinaryOperation(NULL, unaryOpExpr, BfBinaryOp_Range, opToken, BfBinOpFlag_None);
  20834. break;
  20835. case BfUnaryOp_PartialRangeThrough:
  20836. PerformBinaryOperation(NULL, unaryOpExpr, BfBinaryOp_ClosedRange, opToken, BfBinOpFlag_None);
  20837. break;
  20838. case BfUnaryOp_PartialRangeFrom:
  20839. PerformBinaryOperation(unaryOpExpr, NULL, BfBinaryOp_ClosedRange, opToken, BfBinOpFlag_None);
  20840. break;
  20841. default:
  20842. mModule->Fail(StrFormat("Illegal use of '%s' unary operator", BfGetOpName(unaryOp)), unaryOpExpr);
  20843. break;
  20844. }
  20845. if (numericFail)
  20846. {
  20847. if (opToken == NULL)
  20848. {
  20849. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  20850. }
  20851. else if ((mResult.mType != NULL) && (mResult.mType->IsInterface()))
  20852. {
  20853. mModule->Fail(
  20854. StrFormat("Operator '%s' cannot be used on interface '%s'. Consider rewriting using generics and use this interface as a generic constraint.",
  20855. BfTokenToString(opToken->mToken), mModule->TypeToString(mResult.mType).c_str()), opToken);
  20856. }
  20857. else
  20858. {
  20859. mModule->Fail(
  20860. StrFormat("Operator '%s' cannot be used because type '%s' is neither a numeric type nor does it define an applicable operator overload",
  20861. BfTokenToString(opToken->mToken), mModule->TypeToString(mResult.mType).c_str()), opToken);
  20862. }
  20863. mResult = BfTypedValue();
  20864. }
  20865. if (writeToProp)
  20866. {
  20867. auto setMethod = GetPropertyMethodDef(propDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  20868. if (setMethod == NULL)
  20869. {
  20870. mModule->Fail("Property has no setter", propSrc);
  20871. return;
  20872. }
  20873. auto methodInstance = GetPropertyMethodInstance(setMethod);
  20874. if (!methodInstance.mFunc)
  20875. return;
  20876. if (propSrc != NULL)
  20877. mModule->UpdateExprSrcPos(propSrc);
  20878. SizedArray<BfIRValue, 4> args;
  20879. if (!setMethod->mIsStatic)
  20880. {
  20881. auto usePropTarget = propTarget;
  20882. if (origPropTarget.mType == methodInstance.mMethodInstance->GetOwner())
  20883. usePropTarget = origPropTarget;
  20884. else
  20885. BF_ASSERT(propTarget.mType == methodInstance.mMethodInstance->GetOwner());
  20886. PushThis(propSrc, usePropTarget, methodInstance.mMethodInstance, args);
  20887. }
  20888. for (int paramIdx = 0; paramIdx < (int)indexerVals.size(); paramIdx++)
  20889. {
  20890. auto val = mModule->Cast(propSrc, indexerVals[paramIdx].mTypedValue, methodInstance.mMethodInstance->GetParamType(paramIdx));
  20891. if (!val)
  20892. return;
  20893. PushArg(val, args);
  20894. }
  20895. PushArg(writeToProp, args);
  20896. CreateCall(opToken, methodInstance.mMethodInstance, methodInstance.mFunc, false, args);
  20897. }
  20898. }
  20899. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue)
  20900. {
  20901. BfTypedValue rightValue;
  20902. if (rightExpression == NULL)
  20903. {
  20904. mModule->AssertErrorState();
  20905. return;
  20906. }
  20907. if (!leftValue)
  20908. {
  20909. if (!rightValue)
  20910. mModule->CreateValueFromExpression(rightExpression, mExpectingType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  20911. return;
  20912. }
  20913. if (leftValue.mType->IsRef())
  20914. leftValue.mType = leftValue.mType->GetUnderlyingType();
  20915. if ((binaryOp == BfBinaryOp_ConditionalAnd) || (binaryOp == BfBinaryOp_ConditionalOr))
  20916. {
  20917. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  20918. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  20919. if (mModule->mCurMethodState->mCurScope->mScopeKind == BfScopeKind_StatementTarget)
  20920. mModule->mCurMethodState->mCurScope->mScopeKind = BfScopeKind_StatementTarget_Conditional;
  20921. bool isAnd = binaryOp == BfBinaryOp_ConditionalAnd;
  20922. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  20923. leftValue = mModule->Cast(leftExpression, leftValue, boolType);
  20924. if (!leftValue)
  20925. {
  20926. mModule->CreateValueFromExpression(rightExpression);
  20927. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Undef);
  20928. return;
  20929. }
  20930. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  20931. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mInConditionalBlock, true);
  20932. // The RHS is not guaranteed to be executed
  20933. if ((mModule->mCurMethodState->mDeferredLocalAssignData != NULL) &&
  20934. (mModule->mCurMethodState->mDeferredLocalAssignData->mIsIfCondition))
  20935. mModule->mCurMethodState->mDeferredLocalAssignData->mIfMayBeSkipped = true;
  20936. if (isAnd)
  20937. {
  20938. bool isConstBranch = false;
  20939. bool constResult = false;
  20940. if (leftValue.mValue.IsConst())
  20941. {
  20942. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  20943. if (constValue->mTypeCode == BfTypeCode_Boolean)
  20944. {
  20945. isConstBranch = true;
  20946. constResult = constValue->mBool;
  20947. }
  20948. }
  20949. if (isConstBranch)
  20950. {
  20951. if ((constResult) || (HasVariableDeclaration(rightExpression)))
  20952. {
  20953. // Only right side
  20954. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  20955. mResult = rightValue;
  20956. }
  20957. else
  20958. {
  20959. // Always false
  20960. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  20961. SetAndRestoreValue<bool> prevInConstIgnore(mModule->mCurMethodState->mCurScope->mInConstIgnore, true);
  20962. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  20963. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolType);
  20964. }
  20965. }
  20966. else
  20967. {
  20968. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("land.rhs");
  20969. auto endBB = mModule->mBfIRBuilder->CreateBlock("land.end");
  20970. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, rhsBB, endBB);
  20971. mModule->AddBasicBlock(rhsBB);
  20972. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_CreateConditionalScope));
  20973. mModule->mBfIRBuilder->CreateBr(endBB);
  20974. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  20975. mModule->AddBasicBlock(endBB);
  20976. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  20977. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(0, boolType), prevBB);
  20978. if (rightValue)
  20979. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  20980. mResult = BfTypedValue(phi, boolType);
  20981. }
  20982. }
  20983. else
  20984. {
  20985. // Put variables in here into a 'possibly assigned' but never commit it.
  20986. // Because if we had "if ((Get(out a)) || (GetOther(out a))" then the LHS would already set it as defined, so
  20987. // the RHS is inconsequential
  20988. BfDeferredLocalAssignData deferredLocalAssignData;
  20989. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData, false);
  20990. deferredLocalAssignData.mVarIdBarrier = mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  20991. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mModule->mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  20992. bool isConstBranch = false;
  20993. bool constResult = false;
  20994. if (leftValue.mValue.IsConst())
  20995. {
  20996. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  20997. if (constValue->mTypeCode == BfTypeCode_Boolean)
  20998. {
  20999. isConstBranch = true;
  21000. constResult = constValue->mBool;
  21001. }
  21002. }
  21003. if (isConstBranch)
  21004. {
  21005. if ((constResult) && (!HasVariableDeclaration(rightExpression)))
  21006. {
  21007. // Always true
  21008. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  21009. SetAndRestoreValue<bool> prevInConstIgnore(mModule->mCurMethodState->mCurScope->mInConstIgnore, true);
  21010. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  21011. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  21012. }
  21013. else
  21014. {
  21015. // Only right side
  21016. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  21017. mResult = rightValue;
  21018. }
  21019. }
  21020. else
  21021. {
  21022. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("lor.rhs");
  21023. auto endBB = mModule->mBfIRBuilder->CreateBlock("lor.end");
  21024. // This makes any 'scope' allocs be dyn since we aren't sure if this will be short-circuited
  21025. SetAndRestoreValue<bool> prevIsConditional(mModule->mCurMethodState->mCurScope->mIsConditional, true);
  21026. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, endBB, rhsBB);
  21027. mModule->AddBasicBlock(rhsBB);
  21028. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  21029. mModule->mBfIRBuilder->CreateBr(endBB);
  21030. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  21031. mModule->AddBasicBlock(endBB);
  21032. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  21033. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(1, boolType), prevBB);
  21034. if (rightValue)
  21035. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  21036. mResult = BfTypedValue(phi, boolType);
  21037. }
  21038. }
  21039. return;
  21040. }
  21041. BfType* wantType = leftValue.mType;
  21042. BfType* origWantType = wantType;
  21043. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  21044. wantType = NULL; // Don't presume
  21045. wantType = mModule->FixIntUnknown(wantType);
  21046. if ((binaryOp == BfBinaryOp_NullCoalesce) && (PerformBinaryOperation_NullCoalesce(opToken, leftExpression, rightExpression, leftValue, wantType, NULL)))
  21047. return;
  21048. BfType* rightWantType = wantType;
  21049. if (origWantType->IsIntUnknown())
  21050. rightWantType = NULL;
  21051. else if ((mExpectingType != NULL) && (wantType != NULL) && (mExpectingType->IsIntegral()) && (wantType->IsIntegral()) && (mExpectingType->mSize > wantType->mSize) &&
  21052. ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_Multiply)))
  21053. rightWantType = mExpectingType;
  21054. rightValue = mModule->CreateValueFromExpression(rightExpression, rightWantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  21055. if ((rightWantType != wantType) && (rightValue.mType == rightWantType))
  21056. wantType = rightWantType;
  21057. if ((!leftValue) || (!rightValue))
  21058. return;
  21059. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue);
  21060. }
  21061. bool BfExprEvaluator::PerformBinaryOperation_NullCoalesce(BfTokenNode* opToken, BfExpression* leftExpression, BfExpression* rightExpression, BfTypedValue leftValue, BfType* wantType, BfTypedValue* assignTo)
  21062. {
  21063. if ((leftValue) && ((leftValue.mType->IsPointer()) || (leftValue.mType->IsFunction()) || (leftValue.mType->IsObject())) || (leftValue.mType->IsNullable()))
  21064. {
  21065. leftValue = mModule->LoadOrAggregateValue(leftValue);
  21066. mModule->mBfIRBuilder->PopulateType(leftValue.mType);
  21067. BfType* nullableElementType = NULL;
  21068. BfIRValue nullableHasValue;
  21069. BfTypedValue nullableExtractedLeftValue;
  21070. if (leftValue.mType->IsNullable())
  21071. {
  21072. nullableElementType = leftValue.mType->GetUnderlyingType();
  21073. nullableHasValue = mModule->mBfIRBuilder->CreateExtractValue(leftValue.mValue, nullableElementType->IsValuelessType() ? 1 : 2); // has_value
  21074. if (!nullableElementType->IsValuelessType())
  21075. nullableExtractedLeftValue = BfTypedValue(mModule->mBfIRBuilder->CreateExtractValue(leftValue.mValue, 1), nullableElementType); // value
  21076. else
  21077. nullableExtractedLeftValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), nullableElementType);
  21078. }
  21079. if (leftValue.mValue.IsConst())
  21080. {
  21081. auto constant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  21082. if (constant->IsNull())
  21083. {
  21084. mResult = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  21085. return true;
  21086. }
  21087. // Already have a value, we don't need the right side
  21088. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  21089. SetAndRestoreValue<bool> prevInConstIgnore(mModule->mCurMethodState->mCurScope->mInConstIgnore, true);
  21090. mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_CreateConditionalScope));
  21091. mResult = leftValue;
  21092. return true;
  21093. }
  21094. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  21095. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("nullc.rhs");
  21096. auto endBB = mModule->mBfIRBuilder->CreateBlock("nullc.end");
  21097. auto lhsBB = endBB;
  21098. auto endLhsBB = prevBB;
  21099. BfIRValue isNull;
  21100. if (nullableHasValue)
  21101. isNull = mModule->mBfIRBuilder->CreateCmpEQ(nullableHasValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0));
  21102. else if (leftValue.mType->IsFunction())
  21103. isNull = mModule->mBfIRBuilder->CreateIsNull(
  21104. mModule->mBfIRBuilder->CreateIntToPtr(leftValue.mValue, mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_NullPtr))));
  21105. else
  21106. isNull = mModule->mBfIRBuilder->CreateIsNull(leftValue.mValue);
  21107. mModule->AddBasicBlock(rhsBB);
  21108. BfTypedValue rightValue;
  21109. if (assignTo != NULL)
  21110. rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_CreateConditionalScope));
  21111. else
  21112. rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  21113. if (!rightValue)
  21114. {
  21115. mModule->AssertErrorState();
  21116. return true;
  21117. }
  21118. if ((assignTo == NULL) && (leftValue.mType->IsNullable()) && (!rightValue.mType->IsNullable()))
  21119. {
  21120. if (wantType == leftValue.mType)
  21121. wantType = nullableElementType;
  21122. leftValue = nullableExtractedLeftValue;
  21123. }
  21124. rightValue = mModule->LoadValue(rightValue);
  21125. if (assignTo == NULL)
  21126. {
  21127. auto rightToLeftValue = mModule->CastToValue(rightExpression, rightValue, leftValue.mType, BfCastFlags_SilentFail);
  21128. if (rightToLeftValue)
  21129. {
  21130. rightValue = BfTypedValue(rightToLeftValue, leftValue.mType);
  21131. }
  21132. else
  21133. {
  21134. lhsBB = mModule->mBfIRBuilder->CreateBlock("nullc.lhs", true);
  21135. mModule->mBfIRBuilder->SetInsertPoint(lhsBB);
  21136. auto leftToRightValue = mModule->CastToValue(leftExpression, leftValue, rightValue.mType, BfCastFlags_SilentFail);
  21137. if (leftToRightValue)
  21138. {
  21139. leftValue = BfTypedValue(leftToRightValue, rightValue.mType);
  21140. }
  21141. else
  21142. {
  21143. // Note: Annoying trigraph split for '??'
  21144. mModule->Fail(StrFormat("Operator '?" "?' cannot be applied to operands of type '%s' and '%s'",
  21145. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  21146. leftValue = mModule->GetDefaultTypedValue(rightValue.mType);
  21147. }
  21148. mModule->mBfIRBuilder->CreateBr(endBB);
  21149. endLhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  21150. mModule->mBfIRBuilder->SetInsertPoint(rhsBB);
  21151. }
  21152. }
  21153. if (assignTo != NULL)
  21154. mModule->mBfIRBuilder->CreateStore(rightValue.mValue, assignTo->mValue);
  21155. mModule->mBfIRBuilder->CreateBr(endBB);
  21156. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  21157. // Actually add CondBr at start
  21158. mModule->mBfIRBuilder->SetInsertPoint(prevBB);
  21159. mModule->mBfIRBuilder->CreateCondBr(isNull, rhsBB, lhsBB);
  21160. mModule->AddBasicBlock(endBB);
  21161. if (assignTo != NULL)
  21162. {
  21163. mResult = *assignTo;
  21164. }
  21165. else
  21166. {
  21167. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(leftValue.mType), 2);
  21168. if (!leftValue.mType->IsValuelessType())
  21169. mModule->mBfIRBuilder->AddPhiIncoming(phi, leftValue.mValue, endLhsBB);
  21170. if (!rightValue.mType->IsValuelessType())
  21171. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  21172. mResult = BfTypedValue(phi, leftValue.mType);
  21173. }
  21174. return true;
  21175. }
  21176. return false;
  21177. }
  21178. bool BfExprEvaluator::PerformBinaryOperation_Numeric(BfAstNode* leftExpression, BfAstNode* rightExpression, BfBinaryOp binaryOp, BfAstNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue, BfTypedValue rightValue)
  21179. {
  21180. switch (binaryOp)
  21181. {
  21182. case BfBinaryOp_Add:
  21183. case BfBinaryOp_Subtract:
  21184. case BfBinaryOp_Multiply:
  21185. case BfBinaryOp_Divide:
  21186. case BfBinaryOp_Modulus:
  21187. break;
  21188. default:
  21189. return false;
  21190. }
  21191. auto wantType = mExpectingType;
  21192. if ((wantType == NULL) ||
  21193. ((!wantType->IsFloat()) && (!wantType->IsIntegral())))
  21194. wantType = NULL;
  21195. auto leftType = mModule->GetClosestNumericCastType(leftValue, mExpectingType);
  21196. auto rightType = mModule->GetClosestNumericCastType(rightValue, mExpectingType);
  21197. if (leftType != NULL)
  21198. {
  21199. if ((rightType == NULL) || (mModule->CanCast(mModule->GetFakeTypedValue(rightType), leftType)))
  21200. wantType = leftType;
  21201. else if ((rightType != NULL) && (mModule->CanCast(mModule->GetFakeTypedValue(leftType), rightType)))
  21202. wantType = rightType;
  21203. }
  21204. else if (rightType != NULL)
  21205. wantType = rightType;
  21206. if (wantType == NULL)
  21207. wantType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  21208. auto convLeftValue = mModule->Cast(opToken, leftValue, wantType, BfCastFlags_SilentFail);
  21209. if (!convLeftValue)
  21210. return false;
  21211. auto convRightValue = mModule->Cast(opToken, rightValue, wantType, BfCastFlags_SilentFail);
  21212. if (!convRightValue)
  21213. return false;
  21214. mResult = BfTypedValue();
  21215. // Let the error come from here, if any - so we always return 'true' to avoid a second error
  21216. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, convLeftValue, convRightValue);
  21217. return true;
  21218. }
  21219. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags)
  21220. {
  21221. if ((binaryOp == BfBinaryOp_Range) || (binaryOp == BfBinaryOp_ClosedRange))
  21222. {
  21223. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  21224. bool isIndexExpr = false;
  21225. BfTypeDef* typeDef = NULL;
  21226. if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(leftExpression))
  21227. if (unaryOpExpr->mOp == BfUnaryOp_FromEnd)
  21228. isIndexExpr = true;
  21229. if (rightExpression == NULL)
  21230. isIndexExpr = true;
  21231. if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(rightExpression))
  21232. if (unaryOpExpr->mOp == BfUnaryOp_FromEnd)
  21233. isIndexExpr = true;
  21234. if (isIndexExpr)
  21235. typeDef = mModule->mCompiler->mIndexRangeTypeDef;
  21236. else
  21237. typeDef = (binaryOp == BfBinaryOp_Range) ? mModule->mCompiler->mRangeTypeDef : mModule->mCompiler->mClosedRangeTypeDef;
  21238. auto allocType = mModule->ResolveTypeDef(typeDef)->ToTypeInstance();
  21239. auto alloca = mModule->CreateAlloca(allocType);
  21240. BfTypedValueExpression leftTypedValueExpr;
  21241. BfTypedValueExpression rightTypedValueExpr;
  21242. BfTypedValueExpression isClosedTypedValueExpr;
  21243. SizedArray<BfExpression*, 2> argExprs;
  21244. if (leftExpression != NULL)
  21245. {
  21246. argExprs.Add(leftExpression);
  21247. }
  21248. else
  21249. {
  21250. leftTypedValueExpr.mRefNode = opToken;
  21251. leftTypedValueExpr.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  21252. argExprs.Add(&leftTypedValueExpr);
  21253. }
  21254. if (rightExpression != NULL)
  21255. {
  21256. argExprs.Add(rightExpression);
  21257. }
  21258. else
  21259. {
  21260. // Add as a `^1`
  21261. auto indexType = mModule->ResolveTypeDef(mModule->mCompiler->mIndexTypeDef)->ToTypeInstance();
  21262. mModule->PopulateType(indexType->mBaseType);
  21263. BF_ASSERT_REL(indexType->mBaseType->mBaseType != NULL);
  21264. rightTypedValueExpr.mRefNode = opToken;
  21265. auto valueTypeEmpty = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType->mBaseType->mBaseType), {});
  21266. SizedArray<BfIRValue, 8> tupleEmptyMembers;
  21267. tupleEmptyMembers.Add(valueTypeEmpty);
  21268. auto tupleTypeEmpty = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(mModule->ResolveTypeDef(mModule->mCompiler->mTupleTypeDef)), tupleEmptyMembers);
  21269. SizedArray<BfIRValue, 8> enumMembers;
  21270. enumMembers.Add(valueTypeEmpty);
  21271. auto enumValue = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType->mBaseType), enumMembers);
  21272. SizedArray<BfIRValue, 8> tupleMembers;
  21273. tupleMembers.Add(tupleTypeEmpty);
  21274. tupleMembers.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  21275. auto tupleValue = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType->mFieldInstances[0].mResolvedType), tupleMembers);
  21276. SizedArray<BfIRValue, 8> indexMembers;
  21277. indexMembers.Add(enumValue);
  21278. indexMembers.Add(tupleValue);
  21279. indexMembers.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 1));
  21280. auto indexValue = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType), indexMembers);
  21281. rightTypedValueExpr.mTypedValue = BfTypedValue(indexValue, indexType);
  21282. argExprs.Add(&rightTypedValueExpr);
  21283. }
  21284. if (isIndexExpr)
  21285. {
  21286. isClosedTypedValueExpr.mRefNode = opToken;
  21287. isClosedTypedValueExpr.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (binaryOp == BfBinaryOp_ClosedRange) ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21288. argExprs.Add(&isClosedTypedValueExpr);
  21289. }
  21290. BfSizedArray<BfExpression*> args = argExprs;
  21291. BfResolvedArgs argValues;
  21292. argValues.Init(&args);
  21293. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  21294. mResult = BfTypedValue(alloca, allocType, true);
  21295. auto result = MatchConstructor(opToken, NULL, mResult, allocType, argValues, true, BfMethodGenericArguments(), BfAllowAppendKind_No);
  21296. if ((result) && (!result.mType->IsVoid()))
  21297. mResult = result;
  21298. return;
  21299. }
  21300. BfTypedValue leftValue;
  21301. if (leftExpression != NULL)
  21302. {
  21303. leftValue = mModule->CreateValueFromExpression(leftExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  21304. }
  21305. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue);
  21306. }
  21307. bool BfExprEvaluator::CheckConstCompare(BfBinaryOp binaryOp, BfAstNode* opToken, const BfTypedValue& leftValue, const BfTypedValue& rightValue)
  21308. {
  21309. if ((binaryOp < BfBinaryOp_Equality) || (binaryOp > BfBinaryOp_LessThanOrEqual))
  21310. return false;
  21311. // LHS is expected to be a value and RHS is expected to be a const
  21312. if (!leftValue.mType->IsIntegral())
  21313. return false;
  21314. BF_ASSERT(rightValue.mValue.IsConst());
  21315. auto rightConst = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  21316. if (!mModule->mBfIRBuilder->IsInt(rightConst->mTypeCode))
  21317. return false;
  21318. BfType* checkType = leftValue.mType;
  21319. if (checkType->IsTypedPrimitive())
  21320. checkType = checkType->GetUnderlyingType();
  21321. if (!checkType->IsPrimitiveType())
  21322. return false;
  21323. BfTypeCode typeCode = ((BfPrimitiveType*)checkType)->mTypeDef->mTypeCode;
  21324. int64 minValue = 0;
  21325. int64 maxValue = 0;
  21326. switch (typeCode)
  21327. {
  21328. case BfTypeCode_Int8:
  21329. minValue = -0x80;
  21330. maxValue = 0x7F;
  21331. break;
  21332. case BfTypeCode_Int16:
  21333. minValue = -0x8000;
  21334. maxValue = 0x7FFF;
  21335. break;
  21336. case BfTypeCode_Int32:
  21337. minValue = -0x80000000LL;
  21338. maxValue = 0x7FFFFFFF;
  21339. break;
  21340. case BfTypeCode_Int64:
  21341. minValue = -0x8000000000000000LL;
  21342. maxValue = 0x7FFFFFFFFFFFFFFFLL;
  21343. break;
  21344. case BfTypeCode_UInt8:
  21345. maxValue = 0xFF;
  21346. break;
  21347. case BfTypeCode_UInt16:
  21348. maxValue = 0xFFFF;
  21349. break;
  21350. case BfTypeCode_UInt32:
  21351. maxValue = 0xFFFFFFFF;
  21352. break;
  21353. default:
  21354. return false;
  21355. }
  21356. int constResult = -1;
  21357. if (typeCode == BfTypeCode_UInt64)
  21358. {
  21359. switch (binaryOp)
  21360. {
  21361. case BfBinaryOp_Equality:
  21362. case BfBinaryOp_StrictEquality:
  21363. if (rightConst->mInt64 < minValue)
  21364. constResult = 0;
  21365. break;
  21366. case BfBinaryOp_InEquality:
  21367. case BfBinaryOp_StrictInEquality:
  21368. if (rightConst->mInt64 < minValue)
  21369. constResult = 1;
  21370. break;
  21371. case BfBinaryOp_LessThan:
  21372. if (rightConst->mInt64 <= minValue)
  21373. constResult = 0;
  21374. break;
  21375. case BfBinaryOp_LessThanOrEqual:
  21376. if (rightConst->mInt64 < minValue)
  21377. constResult = 0;
  21378. break;
  21379. default: break;
  21380. }
  21381. return false;
  21382. }
  21383. else
  21384. {
  21385. switch (binaryOp)
  21386. {
  21387. case BfBinaryOp_Equality:
  21388. case BfBinaryOp_StrictEquality:
  21389. if (rightConst->mInt64 < minValue)
  21390. constResult = 0;
  21391. else if (rightConst->mInt64 > maxValue)
  21392. constResult = 0;
  21393. break;
  21394. case BfBinaryOp_InEquality:
  21395. case BfBinaryOp_StrictInEquality:
  21396. if (rightConst->mInt64 < minValue)
  21397. constResult = 1;
  21398. else if (rightConst->mInt64 > maxValue)
  21399. constResult = 1;
  21400. break;
  21401. case BfBinaryOp_LessThan:
  21402. if (rightConst->mInt64 <= minValue)
  21403. constResult = 0;
  21404. else if (rightConst->mInt64 > maxValue)
  21405. constResult = 1;
  21406. break;
  21407. case BfBinaryOp_LessThanOrEqual:
  21408. if (rightConst->mInt64 < minValue)
  21409. constResult = 0;
  21410. else if (rightConst->mInt64 >= maxValue)
  21411. constResult = 1;
  21412. break;
  21413. case BfBinaryOp_GreaterThan:
  21414. if (rightConst->mInt64 >= maxValue)
  21415. constResult = 0;
  21416. else if (rightConst->mInt64 < minValue)
  21417. constResult = 1;
  21418. break;
  21419. case BfBinaryOp_GreaterThanOrEqual:
  21420. if (rightConst->mInt64 > maxValue)
  21421. constResult = 0;
  21422. else if (rightConst->mInt64 <= minValue)
  21423. constResult = 1;
  21424. break;
  21425. default: break;
  21426. }
  21427. }
  21428. if (constResult == 0)
  21429. {
  21430. mModule->Warn(0, "The result of this operation is always 'false'", opToken);
  21431. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21432. return true;
  21433. }
  21434. else if (constResult == 1)
  21435. {
  21436. mModule->Warn(0, "The result of this operation is always 'true'", opToken);
  21437. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21438. return true;
  21439. }
  21440. return false;
  21441. }
  21442. void BfExprEvaluator::AddStrings(const BfTypedValue& leftValue, const BfTypedValue& rightValue, BfAstNode* refNode)
  21443. {
  21444. if ((leftValue.mValue.IsConst()) && (rightValue.mValue.IsConst()))
  21445. {
  21446. String* lhsStr = mModule->GetStringPoolString(leftValue.mValue, mModule->mBfIRBuilder);
  21447. String* rhsStr = mModule->GetStringPoolString(rightValue.mValue, mModule->mBfIRBuilder);
  21448. if ((lhsStr != NULL) && (rhsStr != NULL))
  21449. {
  21450. String resultStr = *lhsStr + *rhsStr;
  21451. BfVariant variant;
  21452. variant.mTypeCode = BfTypeCode_CharPtr;
  21453. variant.mString = &resultStr;
  21454. GetLiteral(refNode, variant);
  21455. return;
  21456. }
  21457. }
  21458. mModule->Fail("Strings can only be added when they are constants. Consider allocating a string and using Concat.", refNode);
  21459. return;
  21460. }
  21461. void BfExprEvaluator::PerformBinaryOperation(BfAstNode* leftExpression, BfAstNode* rightExpression, BfBinaryOp binaryOp, BfAstNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue, BfTypedValue rightValue)
  21462. {
  21463. bool noClassify = (flags & BfBinOpFlag_NoClassify) != 0;
  21464. bool forceRightType = (flags & BfBinOpFlag_ForceRightType) != 0;
  21465. bool forceLeftType = (flags & BfBinOpFlag_ForceLeftType) != 0;
  21466. bool deferRight = (flags & BfBinOpFlag_DeferRight) != 0;
  21467. if (deferRight)
  21468. {
  21469. rightValue = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  21470. }
  21471. if ((rightValue.mValue.IsConst()) && (!leftValue.mValue.IsConst()))
  21472. {
  21473. if (CheckConstCompare(binaryOp, opToken, leftValue, rightValue))
  21474. return;
  21475. }
  21476. else if ((leftValue.mValue.IsConst()) && (!rightValue.mValue.IsConst()))
  21477. {
  21478. if (CheckConstCompare(BfGetOppositeBinaryOp(binaryOp), opToken, rightValue, leftValue))
  21479. return;
  21480. }
  21481. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  21482. {
  21483. forceLeftType = true;
  21484. mModule->FixIntUnknown(leftValue);
  21485. }
  21486. if (rightValue.mType->IsRef())
  21487. rightValue.mType = rightValue.mType->GetUnderlyingType();
  21488. BfType* origLeftType = leftValue.mType;
  21489. BfType* origRightType = rightValue.mType;
  21490. mModule->FixIntUnknown(leftValue, rightValue);
  21491. // Prefer floats, prefer chars
  21492. int leftCompareSize = leftValue.mType->mSize;
  21493. if (leftValue.mType->IsFloat())
  21494. leftCompareSize += 0x10;
  21495. if (leftValue.mType->IsChar())
  21496. leftCompareSize += 0x100;
  21497. if (!leftValue.mType->IsPrimitiveType())
  21498. leftCompareSize += 0x1000;
  21499. int rightCompareSize = rightValue.mType->mSize;
  21500. if (rightValue.mType->IsFloat())
  21501. rightCompareSize += 0x10;
  21502. if (rightValue.mType->IsChar())
  21503. rightCompareSize += 0x100;
  21504. if (!rightValue.mType->IsPrimitiveType())
  21505. rightCompareSize += 0x1000;
  21506. if ((leftValue.mType->IsTypeInstance()) && (rightValue.mType->IsTypeInstance()))
  21507. {
  21508. int leftInheritDepth = leftValue.mType->ToTypeInstance()->mInheritDepth;
  21509. int rightInheritDepth = rightValue.mType->ToTypeInstance()->mInheritDepth;
  21510. if (leftInheritDepth < rightInheritDepth)
  21511. {
  21512. // If both are type instances then choose the type with the lowest inherit depth
  21513. // so we will choose the base type when applicable
  21514. forceLeftType = true;
  21515. }
  21516. }
  21517. auto resultType = leftValue.mType;
  21518. if (forceRightType)
  21519. {
  21520. resultType = rightValue.mType;
  21521. }
  21522. else if (!forceLeftType)
  21523. {
  21524. bool handled = false;
  21525. BfType* expectingType = mExpectingType;
  21526. if (leftValue.mType == rightValue.mType)
  21527. {
  21528. // All good
  21529. handled = true;
  21530. }
  21531. else if ((expectingType != NULL) &&
  21532. (mModule->CanCast(leftValue, expectingType, BfCastFlags_NoBox)) &&
  21533. (mModule->CanCast(rightValue, expectingType, BfCastFlags_NoBox)) &&
  21534. (!leftValue.mType->IsVar()) && (!rightValue.mType->IsVar()))
  21535. {
  21536. resultType = expectingType;
  21537. handled = true;
  21538. }
  21539. else
  21540. {
  21541. // If one of these is a constant that can be converted into a smaller type, then do that
  21542. if (rightValue.mValue.IsConst())
  21543. {
  21544. if (mModule->CanCast(rightValue, leftValue.mType, BfCastFlags_NoBox))
  21545. {
  21546. resultType = leftValue.mType;
  21547. handled = true;
  21548. }
  21549. }
  21550. // If left is an IntUnknown, allow the right to inform the type
  21551. if (leftValue.mType->IsIntUnknown())
  21552. {
  21553. if (leftValue.mValue.IsConst())
  21554. {
  21555. if (mModule->CanCast(leftValue, rightValue.mType))
  21556. {
  21557. resultType = rightValue.mType;
  21558. handled = true;
  21559. }
  21560. }
  21561. }
  21562. if ((leftValue.mType->IsPointer()) &&
  21563. (rightValue.mType->IsPointer()))
  21564. {
  21565. BfPointerType* leftPointerType = (BfPointerType*)leftValue.mType;
  21566. BfPointerType* rightPointerType = (BfPointerType*)rightValue.mType;
  21567. // If one is a pointer to a sized array then use the other type
  21568. if (leftPointerType->mElementType->IsSizedArray())
  21569. {
  21570. resultType = rightPointerType;
  21571. handled = true;
  21572. }
  21573. else if (rightPointerType->mElementType->IsSizedArray())
  21574. {
  21575. resultType = leftPointerType;
  21576. handled = true;
  21577. }
  21578. }
  21579. }
  21580. if (!handled)
  21581. {
  21582. if ((resultType->IsNull()) ||
  21583. (rightCompareSize > leftCompareSize) ||
  21584. (((rightCompareSize == leftCompareSize) && (!rightValue.mType->IsSigned()))) ||
  21585. (rightValue.mType->IsTypedPrimitive()))
  21586. {
  21587. // Select the type with the "most information"
  21588. if (!rightValue.mType->IsNull())
  21589. resultType = rightValue.mType;
  21590. }
  21591. if ((!resultType->IsPointer()) && (rightValue.mType->IsPointer()))
  21592. resultType = rightValue.mType;
  21593. }
  21594. }
  21595. bool explicitCast = false;
  21596. BfTypedValue* resultTypedValue;
  21597. BfTypedValue* otherTypedValue;
  21598. BfType* otherType;
  21599. BfAstNode* resultTypeSrc;
  21600. BfAstNode* otherTypeSrc;
  21601. if (resultType == leftValue.mType)
  21602. {
  21603. resultTypedValue = &leftValue;
  21604. resultTypeSrc = leftExpression;
  21605. otherTypedValue = &rightValue;
  21606. otherTypeSrc = rightExpression;
  21607. otherType = otherTypedValue->mType;
  21608. }
  21609. else
  21610. {
  21611. resultTypedValue = &rightValue;
  21612. resultTypeSrc = rightExpression;
  21613. otherTypedValue = &leftValue;
  21614. otherTypeSrc = leftExpression;
  21615. otherType = otherTypedValue->mType;
  21616. }
  21617. auto _OpFail = [&]()
  21618. {
  21619. if ((rightValue.mType != NULL) && (leftValue.mType != NULL))
  21620. {
  21621. if (rightValue.mType != leftValue.mType)
  21622. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between types '%s' and '%s'",
  21623. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  21624. else
  21625. {
  21626. if (leftValue.mType->IsInterface())
  21627. {
  21628. 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.",
  21629. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  21630. }
  21631. else
  21632. {
  21633. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between two instances of type '%s'",
  21634. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  21635. }
  21636. }
  21637. }
  21638. else
  21639. mModule->Fail(StrFormat("Cannot perform binary operation '%s'", BfGetOpName(binaryOp)), opToken);
  21640. };
  21641. // This case fixes cases like "c == 0" where "0" is technically an int but can be reduced
  21642. if (BfBinOpEqualityCheck(binaryOp))
  21643. {
  21644. if ((resultType != otherType) && (resultTypedValue->mValue.IsConst()) && (mModule->CanCast(*resultTypedValue, otherType)))
  21645. {
  21646. std::swap(resultTypedValue, otherTypedValue);
  21647. std::swap(resultTypeSrc, otherTypeSrc);
  21648. std::swap(resultType, otherType);
  21649. }
  21650. }
  21651. BfIRValue convLeftValue;
  21652. BfIRValue convRightValue;
  21653. if (((resultType->IsVar()) || (otherType->IsVar())) && (!deferRight))
  21654. {
  21655. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  21656. if (isComparison)
  21657. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Boolean), false, BfDefaultValueKind_Addr);
  21658. else if (mExpectingType != NULL)
  21659. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  21660. else
  21661. mResult = mModule->GetDefaultTypedValue(resultType, false, BfDefaultValueKind_Addr);
  21662. return;
  21663. }
  21664. if ((otherType->IsNull()) && (BfBinOpEqualityCheck(binaryOp)))
  21665. {
  21666. bool isEquality = (binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality);
  21667. if ((resultType->IsValueType()) && (!resultType->IsFunction()))
  21668. {
  21669. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  21670. if (resultType->IsNullable())
  21671. {
  21672. auto elementType = resultType->GetUnderlyingType();
  21673. mModule->PopulateType(elementType);
  21674. if (elementType->IsValuelessType())
  21675. {
  21676. mModule->mBfIRBuilder->PopulateType(resultType);
  21677. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  21678. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 1);
  21679. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateAlignedLoad(hasValuePtr, 1);
  21680. if (isEquality)
  21681. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  21682. mResult = BfTypedValue(hasValueValue, boolType);
  21683. }
  21684. else
  21685. {
  21686. mModule->mBfIRBuilder->PopulateType(resultType);
  21687. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  21688. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 2);
  21689. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateAlignedLoad(hasValuePtr, 1);
  21690. if (isEquality)
  21691. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  21692. mResult = BfTypedValue(hasValueValue, boolType);
  21693. }
  21694. return;
  21695. }
  21696. if (resultType->IsNull())
  21697. {
  21698. // Null always equals null
  21699. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 1 : 0, boolType), boolType);
  21700. return;
  21701. }
  21702. if (!mModule->IsInSpecializedSection())
  21703. {
  21704. //CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type '<null>'
  21705. mModule->Warn(BfWarning_CS0472_ValueTypeNullCompare,
  21706. StrFormat("The result of the expression is always '%s' since a value of type '%s' can never be null",
  21707. isEquality ? "false" : "true", mModule->TypeToString(resultType).c_str()), otherTypeSrc);
  21708. }
  21709. // Valuetypes never equal null
  21710. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 0 : 1, boolType), boolType);
  21711. return;
  21712. }
  21713. }
  21714. // Check for constant equality checks (mostly for strings)
  21715. if (BfBinOpEqualityCheck(binaryOp))
  21716. {
  21717. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  21718. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  21719. if ((leftConstant != NULL) && (rightConstant != NULL))
  21720. {
  21721. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  21722. int leftStringPoolIdx = mModule->GetStringPoolIdx(leftValue.mValue, mModule->mBfIRBuilder);
  21723. if (leftStringPoolIdx != -1)
  21724. {
  21725. int rightStringPoolIdx = mModule->GetStringPoolIdx(rightValue.mValue, mModule->mBfIRBuilder);
  21726. if (rightStringPoolIdx != -1)
  21727. {
  21728. bool isEqual = leftStringPoolIdx == rightStringPoolIdx;
  21729. if ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  21730. isEqual = !isEqual;
  21731. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  21732. return;
  21733. }
  21734. }
  21735. int eqResult = mModule->mBfIRBuilder->CheckConstEquality(leftValue.mValue, rightValue.mValue);
  21736. if (eqResult != -1)
  21737. {
  21738. bool isEqual = eqResult == 1;
  21739. if ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  21740. isEqual = !isEqual;
  21741. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  21742. return;
  21743. }
  21744. }
  21745. }
  21746. if ((leftValue.mType->IsTypeInstance()) || (leftValue.mType->IsGenericParam()) ||
  21747. (rightValue.mType->IsTypeInstance()) || (rightValue.mType->IsGenericParam()))
  21748. {
  21749. // As an optimization, we don't call user operator overloads for null checks
  21750. bool skipOpOverload = false;
  21751. if ((binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  21752. skipOpOverload = true;
  21753. else if (BfBinOpEqualityCheck(binaryOp))
  21754. {
  21755. if (!leftValue.IsAddr())
  21756. {
  21757. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  21758. if ((leftConstant != NULL) && (leftConstant->IsNull()))
  21759. skipOpOverload = true;
  21760. }
  21761. if (!rightValue.IsAddr())
  21762. {
  21763. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  21764. if ((rightConstant != NULL) && (rightConstant->IsNull()))
  21765. skipOpOverload = true;
  21766. }
  21767. }
  21768. if ((binaryOp == BfBinaryOp_Add) && (resultType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  21769. {
  21770. // Allow failover to constant string addition
  21771. if ((leftValue.mValue.IsConst()) && (rightValue.mValue.IsConst()))
  21772. skipOpOverload = true;
  21773. }
  21774. if (!skipOpOverload)
  21775. {
  21776. BfBinaryOp findBinaryOp = binaryOp;
  21777. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  21778. for (int pass = 0; pass < 2; pass++)
  21779. {
  21780. BfBinaryOp oppositeBinaryOp = BfGetOppositeBinaryOp(findBinaryOp);
  21781. BfBinaryOp overflowBinaryOp = BfBinaryOp_None;
  21782. if (findBinaryOp == BfBinaryOp_OverflowAdd)
  21783. overflowBinaryOp = BfBinaryOp_Add;
  21784. else if (findBinaryOp == BfBinaryOp_OverflowSubtract)
  21785. overflowBinaryOp = BfBinaryOp_Subtract;
  21786. else if (findBinaryOp == BfBinaryOp_OverflowMultiply)
  21787. overflowBinaryOp = BfBinaryOp_Multiply;
  21788. bool foundOp = false;
  21789. BfResolvedArg leftArg;
  21790. leftArg.mExpression = leftExpression;
  21791. leftArg.mTypedValue = leftValue;
  21792. BfResolvedArg rightArg;
  21793. rightArg.mExpression = rightExpression;
  21794. rightArg.mTypedValue = rightValue;
  21795. if (deferRight)
  21796. {
  21797. BfResolvedArgs argValues;
  21798. SizedArray<BfExpression*, 2> argExprs;
  21799. argExprs.push_back(BfNodeDynCast<BfExpression>(rightExpression));
  21800. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  21801. argValues.Init(&sizedArgExprs);
  21802. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  21803. rightArg = argValues.mResolvedArgs[0];
  21804. }
  21805. SizedArray<BfResolvedArg, 2> args;
  21806. if (pass == 0)
  21807. {
  21808. args.push_back(leftArg);
  21809. args.push_back(rightArg);
  21810. }
  21811. else
  21812. {
  21813. args.push_back(rightArg);
  21814. args.push_back(leftArg);
  21815. }
  21816. auto checkLeftType = leftValue.mType;
  21817. auto checkRightType = rightValue.mType;
  21818. BfMethodMatcher methodMatcher(opToken, mModule, "", args, BfMethodGenericArguments());
  21819. methodMatcher.mAllowImplicitRef = true;
  21820. methodMatcher.mBfEvalExprFlags = BfEvalExprFlags_NoAutoComplete;
  21821. BfBaseClassWalker baseClassWalker(checkLeftType, checkRightType, mModule);
  21822. bool invertResult = false;
  21823. BfType* operatorConstraintReturnType = NULL;
  21824. bool wasTransformedUsage = (pass == 1);
  21825. while (true)
  21826. {
  21827. auto entry = baseClassWalker.Next();
  21828. auto checkType = entry.mTypeInstance;
  21829. if (checkType == NULL)
  21830. break;
  21831. bool foundExactMatch = false;
  21832. SizedArray<BfOperatorDef*, 8> oppositeOperatorDefs;
  21833. for (auto operatorDef : checkType->mTypeDef->mOperators)
  21834. {
  21835. bool allowOp = operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp;
  21836. if ((isComparison) && (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare))
  21837. allowOp = true;
  21838. if (allowOp)
  21839. {
  21840. foundOp = true;
  21841. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  21842. continue;
  21843. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  21844. {
  21845. if (operatorDef->mGenericParams.IsEmpty())
  21846. {
  21847. // Fast check
  21848. auto returnType = mModule->CheckOperator(checkType, operatorDef, args[0].mTypedValue, args[1].mTypedValue);
  21849. if (returnType != NULL)
  21850. {
  21851. operatorConstraintReturnType = returnType;
  21852. methodMatcher.mBestMethodDef = operatorDef;
  21853. methodMatcher.mBestMethodTypeInstance = checkType;
  21854. foundExactMatch = true;
  21855. }
  21856. }
  21857. else
  21858. {
  21859. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  21860. {
  21861. auto rawMethodInstance = mModule->GetRawMethodInstance(checkType, operatorDef);
  21862. auto returnType = mModule->ResolveGenericType(rawMethodInstance->mReturnType, NULL, &methodMatcher.mBestMethodGenericArguments,
  21863. mModule->mCurTypeInstance);
  21864. if (returnType != NULL)
  21865. {
  21866. operatorConstraintReturnType = returnType;
  21867. foundExactMatch = true;
  21868. }
  21869. }
  21870. }
  21871. }
  21872. else
  21873. {
  21874. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  21875. {
  21876. methodMatcher.mSelfType = entry.mSrcType;
  21877. if (operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp)
  21878. foundExactMatch = true;
  21879. }
  21880. }
  21881. }
  21882. else if ((operatorDef->mOperatorDeclaration->mBinOp == oppositeBinaryOp) || (operatorDef->mOperatorDeclaration->mBinOp == overflowBinaryOp))
  21883. oppositeOperatorDefs.Add(operatorDef);
  21884. }
  21885. if ((((methodMatcher.mBestMethodDef == NULL) && (operatorConstraintReturnType == NULL)) || (!foundExactMatch)) && (!oppositeOperatorDefs.IsEmpty()))
  21886. {
  21887. foundOp = true;
  21888. for (auto oppositeOperatorDef : oppositeOperatorDefs)
  21889. {
  21890. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  21891. {
  21892. if (oppositeOperatorDef->mGenericParams.IsEmpty())
  21893. {
  21894. // Fast check
  21895. auto returnType = mModule->CheckOperator(checkType, oppositeOperatorDef, args[0].mTypedValue, args[1].mTypedValue);
  21896. if (returnType != NULL)
  21897. {
  21898. operatorConstraintReturnType = returnType;
  21899. methodMatcher.mBestMethodDef = oppositeOperatorDef;
  21900. methodMatcher.mBestMethodTypeInstance = checkType;
  21901. methodMatcher.mSelfType = entry.mSrcType;
  21902. if (oppositeBinaryOp != BfBinaryOp_None)
  21903. wasTransformedUsage = true;
  21904. }
  21905. }
  21906. else
  21907. {
  21908. if (methodMatcher.CheckMethod(NULL, checkType, oppositeOperatorDef, false))
  21909. {
  21910. auto rawMethodInstance = mModule->GetRawMethodInstance(checkType, oppositeOperatorDef);
  21911. auto returnType = mModule->ResolveGenericType(rawMethodInstance->mReturnType, NULL, &methodMatcher.mBestMethodGenericArguments,
  21912. mModule->mCurTypeInstance);
  21913. if (returnType != NULL)
  21914. {
  21915. operatorConstraintReturnType = returnType;
  21916. methodMatcher.mSelfType = entry.mSrcType;
  21917. if (oppositeBinaryOp != BfBinaryOp_None)
  21918. wasTransformedUsage = true;
  21919. }
  21920. }
  21921. }
  21922. }
  21923. else
  21924. {
  21925. if (methodMatcher.CheckMethod(NULL, checkType, oppositeOperatorDef, false))
  21926. {
  21927. methodMatcher.mSelfType = entry.mSrcType;
  21928. if (oppositeBinaryOp != BfBinaryOp_None)
  21929. wasTransformedUsage = true;
  21930. }
  21931. }
  21932. }
  21933. }
  21934. }
  21935. bool hadMatch = (methodMatcher.mBestMethodDef != NULL);
  21936. if ((methodMatcher.mBestMethodDef != NULL) && ((flags & BfBinOpFlag_IgnoreOperatorWithWrongResult) != 0))
  21937. {
  21938. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  21939. methodMatcher.mBestMethodInstance = GetSelectedMethod(methodMatcher.mTargetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  21940. if ((methodMatcher.mBestMethodInstance.mMethodInstance->mReturnType != mExpectingType) &&
  21941. ((matchedOp == binaryOp) || (matchedOp == oppositeBinaryOp)))
  21942. {
  21943. if (binaryOp == BfBinaryOp_Equality)
  21944. binaryOp = BfBinaryOp_StrictEquality;
  21945. if (binaryOp == BfBinaryOp_InEquality)
  21946. binaryOp = BfBinaryOp_StrictEquality;
  21947. hadMatch = false;
  21948. break;
  21949. }
  21950. }
  21951. if (hadMatch)
  21952. {
  21953. methodMatcher.FlushAmbiguityError();
  21954. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  21955. bool invertResult = matchedOp == oppositeBinaryOp;
  21956. auto methodDef = methodMatcher.mBestMethodDef;
  21957. auto autoComplete = GetAutoComplete();
  21958. bool wasCapturingMethodInfo = false;
  21959. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  21960. {
  21961. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  21962. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  21963. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  21964. }
  21965. if ((wasTransformedUsage) && (methodDef->mCommutableKind != BfCommutableKind_Operator))
  21966. {
  21967. auto error = mModule->Warn(BfWarning_BF4206_OperatorCommutableUsage, "Transformed operator usage requires 'Commutable' attribute to be added to the operator declaration", opToken);
  21968. if ((error != NULL) && (methodDef->GetRefNode() != NULL))
  21969. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See operator declaration"), methodDef->GetRefNode());
  21970. }
  21971. if (opToken != NULL)
  21972. {
  21973. if ((opToken->IsA<BfTokenNode>()) && (!noClassify) && (!baseClassWalker.mMayBeFromInterface))
  21974. mModule->SetElementType(opToken, BfSourceElementType_Method);
  21975. }
  21976. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  21977. {
  21978. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), operatorConstraintReturnType);
  21979. }
  21980. else
  21981. {
  21982. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  21983. mResult = CreateCall(&methodMatcher, BfTypedValue());
  21984. }
  21985. if ((mResult.mType != NULL) && (methodMatcher.mSelfType != NULL) && (mResult.mType->IsSelf()))
  21986. {
  21987. BF_ASSERT(mModule->IsInGeneric());
  21988. mResult = mModule->GetDefaultTypedValue(methodMatcher.mSelfType, false, BfDefaultValueKind_Value);
  21989. }
  21990. if ((invertResult) && (mResult.mType == mModule->GetPrimitiveType(BfTypeCode_Boolean)))
  21991. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  21992. if (pass == 1)
  21993. {
  21994. if (findBinaryOp == BfBinaryOp_Compare)
  21995. {
  21996. mResult = mModule->LoadValue(mResult);
  21997. if (mResult.mType->IsIntegral())
  21998. mResult.mValue = mModule->mBfIRBuilder->CreateNeg(mResult.mValue);
  21999. }
  22000. }
  22001. if ((isComparison) && (matchedOp == BfBinaryOp_Compare))
  22002. {
  22003. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  22004. mResult = mModule->LoadValue(mResult);
  22005. if (mResult.mType != intType)
  22006. mResult = mModule->GetDefaultTypedValue(intType);
  22007. auto zeroVal = mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  22008. auto useBinaryOp = binaryOp;
  22009. if (pass == 1)
  22010. useBinaryOp = BfGetFlippedBinaryOp(useBinaryOp);
  22011. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  22012. switch (useBinaryOp)
  22013. {
  22014. case BfBinaryOp_Equality:
  22015. case BfBinaryOp_StrictEquality:
  22016. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mResult.mValue, zeroVal), boolType);
  22017. break;
  22018. case BfBinaryOp_InEquality:
  22019. case BfBinaryOp_StrictInEquality:
  22020. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mResult.mValue, zeroVal), boolType);
  22021. break;
  22022. case BfBinaryOp_GreaterThan:
  22023. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(mResult.mValue, zeroVal, true), boolType);
  22024. break;
  22025. case BfBinaryOp_LessThan:
  22026. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(mResult.mValue, zeroVal, true), boolType);
  22027. break;
  22028. case BfBinaryOp_GreaterThanOrEqual:
  22029. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(mResult.mValue, zeroVal, true), boolType);
  22030. break;
  22031. case BfBinaryOp_LessThanOrEqual:
  22032. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(mResult.mValue, zeroVal, true), boolType);
  22033. break;
  22034. default: break;
  22035. }
  22036. }
  22037. return;
  22038. }
  22039. auto _CheckBinaryOp = [&](BfGenericParamInstance* genericParam)
  22040. {
  22041. for (auto& opConstraint : genericParam->mOperatorConstraints)
  22042. {
  22043. BfType* returnType = genericParam->mExternType;
  22044. bool works = false;
  22045. if (opConstraint.mBinaryOp == findBinaryOp)
  22046. {
  22047. if (((args[0].mTypedValue) && (mModule->CanCast(args[0].mTypedValue, opConstraint.mLeftType))) &&
  22048. ((args[1].mTypedValue) && (mModule->CanCast(args[1].mTypedValue, opConstraint.mRightType))))
  22049. {
  22050. works = true;
  22051. }
  22052. }
  22053. if ((isComparison) && (opConstraint.mBinaryOp == BfBinaryOp_Compare))
  22054. {
  22055. if (((args[0].mTypedValue) && (mModule->CanCast(args[0].mTypedValue, opConstraint.mLeftType))) &&
  22056. ((args[1].mTypedValue) && (mModule->CanCast(args[1].mTypedValue, opConstraint.mRightType))))
  22057. {
  22058. works = true;
  22059. }
  22060. else if (((args[0].mTypedValue) && (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType))) &&
  22061. ((args[1].mTypedValue) && (mModule->CanCast(args[1].mTypedValue, opConstraint.mLeftType))))
  22062. {
  22063. works = true;
  22064. }
  22065. if (works)
  22066. {
  22067. returnType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  22068. }
  22069. }
  22070. if (works)
  22071. {
  22072. BF_ASSERT(genericParam->mExternType != NULL);
  22073. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  22074. return true;
  22075. }
  22076. }
  22077. return false;
  22078. };
  22079. // Check method generic constraints
  22080. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  22081. {
  22082. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  22083. {
  22084. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  22085. if (_CheckBinaryOp(genericParam))
  22086. return;
  22087. }
  22088. }
  22089. // Check type generic constraints
  22090. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  22091. {
  22092. SizedArray<BfGenericParamInstance*, 4> genericParams;
  22093. mModule->GetActiveTypeGenericParamInstances(genericParams);
  22094. for (auto genericParam : genericParams)
  22095. {
  22096. if (_CheckBinaryOp(genericParam))
  22097. return;
  22098. }
  22099. }
  22100. if (pass == 1)
  22101. break;
  22102. auto flippedBinaryOp = BfGetFlippedBinaryOp(findBinaryOp);
  22103. if (flippedBinaryOp != BfBinaryOp_None)
  22104. findBinaryOp = flippedBinaryOp;
  22105. }
  22106. bool resultHandled = false;
  22107. if (((origLeftType != NULL) && (origLeftType->IsIntUnknown())) ||
  22108. ((origRightType != NULL) && (origRightType->IsIntUnknown())))
  22109. {
  22110. if (!resultType->IsPrimitiveType())
  22111. {
  22112. BfType* numericCastType = mModule->GetClosestNumericCastType(*resultTypedValue, mExpectingType);
  22113. if (numericCastType != NULL)
  22114. {
  22115. resultHandled = true;
  22116. resultType = numericCastType;
  22117. }
  22118. }
  22119. }
  22120. if (!resultHandled)
  22121. {
  22122. auto prevResultType = resultType;
  22123. if ((leftValue.mType->IsPrimitiveType()) && (!origLeftType->IsIntUnknown()) && (!rightValue.mType->IsTypedPrimitive()))
  22124. resultType = leftValue.mType;
  22125. if ((rightValue.mType->IsPrimitiveType()) && (!origRightType->IsIntUnknown()) && (!leftValue.mType->IsTypedPrimitive()))
  22126. resultType = rightValue.mType;
  22127. }
  22128. }
  22129. }
  22130. if (deferRight)
  22131. {
  22132. auto expectedType = resultType;
  22133. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  22134. expectedType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  22135. rightValue = mModule->CreateValueFromExpression(BfNodeDynCast<BfExpression>(rightExpression), expectedType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  22136. if (rightValue)
  22137. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, (BfBinOpFlags)(flags & ~BfBinOpFlag_DeferRight), leftValue, rightValue);
  22138. return;
  22139. }
  22140. if (mModule->IsUnboundGeneric(resultType))
  22141. {
  22142. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  22143. return;
  22144. }
  22145. if (resultType->IsPointer() && otherType->IsPointer())
  22146. {
  22147. if ((binaryOp == BfBinaryOp_Add) && (resultType == otherType) &&
  22148. (resultType->GetUnderlyingType() == mModule->GetPrimitiveType(BfTypeCode_Char8)))
  22149. {
  22150. AddStrings(leftValue, rightValue, opToken);
  22151. return;
  22152. }
  22153. //TODO: Allow all pointer comparisons, but only allow SUBTRACTION between equal pointer types
  22154. if ((binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowSubtract))
  22155. {
  22156. if (!mModule->CanCast(*otherTypedValue, resultType))
  22157. {
  22158. mModule->Fail(StrFormat("Operands '%s' and '%s' are not comparable types.",
  22159. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()),
  22160. opToken);
  22161. return;
  22162. }
  22163. BfPointerType* resultPointerType = (BfPointerType*)resultType;
  22164. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  22165. if (resultPointerType->mElementType->mSize == 0)
  22166. {
  22167. if (!mModule->IsInSpecializedSection())
  22168. mModule->Warn(0, "Subtracting pointers to zero-sized elements will always result in zero", opToken);
  22169. mResult = mModule->GetDefaultTypedValue(intPtrType);
  22170. }
  22171. else
  22172. {
  22173. convLeftValue = mModule->CastToValue(leftExpression, leftValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  22174. convRightValue = mModule->CastToValue(rightExpression, rightValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  22175. BfIRValue diffValue = mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue);
  22176. diffValue = mModule->mBfIRBuilder->CreateDiv(diffValue, mModule->GetConstValue(resultPointerType->mElementType->GetStride(), intPtrType), true);
  22177. mResult = BfTypedValue(diffValue, intPtrType);
  22178. }
  22179. return;
  22180. }
  22181. else if ((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_StrictEquality) &&
  22182. (binaryOp != BfBinaryOp_InEquality) && (binaryOp != BfBinaryOp_StrictInEquality) &&
  22183. (binaryOp != BfBinaryOp_LessThan) && (binaryOp != BfBinaryOp_LessThanOrEqual) &&
  22184. (binaryOp != BfBinaryOp_GreaterThan) && (binaryOp != BfBinaryOp_GreaterThanOrEqual))
  22185. {
  22186. if (mModule->PreFail())
  22187. mModule->Fail("Invalid operation on pointers", opToken);
  22188. return;
  22189. }
  22190. if ((!BfBinOpEqualityCheck(binaryOp)) || (resultType != otherType))
  22191. {
  22192. resultType = mModule->GetPrimitiveType(BfTypeCode_UIntPtr);
  22193. explicitCast = true;
  22194. }
  22195. }
  22196. else if (resultType->IsPointer())
  22197. {
  22198. if (otherType->IsNull())
  22199. {
  22200. if (!BfBinOpEqualityCheck(binaryOp))
  22201. {
  22202. if (mModule->PreFail())
  22203. mModule->Fail(StrFormat("Invalid operation between '%s' and null", mModule->TypeToString(resultType).c_str()), opToken);
  22204. return;
  22205. }
  22206. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  22207. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22208. else
  22209. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22210. return;
  22211. }
  22212. // One pointer
  22213. if ((!otherType->IsIntegral()) ||
  22214. ((binaryOp != BfBinaryOp_Add) && (binaryOp != BfBinaryOp_Subtract) && (binaryOp != BfBinaryOp_OverflowAdd) && (binaryOp != BfBinaryOp_OverflowSubtract)))
  22215. {
  22216. _OpFail();
  22217. return;
  22218. }
  22219. auto underlyingType = resultType->GetUnderlyingType();
  22220. if ((underlyingType->IsSizedArray()) && (!mModule->IsInSpecializedSection()))
  22221. 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);
  22222. BfIRValue addValue = otherTypedValue->mValue;
  22223. if ((!otherTypedValue->mType->IsSigned()) && (otherTypedValue->mType->mSize < mModule->mSystem->mPtrSize))
  22224. addValue = mModule->mBfIRBuilder->CreateNumericCast(addValue, false, BfTypeCode_UIntPtr);
  22225. if ((binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowSubtract))
  22226. {
  22227. if (resultTypeSrc == rightExpression)
  22228. mModule->Fail("Cannot subtract a pointer from an integer", resultTypeSrc);
  22229. addValue = mModule->mBfIRBuilder->CreateNeg(addValue);
  22230. }
  22231. mModule->PopulateType(underlyingType);
  22232. if (underlyingType->IsValuelessType())
  22233. {
  22234. if (!mModule->IsInSpecializedSection())
  22235. mModule->Warn(0, "Adding to a pointer to a zero-sized element has no effect", opToken);
  22236. mResult = *resultTypedValue;
  22237. return;
  22238. }
  22239. mModule->mBfIRBuilder->PopulateType(underlyingType);
  22240. mResult = BfTypedValue(mModule->CreateIndexedValue(underlyingType, resultTypedValue->mValue, addValue), resultType);
  22241. return;
  22242. }
  22243. if ((resultType->IsFunction()) || (resultType->IsPointer()) || (resultType->IsObject()) || (resultType->IsInterface()) || (resultType->IsGenericParam()))
  22244. {
  22245. if ((binaryOp == BfBinaryOp_Add) &&
  22246. (resultType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)) &&
  22247. (otherType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  22248. {
  22249. AddStrings(leftValue, rightValue, opToken);
  22250. return;
  22251. }
  22252. if (!BfGetBinaryOpPrecendence(binaryOp))
  22253. {
  22254. //mModule->Fail("Invalid operation for objects", opToken);
  22255. _OpFail();
  22256. return;
  22257. }
  22258. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  22259. {
  22260. leftValue = mModule->LoadOrAggregateValue(leftValue);
  22261. rightValue = mModule->LoadOrAggregateValue(rightValue);
  22262. if (resultType->IsInterface())
  22263. {
  22264. // Compare as objects instead
  22265. resultType = mModule->mContext->mBfObjectType;
  22266. *resultTypedValue = mModule->Cast(resultTypeSrc, *resultTypedValue, resultType);
  22267. }
  22268. if (otherType->IsNull())
  22269. {
  22270. if (resultType->IsFunction())
  22271. {
  22272. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  22273. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22274. else
  22275. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22276. }
  22277. else
  22278. {
  22279. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  22280. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22281. else
  22282. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22283. }
  22284. }
  22285. else
  22286. {
  22287. auto convertedValue = mModule->Cast(otherTypeSrc, *otherTypedValue, resultType, BfCastFlags_NoBox);
  22288. if (!convertedValue)
  22289. return;
  22290. convertedValue = mModule->LoadValue(convertedValue);
  22291. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  22292. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(resultTypedValue->mValue, convertedValue.mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22293. else
  22294. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(resultTypedValue->mValue, convertedValue.mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22295. }
  22296. return;
  22297. }
  22298. }
  22299. if (resultType->IsTypedPrimitive())
  22300. {
  22301. bool needsOtherCast = true;
  22302. if (otherType != resultType)
  22303. {
  22304. if ((otherType->IsPrimitiveType()) && (!otherType->IsValuelessType()))
  22305. {
  22306. // Allow zero comparisons to match all typed primitives
  22307. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  22308. {
  22309. auto constant = mModule->mBfIRBuilder->GetConstant(otherTypedValue->mValue);
  22310. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 == 0))
  22311. needsOtherCast = false;
  22312. }
  22313. // Allow integer offsetting
  22314. if ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowAdd) || (binaryOp == BfBinaryOp_OverflowSubtract))
  22315. {
  22316. if (otherType->IsIntegral())
  22317. needsOtherCast = false;
  22318. }
  22319. }
  22320. if (needsOtherCast)
  22321. {
  22322. BfCastFlags castFlags = (BfCastFlags)((explicitCast ? BfCastFlags_Explicit : BfCastFlags_None) | BfCastFlags_SilentFail);
  22323. BfIRValue otherCastResult = mModule->CastToValue(otherTypeSrc, *otherTypedValue, resultType, castFlags);
  22324. if (!otherCastResult)
  22325. {
  22326. // We picked the wrong type, try the other one...
  22327. if (mModule->CanCast(*resultTypedValue, otherType))
  22328. {
  22329. BfBinOpFlags newFlags = flags;
  22330. if (otherTypedValue == &leftValue)
  22331. newFlags = (BfBinOpFlags)(flags | BfBinOpFlag_ForceLeftType & ~BfBinOpFlag_ForceRightType & ~BfBinOpFlag_DeferRight);
  22332. else
  22333. newFlags = (BfBinOpFlags)(flags | BfBinOpFlag_ForceRightType & ~BfBinOpFlag_ForceLeftType & ~BfBinOpFlag_DeferRight);
  22334. return PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, newFlags, leftValue, rightValue);
  22335. }
  22336. // Do again but with an error
  22337. castFlags = (BfCastFlags)(castFlags & ~BfCastFlags_SilentFail);
  22338. otherCastResult = mModule->CastToValue(otherTypeSrc, *otherTypedValue, resultType, castFlags);
  22339. }
  22340. }
  22341. }
  22342. auto underlyingType = resultType->GetUnderlyingType();
  22343. if ((binaryOp == BfBinaryOp_Subtract) && (otherTypedValue->mType == resultType))
  22344. {
  22345. intptr maxDist = 0;
  22346. auto resultTypeInstance = resultType->ToTypeInstance();
  22347. if ((resultTypeInstance != NULL) && (resultTypeInstance->mTypeInfoEx != NULL))
  22348. maxDist = resultTypeInstance->mTypeInfoEx->mMaxValue - resultTypeInstance->mTypeInfoEx->mMinValue;
  22349. if (maxDist >= 0x80000000UL)
  22350. resultType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  22351. else if (maxDist >= 0x8000)
  22352. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  22353. else if (maxDist >= 0x80)
  22354. resultType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  22355. else
  22356. resultType = mModule->GetPrimitiveType(BfTypeCode_Int8);
  22357. underlyingType = resultType;
  22358. }
  22359. BfIRValue convResultValue;
  22360. if (resultTypedValue->mType == resultType)
  22361. convResultValue = mModule->LoadValue(*resultTypedValue).mValue;
  22362. else
  22363. convResultValue = mModule->CastToValue(resultTypeSrc, *resultTypedValue, underlyingType, BfCastFlags_Explicit);
  22364. BfIRValue convOtherValue;
  22365. if (otherTypedValue->mType == resultType)
  22366. convOtherValue = mModule->LoadValue(*otherTypedValue).mValue;
  22367. else
  22368. convOtherValue = mModule->CastToValue(otherTypeSrc, *otherTypedValue, underlyingType, BfCastFlags_Explicit);
  22369. if ((!underlyingType->IsValuelessType()) && ((!convResultValue) || (!convOtherValue)))
  22370. return;
  22371. if (resultTypedValue == &leftValue)
  22372. PerformBinaryOperation(underlyingType, convResultValue, convOtherValue, binaryOp, opToken);
  22373. else
  22374. PerformBinaryOperation(underlyingType, convOtherValue, convResultValue, binaryOp, opToken);
  22375. if (mResult.mType == underlyingType)
  22376. mResult.mType = resultType;
  22377. return;
  22378. }
  22379. auto _CallValueTypeEquals = [&]()
  22380. {
  22381. BfModuleMethodInstance moduleMethodInstance;
  22382. auto typeInst = leftValue.mType->ToTypeInstance();
  22383. if (typeInst != NULL)
  22384. {
  22385. if ((binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  22386. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_STRICT_EQUALS);
  22387. else
  22388. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_EQUALS);
  22389. }
  22390. else
  22391. {
  22392. BF_ASSERT(leftValue.mType->IsSizedArray() || leftValue.mType->IsMethodRef());
  22393. auto valueTypeInst = mModule->ResolveTypeDef(mModule->mCompiler->mValueTypeTypeDef)->ToTypeInstance();
  22394. BfMethodDef* equalsMethodDef = mModule->mCompiler->mValueTypeTypeDef->GetMethodByName("Equals");
  22395. BfTypeVector typeVec;
  22396. typeVec.push_back(leftValue.mType);
  22397. moduleMethodInstance = mModule->GetMethodInstance(valueTypeInst, equalsMethodDef, typeVec);
  22398. }
  22399. if (moduleMethodInstance)
  22400. {
  22401. if ((opToken != NULL) && (!noClassify))
  22402. mModule->SetElementType(opToken, BfSourceElementType_Method);
  22403. SizedArray<BfResolvedArg, 4> argValues;
  22404. BfResolvedArg resolvedArg;
  22405. resolvedArg.mTypedValue = leftValue;
  22406. argValues.push_back(resolvedArg);
  22407. resolvedArg.mTypedValue = rightValue;
  22408. argValues.push_back(resolvedArg);
  22409. mResult = CreateCall(opToken, BfTypedValue(), BfTypedValue(), moduleMethodInstance.mMethodInstance->mMethodDef, moduleMethodInstance, BfCreateCallFlags_None, argValues);
  22410. if ((mResult) &&
  22411. ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality)))
  22412. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  22413. return true;
  22414. }
  22415. return false;
  22416. };
  22417. //if (((leftValue.mType->IsComposite()) || (leftValue.mType->IsObject())))
  22418. if (((resultType->IsComposite()) || (resultType->IsObject())))
  22419. {
  22420. bool areEquivalentTuples = false;
  22421. if ((leftValue.mType->IsTuple()) && (rightValue.mType->IsTuple()))
  22422. {
  22423. auto leftTupleType = (BfTypeInstance*)leftValue.mType;
  22424. auto rightTupleType = (BfTypeInstance*)rightValue.mType;
  22425. // We only do this for tuples, because we would allow an implicit struct
  22426. // truncation if we allow it for all structs, which would result in only
  22427. // the base class's fields being compared
  22428. if (mModule->CanCast(rightValue, leftValue.mType))
  22429. rightValue = mModule->Cast(opToken, rightValue, leftValue.mType, BfCastFlags_Explicit);
  22430. else if (mModule->CanCast(leftValue, rightValue.mType))
  22431. leftValue = mModule->Cast(opToken, leftValue, rightValue.mType, BfCastFlags_Explicit);
  22432. }
  22433. if (leftValue.mType == rightValue.mType)
  22434. {
  22435. if (BfBinOpEqualityCheck(binaryOp))
  22436. {
  22437. auto intCoercibleType = mModule->GetIntCoercibleType(leftValue.mType);
  22438. if (intCoercibleType != NULL)
  22439. {
  22440. auto intLHS = mModule->GetIntCoercible(leftValue);
  22441. auto intRHS = mModule->GetIntCoercible(rightValue);
  22442. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  22443. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  22444. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(intLHS.mValue, intRHS.mValue), boolType);
  22445. else
  22446. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(intLHS.mValue, intRHS.mValue), boolType);
  22447. return;
  22448. }
  22449. // Valueless types always compare as 'equal' if we can ensure no members could have an equality operator overload
  22450. if (leftValue.mType->IsComposite())
  22451. {
  22452. mModule->PopulateType(leftValue.mType);
  22453. if (leftValue.mType->IsValuelessType())
  22454. {
  22455. bool mayHaveEqualOverload = false;
  22456. auto leftTypeInst = leftValue.mType->ToTypeInstance();
  22457. if (leftTypeInst != NULL)
  22458. {
  22459. std::function<bool(BfType*)> _HasTypeInstance = [&](BfType* type)
  22460. {
  22461. if (type == NULL)
  22462. return false;
  22463. if (type->IsTypeInstance())
  22464. return true;
  22465. if (type->IsSizedArray())
  22466. return _HasTypeInstance(((BfSizedArrayType*)type)->mElementType);
  22467. return false;
  22468. };
  22469. for (auto& fieldInstance : leftTypeInst->mFieldInstances)
  22470. {
  22471. if (_HasTypeInstance(fieldInstance.mResolvedType))
  22472. mayHaveEqualOverload = true;
  22473. }
  22474. }
  22475. if (!mayHaveEqualOverload)
  22476. {
  22477. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  22478. bool isEqual = (binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality);
  22479. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  22480. return;
  22481. }
  22482. }
  22483. }
  22484. if (_CallValueTypeEquals())
  22485. return;
  22486. }
  22487. if (PerformBinaryOperation_Numeric(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue))
  22488. return;
  22489. if (mModule->PreFail())
  22490. {
  22491. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s'",
  22492. BfGetOpName(binaryOp),
  22493. mModule->TypeToString(leftValue.mType).c_str()), opToken);
  22494. }
  22495. return;
  22496. }
  22497. else
  22498. {
  22499. bool handled = false;
  22500. for (int pass = 0; pass < 2; pass++)
  22501. {
  22502. BfTypedValue& fromValue = (pass == 0) ? leftValue : rightValue;
  22503. BfType* toType = (pass == 0) ? rightValue.mType : leftValue.mType;
  22504. if (mModule->CanCast(fromValue, toType))
  22505. {
  22506. auto result = mModule->Cast(opToken, fromValue, toType);
  22507. if (result)
  22508. {
  22509. resultType = toType;
  22510. fromValue = result;
  22511. handled = true;
  22512. break;
  22513. }
  22514. }
  22515. }
  22516. if (!handled)
  22517. {
  22518. if ((leftValue.mType->IsUndefSizedArray()) || (rightValue.mType->IsUndefSizedArray()))
  22519. {
  22520. if ((leftValue.mType->IsSizedArray()) && (rightValue.mType->IsSizedArray() &&
  22521. (leftValue.mType->GetUnderlyingType() == rightValue.mType->GetUnderlyingType())))
  22522. {
  22523. if (BfBinOpEqualityCheck(binaryOp))
  22524. {
  22525. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  22526. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Undef);
  22527. return;
  22528. }
  22529. }
  22530. }
  22531. if (PerformBinaryOperation_Numeric(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue))
  22532. return;
  22533. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s' and '%s'",
  22534. BfGetOpName(binaryOp),
  22535. mModule->TypeToString(leftValue.mType).c_str(),
  22536. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  22537. return;
  22538. }
  22539. }
  22540. }
  22541. if (resultType->IsMethodRef() && otherType->IsMethodRef())
  22542. {
  22543. if (BfBinOpEqualityCheck(binaryOp))
  22544. {
  22545. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  22546. BfMethodRefType* lhsMethodRefType = (BfMethodRefType*)leftValue.mType;
  22547. BfMethodRefType* rhsMethodRefType = (BfMethodRefType*)rightValue.mType;
  22548. if (lhsMethodRefType->mMethodRef != rhsMethodRefType->mMethodRef)
  22549. {
  22550. mResult = BfTypedValue(mModule->GetConstValue(((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality)) ? 0 : 1, boolType), boolType);
  22551. return;
  22552. }
  22553. if (_CallValueTypeEquals())
  22554. return;
  22555. }
  22556. }
  22557. if (resultType->IsIntegral())
  22558. {
  22559. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  22560. {
  22561. if (rightValue.mValue.IsConst())
  22562. {
  22563. auto constVal = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  22564. if ((constVal->mInt64 < 0) || (constVal->mInt64 >= 8 * resultType->mSize))
  22565. {
  22566. mModule->Fail(StrFormat("Shift value '%lld' is out of range for type '%s'", constVal->mInt64, mModule->TypeToString(resultType).c_str()), opToken);
  22567. }
  22568. }
  22569. }
  22570. // We're trying a simplified scheme that doesn't always try to up-convert into an 'int'
  22571. if (leftValue.mType != rightValue.mType)
  22572. {
  22573. bool isBitwiseExpr =
  22574. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  22575. (binaryOp == BfBinaryOp_BitwiseOr) ||
  22576. (binaryOp == BfBinaryOp_ExclusiveOr) ||
  22577. (binaryOp == BfBinaryOp_LeftShift) ||
  22578. (binaryOp == BfBinaryOp_RightShift) ||
  22579. (binaryOp == BfBinaryOp_Equality) ||
  22580. (binaryOp == BfBinaryOp_InEquality) ||
  22581. (binaryOp == BfBinaryOp_StrictEquality) ||
  22582. (binaryOp == BfBinaryOp_StrictInEquality);
  22583. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  22584. {
  22585. // For shifts we have more lenient rules - shifts are naturally limited so any int type is equally valid
  22586. if (rightValue.mType->IsIntegral())
  22587. explicitCast = true;
  22588. }
  22589. else if (((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowAdd) || (binaryOp == BfBinaryOp_OverflowSubtract)) && (resultType->IsChar()) && (otherType->IsInteger()))
  22590. {
  22591. // charVal += intVal;
  22592. explicitCast = true;
  22593. }
  22594. else if ((!resultType->IsSigned()) && (otherType->IsSigned()))
  22595. {
  22596. if (mModule->CanCast(*otherTypedValue, resultType))
  22597. {
  22598. // If we can convert the 'other' value implicitly then it's a convertible literal, leave as uint
  22599. }
  22600. else
  22601. {
  22602. mModule->Fail(StrFormat("Operator cannot be applied to operands of type '%s' and '%s'",
  22603. mModule->TypeToString(leftValue.mType).c_str(),
  22604. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  22605. return;
  22606. }
  22607. }
  22608. else if ((isBitwiseExpr) && (otherType->IsIntegral()) && (resultType->mSize == otherType->mSize))
  22609. {
  22610. // Forget about signed/unsigned mismatches for bitwise operations
  22611. explicitCast = true;
  22612. }
  22613. else
  22614. {
  22615. if (((binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowSubtract)) &&
  22616. (resultType->IsChar()) && (otherType->IsChar()))
  22617. {
  22618. // "wchar - char" subtraction will always fit into int32, because of unicode range
  22619. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  22620. explicitCast = true;
  22621. }
  22622. else if ((otherType->IsChar()) &&
  22623. ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowAdd) || (binaryOp == BfBinaryOp_OverflowSubtract)))
  22624. {
  22625. mModule->Fail(StrFormat("Cannot perform operation between types '%s' and '%s'",
  22626. mModule->TypeToString(leftValue.mType).c_str(),
  22627. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  22628. }
  22629. }
  22630. }
  22631. else if ((!resultType->IsSigned()) && (binaryOp == BfBinaryOp_Subtract) && (!forceLeftType))
  22632. {
  22633. if ((mExpectingType == NULL) || (mExpectingType->IsSigned()) || (resultType->IsChar()))
  22634. {
  22635. if ((resultType->IsChar()) && (resultType->mSize == 4))
  22636. {
  22637. // "wchar - wchar" subtraction will always fit into int32, because of unicode range
  22638. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  22639. }
  22640. else
  22641. {
  22642. // The result of uint8 - uint8 is int16 (for example)
  22643. switch (resultType->mSize)
  22644. {
  22645. case 1:
  22646. resultType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  22647. break;
  22648. case 2:
  22649. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  22650. break;
  22651. case 4:
  22652. resultType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  22653. break;
  22654. }
  22655. }
  22656. explicitCast = true;
  22657. }
  22658. }
  22659. else if (resultType->IsChar())
  22660. {
  22661. bool canDoOp =
  22662. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  22663. (binaryOp == BfBinaryOp_BitwiseOr) ||
  22664. ((binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_Compare));
  22665. if (!canDoOp)
  22666. {
  22667. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  22668. return;
  22669. }
  22670. }
  22671. }
  22672. if (!convLeftValue)
  22673. convLeftValue = mModule->CastToValue(leftExpression, leftValue, resultType,
  22674. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  22675. if (!convRightValue)
  22676. convRightValue = mModule->CastToValue(rightExpression, rightValue, resultType,
  22677. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  22678. PerformBinaryOperation(resultType, convLeftValue, convRightValue, binaryOp, opToken);
  22679. }
  22680. void BfExprEvaluator::PerformBinaryOperation(BfType* resultType, BfIRValue convLeftValue, BfIRValue convRightValue, BfBinaryOp binaryOp, BfAstNode* opToken)
  22681. {
  22682. if (resultType->IsValuelessType())
  22683. {
  22684. switch (binaryOp)
  22685. {
  22686. case BfBinaryOp_Equality:
  22687. case BfBinaryOp_StrictEquality:
  22688. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1),
  22689. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22690. return;
  22691. case BfBinaryOp_InEquality:
  22692. case BfBinaryOp_StrictInEquality:
  22693. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0),
  22694. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22695. return;
  22696. default:
  22697. break;
  22698. }
  22699. }
  22700. if ((!convLeftValue) || (!convRightValue))
  22701. return;
  22702. if (resultType->IsPrimitiveType())
  22703. {
  22704. auto primType = (BfPrimitiveType*)resultType;
  22705. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  22706. {
  22707. bool passThrough = false;
  22708. switch (binaryOp)
  22709. {
  22710. case BfBinaryOp_Equality:
  22711. case BfBinaryOp_StrictEquality:
  22712. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  22713. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22714. break;
  22715. case BfBinaryOp_InEquality:
  22716. case BfBinaryOp_StrictInEquality:
  22717. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  22718. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22719. break;
  22720. case BfBinaryOp_BitwiseAnd:
  22721. case BfBinaryOp_ConditionalAnd:
  22722. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue),
  22723. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22724. break;
  22725. case BfBinaryOp_BitwiseOr:
  22726. case BfBinaryOp_ConditionalOr:
  22727. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue),
  22728. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22729. break;
  22730. case BfBinaryOp_ExclusiveOr:
  22731. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue),
  22732. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22733. break;
  22734. case BfBinaryOp_Compare:
  22735. passThrough = true;
  22736. break;
  22737. default:
  22738. if (mModule->PreFail())
  22739. mModule->Fail("Invalid operation for booleans", opToken);
  22740. break;
  22741. }
  22742. if (!passThrough)
  22743. return;
  22744. }
  22745. }
  22746. if ((!resultType->IsIntegralOrBool()) && (!resultType->IsFloat()))
  22747. {
  22748. if (mModule->PreFail())
  22749. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  22750. return;
  22751. }
  22752. if (resultType->IsIntegral())
  22753. {
  22754. switch (binaryOp)
  22755. {
  22756. case BfBinaryOp_BitwiseAnd:
  22757. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue), resultType);
  22758. return;
  22759. case BfBinaryOp_BitwiseOr:
  22760. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue), resultType);
  22761. return;
  22762. case BfBinaryOp_ExclusiveOr:
  22763. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue), resultType);
  22764. return;
  22765. case BfBinaryOp_LeftShift:
  22766. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShl(convLeftValue, convRightValue), resultType);
  22767. mModule->CheckRangeError(resultType, opToken);
  22768. return;
  22769. case BfBinaryOp_RightShift:
  22770. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShr(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  22771. return;
  22772. default: break;
  22773. }
  22774. }
  22775. if ((resultType->IsChar()) &&
  22776. ((binaryOp == BfBinaryOp_Multiply) ||
  22777. (binaryOp == BfBinaryOp_OverflowMultiply) ||
  22778. (binaryOp == BfBinaryOp_Divide) ||
  22779. (binaryOp == BfBinaryOp_Modulus)))
  22780. {
  22781. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  22782. return;
  22783. }
  22784. auto _GetOverflowKind = [&](bool wantOverflow)
  22785. {
  22786. if (resultType->IsFloat())
  22787. return BfOverflowCheckKind_None;
  22788. if (!wantOverflow)
  22789. return BfOverflowCheckKind_None;
  22790. if (mModule->GetDefaultCheckedKind() != BfCheckedKind_Checked)
  22791. return BfOverflowCheckKind_None;
  22792. bool arithmeticChecks = mModule->mCompiler->mOptions.mArithmeticChecks;
  22793. auto typeOptions = mModule->GetTypeOptions();
  22794. if (typeOptions != NULL)
  22795. arithmeticChecks = typeOptions->Apply(arithmeticChecks, BfOptionFlags_ArithmeticCheck);
  22796. if (!arithmeticChecks)
  22797. return BfOverflowCheckKind_None;
  22798. BfOverflowCheckKind overflowCheckKind = (resultType->IsSigned()) ? BfOverflowCheckKind_Signed : BfOverflowCheckKind_Unsigned;
  22799. if (!mModule->IsOptimized())
  22800. overflowCheckKind = (BfOverflowCheckKind)(overflowCheckKind | BfOverflowCheckKind_Flag_UseAsm);
  22801. return overflowCheckKind;
  22802. };
  22803. switch (binaryOp)
  22804. {
  22805. case BfBinaryOp_Add:
  22806. case BfBinaryOp_OverflowAdd:
  22807. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAdd(convLeftValue, convRightValue, _GetOverflowKind(binaryOp == BfBinaryOp_Add)), resultType);
  22808. if (binaryOp != BfBinaryOp_OverflowAdd)
  22809. mModule->CheckRangeError(resultType, opToken);
  22810. break;
  22811. case BfBinaryOp_Subtract:
  22812. case BfBinaryOp_OverflowSubtract:
  22813. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue, _GetOverflowKind(binaryOp == BfBinaryOp_Subtract)), resultType);
  22814. if (binaryOp != BfBinaryOp_OverflowSubtract)
  22815. mModule->CheckRangeError(resultType, opToken);
  22816. break;
  22817. case BfBinaryOp_Multiply:
  22818. case BfBinaryOp_OverflowMultiply:
  22819. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateMul(convLeftValue, convRightValue, _GetOverflowKind(binaryOp == BfBinaryOp_Multiply)), resultType);
  22820. if (binaryOp != BfBinaryOp_OverflowMultiply)
  22821. mModule->CheckRangeError(resultType, opToken);
  22822. break;
  22823. case BfBinaryOp_Divide:
  22824. {
  22825. bool isZero = false;
  22826. if (convRightValue.IsConst())
  22827. {
  22828. auto constVal = mModule->mBfIRBuilder->GetConstant(convRightValue);
  22829. if (BfIRBuilder::IsInt(constVal->mTypeCode))
  22830. isZero = constVal->mInt64 == 0;
  22831. }
  22832. if (isZero)
  22833. {
  22834. mModule->Fail("Divide by zero", opToken);
  22835. mResult = mModule->GetDefaultTypedValue(resultType);
  22836. }
  22837. else
  22838. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateDiv(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  22839. }
  22840. break;
  22841. case BfBinaryOp_Modulus:
  22842. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateRem(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  22843. break;
  22844. case BfBinaryOp_Equality:
  22845. case BfBinaryOp_StrictEquality:
  22846. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  22847. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22848. break;
  22849. case BfBinaryOp_InEquality:
  22850. case BfBinaryOp_StrictInEquality:
  22851. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  22852. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22853. break;
  22854. case BfBinaryOp_LessThan:
  22855. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned()),
  22856. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22857. break;
  22858. case BfBinaryOp_LessThanOrEqual:
  22859. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(convLeftValue, convRightValue, resultType->IsSigned()),
  22860. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22861. break;
  22862. case BfBinaryOp_GreaterThan:
  22863. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned()),
  22864. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22865. break;
  22866. case BfBinaryOp_GreaterThanOrEqual:
  22867. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(convLeftValue, convRightValue, resultType->IsSigned()),
  22868. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  22869. break;
  22870. case BfBinaryOp_Compare:
  22871. {
  22872. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  22873. if ((convLeftValue.IsConst()) && (convRightValue.IsConst()))
  22874. {
  22875. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned());
  22876. auto ltConstant = mModule->mBfIRBuilder->GetConstant(cmpLtVal);
  22877. if (ltConstant->mBool)
  22878. {
  22879. mResult = BfTypedValue(mModule->GetConstValue(-1, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  22880. }
  22881. else
  22882. {
  22883. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned());
  22884. auto rtConstant = mModule->mBfIRBuilder->GetConstant(cmpGtVal);
  22885. if (rtConstant->mBool)
  22886. mResult = BfTypedValue(mModule->GetConstValue(1, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  22887. else
  22888. mResult = BfTypedValue(mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  22889. }
  22890. }
  22891. else if ((resultType->IsIntegralOrBool()) && (resultType->mSize < intType->mSize))
  22892. {
  22893. auto leftIntValue = mModule->mBfIRBuilder->CreateNumericCast(convLeftValue, resultType->IsSigned(), BfTypeCode_IntPtr);
  22894. auto rightIntValue = mModule->mBfIRBuilder->CreateNumericCast(convRightValue, resultType->IsSigned(), BfTypeCode_IntPtr);
  22895. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(leftIntValue, rightIntValue), intType);
  22896. }
  22897. else
  22898. {
  22899. BfIRBlock checkGtBlock = mModule->mBfIRBuilder->CreateBlock("cmpCheckGt");
  22900. BfIRBlock eqBlock = mModule->mBfIRBuilder->CreateBlock("cmpEq");
  22901. BfIRBlock endBlock = mModule->mBfIRBuilder->CreateBlock("cmpEnd");
  22902. auto startBlock = mModule->mBfIRBuilder->GetInsertBlock();
  22903. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned());
  22904. mModule->mBfIRBuilder->CreateCondBr(cmpLtVal, endBlock, checkGtBlock);
  22905. mModule->mBfIRBuilder->AddBlock(checkGtBlock);
  22906. mModule->mBfIRBuilder->SetInsertPoint(checkGtBlock);
  22907. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned());
  22908. mModule->mBfIRBuilder->CreateCondBr(cmpGtVal, endBlock, eqBlock);
  22909. mModule->mBfIRBuilder->AddBlock(eqBlock);
  22910. mModule->mBfIRBuilder->SetInsertPoint(eqBlock);
  22911. mModule->mBfIRBuilder->CreateBr(endBlock);
  22912. mModule->mBfIRBuilder->AddBlock(endBlock);
  22913. mModule->mBfIRBuilder->SetInsertPoint(endBlock);
  22914. auto phiVal = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(intType), 3);
  22915. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, -1), startBlock);
  22916. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), checkGtBlock);
  22917. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), eqBlock);
  22918. mResult = BfTypedValue(phiVal, intType);
  22919. }
  22920. }
  22921. break;
  22922. default:
  22923. if (mModule->PreFail())
  22924. mModule->Fail("Invalid operation", opToken);
  22925. break;
  22926. }
  22927. }
  22928. void BfExprEvaluator::Visit(BfBinaryOperatorExpression* binOpExpr)
  22929. {
  22930. BfAutoParentNodeEntry autoParentNodeEntry(mModule, binOpExpr);
  22931. // There are a few binary operations that could actually be casts followed by an unary operation
  22932. // We can't determine that until we know whether the identifier in the parens is a typename or not
  22933. // (double)-1.0 (intptr)&val (BaseStruct)*val
  22934. BfUnaryOp unaryOp = BfUnaryOp_None;
  22935. switch (binOpExpr->mOp)
  22936. {
  22937. case BfBinaryOp_Add: unaryOp = BfUnaryOp_Positive; break;
  22938. case BfBinaryOp_Subtract: unaryOp = BfUnaryOp_Negate; break;
  22939. case BfBinaryOp_Multiply: unaryOp = BfUnaryOp_Dereference; break;
  22940. case BfBinaryOp_BitwiseAnd: unaryOp = BfUnaryOp_AddressOf; break;
  22941. default: break;
  22942. }
  22943. if (unaryOp != BfUnaryOp_None)
  22944. {
  22945. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(binOpExpr->mLeft))
  22946. {
  22947. if (auto castTypeExpr = BfNodeDynCast<BfIdentifierNode>(parenExpr->mExpression))
  22948. {
  22949. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  22950. auto resolvedType = mModule->ResolveTypeRef(castTypeExpr, NULL);
  22951. prevIgnoreError.Restore();
  22952. if (resolvedType != NULL)
  22953. {
  22954. if (auto rightBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>(binOpExpr->mRight))
  22955. {
  22956. int leftPrecedence = BfGetBinaryOpPrecendence(binOpExpr->mOp);
  22957. int rightPrecedence = BfGetBinaryOpPrecendence(rightBinOpExpr->mOp);
  22958. // Do we have a precedence order issue due to mis-parsing this?
  22959. // An example is: "(int)-5.5 * 10"
  22960. if (rightPrecedence > leftPrecedence)
  22961. {
  22962. mModule->FailAfter("Cast target must be wrapped in parentheses", binOpExpr->mLeft);
  22963. }
  22964. }
  22965. PerformUnaryOperation(binOpExpr->mRight, unaryOp, binOpExpr->mOpToken, BfUnaryOpFlag_None);
  22966. if (mResult)
  22967. {
  22968. mResult = mModule->LoadValue(mResult);
  22969. mResult = mModule->Cast(binOpExpr, mResult, resolvedType, BfCastFlags_Explicit);
  22970. }
  22971. return;
  22972. }
  22973. }
  22974. }
  22975. }
  22976. if ((binOpExpr->mOp == BfBinaryOp_LeftShift) || (binOpExpr->mOp == BfBinaryOp_RightShift) ||
  22977. (binOpExpr->mOp == BfBinaryOp_BitwiseAnd) || (binOpExpr->mOp == BfBinaryOp_BitwiseOr) ||
  22978. (binOpExpr->mOp == BfBinaryOp_ExclusiveOr))
  22979. {
  22980. for (int side = 0; side < 2; side++)
  22981. {
  22982. if (auto innerBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>((side == 0) ? binOpExpr->mLeft : binOpExpr->mRight))
  22983. {
  22984. if ((innerBinOpExpr->mOp == BfBinaryOp_Add) || (innerBinOpExpr->mOp == BfBinaryOp_Subtract))
  22985. {
  22986. mModule->Warn(BfWarning_C4554_PossiblePrecedenceError, "Check operator precedence for possible error. Consider using parentheses to clarify precedence", innerBinOpExpr);
  22987. }
  22988. }
  22989. }
  22990. }
  22991. if (binOpExpr->mRight == NULL)
  22992. {
  22993. // We visit the children for autocompletion only
  22994. if (binOpExpr->mLeft != NULL)
  22995. VisitChild(binOpExpr->mLeft);
  22996. if (mResult)
  22997. {
  22998. auto autoComplete = GetAutoComplete();
  22999. if (autoComplete != NULL)
  23000. autoComplete->CheckEmptyStart(binOpExpr->mOpToken, mResult.mType);
  23001. }
  23002. if (binOpExpr->mRight != NULL)
  23003. VisitChild(binOpExpr->mRight);
  23004. return;
  23005. }
  23006. PerformBinaryOperation(binOpExpr->mLeft, binOpExpr->mRight, binOpExpr->mOp, binOpExpr->mOpToken, BfBinOpFlag_None);
  23007. }