BfExprEvaluator.cpp 598 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722
  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 "BfResolvePass.h"
  17. #include "BfUtil.h"
  18. #include "BfDeferEvalChecker.h"
  19. #include "BfVarDeclChecker.h"
  20. #pragma warning(pop)
  21. #include "BeefySysLib/util/AllocDebug.h"
  22. USING_NS_BF;
  23. using namespace llvm;
  24. static BfBinaryOp GetOppositeBinaryOp(BfBinaryOp origOp)
  25. {
  26. switch (origOp)
  27. {
  28. case BfBinaryOp_Equality:
  29. return BfBinaryOp_InEquality;
  30. case BfBinaryOp_InEquality:
  31. return BfBinaryOp_Equality;
  32. case BfBinaryOp_LessThan:
  33. return BfBinaryOp_GreaterThanOrEqual;
  34. case BfBinaryOp_LessThanOrEqual:
  35. return BfBinaryOp_GreaterThan;
  36. case BfBinaryOp_GreaterThan:
  37. return BfBinaryOp_LessThanOrEqual;
  38. case BfBinaryOp_GreaterThanOrEqual:
  39. return BfBinaryOp_LessThan;
  40. default: break;
  41. }
  42. return BfBinaryOp_None;
  43. }
  44. static BfBinaryOp GetFlippedBinaryOp(BfBinaryOp origOp)
  45. {
  46. switch (origOp)
  47. {
  48. case BfBinaryOp_Equality:
  49. return BfBinaryOp_Equality;
  50. case BfBinaryOp_InEquality:
  51. return BfBinaryOp_InEquality;
  52. case BfBinaryOp_LessThan:
  53. return BfBinaryOp_GreaterThan;
  54. case BfBinaryOp_LessThanOrEqual:
  55. return BfBinaryOp_GreaterThanOrEqual;
  56. case BfBinaryOp_GreaterThan:
  57. return BfBinaryOp_LessThan;
  58. case BfBinaryOp_GreaterThanOrEqual:
  59. return BfBinaryOp_LessThanOrEqual;
  60. default: break;
  61. }
  62. return BfBinaryOp_None;
  63. }
  64. //////////////////////////////////////////////////////////////////////////
  65. DeferredTupleAssignData::~DeferredTupleAssignData()
  66. {
  67. for (auto entry : mChildren)
  68. {
  69. delete entry.mExprEvaluator;
  70. delete entry.mInnerTuple;
  71. }
  72. }
  73. //////////////////////////////////////////////////////////////////////////
  74. BfBaseClassWalker::BfBaseClassWalker(BfType* typeA, BfType* typeB, BfModule* module)
  75. {
  76. mMayBeFromInterface = false;
  77. if ((typeA != NULL) && (!typeA->IsInterface()))
  78. mTypes[0] = typeA->ToTypeInstance();
  79. else
  80. mTypes[0] = NULL;
  81. if ((typeB != NULL) && (!typeB->IsInterface()))
  82. mTypes[1] = typeB->ToTypeInstance();
  83. else
  84. mTypes[1] = NULL;
  85. if ((typeA != NULL) && (typeA->IsGenericParam()))
  86. {
  87. mMayBeFromInterface = true;
  88. AddConstraints(typeA, module->GetGenericParamInstance((BfGenericParamType*)typeA));
  89. }
  90. if ((typeB != NULL) && (typeB->IsGenericParam()))
  91. {
  92. mMayBeFromInterface = true;
  93. AddConstraints(typeB, module->GetGenericParamInstance((BfGenericParamType*)typeB));
  94. }
  95. }
  96. /*BfBaseClassWalker::BfBaseClassWalker(BfTypeInstance* typeA, BfTypeInstance* typeB)
  97. {
  98. mTypes[0] = typeA;
  99. mTypes[1] = typeB;
  100. }*/
  101. BfBaseClassWalker::BfBaseClassWalker()
  102. {
  103. mMayBeFromInterface = false;
  104. mTypes[0] = NULL;
  105. mTypes[1] = NULL;
  106. }
  107. void BfBaseClassWalker::AddConstraints(BfType* srcType, BfGenericParamInstance* genericParam)
  108. {
  109. if (genericParam->mTypeConstraint != NULL)
  110. {
  111. auto typeInst = genericParam->mTypeConstraint->ToTypeInstance();
  112. {
  113. Entry entry(srcType, typeInst);
  114. if ((typeInst != NULL) && (!mManualList.Contains(entry)))
  115. mManualList.Add(entry);
  116. }
  117. }
  118. for (auto typeInst : genericParam->mInterfaceConstraints)
  119. {
  120. Entry entry(srcType, typeInst);
  121. if ((typeInst != NULL) && (!mManualList.Contains(entry)))
  122. mManualList.Add(entry);
  123. }
  124. }
  125. BfBaseClassWalker::Entry BfBaseClassWalker::Next()
  126. {
  127. if (!mManualList.IsEmpty())
  128. {
  129. auto entry = mManualList.back();
  130. mManualList.pop_back();
  131. return entry;
  132. }
  133. // Check the most specific type instance first (highest inheritance level)
  134. auto checkInstance = mTypes[0];
  135. if (mTypes[0] == NULL)
  136. checkInstance = mTypes[1];
  137. else if ((mTypes[1] != NULL) && (mTypes[1]->mInheritDepth > mTypes[0]->mInheritDepth))
  138. checkInstance = mTypes[1];
  139. if (checkInstance == NULL)
  140. return Entry();
  141. // Do it this was so if we reach the same base class for both types that we only handle each base type once
  142. if (checkInstance == mTypes[0])
  143. mTypes[0] = checkInstance->mBaseType;
  144. if (checkInstance == mTypes[1])
  145. mTypes[1] = checkInstance->mBaseType;
  146. Entry entry;
  147. entry.mSrcType = checkInstance;
  148. entry.mTypeInstance = checkInstance;
  149. return entry;
  150. }
  151. //////////////////////////////////////////////////////////////////////////
  152. BfMethodMatcher::BfMethodMatcher(BfAstNode* targetSrc, BfModule* module, const StringImpl& methodName, SizedArrayImpl<BfResolvedArg>& arguments, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments) :
  153. mArguments(arguments)
  154. {
  155. mTargetSrc = targetSrc;
  156. mModule = module;
  157. mMethodName = methodName;
  158. Init(/*arguments, */methodGenericArguments);
  159. }
  160. BfMethodMatcher::BfMethodMatcher(BfAstNode* targetSrc, BfModule* module, BfMethodInstance* interfaceMethodInstance, SizedArrayImpl<BfResolvedArg>& arguments, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments) :
  161. mArguments(arguments)
  162. {
  163. mTargetSrc = targetSrc;
  164. mModule = module;
  165. Init(/*arguments, */methodGenericArguments);
  166. mInterfaceMethodInstance = interfaceMethodInstance;
  167. mMethodName = mInterfaceMethodInstance->mMethodDef->mName;
  168. }
  169. void BfMethodMatcher::Init(/*SizedArrayImpl<BfResolvedArg>& arguments, */BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments)
  170. {
  171. //mArguments = arguments;
  172. mBestMethodDef = NULL;
  173. mBackupMethodDef = NULL;
  174. mBestMethodTypeInstance = NULL;
  175. mExplicitInterfaceCheck = NULL;
  176. mSelfType = NULL;
  177. mMethodType = BfMethodType_Normal;
  178. mHadExplicitGenericArguments = false;
  179. mHasVarArguments = false;
  180. mInterfaceMethodInstance = NULL;
  181. mFakeConcreteTarget = false;
  182. mBypassVirtual = false;
  183. mAllowStatic = true;
  184. mAllowNonStatic = true;
  185. mSkipImplicitParams = false;
  186. mAllowImplicitThis = false;
  187. mMethodCheckCount = 0;
  188. mInferGenericProgressIdx = 0;
  189. mCheckedKind = BfCheckedKind_NotSet;
  190. mMatchFailKind = MatchFailKind_None;
  191. for (auto& arg : mArguments)
  192. {
  193. auto bfType = arg.mTypedValue.mType;
  194. if (bfType != NULL)
  195. mHasVarArguments |= bfType->IsVar();
  196. }
  197. if (methodGenericArguments != NULL)
  198. {
  199. for (BfTypeReference* genericArg : *methodGenericArguments)
  200. {
  201. auto genericArgType = mModule->ResolveTypeRef(genericArg);
  202. // if (genericArgType == NULL)
  203. // return;
  204. mExplicitMethodGenericArguments.push_back(genericArgType);
  205. }
  206. mHadExplicitGenericArguments = true;
  207. }
  208. }
  209. bool BfMethodMatcher::InferGenericArgument(BfMethodInstance* methodInstance, BfType* argType, BfType* wantType, BfIRValue argValue)
  210. {
  211. if (argType == NULL)
  212. return false;
  213. if (wantType->IsGenericParam())
  214. {
  215. auto wantGenericParam = (BfGenericParamType*)wantType;
  216. BfType* methodGenericTypeConstraint = NULL;
  217. auto _SetGeneric = [&]()
  218. {
  219. if (mCheckMethodGenericArguments[wantGenericParam->mGenericParamIdx] != argType)
  220. {
  221. if (methodGenericTypeConstraint != NULL)
  222. {
  223. if (methodGenericTypeConstraint->IsGenericTypeInstance())
  224. {
  225. auto wantGenericType = (BfGenericTypeInstance*)methodGenericTypeConstraint;
  226. auto checkArgType = argType;
  227. while (checkArgType != NULL)
  228. {
  229. if (checkArgType->IsGenericTypeInstance())
  230. {
  231. auto argGenericType = (BfGenericTypeInstance*)checkArgType;
  232. if (argGenericType->mTypeDef == wantGenericType->mTypeDef)
  233. {
  234. for (int genericArgIdx = 0; genericArgIdx < (int)argGenericType->mTypeGenericArguments.size(); genericArgIdx++)
  235. InferGenericArgument(methodInstance, argGenericType->mTypeGenericArguments[genericArgIdx], wantGenericType->mTypeGenericArguments[genericArgIdx], BfIRValue());
  236. }
  237. }
  238. else if (checkArgType->IsSizedArray())
  239. {
  240. auto sizedArrayType = (BfSizedArrayType*)checkArgType;
  241. if (wantGenericType->mTypeDef == mModule->mCompiler->mSizedArrayTypeDef)
  242. {
  243. InferGenericArgument(methodInstance, sizedArrayType->mElementType, wantGenericType->mTypeGenericArguments[0], BfIRValue());
  244. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  245. BfTypedValue arraySize = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), intType);
  246. InferGenericArgument(methodInstance, mModule->CreateConstExprValueType(arraySize), wantGenericType->mTypeGenericArguments[1], BfIRValue());
  247. }
  248. }
  249. else if (checkArgType->IsPointer())
  250. {
  251. auto pointerType = (BfPointerType*)checkArgType;
  252. if (wantGenericType->mTypeDef == mModule->mCompiler->mPointerTTypeDef)
  253. {
  254. InferGenericArgument(methodInstance, pointerType->mElementType, wantGenericType->mTypeGenericArguments[0], BfIRValue());
  255. }
  256. }
  257. auto checkTypeInst = checkArgType->ToTypeInstance();
  258. if ((checkTypeInst == NULL) || (!checkTypeInst->mHasParameterizedBase))
  259. break;
  260. checkArgType = checkTypeInst->mBaseType;
  261. }
  262. }
  263. }
  264. mInferGenericProgressIdx++;
  265. mCheckMethodGenericArguments[wantGenericParam->mGenericParamIdx] = argType;
  266. }
  267. mCheckMethodGenericArguments[wantGenericParam->mGenericParamIdx] = argType;
  268. mPrevArgValues[wantGenericParam->mGenericParamIdx] = argValue;
  269. };
  270. if (wantGenericParam->mGenericParamKind == BfGenericParamKind_Method)
  271. {
  272. auto genericParamInst = methodInstance->mMethodInfoEx->mGenericParams[wantGenericParam->mGenericParamIdx];
  273. methodGenericTypeConstraint = genericParamInst->mTypeConstraint;
  274. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  275. {
  276. if (argValue.IsConst())
  277. {
  278. argType = mModule->CreateConstExprValueType(BfTypedValue(argValue, argType));
  279. }
  280. else if (!argType->IsConstExprValue())
  281. {
  282. return false;
  283. }
  284. }
  285. if (argType == mModule->mContext->mBfObjectType)
  286. {
  287. if ((genericParamInst->mTypeConstraint != NULL) && (genericParamInst->mTypeConstraint->IsDelegate()))
  288. {
  289. argType = genericParamInst->mTypeConstraint;
  290. }
  291. }
  292. auto prevGenericMethodArg = mCheckMethodGenericArguments[wantGenericParam->mGenericParamIdx];
  293. auto prevArgValue = mPrevArgValues[wantGenericParam->mGenericParamIdx];
  294. if (prevGenericMethodArg == NULL)
  295. {
  296. _SetGeneric();
  297. return true;
  298. }
  299. if ((prevGenericMethodArg->IsIntUnknown()) && (!argType->IsIntUnknown()))
  300. {
  301. // Old int fits into new argType, that's good
  302. if (mModule->CanImplicitlyCast(BfTypedValue(prevArgValue, prevGenericMethodArg), argType))
  303. {
  304. _SetGeneric();
  305. return true;
  306. }
  307. // Doesn't fit, upgrade type to 'int'
  308. argType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  309. if (mModule->CanImplicitlyCast(BfTypedValue(prevArgValue, prevGenericMethodArg), argType))
  310. {
  311. _SetGeneric();
  312. return true;
  313. }
  314. }
  315. if (argType->IsIntUnknown())
  316. {
  317. // New int fits into previous arg type, that's good
  318. if (mModule->CanImplicitlyCast(BfTypedValue(argValue, argType), prevGenericMethodArg))
  319. return true;
  320. // Doesn't fit, upgrade type to 'int'
  321. argType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  322. }
  323. else
  324. {
  325. // Prev is already best
  326. if (mModule->CanImplicitlyCast(mModule->GetFakeTypedValue(argType), prevGenericMethodArg))
  327. return true;
  328. }
  329. // New best?
  330. if (mModule->CanImplicitlyCast(mModule->GetFakeTypedValue(prevGenericMethodArg), argType))
  331. {
  332. _SetGeneric();
  333. return true;
  334. }
  335. // No implicit conversion, FAIL!
  336. mCheckMethodGenericArguments[wantGenericParam->mGenericParamIdx] = NULL;
  337. return false;
  338. }
  339. return true;
  340. }
  341. if (wantType->IsGenericTypeInstance())
  342. {
  343. auto wantGenericType = (BfGenericTypeInstance*)wantType;
  344. if (!argType->IsGenericTypeInstance())
  345. return true;
  346. auto argGenericType = (BfGenericTypeInstance*)argType;
  347. if (argGenericType->mTypeDef != wantGenericType->mTypeDef)
  348. return true;
  349. for (int genericArgIdx = 0; genericArgIdx < (int)argGenericType->mTypeGenericArguments.size(); genericArgIdx++)
  350. InferGenericArgument(methodInstance, argGenericType->mTypeGenericArguments[genericArgIdx], wantGenericType->mTypeGenericArguments[genericArgIdx], BfIRValue());
  351. return true;
  352. }
  353. if (wantType->IsRef())
  354. {
  355. auto wantRefType = (BfRefType*)wantType;
  356. if (!argType->IsRef())
  357. {
  358. // Match to non-ref
  359. InferGenericArgument(methodInstance, argType, wantRefType->mElementType, BfIRValue());
  360. return true;
  361. }
  362. auto argRefType = (BfRefType*)argType;
  363. //TODO: We removed this check so we still infer even if we have the wrong ref kind
  364. //if (wantRefType->mRefKind != argRefType->mRefKind)
  365. //return true;
  366. InferGenericArgument(methodInstance, argRefType->mElementType, wantRefType->mElementType, BfIRValue());
  367. return true;
  368. }
  369. if (wantType->IsPointer())
  370. {
  371. if (!argType->IsPointer())
  372. return true;
  373. auto wantPointerType = (BfPointerType*) wantType;
  374. auto argPointerType = (BfPointerType*) argType;
  375. InferGenericArgument(methodInstance, argPointerType->mElementType, wantPointerType->mElementType, BfIRValue());
  376. return true;
  377. }
  378. if (wantType->IsUnknownSizedArray())
  379. {
  380. auto wantArrayType = (BfUnknownSizedArrayType*)wantType;
  381. if (argType->IsUnknownSizedArray())
  382. {
  383. auto argArrayType = (BfUnknownSizedArrayType*)argType;
  384. InferGenericArgument(methodInstance, argArrayType->mElementCountSource, wantArrayType->mElementCountSource, BfIRValue());
  385. }
  386. else if (argType->IsSizedArray())
  387. {
  388. auto argArrayType = (BfSizedArrayType*)argType;
  389. BfTypedValue sizeValue(mModule->GetConstValue(argArrayType->mElementCount), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  390. auto sizedType = mModule->CreateConstExprValueType(sizeValue);
  391. InferGenericArgument(methodInstance, sizedType, wantArrayType->mElementCountSource, BfIRValue());
  392. }
  393. }
  394. if (wantType->IsSizedArray())
  395. {
  396. if (argType->IsSizedArray())
  397. {
  398. auto wantArrayType = (BfSizedArrayType*)wantType;
  399. auto argArrayType = (BfSizedArrayType*)argType;
  400. InferGenericArgument(methodInstance, argArrayType->mElementType, wantArrayType->mElementType, BfIRValue());
  401. }
  402. }
  403. return true;
  404. }
  405. void BfMethodMatcher::CompareMethods(BfMethodInstance* prevMethodInstance, BfTypeVector* prevGenericArgumentsSubstitute,
  406. BfMethodInstance* newMethodInstance, BfTypeVector* genericArgumentsSubstitute,
  407. bool* outNewIsBetter, bool* outNewIsWorse, bool allowSpecializeFail)
  408. {
  409. #define SET_BETTER_OR_WORSE(lhs, rhs) \
  410. if ((!isBetter) && (lhs) && !(rhs)) isBetter = true; \
  411. if ((!isWorse) && !(lhs) && (rhs)) isWorse = true;
  412. #define RETURN_BETTER_OR_WORSE(lhs, rhs) \
  413. if ((!isBetter) && (lhs) && !(rhs)) { *outNewIsBetter = true; *outNewIsWorse = false; return; } \
  414. if ((!isWorse) && !(lhs) && (rhs)) { *outNewIsBetter = false; *outNewIsWorse = true; return; };
  415. #define RETURN_RESULTS \
  416. *outNewIsBetter = isBetter; \
  417. *outNewIsWorse = isWorse; \
  418. return;
  419. int numUsedParams = 0;
  420. int prevNumUsedParams = 0;
  421. bool usedExtendedForm = false;
  422. bool prevUsedExtendedForm = false;
  423. bool isBetter = false;
  424. bool isWorse = false;
  425. int argIdx;
  426. BfMethodDef* prevMethodDef = prevMethodInstance->mMethodDef;
  427. BfMethodDef* newMethodDef = newMethodInstance->mMethodDef;
  428. if (newMethodDef->mExplicitInterface != prevMethodDef->mExplicitInterface)
  429. {
  430. if (mModule->CompareMethodSignatures(newMethodInstance, prevMethodInstance))
  431. {
  432. SET_BETTER_OR_WORSE(newMethodDef->mExplicitInterface != NULL, prevMethodDef->mExplicitInterface != NULL);
  433. *outNewIsBetter = isBetter;
  434. *outNewIsWorse = isWorse;
  435. return;
  436. }
  437. }
  438. int newImplicitParamCount = newMethodInstance->GetImplicitParamCount();
  439. if (newMethodInstance->mMethodDef->mHasAppend)
  440. newImplicitParamCount++;
  441. int prevImplicitParamCount = prevMethodInstance->GetImplicitParamCount();
  442. if (prevMethodInstance->mMethodDef->mHasAppend)
  443. prevImplicitParamCount++;
  444. bool hadEnoughArgs = newMethodInstance->GetParamCount() - newImplicitParamCount < (int)mArguments.size();
  445. bool prevHadEnoughArgs = prevMethodInstance->GetParamCount() - prevImplicitParamCount < (int)mArguments.size();
  446. RETURN_BETTER_OR_WORSE(hadEnoughArgs, prevHadEnoughArgs);
  447. bool chainSkip = (newMethodInstance->mChainType == BfMethodChainType_ChainMember) || (newMethodInstance->mChainType == BfMethodChainType_ChainSkip);
  448. bool prevChainSkip = (prevMethodInstance->mChainType == BfMethodChainType_ChainMember) || (prevMethodInstance->mChainType == BfMethodChainType_ChainSkip);
  449. RETURN_BETTER_OR_WORSE(!chainSkip, !prevChainSkip);
  450. // If one of these methods is local to the current extension then choose that one
  451. auto activeDef = mModule->GetActiveTypeDef();
  452. RETURN_BETTER_OR_WORSE(newMethodDef->mDeclaringType == activeDef, prevMethodDef->mDeclaringType == activeDef);
  453. RETURN_BETTER_OR_WORSE(newMethodDef->mDeclaringType->IsExtension(), prevMethodDef->mDeclaringType->IsExtension());
  454. if ((!isBetter) && (!isWorse))
  455. {
  456. bool betterByGenericParam = false;
  457. bool worseByGenericParam = false;
  458. for (argIdx = 0; argIdx < (int)mArguments.size(); argIdx++)
  459. {
  460. BfResolvedArg resolvedArg = mArguments[argIdx];;
  461. BfTypedValue arg = resolvedArg.mTypedValue;
  462. int newArgIdx = argIdx + newImplicitParamCount;
  463. int prevArgIdx = argIdx + prevImplicitParamCount;
  464. bool wasGenericParam = newMethodInstance->WasGenericParam(newArgIdx);
  465. bool prevWasGenericParam = prevMethodInstance->WasGenericParam(prevArgIdx);
  466. BfType* paramType = newMethodInstance->GetParamType(newArgIdx);
  467. BfType* prevParamType = prevMethodInstance->GetParamType(prevArgIdx);
  468. numUsedParams++;
  469. prevNumUsedParams++;
  470. BfType* origParamType = paramType;
  471. BfType* origPrevParamType = prevParamType;
  472. if ((genericArgumentsSubstitute != NULL) && (paramType->IsUnspecializedType()))
  473. paramType = mModule->ResolveGenericType(paramType, *genericArgumentsSubstitute, allowSpecializeFail);
  474. if ((prevGenericArgumentsSubstitute != NULL) && (prevParamType->IsUnspecializedType()))
  475. prevParamType = mModule->ResolveGenericType(prevParamType, *prevGenericArgumentsSubstitute, allowSpecializeFail);
  476. if ((wasGenericParam) || (prevWasGenericParam))
  477. {
  478. if ((wasGenericParam) && (!prevWasGenericParam))
  479. worseByGenericParam = true;
  480. else if ((!wasGenericParam) && (prevWasGenericParam))
  481. betterByGenericParam = true;
  482. }
  483. if ((prevParamType == NULL) || (paramType == NULL))
  484. {
  485. SET_BETTER_OR_WORSE(paramType != NULL, prevParamType != NULL);
  486. }
  487. else if (paramType != prevParamType)
  488. {
  489. bool isUnspecializedParam = paramType->IsUnspecializedType();
  490. bool isPrevUnspecializedParam = prevParamType->IsUnspecializedType();
  491. SET_BETTER_OR_WORSE((!isUnspecializedParam) && (!paramType->IsVar()),
  492. (!isPrevUnspecializedParam) && (!prevParamType->IsVar()));
  493. if ((!isBetter) && (!isWorse))
  494. SET_BETTER_OR_WORSE(paramType->IsConstExprValue(), prevParamType->IsConstExprValue());
  495. if ((!isBetter) && (!isWorse) && (!isUnspecializedParam) && (!isPrevUnspecializedParam))
  496. {
  497. SET_BETTER_OR_WORSE((paramType != NULL) && (!paramType->IsUnspecializedType()),
  498. (prevParamType != NULL) && (!prevParamType->IsUnspecializedType()));
  499. if ((!isBetter) && (!isWorse))
  500. {
  501. // The resolved argument type may actually match for both considered functions. IE:
  502. // Method(int8 val) and Method(int16 val) called with Method(0) will create arguments that match their param types
  503. if ((paramType == arg.mType) && (prevParamType != resolvedArg.mBestBoundType))
  504. isBetter = true;
  505. else if ((prevParamType == arg.mType) && (paramType != arg.mType))
  506. isWorse = true;
  507. else
  508. {
  509. bool canCastFromCurToPrev = mModule->CanImplicitlyCast(mModule->GetFakeTypedValue(paramType), prevParamType);
  510. bool canCastFromPrevToCur = mModule->CanImplicitlyCast(mModule->GetFakeTypedValue(prevParamType), paramType);
  511. if ((canCastFromCurToPrev) && (!canCastFromPrevToCur))
  512. isBetter = true;
  513. else if ((canCastFromPrevToCur) && (!canCastFromCurToPrev))
  514. isWorse = true;
  515. else if ((paramType->IsIntegral()) && (prevParamType->IsIntegral()))
  516. {
  517. if (paramType == arg.mType)
  518. isBetter = true;
  519. else if (prevParamType == arg.mType)
  520. isWorse = true;
  521. else
  522. {
  523. if (paramType->mSize < prevParamType->mSize)
  524. isBetter = true;
  525. else if (paramType->mSize > prevParamType->mSize)
  526. isWorse = true;
  527. else if (paramType->IsSigned())
  528. isBetter = true;
  529. else
  530. isWorse = true;
  531. }
  532. }
  533. }
  534. /*if ((paramType->IsIntegral()) && (prevParamType->IsIntegral()))
  535. {
  536. if (paramType == arg.mType)
  537. isBetter = true;
  538. else if (prevParamType == arg.mType)
  539. isWorse = true;
  540. else
  541. {
  542. if (paramType->mSize < prevParamType->mSize)
  543. isBetter = true;
  544. else if (paramType->mSize > prevParamType->mSize)
  545. isWorse = true;
  546. else if (paramType->IsSigned())
  547. isBetter = true;
  548. else
  549. isWorse = true;
  550. }
  551. }
  552. else
  553. {
  554. if (mModule->CanImplicitlyCast(mModule->GetFakeTypedValue(paramType), prevParamType))
  555. isBetter = true;
  556. if (mModule->CanImplicitlyCast(mModule->GetFakeTypedValue(prevParamType), paramType))
  557. isWorse = true;
  558. }*/
  559. }
  560. }
  561. }
  562. else if ((wasGenericParam) || (prevWasGenericParam))
  563. {
  564. if (!wasGenericParam)
  565. isBetter = true;
  566. else if (!prevWasGenericParam)
  567. isWorse = true;
  568. }
  569. if (newMethodInstance->GetParamKind(newArgIdx) == BfParamKind_Params)
  570. usedExtendedForm = true;
  571. if (prevMethodInstance->GetParamKind(prevArgIdx) == BfParamKind_Params)
  572. prevUsedExtendedForm = true;
  573. if ((usedExtendedForm) || (prevUsedExtendedForm))
  574. break;
  575. }
  576. if ((!isBetter) && (!isWorse))
  577. {
  578. isBetter = betterByGenericParam;
  579. isWorse = worseByGenericParam;
  580. }
  581. if ((isBetter) || (isWorse))
  582. {
  583. RETURN_RESULTS;
  584. }
  585. }
  586. // Check for unused extended params as next param - that still counts as using extended form
  587. usedExtendedForm = newMethodInstance->HasParamsArray();
  588. prevUsedExtendedForm = prevMethodInstance->HasParamsArray();
  589. // Non-generic is better than generic.
  590. // The only instance where we can disambiguate is when we have the same number of generic arguments, and the
  591. // constraints for one method's generic argument is a superset of another's. More specific is better.
  592. //TODO: WE changed this to compare the constraints of the ARGUMENTS
  593. // if (newMethodInstance->GetNumGenericArguments() == prevMethodInstance->GetNumGenericArguments())
  594. // {
  595. // if (newMethodInstance->GetNumGenericArguments() != 0)
  596. // {
  597. // for (int genericIdx = 0; genericIdx < (int)newMethodInstance->mMethodInfoEx->mMethodGenericArguments.size(); genericIdx++)
  598. // {
  599. // auto newMethodGenericParam = newMethodInstance->mMethodInfoEx->mGenericParams[genericIdx];
  600. // auto prevMethodGenericParam = prevMethodInstance->mMethodInfoEx->mGenericParams[genericIdx];
  601. // RETURN_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  602. // }
  603. // }
  604. // }
  605. // else
  606. RETURN_BETTER_OR_WORSE(newMethodInstance->GetNumGenericArguments() == 0, prevMethodInstance->GetNumGenericArguments() == 0);
  607. // Not using generic delegate params is better
  608. RETURN_BETTER_OR_WORSE(!newMethodInstance->mHadGenericDelegateParams, !prevMethodInstance->mHadGenericDelegateParams);
  609. // Normal form trumps extended form
  610. RETURN_BETTER_OR_WORSE(!usedExtendedForm, !prevUsedExtendedForm);
  611. // More used params trumps less params
  612. int paramDiff = (int) numUsedParams - (int) prevNumUsedParams;
  613. RETURN_BETTER_OR_WORSE(paramDiff > 0, paramDiff < 0);
  614. // Fewer defaults trumps more defaults
  615. // Since we know the number of used params is the same (previous check), we infer that the rest are defaults
  616. paramDiff = (int) newMethodInstance->GetParamCount() - (int) prevMethodInstance->GetParamCount();
  617. RETURN_BETTER_OR_WORSE(paramDiff < 0, paramDiff > 0);
  618. // Check specificity of args
  619. std::function<void(BfType*, BfType*)> _CompareParamTypes = [&](BfType* newType, BfType* prevType)
  620. {
  621. if ((newType->IsGenericParam()) && (prevType->IsGenericParam()))
  622. {
  623. auto newGenericParamType = (BfGenericParamType*)newType;
  624. auto prevGenericParamType = (BfGenericParamType*)prevType;
  625. if ((newGenericParamType->mGenericParamKind == BfGenericParamKind_Method) && (prevGenericParamType->mGenericParamKind == BfGenericParamKind_Method))
  626. {
  627. auto newMethodGenericParam = newMethodInstance->mMethodInfoEx->mGenericParams[newGenericParamType->mGenericParamIdx];
  628. auto prevMethodGenericParam = prevMethodInstance->mMethodInfoEx->mGenericParams[prevGenericParamType->mGenericParamIdx];
  629. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  630. }
  631. }
  632. else if (newType == prevType)
  633. {
  634. if ((newType->IsUnspecializedType()) && (newType->IsGenericTypeInstance()))
  635. {
  636. BfGenericTypeInstance* newGenericType = (BfGenericTypeInstance*)newType;
  637. BfGenericTypeInstance* prevGenericType = (BfGenericTypeInstance*)prevType;
  638. for (int genericArgIdx = 0; genericArgIdx < (int)newGenericType->mTypeGenericArguments.size(); genericArgIdx++)
  639. {
  640. _CompareParamTypes(newGenericType->mTypeGenericArguments[genericArgIdx], prevGenericType->mTypeGenericArguments[genericArgIdx]);
  641. }
  642. }
  643. }
  644. else
  645. {
  646. //TODO: Why did we need this?
  647. //isBetter |= mModule->IsTypeMoreSpecific(newType, prevType);
  648. //isWorse |= mModule->IsTypeMoreSpecific(prevType, newType);
  649. }
  650. };
  651. int paramCheckCount = (int)BF_MIN(newMethodInstance->GetParamCount() - newImplicitParamCount, prevMethodInstance->GetParamCount() - prevImplicitParamCount);
  652. for (argIdx = 0; argIdx < (int)paramCheckCount/*mArguments.size()*/; argIdx++)
  653. {
  654. int newArgIdx = argIdx + newImplicitParamCount;
  655. int prevArgIdx = argIdx + prevImplicitParamCount;
  656. _CompareParamTypes(newMethodInstance->GetParamType(newArgIdx), prevMethodInstance->GetParamType(prevArgIdx));
  657. }
  658. // Do generic constraint subset test directly to handle cases like "NotDisposed<T>()" vs "NOtDisposed<T>() where T : IDisposable"
  659. if ((newMethodInstance->GetNumGenericArguments() > 0) && (newMethodInstance->GetNumGenericArguments() == prevMethodInstance->GetNumGenericArguments()))
  660. {
  661. for (int genericParamIdx = 0; genericParamIdx < (int)newMethodInstance->GetNumGenericArguments(); genericParamIdx++)
  662. {
  663. auto newMethodGenericParam = newMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  664. auto prevMethodGenericParam = prevMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  665. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  666. }
  667. }
  668. if ((isBetter) || (isWorse))
  669. {
  670. RETURN_RESULTS;
  671. }
  672. // Does one have a body and one doesn't? Obvious!
  673. isBetter = prevMethodDef->IsEmptyPartial();
  674. isWorse = newMethodDef->IsEmptyPartial();
  675. if ((isBetter) && (isWorse))
  676. {
  677. // If both are empty partials then just bind to either
  678. isWorse = true;
  679. RETURN_RESULTS;
  680. }
  681. // For operators, prefer explicit comparison over '<=>' comparison operator
  682. if ((!isBetter) && (!isWorse))
  683. {
  684. if ((prevMethodDef->mIsOperator) && (newMethodDef->mIsOperator))
  685. {
  686. bool newIsComparison = ((BfOperatorDeclaration*)newMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  687. bool prevIsComparison = ((BfOperatorDeclaration*)prevMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  688. RETURN_BETTER_OR_WORSE(!newIsComparison, !prevIsComparison);
  689. }
  690. }
  691. // For extensions, select the version in the most-specific project (only applicable for ctors)
  692. if ((!isBetter) && (!isWorse))
  693. {
  694. auto newProject = newMethodDef->mDeclaringType->mProject;
  695. auto prevProject = prevMethodDef->mDeclaringType->mProject;
  696. if (newProject != prevProject)
  697. {
  698. RETURN_BETTER_OR_WORSE(newProject->ContainsReference(prevProject), prevProject->ContainsReference(newProject));
  699. }
  700. }
  701. // If we have conditional type extensions that both define an implementation for a method, use the most-specific conditional extension constraints
  702. auto owner = newMethodInstance->GetOwner();
  703. if ((newMethodDef->mDeclaringType != prevMethodDef->mDeclaringType) && (owner->IsGenericTypeInstance()))
  704. {
  705. auto genericOwner = (BfGenericTypeInstance*)owner;
  706. if (genericOwner->mGenericExtensionInfo != NULL)
  707. {
  708. BfGenericExtensionEntry* newGenericExtesionEntry = NULL;
  709. BfGenericExtensionEntry* prevGenericExtesionEntry = NULL;
  710. if ((genericOwner->mGenericExtensionInfo->mExtensionMap.TryGetValue(newMethodDef->mDeclaringType, &newGenericExtesionEntry)) &&
  711. (genericOwner->mGenericExtensionInfo->mExtensionMap.TryGetValue(prevMethodDef->mDeclaringType, &prevGenericExtesionEntry)))
  712. {
  713. if ((newGenericExtesionEntry->mGenericParams.size() == prevGenericExtesionEntry->mGenericParams.size()))
  714. {
  715. for (int genericParamIdx = 0; genericParamIdx < (int)newGenericExtesionEntry->mGenericParams.size(); genericParamIdx++)
  716. {
  717. auto newMethodGenericParam = newGenericExtesionEntry->mGenericParams[genericParamIdx];
  718. auto prevMethodGenericParam = prevGenericExtesionEntry->mGenericParams[genericParamIdx];
  719. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  720. }
  721. }
  722. if ((isBetter) || (isWorse))
  723. {
  724. RETURN_RESULTS;
  725. }
  726. }
  727. }
  728. }
  729. RETURN_BETTER_OR_WORSE(newMethodDef->mCheckedKind == mCheckedKind, prevMethodDef->mCheckedKind == mCheckedKind);
  730. RETURN_RESULTS;
  731. }
  732. BfTypedValue BfMethodMatcher::ResolveArgTypedValue(BfResolvedArg& resolvedArg, BfType* checkType)
  733. {
  734. BfTypedValue argTypedValue = resolvedArg.mTypedValue;
  735. if ((resolvedArg.mArgFlags & BfArgFlag_DelegateBindAttempt) != 0)
  736. {
  737. //TODO: See if we can bind it to a delegate type
  738. BfExprEvaluator exprEvaluator(mModule);
  739. exprEvaluator.mExpectingType = checkType;
  740. BF_ASSERT(resolvedArg.mExpression->IsA<BfDelegateBindExpression>());
  741. auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(resolvedArg.mExpression);
  742. BfMethodInstance* boundMethodInstance = NULL;
  743. if (exprEvaluator.CanBindDelegate(delegateBindExpr, &boundMethodInstance))
  744. {
  745. if (delegateBindExpr->mNewToken == NULL)
  746. {
  747. resolvedArg.mExpectedType = checkType;
  748. auto methodRefType = mModule->CreateMethodRefType(boundMethodInstance);
  749. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  750. mModule->AddCallDependency(boundMethodInstance);
  751. argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodRefType);
  752. }
  753. else
  754. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  755. //argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), checkType);
  756. }
  757. }
  758. else if ((resolvedArg.mArgFlags & BfArgFlag_LambdaBindAttempt) != 0)
  759. {
  760. BfExprEvaluator exprEvaluator(mModule);
  761. exprEvaluator.mExpectingType = checkType;
  762. BF_ASSERT(resolvedArg.mExpression->IsA<BfLambdaBindExpression>());
  763. auto lambdaBindExpr = (BfLambdaBindExpression*)resolvedArg.mExpression;
  764. if ((checkType != NULL) && (checkType->IsDelegate()))
  765. {
  766. BfMethodInstance* methodInstance = mModule->GetRawMethodInstanceAtIdx(checkType->ToTypeInstance(), 0, "Invoke");
  767. if (methodInstance != NULL)
  768. {
  769. if (methodInstance->GetParamCount() == (int)lambdaBindExpr->mParams.size())
  770. {
  771. if (lambdaBindExpr->mNewToken == NULL)
  772. {
  773. if (!resolvedArg.mTypedValue)
  774. {
  775. // Resolve for real
  776. resolvedArg.mTypedValue = mModule->CreateValueFromExpression(lambdaBindExpr, checkType, BfEvalExprFlags_NoCast);
  777. }
  778. argTypedValue = resolvedArg.mTypedValue;
  779. }
  780. else
  781. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  782. //argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), checkType);
  783. }
  784. }
  785. }
  786. }
  787. else if ((resolvedArg.mArgFlags & BfArgFlag_UnqualifiedDotAttempt) != 0)
  788. {
  789. if ((checkType != NULL) && (checkType->IsPayloadEnum()))
  790. {
  791. // Should we actually check the member name?
  792. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  793. }
  794. }
  795. else if ((resolvedArg.mArgFlags & BfArgFlag_UntypedDefault) != 0)
  796. {
  797. if (checkType != NULL)
  798. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  799. }
  800. else if ((resolvedArg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  801. {
  802. if (resolvedArg.mExpression != NULL)
  803. {
  804. if ((resolvedArg.mExpectedType != checkType) || (resolvedArg.mExpectedType == NULL)) // Did our last check match for this type?
  805. {
  806. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  807. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  808. //SetAndRestoreValue<bool> prevNoBind(mModule->mCurMethodState->mNoBind, true);
  809. bool prevNoBind = false;
  810. if (mModule->mCurMethodState != NULL)
  811. {
  812. prevNoBind = mModule->mCurMethodState->mNoBind;
  813. mModule->mCurMethodState->mNoBind = true;
  814. }
  815. auto prevBlock = mModule->mBfIRBuilder->GetInsertBlock();
  816. BfExprEvaluator exprEvaluator(mModule);
  817. exprEvaluator.mExpectingType = checkType;
  818. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowIntUnknown);
  819. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) != 0)
  820. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  821. exprEvaluator.Evaluate(resolvedArg.mExpression);
  822. argTypedValue = exprEvaluator.GetResult();
  823. if (mModule->mCurMethodState != NULL)
  824. mModule->mCurMethodState->mNoBind = prevNoBind;
  825. if (argTypedValue)
  826. {
  827. if (checkType != NULL)
  828. resolvedArg.mExpectedType = checkType;
  829. auto storeTypedValue = argTypedValue;
  830. if ((storeTypedValue.mValue) & (!storeTypedValue.mValue.IsFake()))
  831. {
  832. // We actually want to ensure that this cached value is a fake val. There are potential cases where a fake val
  833. // won't be generated but we should throw an error, so we need to make sure we actually re-evaluate when the call
  834. // is generated
  835. //storeTypedValue.mValue = mModule->mBfIRBuilder->GetFakeVal();
  836. resolvedArg.mWantsRecalc = true;
  837. }
  838. resolvedArg.mTypedValue = storeTypedValue;
  839. //BF_ASSERT(argTypedValue.mValue.mId != -1);
  840. }
  841. mModule->mBfIRBuilder->SetInsertPoint(prevBlock);
  842. }
  843. }
  844. }
  845. else if ((resolvedArg.mArgFlags & BfArgFlag_VariableDeclaration) != 0)
  846. {
  847. if ((checkType != NULL) && (checkType->IsRef()))
  848. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  849. }
  850. return argTypedValue;
  851. }
  852. bool BfMethodMatcher::WantsCheckMethod(BfProtectionCheckFlags& flags, BfTypeInstance* startTypeInstance, BfTypeInstance* checkTypeInstance, BfMethodDef* checkMethod)
  853. {
  854. MatchFailKind matchFailKind = MatchFailKind_None;
  855. if (!mModule->CheckProtection(flags, checkTypeInstance, checkMethod->mProtection, startTypeInstance))
  856. {
  857. if ((mBypassVirtual) && (checkMethod->mProtection == BfProtection_Protected) && (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, startTypeInstance)))
  858. {
  859. // Allow explicit 'base' call
  860. }
  861. else
  862. {
  863. return false;
  864. }
  865. }
  866. if (mCheckedKind != checkMethod->mCheckedKind)
  867. {
  868. bool passes = true;
  869. if (mCheckedKind != BfCheckedKind_NotSet)
  870. {
  871. passes = false;
  872. }
  873. else
  874. {
  875. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  876. if (defaultCheckedKind != checkMethod->mCheckedKind)
  877. passes = false;
  878. }
  879. if (!passes)
  880. {
  881. return false;
  882. }
  883. }
  884. return true;
  885. }
  886. bool BfMethodMatcher::CheckMethod(BfTypeInstance* typeInstance, BfMethodDef* checkMethod, bool isFailurePass)
  887. {
  888. bool hadMatch = false;
  889. // Never consider overrides - they only get found at original method declaration
  890. // mBypassVirtual gets set when we are doing an explicit "base" call, or when we are a struct --
  891. // because on structs we know the exact type
  892. if ((checkMethod->mIsOverride) && (!mBypassVirtual) && (!typeInstance->IsValueType()))
  893. return false;
  894. mMethodCheckCount++;
  895. BfMethodInstance* methodInstance = mModule->GetRawMethodInstance(typeInstance, checkMethod);
  896. if ((mInterfaceMethodInstance != NULL) && (methodInstance->GetExplicitInterface() != NULL))
  897. {
  898. BfTypeInstance* wantInterface = mInterfaceMethodInstance->mMethodInstanceGroup->mOwner;
  899. if (wantInterface != methodInstance->GetExplicitInterface())
  900. return false;
  901. }
  902. HashSet<int> allowEmptyGenericSet;
  903. BfAutoComplete* autoComplete = NULL;
  904. if ((mModule->mCompiler->mResolvePassData != NULL) && (!isFailurePass))
  905. autoComplete = mModule->mCompiler->mResolvePassData->mAutoComplete;
  906. if (((checkMethod->mIsStatic) && (!mAllowStatic)) ||
  907. ((!checkMethod->mIsStatic) && (!mAllowNonStatic)))
  908. {
  909. if (!typeInstance->IsFunction())
  910. autoComplete = NULL;
  911. }
  912. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  913. {
  914. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  915. methodMatchEntry.mMethodDef = checkMethod;
  916. methodMatchEntry.mTypeInstance = typeInstance;
  917. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  918. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  919. }
  920. BfTypeVector* genericArgumentsSubstitute = NULL;
  921. int argIdx = 0;
  922. bool needInferGenericParams = (checkMethod->mGenericParams.size() != 0) && (!mHadExplicitGenericArguments);
  923. int paramIdx = 0;
  924. BfType* paramsElementType = NULL;
  925. if (checkMethod->mHasAppend)
  926. paramIdx++;
  927. // int outmostGenericCount = 0;
  928. // if (checkMethod->mIsLocalMethod)
  929. // outmostGenericCount = (int)mModule->mCurMethodState->GetRootMethodState()->mMethodInstance->mGenericParams.size();
  930. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(checkMethod);
  931. if ((mHadExplicitGenericArguments) && (checkMethod->mGenericParams.size() != mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx))
  932. goto NoMatch;
  933. for (auto& checkGenericArgRef : mCheckMethodGenericArguments)
  934. checkGenericArgRef = NULL;
  935. mCheckMethodGenericArguments.resize(checkMethod->mGenericParams.size());
  936. mPrevArgValues.resize(checkMethod->mGenericParams.size());
  937. for (auto& genericArgRef : mCheckMethodGenericArguments)
  938. genericArgRef = NULL;
  939. if (mHadExplicitGenericArguments)
  940. {
  941. if (uniqueGenericStartIdx > 0)
  942. {
  943. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  944. mCheckMethodGenericArguments.clear();
  945. mCheckMethodGenericArguments.reserve(mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx);
  946. for (int i = 0; i < uniqueGenericStartIdx; i++)
  947. mCheckMethodGenericArguments.Add(NULL);
  948. for (int i = 0; i < (int)mExplicitMethodGenericArguments.size(); i++)
  949. mCheckMethodGenericArguments.Add(mExplicitMethodGenericArguments[i]);
  950. }
  951. else
  952. {
  953. genericArgumentsSubstitute = &mExplicitMethodGenericArguments;
  954. }
  955. }
  956. else if (needInferGenericParams)
  957. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  958. if (mSkipImplicitParams)
  959. {
  960. //paramOfs = methodInstance->GetImplicitParamCount();
  961. //paramIdx += paramOfs;
  962. }
  963. if (needInferGenericParams)
  964. {
  965. int paramOfs = methodInstance->GetImplicitParamCount();
  966. int paramCount = methodInstance->GetParamCount();
  967. if (checkMethod->mHasAppend)
  968. paramOfs++;
  969. for (int argIdx = 0; argIdx < (int)mArguments.size(); argIdx++)
  970. {
  971. if (argIdx >= (int)checkMethod->mParams.size())
  972. break;
  973. int paramIdx = argIdx + paramOfs;
  974. if (paramIdx >= paramCount)
  975. break; // Possible for delegate 'params' type methods
  976. auto wantType = methodInstance->GetParamType(argIdx + paramOfs);
  977. auto checkType = wantType;
  978. auto origCheckType = checkType;
  979. if (checkType->IsGenericParam())
  980. {
  981. BfGenericParamInstance* genericParamInstance = NULL;
  982. auto genericParamType = (BfGenericParamType*)checkType;
  983. checkType = NULL;
  984. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  985. {
  986. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  987. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  988. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  989. }
  990. else
  991. genericParamInstance = mModule->GetGenericParamInstance(genericParamType);
  992. if (checkType == NULL)
  993. checkType = genericParamInstance->mTypeConstraint;
  994. }
  995. if ((checkType != NULL) && (genericArgumentsSubstitute != NULL) && (checkType->IsUnspecializedTypeVariation()))
  996. {
  997. checkType = mModule->ResolveGenericType(origCheckType, *genericArgumentsSubstitute);
  998. }
  999. if (wantType->IsUnspecializedType())
  1000. {
  1001. BfTypedValue argTypedValue = ResolveArgTypedValue(mArguments[argIdx], checkType);
  1002. if (!argTypedValue.IsUntypedValue())
  1003. {
  1004. auto type = argTypedValue.mType;
  1005. if ((!argTypedValue) || (!InferGenericArgument(methodInstance, type, wantType, argTypedValue.mValue)))
  1006. goto NoMatch;
  1007. }
  1008. }
  1009. }
  1010. //
  1011. {
  1012. int paramIdx = (int)mArguments.size() + paramOfs;
  1013. while (paramIdx < checkMethod->mParams.size())
  1014. {
  1015. if ((paramIdx < methodInstance->mDefaultValues.size()) && (methodInstance->mDefaultValues[paramIdx]))
  1016. {
  1017. auto wantType = methodInstance->GetParamType(paramIdx);
  1018. auto checkType = wantType;
  1019. if (checkType->IsGenericParam())
  1020. {
  1021. BfGenericParamInstance* genericParamInstance = NULL;
  1022. auto genericParamType = (BfGenericParamType*)checkType;
  1023. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1024. {
  1025. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  1026. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  1027. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1028. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  1029. {
  1030. if (mCheckMethodGenericArguments[genericParamType->mGenericParamIdx] == NULL)
  1031. allowEmptyGenericSet.Add(genericParamType->mGenericParamIdx);
  1032. }
  1033. }
  1034. }
  1035. }
  1036. paramIdx++;
  1037. }
  1038. }
  1039. //
  1040. for (int genericArgIdx = uniqueGenericStartIdx; genericArgIdx < (int)checkMethod->mGenericParams.size(); genericArgIdx++)
  1041. {
  1042. auto& genericArg = mCheckMethodGenericArguments[genericArgIdx];
  1043. if (genericArg == NULL)
  1044. {
  1045. if (!allowEmptyGenericSet.Contains(genericArgIdx))
  1046. goto NoMatch;
  1047. }
  1048. }
  1049. }
  1050. // Iterate through params
  1051. while (true)
  1052. {
  1053. // Too many arguments
  1054. if (paramIdx >= (int)methodInstance->GetParamCount())
  1055. {
  1056. break;
  1057. }
  1058. bool isDeferredEval = false;
  1059. if ((methodInstance->GetParamKind(paramIdx) == BfParamKind_Params) && (paramsElementType == NULL))
  1060. {
  1061. if (paramIdx >= (int) mArguments.size())
  1062. break; // No params
  1063. BfTypedValue argTypedValue = ResolveArgTypedValue(mArguments[argIdx], NULL);
  1064. if (!argTypedValue)
  1065. goto NoMatch;
  1066. if ((!argTypedValue.HasType()) && (!mArguments[argIdx].IsDeferredEval()))
  1067. goto NoMatch;
  1068. auto paramsArrayType = methodInstance->GetParamType(paramIdx);
  1069. if ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1070. {
  1071. // Direct-pass params
  1072. if ((argTypedValue.IsUntypedValue()) || (mModule->CanImplicitlyCast(argTypedValue, paramsArrayType)))
  1073. {
  1074. argIdx++;
  1075. paramIdx++;
  1076. break;
  1077. }
  1078. goto NoMatch;
  1079. }
  1080. if (paramsArrayType->IsArray())
  1081. {
  1082. auto arrayType = (BfArrayType*)paramsArrayType;
  1083. paramsElementType = arrayType->mTypeGenericArguments[0];
  1084. while (argIdx < (int)mArguments.size())
  1085. {
  1086. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], paramsElementType);
  1087. if (!argTypedValue.HasType())
  1088. goto NoMatch;
  1089. if (!mModule->CanImplicitlyCast(argTypedValue, paramsElementType))
  1090. goto NoMatch;
  1091. argIdx++;
  1092. }
  1093. }
  1094. else
  1095. goto NoMatch;
  1096. break;
  1097. }
  1098. if (methodInstance->IsImplicitCapture(paramIdx))
  1099. {
  1100. paramIdx++;
  1101. continue;
  1102. }
  1103. if (argIdx >= (int) mArguments.size())
  1104. {
  1105. // We have defaults the rest of the way, so that's cool
  1106. if (methodInstance->GetParamInitializer(paramIdx) != NULL)
  1107. break;
  1108. // We have unused params left over
  1109. goto NoMatch;
  1110. }
  1111. auto wantType = methodInstance->GetParamType(paramIdx);
  1112. if ((genericArgumentsSubstitute != NULL) && (wantType->IsUnspecializedType()))
  1113. {
  1114. auto resolvedType = mModule->ResolveGenericType(wantType, *genericArgumentsSubstitute);
  1115. if (resolvedType == NULL)
  1116. goto NoMatch;
  1117. wantType = resolvedType;
  1118. }
  1119. if (wantType->IsSelf())
  1120. wantType = typeInstance;
  1121. if ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1122. {
  1123. // We had a 'params' expression but this method didn't have a params slot in this parameter
  1124. goto NoMatch;
  1125. }
  1126. BfTypedValue argTypedValue = ResolveArgTypedValue(mArguments[argIdx], wantType);
  1127. if (!argTypedValue.IsUntypedValue())
  1128. {
  1129. if (!argTypedValue.HasType())
  1130. {
  1131. goto NoMatch;
  1132. }
  1133. else if (!mModule->CanImplicitlyCast(argTypedValue, wantType))
  1134. goto NoMatch;
  1135. }
  1136. paramIdx++;
  1137. argIdx++;
  1138. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1139. {
  1140. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1141. if (!methodMatchInfo->mHadExactMatch)
  1142. {
  1143. bool isBetter = false;
  1144. bool isWorse = false;
  1145. int methodIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  1146. if ((methodMatchInfo->mBestIdx != -1) && (methodMatchInfo->mBestIdx < (int)methodMatchInfo->mInstanceList.size()))
  1147. {
  1148. auto prevMethodMatchEntry = &methodMatchInfo->mInstanceList[methodMatchInfo->mBestIdx];
  1149. if (checkMethod->mParams.size() < mArguments.size())
  1150. {
  1151. isWorse = true;
  1152. }
  1153. else if ((prevMethodMatchEntry->mMethodDef != NULL) && (prevMethodMatchEntry->mMethodDef->mParams.size() < (int) mArguments.size()))
  1154. {
  1155. isBetter = true;
  1156. }
  1157. }
  1158. }
  1159. }
  1160. }
  1161. //TODO: Does this ever get hit?
  1162. // Not enough arguments?
  1163. if (argIdx < (int)mArguments.size())
  1164. {
  1165. goto NoMatch;
  1166. }
  1167. if ((genericArgumentsSubstitute != NULL) && (genericArgumentsSubstitute->size() != 0))
  1168. {
  1169. for (int checkGenericIdx = uniqueGenericStartIdx; checkGenericIdx < (int)genericArgumentsSubstitute->size(); checkGenericIdx++)
  1170. {
  1171. auto& genericParams = methodInstance->mMethodInfoEx->mGenericParams;
  1172. auto genericArg = (*genericArgumentsSubstitute)[checkGenericIdx];
  1173. if (genericArg == NULL)
  1174. {
  1175. if (allowEmptyGenericSet.Contains(checkGenericIdx))
  1176. continue;
  1177. goto NoMatch;
  1178. }
  1179. if (genericArg->IsPrimitiveType())
  1180. {
  1181. auto primType = (BfPrimitiveType*) genericArg;
  1182. genericArg = mModule->GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  1183. }
  1184. //SetAndRestoreValue<bool> ignoreError(mModule->mIgnoreErrors, true);
  1185. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericArg, NULL, genericParams[checkGenericIdx], genericArgumentsSubstitute, NULL))
  1186. {
  1187. goto NoMatch;
  1188. }
  1189. }
  1190. }
  1191. // Method is applicable, check to see which method is better
  1192. if (mBestMethodDef != NULL)
  1193. {
  1194. bool isBetter = false;
  1195. bool isWorse = false;
  1196. BfMethodInstance* prevMethodInstance = mModule->GetRawMethodInstance(mBestMethodTypeInstance, mBestMethodDef);
  1197. bool allowSpecializeFail = mModule->mCurTypeInstance->IsUnspecializedType();
  1198. if (mModule->mCurMethodInstance != NULL)
  1199. allowSpecializeFail = mModule->mCurMethodInstance->mIsUnspecialized;
  1200. CompareMethods(prevMethodInstance, &mBestMethodGenericArguments, methodInstance, genericArgumentsSubstitute, &isBetter, &isWorse, allowSpecializeFail);
  1201. // If we had both a 'better' and 'worse', that's ambiguous because the methods are each better in different ways (not allowed)
  1202. // And if neither better nor worse then they are equally good, which is not allowed either
  1203. if (((!isBetter) && (!isWorse)) || ((isBetter) && (isWorse)))
  1204. {
  1205. if (!mHasVarArguments)
  1206. {
  1207. BfAmbiguousEntry ambiguousEntry;
  1208. ambiguousEntry.mMethodInstance = methodInstance;
  1209. if (genericArgumentsSubstitute != NULL)
  1210. ambiguousEntry.mBestMethodGenericArguments = *genericArgumentsSubstitute;
  1211. if (methodInstance->GetNumGenericParams() != 0)
  1212. {
  1213. BF_ASSERT(!ambiguousEntry.mBestMethodGenericArguments.empty());
  1214. }
  1215. mAmbiguousEntries.push_back(ambiguousEntry);
  1216. }
  1217. }
  1218. if (!isBetter)
  1219. goto Done;
  1220. }
  1221. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1222. {
  1223. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1224. // Try to persist with previous partial match, if we have one - this keeps us from locking onto
  1225. // an incorrect method just because it had the current number of params that we've typed so far
  1226. if (methodMatchInfo->mPrevBestIdx == -1)
  1227. {
  1228. methodMatchInfo->mHadExactMatch = true;
  1229. methodMatchInfo->mBestIdx = (int) methodMatchInfo->mInstanceList.size() - 1;
  1230. }
  1231. }
  1232. mAmbiguousEntries.Clear();
  1233. hadMatch = true;
  1234. mBestMethodDef = checkMethod;
  1235. for (auto& arg : mArguments)
  1236. arg.mBestBoundType = arg.mTypedValue.mType;
  1237. NoMatch:
  1238. if (!hadMatch)
  1239. {
  1240. if (mBestMethodDef != NULL)
  1241. return false;
  1242. /*if ((mHadExplicitGenericArguments) && (mBestMethodGenericArguments.size() != checkMethod->mGenericParams.size()))
  1243. return false;*/
  1244. if (mBackupMethodDef != NULL)
  1245. {
  1246. int prevParamDiff = (int)mBackupMethodDef->mParams.size() - (int)mArguments.size();
  1247. int paramDiff = (int)checkMethod->mParams.size() - (int)mArguments.size();
  1248. if ((prevParamDiff < 0) && (prevParamDiff > paramDiff))
  1249. return false;
  1250. if ((prevParamDiff >= 0) && ((paramDiff < 0) || (prevParamDiff < paramDiff)))
  1251. return false;
  1252. // We search from the most specific type, so don't prefer a less specific type
  1253. if ((paramDiff == prevParamDiff) && (mBestMethodTypeInstance != typeInstance))
  1254. return false;
  1255. }
  1256. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1257. {
  1258. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1259. if ((methodMatchInfo->mPrevBestIdx == -1) && (!methodMatchInfo->mHadExactMatch))
  1260. {
  1261. methodMatchInfo->mBestIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  1262. }
  1263. }
  1264. mBackupMethodDef = checkMethod;
  1265. // Lie temporarily to store at least one candidate (but mBestMethodDef is still NULL)
  1266. hadMatch = true;
  1267. }
  1268. if (hadMatch)
  1269. {
  1270. mBestMethodTypeInstance = typeInstance;
  1271. if (genericArgumentsSubstitute != &mBestMethodGenericArguments)
  1272. {
  1273. if (genericArgumentsSubstitute != NULL)
  1274. mBestMethodGenericArguments = *genericArgumentsSubstitute;
  1275. else
  1276. mBestMethodGenericArguments.clear();
  1277. }
  1278. }
  1279. Done:
  1280. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (genericArgumentsSubstitute != NULL))
  1281. {
  1282. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1283. if (!methodMatchInfo->mInstanceList.IsEmpty())
  1284. {
  1285. methodMatchInfo->mInstanceList[methodMatchInfo->mInstanceList.size() - 1].mGenericArguments = *genericArgumentsSubstitute;
  1286. }
  1287. }
  1288. return mBestMethodDef == checkMethod;
  1289. }
  1290. void BfMethodMatcher::FlushAmbiguityError()
  1291. {
  1292. if (!mAmbiguousEntries.empty())
  1293. {
  1294. BfError* error;
  1295. if (!mMethodName.empty())
  1296. error = mModule->Fail(StrFormat("Ambiguous method call for '%s'", mMethodName.c_str()), mTargetSrc);
  1297. else
  1298. error = mModule->Fail("Ambiguous method call", mTargetSrc);
  1299. if (error != NULL)
  1300. {
  1301. BfMethodInstance* bestMethodInstance = mModule->GetRawMethodInstance(mBestMethodTypeInstance, mBestMethodDef);
  1302. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(bestMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  1303. mBestMethodGenericArguments.empty() ? NULL : &mBestMethodGenericArguments).c_str()),
  1304. bestMethodInstance->mMethodDef->GetRefNode());
  1305. for (auto& ambiguousEntry : mAmbiguousEntries)
  1306. {
  1307. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(ambiguousEntry.mMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  1308. ambiguousEntry.mBestMethodGenericArguments.empty() ? NULL : &ambiguousEntry.mBestMethodGenericArguments).c_str()),
  1309. ambiguousEntry.mMethodInstance->mMethodDef->GetRefNode());
  1310. }
  1311. }
  1312. mAmbiguousEntries.Clear();
  1313. }
  1314. }
  1315. // This method checks all base classes before checking interfaces. Is that correct?
  1316. bool BfMethodMatcher::CheckType(BfTypeInstance* typeInstance, BfTypedValue target, bool isFailurePass)
  1317. {
  1318. auto curTypeInst = typeInstance;
  1319. auto curTypeDef = typeInstance->mTypeDef;
  1320. int checkInterfaceIdx = 0;
  1321. bool allowExplicitInterface = curTypeInst->IsInterface() && mBypassVirtual;
  1322. auto activeTypeDef = mModule->GetActiveTypeDef();
  1323. bool isDelegate = typeInstance->IsDelegate();
  1324. bool targetIsBase = target.IsBase();
  1325. bool checkExtensionBase = false;
  1326. if (targetIsBase)
  1327. {
  1328. if ((curTypeInst == mModule->mCurTypeInstance) && (curTypeInst->mTypeDef->mIsCombinedPartial))
  1329. {
  1330. checkExtensionBase = true;
  1331. }
  1332. else
  1333. {
  1334. curTypeInst = curTypeInst->mBaseType;
  1335. }
  1336. }
  1337. while (true)
  1338. {
  1339. curTypeDef->PopulateMemberSets();
  1340. BfMethodDef* nextMethodDef = NULL;
  1341. BfMemberSetEntry* entry;
  1342. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  1343. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  1344. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  1345. while (nextMethodDef != NULL)
  1346. {
  1347. auto checkMethod = nextMethodDef;
  1348. nextMethodDef = nextMethodDef->mNextWithSameName;
  1349. if ((checkExtensionBase) && (curTypeInst == mModule->mCurTypeInstance))
  1350. {
  1351. // Accept either a method in the same project but that's the root definition, OR a method that's in a dependent project
  1352. bool accept = false;
  1353. if (activeTypeDef->mProject == checkMethod->mDeclaringType->mProject)
  1354. accept = (activeTypeDef->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension());
  1355. else
  1356. accept = activeTypeDef->mProject->ContainsReference(checkMethod->mDeclaringType->mProject);
  1357. if (!accept)
  1358. continue;
  1359. }
  1360. if ((!allowExplicitInterface) && (checkMethod->mExplicitInterface != NULL) && (mInterfaceMethodInstance == NULL))
  1361. {
  1362. continue;
  1363. }
  1364. if (checkMethod->mMethodType != mMethodType)
  1365. continue;
  1366. // if (checkMethod->mName != mMethodName)
  1367. // continue;
  1368. if (!isDelegate)
  1369. {
  1370. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  1371. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, activeTypeDef)))
  1372. continue;
  1373. }
  1374. MatchFailKind matchFailKind = MatchFailKind_None;
  1375. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkMethod->mProtection, typeInstance))
  1376. {
  1377. if ((mBypassVirtual) && (checkMethod->mProtection == BfProtection_Protected) && (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, typeInstance)))
  1378. {
  1379. // Allow explicit 'base' call
  1380. }
  1381. else
  1382. {
  1383. if (!isFailurePass)
  1384. continue;
  1385. matchFailKind = MatchFailKind_Protection;
  1386. }
  1387. }
  1388. if (mCheckedKind != checkMethod->mCheckedKind)
  1389. {
  1390. bool passes = true;
  1391. if (mCheckedKind != BfCheckedKind_NotSet)
  1392. {
  1393. passes = false;
  1394. }
  1395. else
  1396. {
  1397. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  1398. if (defaultCheckedKind != checkMethod->mCheckedKind)
  1399. passes = false;
  1400. }
  1401. if (!passes)
  1402. {
  1403. if (!isFailurePass)
  1404. continue;
  1405. matchFailKind = MatchFailKind_CheckedMismatch;
  1406. }
  1407. }
  1408. CheckMethod(curTypeInst, checkMethod, isFailurePass);
  1409. if ((isFailurePass) &&
  1410. ((mBestMethodDef == checkMethod) || (mBackupMethodDef == checkMethod)))
  1411. mMatchFailKind = matchFailKind;
  1412. }
  1413. if (mBestMethodDef != NULL)
  1414. {
  1415. FlushAmbiguityError();
  1416. return true;
  1417. }
  1418. auto baseType = curTypeInst->mBaseType;
  1419. if (baseType == NULL)
  1420. {
  1421. //TODO: Why were we doing the interface checking?
  1422. if ((curTypeInst != mModule->mContext->mBfObjectType) && (!curTypeInst->IsInterface()))
  1423. {
  1424. // This can happen for structs
  1425. baseType = mModule->mContext->mBfObjectType;
  1426. }
  1427. else if ((typeInstance->IsInterface()) && (checkInterfaceIdx < (int)typeInstance->mInterfaces.size()))
  1428. {
  1429. baseType = typeInstance->mInterfaces[checkInterfaceIdx].mInterfaceType;
  1430. checkInterfaceIdx++;
  1431. }
  1432. else
  1433. {
  1434. break;
  1435. }
  1436. }
  1437. curTypeDef = baseType->mTypeDef;
  1438. curTypeInst = baseType;
  1439. if ((isFailurePass) && (mBackupMethodDef != NULL))
  1440. break;
  1441. }
  1442. if (mBestMethodDef == NULL)
  1443. {
  1444. // FAILED, but select the first method which will fire an actual error on param type matching
  1445. mBestMethodDef = mBackupMethodDef;
  1446. }
  1447. if ((mBestMethodDef == NULL) && (!target) && (mAllowImplicitThis))
  1448. {
  1449. // No explicit target - maybe this was a static call in the outer type?
  1450. auto outerType = mModule->GetOuterType(typeInstance);
  1451. if (outerType != NULL)
  1452. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  1453. }
  1454. FlushAmbiguityError();
  1455. return mBestMethodDef != NULL;
  1456. }
  1457. void BfMethodMatcher::TryDevirtualizeCall(BfTypedValue target, BfTypedValue* origTarget, BfTypedValue* staticResult)
  1458. {
  1459. if ((mBestMethodDef == NULL) || (target.mType == NULL))
  1460. return;
  1461. if ((mModule->mCompiler->IsAutocomplete()) || (mModule->mContext->mResolvingVarField))
  1462. return;
  1463. if (mModule->mBfIRBuilder->mIgnoreWrites)
  1464. return;
  1465. if (mBestMethodTypeInstance->IsInterface())
  1466. {
  1467. mModule->PopulateType(mBestMethodTypeInstance, BfPopulateType_DataAndMethods);
  1468. auto activeTypeDef = mModule->GetActiveTypeDef();
  1469. // Statically map this call
  1470. auto checkType = target.mType;
  1471. if (checkType->IsPointer())
  1472. checkType = ((BfPointerType*)checkType)->mElementType;
  1473. if (checkType->IsWrappableType())
  1474. checkType = mModule->GetWrappedStructType(checkType);
  1475. if ((checkType != NULL) && (checkType->IsTypeInstance()) && (!checkType->IsInterface()))
  1476. {
  1477. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  1478. auto checkTypeInst = checkType->ToTypeInstance();
  1479. if (mBestMethodTypeInstance->mTypeDef == mModule->mCompiler->mIHashableTypeDef)
  1480. {
  1481. if ((origTarget != NULL) && (origTarget->mType->IsPointer()) && (staticResult != NULL))
  1482. {
  1483. BfTypedValue ptrVal = mModule->LoadValue(*origTarget);
  1484. *staticResult = BfTypedValue(mModule->mBfIRBuilder->CreatePtrToInt(ptrVal.mValue, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  1485. return;
  1486. }
  1487. }
  1488. while (checkTypeInst != NULL)
  1489. {
  1490. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  1491. for (auto&& iface : checkTypeInst->mInterfaces)
  1492. {
  1493. //TODO: Why did we have this check? This caused Dictionary to not be able to devirtualize
  1494. // calls to TKey GetHashCode when TKey was from a user's project...
  1495. /*if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  1496. continue;*/
  1497. if (iface.mInterfaceType == mBestMethodTypeInstance)
  1498. {
  1499. if (bestIFaceEntry == NULL)
  1500. {
  1501. bestIFaceEntry = &iface;
  1502. continue;
  1503. }
  1504. bool isBetter;
  1505. bool isWorse;
  1506. mModule->CompareDeclTypes(iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  1507. if (isBetter == isWorse)
  1508. {
  1509. // Failed
  1510. }
  1511. else
  1512. {
  1513. if (isBetter)
  1514. bestIFaceEntry = &iface;
  1515. }
  1516. }
  1517. }
  1518. if (bestIFaceEntry != NULL)
  1519. break;
  1520. checkTypeInst = checkTypeInst->mBaseType;
  1521. if ((checkTypeInst == NULL) && (checkType->HasWrappedRepresentation()))
  1522. {
  1523. auto underlyingType = checkType->GetUnderlyingType();
  1524. if ((underlyingType != NULL) && (underlyingType->IsWrappableType()))
  1525. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  1526. }
  1527. }
  1528. if (bestIFaceEntry != NULL)
  1529. {
  1530. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + mBestMethodDef->mIdx];
  1531. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  1532. if (bestMethodInstance != NULL)
  1533. {
  1534. bool isMissingArg = false;
  1535. for (auto genericArg : mBestMethodGenericArguments)
  1536. {
  1537. if (genericArg == NULL)
  1538. isMissingArg = true;
  1539. }
  1540. if (!isMissingArg)
  1541. {
  1542. // Assert error state?
  1543. mBestMethodTypeInstance = ifaceMethodEntry.mMethodRef.mTypeInstance;
  1544. mBestMethodDef = bestMethodInstance->mMethodDef;
  1545. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, bestMethodInstance->mMethodDef, mBestMethodGenericArguments,
  1546. bestMethodInstance->mIsForeignMethodDef ? BfGetMethodInstanceFlag_ForeignMethodDef : BfGetMethodInstanceFlag_None,
  1547. bestMethodInstance->GetForeignType());
  1548. }
  1549. }
  1550. else
  1551. {
  1552. // Failed
  1553. mFakeConcreteTarget = true;
  1554. }
  1555. }
  1556. }
  1557. }
  1558. if ((target.mType->IsValueType()) && (mBestMethodTypeInstance->IsObject()) && (mBestMethodDef->mIsVirtual))
  1559. {
  1560. auto structType = target.mType->ToTypeInstance();
  1561. auto virtualMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, mBestMethodDef, BfTypeVector());
  1562. BF_ASSERT(virtualMethodInstance.mMethodInstance->mVirtualTableIdx != -1);
  1563. BfTypeInstance* boxedType;
  1564. if (structType->HasOverrideMethods())
  1565. {
  1566. // We don't actually need this boxed type, so just resolve it unreified
  1567. auto useModule = mModule->mContext->mUnreifiedModule;
  1568. boxedType = useModule->CreateBoxedType(target.mType);
  1569. useModule->PopulateType(boxedType, BfPopulateType_DataAndMethods);
  1570. useModule->AddDependency(boxedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  1571. }
  1572. else
  1573. {
  1574. boxedType = mModule->mContext->mBfObjectType;
  1575. }
  1576. auto methodRef = boxedType->mVirtualMethodTable[virtualMethodInstance.mMethodInstance->mVirtualTableIdx];
  1577. if (methodRef.mImplementingMethod.mTypeInstance->IsBoxed())
  1578. {
  1579. auto useModule = mModule->mContext->mUnreifiedModule;
  1580. auto boxedMethodInstance = useModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  1581. BfBoxedType* vBoxedType = (BfBoxedType*)methodRef.mImplementingMethod.mTypeInstance;
  1582. mBestMethodTypeInstance = vBoxedType->mElementType;
  1583. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, boxedMethodInstance.mMethodInstance->mMethodDef, BfTypeVector());
  1584. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  1585. }
  1586. else
  1587. {
  1588. mBestMethodTypeInstance = methodRef.mImplementingMethod.mTypeInstance;
  1589. mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  1590. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  1591. }
  1592. mBypassVirtual = true;
  1593. }
  1594. }
  1595. void BfMethodMatcher::CheckOuterTypeStaticMethods(BfTypeInstance* typeInstance, bool isFailurePass)
  1596. {
  1597. bool allowPrivate = true;
  1598. bool allowProtected = true;
  1599. auto curTypeInst = typeInstance;
  1600. auto curTypeDef = typeInstance->mTypeDef;
  1601. while (true)
  1602. {
  1603. curTypeDef->PopulateMemberSets();
  1604. BfMethodDef* nextMethodDef = NULL;
  1605. BfMemberSetEntry* entry;
  1606. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  1607. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  1608. while (nextMethodDef != NULL)
  1609. {
  1610. auto checkMethod = nextMethodDef;
  1611. nextMethodDef = nextMethodDef->mNextWithSameName;
  1612. // These can only be invoked when the target itself is the interface
  1613. if (checkMethod->mExplicitInterface != NULL)
  1614. continue;
  1615. if ((checkMethod->mMethodType != BfMethodType_Normal) || (!checkMethod->mIsStatic))
  1616. continue;
  1617. if (checkMethod->mName != mMethodName)
  1618. continue;
  1619. if ((!isFailurePass) && (!mModule->CheckProtection(checkMethod->mProtection, allowProtected, allowPrivate)))
  1620. continue;
  1621. CheckMethod(curTypeInst, checkMethod, isFailurePass);
  1622. }
  1623. if (mBestMethodDef != NULL)
  1624. return;
  1625. auto baseType = curTypeInst->mBaseType;
  1626. if (baseType == NULL)
  1627. break;
  1628. curTypeDef = baseType->mTypeDef;
  1629. curTypeInst = baseType;
  1630. allowPrivate = false;
  1631. if ((isFailurePass) && (mBackupMethodDef != NULL))
  1632. break;
  1633. }
  1634. if (mBestMethodDef == NULL)
  1635. {
  1636. // FAILED, but select the first method which will fire an actual error on param type matching
  1637. mBestMethodDef = mBackupMethodDef;
  1638. }
  1639. if (mBestMethodDef == NULL)
  1640. {
  1641. // No explicit target - maybe this was a static call in the outer type?
  1642. auto outerType = mModule->GetOuterType(typeInstance);
  1643. if (outerType != NULL)
  1644. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  1645. }
  1646. }
  1647. //////////////////////////////////////////////////////////////////////////
  1648. void BfResolvedArgs::HandleFixits(BfModule* module)
  1649. {
  1650. auto compiler = module->mCompiler;
  1651. if ((!compiler->IsAutocomplete()) || (compiler->mResolvePassData->mResolveType != BfResolveType_GetFixits))
  1652. return;
  1653. SetAndRestoreValue<bool> ignoreErrors(module->mIgnoreErrors, true);
  1654. for (int argIdx = 0; argIdx < (int)mResolvedArgs.size(); argIdx++)
  1655. {
  1656. auto& resolvedArg = mResolvedArgs[argIdx];
  1657. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  1658. if (expr != NULL)
  1659. {
  1660. module->CreateValueFromExpression(expr, resolvedArg.mExpectedType);
  1661. }
  1662. }
  1663. }
  1664. //////////////////////////////////////////////////////////////////////////
  1665. BfExprEvaluator::BfExprEvaluator(BfModule* module)
  1666. {
  1667. mBfEvalExprFlags = BfEvalExprFlags_None;
  1668. mModule = module;
  1669. mPropDef = NULL;
  1670. mPropSrc = NULL;
  1671. mPropGetMethodFlags = BfGetMethodInstanceFlag_None;
  1672. mPropCheckedKind = BfCheckedKind_NotSet;
  1673. mUsedAsStatement = false;
  1674. mPropDefBypassVirtual = false;
  1675. mExpectingType = NULL;
  1676. mFunctionBindResult = NULL;
  1677. mExplicitCast = false;
  1678. mDeferCallRef = NULL;
  1679. mDeferScopeAlloc = NULL;
  1680. mPrefixedAttributeState = NULL;
  1681. mResolveGenericParam = true;
  1682. mNoBind = false;
  1683. mResultLocalVar = NULL;
  1684. mResultLocalVarField = 0;
  1685. mResultLocalVarFieldCount = 0;
  1686. mResultLocalVarRefNode = NULL;
  1687. mIsVolatileReference = false;
  1688. mIsHeapReference = false;
  1689. mResultIsTempComposite = false;
  1690. mAllowReadOnlyReference = false;
  1691. mReceivingValue = NULL;
  1692. }
  1693. BfExprEvaluator::~BfExprEvaluator()
  1694. {
  1695. }
  1696. BfAutoComplete* BfExprEvaluator::GetAutoComplete()
  1697. {
  1698. if (mModule->mCompiler->mResolvePassData == NULL)
  1699. return NULL;
  1700. // For local methods- only process autocomplete on capture phase
  1701. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  1702. return NULL;
  1703. // if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod))
  1704. // return NULL;
  1705. return mModule->mCompiler->mResolvePassData->mAutoComplete;
  1706. }
  1707. BfType* BfExprEvaluator::BindGenericType(BfAstNode* node, BfType* bindType)
  1708. {
  1709. if ((mModule->mCurMethodState == NULL) || (mModule->mCurMethodInstance == NULL) || (bindType == NULL))
  1710. return bindType;
  1711. BF_ASSERT(!mModule->mCurMethodInstance->mIsUnspecializedVariation);
  1712. auto parser = node->GetSourceData()->ToParserData();
  1713. if (parser == NULL)
  1714. return bindType;
  1715. int64 nodeId = ((int64)parser->mDataId << 32) + node->GetSrcStart();
  1716. if (mModule->mCurMethodInstance->mIsUnspecialized)
  1717. {
  1718. if (!bindType->IsGenericParam())
  1719. return bindType;
  1720. (*mModule->mCurMethodState->mGenericTypeBindings)[nodeId] = bindType;
  1721. return bindType;
  1722. }
  1723. else
  1724. {
  1725. if (mModule->mCurMethodState->mGenericTypeBindings == NULL)
  1726. return bindType;
  1727. /*auto itr = mModule->mCurMethodState->mGenericTypeBindings->find(nodeId);
  1728. if (itr != mModule->mCurMethodState->mGenericTypeBindings->end())
  1729. return itr->second;*/
  1730. BfType** typePtr = NULL;
  1731. if (mModule->mCurMethodState->mGenericTypeBindings->TryGetValue(nodeId, &typePtr))
  1732. return *typePtr;
  1733. return bindType;
  1734. }
  1735. }
  1736. BfType * BfExprEvaluator::ResolveTypeRef(BfTypeReference* typeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  1737. {
  1738. if (mExpectingType != NULL)
  1739. {
  1740. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(typeRef))
  1741. {
  1742. if (namedTypeRef->ToString() == "ExpectedType")
  1743. {
  1744. return mModule->ResolveTypeResult(typeRef, mExpectingType, populateType, resolveFlags);
  1745. }
  1746. }
  1747. }
  1748. return mModule->ResolveTypeRef(typeRef, populateType, resolveFlags);
  1749. }
  1750. void BfExprEvaluator::ResolveGenericType()
  1751. {
  1752. if (mResult)
  1753. {
  1754. if (mModule->IsUnboundGeneric(mResult.mType))
  1755. mResult.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  1756. //mResult.mType = mModule->ResolveGenericType(mResult.mType, true);
  1757. }
  1758. }
  1759. void BfExprEvaluator::Evaluate(BfAstNode* astNode, bool propogateNullConditional, bool ignoreNullConditional, bool allowSplat)
  1760. {
  1761. BP_ZONE("BfExprEvaluator::Evaluate");
  1762. // ParenthesizedExpression breaks null conditional chain
  1763. if (astNode->IsExact<BfParenthesizedExpression>())
  1764. propogateNullConditional = false;
  1765. BfPendingNullConditional* pendingNullCond = NULL;
  1766. if (mModule->mCurMethodState != NULL)
  1767. {
  1768. pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  1769. if (!propogateNullConditional)
  1770. mModule->mCurMethodState->mPendingNullConditional = NULL;
  1771. }
  1772. astNode->Accept(this);
  1773. GetResult();
  1774. if ((mResultIsTempComposite) && (mResult.IsAddr()))
  1775. mResult.mKind = BfTypedValueKind_TempAddr;
  1776. if ((!allowSplat) && (mResult.IsSplat()))
  1777. mResult = mModule->AggregateSplat(mResult);
  1778. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowIntUnknown) == 0)
  1779. mModule->FixIntUnknown(mResult);
  1780. if ((!propogateNullConditional) && (mModule->mCurMethodState != NULL))
  1781. {
  1782. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  1783. mResult = mModule->FlushNullConditional(mResult, ignoreNullConditional);
  1784. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  1785. }
  1786. }
  1787. void BfExprEvaluator::Visit(BfTypeReference* typeRef)
  1788. {
  1789. mResult.mType = ResolveTypeRef(typeRef, BfPopulateType_Declaration);
  1790. }
  1791. void BfExprEvaluator::Visit(BfAttributedExpression* attribExpr)
  1792. {
  1793. BfAttributeState attributeState;
  1794. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  1795. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attribExpr->mAttributes, attributeState.mTarget);
  1796. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  1797. VisitChild(attribExpr->mExpression);
  1798. if (!attributeState.mUsed)
  1799. {
  1800. mModule->Fail("Unused attributes", attribExpr->mAttributes);
  1801. }
  1802. }
  1803. void BfExprEvaluator::Visit(BfBlock* blockExpr)
  1804. {
  1805. if (mModule->mCurMethodState == NULL)
  1806. {
  1807. mModule->Fail("Illegal use of block expression", blockExpr);
  1808. return;
  1809. }
  1810. auto autoComplete = GetAutoComplete();
  1811. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(blockExpr)))
  1812. {
  1813. // Don't show outer method match info when our cursor is inside a block (being passed as a parameter)
  1814. autoComplete->RemoveMethodMatchInfo();
  1815. }
  1816. if (blockExpr->mChildArr.IsEmpty())
  1817. {
  1818. mModule->Fail("An empty block cannot be used as an expression", blockExpr);
  1819. return;
  1820. }
  1821. bool lastWasResultExpr = false;
  1822. if (auto lastExpr = BfNodeDynCast<BfExpressionStatement>(blockExpr->mChildArr.GetLast()))
  1823. {
  1824. if (!lastExpr->IsMissingSemicolon())
  1825. mModule->Fail("Expression blocks must end in an expression which is missing its terminating semicolon", lastExpr->mTrailingSemicolon);
  1826. }
  1827. else if (auto lastExpr = BfNodeDynCast<BfExpression>(blockExpr->mChildArr.GetLast()))
  1828. {
  1829. // Expression
  1830. }
  1831. else
  1832. {
  1833. mModule->Fail("Expression blocks must end with an expression", blockExpr);
  1834. }
  1835. mModule->VisitEmbeddedStatement(blockExpr, this);
  1836. }
  1837. bool BfExprEvaluator::CheckVariableDeclaration(BfAstNode* checkNode, bool requireSimpleIfExpr, bool exprMustBeTrue, bool silentFail)
  1838. {
  1839. BfAstNode* checkChild = checkNode;
  1840. bool foundIf = false;
  1841. auto parentNodeEntry = mModule->mParentNodeEntry;
  1842. if (parentNodeEntry != NULL)
  1843. {
  1844. if (BfNodeIsA<BfInvocationExpression>(parentNodeEntry->mNode))
  1845. {
  1846. checkChild = parentNodeEntry->mNode;
  1847. parentNodeEntry = parentNodeEntry->mPrev;
  1848. }
  1849. }
  1850. while (parentNodeEntry != NULL)
  1851. {
  1852. BfAstNode* checkParent = parentNodeEntry->mNode;
  1853. if (auto binOpExpr = BfNodeDynCastExact<BfBinaryOperatorExpression>(checkParent))
  1854. {
  1855. if (binOpExpr->mOp == BfBinaryOp_ConditionalAnd)
  1856. {
  1857. // This is always okay
  1858. }
  1859. else if ((binOpExpr->mOp == BfBinaryOp_ConditionalOr) && (!exprMustBeTrue))
  1860. {
  1861. bool matches = false;
  1862. auto checkRight = binOpExpr->mRight;
  1863. while (checkRight != NULL)
  1864. {
  1865. if (checkRight == checkChild)
  1866. {
  1867. matches = true;
  1868. break;
  1869. }
  1870. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkRight))
  1871. checkRight = parenExpr->mExpression;
  1872. else
  1873. {
  1874. break;
  1875. }
  1876. }
  1877. if (matches)
  1878. {
  1879. if (!silentFail)
  1880. mModule->Fail("Conditional short-circuiting may skip variable initialization", binOpExpr->mOpToken);
  1881. return false;
  1882. }
  1883. }
  1884. else
  1885. {
  1886. if (exprMustBeTrue)
  1887. {
  1888. if (!silentFail)
  1889. mModule->Fail("Operator cannot be used with variable initialization", binOpExpr->mOpToken);
  1890. return false;
  1891. }
  1892. }
  1893. }
  1894. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkParent))
  1895. {
  1896. // This is okay
  1897. }
  1898. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkParent))
  1899. {
  1900. if (exprMustBeTrue)
  1901. {
  1902. if (!silentFail)
  1903. mModule->Fail("Operator cannot be used with variable initialization", unaryOp->mOpToken);
  1904. return false;
  1905. }
  1906. }
  1907. else if (auto ifStmt = BfNodeDynCast<BfIfStatement>(checkParent))
  1908. {
  1909. // Done
  1910. foundIf = true;
  1911. break;
  1912. }
  1913. else
  1914. {
  1915. if (requireSimpleIfExpr)
  1916. {
  1917. if (!silentFail)
  1918. mModule->Fail("Variable declaration expression can only be contained in simple 'if' expressions", checkNode);
  1919. return false;
  1920. }
  1921. break;
  1922. }
  1923. checkChild = parentNodeEntry->mNode;
  1924. parentNodeEntry = parentNodeEntry->mPrev;
  1925. }
  1926. return foundIf;
  1927. }
  1928. bool BfExprEvaluator::HasVariableDeclaration(BfAstNode* checkNode)
  1929. {
  1930. BfVarDeclChecker checker;
  1931. checker.VisitChild(checkNode);
  1932. return checker.mHasVarDecl;
  1933. }
  1934. void BfExprEvaluator::Visit(BfVariableDeclaration* varDecl)
  1935. {
  1936. mModule->UpdateExprSrcPos(varDecl);
  1937. CheckVariableDeclaration(varDecl, true, false, false);
  1938. if (varDecl->mInitializer == NULL)
  1939. {
  1940. mModule->Fail("Variable declarations used as expressions must have an initializer", varDecl);
  1941. }
  1942. BfTupleExpression* tupleVariableDeclaration = BfNodeDynCast<BfTupleExpression>(varDecl->mNameNode);
  1943. if (tupleVariableDeclaration != NULL)
  1944. {
  1945. mModule->Fail("Tuple variable declarations cannot be used as expressions", varDecl);
  1946. mModule->HandleTupleVariableDeclaration(varDecl);
  1947. }
  1948. else
  1949. mModule->HandleVariableDeclaration(varDecl, this);
  1950. }
  1951. void BfExprEvaluator::Visit(BfCaseExpression* caseExpr)
  1952. {
  1953. if (caseExpr->mEqualsNode != NULL)
  1954. {
  1955. mModule->Warn(0, "Deprecated case syntax", caseExpr->mEqualsNode);
  1956. }
  1957. BfTypedValue caseValAddr;
  1958. if (caseExpr->mValueExpression != NULL)
  1959. caseValAddr = mModule->CreateValueFromExpression(caseExpr->mValueExpression);
  1960. if (caseValAddr.mType != NULL)
  1961. mModule->mBfIRBuilder->PopulateType(caseValAddr.mType);
  1962. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  1963. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  1964. if (auto bindExpr = BfNodeDynCast<BfEnumCaseBindExpression>(caseExpr->mCaseExpression))
  1965. {
  1966. if (caseValAddr)
  1967. {
  1968. BfTypedValue enumTagVal;
  1969. if (caseValAddr.mType->IsPayloadEnum())
  1970. {
  1971. int dscrDataIdx;
  1972. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  1973. enumTagVal = BfTypedValue(mModule->ExtractValue(caseValAddr, dscrDataIdx), dscrType);
  1974. }
  1975. else
  1976. enumTagVal = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Int32));
  1977. mResult = mModule->HandleCaseBind(caseValAddr, enumTagVal, bindExpr);
  1978. return;
  1979. }
  1980. }
  1981. if ((caseValAddr) && (caseValAddr.mType->IsPayloadEnum()))
  1982. {
  1983. bool hasVariable = false;
  1984. bool hasOut = false;
  1985. bool clearOutOnMismatch = false;
  1986. if (auto invocateExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression))
  1987. {
  1988. for (auto arg : invocateExpr->mArguments)
  1989. {
  1990. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(arg))
  1991. {
  1992. hasVariable = true;
  1993. }
  1994. else if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(arg))
  1995. {
  1996. if (unaryOpExpr->mOpToken->mToken == BfToken_Out)
  1997. {
  1998. hasOut = true;
  1999. }
  2000. }
  2001. }
  2002. }
  2003. if (hasVariable)
  2004. {
  2005. CheckVariableDeclaration(caseExpr, false, true, false);
  2006. }
  2007. // We can avoid clearing on mismatch if we can be sure we ONLY enter the true block on a match.
  2008. // An example of requiring clearing is: if ((result case .Ok(out val)) || (force))
  2009. if (hasOut)
  2010. clearOutOnMismatch = !CheckVariableDeclaration(caseExpr, true, true, true);
  2011. int dscrDataIdx;
  2012. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  2013. auto enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  2014. int uncondTagId = -1;
  2015. bool hadConditional = false;
  2016. mResult = mModule->TryCaseEnumMatch(caseValAddr, enumTagVal, caseExpr->mCaseExpression, NULL, NULL, NULL, uncondTagId, hadConditional, clearOutOnMismatch);
  2017. if (mResult)
  2018. return;
  2019. }
  2020. if ((caseValAddr) && (caseValAddr.mType->IsVar()))
  2021. {
  2022. auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression);
  2023. if (invocationExpr != NULL)
  2024. {
  2025. for (auto expr : invocationExpr->mArguments)
  2026. {
  2027. if (expr == NULL)
  2028. continue;
  2029. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(expr))
  2030. {
  2031. auto localVar = mModule->HandleVariableDeclaration(varDecl, BfTypedValue());
  2032. if (localVar != NULL)
  2033. localVar->mReadFromId = 0;
  2034. }
  2035. }
  2036. }
  2037. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  2038. mResult = mModule->GetDefaultTypedValue(boolType);
  2039. return;
  2040. }
  2041. if ((caseValAddr.mType != NULL) && (caseValAddr.mType->IsPointer()))
  2042. {
  2043. caseValAddr = mModule->LoadValue(caseValAddr);
  2044. caseValAddr = BfTypedValue(caseValAddr.mValue, caseValAddr.mType->GetUnderlyingType(), true);
  2045. }
  2046. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  2047. BfTypedValue caseMatch;
  2048. if (caseExpr->mCaseExpression != NULL)
  2049. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, caseValAddr.mType, BfEvalExprFlags_AllowEnumId);
  2050. if ((!caseMatch) || (!caseValAddr))
  2051. {
  2052. mResult = mModule->GetDefaultTypedValue(boolType);
  2053. return;
  2054. }
  2055. if (caseValAddr.mType == caseMatch.mType)
  2056. {
  2057. if (((caseValAddr.mType->IsEnum()) && (caseValAddr.mType->IsStruct())) &&
  2058. ((caseMatch) && (caseMatch.mType->IsPayloadEnum()) && (caseMatch.mValue.IsConst())))
  2059. {
  2060. BfTypedValue enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  2061. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(enumTagVal.mValue, caseMatch.mValue), boolType);
  2062. return;
  2063. }
  2064. }
  2065. else
  2066. {
  2067. // We need to get rid of the int-const for the 'scalar match'. We get a full payload enum value so we can
  2068. // possibly use it in a user-defined comparison operator
  2069. if ((caseMatch.mType->IsStruct()) && (caseMatch.mValue.IsConst()))
  2070. {
  2071. // Is it possible this could throw an error twice? Hope not.
  2072. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, NULL);
  2073. }
  2074. }
  2075. PerformBinaryOperation(caseExpr->mCaseExpression, caseExpr->mValueExpression, BfBinaryOp_Equality, caseExpr->mEqualsNode, BfBinOpFlag_None, caseValAddr, caseMatch);
  2076. }
  2077. void BfExprEvaluator::Visit(BfTypedValueExpression* typedValueExpr)
  2078. {
  2079. mResult = typedValueExpr->mTypedValue;
  2080. }
  2081. static bool IsCharType(BfTypeCode typeCode)
  2082. {
  2083. switch (typeCode)
  2084. {
  2085. case BfTypeCode_Char8:
  2086. case BfTypeCode_Char16:
  2087. case BfTypeCode_Char32:
  2088. return true;
  2089. default:
  2090. return false;
  2091. }
  2092. }
  2093. void BfExprEvaluator::GetLiteral(BfAstNode* refNode, const BfVariant& variant)
  2094. {
  2095. switch (variant.mTypeCode)
  2096. {
  2097. case BfTypeCode_NullPtr:
  2098. {
  2099. auto nullType = mModule->ResolveTypeDef(mModule->mSystem->mTypeNullPtr);
  2100. /*mResult = BfTypedValue(ConstantPointerNull::get((PointerType*) nullType->mIRType), nullType);*/
  2101. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstNull(), nullType);
  2102. }
  2103. break;
  2104. case BfTypeCode_CharPtr:
  2105. {
  2106. if ((mExpectingType != NULL) && (mExpectingType->IsSizedArray()))
  2107. {
  2108. auto sizedArray = (BfSizedArrayType*)mExpectingType;
  2109. if (sizedArray->mElementType == mModule->GetPrimitiveType(BfTypeCode_Char8))
  2110. {
  2111. if (variant.mString->GetLength() > sizedArray->mElementCount)
  2112. {
  2113. mModule->Fail(StrFormat("String literal is too long to fit into '%s'", mModule->TypeToString(sizedArray).c_str()), refNode);
  2114. }
  2115. Array<BfIRValue> charValues;
  2116. for (int i = 0; i < (int)BF_MIN(variant.mString->GetLength(), sizedArray->mElementCount); i++)
  2117. {
  2118. char c = (*variant.mString)[i];
  2119. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)(uint8)c));
  2120. }
  2121. if (sizedArray->mElementCount > charValues.size())
  2122. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, 0));
  2123. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstArray(mModule->mBfIRBuilder->MapType(sizedArray), charValues), sizedArray);
  2124. return;
  2125. }
  2126. }
  2127. if ((mExpectingType == NULL) || (!mExpectingType->IsPointer()))
  2128. {
  2129. mResult = BfTypedValue(mModule->GetStringObjectValue(*variant.mString),
  2130. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  2131. }
  2132. else
  2133. {
  2134. auto charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  2135. auto charPtrType = mModule->CreatePointerType(charType);
  2136. mResult = BfTypedValue(mModule->GetStringCharPtr(*variant.mString),
  2137. charPtrType);
  2138. }
  2139. }
  2140. break;
  2141. case BfTypeCode_Boolean:
  2142. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  2143. break;
  2144. case BfTypeCode_Char8:
  2145. case BfTypeCode_Char16:
  2146. case BfTypeCode_Char32:
  2147. case BfTypeCode_Int8:
  2148. case BfTypeCode_UInt8:
  2149. case BfTypeCode_Int16:
  2150. case BfTypeCode_UInt16:
  2151. case BfTypeCode_Int32:
  2152. case BfTypeCode_UInt32:
  2153. case BfTypeCode_Int64:
  2154. case BfTypeCode_UInt64:
  2155. case BfTypeCode_IntPtr:
  2156. case BfTypeCode_UIntPtr:
  2157. case BfTypeCode_IntUnknown:
  2158. case BfTypeCode_UIntUnknown:
  2159. if ((mExpectingType != NULL) && (mExpectingType->IsIntegral()) && (mExpectingType->IsChar() == IsCharType(variant.mTypeCode)))
  2160. {
  2161. auto primType = (BfPrimitiveType*)mExpectingType;
  2162. if (mModule->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, variant.mInt64))
  2163. {
  2164. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, variant.mUInt64), mExpectingType);
  2165. break;
  2166. }
  2167. }
  2168. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  2169. break;
  2170. case BfTypeCode_Single:
  2171. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mSingle), mModule->GetPrimitiveType(variant.mTypeCode));
  2172. break;
  2173. case BfTypeCode_Double:
  2174. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mDouble), mModule->GetPrimitiveType(variant.mTypeCode));
  2175. break;
  2176. default:
  2177. mModule->Fail("Invalid literal", refNode);
  2178. break;
  2179. }
  2180. }
  2181. void BfExprEvaluator::Visit(BfLiteralExpression* literalExpr)
  2182. {
  2183. switch (literalExpr->mValue.mWarnType)
  2184. {
  2185. case BfWarning_BF4201_Only7Hex:
  2186. mModule->Warn(BfWarning_BF4201_Only7Hex, "Only 7 hex digits specified. Add a leading zero to clarify intention.", literalExpr);
  2187. break;
  2188. case BfWarning_BF4202_TooManyHexForInt:
  2189. mModule->Warn(BfWarning_BF4202_TooManyHexForInt, "Too many hex digits for an int, but too few for a long. Use 'L' suffix if a long was intended.", literalExpr);
  2190. break;
  2191. }
  2192. GetLiteral(literalExpr, literalExpr->mValue);
  2193. }
  2194. BfTypedValue BfExprEvaluator::LoadLocal(BfLocalVariable* varDecl, bool allowRef)
  2195. {
  2196. if (!mModule->mIsInsideAutoComplete)
  2197. varDecl->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  2198. // The Beef backend prefers readonly addrs since that reduces register pressure, whereas
  2199. // LLVM prefers values to avoid memory loads. This only applies to primitive types...
  2200. bool preferValue = (varDecl->mResolvedType->IsPrimitiveType()) && (!mModule->IsTargetingBeefBackend());
  2201. BfTypedValue localResult;
  2202. if (varDecl->mIsThis)
  2203. {
  2204. return mModule->GetThis();
  2205. }
  2206. else if (varDecl->mConstValue)
  2207. {
  2208. localResult = BfTypedValue(varDecl->mConstValue, varDecl->mResolvedType, false);
  2209. }
  2210. else if (varDecl->mIsSplat)
  2211. {
  2212. if ((!preferValue) && (varDecl->mAddr))
  2213. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  2214. else if (!varDecl->mResolvedType->IsValuelessType())
  2215. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  2216. else
  2217. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType);
  2218. //BF_ASSERT(varDecl->mValue.IsArg());
  2219. }
  2220. else if ((varDecl->mValue) && ((varDecl->mIsReadOnly && preferValue) || (!varDecl->mAddr)))
  2221. {
  2222. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  2223. {
  2224. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  2225. BfType* innerType = refType->mElementType;
  2226. if (innerType->IsGenericParam())
  2227. {
  2228. if (refType->mRefKind == BfRefType::RefKind_Mut)
  2229. {
  2230. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_MutableValue);
  2231. return localResult;
  2232. }
  2233. else
  2234. {
  2235. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_Addr);
  2236. return localResult;
  2237. }
  2238. }
  2239. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_Addr);
  2240. }
  2241. else
  2242. {
  2243. BfTypedValueKind kind;
  2244. if ((varDecl->mResolvedType->IsComposite()) && (varDecl->IsParam()) && (mModule->mCurMethodState->mMixinState == NULL))
  2245. kind = varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr;
  2246. else
  2247. kind = BfTypedValueKind_Value;
  2248. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, kind);
  2249. }
  2250. }
  2251. else if (varDecl->mAddr)
  2252. {
  2253. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  2254. {
  2255. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  2256. BfType* innerType = refType->mElementType;
  2257. if (innerType->IsValuelessType())
  2258. {
  2259. if (refType->mRefKind == BfRefType::RefKind_Mut)
  2260. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, BfTypedValueKind_MutableValue);
  2261. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  2262. }
  2263. if (refType->mRefKind == BfRefType::RefKind_Mut)
  2264. {
  2265. if (innerType->IsGenericParam())
  2266. {
  2267. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, BfTypedValueKind_MutableValue);
  2268. return localResult;
  2269. }
  2270. }
  2271. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  2272. }
  2273. else if (varDecl->mHasLocalStructBacking)
  2274. {
  2275. // varDecl->mAddr is a "struct**"
  2276. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), varDecl->mResolvedType, true);
  2277. }
  2278. else
  2279. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  2280. }
  2281. else if (varDecl->mResolvedType->IsValuelessType())
  2282. {
  2283. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  2284. {
  2285. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  2286. BfType* innerType = refType->mElementType;
  2287. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, true);
  2288. return localResult;
  2289. }
  2290. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), varDecl->mResolvedType, true);
  2291. }
  2292. else if (varDecl->mCompositeCount >= 0)
  2293. {
  2294. localResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  2295. }
  2296. else
  2297. {
  2298. BF_ASSERT((mModule->mCurMethodState->mClosureState != NULL) || (mModule->mBfIRBuilder->mIgnoreWrites));
  2299. // Just temporary
  2300. auto varType = varDecl->mResolvedType;
  2301. auto allocType = varType;
  2302. if (varType->IsRef())
  2303. {
  2304. BfRefType* refType = (BfRefType*)varType;
  2305. allocType = refType->mElementType;
  2306. }
  2307. auto declType = varDecl->mResolvedType;
  2308. if (declType->IsRef())
  2309. {
  2310. BfRefType* refType = (BfRefType*)declType;
  2311. declType = refType->mElementType;
  2312. }
  2313. mModule->PopulateType(allocType);
  2314. varDecl->mAddr = mModule->mBfIRBuilder->CreateAlloca(mModule->mBfIRBuilder->MapType(allocType));
  2315. localResult = BfTypedValue(varDecl->mAddr, declType, true);
  2316. return localResult;
  2317. }
  2318. if ((varDecl->mIsThis) && (localResult.mKind == BfTypedValueKind_Value))
  2319. localResult.mKind = BfTypedValueKind_ThisValue;
  2320. return localResult;
  2321. }
  2322. BfTypedValue BfExprEvaluator::LookupIdentifier(BfAstNode* refNode, const StringImpl& findName, bool ignoreInitialError, bool* hadError)
  2323. {
  2324. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(refNode);
  2325. if (mModule->mCurMethodState != NULL)
  2326. {
  2327. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  2328. auto checkMethodState = mModule->mCurMethodState;
  2329. bool isMixinOuterVariablePass = false;
  2330. while (checkMethodState != NULL)
  2331. {
  2332. BP_ZONE("LookupIdentifier:LocalVar");
  2333. BfTypeInstance* closureTypeInst = NULL;
  2334. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  2335. {
  2336. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  2337. }
  2338. int varSkipCount = 0;
  2339. StringT<128> wantName = findName;
  2340. while (wantName.StartsWith("@"))
  2341. {
  2342. varSkipCount++;
  2343. wantName.Remove(0);
  2344. }
  2345. if (wantName.IsEmpty())
  2346. {
  2347. mModule->Fail("Shadowed variable name expected after '@'", refNode);
  2348. }
  2349. BfLocalVarEntry* entry;
  2350. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(wantName, &entry))
  2351. {
  2352. auto varDecl = entry->mLocalVar;
  2353. while ((varSkipCount > 0) && (varDecl != NULL))
  2354. {
  2355. varDecl = varDecl->mShadowedLocal;
  2356. varSkipCount--;
  2357. }
  2358. if ((varSkipCount == 0) && (varDecl != NULL))
  2359. {
  2360. if ((closureTypeInst != NULL) && (wantName == "this"))
  2361. break;
  2362. if ((varDecl->mCompositeCount >= 0) && ((mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) == 0))
  2363. {
  2364. mModule->Fail("Invalid use of 'params' parameter", refNode);
  2365. }
  2366. if (varDecl->mResolvedType->IsVoid())
  2367. {
  2368. if ((varDecl->mIsReadOnly) && (varDecl->mParamIdx == -2) && (varDecl->mParamFailed))
  2369. {
  2370. BF_ASSERT(mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  2371. 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);
  2372. }
  2373. }
  2374. BfTypedValue localResult = LoadLocal(varDecl);
  2375. auto autoComplete = GetAutoComplete();
  2376. if (identifierNode != NULL)
  2377. {
  2378. if (autoComplete != NULL)
  2379. autoComplete->CheckLocalRef(identifierNode, varDecl);
  2380. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  2381. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL))
  2382. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, varDecl->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, varDecl->mLocalVarId);
  2383. }
  2384. if (!isMixinOuterVariablePass)
  2385. {
  2386. mResultLocalVar = varDecl;
  2387. mResultLocalVarRefNode = identifierNode;
  2388. }
  2389. return localResult;
  2390. }
  2391. }
  2392. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  2393. if (closureTypeInst != NULL)
  2394. {
  2395. closureTypeInst->mTypeDef->PopulateMemberSets();
  2396. BfMemberSetEntry* memberSetEntry = NULL;
  2397. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  2398. {
  2399. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  2400. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  2401. if (!field.mResolvedType->IsValuelessType())
  2402. {
  2403. if (mModule->mCurMethodState->mClosureState->mCapturing)
  2404. {
  2405. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  2406. return mModule->GetDefaultTypedValue(field.mResolvedType);
  2407. }
  2408. auto localVar = mModule->mCurMethodState->mLocals[0];
  2409. auto thisValue = localVar->mValue;
  2410. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  2411. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  2412. if (field.mResolvedType->IsRef())
  2413. {
  2414. auto refType = (BfRefType*)field.mResolvedType;
  2415. auto underlyingType = refType->GetUnderlyingType();
  2416. result = BfTypedValue(mModule->mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  2417. }
  2418. else if (fieldDef->mIsReadOnly)
  2419. result = mModule->LoadValue(result);
  2420. mResultLocalVar = localVar;
  2421. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  2422. return result;
  2423. }
  2424. }
  2425. }
  2426. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  2427. {
  2428. checkMethodState = checkMethodState->mPrevMethodState;
  2429. continue;
  2430. }
  2431. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  2432. bool isLocalMixinProcessing = false;
  2433. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  2434. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  2435. isLocalMixinProcessing = true;
  2436. if (!isLocalMixinProcessing)
  2437. break;
  2438. isMixinOuterVariablePass = true;
  2439. checkMethodState = checkMethodState->mPrevMethodState;
  2440. }
  2441. }
  2442. BfTypedValue thisValue = mModule->GetThis();
  2443. bool forcedIFaceLookup = false;
  2444. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef))
  2445. {
  2446. thisValue.mType = mModule->mCurMethodInstance->GetForeignType();
  2447. forcedIFaceLookup = true;
  2448. }
  2449. if (thisValue)
  2450. {
  2451. if (findName == "this")
  2452. return thisValue;
  2453. if (findName == "base")
  2454. {
  2455. auto baseValue = thisValue;
  2456. if (baseValue.IsThis())
  2457. baseValue.ToBase();
  2458. if (mModule->GetActiveTypeDef()->mTypeCode != BfTypeCode_Extension)
  2459. {
  2460. MakeBaseConcrete(baseValue);
  2461. }
  2462. return baseValue;
  2463. }
  2464. if (!mModule->mCurMethodState->HasNonStaticMixin())
  2465. {
  2466. mResultLocalVar = mModule->GetThisVariable();
  2467. mResultLocalVarRefNode = identifierNode;
  2468. }
  2469. }
  2470. if (!thisValue)
  2471. thisValue = BfTypedValue(mModule->mCurTypeInstance);
  2472. BfTypedValue result = LookupField(identifierNode, thisValue, findName, BfLookupFieldFlag_IsImplicitThis);
  2473. if (mPropDef != NULL)
  2474. {
  2475. if (forcedIFaceLookup)
  2476. {
  2477. }
  2478. }
  2479. if ((!result) && (mPropDef == NULL))
  2480. {
  2481. if (mModule->mContext->mCurTypeState != NULL)
  2482. {
  2483. // This is not necessarily true since we changed ConstResolver
  2484. //BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mTypeInstance);
  2485. BfGlobalLookup globalLookup;
  2486. globalLookup.mKind = BfGlobalLookup::Kind_Field;
  2487. globalLookup.mName = findName;
  2488. mModule->PopulateGlobalContainersList(globalLookup);
  2489. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  2490. {
  2491. if (globalContainer.mTypeInst == NULL)
  2492. continue;
  2493. thisValue = BfTypedValue(globalContainer.mTypeInst);
  2494. result = LookupField(identifierNode, thisValue, findName);
  2495. if ((result) || (mPropDef != NULL))
  2496. return result;
  2497. }
  2498. }
  2499. }
  2500. if ((!result) && (identifierNode != NULL))
  2501. result = mModule->TryLookupGenericConstVaue(identifierNode, mExpectingType);
  2502. return result;
  2503. }
  2504. BfTypedValue BfExprEvaluator::LookupIdentifier(BfIdentifierNode* identifierNode, bool ignoreInitialError, bool* hadError)
  2505. {
  2506. auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode);
  2507. if (qualifiedNameNode != NULL)
  2508. {
  2509. LookupQualifiedName(qualifiedNameNode, ignoreInitialError, hadError);
  2510. auto qualifiedResult = mResult;
  2511. mResult = BfTypedValue();
  2512. return qualifiedResult;
  2513. }
  2514. return LookupIdentifier(identifierNode, identifierNode->ToString(), ignoreInitialError, hadError);
  2515. }
  2516. void BfExprEvaluator::Visit(BfIdentifierNode* identifierNode)
  2517. {
  2518. if (GetAutoComplete() != NULL)
  2519. GetAutoComplete()->CheckIdentifier(identifierNode, true);
  2520. mResult = LookupIdentifier(identifierNode);
  2521. if ((!mResult) && (mPropDef == NULL))
  2522. mModule->Fail("Identifier not found", identifierNode);
  2523. }
  2524. void BfExprEvaluator::Visit(BfAttributedIdentifierNode* attrIdentifierNode)
  2525. {
  2526. if ((mModule->mAttributeState != NULL))
  2527. {
  2528. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  2529. VisitChild(attrIdentifierNode->mIdentifier);
  2530. }
  2531. else
  2532. {
  2533. BfAttributeState attributeState;
  2534. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  2535. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  2536. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  2537. VisitChild(attrIdentifierNode->mIdentifier);
  2538. }
  2539. }
  2540. static int gPropIdx = 0;
  2541. void BfExprEvaluator::FixitAddMember(BfTypeInstance* typeInst, BfType* fieldType, const StringImpl& fieldName, bool isStatic)
  2542. {
  2543. if (fieldType == NULL)
  2544. {
  2545. fieldType = mExpectingType;
  2546. }
  2547. if (fieldType != NULL)
  2548. {
  2549. if (fieldType->IsRef())
  2550. fieldType = fieldType->GetUnderlyingType();
  2551. }
  2552. mModule->mCompiler->mResolvePassData->mAutoComplete->FixitAddMember(typeInst, fieldType, fieldName, isStatic, mModule->mCurTypeInstance);
  2553. }
  2554. BfTypedValue BfExprEvaluator::LookupField(BfAstNode* targetSrc, BfTypedValue target, const StringImpl& fieldName, BfLookupFieldFlags flags)
  2555. {
  2556. BfTypeInstance* startCheckType = mModule->mCurTypeInstance;
  2557. mPropDef = NULL;
  2558. mPropDefBypassVirtual = false;
  2559. if ((target.mType != NULL) && (mModule->mCurMethodState != NULL))
  2560. {
  2561. mModule->PopulateType(target.mType, BfPopulateType_BaseType);
  2562. }
  2563. if (target)
  2564. {
  2565. if ((!target.mType->IsValueType()) && (target.IsAddr()))
  2566. target = mModule->LoadValue(target);
  2567. if (target.mType->IsPrimitiveType())
  2568. {
  2569. auto primType = (BfPrimitiveType*)target.mType;
  2570. startCheckType = mModule->GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  2571. }
  2572. else
  2573. {
  2574. startCheckType = target.mType->ToTypeInstance();
  2575. if ((startCheckType == NULL) && (target.mType->IsPointer()))
  2576. startCheckType = ((BfPointerType*) target.mType)->mElementType->ToTypeInstance();
  2577. }
  2578. //BF_ASSERT(startCheckType != NULL);
  2579. }
  2580. else if (target.mType != NULL)
  2581. {
  2582. startCheckType = target.mType->ToTypeInstance();
  2583. }
  2584. auto activeTypeDef = mModule->GetActiveTypeDef();
  2585. for (int pass = 0; pass < 2; pass++)
  2586. {
  2587. auto curCheckType = startCheckType;
  2588. bool isFailurePass = pass == 1;
  2589. bool isBaseLookup = false;
  2590. while (curCheckType != NULL)
  2591. {
  2592. curCheckType->mTypeDef->PopulateMemberSets();
  2593. BfFieldDef* nextField = NULL;
  2594. BfMemberSetEntry* entry;
  2595. if (curCheckType->mTypeDef->mFieldSet.TryGetWith(fieldName, &entry))
  2596. nextField = (BfFieldDef*)entry->mMemberDef;
  2597. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  2598. BfFieldDef* matchedField = NULL;
  2599. while (nextField != NULL)
  2600. {
  2601. auto field = nextField;
  2602. nextField = nextField->mNextWithSameName;
  2603. if ((!isFailurePass) && (!mModule->CheckProtection(protectionCheckFlags, curCheckType, field->mProtection, startCheckType)))
  2604. {
  2605. continue;
  2606. }
  2607. //OLD:
  2608. bool isResolvingFields = curCheckType->mResolvingConstField || curCheckType->mResolvingVarField;
  2609. // mCurMethodState is NULL when we're pre-evaluating var field expressions
  2610. // to determine their type in PopulateFields
  2611. /*if (!isResolvingFields)
  2612. {
  2613. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  2614. }*/
  2615. if (curCheckType->mFieldInstances.IsEmpty())
  2616. {
  2617. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  2618. }
  2619. BF_ASSERT(field->mIdx < (int)curCheckType->mFieldInstances.size());
  2620. auto fieldInstance = &curCheckType->mFieldInstances[field->mIdx];
  2621. if (!fieldInstance->mFieldIncluded)
  2622. continue;
  2623. if (curCheckType->IsUnspecializedType())
  2624. {
  2625. // The check for non-unspecialized types is already handled in mFieldIncluded
  2626. if (!curCheckType->IsTypeMemberIncluded(field->mDeclaringType, activeTypeDef, mModule))
  2627. continue;
  2628. }
  2629. if (!curCheckType->IsTypeMemberAccessible(field->mDeclaringType, activeTypeDef))
  2630. continue;
  2631. if (matchedField != NULL)
  2632. {
  2633. auto error = mModule->Fail(StrFormat("Ambiguous reference to field '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  2634. if (error != NULL)
  2635. {
  2636. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", matchedField->mDeclaringType->mProject->mName.c_str()), matchedField->mFieldDeclaration);
  2637. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", field->mDeclaringType->mProject->mName.c_str()), field->mFieldDeclaration);
  2638. break;
  2639. }
  2640. }
  2641. matchedField = field;
  2642. }
  2643. if (matchedField != NULL)
  2644. {
  2645. auto field = matchedField;
  2646. auto fieldInstance = &curCheckType->mFieldInstances[field->mIdx];
  2647. bool isResolvingFields = curCheckType->mResolvingConstField || curCheckType->mResolvingVarField;
  2648. if (field->mIsVolatile)
  2649. mIsVolatileReference = true;
  2650. if (isFailurePass)
  2651. {
  2652. mModule->Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", mModule->TypeToString(curCheckType).c_str(), field->mName.c_str()), targetSrc);
  2653. }
  2654. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  2655. if ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field))
  2656. {
  2657. resolvePassData->HandleFieldReference(targetSrc, curCheckType->mTypeDef, field);
  2658. }
  2659. if ((!curCheckType->mTypeFailed) && (!isResolvingFields) && (curCheckType->IsIncomplete()))
  2660. {
  2661. if ((fieldInstance->mResolvedType == NULL) ||
  2662. (!field->mIsStatic))
  2663. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  2664. }
  2665. if (fieldInstance->mResolvedType == NULL)
  2666. {
  2667. BF_ASSERT((curCheckType->mTypeFailed) || (isResolvingFields));
  2668. return BfTypedValue();
  2669. }
  2670. if (fieldInstance->mFieldIdx == -1)
  2671. {
  2672. mModule->AssertErrorState();
  2673. return BfTypedValue();
  2674. }
  2675. // Are we accessing a 'var' field that has not yet been resolved?
  2676. if (fieldInstance->mResolvedType->IsVar())
  2677. {
  2678. // This can happen if we have one var field referencing another var field
  2679. fieldInstance->mResolvedType = mModule->ResolveVarFieldType(curCheckType, fieldInstance, field);
  2680. if (fieldInstance->mResolvedType == NULL)
  2681. return BfTypedValue();
  2682. if ((fieldInstance->mResolvedType->IsVar()) && (mModule->mCompiler->mIsResolveOnly))
  2683. mModule->Fail("Field type reference failed to resolve", targetSrc);
  2684. }
  2685. auto resolvedFieldType = fieldInstance->mResolvedType;
  2686. if (fieldInstance->mIsEnumPayloadCase)
  2687. {
  2688. resolvedFieldType = curCheckType;
  2689. }
  2690. mModule->PopulateType(resolvedFieldType, BfPopulateType_Data);
  2691. mModule->AddDependency(curCheckType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  2692. auto autoComplete = GetAutoComplete();
  2693. if (autoComplete != NULL)
  2694. autoComplete->CheckFieldRef(BfNodeDynCast<BfIdentifierNode>(targetSrc), fieldInstance);
  2695. if (field->mIsStatic)
  2696. {
  2697. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!curCheckType->mTypeDef->IsGlobalsContainer()))
  2698. {
  2699. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  2700. mModule->Fail(StrFormat("Member '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  2701. mModule->TypeToString(curCheckType).c_str(), field->mName.c_str()), targetSrc);
  2702. }
  2703. // Target must be an implicit 'this', or an error (accessing a static with a non-static target).
  2704. // Not actually needed in either case since this is a static lookup.
  2705. mResultLocalVar = NULL;
  2706. }
  2707. bool isConst = false;
  2708. if (field->mIsConst)
  2709. {
  2710. isConst = true;
  2711. auto fieldDef = fieldInstance->GetFieldDef();
  2712. if ((resolvedFieldType->IsPointer()) && (fieldDef->mIsExtern))
  2713. isConst = false;
  2714. }
  2715. if (resolvedFieldType->IsValuelessType())
  2716. {
  2717. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedFieldType, true);
  2718. }
  2719. if (isConst)
  2720. {
  2721. if (fieldInstance->mIsEnumPayloadCase)
  2722. {
  2723. auto dscrType = curCheckType->GetDiscriminatorType();
  2724. mModule->mBfIRBuilder->PopulateType(curCheckType);
  2725. int tagIdx = -fieldInstance->mDataIdx - 1;
  2726. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowEnumId) != 0)
  2727. {
  2728. return BfTypedValue(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), fieldInstance->mOwner);
  2729. }
  2730. mModule->PopulateType(fieldInstance->mOwner, BfPopulateType_Data);
  2731. // auto agg = mModule->mBfIRBuilder->CreateUndefValue(mModule->mBfIRBuilder->MapType(fieldInstance->mOwner));
  2732. // agg = mModule->mBfIRBuilder->CreateInsertValue(agg, mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), 2);
  2733. //
  2734. // if (fieldInstance->mResolvedType->mSize != 0)
  2735. // {
  2736. // mModule->FailAfter("Enum case parameters expected", targetSrc);
  2737. // }
  2738. //
  2739. // return BfTypedValue(agg, fieldInstance->mOwner);
  2740. auto agg = mModule->CreateAlloca(fieldInstance->mOwner);
  2741. auto gep = mModule->mBfIRBuilder->CreateInBoundsGEP(agg, 0, 2);
  2742. mModule->mBfIRBuilder->CreateStore(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), gep);
  2743. if (fieldInstance->mResolvedType->mSize != 0)
  2744. {
  2745. mModule->FailAfter("Enum case parameters expected", targetSrc);
  2746. }
  2747. return BfTypedValue(agg, fieldInstance->mOwner, true);
  2748. }
  2749. if (fieldInstance->mConstIdx == -1)
  2750. {
  2751. curCheckType->mModule->ResolveConstField(curCheckType, fieldInstance, field);
  2752. if (fieldInstance->mConstIdx == -1)
  2753. return BfTypedValue(mModule->GetDefaultValue(resolvedFieldType), resolvedFieldType);
  2754. }
  2755. BF_ASSERT(fieldInstance->mConstIdx != -1);
  2756. auto foreignConst = curCheckType->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  2757. auto retVal = mModule->ConstantToCurrent(foreignConst, curCheckType->mConstHolder, resolvedFieldType);
  2758. return BfTypedValue(retVal, resolvedFieldType);
  2759. }
  2760. else if (field->mIsStatic)
  2761. {
  2762. mModule->CheckStaticAccess(curCheckType);
  2763. auto retVal = mModule->ReferenceStaticField(fieldInstance);
  2764. if (field->mIsReadOnly)
  2765. retVal = mModule->LoadValue(retVal, NULL, mIsVolatileReference);
  2766. else
  2767. mIsHeapReference = true;
  2768. return retVal;
  2769. }
  2770. else if (!target)
  2771. {
  2772. if ((flags & BfLookupFieldFlag_CheckingOuter) != 0)
  2773. mModule->Fail(StrFormat("An instance reference is required to reference non-static outer field '%s.%s'", mModule->TypeToString(curCheckType).c_str(), field->mName.c_str()),
  2774. targetSrc);
  2775. else if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  2776. mModule->Fail(StrFormat("Cannot reference field '%s' before append allocations", field->mName.c_str()), targetSrc);
  2777. else
  2778. mModule->Fail(StrFormat("Cannot reference non-static field '%s' from a static method", field->mName.c_str()), targetSrc);
  2779. return mModule->GetDefaultTypedValue(resolvedFieldType, false, BfDefaultValueKind_Addr);
  2780. }
  2781. if ((mResultLocalVar != NULL) && (fieldInstance->mMergedDataIdx != -1))
  2782. {
  2783. int minMergedDataIdx = fieldInstance->mMergedDataIdx;
  2784. int maxMergedDataIdx = minMergedDataIdx + 1;
  2785. if (resolvedFieldType->IsStruct())
  2786. maxMergedDataIdx = minMergedDataIdx + resolvedFieldType->ToTypeInstance()->mMergedFieldDataCount;
  2787. if (curCheckType->mIsUnion)
  2788. {
  2789. for (auto& checkFieldInstance : curCheckType->mFieldInstances)
  2790. {
  2791. if (&checkFieldInstance == fieldInstance)
  2792. continue;
  2793. if (checkFieldInstance.mDataIdx == fieldInstance->mDataIdx)
  2794. {
  2795. int checkMinMergedDataIdx = checkFieldInstance.mMergedDataIdx;
  2796. int checkMaxMergedDataIdx = checkMinMergedDataIdx + 1;
  2797. if (checkFieldInstance.GetResolvedType()->IsStruct())
  2798. checkMaxMergedDataIdx = checkMinMergedDataIdx + checkFieldInstance.mResolvedType->ToTypeInstance()->mMergedFieldDataCount;
  2799. minMergedDataIdx = BF_MIN(minMergedDataIdx, checkMinMergedDataIdx);
  2800. maxMergedDataIdx = BF_MAX(maxMergedDataIdx, checkMaxMergedDataIdx);
  2801. }
  2802. }
  2803. }
  2804. int fieldIdx = -1;
  2805. if (fieldIdx == -1)
  2806. {
  2807. mResultLocalVarField = minMergedDataIdx + 1;
  2808. }
  2809. else
  2810. {
  2811. fieldIdx += minMergedDataIdx;
  2812. mResultLocalVarField = fieldIdx + 1;
  2813. }
  2814. mResultLocalVarFieldCount = maxMergedDataIdx - minMergedDataIdx;
  2815. mResultLocalVarRefNode = targetSrc;
  2816. /*int fieldIdx = (mResultLocalVarIdx >> 16) - 1;
  2817. if (fieldIdx == -1)
  2818. {
  2819. mResultLocalVarField = fieldInstance->mMergedDataIdx + 1;
  2820. }
  2821. else
  2822. {
  2823. fieldIdx += fieldInstance->mMergedDataIdx;
  2824. mResultLocalVarField = fieldIdx + 1;
  2825. }
  2826. mResultLocalVarFieldCount = 1;
  2827. if (fieldInstance->mType->IsStruct())
  2828. {
  2829. auto fieldTypeInstance = fieldInstance->mType->ToTypeInstance();
  2830. mResultLocalVarFieldCount = fieldTypeInstance->mMergedFieldDataCount;
  2831. }
  2832. mResultLocalVarRefNode = targetSrc;*/
  2833. }
  2834. if ((curCheckType->IsIncomplete()) && (!curCheckType->mNeedsMethodProcessing))
  2835. {
  2836. BF_ASSERT(curCheckType->mTypeFailed || (mModule->mCurMethodState == NULL) || (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCompiler->IsAutocomplete()));
  2837. return mModule->GetDefaultTypedValue(resolvedFieldType);
  2838. }
  2839. bool isTemporary = false;
  2840. bool wantsLoadValue = false;
  2841. if ((field->mIsReadOnly) && ((mModule->mCurMethodInstance->mMethodDef->mMethodType != BfMethodType_Ctor) || (!target.IsThis())))
  2842. wantsLoadValue = true;
  2843. bool isComposite = target.mType->IsComposite();
  2844. if ((isComposite) && (!target.mType->IsTypedPrimitive()) && (!target.IsAddr()))
  2845. isTemporary = true;
  2846. if ((isComposite) && (!target.IsAddr()))
  2847. wantsLoadValue = true;
  2848. if ((target.mType->IsWrappableType()) && (!target.mType->IsPointer()))
  2849. {
  2850. BfTypeInstance* primStructType = mModule->GetWrappedStructType(target.mType);
  2851. BfIRValue allocaInst = mModule->CreateAlloca(primStructType, true, "tmpStruct");
  2852. BfIRValue elementAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  2853. mModule->mBfIRBuilder->CreateStore(target.mValue, elementAddr);
  2854. target = BfTypedValue(allocaInst, primStructType, true);
  2855. }
  2856. BfTypedValue targetValue;
  2857. if ((isBaseLookup) && (!target.IsSplat()))
  2858. {
  2859. if ((!isComposite) || (target.IsAddr()))
  2860. targetValue = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(curCheckType)), curCheckType);
  2861. else
  2862. {
  2863. BfIRValue curVal = target.mValue;
  2864. auto baseCheckType = target.mType->ToTypeInstance();
  2865. while (baseCheckType != curCheckType)
  2866. {
  2867. curVal = mModule->mBfIRBuilder->CreateExtractValue(curVal, 0);
  2868. baseCheckType = baseCheckType->mBaseType;
  2869. }
  2870. targetValue = BfTypedValue(curVal, curCheckType);
  2871. }
  2872. }
  2873. else
  2874. targetValue = target;
  2875. bool doAccessCheck = true;
  2876. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mSkipAccessCheckAttributeTypeDef)))
  2877. doAccessCheck = false;
  2878. if (target.IsThis())
  2879. {
  2880. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  2881. doAccessCheck = false;
  2882. }
  2883. if (doAccessCheck)
  2884. mModule->EmitObjectAccessCheck(target);
  2885. if (fieldInstance->mDataIdx < 0)
  2886. {
  2887. BF_ASSERT(curCheckType->mTypeFailed);
  2888. return mModule->GetDefaultTypedValue(resolvedFieldType);
  2889. }
  2890. BfTypedValue retVal;
  2891. if (target.IsSplat())
  2892. {
  2893. retVal = mModule->ExtractValue(targetValue, fieldInstance, fieldInstance->mDataIdx);
  2894. }
  2895. else if ((target.mType->IsStruct()) && (!target.IsAddr()))
  2896. {
  2897. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateExtractValue(targetValue.mValue, fieldInstance->mDataIdx/*, field->mName*/),
  2898. resolvedFieldType);
  2899. }
  2900. else
  2901. {
  2902. mModule->mBfIRBuilder->PopulateType(curCheckType);
  2903. if ((targetValue.IsAddr()) && (!curCheckType->IsValueType()))
  2904. targetValue = mModule->LoadValue(targetValue);
  2905. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(targetValue.mValue, 0, fieldInstance->mDataIdx/*, field->mName*/),
  2906. resolvedFieldType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  2907. }
  2908. if (!retVal.IsSplat())
  2909. {
  2910. if (curCheckType->mIsUnion)
  2911. {
  2912. BfIRType llvmPtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(resolvedFieldType));
  2913. retVal.mValue = mModule->mBfIRBuilder->CreateBitCast(retVal.mValue, llvmPtrType);
  2914. }
  2915. }
  2916. if (wantsLoadValue)
  2917. retVal = mModule->LoadValue(retVal, NULL, mIsVolatileReference);
  2918. else
  2919. mIsHeapReference = true;
  2920. if (isTemporary)
  2921. {
  2922. if (retVal.IsAddr())
  2923. retVal.mKind = BfTypedValueKind_TempAddr;
  2924. }
  2925. return retVal;
  2926. }
  2927. BfPropertyDef* nextProp = NULL;
  2928. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(fieldName, &entry))
  2929. nextProp = (BfPropertyDef*)entry->mMemberDef;
  2930. if (nextProp != NULL)
  2931. {
  2932. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  2933. bool isInlined = false;
  2934. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  2935. {
  2936. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  2937. {
  2938. isInlined = true;
  2939. mModule->mAttributeState->mUsed = true;
  2940. }
  2941. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  2942. {
  2943. checkedKind = BfCheckedKind_Checked;
  2944. mModule->mAttributeState->mUsed = true;
  2945. }
  2946. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  2947. {
  2948. checkedKind = BfCheckedKind_Unchecked;
  2949. mModule->mAttributeState->mUsed = true;
  2950. }
  2951. }
  2952. BfPropertyDef* matchedProp = NULL;
  2953. while (nextProp != NULL)
  2954. {
  2955. auto prop = nextProp;
  2956. nextProp = nextProp->mNextWithSameName;
  2957. if ((!isFailurePass) && (!mModule->CheckProtection(protectionCheckFlags, curCheckType, prop->mProtection, startCheckType)))
  2958. {
  2959. continue;
  2960. }
  2961. if (!prop->mMethods.IsEmpty())
  2962. {
  2963. BfMethodDef* checkMethod = prop->mMethods[0];;
  2964. // Properties with explicit interfaces or marked as overrides can only be called indirectly
  2965. if ((checkMethod->mExplicitInterface != NULL) || (checkMethod->mIsOverride))
  2966. continue;
  2967. }
  2968. if ((!target.IsStatic()) || (prop->mIsStatic))
  2969. {
  2970. if ((!curCheckType->IsTypeMemberIncluded(prop->mDeclaringType, activeTypeDef, mModule)) ||
  2971. (!curCheckType->IsTypeMemberAccessible(prop->mDeclaringType, activeTypeDef)))
  2972. continue;
  2973. if (matchedProp != NULL)
  2974. {
  2975. auto error = mModule->Fail(StrFormat("Ambiguous reference to property '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  2976. if (error != NULL)
  2977. {
  2978. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", matchedProp->mDeclaringType->mProject->mName.c_str()), matchedProp->mFieldDeclaration);
  2979. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", prop->mDeclaringType->mProject->mName.c_str()), prop->mFieldDeclaration);
  2980. break;
  2981. }
  2982. }
  2983. matchedProp = prop;
  2984. }
  2985. }
  2986. if (matchedProp != NULL)
  2987. {
  2988. auto prop = matchedProp;
  2989. gPropIdx++;
  2990. mModule->SetElementType(targetSrc, BfSourceElementType_Method);
  2991. mPropSrc = targetSrc;
  2992. mPropDef = prop;
  2993. mPropCheckedKind = checkedKind;
  2994. if (isInlined)
  2995. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  2996. if (mPropDef->mIsStatic)
  2997. {
  2998. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!curCheckType->mTypeDef->IsGlobalsContainer()))
  2999. {
  3000. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  3001. mModule->Fail(StrFormat("Property '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  3002. mModule->TypeToString(curCheckType).c_str(), mPropDef->mName.c_str()), targetSrc);
  3003. }
  3004. }
  3005. if (prop->mIsStatic)
  3006. mPropTarget = BfTypedValue(curCheckType);
  3007. else if (isBaseLookup)
  3008. {
  3009. mPropTarget = mModule->Cast(targetSrc, target, curCheckType);
  3010. BF_ASSERT(mPropTarget);
  3011. }
  3012. else
  3013. mPropTarget = target;
  3014. mOrigPropTarget = mPropTarget;
  3015. auto autoComplete = GetAutoComplete();
  3016. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  3017. if (((autoComplete != NULL) && (autoComplete->mIsGetDefinition)) ||
  3018. ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Property)))
  3019. {
  3020. BfPropertyDef* basePropDef = mPropDef;
  3021. BfTypeInstance* baseTypeInst = curCheckType;
  3022. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  3023. resolvePassData->HandlePropertyReference(targetSrc, baseTypeInst->mTypeDef, basePropDef);
  3024. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetSrc)))
  3025. {
  3026. autoComplete->mDefProp = basePropDef;
  3027. autoComplete->mDefType = baseTypeInst->mTypeDef;
  3028. }
  3029. }
  3030. SetAndRestoreValue<BfTypedValue> prevResult(mResult, target);
  3031. CheckResultForReading(mResult);
  3032. return BfTypedValue();
  3033. }
  3034. }
  3035. isBaseLookup = true;
  3036. curCheckType = curCheckType->mBaseType;
  3037. }
  3038. }
  3039. auto outerTypeDef = mModule->GetOuterType(startCheckType);
  3040. if (outerTypeDef != NULL)
  3041. {
  3042. // Check statics in outer type
  3043. return LookupField(targetSrc, BfTypedValue(outerTypeDef), fieldName, BfLookupFieldFlag_CheckingOuter);
  3044. }
  3045. return BfTypedValue();
  3046. }
  3047. void BfExprEvaluator::ResolveArgValues(BfResolvedArgs& resolvedArgs, BfResolveArgFlags flags)
  3048. {
  3049. static int idx = 0;
  3050. idx++;
  3051. int curIdx = idx;
  3052. if (resolvedArgs.mArguments == NULL)
  3053. return;
  3054. int argCount = (int)resolvedArgs.mArguments->size();
  3055. if ((resolvedArgs.mCommas != NULL) && (resolvedArgs.mCommas->size() != 0) && (resolvedArgs.mCommas->size() >= resolvedArgs.mArguments->size()))
  3056. {
  3057. //mModule->FailAfter("Expression expected", resolvedArgs.mCommas->back());
  3058. argCount++;
  3059. }
  3060. BfAutoComplete* autoComplete = GetAutoComplete();
  3061. bool hadIgnoredFixits = false;
  3062. if (autoComplete != NULL)
  3063. {
  3064. hadIgnoredFixits = autoComplete->mIgnoreFixits;
  3065. if (flags & BfResolveArgFlag_DeferFixits)
  3066. autoComplete->mIgnoreFixits = true;
  3067. }
  3068. for (int argIdx = 0; argIdx < argCount ; argIdx++)
  3069. {
  3070. //printf("Args: %p %p %d\n", resolvedArgs.mArguments, resolvedArgs.mArguments->mVals, resolvedArgs.mArguments->mSize);
  3071. BfExpression* argExpr = NULL;
  3072. if (argIdx < resolvedArgs.mArguments->size())
  3073. argExpr = (*resolvedArgs.mArguments)[argIdx];
  3074. if (argExpr == NULL)
  3075. {
  3076. if (argIdx == 0)
  3077. {
  3078. if (resolvedArgs.mOpenToken != NULL)
  3079. mModule->FailAfter("Expression expected", resolvedArgs.mOpenToken);
  3080. }
  3081. else if (resolvedArgs.mCommas != NULL)
  3082. mModule->FailAfter("Expression expected", (*resolvedArgs.mCommas)[argIdx - 1]);
  3083. }
  3084. if (auto typedValueExpr = BfNodeDynCast<BfTypedValueExpression>(argExpr))
  3085. {
  3086. BfResolvedArg resolvedArg;
  3087. resolvedArg.mTypedValue = typedValueExpr->mTypedValue;
  3088. resolvedArg.mExpression = typedValueExpr->mRefNode;
  3089. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  3090. continue;
  3091. }
  3092. BfResolvedArg resolvedArg;
  3093. BfExprEvaluator exprEvaluator(mModule);
  3094. exprEvaluator.mResolveGenericParam = (flags & BfResolveArgFlag_AllowUnresolvedTypes) == 0;
  3095. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr);
  3096. bool handled = false;
  3097. bool evaluated = false;
  3098. bool deferParamEval = false;
  3099. if ((flags & BfResolveArgFlag_DeferParamEval) != 0)
  3100. {
  3101. if (argExpr != NULL)
  3102. {
  3103. BfDeferEvalChecker deferEvalChecker;
  3104. argExpr->Accept(&deferEvalChecker);
  3105. deferParamEval = deferEvalChecker.mNeedsDeferEval;
  3106. }
  3107. }
  3108. if (deferParamEval)
  3109. {
  3110. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredEval);
  3111. handled = true;
  3112. }
  3113. else if (auto delegateBindExpression = BfNodeDynCast<BfDelegateBindExpression>(argExpr))
  3114. {
  3115. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DelegateBindAttempt);
  3116. handled = true;
  3117. }
  3118. else if (auto lambdaBindExpression = BfNodeDynCast<BfLambdaBindExpression>(argExpr))
  3119. {
  3120. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_LambdaBindAttempt);
  3121. handled = true;
  3122. }
  3123. else if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(argExpr))
  3124. {
  3125. if (memberRef->mTarget == NULL)
  3126. {
  3127. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  3128. handled = true;
  3129. }
  3130. }
  3131. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(argExpr))
  3132. {
  3133. if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(invokeExpr->mTarget))
  3134. {
  3135. if (memberRef->mTarget == NULL)
  3136. {
  3137. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  3138. handled = true;
  3139. }
  3140. }
  3141. }
  3142. else if (auto defaultExpr = BfNodeDynCast<BfDefaultExpression>(argExpr))
  3143. {
  3144. if (defaultExpr->mTypeRef == NULL)
  3145. {
  3146. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UntypedDefault);
  3147. handled = true;
  3148. }
  3149. }
  3150. else if (auto varDeclExpr = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  3151. {
  3152. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  3153. handled = true;
  3154. }
  3155. else if (auto unaryExpr = BfNodeDynCast<BfUnaryOperatorExpression>(argExpr))
  3156. {
  3157. if (unaryExpr->mOp == BfUnaryOp_Params)
  3158. {
  3159. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ParamsExpr);
  3160. }
  3161. }
  3162. /*else if (auto castExpr = BfNodeDynCast<BfCastExpression>(argExpr))
  3163. {
  3164. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(castExpr->mTypeRef))
  3165. {
  3166. if (namedTypeRef->ToString() == "ExpectedType")
  3167. {
  3168. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ExpectedTypeCast);
  3169. handled = true;
  3170. }
  3171. }
  3172. }*/
  3173. if ((argExpr != NULL) && (!handled))
  3174. {
  3175. bool deferParamValues = (flags & BfResolveArgFlag_DeferParamValues) != 0;
  3176. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || deferParamValues);
  3177. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  3178. if (deferParamValues)
  3179. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredValue);
  3180. if (!evaluated)
  3181. {
  3182. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  3183. exprEvaluator.Evaluate(argExpr, false, false, true);
  3184. }
  3185. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  3186. {
  3187. auto localVar = exprEvaluator.mResultLocalVar;
  3188. int fieldIdx = mResultLocalVarField - 1;
  3189. auto methodState = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  3190. if (localVar->mCompositeCount >= 0)
  3191. {
  3192. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) == 0)
  3193. mModule->Warn(0, "'params' token expected", argExpr);
  3194. for (int compositeIdx = 0; compositeIdx < localVar->mCompositeCount; compositeIdx++)
  3195. {
  3196. BfResolvedArg compositeResolvedArg;
  3197. auto compositeLocalVar = methodState->mLocals[localVar->mLocalVarIdx + compositeIdx + 1];
  3198. auto argValue = exprEvaluator.LoadLocal(compositeLocalVar);
  3199. if (argValue)
  3200. {
  3201. if (argValue.mType->IsRef())
  3202. argValue.mKind = BfTypedValueKind_Value;
  3203. else if (!argValue.mType->IsStruct())
  3204. argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  3205. }
  3206. resolvedArg.mTypedValue = argValue;
  3207. resolvedArg.mExpression = argExpr;
  3208. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_FromParamComposite);
  3209. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  3210. }
  3211. continue;
  3212. }
  3213. }
  3214. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  3215. auto argValue = exprEvaluator.mResult;
  3216. if (argValue)
  3217. {
  3218. //resolvedArg.mResolvedType = mModule->ResolveGenericType(argValue.mType);
  3219. resolvedArg.mResolvedType = argValue.mType;
  3220. if (resolvedArg.mResolvedType->IsRef())
  3221. argValue.mKind = BfTypedValueKind_Value;
  3222. else if ((!resolvedArg.mResolvedType->IsStruct()) && (!resolvedArg.mResolvedType->IsSizedArray()) && (!resolvedArg.mResolvedType->IsValuelessType()))
  3223. argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  3224. }
  3225. resolvedArg.mTypedValue = argValue;
  3226. if (deferParamValues)
  3227. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  3228. }
  3229. resolvedArg.mExpression = argExpr;
  3230. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  3231. }
  3232. if (autoComplete != NULL)
  3233. autoComplete->mIgnoreFixits = hadIgnoredFixits;
  3234. }
  3235. void BfExprEvaluator::PerformCallChecks(BfMethodInstance* methodInstance, BfAstNode* targetSrc)
  3236. {
  3237. BfCustomAttributes* customAttributes = methodInstance->GetCustomAttributes();
  3238. if (customAttributes != NULL)
  3239. {
  3240. auto _AddMethodDeclarationMoreInfo = [&]()
  3241. {
  3242. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  3243. mModule->mCompiler->mPassInstance->MoreInfo(
  3244. StrFormat("See method declaration '%s'", mModule->MethodToString(methodInstance).c_str()),
  3245. methodInstance->mMethodDef->GetRefNode());
  3246. };
  3247. BfIRConstHolder* constHolder = methodInstance->GetOwner()->mConstHolder;
  3248. auto customAttribute = customAttributes->Get(mModule->mCompiler->mObsoleteAttributeTypeDef);
  3249. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3250. {
  3251. String err;
  3252. err = StrFormat("'%s' is obsolete", mModule->MethodToString(methodInstance).c_str());
  3253. bool isError = false;
  3254. auto constant = constHolder->GetConstant(customAttribute->mCtorArgs[0]);
  3255. if (constant->mTypeCode == BfTypeCode_Boolean)
  3256. {
  3257. isError = constant->mBool;
  3258. }
  3259. else if (customAttribute->mCtorArgs.size() >= 2)
  3260. {
  3261. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3262. if (str != NULL)
  3263. {
  3264. err += ":\n '";
  3265. err += *str;
  3266. err += "'";
  3267. }
  3268. constant = constHolder->GetConstant(customAttribute->mCtorArgs[1]);
  3269. isError = constant->mBool;
  3270. }
  3271. BfError* error = NULL;
  3272. if (isError)
  3273. error = mModule->Fail(err, targetSrc);
  3274. else
  3275. error = mModule->Warn(0, err, targetSrc);
  3276. if (error != NULL)
  3277. _AddMethodDeclarationMoreInfo();
  3278. }
  3279. customAttribute = customAttributes->Get(mModule->mCompiler->mErrorAttributeTypeDef);
  3280. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3281. {
  3282. String err = StrFormat("Method error: '", mModule->MethodToString(methodInstance).c_str());
  3283. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3284. if (str != NULL)
  3285. err += *str;
  3286. err += "'";
  3287. if (mModule->Fail(err, targetSrc) != NULL)
  3288. _AddMethodDeclarationMoreInfo();
  3289. }
  3290. customAttribute = customAttributes->Get(mModule->mCompiler->mWarnAttributeTypeDef);
  3291. if ((customAttribute != NULL) && (!customAttribute->mCtorArgs.IsEmpty()))
  3292. {
  3293. String err = StrFormat("Method warning: '", mModule->MethodToString(methodInstance).c_str());
  3294. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  3295. if (str != NULL)
  3296. err += *str;
  3297. err += "'";
  3298. if (mModule->Warn(0, err, targetSrc) != NULL)
  3299. _AddMethodDeclarationMoreInfo();
  3300. }
  3301. }
  3302. }
  3303. BfTypedValue BfExprEvaluator::CreateCall(BfMethodInstance* methodInstance, BfIRValue func, bool bypassVirtual, SizedArrayImpl<BfIRValue>& irArgs, BfTypedValue* sret, bool isTailCall)
  3304. {
  3305. // static int sCallIdx = 0;
  3306. // if (!mModule->mCompiler->mIsResolveOnly)
  3307. // sCallIdx++;
  3308. // int callIdx = sCallIdx;
  3309. // if (callIdx == 0x000000E8)
  3310. // {
  3311. // NOP;
  3312. // }
  3313. auto methodDef = methodInstance->mMethodDef;
  3314. BfIRValue funcCallInst = func;
  3315. auto importCallKind = methodInstance->GetImportCallKind();
  3316. if ((funcCallInst) && (importCallKind != BfImportCallKind_None))
  3317. {
  3318. if ((funcCallInst.IsFake()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  3319. {
  3320. mModule->mFuncReferences.TryGetValue(methodInstance, &funcCallInst);
  3321. }
  3322. if (importCallKind == BfImportCallKind_GlobalVar_Hot)
  3323. {
  3324. //TODO: Check against NULL for calling BfLoadSharedLibraries
  3325. auto checkVal = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  3326. BfIRBlock nullBlock = mModule->mBfIRBuilder->CreateBlock("importNull");
  3327. BfIRBlock doneBlock = mModule->mBfIRBuilder->CreateBlock("importLoad");
  3328. auto condVal = mModule->mBfIRBuilder->CreateIsNull(checkVal);
  3329. mModule->mBfIRBuilder->CreateCondBr(condVal, nullBlock, doneBlock);
  3330. mModule->mBfIRBuilder->AddBlock(nullBlock);
  3331. mModule->mBfIRBuilder->SetInsertPoint(nullBlock);
  3332. auto loadSharedLibsFunc = mModule->GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  3333. mModule->mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  3334. mModule->mBfIRBuilder->CreateBr(doneBlock);
  3335. mModule->mBfIRBuilder->AddBlock(doneBlock);
  3336. mModule->mBfIRBuilder->SetInsertPoint(doneBlock);
  3337. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  3338. }
  3339. else
  3340. {
  3341. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  3342. }
  3343. }
  3344. if ((methodInstance->GetOwner()->mTypeDef == mModule->mCompiler->mDeferredCallTypeDef) &&
  3345. (methodInstance->mMethodDef->mName == "Cancel"))
  3346. {
  3347. if (mModule->mCurMethodState != NULL)
  3348. mModule->mCurMethodState->mCancelledDeferredCall = true;
  3349. }
  3350. if (methodDef->mNoReturn)
  3351. {
  3352. mModule->mCurMethodState->SetHadReturn(true);
  3353. mModule->mCurMethodState->mLeftBlockUncond = true;
  3354. }
  3355. if (mModule->mCurTypeInstance != NULL)
  3356. {
  3357. bool isVirtual = (methodInstance->mVirtualTableIdx != -1) && (!bypassVirtual);
  3358. mModule->AddDependency(methodInstance->mMethodInstanceGroup->mOwner, mModule->mCurTypeInstance, isVirtual ? BfDependencyMap::DependencyFlag_VirtualCall : BfDependencyMap::DependencyFlag_Calls);
  3359. mModule->AddCallDependency(methodInstance, bypassVirtual);
  3360. }
  3361. if (methodInstance->GetOwner()->IsUnspecializedType())
  3362. {
  3363. BF_ASSERT((!methodInstance->mIRFunction) || (methodInstance == mModule->mCurMethodInstance));
  3364. }
  3365. if (mFunctionBindResult != NULL)
  3366. {
  3367. BF_ASSERT(mFunctionBindResult->mMethodInstance == NULL);
  3368. mFunctionBindResult->mMethodInstance = methodInstance;
  3369. for (auto arg : irArgs)
  3370. mFunctionBindResult->mIRArgs.push_back(arg);
  3371. }
  3372. BfType* origReturnType = methodInstance->mReturnType;
  3373. /*if (origReturnType->IsSelf())
  3374. {
  3375. origReturnType = methodInstance->GetOwner();
  3376. BF_ASSERT(origReturnType->IsInterface());
  3377. }*/
  3378. BfType* returnType = origReturnType;
  3379. BfTypedValue sretVal;
  3380. auto _GetDefaultReturnValue = [&]()
  3381. {
  3382. if (returnType->IsRef())
  3383. {
  3384. auto result = mModule->GetDefaultTypedValue(returnType->GetUnderlyingType(), true, BfDefaultValueKind_Addr);
  3385. if (methodDef->mIsReadOnly)
  3386. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  3387. return result;
  3388. }
  3389. else
  3390. {
  3391. return mModule->GetDefaultTypedValue(returnType, true, returnType->IsComposite() ? BfDefaultValueKind_Addr : BfDefaultValueKind_Value);
  3392. }
  3393. };
  3394. mModule->PopulateType(origReturnType, BfPopulateType_Data);
  3395. if (methodInstance->HasStructRet())
  3396. {
  3397. // We need to ensure that mReceivingValue has the correct type, otherwise it's possible that a conversion operator needs to be applied
  3398. // This happens for returning Result<T>'s with a 'T' value
  3399. if ((sret == NULL) && (mReceivingValue != NULL) && (mReceivingValue->mType == returnType))
  3400. {
  3401. sretVal = *mReceivingValue;
  3402. sret = &sretVal;
  3403. auto ptrType = mModule->CreatePointerType(returnType);
  3404. if (returnType != sret->mType)
  3405. {
  3406. sret->mValue = mModule->mBfIRBuilder->CreateBitCast(sret->mValue, mModule->mBfIRBuilder->MapType(ptrType));
  3407. sret->mType = returnType;
  3408. }
  3409. mReceivingValue = NULL;
  3410. }
  3411. if (sret == NULL)
  3412. {
  3413. sretVal = BfTypedValue(mModule->CreateAlloca(returnType), returnType, BfTypedValueKind_TempAddr);
  3414. sret = &sretVal;
  3415. }
  3416. }
  3417. else
  3418. {
  3419. BF_ASSERT(sret == NULL);
  3420. }
  3421. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  3422. {
  3423. return _GetDefaultReturnValue();
  3424. }
  3425. BF_ASSERT(!methodInstance->mDisallowCalling);
  3426. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mAutoComplete != NULL))
  3427. {
  3428. // In an autocomplete pass we may have stale method references that need to be resolved
  3429. // in the full classify pass, and in the full classify pass while just refreshing internals, we
  3430. // may have NULL funcs temporarily. We simply skip generating the method call here.
  3431. if (methodInstance->mVirtualTableIdx == -1)
  3432. {
  3433. if (methodInstance->GetOwner()->IsInterface())
  3434. {
  3435. // We're attempting to directly invoke a non-virtual interface method, if we're return an interface then
  3436. // it is a concrete interface
  3437. if (returnType->IsInterface())
  3438. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  3439. }
  3440. }
  3441. BfTypedValue result;
  3442. if (sret != NULL)
  3443. result = *sret;
  3444. else
  3445. result = _GetDefaultReturnValue();
  3446. return result;
  3447. }
  3448. if (((!func) && (methodInstance->mIsUnspecialized)) || (mModule->mBfIRBuilder->mIgnoreWrites))
  3449. {
  3450. // We don't actually submit method calls for unspecialized methods
  3451. // - this includes all methods in unspecialized types
  3452. return _GetDefaultReturnValue();
  3453. }
  3454. if (methodInstance->mVirtualTableIdx != -1)
  3455. {
  3456. if ((!bypassVirtual) && (mDeferCallRef == NULL))
  3457. {
  3458. auto funcType = mModule->mBfIRBuilder->MapMethod(methodInstance);
  3459. auto funcPtrType1 = mModule->mBfIRBuilder->GetPointerTo(funcType);
  3460. auto funcPtrType2 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType1);
  3461. auto funcPtrType3 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType2);
  3462. auto funcPtrType4 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType3);
  3463. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  3464. {
  3465. // IFace dispatch
  3466. auto ifaceTypeInst = methodInstance->mMethodInstanceGroup->mOwner;
  3467. BfIRValue slotOfs = mModule->GetInterfaceSlotNum(methodInstance->mMethodInstanceGroup->mOwner);
  3468. auto vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  3469. auto vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3470. auto ifacePtrPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  3471. auto ifacePtr = mModule->mBfIRBuilder->CreateLoad(ifacePtrPtr);
  3472. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(ifacePtr, methodInstance->mVirtualTableIdx/*, "vfn"*/);
  3473. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  3474. }
  3475. else
  3476. {
  3477. mModule->HadSlotCountDependency();
  3478. // Virtual dispatch
  3479. // int vDataIdx = 0;
  3480. // vDataIdx += 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots;
  3481. BfIRValue vDataPtr;
  3482. BfIRValue vDataIdx;
  3483. if ((mModule->mCompiler->mOptions.mHasVDataExtender) && (mModule->mCompiler->IsHotCompile()))
  3484. {
  3485. auto typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  3486. int extMethodIdx = (methodInstance->mVirtualTableIdx - typeInst->GetBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  3487. if (extMethodIdx >= 0)
  3488. {
  3489. BF_ASSERT(mModule->mCompiler->IsHotCompile());
  3490. // We have grown outside our original virtual table, Load the new vdataPtr from the mHasVDataExtender
  3491. // vDataPtr = obj.vtable.extension.entry[curVersion]
  3492. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  3493. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr));
  3494. // The offset of the vExt is one past the base vtable. When a base class extends its virtual table, an entry
  3495. // for that new method is inserted in mVirtualMethodTable (thus increasing the index relative to GetBaseVTableSize()),
  3496. // but the actual written vtable position doesn't change, hence offsetting from GetOrigBaseVTableSize()
  3497. #ifdef _DEBUG
  3498. int vExtIdx = typeInst->GetBaseVTableSize();
  3499. BF_ASSERT(typeInst->mVirtualMethodTable[vExtIdx].mDeclaringMethod.mMethodNum == -1); // A type entry with a -1 mMethodNum means it's a vtable ext slot
  3500. #endif
  3501. int vExtOfs = typeInst->GetOrigBaseVTableSize();
  3502. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + mModule->mCompiler->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  3503. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, vExtOfs));
  3504. BfIRValue extendPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx);
  3505. vDataPtr = mModule->mBfIRBuilder->CreateLoad(extendPtr);
  3506. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, extMethodIdx);
  3507. }
  3508. else
  3509. {
  3510. // Map this new virtual index back to the original index
  3511. //vDataIdx += (methodInstance->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  3512. //vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  3513. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  3514. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32,
  3515. (methodInstance->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize()));
  3516. }
  3517. }
  3518. else
  3519. {
  3520. //vDataIdx += methodInstance->mVirtualTableIdx;
  3521. //vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  3522. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  3523. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, methodInstance->mVirtualTableIdx));
  3524. }
  3525. if (!vDataPtr)
  3526. {
  3527. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType3);
  3528. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  3529. }
  3530. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx/*, "vfn"*/);
  3531. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  3532. }
  3533. }
  3534. }
  3535. else // non-virtual
  3536. {
  3537. if (methodInstance->GetOwner()->IsInterface())
  3538. {
  3539. // We're attempting to directly invoke a non-virtual interface method, this will happen during the unspecialized pass
  3540. // OR if we had an error and didn't find an implementing member in the actual target
  3541. if (!mModule->mCurMethodInstance->mIsUnspecialized)
  3542. mModule->AssertErrorState();
  3543. if (returnType->IsInterface())
  3544. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  3545. return _GetDefaultReturnValue();
  3546. }
  3547. }
  3548. if (mFunctionBindResult != NULL)
  3549. {
  3550. mFunctionBindResult->mFunc = funcCallInst;
  3551. if (irArgs.size() != 0)
  3552. {
  3553. auto targetType = methodInstance->mMethodInstanceGroup->mOwner;
  3554. if ((targetType->IsValueType()) && (targetType->IsSplattable()) && (!methodDef->HasNoThisSplat()))
  3555. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, BfTypedValueKind_SplatHead);
  3556. else
  3557. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, targetType->IsComposite() ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  3558. }
  3559. else
  3560. {
  3561. mFunctionBindResult->mTarget = BfTypedValue();
  3562. }
  3563. return BfTypedValue();
  3564. }
  3565. if (methodInstance->mReturnType == NULL)
  3566. {
  3567. mModule->AssertErrorState();
  3568. return BfTypedValue();
  3569. }
  3570. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  3571. {
  3572. // Don't actually do the call - our target may be a generic param
  3573. return _GetDefaultReturnValue();
  3574. }
  3575. if (mDeferCallRef != NULL)
  3576. {
  3577. mModule->AddDeferredCall(BfModuleMethodInstance(methodInstance, func), irArgs, mDeferScopeAlloc, mDeferCallRef);
  3578. //return _GetDefaultReturnValue();
  3579. return mModule->GetFakeTypedValue(returnType);
  3580. }
  3581. if (!funcCallInst)
  3582. {
  3583. if ((mModule->HasCompiledOutput()) || (mModule->mCompiler->mOptions.mExtraResolveChecks))
  3584. {
  3585. // This can happen either from an error, or from the resolver while doing Internals_Changed processing
  3586. mModule->AssertErrorState();
  3587. }
  3588. //return mModule->GetDefaultTypedValue(returnType,/*, true*/false, returnType->IsComposite());
  3589. return _GetDefaultReturnValue();
  3590. }
  3591. bool hasResult = !methodInstance->mReturnType->IsValuelessType();
  3592. BfIRValue firstArg;
  3593. if (irArgs.size() != 0)
  3594. firstArg = irArgs[0];
  3595. auto methodInstOwner = methodInstance->GetOwner();
  3596. auto expectCallingConvention = mModule->GetCallingConvention(methodInstOwner, methodDef);
  3597. if ((methodInstOwner->IsFunction()) && (methodInstance->GetParamCount() > 0) && (methodInstance->GetParamName(0) == "this"))
  3598. {
  3599. auto paramType = methodInstance->GetParamType(0);
  3600. if (!paramType->IsValueType())
  3601. expectCallingConvention = BfIRCallingConv_ThisCall;
  3602. }
  3603. if ((methodInstance->mAlwaysInline) && (mModule->mCompiler->mOptions.mEmitLineInfo))
  3604. {
  3605. // Emit a NOP so we always have a "step over" point
  3606. mModule->EmitEnsureInstructionAt();
  3607. }
  3608. if (returnType->IsComposite())
  3609. mModule->mBfIRBuilder->PopulateType(returnType);
  3610. BfIRValue callInst;
  3611. if (sret != NULL)
  3612. {
  3613. SizedArray<BfIRValue, 8> sretIRArgs;
  3614. sretIRArgs.push_back(sret->mValue);
  3615. if (!irArgs.IsEmpty())
  3616. sretIRArgs.Insert(sretIRArgs.size(), &irArgs[0], irArgs.size());
  3617. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, sretIRArgs);
  3618. }
  3619. else
  3620. {
  3621. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, irArgs);
  3622. if (hasResult)
  3623. mModule->mBfIRBuilder->SetName(callInst, methodDef->mName);
  3624. }
  3625. if (expectCallingConvention != BfIRCallingConv_CDecl)
  3626. mModule->mBfIRBuilder->SetCallCallingConv(callInst, expectCallingConvention);
  3627. if (methodDef->mNoReturn)
  3628. mModule->mBfIRBuilder->Call_AddAttribute(callInst, -1, BfIRAttribute_NoReturn);
  3629. bool hadAttrs = false;
  3630. int paramIdx = 0;
  3631. bool doingThis = !methodDef->mIsStatic;
  3632. int argIdx = 0;
  3633. if (sret != NULL)
  3634. {
  3635. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_StructRet);
  3636. argIdx++;
  3637. }
  3638. for ( ; argIdx < (int)irArgs.size(); /*argIdx++*/)
  3639. {
  3640. auto _HandleParamType = [&] (BfType* paramType)
  3641. {
  3642. if (paramType->IsStruct())
  3643. {
  3644. if ((!doingThis) || (!methodDef->mIsMutating && !methodDef->mNoSplat))
  3645. {
  3646. auto loweredTypeCode = paramType->GetLoweredType();
  3647. if (loweredTypeCode != BfTypeCode_None)
  3648. {
  3649. argIdx++;
  3650. return; // Lowering never requires attributes
  3651. }
  3652. }
  3653. }
  3654. int addDeref = -1;
  3655. if (paramType->IsRef())
  3656. {
  3657. auto refType = (BfRefType*)paramType;
  3658. auto elementType = refType->mElementType;
  3659. mModule->PopulateType(elementType, BfPopulateType_Data);
  3660. addDeref = elementType->mSize;
  3661. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  3662. mModule->AssertErrorState();
  3663. }
  3664. if ((paramType->IsComposite()) && (!paramType->IsTypedPrimitive()))
  3665. {
  3666. if (mModule->mCompiler->mOptions.mAllowStructByVal)
  3667. {
  3668. //byval
  3669. }
  3670. else
  3671. {
  3672. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_NoCapture);
  3673. mModule->PopulateType(paramType, BfPopulateType_Data);
  3674. addDeref = paramType->mSize;
  3675. }
  3676. }
  3677. else if (paramType->IsPrimitiveType())
  3678. {
  3679. auto primType = (BfPrimitiveType*)paramType;
  3680. if ((primType->mTypeDef->mTypeCode == BfTypeCode_Boolean) && (!methodInstance->mIsIntrinsic))
  3681. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ZExt);
  3682. }
  3683. if (addDeref >= 0)
  3684. {
  3685. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  3686. }
  3687. argIdx++;
  3688. };
  3689. BfType* paramType = NULL;
  3690. if (doingThis)
  3691. {
  3692. paramType = methodInstance->GetOwner();
  3693. if (paramType->IsValuelessType())
  3694. {
  3695. doingThis = false;
  3696. continue;
  3697. }
  3698. bool isSplatted = methodInstance->GetParamIsSplat(-1); // (resolvedTypeRef->IsSplattable()) && (!methodDef->mIsMutating);
  3699. if (isSplatted)
  3700. {
  3701. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  3702. doingThis = false;
  3703. continue;
  3704. }
  3705. else
  3706. _HandleParamType(paramType);
  3707. }
  3708. else
  3709. {
  3710. paramType = methodInstance->GetParamType(paramIdx);
  3711. if ((paramType->IsValuelessType()) && (!paramType->IsMethodRef()))
  3712. {
  3713. paramIdx++;
  3714. continue;
  3715. }
  3716. //if (resolvedTypeRef->IsSplattable())
  3717. if (methodInstance->GetParamIsSplat(paramIdx))
  3718. {
  3719. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  3720. paramIdx++;
  3721. continue;
  3722. }
  3723. else
  3724. _HandleParamType(methodInstance->GetParamType(paramIdx));
  3725. }
  3726. if (doingThis)
  3727. doingThis = false;
  3728. else
  3729. paramIdx++;
  3730. //argIdx++;
  3731. }
  3732. if (isTailCall)
  3733. mModule->mBfIRBuilder->SetTailCall(callInst);
  3734. if (methodDef->mNoReturn)
  3735. {
  3736. mModule->mBfIRBuilder->CreateUnreachable();
  3737. // For debuggability when looking back at stack trace
  3738. //mModule->ExtendLocalLifetimes(0);
  3739. if (mModule->IsTargetingBeefBackend())
  3740. {
  3741. auto checkScope = mModule->mCurMethodState->mCurScope;
  3742. while (checkScope != NULL)
  3743. {
  3744. mModule->EmitLifetimeEnds(checkScope);
  3745. checkScope = checkScope->mPrevScope;
  3746. }
  3747. // This 'fake' branch extends lifetimes of outer variable scopes
  3748. if (mModule->mCurMethodState->mIRExitBlock)
  3749. mModule->mBfIRBuilder->CreateBr_Fake(mModule->mCurMethodState->mIRExitBlock);
  3750. }
  3751. }
  3752. else
  3753. {
  3754. if (mModule->mCurMethodState != NULL)
  3755. mModule->mCurMethodState->mMayNeedThisAccessCheck = true;
  3756. }
  3757. BfTypedValue result;
  3758. if (sret != NULL)
  3759. result = *sret;
  3760. else if (hasResult)
  3761. result = BfTypedValue(callInst, methodInstance->mReturnType);
  3762. else
  3763. result = mModule->GetFakeTypedValue(methodInstance->mReturnType);
  3764. if (result.mType->IsRef())
  3765. {
  3766. result = mModule->RemoveRef(result);
  3767. if (methodDef->mIsReadOnly)
  3768. {
  3769. if (result.mKind == BfTypedValueKind_Addr)
  3770. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  3771. }
  3772. }
  3773. return result;
  3774. }
  3775. BfTypedValue BfExprEvaluator::CreateCall(BfMethodMatcher* methodMatcher, BfTypedValue target)
  3776. {
  3777. auto moduleMethodInstance = mModule->GetMethodInstance(methodMatcher->mBestMethodTypeInstance, methodMatcher->mBestMethodDef, methodMatcher->mBestMethodGenericArguments);
  3778. if (moduleMethodInstance.mMethodInstance == NULL)
  3779. return BfTypedValue();
  3780. if ((target) && (target.mType != moduleMethodInstance.mMethodInstance->GetOwner()))
  3781. {
  3782. auto castedTarget = mModule->Cast(methodMatcher->mTargetSrc, target, moduleMethodInstance.mMethodInstance->GetOwner());
  3783. BF_ASSERT(castedTarget);
  3784. target = castedTarget;
  3785. }
  3786. return CreateCall(methodMatcher->mTargetSrc, target, BfTypedValue(), methodMatcher->mBestMethodDef, moduleMethodInstance, false, methodMatcher->mArguments);
  3787. }
  3788. void BfExprEvaluator::MakeBaseConcrete(BfTypedValue& typedValue)
  3789. {
  3790. if (typedValue.IsBase())
  3791. {
  3792. auto baseType = mModule->mCurTypeInstance->mBaseType;
  3793. if (baseType == NULL)
  3794. baseType = mModule->mContext->mBfObjectType;
  3795. mModule->PopulateType(baseType, BfPopulateType_Data);
  3796. typedValue = mModule->Cast(NULL, typedValue, baseType, BfCastFlags_Explicit);
  3797. }
  3798. }
  3799. void BfExprEvaluator::SplatArgs(BfTypedValue value, SizedArrayImpl<BfIRValue>& irArgs)
  3800. {
  3801. if (value.IsSplat())
  3802. {
  3803. int componentIdx = 0;
  3804. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->ExtractSplatValue(value, componentIdx++, checkType)); }, value.mType);
  3805. return;
  3806. }
  3807. mModule->mBfIRBuilder->PopulateType(value.mType);
  3808. std::function<void(BfTypedValue)> checkTypeLambda = [&](BfTypedValue curValue)
  3809. {
  3810. BfType* checkType = curValue.mType;
  3811. if (checkType->IsStruct())
  3812. {
  3813. auto checkTypeInstance = checkType->ToTypeInstance();
  3814. if ((checkTypeInstance->mBaseType != NULL) && (!checkTypeInstance->mBaseType->IsValuelessType()))
  3815. {
  3816. BfTypedValue baseValue;
  3817. if (curValue.IsAddr())
  3818. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, 0), checkTypeInstance->mBaseType, true);
  3819. else
  3820. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateExtractValue(curValue.mValue, 0), checkTypeInstance->mBaseType);
  3821. checkTypeLambda(baseValue);
  3822. }
  3823. if (checkTypeInstance->mIsUnion)
  3824. {
  3825. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  3826. if (!unionInnerType->IsValuelessType())
  3827. {
  3828. BfTypedValue unionValue = mModule->ExtractValue(curValue, NULL, 1);
  3829. checkTypeLambda(unionValue);
  3830. }
  3831. if (checkTypeInstance->IsEnum())
  3832. {
  3833. BfTypedValue dscrValue = mModule->ExtractValue(curValue, NULL, 2);
  3834. checkTypeLambda(dscrValue);
  3835. }
  3836. }
  3837. else
  3838. {
  3839. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  3840. {
  3841. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  3842. if (fieldInstance->mDataIdx >= 0)
  3843. {
  3844. BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  3845. checkTypeLambda(fieldValue);
  3846. }
  3847. }
  3848. }
  3849. }
  3850. else if (checkType->IsMethodRef())
  3851. {
  3852. BF_ASSERT(curValue.IsAddr());
  3853. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  3854. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  3855. {
  3856. auto checkType = methodRefType->GetCaptureType(dataIdx);
  3857. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  3858. {
  3859. BF_ASSERT(dataIdx == 0);
  3860. auto ptrType = mModule->CreatePointerType(checkType);
  3861. auto elemPtr = mModule->mBfIRBuilder->CreateBitCast(curValue.mValue, mModule->mBfIRBuilder->MapType(ptrType));
  3862. checkTypeLambda(BfTypedValue(elemPtr, checkType, BfTypedValueKind_Addr));
  3863. //BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  3864. //checkTypeLambda(fieldValue);
  3865. }
  3866. else
  3867. {
  3868. auto elemVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, dataIdx);
  3869. if (!checkType->IsComposite())
  3870. elemVal = mModule->mBfIRBuilder->CreateLoad(elemVal);
  3871. irArgs.Add(elemVal);
  3872. //irArgs.Add(mModule->ExtractValue(curValue, dataIdx));
  3873. }
  3874. }
  3875. }
  3876. else if (!checkType->IsValuelessType())
  3877. {
  3878. auto loadedVal = mModule->LoadValue(curValue);
  3879. irArgs.push_back(loadedVal.mValue);
  3880. }
  3881. };
  3882. checkTypeLambda(value);
  3883. }
  3884. void BfExprEvaluator::PushArg(BfTypedValue argVal, SizedArrayImpl<BfIRValue>& irArgs, bool disableSplat, bool disableLowering)
  3885. {
  3886. MakeBaseConcrete(argVal);
  3887. if (argVal.mType->IsValuelessType())
  3888. return;
  3889. bool wantSplat = false;
  3890. if ((argVal.mType->IsSplattable()) && (!disableSplat))
  3891. {
  3892. if ((int)irArgs.size() + argVal.mType->GetSplatCount() <= mModule->mCompiler->mOptions.mMaxSplatRegs)
  3893. wantSplat = true;
  3894. }
  3895. if (wantSplat)
  3896. {
  3897. SplatArgs(argVal, irArgs);
  3898. }
  3899. else
  3900. {
  3901. if (argVal.mType->IsComposite())
  3902. {
  3903. argVal = mModule->MakeAddressable(argVal);
  3904. if (!disableLowering)
  3905. {
  3906. auto loweredTypeCode = argVal.mType->GetLoweredType();
  3907. if (loweredTypeCode != BfTypeCode_None)
  3908. {
  3909. auto primType = mModule->GetPrimitiveType(loweredTypeCode);
  3910. auto ptrType = mModule->CreatePointerType(primType);
  3911. BfIRValue primPtrVal = mModule->mBfIRBuilder->CreateBitCast(argVal.mValue, mModule->mBfIRBuilder->MapType(ptrType));
  3912. auto primVal = mModule->mBfIRBuilder->CreateLoad(primPtrVal);
  3913. irArgs.push_back(primVal);
  3914. return;
  3915. }
  3916. }
  3917. }
  3918. else
  3919. argVal = mModule->LoadValue(argVal);
  3920. irArgs.push_back(argVal.mValue);
  3921. }
  3922. }
  3923. void BfExprEvaluator::PushThis(BfAstNode* targetSrc, BfTypedValue argVal, BfMethodInstance* methodInstance, SizedArrayImpl<BfIRValue>& irArgs, bool skipMutCheck)
  3924. {
  3925. MakeBaseConcrete(argVal);
  3926. auto methodDef = methodInstance->mMethodDef;
  3927. if (methodInstance->IsSkipCall())
  3928. return;
  3929. if (!argVal)
  3930. {
  3931. //BF_ASSERT(mFunctionBindResult != NULL);
  3932. return;
  3933. }
  3934. if (methodDef->mIsMutating)
  3935. {
  3936. bool checkMut = false;
  3937. if (argVal.mType->IsGenericParam())
  3938. {
  3939. // For capturing mutability
  3940. if (mResultLocalVar != NULL)
  3941. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  3942. }
  3943. if (((argVal.mType->IsComposite()) || (argVal.mType->IsTypedPrimitive())))
  3944. {
  3945. if ((argVal.IsReadOnly()) || (!argVal.IsAddr()))
  3946. {
  3947. if (!skipMutCheck)
  3948. {
  3949. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(methodInstance).c_str());
  3950. CheckModifyResult(argVal, targetSrc, err.c_str());
  3951. }
  3952. if (argVal.IsSplat())
  3953. {
  3954. argVal = mModule->AggregateSplat(argVal);
  3955. argVal = mModule->MakeAddressable(argVal);
  3956. }
  3957. }
  3958. else
  3959. {
  3960. if (mResultLocalVar != NULL)
  3961. {
  3962. // When we are capturing, we need to note that we require capturing by reference here
  3963. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  3964. }
  3965. }
  3966. }
  3967. }
  3968. if (argVal.mType->IsValuelessType())
  3969. return;
  3970. if ((argVal.mType->IsTypedPrimitive()) && (methodDef->HasNoThisSplat()))
  3971. {
  3972. argVal = mModule->MakeAddressable(argVal);
  3973. irArgs.push_back(argVal.mValue);
  3974. return;
  3975. }
  3976. auto thisType = methodInstance->GetParamType(-1);
  3977. PushArg(argVal, irArgs, methodDef->HasNoThisSplat(), thisType->IsPointer());
  3978. }
  3979. void BfExprEvaluator::FinishDeferredEvals(SizedArrayImpl<BfResolvedArg>& argValues)
  3980. {
  3981. for (int argIdx = 0; argIdx < argValues.size(); argIdx++)
  3982. {
  3983. auto argValue = argValues[argIdx].mTypedValue;
  3984. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  3985. {
  3986. if (!argValue)
  3987. {
  3988. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  3989. if (expr != NULL)
  3990. argValue = mModule->CreateValueFromExpression(expr);
  3991. }
  3992. }
  3993. }
  3994. }
  3995. void BfExprEvaluator::AddCallDependencies(BfMethodInstance* methodInstance)
  3996. {
  3997. if (methodInstance->mReturnType != NULL)
  3998. mModule->AddDependency(methodInstance->mReturnType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  3999. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  4000. {
  4001. auto paramType = methodInstance->GetParamType(paramIdx);
  4002. mModule->AddDependency(paramType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  4003. }
  4004. if (methodInstance->mMethodInfoEx != NULL)
  4005. {
  4006. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  4007. {
  4008. if (genericArg->IsWrappableType())
  4009. genericArg = mModule->GetWrappedStructType(genericArg);
  4010. mModule->AddDependency(genericArg, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  4011. }
  4012. }
  4013. }
  4014. //TODO: delete argumentsZ
  4015. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, const BfTypedValue& inTarget, const BfTypedValue& origTarget, BfMethodDef* methodDef, BfModuleMethodInstance moduleMethodInstance, bool bypassVirtual, SizedArrayImpl<BfResolvedArg>& argValues, bool skipThis)
  4016. {
  4017. static int sCallIdx = 0;
  4018. if (!mModule->mCompiler->mIsResolveOnly)
  4019. sCallIdx++;
  4020. int callIdx = sCallIdx;
  4021. if (callIdx == 0x0000042B)
  4022. {
  4023. NOP;
  4024. }
  4025. // Temporarily disable so we don't capture calls in params
  4026. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  4027. BfMethodInstance* methodInstance = moduleMethodInstance.mMethodInstance;
  4028. SizedArray<BfIRValue, 4> irArgs;
  4029. if ((methodDef->mIsAbstract) && (bypassVirtual))
  4030. {
  4031. mModule->Fail(StrFormat("Abstract base method '%s' cannot be invoked", mModule->MethodToString(methodInstance).c_str()), targetSrc);
  4032. }
  4033. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  4034. BfType* returnType = methodInstance->mReturnType;
  4035. /*if (returnType->IsSelf())
  4036. {
  4037. returnType = methodInstance->GetOwner();
  4038. BF_ASSERT(returnType->IsInterface());
  4039. }*/
  4040. BfTypedValue target = inTarget;
  4041. if (!skipThis)
  4042. {
  4043. if (!methodDef->mIsStatic)
  4044. {
  4045. if (!target)
  4046. {
  4047. FinishDeferredEvals(argValues);
  4048. mModule->Fail(StrFormat("An instance reference is required to %s the non-static method '%s'",
  4049. (prevBindResult.mPrevVal != NULL) ? "bind" : "invoke",
  4050. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  4051. return mModule->GetDefaultTypedValue(returnType);
  4052. }
  4053. auto prevResult = mResult;
  4054. mResult = target;
  4055. CheckResultForReading(mResult);
  4056. mResult = prevResult;
  4057. if (methodDef->mMethodType != BfMethodType_Ctor)
  4058. {
  4059. bool doAccessCheck = true;
  4060. if (target.IsThis())
  4061. {
  4062. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  4063. doAccessCheck = false;
  4064. }
  4065. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mSkipAccessCheckAttributeTypeDef)))
  4066. doAccessCheck = false;
  4067. if ((doAccessCheck) && (!isSkipCall))
  4068. mModule->EmitObjectAccessCheck(target);
  4069. }
  4070. if (((prevBindResult.mPrevVal == NULL) || (!prevBindResult.mPrevVal->mSkipThis)) &&
  4071. (!isSkipCall))
  4072. {
  4073. bool skipMutCheck = false;
  4074. if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mSkipMutCheck))
  4075. {
  4076. // If we are binding a delegate, then we will end up making a copy of the target anyway
  4077. // so we don't need to do a mutability check
  4078. skipMutCheck = true;
  4079. }
  4080. PushThis(targetSrc, target, moduleMethodInstance.mMethodInstance, irArgs, skipMutCheck);
  4081. }
  4082. }
  4083. else if ((target) && (target.mType->IsFunction()))
  4084. {
  4085. CheckResultForReading(target);
  4086. target = mModule->LoadValue(target);
  4087. auto funcType = mModule->mBfIRBuilder->MapMethod(moduleMethodInstance.mMethodInstance);
  4088. auto funcPtrType = mModule->mBfIRBuilder->GetPointerTo(funcType);
  4089. moduleMethodInstance.mFunc = mModule->mBfIRBuilder->CreateIntToPtr(target.mValue, funcPtrType);
  4090. }
  4091. else
  4092. {
  4093. mModule->CheckStaticAccess(methodInstance->mMethodInstanceGroup->mOwner);
  4094. if (target)
  4095. {
  4096. FinishDeferredEvals(argValues);
  4097. mModule->Fail(StrFormat("Method '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  4098. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  4099. return mModule->GetDefaultTypedValue(returnType);
  4100. }
  4101. }
  4102. }
  4103. if (isSkipCall)
  4104. {
  4105. FinishDeferredEvals(argValues);
  4106. mModule->EmitEnsureInstructionAt();
  4107. return mModule->GetDefaultTypedValue(returnType);
  4108. }
  4109. int argIdx = 0;
  4110. int paramIdx = 0;
  4111. BfIRValue expandedParamAlloca;
  4112. BfTypedValue expandedParamsArray;
  4113. BfType* expandedParamsElementType = NULL;
  4114. int extendedParamIdx = 0;
  4115. AddCallDependencies(methodInstance);
  4116. auto autoComplete = GetAutoComplete();
  4117. if (autoComplete != NULL)
  4118. {
  4119. // Set to false to make sure we don't capture method match info from 'params' array creation
  4120. autoComplete->mIsCapturingMethodMatchInfo = false;
  4121. }
  4122. BfScopeData* boxScopeData = mDeferScopeAlloc;
  4123. if ((boxScopeData == NULL) && (mModule->mCurMethodState != NULL))
  4124. boxScopeData = mModule->mCurMethodState->mCurScope;
  4125. bool failed = false;
  4126. while (true)
  4127. {
  4128. bool isDirectPass = false;
  4129. if (paramIdx >= (int)methodInstance->GetParamCount())
  4130. {
  4131. if (argIdx < (int)argValues.size())
  4132. {
  4133. BfAstNode* errorRef = argValues[argIdx].mExpression;
  4134. if (errorRef == NULL)
  4135. errorRef = targetSrc;
  4136. BfError* error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", (int)argValues.size() - argIdx), errorRef);
  4137. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  4138. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  4139. failed = true;
  4140. break;
  4141. }
  4142. break;
  4143. }
  4144. // Only create actual params if we're not just trying to bind the function
  4145. if ((prevBindResult.mPrevVal != NULL) && (!prevBindResult.mPrevVal->mWantsArgs))
  4146. break;
  4147. BfType* wantType = NULL;
  4148. bool wantsSplat = false;
  4149. if (expandedParamsElementType != NULL)
  4150. {
  4151. wantType = expandedParamsElementType;
  4152. }
  4153. else
  4154. {
  4155. wantsSplat = methodInstance->GetParamIsSplat(paramIdx);
  4156. if (methodInstance->IsImplicitCapture(paramIdx))
  4157. {
  4158. if (mModule->mCurMethodInstance->IsMixin())
  4159. {
  4160. // Don't bother, also- can fail on captures
  4161. }
  4162. else
  4163. {
  4164. // static int captureIdx = 0;
  4165. // captureIdx++;
  4166. // int curCaptureIdx = captureIdx;
  4167. //
  4168. // if (curCaptureIdx == 0x91)
  4169. // {
  4170. // NOP;
  4171. // }
  4172. auto lookupVal = DoImplicitArgCapture(targetSrc, methodInstance, paramIdx, failed, BfImplicitParamKind_General, origTarget);
  4173. if (lookupVal)
  4174. {
  4175. if (wantsSplat)
  4176. {
  4177. SplatArgs(lookupVal, irArgs);
  4178. }
  4179. else
  4180. {
  4181. irArgs.push_back(lookupVal.mValue);
  4182. }
  4183. }
  4184. }
  4185. paramIdx++;
  4186. continue;
  4187. }
  4188. wantType = methodInstance->GetParamType(paramIdx);
  4189. if (wantType->IsSelf())
  4190. wantType = methodInstance->GetOwner();
  4191. BfParamKind paramKind = methodInstance->GetParamKind(paramIdx);
  4192. if (paramKind == BfParamKind_Params)
  4193. {
  4194. //TODO: Check to see if it's a direct array pass
  4195. if (argIdx < (int)argValues.size())
  4196. {
  4197. auto argValue = argValues[argIdx].mTypedValue;
  4198. if ((argValue.IsParams()) /*&& (mModule->CanImplicitlyCast(argValue, wantType))*/)
  4199. isDirectPass = true;
  4200. }
  4201. if (!isDirectPass)
  4202. {
  4203. if (wantType->IsArray())
  4204. {
  4205. BfArrayType* arrayType = (BfArrayType*)wantType;
  4206. mModule->PopulateType(arrayType, BfPopulateType_DataAndMethods);
  4207. expandedParamsElementType = arrayType->mTypeGenericArguments[0];
  4208. int arrayClassSize = arrayType->mInstSize - expandedParamsElementType->mSize;
  4209. int numElements = (int)argValues.size() - argIdx;
  4210. expandedParamsArray = BfTypedValue(mModule->AllocFromType(arrayType->GetUnderlyingType(), boxScopeData, BfIRValue(), mModule->GetConstValue(numElements), 1, BfAllocFlags_None),
  4211. arrayType, false);
  4212. BfResolvedArgs resolvedArgs;
  4213. MatchConstructor(targetSrc, NULL, expandedParamsArray, arrayType, resolvedArgs, false, false);
  4214. //TODO: Assert 'length' var is at slot 1
  4215. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(expandedParamsArray.mValue, mModule->mBfIRBuilder->MapType(arrayType->mBaseType));
  4216. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  4217. if (arrayLengthBitCount == 0)
  4218. {
  4219. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", targetSrc);
  4220. return BfTypedValue();
  4221. }
  4222. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, 1);
  4223. if (arrayLengthBitCount == 64)
  4224. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue64(numElements), addr, 8);
  4225. else
  4226. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue32(numElements), addr, 4);
  4227. PushArg(expandedParamsArray, irArgs);
  4228. }
  4229. else
  4230. {
  4231. int numElements = (int)argValues.size() - argIdx;
  4232. auto genericTypeInst = wantType->ToGenericTypeInstance();
  4233. expandedParamsElementType = genericTypeInst->mTypeGenericArguments[0];
  4234. expandedParamsArray = BfTypedValue(mModule->CreateAlloca(wantType), wantType, true);
  4235. expandedParamAlloca = mModule->CreateAlloca(genericTypeInst->mTypeGenericArguments[0], true, NULL, mModule->GetConstValue(numElements));
  4236. mModule->mBfIRBuilder->CreateStore(expandedParamAlloca, mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 1));
  4237. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(numElements), mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 2));
  4238. PushArg(expandedParamsArray, irArgs);
  4239. }
  4240. continue;
  4241. }
  4242. }
  4243. }
  4244. BfAstNode* arg = NULL;
  4245. bool hadMissingArg = false;
  4246. if (argIdx < (int)argValues.size())
  4247. {
  4248. arg = argValues[argIdx].mExpression;
  4249. if ((arg == NULL) && (argValues[0].mExpression != NULL))
  4250. hadMissingArg = true;
  4251. }
  4252. else
  4253. hadMissingArg = true;
  4254. BfTypedValue argValue;
  4255. if (hadMissingArg)
  4256. {
  4257. if (expandedParamsArray)
  4258. break;
  4259. if ((argIdx >= (int) methodInstance->mDefaultValues.size()) || (!methodInstance->mDefaultValues[argIdx]))
  4260. {
  4261. BfAstNode* refNode = targetSrc;
  4262. if (argValues.size() > 0)
  4263. {
  4264. auto checkExpr = argValues.back().mExpression;
  4265. if (checkExpr != NULL)
  4266. refNode = checkExpr;
  4267. }
  4268. BfAstNode* prevNode = NULL;
  4269. if (targetSrc == NULL)
  4270. {
  4271. // We must be in BfModule::EmitCtorBody
  4272. }
  4273. else if (auto tupleExpr = BfNodeDynCastExact<BfTupleExpression>(targetSrc))
  4274. {
  4275. if (tupleExpr->mCommas.size() > 0)
  4276. prevNode = tupleExpr->mCommas.back();
  4277. else
  4278. prevNode = tupleExpr->mOpenParen;
  4279. if (tupleExpr->mCloseParen != NULL)
  4280. refNode = tupleExpr->mCloseParen;
  4281. }
  4282. else if (mModule->mParentNodeEntry != NULL)
  4283. {
  4284. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(mModule->mParentNodeEntry->mNode))
  4285. {
  4286. if (objectCreateExpr->mCommas.size() > 0)
  4287. prevNode = objectCreateExpr->mCommas.back();
  4288. else
  4289. prevNode = objectCreateExpr->mOpenToken;
  4290. if (objectCreateExpr->mCloseToken != NULL)
  4291. refNode = objectCreateExpr->mCloseToken;
  4292. if (auto newNode = BfNodeDynCast<BfNewNode>(objectCreateExpr->mNewNode))
  4293. {
  4294. if (newNode->mAllocNode == targetSrc)
  4295. refNode = targetSrc;
  4296. }
  4297. }
  4298. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  4299. {
  4300. if (invokeExpr->mCommas.size() > 0)
  4301. prevNode = invokeExpr->mCommas.back();
  4302. else
  4303. prevNode = invokeExpr->mOpenParen;
  4304. if (invokeExpr->mCloseParen != NULL)
  4305. refNode = invokeExpr->mCloseParen;
  4306. }
  4307. }
  4308. if ((autoComplete != NULL) && (prevNode != NULL))
  4309. autoComplete->CheckEmptyStart(prevNode, wantType);
  4310. BfError* error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", methodInstance->GetParamCount() - paramIdx), refNode);
  4311. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  4312. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  4313. failed = true;
  4314. break;
  4315. }
  4316. auto foreignDefaultVal = methodInstance->mDefaultValues[argIdx];
  4317. auto foreignConst = methodInstance->GetOwner()->mConstHolder->GetConstant(methodInstance->mDefaultValues[argIdx]);
  4318. if (foreignConst->mConstType == BfConstType_AggZero)
  4319. {
  4320. // Allow this
  4321. }
  4322. else if (foreignConst->mTypeCode == BfTypeCode_NullPtr)
  4323. {
  4324. if (wantType->IsNullable())
  4325. {
  4326. argValue = mModule->GetDefaultTypedValue(wantType, false, BfDefaultValueKind_Addr);
  4327. }
  4328. }
  4329. if (!argValue)
  4330. {
  4331. argValue = mModule->GetTypedValueFromConstant(foreignConst, methodInstance->GetOwner()->mConstHolder, wantType);
  4332. }
  4333. }
  4334. else
  4335. {
  4336. argValue = argValues[argIdx].mTypedValue;
  4337. if ((argValue.IsParams()) && (!isDirectPass))
  4338. {
  4339. BfAstNode* refNode = argValues[argIdx].mExpression;
  4340. if (auto unaryOperatorExpr = BfNodeDynCast<BfUnaryOperatorExpression>(refNode))
  4341. refNode = unaryOperatorExpr->mOpToken;
  4342. mModule->Warn(0, "Unused 'params' expression", refNode);
  4343. }
  4344. if (wantType->IsMethodRef())
  4345. {
  4346. auto expr = argValues[argIdx].mExpression;
  4347. if (expr != NULL)
  4348. SetMethodElementType(expr);
  4349. if (!argValue)
  4350. argValue = mModule->CreateValueFromExpression(BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression), wantType, BfEvalExprFlags_NoCast);
  4351. // Add any implicit captures now
  4352. auto methodRefType = (BfMethodRefType*)wantType;
  4353. BfMethodInstance* useMethodInstance = methodRefType->mMethodRef;
  4354. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  4355. {
  4356. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  4357. auto lookupVal = DoImplicitArgCapture(argValues[argIdx].mExpression, useMethodInstance, paramIdx, failed, BfImplicitParamKind_General, argValue);
  4358. if (lookupVal)
  4359. {
  4360. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  4361. SplatArgs(lookupVal, irArgs);
  4362. else if (lookupVal.mType->IsComposite())
  4363. {
  4364. irArgs.push_back(lookupVal.mValue);
  4365. }
  4366. else
  4367. irArgs.push_back(lookupVal.mValue);
  4368. }
  4369. }
  4370. paramIdx++;
  4371. argIdx++;
  4372. continue;
  4373. }
  4374. else
  4375. {
  4376. BfParamKind paramKind = BfParamKind_Normal;
  4377. if (paramIdx < methodInstance->GetParamCount())
  4378. paramKind = methodInstance->GetParamKind(paramIdx);
  4379. argValues[argIdx].mExpectedType = wantType;
  4380. argValue = ResolveArgValue(argValues[argIdx], wantType, NULL, paramKind);
  4381. }
  4382. }
  4383. if (!argValue)
  4384. {
  4385. failed = true;
  4386. }
  4387. if ((argValue) && (arg != NULL))
  4388. {
  4389. argValue = mModule->Cast(arg, argValue, wantType);
  4390. if (!argValue)
  4391. {
  4392. failed = true;
  4393. }
  4394. else if ((wantType->IsComposite()) && (!expandedParamsArray))
  4395. {
  4396. // We need to make a temp and get the addr of that
  4397. if ((!wantsSplat) && (!argValue.IsValuelessType()) && (!argValue.IsAddr()))
  4398. {
  4399. argValue = mModule->MakeAddressable(argValue);
  4400. }
  4401. }
  4402. else if (!wantType->IsRef())
  4403. argValue = mModule->LoadValue(argValue);
  4404. }
  4405. if (expandedParamsArray)
  4406. {
  4407. if (argValue)
  4408. {
  4409. if (expandedParamAlloca)
  4410. {
  4411. argValue = mModule->LoadValue(argValue);
  4412. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamAlloca, extendedParamIdx);
  4413. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, addr, argValue.mType->mAlign);
  4414. }
  4415. else
  4416. {
  4417. argValue = mModule->LoadValue(argValue);
  4418. auto firstAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 1);
  4419. auto indexedAddr = mModule->CreateIndexedValue(argValue.mType, firstAddr, extendedParamIdx);
  4420. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, indexedAddr, argValue.mType->mAlign);
  4421. }
  4422. }
  4423. extendedParamIdx++;
  4424. }
  4425. else
  4426. {
  4427. if ((paramIdx == 0) && (methodInstance->GetParamName(paramIdx) == "this") && (wantType->IsPointer()))
  4428. {
  4429. auto underlyingType = wantType->GetUnderlyingType();
  4430. mModule->PopulateType(underlyingType, BfPopulateType_Data);
  4431. if (underlyingType->IsValuelessType())
  4432. {
  4433. // We don't actually pass a 'this' pointer for mut methods on valueless structs
  4434. argIdx++;
  4435. paramIdx++;
  4436. continue;
  4437. }
  4438. }
  4439. if (argValue)
  4440. {
  4441. if (wantsSplat)
  4442. SplatArgs(argValue, irArgs);
  4443. else
  4444. PushArg(argValue, irArgs, true, false);
  4445. }
  4446. paramIdx++;
  4447. }
  4448. argIdx++;
  4449. }
  4450. if (failed)
  4451. {
  4452. // Process the other unused arguments
  4453. while (argIdx < argValues.size())
  4454. {
  4455. mModule->AssertErrorState();
  4456. auto argValue = argValues[argIdx].mTypedValue;
  4457. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval | BfArgFlag_VariableDeclaration)) != 0)
  4458. {
  4459. if (!argValue)
  4460. {
  4461. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  4462. if (expr != NULL)
  4463. argValue = mModule->CreateValueFromExpression(expr);
  4464. }
  4465. }
  4466. argIdx++;
  4467. }
  4468. mModule->AssertErrorState();
  4469. return mModule->GetDefaultTypedValue(returnType, false, BfDefaultValueKind_Addr);
  4470. }
  4471. prevBindResult.Restore();
  4472. if (!methodDef->mIsStatic)
  4473. {
  4474. if ((methodInstance->GetOwner()->IsInterface()) && (!target.mType->IsGenericParam()) && (!target.mType->IsConcreteInterfaceType()))
  4475. {
  4476. if (methodInstance->mVirtualTableIdx == -1)
  4477. {
  4478. mModule->PopulateType(methodInstance->GetOwner(), BfPopulateType_DataAndMethods);
  4479. }
  4480. if (methodInstance->mVirtualTableIdx == -1)
  4481. {
  4482. if (methodInstance->mMethodDef->mIsConcrete)
  4483. {
  4484. 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);
  4485. }
  4486. else if (methodInstance->HasSelf())
  4487. {
  4488. 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);
  4489. }
  4490. else
  4491. {
  4492. if ((bypassVirtual) && (mModule->mCurTypeInstance->IsInterface()))
  4493. {
  4494. // Allow a base call to be defined
  4495. }
  4496. else if ((!mModule->mCurMethodInstance->mIsUnspecialized))
  4497. {
  4498. // Compiler error?
  4499. mModule->Fail(StrFormat("Unable to dynamically dispatch '%s'", mModule->MethodToString(methodInstance).c_str()), targetSrc);
  4500. }
  4501. //BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  4502. }
  4503. if (mFunctionBindResult != NULL)
  4504. {
  4505. mFunctionBindResult->mMethodInstance = methodInstance;
  4506. mFunctionBindResult->mTarget = target;
  4507. mFunctionBindResult->mFunc = moduleMethodInstance.mFunc;
  4508. for (auto arg : irArgs)
  4509. mFunctionBindResult->mIRArgs.push_back(arg);
  4510. }
  4511. return mModule->GetDefaultTypedValue(returnType);
  4512. }
  4513. }
  4514. }
  4515. else
  4516. {
  4517. //BF_ASSERT(!methodInstance->GetOwner()->IsInterface());
  4518. }
  4519. if (target.mType != NULL)
  4520. {
  4521. // When we call a method from a static ctor, that method could access static fields so we need to make sure
  4522. // the type has been initialized
  4523. auto targetTypeInst = target.mType->ToTypeInstance();
  4524. if (targetTypeInst != NULL)
  4525. mModule->CheckStaticAccess(targetTypeInst);
  4526. }
  4527. auto func = moduleMethodInstance.mFunc;
  4528. BfTypedValue result = CreateCall(methodInstance, func, bypassVirtual, irArgs);
  4529. if ((result.mType != NULL) && (result.mType->IsVar()) && (mModule->mCompiler->mIsResolveOnly))
  4530. mModule->Fail("Method return type reference failed to resolve", targetSrc);
  4531. return result;
  4532. }
  4533. BfTypedValue BfExprEvaluator::MatchConstructor(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, BfTypeInstance* targetType, BfResolvedArgs& argValues, bool callCtorBodyOnly, bool allowAppendAlloc, BfTypedValue* appendIndexValue)
  4534. {
  4535. // Temporarily disable so we don't capture calls in params
  4536. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  4537. static int sCtorCount = 0;
  4538. sCtorCount++;
  4539. BfMethodMatcher methodMatcher(targetSrc, mModule, "", argValues.mResolvedArgs, NULL);
  4540. BfTypeVector typeGenericArguments;
  4541. auto curTypeInst = targetType;
  4542. auto curTypeDef = targetType->mTypeDef;
  4543. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  4544. auto activeTypeDef = mModule->GetActiveTypeDef();
  4545. bool isFailurePass = false;
  4546. for (int pass = 0; pass < 2; pass++)
  4547. {
  4548. isFailurePass = pass == 1;
  4549. curTypeDef->PopulateMemberSets();
  4550. BfMethodDef* nextMethodDef = NULL;
  4551. BfMemberSetEntry* entry;
  4552. if (curTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  4553. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  4554. while (nextMethodDef != NULL)
  4555. {
  4556. auto checkMethod = nextMethodDef;
  4557. nextMethodDef = nextMethodDef->mNextWithSameName;
  4558. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  4559. continue; // Don't match private default ctor if there's a user-defined one
  4560. if (checkMethod->mIsStatic)
  4561. continue;
  4562. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  4563. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, activeTypeDef)))
  4564. continue;
  4565. auto checkProt = checkMethod->mProtection;
  4566. if (!isFailurePass)
  4567. {
  4568. if (callCtorBodyOnly)
  4569. {
  4570. // We're calling the base class's ctor from a derived class
  4571. if (checkProt == BfProtection_Private)
  4572. continue;
  4573. }
  4574. else
  4575. {
  4576. if (checkProt == BfProtection_Protected) // Treat protected constructors as private
  4577. checkProt = BfProtection_Private;
  4578. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkProt, curTypeInst))
  4579. continue;
  4580. }
  4581. }
  4582. methodMatcher.CheckMethod(curTypeInst, checkMethod, isFailurePass);
  4583. }
  4584. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  4585. break;
  4586. }
  4587. if (methodMatcher.mBestMethodDef == NULL)
  4588. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  4589. if (methodMatcher.mBestMethodDef == NULL)
  4590. {
  4591. mModule->Fail("No constructor available", targetSrc);
  4592. return BfTypedValue();
  4593. }
  4594. auto methodDef = methodMatcher.mBestMethodDef;
  4595. if (mModule->mCompiler->mResolvePassData != NULL)
  4596. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetSrc, curTypeInst->mTypeDef, methodDef);
  4597. BfAutoComplete* autoComplete = GetAutoComplete();
  4598. if (autoComplete != NULL)
  4599. {
  4600. BfTypeInstance* resolvedTypeInstance = target.mType->ToTypeInstance();
  4601. auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(methodDef->mMethodDeclaration);
  4602. if ((autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(targetSrc)) && (!BfNodeIsA<BfDelegateBindExpression>(targetSrc)))
  4603. {
  4604. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  4605. (autoComplete->mDefProp == NULL)
  4606. && ((autoComplete->mDefType == NULL) || (autoComplete->mDefType == resolvedTypeInstance->mTypeDef)))
  4607. {
  4608. // Do we need to do this mDefType setting? If we do, then make sure we only get the element type of generics and such
  4609. //autoComplete->mDefType = resolvedTypeInstance->mTypeDef;
  4610. if (ctorDecl != NULL)
  4611. autoComplete->SetDefinitionLocation(ctorDecl->mThisToken, true);
  4612. else if (resolvedTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  4613. autoComplete->SetDefinitionLocation(resolvedTypeInstance->mTypeDef->mTypeDeclaration->mNameNode, true);
  4614. }
  4615. }
  4616. }
  4617. // There should always be a constructor
  4618. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  4619. auto moduleMethodInstance = mModule->GetMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher.mBestMethodGenericArguments);
  4620. BfConstructorDeclaration* ctorDecl = (BfConstructorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration;
  4621. if ((methodMatcher.mBestMethodDef->mHasAppend) && (targetType->IsObject()))
  4622. {
  4623. if (!allowAppendAlloc)
  4624. {
  4625. if (mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration == NULL)
  4626. mModule->Fail("Constructors with append allocations cannot be called from a default constructor. Considering adding an explicit default constructor with the [AllowAppend] specifier.", targetSrc);
  4627. else
  4628. mModule->Fail("Constructors with append allocations cannot be called from a constructor without [AllowAppend] specified.", targetSrc);
  4629. }
  4630. else
  4631. {
  4632. BfResolvedArg resolvedArg;
  4633. if (appendIndexValue != NULL)
  4634. {
  4635. resolvedArg.mTypedValue = *appendIndexValue;
  4636. }
  4637. else
  4638. {
  4639. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  4640. auto intPtrRefType = mModule->CreateRefType(intPtrType);
  4641. if (target.mValue.IsFake())
  4642. {
  4643. resolvedArg.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), intPtrType);
  4644. }
  4645. else
  4646. {
  4647. // auto thisVal = target;
  4648. // BfIRValue intPtrVal = mModule->CreateAlloca(intPtrType);
  4649. // auto intPtrThisVal = mModule->mBfIRBuilder->CreatePtrToInt(thisVal.mValue, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  4650. // auto curValPtr = mModule->mBfIRBuilder->CreateAdd(intPtrThisVal, mModule->GetConstValue(targetType->mInstSize, intPtrType));
  4651. // mModule->mBfIRBuilder->CreateStore(curValPtr, intPtrVal);
  4652. // resolvedArg.mTypedValue = BfTypedValue(intPtrVal, intPtrRefType);
  4653. BF_FATAL("Bad");
  4654. }
  4655. }
  4656. methodMatcher.mArguments.Insert(0, resolvedArg);
  4657. }
  4658. }
  4659. if (isFailurePass)
  4660. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  4661. prevBindResult.Restore();
  4662. return CreateCall(methodMatcher.mTargetSrc, target, BfTypedValue(), methodMatcher.mBestMethodDef, moduleMethodInstance, false, methodMatcher.mArguments);
  4663. }
  4664. static int sInvocationIdx = 0;
  4665. BfTypedValue BfExprEvaluator::ResolveArgValue(BfResolvedArg& resolvedArg, BfType* wantType, BfTypedValue* receivingValue, BfParamKind paramKind)
  4666. {
  4667. BfTypedValue argValue = resolvedArg.mTypedValue;
  4668. if ((resolvedArg.mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  4669. {
  4670. if ((!argValue) || (argValue.mValue.IsFake()) || (resolvedArg.mWantsRecalc))
  4671. {
  4672. resolvedArg.mWantsRecalc = false;
  4673. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  4674. if (expr != NULL)
  4675. {
  4676. BfExprEvaluator exprEvaluator(mModule);
  4677. exprEvaluator.mReceivingValue = receivingValue;
  4678. BfEvalExprFlags flags = BfEvalExprFlags_NoCast;
  4679. if ((paramKind == BfParamKind_Params) || (paramKind == BfParamKind_DelegateParam))
  4680. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowParamsExpr);
  4681. // if ((mModule->mCurMethodInstance->mHadGenericDelegateParams) && (!mModule->mCurMethodInstance->mIsUnspecialized))
  4682. // flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowParamsExpr);
  4683. argValue = mModule->CreateValueFromExpression(exprEvaluator, expr, wantType, flags);
  4684. // if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) != 0)
  4685. // {
  4686. // if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  4687. // {
  4688. // auto localVar = exprEvaluator.mResultLocalVar;
  4689. // int fieldIdx = mResultLocalVarField - 1;
  4690. // auto methodState = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  4691. // if (localVar->mCompositeCount >= 0)
  4692. // {
  4693. // for (int compositeIdx = 0; compositeIdx < localVar->mCompositeCount; compositeIdx++)
  4694. // {
  4695. // BfResolvedArg compositeResolvedArg;
  4696. // auto compositeLocalVar = methodState->mLocals[localVar->mLocalVarIdx + compositeIdx + 1];
  4697. // auto argValue = exprEvaluator.LoadLocal(compositeLocalVar);
  4698. // if (argValue)
  4699. // {
  4700. // if (argValue.mType->IsRef())
  4701. // argValue.mKind = BfTypedValueKind_Value;
  4702. // else if (!argValue.mType->IsStruct())
  4703. // argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  4704. // }
  4705. // resolvedArg.mTypedValue = argValue;
  4706. // resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_FromParamComposite);
  4707. // return resolvedArg.mTypedValue;
  4708. // }
  4709. // }
  4710. // }
  4711. // }
  4712. if ((argValue) && (argValue.mType != wantType))
  4713. {
  4714. if ((mDeferScopeAlloc != NULL) && (wantType == mModule->mContext->mBfObjectType))
  4715. {
  4716. BfAllocTarget allocTarget(mDeferScopeAlloc);
  4717. argValue = mModule->BoxValue(expr, argValue, wantType, allocTarget);
  4718. }
  4719. else
  4720. argValue = mModule->Cast(expr, argValue, wantType);
  4721. }
  4722. }
  4723. }
  4724. }
  4725. else if ((resolvedArg.mArgFlags & (BfArgFlag_DeferredValue)) != 0)
  4726. {
  4727. // We should have already had an error on the first call
  4728. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, mModule->mHadBuildError);
  4729. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  4730. BF_ASSERT(expr != NULL);
  4731. argValue = mModule->CreateValueFromExpression(expr, wantType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr));
  4732. if (argValue)
  4733. argValue = mModule->Cast(expr, argValue, wantType);
  4734. }
  4735. else if ((resolvedArg.mArgFlags & (BfArgFlag_UntypedDefault)) != 0)
  4736. {
  4737. argValue = mModule->GetDefaultTypedValue(wantType);
  4738. }
  4739. else if ((resolvedArg.mArgFlags & (BfArgFlag_VariableDeclaration)) != 0)
  4740. {
  4741. auto variableDeclaration = BfNodeDynCast<BfVariableDeclaration>(resolvedArg.mExpression);
  4742. auto variableType = wantType;
  4743. bool isLet = variableDeclaration->mTypeRef->IsExact<BfLetTypeReference>();
  4744. bool isVar = variableDeclaration->mTypeRef->IsExact<BfVarTypeReference>();
  4745. if ((!isLet) && (!isVar))
  4746. {
  4747. mModule->Fail("Only 'ref' or 'var' variables can be declared in method arguments", variableDeclaration);
  4748. auto autoComplete = GetAutoComplete();
  4749. if (autoComplete != NULL)
  4750. autoComplete->CheckTypeRef(variableDeclaration->mTypeRef, true, true);
  4751. }
  4752. if (wantType->IsRef())
  4753. {
  4754. auto refType = (BfRefType*)wantType;
  4755. variableType = refType->mElementType;
  4756. }
  4757. if (variableDeclaration->mInitializer != NULL)
  4758. {
  4759. mModule->Fail("Initializers cannot be used when declaring variables for 'out' parameters", variableDeclaration->mEqualsNode);
  4760. mModule->CreateValueFromExpression(variableDeclaration->mInitializer, variableType, BfEvalExprFlags_NoCast);
  4761. }
  4762. if (variableDeclaration->mNameNode == NULL)
  4763. return argValue;
  4764. BfLocalVariable* localVar = new BfLocalVariable();
  4765. localVar->mName = variableDeclaration->mNameNode->ToString();
  4766. localVar->mNameNode = BfNodeDynCast<BfIdentifierNode>(variableDeclaration->mNameNode);
  4767. localVar->mResolvedType = variableType;
  4768. if (!variableType->IsValuelessType())
  4769. localVar->mAddr = mModule->CreateAlloca(variableType);
  4770. localVar->mIsReadOnly = isLet;
  4771. localVar->mReadFromId = 0;
  4772. localVar->mWrittenToId = 0;
  4773. localVar->mIsAssigned = true;
  4774. mModule->CheckVariableDef(localVar);
  4775. localVar->Init();
  4776. mModule->AddLocalVariableDef(localVar, true);
  4777. CheckVariableDeclaration(resolvedArg.mExpression, false, false, false);
  4778. argValue = BfTypedValue(localVar->mAddr, mModule->CreateRefType(variableType, BfRefType::RefKind_Out));
  4779. //argValue = mModule->GetDefaultTypedValue(wantType);
  4780. }
  4781. return argValue;
  4782. }
  4783. BfTypedValue BfExprEvaluator::CheckEnumCreation(BfAstNode* targetSrc, BfTypeInstance* enumType, const StringImpl& caseName, BfResolvedArgs& argValues)
  4784. {
  4785. auto activeTypeDef = mModule->GetActiveTypeDef();
  4786. mModule->mBfIRBuilder->PopulateType(enumType);
  4787. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  4788. // if (resolvePassData != NULL)
  4789. // {
  4790. // if (mModule->mParentNodeEntry != NULL)
  4791. // {
  4792. // if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  4793. // {
  4794. // if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  4795. // {
  4796. // BfAstNode* dotNode = memberRefExpr->mDotToken;
  4797. // BfAstNode* nameNode = targetSrc;
  4798. // String filter;
  4799. // auto autoComplete = resolvePassData->mAutoComplete;
  4800. // if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(dotNode, nameNode, filter)))
  4801. // autoComplete->AddEnumTypeMembers(enumType, caseName, false, enumType == mModule->mCurTypeInstance);
  4802. // }
  4803. // }
  4804. // }
  4805. // }
  4806. for (int fieldIdx = 0; fieldIdx < (int)enumType->mFieldInstances.size(); fieldIdx++)
  4807. {
  4808. auto fieldInstance = &enumType->mFieldInstances[fieldIdx];
  4809. auto fieldDef = fieldInstance->GetFieldDef();
  4810. if (fieldDef == NULL)
  4811. continue;
  4812. if ((fieldInstance->mIsEnumPayloadCase) && (fieldDef->mName == caseName))
  4813. {
  4814. if ((!enumType->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, mModule)) ||
  4815. (!enumType->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  4816. continue;
  4817. auto autoComplete = GetAutoComplete();
  4818. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  4819. {
  4820. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  4821. methodMatchEntry.mPayloadEnumField = fieldInstance;
  4822. methodMatchEntry.mTypeInstance = enumType;
  4823. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  4824. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  4825. }
  4826. if (resolvePassData != NULL)
  4827. {
  4828. BfAstNode* nameNode = targetSrc;
  4829. if (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field)
  4830. resolvePassData->HandleFieldReference(nameNode, enumType->mTypeDef, fieldDef);
  4831. }
  4832. BfIRValue enumValue;
  4833. BfTypedValue result;
  4834. if ((mReceivingValue != NULL) && (mReceivingValue->mType == enumType) && (mReceivingValue->IsAddr()))
  4835. {
  4836. result = *mReceivingValue;
  4837. mReceivingValue = NULL;
  4838. enumValue = result.mValue;
  4839. }
  4840. else
  4841. {
  4842. mResultIsTempComposite = true;
  4843. enumValue = mModule->CreateAlloca(enumType);
  4844. result = BfTypedValue(enumValue, fieldInstance->mOwner, BfTypedValueKind_TempAddr);
  4845. }
  4846. BF_ASSERT(fieldInstance->mResolvedType->IsTuple());
  4847. auto tupleType = (BfTupleType*)fieldInstance->mResolvedType;
  4848. mModule->mBfIRBuilder->PopulateType(tupleType);
  4849. BfIRValue fieldPtr;
  4850. BfIRValue tuplePtr;
  4851. if (!tupleType->IsValuelessType())
  4852. {
  4853. fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, 1);
  4854. auto tuplePtrType = mModule->CreatePointerType(tupleType);
  4855. auto mappedPtrType = mModule->mBfIRBuilder->MapType(tuplePtrType);
  4856. tuplePtr = mModule->mBfIRBuilder->CreateBitCast(fieldPtr, mappedPtrType);
  4857. }
  4858. for (int tupleFieldIdx = 0; tupleFieldIdx < (int)tupleType->mFieldInstances.size(); tupleFieldIdx++)
  4859. {
  4860. auto tupleFieldInstance = &tupleType->mFieldInstances[tupleFieldIdx];
  4861. auto resolvedFieldType = tupleFieldInstance->GetResolvedType();
  4862. if (tupleFieldIdx >= argValues.mResolvedArgs.size())
  4863. {
  4864. BfAstNode* refNode = targetSrc;
  4865. BfAstNode* prevNode = NULL;
  4866. if (mModule->mParentNodeEntry != NULL)
  4867. {
  4868. if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  4869. {
  4870. if (invokeExpr->mCloseParen != NULL)
  4871. refNode = invokeExpr->mCloseParen;
  4872. }
  4873. }
  4874. BfError* error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", tupleType->mFieldInstances.size() - (int)argValues.mArguments->size()), refNode);
  4875. if (error != NULL)
  4876. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  4877. break;
  4878. }
  4879. BfTypedValue receivingValue;
  4880. BfIRValue tupleFieldPtr;
  4881. if (tuplePtr)
  4882. {
  4883. tupleFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(tuplePtr, 0, tupleFieldInstance->mDataIdx);
  4884. receivingValue = BfTypedValue(tupleFieldPtr, tupleFieldInstance->mResolvedType, true);
  4885. }
  4886. auto argValue = ResolveArgValue(argValues.mResolvedArgs[tupleFieldIdx], resolvedFieldType, &receivingValue);
  4887. // Used receiving value?
  4888. if (argValue.mValue == receivingValue.mValue)
  4889. continue;
  4890. if ((!argValue) || (argValue.IsValuelessType()))
  4891. continue;
  4892. argValue = mModule->AggregateSplat(argValue);
  4893. argValues.mResolvedArgs[tupleFieldIdx].mExpectedType = resolvedFieldType;
  4894. if ((argValues.mResolvedArgs[tupleFieldIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt)) != 0)
  4895. {
  4896. auto expr = BfNodeDynCast<BfExpression>(argValues.mResolvedArgs[tupleFieldIdx].mExpression);
  4897. BF_ASSERT(expr != NULL);
  4898. argValue = mModule->CreateValueFromExpression(expr, resolvedFieldType);
  4899. }
  4900. if (argValue)
  4901. {
  4902. // argValue can have a value even if tuplePtr does not have a value. This can happen if we are assigning to a (void) tuple,
  4903. // but we have a value that needs to be attempted to be casted to void
  4904. argValue = mModule->Cast(argValues.mResolvedArgs[tupleFieldIdx].mExpression, argValue, resolvedFieldType);
  4905. if (tupleFieldPtr)
  4906. {
  4907. argValue = mModule->LoadValue(argValue);
  4908. if (argValue)
  4909. mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, tupleFieldPtr, resolvedFieldType->mAlign);
  4910. }
  4911. }
  4912. }
  4913. if ((intptr)argValues.mResolvedArgs.size() > tupleType->mFieldInstances.size())
  4914. {
  4915. BfAstNode* errorRef = argValues.mResolvedArgs[tupleType->mFieldInstances.size()].mExpression;
  4916. if (errorRef == NULL)
  4917. errorRef = targetSrc;
  4918. BfError* error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", argValues.mResolvedArgs.size() - tupleType->mFieldInstances.size()), errorRef);
  4919. if (error != NULL)
  4920. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  4921. }
  4922. //auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, 2);
  4923. auto dscrType = enumType->GetDiscriminatorType();
  4924. auto dscrField = &enumType->mFieldInstances.back();
  4925. int tagIdx = -fieldInstance->mDataIdx - 1;
  4926. auto dscFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, dscrField->mDataIdx);
  4927. mModule->mBfIRBuilder->CreateAlignedStore(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), dscFieldPtr, 4);
  4928. return result;
  4929. }
  4930. }
  4931. return BfTypedValue();
  4932. }
  4933. BfTypedValue BfExprEvaluator::MatchMethod(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, bool allowImplicitThis, bool bypassVirtual, const StringImpl& methodName,
  4934. BfResolvedArgs& argValues, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments, BfCheckedKind checkedKind)
  4935. {
  4936. BP_ZONE("MatchMethod");
  4937. if (bypassVirtual)
  4938. {
  4939. // "bypassVirtual" means that we know for sure that the target is EXACTLY the specified target type,
  4940. // not derived from (or implementing) the target type. This cannot apply to interfaces.
  4941. BF_ASSERT(!target.mType->IsInterface());
  4942. }
  4943. auto origTarget = target;
  4944. if (mFunctionBindResult != NULL)
  4945. {
  4946. BF_ASSERT(!mFunctionBindResult->mOrigTarget);
  4947. mFunctionBindResult->mOrigTarget = origTarget;
  4948. }
  4949. if (target)
  4950. {
  4951. if ((!target.mType->IsGenericParam()) && (!target.IsSplat()) && (!target.mType->IsVar()))
  4952. target = MakeCallableTarget(targetSrc, target);
  4953. }
  4954. // static int sCallIdx = 0;
  4955. // if (!mModule->mCompiler->mIsResolveOnly)
  4956. // sCallIdx++;
  4957. // int callIdx = sCallIdx;
  4958. // if (callIdx == 118)
  4959. // {
  4960. // NOP;
  4961. // }
  4962. // Temporarily disable so we don't capture calls in params
  4963. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  4964. sInvocationIdx++;
  4965. bool wantCtor = methodName.IsEmpty();
  4966. BfAutoComplete::MethodMatchInfo* restoreCapturingMethodMatchInfo = NULL;
  4967. auto autoComplete = GetAutoComplete();
  4968. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  4969. {
  4970. if ((!targetSrc->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) ||
  4971. ((autoComplete->mMethodMatchInfo->mInvocationSrcIdx != -1) && (autoComplete->mMethodMatchInfo->mInvocationSrcIdx != targetSrc->GetSrcStart())))
  4972. {
  4973. autoComplete->mIsCapturingMethodMatchInfo = false;
  4974. restoreCapturingMethodMatchInfo = autoComplete->mMethodMatchInfo;
  4975. }
  4976. }
  4977. OnScopeExit doRestoreAutocomplete([&]()
  4978. {
  4979. if ((restoreCapturingMethodMatchInfo != NULL) && (autoComplete->mMethodMatchInfo == restoreCapturingMethodMatchInfo))
  4980. autoComplete->mIsCapturingMethodMatchInfo = true;
  4981. });
  4982. /*if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  4983. autoComplete->mIsCapturingMethodMatchInfo = false;*/
  4984. bool isUnboundCall = false;
  4985. if (target.mType != NULL)
  4986. {
  4987. if (target.mType->IsGenericParam())
  4988. {
  4989. auto genericParamTarget = (BfGenericParamType*) target.mType;
  4990. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  4991. isUnboundCall = (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0;
  4992. if (isUnboundCall)
  4993. {
  4994. if (mModule->mCurMethodInstance->mIsUnspecialized)
  4995. {
  4996. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  4997. target.mType = varType;
  4998. }
  4999. }
  5000. }
  5001. else if (target.mType->IsVar())
  5002. isUnboundCall = true;
  5003. }
  5004. /*if (mPrefixedAttributeState != NULL)
  5005. {
  5006. auto customAttr = mPrefixedAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  5007. if (customAttr != NULL)
  5008. {
  5009. if (!mModule->IsInGeneric())
  5010. {
  5011. mModule->Fail("'Unbound' can only be used within generics");
  5012. }
  5013. mPrefixedAttributeState->mUsed = true;
  5014. isUnboundCall = true;
  5015. }
  5016. }*/
  5017. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  5018. {
  5019. auto customAttr = mModule->mAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  5020. if (customAttr != NULL)
  5021. {
  5022. if (!mModule->IsInGeneric())
  5023. {
  5024. mModule->Fail("'Unbound' can only be used within generics");
  5025. }
  5026. mModule->mAttributeState->mUsed = true;
  5027. isUnboundCall = true;
  5028. }
  5029. }
  5030. if (isUnboundCall)
  5031. {
  5032. if (mModule->mCurMethodInstance->mIsUnspecialized)
  5033. {
  5034. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  5035. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  5036. {
  5037. if ((argValues.mResolvedArgs[argIdx].mArgFlags & BfArgFlag_DeferredEval) != 0)
  5038. {
  5039. mModule->CreateValueFromExpression((*argValues.mArguments)[argIdx], varType);
  5040. }
  5041. }
  5042. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  5043. }
  5044. }
  5045. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isUnboundCall);
  5046. auto targetType = target.mType;
  5047. BfTypeDef* curTypeDef = NULL;
  5048. BfTypeInstance* targetTypeInst = NULL;
  5049. bool checkNonStatic = true;
  5050. if (target)
  5051. {
  5052. if (targetType->IsVar())
  5053. return mModule->GetDefaultTypedValue(targetType);
  5054. targetTypeInst = targetType->ToTypeInstance();
  5055. if (targetTypeInst != NULL)
  5056. curTypeDef = targetTypeInst->mTypeDef;
  5057. }
  5058. else if (targetType != NULL) // Static targeted
  5059. {
  5060. if (targetType->IsWrappableType())
  5061. {
  5062. targetTypeInst = mModule->GetWrappedStructType(targetType);
  5063. }
  5064. else if (targetType->IsGenericParam())
  5065. {
  5066. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)targetType);
  5067. if (genericParamInstance->mTypeConstraint != NULL)
  5068. targetTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  5069. if (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var)
  5070. {
  5071. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  5072. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  5073. }
  5074. }
  5075. else
  5076. targetTypeInst = targetType->ToTypeInstance();
  5077. if (targetTypeInst == NULL)
  5078. {
  5079. //mModule->Fail("No static methods available", targetSrc);
  5080. //return BfTypedValue();
  5081. }
  5082. else
  5083. {
  5084. curTypeDef = targetTypeInst->mTypeDef;
  5085. checkNonStatic = false;
  5086. }
  5087. }
  5088. else // Current scopeData
  5089. {
  5090. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef) && (mModule->mCurMethodInstance->mMethodInfoEx->mForeignType->IsInterface()))
  5091. {
  5092. targetTypeInst = mModule->mCurMethodInstance->mMethodInfoEx->mForeignType;
  5093. curTypeDef = targetTypeInst->mTypeDef;
  5094. checkNonStatic = true;
  5095. target = mModule->GetThis();
  5096. //target.mType = targetTypeInst;
  5097. }
  5098. else
  5099. {
  5100. curTypeDef = mModule->mCurTypeInstance->mTypeDef;
  5101. targetTypeInst = mModule->mCurTypeInstance;
  5102. if (mModule->mCurMethodState == NULL)
  5103. {
  5104. checkNonStatic = false;
  5105. }
  5106. else if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  5107. {
  5108. checkNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  5109. }
  5110. else
  5111. checkNonStatic = !mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  5112. }
  5113. }
  5114. bool isIndirectMethodCall = false;
  5115. BfType* lookupType = targetType;
  5116. BfTypeInstance* lookupTypeInst = targetTypeInst;
  5117. if (targetType != NULL)
  5118. {
  5119. lookupType = BindGenericType(targetSrc, targetType);
  5120. if (lookupType->IsGenericParam())
  5121. lookupTypeInst = NULL;
  5122. }
  5123. BfMethodDef* methodDef = NULL;
  5124. BfTypeVector checkMethodGenericArguments;
  5125. BfTypeInstance* curTypeInst = targetTypeInst;
  5126. BfMethodMatcher methodMatcher(targetSrc, mModule, methodName, argValues.mResolvedArgs, methodGenericArguments);
  5127. methodMatcher.mCheckedKind = checkedKind;
  5128. methodMatcher.mAllowImplicitThis = allowImplicitThis;
  5129. methodMatcher.mAllowStatic = !target.mValue;
  5130. methodMatcher.mAllowNonStatic = !methodMatcher.mAllowStatic;
  5131. if (allowImplicitThis)
  5132. {
  5133. if (mModule->mCurMethodState == NULL)
  5134. {
  5135. methodMatcher.mAllowStatic = true;
  5136. methodMatcher.mAllowNonStatic = false;
  5137. }
  5138. else if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  5139. {
  5140. methodMatcher.mAllowNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  5141. methodMatcher.mAllowStatic = true;
  5142. }
  5143. else
  5144. {
  5145. if (!mModule->mCurMethodInstance->mMethodDef->mIsStatic)
  5146. methodMatcher.mAllowNonStatic = true;
  5147. methodMatcher.mAllowStatic = true;
  5148. if (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod)
  5149. {
  5150. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  5151. methodMatcher.mAllowNonStatic = !rootMethodState->mMethodInstance->mMethodDef->mIsStatic;
  5152. }
  5153. }
  5154. }
  5155. if (methodName == BF_METHODNAME_CALCAPPEND)
  5156. methodMatcher.mMethodType = BfMethodType_CtorCalcAppend;
  5157. BF_ASSERT(methodMatcher.mBestMethodDef == NULL);
  5158. BfLocalMethod* matchedLocalMethod = NULL;
  5159. if (target.mType == NULL)
  5160. {
  5161. CheckLocalMethods(targetSrc, curTypeInst, methodName, methodMatcher, BfMethodType_Normal);
  5162. if (methodMatcher.mBestMethodDef == NULL)
  5163. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  5164. if (methodMatcher.mBestMethodDef != NULL)
  5165. {
  5166. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  5167. auto methodDef = methodMatcher.mBestMethodDef;
  5168. if (mModule->mCompiler->mResolvePassData != NULL)
  5169. {
  5170. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  5171. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, curTypeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, ~methodDef->mIdx);
  5172. auto autoComplete = GetAutoComplete();
  5173. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  5174. {
  5175. autoComplete->SetDefinitionLocation(methodDef->GetRefNode());
  5176. if (autoComplete->mDefType == NULL)
  5177. {
  5178. autoComplete->mDefMethod = mModule->mCurMethodState->GetRootMethodState()->mMethodInstance->mMethodDef;
  5179. autoComplete->mDefType = curTypeDef;
  5180. autoComplete->mReplaceLocalId = ~methodDef->mIdx;
  5181. }
  5182. }
  5183. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  5184. {
  5185. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  5186. methodMatchEntry.mMethodDef = methodDef;
  5187. methodMatchEntry.mTypeInstance = mModule->mCurTypeInstance;
  5188. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  5189. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  5190. }
  5191. }
  5192. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  5193. {
  5194. auto methodInstance = mModule->GetRawMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef);
  5195. if (methodInstance->mReturnType == NULL)
  5196. {
  5197. FinishDeferredEvals(argValues.mResolvedArgs);
  5198. // If we are recursive then we won't even have a completed methodInstance yet to look at
  5199. return mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  5200. }
  5201. }
  5202. }
  5203. }
  5204. if (methodMatcher.mBestMethodDef == NULL)
  5205. {
  5206. if (lookupTypeInst == NULL)
  5207. {
  5208. if ((lookupType != NULL) && (lookupType->IsConcreteInterfaceType()))
  5209. {
  5210. auto concreteInterfaceType = (BfConcreteInterfaceType*)lookupType;
  5211. lookupTypeInst = concreteInterfaceType->mInterface;
  5212. }
  5213. else if (isUnboundCall)
  5214. {
  5215. //auto resolvedType = mModule->ResolveGenericType(lookupType);
  5216. }
  5217. else if (lookupType->IsGenericParam())
  5218. {
  5219. auto genericParamTarget = (BfGenericParamType*)lookupType;
  5220. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  5221. if (genericParamInstance->mTypeConstraint != NULL)
  5222. lookupTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  5223. else
  5224. lookupTypeInst = mModule->mContext->mBfObjectType;
  5225. for (BfType* ifaceInst : genericParamInstance->mInterfaceConstraints)
  5226. {
  5227. if (ifaceInst->IsUnspecializedType())
  5228. ifaceInst = mModule->ResolveType(ifaceInst);
  5229. BfTypeInstance* typeInst = ifaceInst->ToTypeInstance();
  5230. BF_ASSERT(typeInst != NULL);
  5231. if (methodMatcher.CheckType(typeInst, target, false))
  5232. methodMatcher.mSelfType = lookupType;
  5233. }
  5234. }
  5235. }
  5236. if ((lookupTypeInst != NULL) && (!wantCtor))
  5237. {
  5238. methodMatcher.mBypassVirtual = bypassVirtual;
  5239. methodMatcher.CheckType(lookupTypeInst, target, false);
  5240. }
  5241. if ((lookupType != NULL) && (lookupType->IsGenericParam()))
  5242. {
  5243. //lookupType = mModule->ResolveGenericType(lookupType);
  5244. if (!lookupType->IsGenericParam())
  5245. {
  5246. target = MakeCallableTarget(targetSrc, target);
  5247. if (target)
  5248. {
  5249. lookupTypeInst = lookupType->ToTypeInstance();
  5250. }
  5251. }
  5252. }
  5253. }
  5254. bool isFailurePass = false;
  5255. if (methodMatcher.mBestMethodDef == NULL)
  5256. {
  5257. isFailurePass = true;
  5258. if (lookupTypeInst != NULL)
  5259. methodMatcher.CheckType(lookupTypeInst, target, true);
  5260. }
  5261. BfTypedValue staticResult;
  5262. methodMatcher.TryDevirtualizeCall(target, &origTarget, &staticResult);
  5263. if (staticResult)
  5264. return staticResult;
  5265. bypassVirtual |= methodMatcher.mBypassVirtual;
  5266. if (methodMatcher.mBestMethodDef != NULL)
  5267. {
  5268. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  5269. methodDef = methodMatcher.mBestMethodDef;
  5270. }
  5271. if ((methodDef) && (!methodDef->mIsStatic) && (!target) && (allowImplicitThis))
  5272. {
  5273. target = mModule->GetThis();
  5274. }
  5275. // If we call "GetType" on a value type, statically determine the type rather than boxing and then dispatching
  5276. if ((methodDef) && (target) && (curTypeInst == mModule->mContext->mBfObjectType) &&
  5277. (methodDef->mName == "GetType") && (target.mType->IsValueType()))
  5278. {
  5279. BfType* targetType = target.mType;
  5280. if (origTarget)
  5281. targetType = origTarget.mType;
  5282. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  5283. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  5284. return BfTypedValue(mModule->CreateTypeDataRef(targetType), typeType);
  5285. }
  5286. bool skipThis = false;
  5287. // Fail, check for delegate field invocation
  5288. if ((methodDef == NULL) && ((methodGenericArguments == NULL) || (methodGenericArguments->size() == 0)))
  5289. {
  5290. // Check for payload enum initialization first
  5291. BfTypedValue enumResult;
  5292. BfTypeInstance* enumType = NULL;
  5293. if ((!target) && (mModule->mCurTypeInstance->IsPayloadEnum()))
  5294. {
  5295. enumType = mModule->mCurTypeInstance;
  5296. //enumResult = CheckEnumCreation(targetSrc, mModule->mCurTypeInstance, methodName, argValues);
  5297. }
  5298. else if ((!target) && (target.HasType()) && (targetType->IsPayloadEnum()))
  5299. {
  5300. enumType = targetType->ToTypeInstance();
  5301. //enumResult = CheckEnumCreation(targetSrc, enumType, methodName, argValues);
  5302. }
  5303. if (enumType != NULL)
  5304. {
  5305. enumResult = CheckEnumCreation(targetSrc, enumType, methodName, argValues);
  5306. }
  5307. if (enumResult)
  5308. {
  5309. if ((mModule->mCompiler->mResolvePassData != NULL) &&
  5310. (targetSrc->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) &&
  5311. (mModule->mCompiler->mResolvePassData->mSourceClassifier != NULL))
  5312. {
  5313. mModule->mCompiler->mResolvePassData->mSourceClassifier->SetElementType(targetSrc, BfSourceElementType_Normal);
  5314. }
  5315. return enumResult;
  5316. }
  5317. BfTypedValue fieldVal;
  5318. if (allowImplicitThis)
  5319. {
  5320. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  5321. if (identifierNode != NULL)
  5322. fieldVal = LookupIdentifier(identifierNode);
  5323. }
  5324. else
  5325. {
  5326. fieldVal = LookupField(targetSrc, target, methodName);
  5327. }
  5328. if (mPropDef != NULL)
  5329. fieldVal = GetResult();
  5330. if (fieldVal)
  5331. {
  5332. if (fieldVal.mType->IsGenericParam())
  5333. {
  5334. bool delegateFailed = true;
  5335. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  5336. BfTypeInstance* typeInstConstraint = NULL;
  5337. if (genericParamInstance->mTypeConstraint != NULL)
  5338. typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  5339. if ((typeInstConstraint != NULL) &&
  5340. ((typeInstConstraint->mTypeDef == mModule->mCompiler->mDelegateTypeDef) || (typeInstConstraint->mTypeDef == mModule->mCompiler->mFunctionTypeDef)))
  5341. {
  5342. MarkResultUsed();
  5343. // if (argValues.mResolvedArgs.size() > 0)
  5344. // {
  5345. // if ((argValues.mResolvedArgs[0].mArgFlags & BfArgFlag_FromParamComposite) != 0)
  5346. // delegateFailed = false;
  5347. // }
  5348. // else
  5349. if (argValues.mArguments->size() == 1)
  5350. {
  5351. BfExprEvaluator exprEvaluator(mModule);
  5352. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_AllowParamsExpr;
  5353. exprEvaluator.Evaluate((*argValues.mArguments)[0]);
  5354. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  5355. {
  5356. /*if (exprEvaluator.mResult.mKind != BfTypedValueKind_Params)
  5357. mModule->Warn(0, "'params' token expected", (*argValues.mArguments)[0]);*/
  5358. auto localVar = exprEvaluator.mResultLocalVar;
  5359. if ((localVar->mCompositeCount >= 0) && (localVar->mResolvedType == fieldVal.mType))
  5360. {
  5361. delegateFailed = false;
  5362. if (mModule->mCurMethodInstance->mIsUnspecialized)
  5363. {
  5364. auto retTypeType = mModule->CreateRetTypeType(fieldVal.mType);
  5365. return mModule->GetFakeTypedValue(retTypeType);
  5366. }
  5367. }
  5368. }
  5369. }
  5370. if (delegateFailed)
  5371. {
  5372. mModule->Fail(StrFormat("Generic delegates can only be invoked with 'params %s' composite parameters", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  5373. return BfTypedValue();
  5374. }
  5375. }
  5376. }
  5377. if (fieldVal.mType->IsTypeInstance())
  5378. {
  5379. prevBindResult.Restore();
  5380. auto fieldTypeInst = fieldVal.mType->ToTypeInstance();
  5381. MarkResultUsed();
  5382. return MatchMethod(targetSrc, NULL, fieldVal, false, false, "Invoke", argValues, methodGenericArguments, checkedKind);
  5383. }
  5384. if (fieldVal.mType->IsVar())
  5385. return BfTypedValue(mModule->GetDefaultValue(fieldVal.mType), fieldVal.mType);
  5386. if (fieldVal.mType->IsGenericParam())
  5387. {
  5388. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  5389. if ((genericParam->mTypeConstraint != NULL) &&
  5390. ((genericParam->mTypeConstraint->IsDelegate()) || (genericParam->mTypeConstraint->IsFunction())))
  5391. {
  5392. BfMethodInstance* invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(genericParam->mTypeConstraint->ToTypeInstance(), 0, "Invoke");
  5393. methodDef = invokeMethodInstance->mMethodDef;
  5394. methodMatcher.mBestMethodInstance = invokeMethodInstance;
  5395. methodMatcher.mBestMethodTypeInstance = invokeMethodInstance->GetOwner();
  5396. methodMatcher.mBestMethodDef = invokeMethodInstance->mMethodDef;
  5397. target = mModule->GetDefaultTypedValue(methodMatcher.mBestMethodTypeInstance);
  5398. isFailurePass = false;
  5399. isIndirectMethodCall = true;
  5400. }
  5401. }
  5402. else if (fieldVal.mType->IsMethodRef())
  5403. {
  5404. auto functionBindResults = prevBindResult.mPrevVal;
  5405. if (functionBindResults != NULL)
  5406. {
  5407. functionBindResults->mOrigTarget = fieldVal;
  5408. }
  5409. origTarget = fieldVal;
  5410. auto methodRefType = (BfMethodRefType*)fieldVal.mType;
  5411. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  5412. methodDef = methodInstance->mMethodDef;
  5413. if (methodDef->mIsLocalMethod)
  5414. {
  5415. methodMatcher.mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodInstance);
  5416. }
  5417. else
  5418. {
  5419. BfTypeVector methodGenericArguments;
  5420. if (methodInstance->mMethodInfoEx != NULL)
  5421. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  5422. methodMatcher.mBestMethodInstance = mModule->GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, methodGenericArguments);
  5423. }
  5424. methodMatcher.mBestMethodTypeInstance = methodInstance->GetOwner();
  5425. if (methodInstance->HasThis())
  5426. {
  5427. bool failed = false;
  5428. target = DoImplicitArgCapture(targetSrc, methodInstance, -1, failed, BfImplicitParamKind_General, origTarget);
  5429. }
  5430. else if (!methodDef->mIsStatic)
  5431. {
  5432. auto thisType = methodInstance->GetParamType(-1);
  5433. BF_ASSERT(thisType->IsValuelessType());
  5434. target = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodMatcher.mBestMethodTypeInstance);
  5435. }
  5436. else
  5437. target = BfTypedValue(methodMatcher.mBestMethodTypeInstance);
  5438. methodMatcher.mBypassVirtual = true;
  5439. bypassVirtual = true;
  5440. isFailurePass = false;
  5441. isIndirectMethodCall = true;
  5442. }
  5443. if (methodDef == NULL)
  5444. {
  5445. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  5446. return BfTypedValue();
  5447. }
  5448. }
  5449. }
  5450. if ((!methodDef) && (!target.mValue))
  5451. {
  5452. // Check to see if we're constructing a struct via a call like: "Struct structVal = Struct()"
  5453. int wantNumGenericArgs = 0;
  5454. if ((methodGenericArguments != NULL) && (methodGenericArguments->size() > 0))
  5455. wantNumGenericArgs = (int)methodGenericArguments->size();
  5456. BfTypeInstance* resolvedTypeInstance = NULL;
  5457. if (wantCtor)
  5458. {
  5459. resolvedTypeInstance = targetTypeInst;
  5460. }
  5461. else if (targetType != NULL)
  5462. {
  5463. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(methodBoundExpr))
  5464. {
  5465. auto resolvedType = mModule->ResolveTypeRef(invocationExpr->mTarget, methodGenericArguments);
  5466. if (resolvedType != NULL)
  5467. resolvedTypeInstance = resolvedType->ToTypeInstance();
  5468. }
  5469. }
  5470. else
  5471. {
  5472. BfIdentifierNode* identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  5473. if (identifierNode != NULL)
  5474. {
  5475. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  5476. BfType* refType;
  5477. if (methodGenericArguments != NULL)
  5478. {
  5479. refType = mModule->ResolveTypeRef(identifierNode, methodGenericArguments);
  5480. }
  5481. else
  5482. refType = mModule->ResolveTypeRef(identifierNode, NULL);
  5483. prevIgnoreErrors.Restore();
  5484. if ((refType != NULL) && (refType->IsPrimitiveType()))
  5485. {
  5486. if (argValues.mResolvedArgs.size() != 1)
  5487. {
  5488. mModule->Fail("Cast requires one parameter", targetSrc);
  5489. return BfTypedValue();
  5490. }
  5491. // This is just a primitive cast
  5492. auto& resolvedArg = argValues.mResolvedArgs[0];
  5493. BfTypedValue castedValue;
  5494. BfTypedValue castTarget = resolvedArg.mTypedValue;
  5495. if (resolvedArg.mTypedValue)
  5496. {
  5497. castTarget = mModule->LoadValue(castTarget);
  5498. castedValue = mModule->Cast(targetSrc, castTarget, refType, BfCastFlags_Explicit);
  5499. }
  5500. if (!castedValue)
  5501. castedValue = mModule->GetDefaultTypedValue(refType);
  5502. return castedValue;
  5503. }
  5504. if (refType != NULL)
  5505. resolvedTypeInstance = refType->ToTypeInstance();
  5506. }
  5507. }
  5508. if (resolvedTypeInstance != NULL)
  5509. {
  5510. if ((!resolvedTypeInstance->IsStruct()) && (!resolvedTypeInstance->IsTypedPrimitive()))
  5511. {
  5512. mModule->Fail("Objects must be allocated through 'new' or 'stack'", targetSrc);
  5513. return BfTypedValue();
  5514. }
  5515. if (auto identifier = BfNodeDynCastExact<BfIdentifierNode>(targetSrc))
  5516. mModule->SetElementType(identifier, BfSourceElementType_TypeRef);
  5517. if (mModule->mCompiler->mResolvePassData != NULL)
  5518. mModule->mCompiler->mResolvePassData->HandleTypeReference(targetSrc, resolvedTypeInstance->mTypeDef);
  5519. BfTypedValue structInst;
  5520. if (!resolvedTypeInstance->IsValuelessType())
  5521. {
  5522. if ((mReceivingValue != NULL) && (mReceivingValue->mType == resolvedTypeInstance) && (mReceivingValue->IsAddr()))
  5523. {
  5524. structInst = *mReceivingValue;
  5525. mReceivingValue = NULL;
  5526. }
  5527. else
  5528. {
  5529. auto allocaInst = mModule->CreateAlloca(resolvedTypeInstance);
  5530. structInst = BfTypedValue(allocaInst, resolvedTypeInstance, true);
  5531. }
  5532. mResultIsTempComposite = true;
  5533. }
  5534. else
  5535. {
  5536. structInst = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeInstance, true);
  5537. }
  5538. mResultLocalVar = NULL;
  5539. mResultLocalVarRefNode = NULL;
  5540. MatchConstructor(targetSrc, methodBoundExpr, structInst, resolvedTypeInstance, argValues, false, false);
  5541. mModule->ValidateAllocation(resolvedTypeInstance, targetSrc);
  5542. mModule->AddDependency(resolvedTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  5543. if (mUsedAsStatement)
  5544. {
  5545. mModule->Warn(0, "Struct constructor being used as a statement", targetSrc);
  5546. }
  5547. return structInst;
  5548. }
  5549. }
  5550. if ((methodDef == NULL) && (!target) && (mModule->mContext->mCurTypeState != NULL))
  5551. {
  5552. //BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mTypeInstance);
  5553. BfGlobalLookup globalLookup;
  5554. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  5555. globalLookup.mName = methodName;
  5556. mModule->PopulateGlobalContainersList(globalLookup);
  5557. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  5558. {
  5559. if (globalContainer.mTypeInst == NULL)
  5560. continue;
  5561. methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false);
  5562. if (methodMatcher.mBestMethodDef != NULL)
  5563. {
  5564. isFailurePass = false;
  5565. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  5566. methodDef = methodMatcher.mBestMethodDef;
  5567. break;
  5568. }
  5569. }
  5570. }
  5571. if (methodDef == NULL)
  5572. {
  5573. auto compiler = mModule->mCompiler;
  5574. if ((compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(targetSrc)))
  5575. {
  5576. mModule->CheckTypeRefFixit(targetSrc);
  5577. bool wantStatic = !target.mValue;
  5578. if ((targetType == NULL) && (allowImplicitThis))
  5579. {
  5580. targetType = mModule->mCurTypeInstance;
  5581. if (mModule->mCurMethodInstance != NULL)
  5582. wantStatic = mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  5583. }
  5584. if (targetType != NULL)
  5585. {
  5586. auto typeInst = targetType->ToTypeInstance();
  5587. if ((typeInst->mTypeDef->mSource != NULL) && (typeInst != mModule->mContext->mBfObjectType))
  5588. {
  5589. auto parser = typeInst->mTypeDef->mSource->ToParser();
  5590. if (parser != NULL)
  5591. {
  5592. String fullName = typeInst->mTypeDef->mFullName.ToString();
  5593. String methodStr;
  5594. if (typeInst == mModule->mCurTypeInstance)
  5595. {
  5596. // Implicitly private
  5597. }
  5598. else if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, typeInst))
  5599. {
  5600. methodStr += "protected ";
  5601. }
  5602. else
  5603. {
  5604. methodStr += "public ";
  5605. }
  5606. if (wantStatic)
  5607. methodStr += "static ";
  5608. if (mExpectingType != NULL)
  5609. methodStr += mModule->TypeToString(mExpectingType, BfTypeNameFlag_ReduceName);
  5610. else
  5611. methodStr += "void";
  5612. methodStr += " " + methodName + "(";
  5613. std::set<String> usedNames;
  5614. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  5615. {
  5616. if (argIdx > 0)
  5617. methodStr += ", ";
  5618. auto& resolvedArg = argValues.mResolvedArgs[argIdx];
  5619. String checkName = "param";
  5620. if (resolvedArg.mTypedValue.mType != NULL)
  5621. {
  5622. bool isOut = false;
  5623. bool isArr = false;
  5624. BfType* checkType = resolvedArg.mTypedValue.mType;
  5625. while (true)
  5626. {
  5627. if ((checkType->IsArray()) || (checkType->IsSizedArray()))
  5628. {
  5629. isArr = true;
  5630. checkType = checkType->GetUnderlyingType();
  5631. }
  5632. else if (checkType->IsRef())
  5633. {
  5634. BfRefType* refType = (BfRefType*)checkType;
  5635. if (refType->mRefKind == BfRefType::RefKind_Out)
  5636. isOut = true;
  5637. checkType = refType->GetUnderlyingType();
  5638. }
  5639. else if (checkType->IsTypeInstance())
  5640. {
  5641. BfTypeInstance* typeInst = (BfTypeInstance*)checkType;
  5642. checkName = typeInst->mTypeDef->mName->ToString();
  5643. if (checkName == "String")
  5644. checkName = "Str";
  5645. if (checkName == "Object")
  5646. checkName = "Obj";
  5647. if (isOut)
  5648. checkName = "out" + checkName;
  5649. else if (isupper(checkName[0]))
  5650. checkName[0] = tolower(checkName[0]);
  5651. if (isArr)
  5652. checkName += "Arr";
  5653. break;
  5654. }
  5655. else
  5656. break;
  5657. }
  5658. methodStr += mModule->TypeToString(resolvedArg.mTypedValue.mType, BfTypeNameFlag_ReduceName);
  5659. }
  5660. else
  5661. {
  5662. checkName = "param";
  5663. methodStr += "Object";
  5664. }
  5665. for (int i = 1; i < 10; i++)
  5666. {
  5667. String lookupName = checkName;
  5668. if (i > 1)
  5669. lookupName += StrFormat("%d", i);
  5670. if (usedNames.insert(lookupName).second)
  5671. {
  5672. methodStr += " " + lookupName;
  5673. break;
  5674. }
  5675. }
  5676. }
  5677. int fileLoc = typeInst->mTypeDef->mTypeDeclaration->GetSrcEnd();
  5678. if (auto defineBlock = BfNodeDynCast<BfBlock>(typeInst->mTypeDef->mTypeDeclaration->mDefineNode))
  5679. fileLoc = defineBlock->mCloseBrace->GetSrcStart();
  5680. methodStr += ")";
  5681. compiler->mResolvePassData->mAutoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("Create method '%s' in '%s'\taddMethod|%s|%d|||%s|{||}", methodName.c_str(), fullName.c_str(), parser->mFileName.c_str(), fileLoc, methodStr.c_str()).c_str()));
  5682. }
  5683. }
  5684. }
  5685. }
  5686. if (methodName.IsEmpty())
  5687. {
  5688. // Would have caused a parsing error
  5689. }
  5690. else if (target.mType != NULL)
  5691. mModule->Fail(StrFormat("Method '%s' does not exist in type '%s'", methodName.c_str(), mModule->TypeToString(target.mType).c_str()), targetSrc);
  5692. else
  5693. mModule->Fail(StrFormat("Method '%s' does not exist", methodName.c_str()), targetSrc);
  5694. FinishDeferredEvals(argValues.mResolvedArgs);
  5695. return BfTypedValue();
  5696. }
  5697. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  5698. {
  5699. for (auto& arg : methodMatcher.mBestMethodGenericArguments)
  5700. {
  5701. if ((arg != NULL) && (arg->IsVar()))
  5702. return mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  5703. }
  5704. }
  5705. if ((prevBindResult.mPrevVal != NULL) && (methodMatcher.mMethodCheckCount > 1))
  5706. prevBindResult.mPrevVal->mCheckedMultipleMethods = true;
  5707. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, curTypeInst, methodDef, methodMatcher);
  5708. if ((bypassVirtual) && (!target.mValue) && (target.mType->IsInterface()))
  5709. {
  5710. target = mModule->GetThis();
  5711. }
  5712. if (!moduleMethodInstance)
  5713. return BfTypedValue();
  5714. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  5715. if (methodDef->IsEmptyPartial())
  5716. {
  5717. // Ignore call
  5718. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType);
  5719. }
  5720. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mIsStatic) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  5721. {
  5722. bool isConstrained = false;
  5723. if (target.mType != NULL)
  5724. isConstrained = target.mType->IsGenericParam();
  5725. if ((target.mType == NULL) && ((mModule->mCurMethodInstance->mIsForeignMethodDef) || (mModule->mCurTypeInstance->IsInterface())))
  5726. isConstrained = true;
  5727. if (!isConstrained)
  5728. {
  5729. if (mModule->mCurTypeInstance->IsInterface())
  5730. {
  5731. if (methodDef->mBody == NULL)
  5732. mModule->Fail(StrFormat("Interface method '%s' must provide a body to be explicitly invoked", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  5733. }
  5734. else
  5735. 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);
  5736. FinishDeferredEvals(argValues.mResolvedArgs);
  5737. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType);
  5738. }
  5739. }
  5740. // 'base' could really mean 'this' if we're in an extension
  5741. if ((target.IsBase()) && (targetTypeInst == mModule->mCurTypeInstance))
  5742. target.ToThis();
  5743. else
  5744. MakeBaseConcrete(target);
  5745. BfTypedValue callTarget;
  5746. if (isSkipCall)
  5747. {
  5748. // Just a fake value so we can continue on without generating any code (boxing, conversion, etc)
  5749. if (target)
  5750. callTarget = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), targetTypeInst);
  5751. }
  5752. else if (targetTypeInst == curTypeInst)
  5753. {
  5754. if ((target) && (methodDef->HasNoThisSplat()))
  5755. {
  5756. callTarget = mModule->MakeAddressable(target);
  5757. }
  5758. else
  5759. callTarget = target;
  5760. }
  5761. else if (target)
  5762. {
  5763. if (methodMatcher.mFakeConcreteTarget)
  5764. {
  5765. BF_ASSERT(curTypeInst->IsInterface());
  5766. callTarget = mModule->GetDefaultTypedValue(mModule->CreateConcreteInterfaceType(curTypeInst));
  5767. }
  5768. else if (((target.mType->IsGenericParam()) || (target.mType->IsConcreteInterfaceType())) && (curTypeInst->IsInterface()))
  5769. {
  5770. // Leave as generic
  5771. callTarget = target;
  5772. }
  5773. else
  5774. {
  5775. bool handled = false;
  5776. if ((target.mType->IsTypedPrimitive()) && (curTypeInst->IsTypedPrimitive()))
  5777. {
  5778. handled = true;
  5779. callTarget = target;
  5780. }
  5781. else if ((target.mType->IsStructOrStructPtr()) || (target.mType->IsTypedPrimitive()))
  5782. {
  5783. //BF_ASSERT(target.IsAddr());
  5784. if (curTypeInst->IsObjectOrInterface())
  5785. {
  5786. // Box it
  5787. callTarget = mModule->Cast(targetSrc, target, curTypeInst, BfCastFlags_Explicit);
  5788. handled = true;
  5789. }
  5790. else
  5791. {
  5792. //BF_ASSERT(target.IsAddr() || target.IsSplat() || target.mType->IsPointer());
  5793. }
  5794. }
  5795. else
  5796. target = mModule->LoadValue(target);
  5797. if (!handled)
  5798. {
  5799. // Could we have just unconditionally done this?
  5800. callTarget = mModule->Cast(targetSrc, target, curTypeInst, BfCastFlags_Explicit);
  5801. }
  5802. }
  5803. }
  5804. if (isFailurePass)
  5805. {
  5806. BfError* error;
  5807. if (methodMatcher.mMatchFailKind == BfMethodMatcher::MatchFailKind_CheckedMismatch)
  5808. 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);
  5809. else
  5810. error = mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  5811. if (error != NULL)
  5812. {
  5813. if ((error != NULL) && (moduleMethodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL))
  5814. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), moduleMethodInstance.mMethodInstance->mMethodDef->GetRefNode());
  5815. }
  5816. }
  5817. if ((mModule->mCompiler->mResolvePassData != NULL) && (methodDef != NULL))
  5818. {
  5819. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  5820. while (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode))
  5821. identifierNode = qualifiedNameNode->mRight;
  5822. if ((identifierNode != NULL) && (methodDef->mIdx >= 0) && (!isIndirectMethodCall))
  5823. {
  5824. mModule->mCompiler->mResolvePassData->HandleMethodReference(identifierNode, curTypeInst->mTypeDef, methodDef);
  5825. auto autoComplete = GetAutoComplete();
  5826. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  5827. {
  5828. autoComplete->SetDefinitionLocation(methodDef->GetRefNode());
  5829. int virtualIdx = moduleMethodInstance.mMethodInstance->mVirtualTableIdx;
  5830. if ((autoComplete->mResolveType == BfResolveType_GoToDefinition) &&
  5831. (virtualIdx != -1) && (targetTypeInst != NULL) && (!targetTypeInst->IsStruct()) && (!targetTypeInst->IsTypedPrimitive()) && (!targetTypeInst->IsInterface()) &&
  5832. // 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
  5833. (targetTypeInst->mVirtualMethodTable.size() != 0))
  5834. {
  5835. auto methodEntry = targetTypeInst->mVirtualMethodTable[virtualIdx];
  5836. if (methodEntry.mImplementingMethod.mMethodNum != -1)
  5837. {
  5838. BfMethodInstance* callingMethodInstance = methodEntry.mImplementingMethod;
  5839. if (callingMethodInstance != NULL)
  5840. {
  5841. auto callingMethodDef = callingMethodInstance->mMethodDef;
  5842. auto callingMethodDeclaration = callingMethodDef->GetMethodDeclaration();
  5843. if ((callingMethodDeclaration != NULL) && (callingMethodDeclaration->mNameNode != NULL))
  5844. autoComplete->SetDefinitionLocation(callingMethodDeclaration->mNameNode, true);
  5845. }
  5846. }
  5847. }
  5848. if (autoComplete->mDefType == NULL)
  5849. {
  5850. autoComplete->mDefMethod = methodDef;
  5851. autoComplete->mDefType = curTypeInst->mTypeDef;
  5852. }
  5853. }
  5854. }
  5855. }
  5856. // This was causing forward-backward-forward steps when we just used 'targetSrc'. Using closeParen is undesirable because most of the time
  5857. // we DO just want it to just go to the targetSrc... do we even need this?
  5858. /*if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(targetSrc->mParent))
  5859. {
  5860. // We set the srcPos to the close paren right before the call so we keep a forward progression of src positions in the case
  5861. // where some of the params are method calls and such
  5862. if (invokeExpr->mCloseParen != NULL)
  5863. mModule->UpdateExprSrcPos(invokeExpr->mCloseParen);
  5864. else
  5865. mModule->UpdateExprSrcPos(targetSrc);
  5866. }
  5867. else
  5868. mModule->UpdateExprSrcPos(targetSrc);*/
  5869. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  5870. {
  5871. //BF_ASSERT(!callTarget.mValue.IsFake());
  5872. }
  5873. prevBindResult.Restore();
  5874. if ((callTarget.mType != NULL) &&
  5875. (callTarget.mType->IsGenericParam()) &&
  5876. ((!callTarget.IsAddr()) || (callTarget.IsReadOnly())) &&
  5877. (callTarget.mKind != BfTypedValueKind_MutableValue) &&
  5878. (moduleMethodInstance.mMethodInstance->mMethodDef->mIsMutating))
  5879. {
  5880. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)callTarget.mType);
  5881. bool needsMut = true;
  5882. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class | BfGenericParamFlag_Var)) != 0)
  5883. needsMut = false;
  5884. if (genericParamInstance->mTypeConstraint != NULL)
  5885. {
  5886. auto typeConstaintTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  5887. if ((typeConstaintTypeInstance != NULL) && (!typeConstaintTypeInstance->IsComposite()))
  5888. needsMut = false;
  5889. }
  5890. if (needsMut)
  5891. {
  5892. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str());
  5893. CheckModifyResult(callTarget, targetSrc, err.c_str(), true);
  5894. }
  5895. }
  5896. if ((callTarget.mType != NULL) &&
  5897. (callTarget.mType->IsInterface()) &&
  5898. (target.IsThis()) &&
  5899. (mModule->mCurTypeInstance) &&
  5900. (!mModule->mCurMethodInstance->mMethodDef->mIsMutating) &&
  5901. (methodDef->mIsMutating))
  5902. {
  5903. mModule->Fail(StrFormat("Cannot call mutating method '%s' within default interface method '%s'. Consider adding 'mut' specifier to this method.",
  5904. mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), targetSrc);
  5905. }
  5906. auto result = CreateCall(targetSrc, callTarget, origTarget, methodDef, moduleMethodInstance, bypassVirtual, argValues.mResolvedArgs, skipThis);
  5907. if (result)
  5908. {
  5909. if (result.mType->IsRef())
  5910. result = mModule->RemoveRef(result);
  5911. if (result.mType->IsSelf())
  5912. {
  5913. if (methodMatcher.mSelfType != NULL)
  5914. {
  5915. BF_ASSERT(mModule->IsInGeneric());
  5916. result = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  5917. }
  5918. else
  5919. {
  5920. // Will be an error
  5921. result = mModule->GetDefaultTypedValue(methodMatcher.mBestMethodTypeInstance);
  5922. }
  5923. }
  5924. }
  5925. PerformCallChecks(moduleMethodInstance.mMethodInstance, targetSrc);
  5926. if (result)
  5927. {
  5928. bool discardedReturnValue = mUsedAsStatement;
  5929. if (discardedReturnValue)
  5930. {
  5931. auto _ShowDiscardWaring = [&](const String& text, BfCustomAttributes* customAttributes, BfIRConstHolder* constHolder, BfAstNode* refNode)
  5932. {
  5933. if (customAttributes != NULL)
  5934. {
  5935. auto customAttribute = customAttributes->Get(mModule->mCompiler->mNoDiscardAttributeTypeDef);
  5936. if (!customAttribute->mCtorArgs.IsEmpty())
  5937. {
  5938. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  5939. if ((str != NULL) && (!str->IsEmpty()))
  5940. {
  5941. mModule->Warn(0, text + ": " + *str, targetSrc);
  5942. return;
  5943. }
  5944. }
  5945. }
  5946. mModule->Warn(0, text, targetSrc);
  5947. };
  5948. bool showedWarning = false;
  5949. if (moduleMethodInstance.mMethodInstance->mMethodDef->mIsNoDiscard)
  5950. {
  5951. _ShowDiscardWaring("Discarding return value of method with [NoDiscard] attribute", moduleMethodInstance.mMethodInstance->GetCustomAttributes(),
  5952. moduleMethodInstance.mMethodInstance->GetOwner()->mConstHolder, targetSrc);
  5953. showedWarning = true;
  5954. }
  5955. auto typeInst = result.mType->ToTypeInstance();
  5956. if (typeInst != NULL)
  5957. {
  5958. if ((typeInst->mTypeDef->mIsNoDiscard) && (!showedWarning))
  5959. {
  5960. _ShowDiscardWaring("Discarding return value whose type has [NoDiscard] attribute", typeInst->mCustomAttributes, typeInst->mConstHolder, targetSrc);
  5961. }
  5962. BfModuleMethodInstance moduleMethodInstance = mModule->GetMethodByName(typeInst, "ReturnValueDiscarded", 0, true);
  5963. if (moduleMethodInstance)
  5964. {
  5965. auto wasGetDefinition = (autoComplete != NULL) && (autoComplete->mIsGetDefinition);
  5966. if (wasGetDefinition)
  5967. autoComplete->mIsGetDefinition = false;
  5968. result = mModule->MakeAddressable(result);
  5969. BfResolvedArgs resolvedArgs;
  5970. MatchMethod(targetSrc, NULL, result, false, false, "ReturnValueDiscarded", resolvedArgs, NULL);
  5971. if (wasGetDefinition)
  5972. autoComplete->mIsGetDefinition = true;
  5973. }
  5974. }
  5975. }
  5976. }
  5977. return result;
  5978. }
  5979. void BfExprEvaluator::LookupQualifiedName(BfQualifiedNameNode* nameNode, bool ignoreInitialError, bool* hadError)
  5980. {
  5981. BfIdentifierNode* nameLeft = nameNode->mLeft;
  5982. BfIdentifierNode* nameRight = nameNode->mRight;
  5983. StringT<64> fieldName;
  5984. if (nameNode->mRight != NULL)
  5985. nameNode->mRight->ToString(fieldName);
  5986. bool wasBaseLookup = false;
  5987. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  5988. {
  5989. if ((qualifiedLeftName->mRight->GetSrcLength() == 4) && (qualifiedLeftName->mRight->ToStringView() == "base"))
  5990. {
  5991. wasBaseLookup = true;
  5992. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  5993. if (type == NULL)
  5994. return;
  5995. auto fieldName = nameNode->mRight->ToString();
  5996. auto target = mModule->GetThis();
  5997. target.mType = type;
  5998. mResult = LookupField(nameNode->mRight, target, fieldName);
  5999. if (mPropDef != NULL)
  6000. {
  6001. mPropDefBypassVirtual = true;
  6002. }
  6003. return;
  6004. }
  6005. }
  6006. if (!wasBaseLookup)
  6007. mResult = LookupIdentifier(nameNode->mLeft, ignoreInitialError, hadError);
  6008. GetResult();
  6009. if (!mResult)
  6010. {
  6011. if (!ignoreInitialError)
  6012. mModule->Fail("Identifier not found", nameNode->mLeft);
  6013. return;
  6014. }
  6015. if (mResult.mType->IsObject())
  6016. {
  6017. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  6018. }
  6019. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  6020. {
  6021. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  6022. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  6023. mResult.mType = structPtrType->mElementType;
  6024. if (mResult.mKind == BfTypedValueKind_ThisValue)
  6025. mResult.mKind = BfTypedValueKind_ThisAddr;
  6026. else
  6027. mResult.mKind = BfTypedValueKind_Addr;
  6028. }
  6029. mIsVolatileReference = false;
  6030. mIsHeapReference = false;
  6031. if (!mResult)
  6032. return;
  6033. //if (mResult.mType->IsVar())
  6034. //ResolveGenericType();
  6035. auto origResult = mResult;
  6036. auto lookupType = BindGenericType(nameNode, mResult.mType);
  6037. if (mResult.mType->IsGenericParam())
  6038. {
  6039. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)mResult.mType);
  6040. if (mModule->mCurMethodInstance->mIsUnspecialized)
  6041. {
  6042. if (genericParamInst->mTypeConstraint != NULL)
  6043. mResult.mType = genericParamInst->mTypeConstraint;
  6044. else
  6045. mResult.mType = mModule->mContext->mBfObjectType;
  6046. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  6047. {
  6048. mResult.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  6049. }
  6050. }
  6051. else
  6052. {
  6053. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  6054. {
  6055. //mResult.mType = mModule->ResolveGenericType(mResult.mType);
  6056. }
  6057. else if (genericParamInst->mTypeConstraint != NULL)
  6058. {
  6059. mResult = mModule->Cast(nameNode, mResult, genericParamInst->mTypeConstraint);
  6060. BF_ASSERT(mResult);
  6061. }
  6062. else
  6063. {
  6064. // This shouldn't occur - this would infer that we are accessing a member of Object or something...
  6065. //mResult.mType = mModule->ResolveGenericType(mResult.mType);
  6066. }
  6067. }
  6068. }
  6069. if (mResult.mType->IsVar())
  6070. {
  6071. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType, true);
  6072. return;
  6073. }
  6074. if (!mResult.mType->IsTypeInstance())
  6075. {
  6076. if (hadError != NULL)
  6077. *hadError = true;
  6078. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  6079. mResult = BfTypedValue();
  6080. return;
  6081. }
  6082. BfTypedValue lookupVal = mResult;
  6083. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  6084. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  6085. {
  6086. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType);
  6087. SizedArray<BfTypeInstance*, 8> searchConstraints;
  6088. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  6089. {
  6090. //if (std::find(searchConstraints.begin(), searchConstraints.end(), ifaceConstraint) == searchConstraints.end())
  6091. if (!searchConstraints.Contains(ifaceConstraint))
  6092. {
  6093. searchConstraints.push_back(ifaceConstraint);
  6094. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  6095. {
  6096. auto innerIFace = innerIFaceEntry.mInterfaceType;
  6097. //if (std::find(searchConstraints.begin(), searchConstraints.end(), innerIFace) == searchConstraints.end())
  6098. if (!searchConstraints.Contains(innerIFace))
  6099. {
  6100. searchConstraints.push_back(innerIFace);
  6101. }
  6102. }
  6103. }
  6104. }
  6105. BfTypedValue prevTarget;
  6106. BfPropertyDef* prevDef = NULL;
  6107. for (auto ifaceConstraint : searchConstraints)
  6108. {
  6109. //auto lookupVal = mModule->GetDefaultTypedValue(ifaceConstraint, origResult.IsAddr());
  6110. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  6111. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  6112. if (mPropDef != NULL)
  6113. {
  6114. if (prevDef != NULL)
  6115. {
  6116. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  6117. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  6118. if ((isWorse) && (!isBetter))
  6119. continue;
  6120. if (isBetter == isWorse)
  6121. {
  6122. auto error = mModule->Fail("Ambiguous property reference", nameNode->mRight);
  6123. if (error != NULL)
  6124. {
  6125. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  6126. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  6127. }
  6128. }
  6129. }
  6130. prevDef = mPropDef;
  6131. prevTarget = mPropTarget;
  6132. }
  6133. }
  6134. /*if ((mResult) || (mPropDef != NULL))
  6135. break;*/
  6136. }
  6137. if (mPropDef != NULL)
  6138. {
  6139. mOrigPropTarget = origResult;
  6140. if ((nameNode->mLeft->ToString() == "base") || (wasBaseLookup))
  6141. {
  6142. mPropDefBypassVirtual = true;
  6143. }
  6144. }
  6145. if ((mResult) || (mPropDef != NULL))
  6146. return;
  6147. if (hadError != NULL)
  6148. *hadError = true;
  6149. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  6150. auto compiler = mModule->mCompiler;
  6151. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  6152. {
  6153. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), false);
  6154. }
  6155. mModule->Fail("Unable to find member", nameNode->mRight);
  6156. }
  6157. void BfExprEvaluator::LookupQualifiedName(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreInitialError, bool* hadError)
  6158. {
  6159. String fieldName;
  6160. if (nameRight != NULL)
  6161. fieldName = nameRight->ToString();
  6162. bool wasBaseLookup = false;
  6163. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  6164. {
  6165. if (qualifiedLeftName->mRight->ToString() == "base")
  6166. {
  6167. wasBaseLookup = true;
  6168. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  6169. if (type == NULL)
  6170. return;
  6171. auto fieldName = nameRight->ToString();
  6172. auto target = mModule->GetThis();
  6173. target.mType = type;
  6174. mResult = LookupField(nameRight, target, fieldName);
  6175. if (mPropDef != NULL)
  6176. {
  6177. mPropDefBypassVirtual = true;
  6178. }
  6179. return;
  6180. }
  6181. }
  6182. if (!wasBaseLookup)
  6183. {
  6184. mResult = LookupIdentifier(nameLeft, ignoreInitialError, hadError);
  6185. if ((mResult) && (!mResult.mType->IsComposite()))
  6186. CheckResultForReading(mResult);
  6187. }
  6188. GetResult();
  6189. if (!mResult)
  6190. {
  6191. if (!ignoreInitialError)
  6192. mModule->Fail("Identifier not found", nameLeft);
  6193. return;
  6194. }
  6195. if (mResult.mType->IsObject())
  6196. {
  6197. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  6198. }
  6199. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  6200. {
  6201. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  6202. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  6203. mResult.mType = structPtrType->mElementType;
  6204. if (mResult.mKind == BfTypedValueKind_ThisValue)
  6205. mResult.mKind = BfTypedValueKind_ThisAddr;
  6206. else
  6207. mResult.mKind = BfTypedValueKind_Addr;
  6208. }
  6209. mIsVolatileReference = false;
  6210. mIsHeapReference = false;
  6211. if (!mResult)
  6212. return;
  6213. //if (mResult.mType->IsVar())
  6214. //ResolveGenericType();
  6215. auto origResult = mResult;
  6216. auto lookupType = BindGenericType(nameNode, mResult.mType);
  6217. if (mResult.mType->IsGenericParam())
  6218. {
  6219. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)mResult.mType);
  6220. if (mModule->mCurMethodInstance->mIsUnspecialized)
  6221. {
  6222. if (genericParamInst->mTypeConstraint != NULL)
  6223. mResult.mType = genericParamInst->mTypeConstraint;
  6224. else
  6225. mResult.mType = mModule->mContext->mBfObjectType;
  6226. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  6227. {
  6228. mResult.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  6229. }
  6230. }
  6231. else
  6232. {
  6233. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  6234. {
  6235. //mResult.mType = mModule->ResolveGenericType(mResult.mType);
  6236. }
  6237. else if (genericParamInst->mTypeConstraint != NULL)
  6238. {
  6239. mResult = mModule->Cast(nameNode, mResult, genericParamInst->mTypeConstraint);
  6240. BF_ASSERT(mResult);
  6241. }
  6242. else
  6243. {
  6244. // This shouldn't occur - this would infer that we are accessing a member of Object or something...
  6245. //mResult.mType = mModule->ResolveGenericType(mResult.mType);
  6246. }
  6247. }
  6248. }
  6249. if (mResult.mType->IsVar())
  6250. {
  6251. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType, true);
  6252. return;
  6253. }
  6254. if (!mResult.mType->IsTypeInstance())
  6255. {
  6256. if (mResult.mType->IsSizedArray())
  6257. {
  6258. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  6259. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  6260. }
  6261. else if (mResult.mType->IsWrappableType())
  6262. {
  6263. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  6264. }
  6265. else
  6266. {
  6267. if (hadError != NULL)
  6268. *hadError = true;
  6269. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  6270. mResult = BfTypedValue();
  6271. return;
  6272. }
  6273. }
  6274. BfTypedValue lookupVal = mResult;
  6275. mResult = LookupField(nameRight, lookupVal, fieldName);
  6276. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  6277. {
  6278. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType);
  6279. SizedArray<BfTypeInstance*, 8> searchConstraints;
  6280. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  6281. {
  6282. //if (std::find(searchConstraints.begin(), searchConstraints.end(), ifaceConstraint) == searchConstraints.end())
  6283. if (!searchConstraints.Contains(ifaceConstraint))
  6284. {
  6285. searchConstraints.push_back(ifaceConstraint);
  6286. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  6287. {
  6288. auto innerIFace = innerIFaceEntry.mInterfaceType;
  6289. //if (std::find(searchConstraints.begin(), searchConstraints.end(), innerIFace) == searchConstraints.end())
  6290. if (!searchConstraints.Contains(innerIFace))
  6291. {
  6292. searchConstraints.push_back(innerIFace);
  6293. }
  6294. }
  6295. }
  6296. }
  6297. BfTypedValue prevTarget;
  6298. BfPropertyDef* prevDef = NULL;
  6299. for (auto ifaceConstraint : searchConstraints)
  6300. {
  6301. //auto lookupVal = mModule->GetDefaultTypedValue(ifaceConstraint, origResult.IsAddr());
  6302. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  6303. mResult = LookupField(nameRight, lookupVal, fieldName);
  6304. if (mPropDef != NULL)
  6305. {
  6306. if (prevDef != NULL)
  6307. {
  6308. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  6309. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  6310. if ((isWorse) && (!isBetter))
  6311. continue;
  6312. if (isBetter == isWorse)
  6313. {
  6314. auto error = mModule->Fail("Ambiguous property reference", nameRight);
  6315. if (error != NULL)
  6316. {
  6317. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  6318. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  6319. }
  6320. }
  6321. }
  6322. prevDef = mPropDef;
  6323. prevTarget = mPropTarget;
  6324. }
  6325. }
  6326. /*if ((mResult) || (mPropDef != NULL))
  6327. break;*/
  6328. }
  6329. if (mPropDef != NULL)
  6330. {
  6331. mOrigPropTarget = origResult;
  6332. if ((nameLeft->ToString() == "base") || (wasBaseLookup))
  6333. {
  6334. mPropDefBypassVirtual = true;
  6335. }
  6336. }
  6337. if ((mResult) || (mPropDef != NULL))
  6338. return;
  6339. if (hadError != NULL)
  6340. *hadError = true;
  6341. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  6342. auto compiler = mModule->mCompiler;
  6343. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  6344. {
  6345. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), false);
  6346. }
  6347. mModule->Fail("Unable to find member", nameRight);
  6348. }
  6349. void BfExprEvaluator::LookupQualifiedStaticField(BfQualifiedNameNode* nameNode, bool ignoreIdentifierNotFoundError)
  6350. {
  6351. // Lookup left side as a type
  6352. {
  6353. SetAndRestoreValue<bool> prevHadIgnoreError(mModule->mHadIgnoredError, false);
  6354. BfType* type = NULL;
  6355. {
  6356. type = mModule->ResolveTypeRef(nameNode->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  6357. mModule->CheckTypeRefFixit(nameNode->mLeft);
  6358. }
  6359. if (type != NULL)
  6360. {
  6361. BfTypedValue lookupType;
  6362. if (type->IsWrappableType())
  6363. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  6364. else
  6365. lookupType = BfTypedValue(type);
  6366. auto findName = nameNode->mRight->ToString();
  6367. /*if (findName == "base")
  6368. {
  6369. mResult = BfTypedValue(lookupType);
  6370. return;
  6371. }*/
  6372. mResult = LookupField(nameNode->mRight, lookupType, findName);
  6373. if ((mResult) || (mPropDef != NULL))
  6374. return;
  6375. if (lookupType.mType != NULL)
  6376. {
  6377. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  6378. auto compiler = mModule->mCompiler;
  6379. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  6380. {
  6381. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), true);
  6382. }
  6383. }
  6384. mModule->Fail("Field not found", nameNode->mRight);
  6385. return;
  6386. }
  6387. }
  6388. String fieldName = nameNode->mRight->ToString();
  6389. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  6390. LookupQualifiedStaticField(qualifiedLeftName, true);
  6391. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameNode->mLeft))
  6392. {
  6393. mResult = LookupIdentifier(leftName);
  6394. }
  6395. GetResult();
  6396. if (!mResult)
  6397. {
  6398. if (!ignoreIdentifierNotFoundError)
  6399. mModule->Fail("Identifier not found", nameNode->mLeft);
  6400. return;
  6401. }
  6402. if (mResult.mType->IsObject())
  6403. {
  6404. mResult = mModule->LoadValue(mResult);
  6405. }
  6406. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  6407. {
  6408. BfPointerType* structPtrType = (BfPointerType*) mResult.mType;
  6409. mResult = mModule->LoadValue(mResult);
  6410. mResult.mType = structPtrType->mElementType;
  6411. }
  6412. if (!mResult)
  6413. return;
  6414. if (!mResult.mType->IsTypeInstance())
  6415. {
  6416. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  6417. return;
  6418. }
  6419. mResult = LookupField(nameNode->mRight, mResult, fieldName);
  6420. if ((mResult) || (mPropDef != NULL))
  6421. return;
  6422. mModule->Fail("Unable to find member", nameNode->mRight);
  6423. }
  6424. void BfExprEvaluator::LookupQualifiedStaticField(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreIdentifierNotFoundError)
  6425. {
  6426. // Lookup left side as a type
  6427. {
  6428. SetAndRestoreValue<bool> prevHadIgnoreError(mModule->mHadIgnoredError, false);
  6429. BfType* type = NULL;
  6430. {
  6431. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  6432. type = mModule->ResolveTypeRef(nameLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  6433. }
  6434. if (type != NULL)
  6435. {
  6436. BfTypedValue lookupType;
  6437. if (type->IsWrappableType())
  6438. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  6439. else
  6440. lookupType = BfTypedValue(type);
  6441. auto findName = nameRight->ToString();
  6442. /*if (findName == "base")
  6443. {
  6444. mResult = BfTypedValue(lookupType);
  6445. return;
  6446. }*/
  6447. mResult = LookupField(nameRight, lookupType, findName);
  6448. if ((mResult) || (mPropDef != NULL))
  6449. return;
  6450. if (lookupType.mType != NULL)
  6451. {
  6452. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  6453. auto compiler = mModule->mCompiler;
  6454. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  6455. {
  6456. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), true);
  6457. }
  6458. }
  6459. mModule->Fail("Field not found", nameRight);
  6460. return;
  6461. }
  6462. }
  6463. String fieldName = nameRight->ToString();
  6464. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  6465. LookupQualifiedStaticField(qualifiedLeftName, qualifiedLeftName->mLeft, qualifiedLeftName->mRight, true);
  6466. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameLeft))
  6467. {
  6468. mResult = LookupIdentifier(leftName);
  6469. }
  6470. GetResult();
  6471. if (!mResult)
  6472. {
  6473. if (!ignoreIdentifierNotFoundError)
  6474. mModule->Fail("Identifier not found", nameLeft);
  6475. return;
  6476. }
  6477. if (mResult.mType->IsObject())
  6478. {
  6479. mResult = mModule->LoadValue(mResult);
  6480. }
  6481. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  6482. {
  6483. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  6484. mResult = mModule->LoadValue(mResult);
  6485. mResult.mType = structPtrType->mElementType;
  6486. }
  6487. if (!mResult)
  6488. return;
  6489. if (!mResult.mType->IsTypeInstance())
  6490. {
  6491. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  6492. return;
  6493. }
  6494. mResult = LookupField(nameRight, mResult, fieldName);
  6495. if ((mResult) || (mPropDef != NULL))
  6496. return;
  6497. mModule->CheckTypeRefFixit(nameLeft);
  6498. mModule->Fail("Unable to find member", nameRight);
  6499. }
  6500. void BfExprEvaluator::Visit(BfQualifiedNameNode* nameNode)
  6501. {
  6502. auto autoComplete = GetAutoComplete();
  6503. if (autoComplete != NULL)
  6504. {
  6505. autoComplete->CheckMemberReference(nameNode->mLeft, nameNode->mDot, nameNode->mRight);
  6506. }
  6507. bool hadError = false;
  6508. LookupQualifiedName(nameNode, nameNode->mLeft, nameNode->mRight, true, &hadError);
  6509. if ((mResult) || (mPropDef != NULL))
  6510. return;
  6511. if (hadError)
  6512. return;
  6513. LookupQualifiedStaticField(nameNode, nameNode->mLeft, nameNode->mRight, false);
  6514. }
  6515. void BfExprEvaluator::Visit(BfThisExpression* thisExpr)
  6516. {
  6517. mResult = mModule->GetThis();
  6518. if (!mResult)
  6519. {
  6520. mModule->Fail("Static methods don't have 'this'", thisExpr);
  6521. return;
  6522. }
  6523. //if (mResult.mType->IsTypedPrimitive())
  6524. {
  6525. mResultLocalVar = mModule->GetThisVariable();
  6526. }
  6527. }
  6528. void BfExprEvaluator::Visit(BfBaseExpression* baseExpr)
  6529. {
  6530. mResult = mModule->GetThis();
  6531. if (!mResult)
  6532. {
  6533. mModule->Fail("Static methods don't have 'base'", baseExpr);
  6534. return;
  6535. }
  6536. auto baseType = mModule->mCurTypeInstance->mBaseType;
  6537. if (baseType == NULL)
  6538. baseType = mModule->mContext->mBfObjectType;
  6539. mModule->PopulateType(baseType, BfPopulateType_Data);
  6540. mResult = mModule->Cast(baseExpr, mResult, baseType, BfCastFlags_Explicit);
  6541. }
  6542. void BfExprEvaluator::Visit(BfMixinExpression* mixinExpr)
  6543. {
  6544. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  6545. {
  6546. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  6547. auto newVar = mModule->AllocFromType(varType, mModule->mCurMethodState->mCurScope);
  6548. mResult = BfTypedValue(newVar, varType, true);
  6549. return;
  6550. }
  6551. auto curMethodState = mModule->mCurMethodState;
  6552. if (curMethodState->mMixinState == NULL)
  6553. {
  6554. mModule->Fail("Mixin references can only be used within mixins", mixinExpr);
  6555. return;
  6556. }
  6557. int localIdx = GetMixinVariable();
  6558. if (localIdx != -1)
  6559. {
  6560. auto varDecl = curMethodState->mLocals[localIdx];
  6561. if (varDecl != NULL)
  6562. {
  6563. BfTypedValue localResult = LoadLocal(varDecl);
  6564. mResult = localResult;
  6565. mResultLocalVar = varDecl;
  6566. mResultLocalVarRefNode = mixinExpr;
  6567. return;
  6568. }
  6569. }
  6570. if (mModule->mCurMethodInstance->mIsUnspecialized)
  6571. {
  6572. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  6573. return;
  6574. }
  6575. mModule->Fail("Mixin value cannot be inferred", mixinExpr);
  6576. }
  6577. void BfExprEvaluator::Visit(BfSizedArrayCreateExpression* createExpr)
  6578. {
  6579. auto type = mModule->ResolveTypeRef(createExpr->mTypeRef);
  6580. if (type == NULL)
  6581. return;
  6582. if (type->IsArray())
  6583. {
  6584. // If we have a case like 'int[] (1, 2)' then we infer the sized array size from the initializer
  6585. auto arrayType = (BfArrayType*)type;
  6586. if (arrayType->mDimensions == 1)
  6587. {
  6588. int arraySize = 0;
  6589. if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(createExpr->mInitializer))
  6590. {
  6591. arraySize = (int)arrayInitExpr->mValues.size();
  6592. }
  6593. type = mModule->CreateSizedArrayType(arrayType->GetUnderlyingType(), arraySize);
  6594. }
  6595. }
  6596. if (!type->IsSizedArray())
  6597. {
  6598. mModule->Fail("Sized array expected", createExpr->mTypeRef);
  6599. return;
  6600. }
  6601. BfSizedArrayType* arrayType = (BfSizedArrayType*)type;
  6602. if (createExpr->mInitializer == NULL)
  6603. {
  6604. mModule->AssertErrorState();
  6605. mResult = mModule->GetDefaultTypedValue(arrayType);
  6606. return;
  6607. }
  6608. InitializedSizedArray(arrayType, createExpr->mInitializer->mOpenBrace, createExpr->mInitializer->mValues, createExpr->mInitializer->mCommas, createExpr->mInitializer->mCloseBrace);
  6609. }
  6610. void BfExprEvaluator::Visit(BfCollectionInitializerExpression* arrayInitExpr)
  6611. {
  6612. mModule->Fail("Collection initializer not usable here", arrayInitExpr);
  6613. }
  6614. void BfExprEvaluator::Visit(BfParamsExpression* paramsExpr)
  6615. {
  6616. mModule->Fail("Params expression is only usable as a call parameter", paramsExpr);
  6617. }
  6618. void BfExprEvaluator::Visit(BfTypeOfExpression* typeOfExpr)
  6619. {
  6620. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  6621. auto autoComplete = GetAutoComplete();
  6622. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  6623. {
  6624. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  6625. }
  6626. BfType* type;
  6627. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeOfExpr->mTypeRef))
  6628. {
  6629. type = mModule->ResolveTypeRefAllowUnboundGenerics(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  6630. }
  6631. else
  6632. {
  6633. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  6634. }
  6635. if (type == NULL)
  6636. {
  6637. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  6638. return;
  6639. }
  6640. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6641. mResult = BfTypedValue(mModule->CreateTypeDataRef(type), typeType);
  6642. }
  6643. bool BfExprEvaluator::LookupTypeProp(BfTypeOfExpression* typeOfExpr, BfIdentifierNode* propName)
  6644. {
  6645. // We ignore errors because we go through the normal Visit(BfTypeOfExpression) if this fails, which will throw the error again
  6646. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  6647. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  6648. BfType* type;
  6649. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeOfExpr->mTypeRef))
  6650. {
  6651. type = mModule->ResolveTypeRefAllowUnboundGenerics(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  6652. }
  6653. else
  6654. {
  6655. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  6656. }
  6657. if (type == NULL)
  6658. {
  6659. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  6660. return false;
  6661. }
  6662. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6663. mModule->PopulateType(type);
  6664. auto typeInstance = type->ToTypeInstance();
  6665. auto _BoolResult = [&](bool val)
  6666. {
  6667. mResult = BfTypedValue(mModule->GetConstValue8(val ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  6668. };
  6669. auto _Int32Result = [&](int32 val)
  6670. {
  6671. mResult = BfTypedValue(mModule->GetConstValue32(val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  6672. };
  6673. String memberName;
  6674. propName->ToString(memberName);
  6675. bool handled = true;
  6676. if (memberName == "IsTypedPrimitive")
  6677. _BoolResult(type->IsPrimitiveType());
  6678. else if (memberName == "IsObject")
  6679. _BoolResult(type->IsObject());
  6680. else if (memberName == "IsValueType")
  6681. _BoolResult(type->IsValueType());
  6682. else if (memberName == "IsStruct")
  6683. _BoolResult(type->IsStruct());
  6684. else if (memberName == "IsSplattable")
  6685. _BoolResult(type->IsSplattable());
  6686. else if (memberName == "IsUnion")
  6687. _BoolResult(type->IsUnion());
  6688. else if (memberName == "IsBoxed")
  6689. _BoolResult(type->IsBoxed());
  6690. else if (memberName == "IsEnum")
  6691. _BoolResult(type->IsEnum());
  6692. else if (memberName == "IsTuple")
  6693. _BoolResult(type->IsTuple());
  6694. else if (memberName == "IsNullable")
  6695. _BoolResult(type->IsNullable());
  6696. else if (memberName == "IsGenericType")
  6697. _BoolResult(type->IsGenericTypeInstance());
  6698. else if (memberName == "TypeId")
  6699. _Int32Result(type->mTypeId);
  6700. else if (memberName == "GenericParamCount")
  6701. {
  6702. auto genericTypeInst = type->ToGenericTypeInstance();
  6703. _Int32Result((genericTypeInst != NULL) ? (int)genericTypeInst->mTypeGenericArguments.size() : 0);
  6704. }
  6705. else if (memberName == "Size")
  6706. _Int32Result(type->mSize);
  6707. else if (memberName == "Align")
  6708. _Int32Result(type->mAlign);
  6709. else if (memberName == "Stride")
  6710. _Int32Result(type->GetStride());
  6711. else if (memberName == "InstanceSize")
  6712. _Int32Result((typeInstance != NULL) ? typeInstance->mInstSize : type->mSize);
  6713. else if (memberName == "InstanceAlign")
  6714. _Int32Result((typeInstance != NULL) ? typeInstance->mInstAlign : type->mSize);
  6715. else if (memberName == "InstanceStride")
  6716. _Int32Result((typeInstance != NULL) ? typeInstance->GetInstStride() : type->GetStride());
  6717. else if ((memberName == "MinValue") || (memberName == "MaxValue"))
  6718. {
  6719. bool isMin = memberName == "MinValue";
  6720. BfType* checkType = typeInstance;
  6721. if (checkType->IsTypedPrimitive())
  6722. checkType = checkType->GetUnderlyingType();
  6723. if (checkType->IsPrimitiveType())
  6724. {
  6725. auto primType = (BfPrimitiveType*)checkType;
  6726. if (typeInstance->IsEnum())
  6727. {
  6728. if (typeInstance->mTypeInfoEx != NULL)
  6729. {
  6730. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)typeInstance->mTypeInfoEx->mMinValue : (uint64)typeInstance->mTypeInfoEx->mMaxValue), typeInstance);
  6731. return true;
  6732. }
  6733. }
  6734. else
  6735. {
  6736. switch (primType->mTypeDef->mTypeCode)
  6737. {
  6738. case BfTypeCode_Int8:
  6739. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x80 : 0x7F), typeInstance);
  6740. return true;
  6741. case BfTypeCode_Int16:
  6742. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x8000 : 0x7FFF), typeInstance);
  6743. return true;
  6744. case BfTypeCode_Int32:
  6745. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x80000000LL : 0x7FFFFFFF), typeInstance);
  6746. return true;
  6747. case BfTypeCode_Int64:
  6748. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x8000000000000000LL : (uint64)0x7FFFFFFFFFFFFFFFLL), typeInstance);
  6749. return true;
  6750. case BfTypeCode_UInt8:
  6751. case BfTypeCode_Char8:
  6752. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFF), typeInstance);
  6753. return true;
  6754. case BfTypeCode_UInt16:
  6755. case BfTypeCode_Char16:
  6756. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFFFF), typeInstance);
  6757. return true;
  6758. case BfTypeCode_UInt32:
  6759. case BfTypeCode_Char32:
  6760. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFLL), typeInstance);
  6761. return true;
  6762. case BfTypeCode_UInt64:
  6763. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFFFFFFFFFLL), typeInstance);
  6764. return true;
  6765. default: break;
  6766. }
  6767. }
  6768. }
  6769. if (typeInstance->IsEnum())
  6770. {
  6771. mModule->Fail("'MinValue' cannot be used on enums with payloads", propName);
  6772. }
  6773. else
  6774. {
  6775. mModule->Fail(StrFormat("'%s' cannot be used on type '%s'", memberName.c_str(), mModule->TypeToString(typeInstance).c_str()), propName);
  6776. }
  6777. }
  6778. else
  6779. return false;
  6780. auto autoComplete = GetAutoComplete();
  6781. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  6782. {
  6783. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  6784. }
  6785. return true;
  6786. }
  6787. void BfExprEvaluator::DoTypeIntAttr(BfTypeReference* typeRef, BfToken token)
  6788. {
  6789. auto type = mModule->ResolveTypeRef(typeRef, BfPopulateType_Data, BfResolveTypeRefFlag_AutoComplete);
  6790. if (type == NULL)
  6791. return;
  6792. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage); // Local usage ensures it changes when the type data changes
  6793. auto typeInst = type->ToTypeInstance();
  6794. if ((typeInst != NULL) && (typeInst->mTypeDef->mIsOpaque))
  6795. {
  6796. mModule->Fail(StrFormat("Unable to determine attributes for opaque type '%s'", mModule->TypeToString(type).c_str()), typeRef);
  6797. }
  6798. BfType* sizeType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  6799. int attrVal = 0;
  6800. switch (token)
  6801. {
  6802. case BfToken_SizeOf: attrVal = type->mSize; break;
  6803. case BfToken_AlignOf: attrVal = type->mAlign; break;
  6804. case BfToken_StrideOf: attrVal = type->GetStride(); break;
  6805. default: break;
  6806. }
  6807. bool isUndefVal = false;
  6808. if (type->IsGenericParam())
  6809. isUndefVal = true;
  6810. if (type->IsSizedArray())
  6811. {
  6812. auto sizedArray = (BfSizedArrayType*)type;
  6813. if (sizedArray->mElementCount == -1)
  6814. isUndefVal = true;
  6815. }
  6816. if (isUndefVal)
  6817. {
  6818. // We do this so we know it's a constant but we can't assume anything about its value
  6819. // We make the value an Int32 which doesn't match the IntPtr type, but it allows us to
  6820. // assume it can be implicitly cased to int32
  6821. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(BfTypeCode_Int32), sizeType);
  6822. }
  6823. else
  6824. mResult = BfTypedValue(mModule->GetConstValue(attrVal, sizeType), sizeType);
  6825. }
  6826. void BfExprEvaluator::Visit(BfSizeOfExpression* sizeOfExpr)
  6827. {
  6828. DoTypeIntAttr(sizeOfExpr->mTypeRef, BfToken_SizeOf);
  6829. }
  6830. void BfExprEvaluator::Visit(BfAlignOfExpression* alignOfExpr)
  6831. {
  6832. DoTypeIntAttr(alignOfExpr->mTypeRef, BfToken_AlignOf);
  6833. }
  6834. void BfExprEvaluator::Visit(BfStrideOfExpression* strideOfExpr)
  6835. {
  6836. DoTypeIntAttr(strideOfExpr->mTypeRef, BfToken_StrideOf);
  6837. }
  6838. void BfExprEvaluator::Visit(BfDefaultExpression* defaultExpr)
  6839. {
  6840. auto autoComplete = GetAutoComplete();
  6841. if (autoComplete != NULL)
  6842. autoComplete->CheckTypeRef(defaultExpr->mTypeRef, false, true);
  6843. BfType* type = NULL;
  6844. if (defaultExpr->mOpenParen == NULL)
  6845. {
  6846. if (mExpectingType)
  6847. {
  6848. type = mExpectingType;
  6849. }
  6850. else
  6851. {
  6852. mModule->Fail("Type cannot be inferred, consider adding explicit type name", defaultExpr);
  6853. return;
  6854. }
  6855. }
  6856. else
  6857. type = mModule->ResolveTypeRef(defaultExpr->mTypeRef);
  6858. if (type == NULL)
  6859. return;
  6860. mModule->ValidateAllocation(type, defaultExpr->mTypeRef);
  6861. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6862. mResult = mModule->GetDefaultTypedValue(type);
  6863. }
  6864. void BfExprEvaluator::Visit(BfUninitializedExpression* uninitialziedExpr)
  6865. {
  6866. mModule->Fail("Invalid use of the '?' uninitialized specifier", uninitialziedExpr);
  6867. }
  6868. void BfExprEvaluator::Visit(BfCheckTypeExpression* checkTypeExpr)
  6869. {
  6870. auto targetValue = mModule->CreateValueFromExpression(checkTypeExpr->mTarget);
  6871. if (!targetValue)
  6872. return;
  6873. if (checkTypeExpr->mTypeRef == NULL)
  6874. {
  6875. mModule->AssertErrorState();
  6876. return;
  6877. }
  6878. auto autoComplete = GetAutoComplete();
  6879. if (autoComplete != NULL)
  6880. autoComplete->CheckTypeRef(checkTypeExpr->mTypeRef, false, true);
  6881. auto targetType = mModule->ResolveTypeRefAllowUnboundGenerics(checkTypeExpr->mTypeRef);
  6882. if (!targetType)
  6883. {
  6884. mModule->AssertErrorState();
  6885. return;
  6886. }
  6887. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6888. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  6889. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  6890. {
  6891. auto typeInstance = targetValue.mType->ToTypeInstance();
  6892. if (targetValue.mType->IsWrappableType())
  6893. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  6894. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  6895. if (!matches)
  6896. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  6897. mResult = BfTypedValue(mModule->GetConstValue(matches ? 1 : 0, boolType), boolType);
  6898. return;
  6899. }
  6900. if (targetType->IsValueType())
  6901. {
  6902. if ((targetValue.mType != mModule->mContext->mBfObjectType) && (!targetValue.mType->IsInterface()))
  6903. {
  6904. mResult = BfTypedValue(mModule->GetConstValue(0, boolType), boolType);
  6905. return;
  6906. }
  6907. }
  6908. int wantTypeId = 0;
  6909. if (!targetType->IsGenericParam())
  6910. wantTypeId = targetType->mTypeId;
  6911. auto objectType = mModule->mContext->mBfObjectType;
  6912. mModule->PopulateType(objectType, BfPopulateType_Full);
  6913. targetValue = mModule->LoadValue(targetValue);
  6914. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  6915. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  6916. bool wasGenericParamType = false;
  6917. if ((srcTypeInstance != NULL) && (targetTypeInstance != NULL))
  6918. {
  6919. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  6920. {
  6921. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  6922. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  6923. // it may be a "necessary cast" indeed
  6924. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  6925. {
  6926. if (srcTypeInstance == targetType)
  6927. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, the value is already type '%s'",
  6928. mModule->TypeToString(srcTypeInstance).c_str()), checkTypeExpr->mIsToken);
  6929. else
  6930. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, '%s' is a subtype of '%s'",
  6931. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), checkTypeExpr->mIsToken);
  6932. }
  6933. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  6934. return;
  6935. }
  6936. else if ((!targetType->IsInterface()) && (srcTypeInstance != mModule->mContext->mBfObjectType) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  6937. {
  6938. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  6939. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), checkTypeExpr->mIsToken);
  6940. }
  6941. }
  6942. if (mModule->mCompiler->IsAutocomplete())
  6943. {
  6944. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Addr);
  6945. return;
  6946. }
  6947. auto irb = mModule->mBfIRBuilder;
  6948. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  6949. auto matchBB = mModule->mBfIRBuilder->CreateBlock("is.match");
  6950. auto endBB = mModule->mBfIRBuilder->CreateBlock("is.done");
  6951. BfIRValue boolResult = mModule->CreateAlloca(boolType);
  6952. irb->CreateStore(irb->CreateConst(BfTypeCode_Boolean, 0), boolResult);
  6953. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBB, endBB);
  6954. mModule->AddBasicBlock(matchBB);
  6955. irb->CreateStore(irb->CreateConst(BfTypeCode_Boolean, 1), boolResult);
  6956. irb->CreateBr(endBB);
  6957. mModule->AddBasicBlock(endBB);
  6958. mResult = BfTypedValue(irb->CreateLoad(boolResult), boolType);
  6959. }
  6960. void BfExprEvaluator::Visit(BfDynamicCastExpression* dynCastExpr)
  6961. {
  6962. auto targetValue = mModule->CreateValueFromExpression(dynCastExpr->mTarget);
  6963. auto targetType = mModule->ResolveTypeRefAllowUnboundGenerics(dynCastExpr->mTypeRef, BfPopulateType_Data, false);
  6964. auto autoComplete = GetAutoComplete();
  6965. if (autoComplete != NULL)
  6966. {
  6967. autoComplete->CheckTypeRef(dynCastExpr->mTypeRef, false, true);
  6968. }
  6969. if (!targetValue)
  6970. return;
  6971. if (!targetType)
  6972. {
  6973. mModule->AssertErrorState();
  6974. return;
  6975. }
  6976. bool wasGenericParamType = false;
  6977. if (targetType->IsGenericParam())
  6978. {
  6979. //targetType = mModule->ResolveGenericType(targetType);
  6980. //wasGenericParamType = true;
  6981. }
  6982. if ((targetValue.mType->IsMethodRef()) || (targetType->IsMethodRef()))
  6983. {
  6984. // We can never cast a MethodRef to any class type
  6985. mResult = mModule->GetDefaultTypedValue(targetType);
  6986. return;
  6987. }
  6988. if (mModule->mContext->mResolvingVarField)
  6989. {
  6990. mResult = mModule->GetDefaultTypedValue(targetType);
  6991. return;
  6992. }
  6993. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  6994. if (targetType->IsGenericParam())
  6995. {
  6996. wasGenericParamType = true;
  6997. //wasGenericParamType = false; // "was", not "is"
  6998. auto genericParamType = (BfGenericParamType*) targetType;
  6999. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  7000. auto typeConstraint = genericParam->mTypeConstraint;
  7001. if ((typeConstraint == NULL) && (genericParam->mGenericParamFlags & BfGenericParamFlag_Class))
  7002. typeConstraint = mModule->mContext->mBfObjectType;
  7003. if ((typeConstraint == NULL) || (!typeConstraint->IsObject()))
  7004. {
  7005. 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' constraint",
  7006. genericParam->GetGenericParamDef()->mName.c_str()), dynCastExpr->mTypeRef);
  7007. return;
  7008. }
  7009. targetType = typeConstraint;
  7010. targetValue = mModule->GetDefaultTypedValue(targetType);
  7011. }
  7012. if ((!targetType->IsObjectOrInterface()) && (!targetType->IsNullable()))
  7013. {
  7014. mModule->Fail(StrFormat("The as operator must be used with a reference type or nullable type ('%s' is a non-nullable value type)",
  7015. mModule->TypeToString(targetType).c_str()), dynCastExpr->mTypeRef);
  7016. return;
  7017. }
  7018. if (targetValue.mType->IsGenericParam())
  7019. {
  7020. auto genericParamType = (BfGenericParamType*)targetValue.mType;
  7021. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  7022. auto typeConstraint = genericParam->mTypeConstraint;
  7023. if (typeConstraint == NULL)
  7024. typeConstraint = mModule->mContext->mBfObjectType;
  7025. if ((typeConstraint->IsDelegate()) && (typeConstraint == targetType))
  7026. {
  7027. // Delegate constraints may be matched by valueless method references, so this won't always match (don't warn)
  7028. mResult = mModule->GetDefaultTypedValue(targetType);
  7029. return;
  7030. }
  7031. //targetType = typeConstraint;
  7032. targetValue = mModule->GetDefaultTypedValue(typeConstraint);
  7033. }
  7034. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  7035. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  7036. {
  7037. mModule->Warn(0, StrFormat("Type '%s' is not applicable for dynamic casting",
  7038. mModule->TypeToString(targetValue.mType).c_str()), dynCastExpr->mAsToken);
  7039. auto typeInstance = targetValue.mType->ToTypeInstance();
  7040. if (targetValue.mType->IsWrappableType())
  7041. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  7042. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  7043. if (targetType->IsNullable())
  7044. {
  7045. auto elementType = targetType->GetUnderlyingType();
  7046. if (elementType == targetValue.mType)
  7047. {
  7048. // We match nullable element
  7049. auto allocaInst = mModule->CreateAlloca(targetType);
  7050. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  7051. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  7052. hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 0); // value
  7053. mModule->mBfIRBuilder->CreateStore(targetValue.mValue, hasValueAddr);
  7054. mResult = BfTypedValue(allocaInst, targetType, true);
  7055. return;
  7056. }
  7057. }
  7058. if (!matches)
  7059. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  7060. if (matches)
  7061. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_Explicit);
  7062. else if (targetType->IsNullable())
  7063. {
  7064. auto allocaInst = mModule->CreateAlloca(targetType);
  7065. auto allocaBits = mModule->mBfIRBuilder->CreateBitCast(allocaInst, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  7066. mModule->mBfIRBuilder->CreateMemSet(allocaBits, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  7067. mModule->GetConstValue(targetType->mSize), targetType->mAlign);
  7068. mResult = BfTypedValue(allocaInst, targetType, true);
  7069. }
  7070. else
  7071. mResult = BfTypedValue(mModule->GetDefaultValue(targetType), targetType);
  7072. return;
  7073. }
  7074. if (targetType->IsNullable())
  7075. {
  7076. if (autoComplete != NULL)
  7077. {
  7078. mResult = mModule->GetDefaultTypedValue(targetType);
  7079. return;
  7080. }
  7081. auto elementType = targetType->GetUnderlyingType();
  7082. auto allocaInst = mModule->CreateAlloca(targetType);
  7083. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, elementType->IsValuelessType() ? 1 : 2); // has_value
  7084. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(0, boolType), hasValueAddr);
  7085. auto objectType = mModule->mContext->mBfObjectType;
  7086. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  7087. auto matchBB = mModule->mBfIRBuilder->CreateBlock("as.match");
  7088. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  7089. mModule->EmitDynamicCastCheck(targetValue, elementType, matchBB, endBB);
  7090. BfBoxedType* boxedType = mModule->CreateBoxedType(elementType);
  7091. mModule->AddBasicBlock(matchBB);
  7092. if (elementType->IsValuelessType())
  7093. {
  7094. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  7095. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  7096. }
  7097. else
  7098. {
  7099. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 2); // has_value
  7100. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  7101. auto nullableValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // value
  7102. auto srcBoxedType = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(boxedType, BfIRPopulateType_Full));
  7103. auto boxedValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(srcBoxedType, 0, 1); // mValue
  7104. auto boxedValue = mModule->mBfIRBuilder->CreateLoad(boxedValueAddr);
  7105. mModule->mBfIRBuilder->CreateStore(boxedValue, nullableValueAddr);
  7106. }
  7107. mModule->mBfIRBuilder->CreateBr(endBB);
  7108. mModule->AddBasicBlock(endBB);
  7109. mResult = BfTypedValue(allocaInst, targetType, true);
  7110. return;
  7111. }
  7112. targetValue = mModule->LoadValue(targetValue);
  7113. if (targetType->IsValueType())
  7114. {
  7115. mModule->Fail("Invalid dynamic cast type", dynCastExpr->mTypeRef);
  7116. return;
  7117. }
  7118. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  7119. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  7120. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  7121. {
  7122. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  7123. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  7124. // it may be a "necessary cast" indeed
  7125. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  7126. {
  7127. if (srcTypeInstance == targetType)
  7128. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, the value is already type '%s'",
  7129. mModule->TypeToString(srcTypeInstance).c_str()), dynCastExpr->mAsToken);
  7130. else
  7131. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, '%s' is a subtype of '%s'",
  7132. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), dynCastExpr->mAsToken);
  7133. }
  7134. auto castedValue = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetTypeInstance));
  7135. mResult = BfTypedValue(castedValue, targetTypeInstance);
  7136. return;
  7137. }
  7138. else if ((!targetType->IsInterface()) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  7139. {
  7140. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  7141. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), dynCastExpr->mAsToken);
  7142. }
  7143. if (autoComplete != NULL)
  7144. {
  7145. mResult = mModule->GetDefaultTypedValue(targetType);
  7146. return;
  7147. }
  7148. auto irb = mModule->mBfIRBuilder;
  7149. auto objectType = mModule->mContext->mBfObjectType;
  7150. mModule->PopulateType(objectType, BfPopulateType_Full);
  7151. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  7152. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  7153. auto matchBlock = irb->CreateBlock("as.match");
  7154. BfIRValue targetVal = mModule->CreateAlloca(targetType);
  7155. irb->CreateStore(irb->CreateConstNull(irb->MapType(targetType)), targetVal);
  7156. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBlock, endBB);
  7157. mModule->AddBasicBlock(matchBlock);
  7158. BfIRValue castedCallResult = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetType));
  7159. irb->CreateStore(castedCallResult, targetVal);
  7160. irb->CreateBr(endBB);
  7161. mModule->AddBasicBlock(endBB);
  7162. mResult = BfTypedValue(irb->CreateLoad(targetVal), targetType);
  7163. }
  7164. void BfExprEvaluator::Visit(BfCastExpression* castExpr)
  7165. {
  7166. auto autoComplete = GetAutoComplete();
  7167. if ((autoComplete != NULL) && (castExpr->mTypeRef != NULL))
  7168. {
  7169. // 'mayBeIdentifier' because this may be a misidentified cast - it could be a parenthesized expression
  7170. autoComplete->CheckTypeRef(castExpr->mTypeRef, true, true);
  7171. }
  7172. BfType* resolvedType = NULL;
  7173. if ((BfNodeDynCastExact<BfDotTypeReference>(castExpr->mTypeRef) != NULL) && (mExpectingType != NULL))
  7174. {
  7175. //mModule->SetElementType(castExpr->mTypeRef, BfSourceElementType_TypeRef);
  7176. resolvedType = mExpectingType;
  7177. }
  7178. else
  7179. resolvedType = ResolveTypeRef(castExpr->mTypeRef);
  7180. if (resolvedType != NULL)
  7181. mModule->AddDependency(resolvedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  7182. // If resolvedType is NULL then that's okay- we just leave the following expression uncasted
  7183. if (castExpr->mExpression == NULL)
  7184. {
  7185. mModule->AssertErrorState();
  7186. return;
  7187. }
  7188. mResult = mModule->CreateValueFromExpression(castExpr->mExpression, resolvedType, (BfEvalExprFlags)(BfEvalExprFlags_ExplicitCast));
  7189. }
  7190. bool BfExprEvaluator::IsExactMethodMatch(BfMethodInstance* methodA, BfMethodInstance* methodB, bool ignoreImplicitParams)
  7191. {
  7192. if (methodA->mReturnType != methodB->mReturnType)
  7193. return false;
  7194. int implicitParamCountA = methodA->GetImplicitParamCount();
  7195. int implicitParamCountB = methodB->GetImplicitParamCount();
  7196. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  7197. return false;
  7198. for (int i = 0; i < (int)methodA->GetParamCount() - implicitParamCountA; i++)
  7199. {
  7200. auto paramA = methodA->GetParamType(i + implicitParamCountA);
  7201. auto paramB = methodB->GetParamType(i + implicitParamCountB);
  7202. if (paramA != paramB)
  7203. return false;
  7204. }
  7205. return true;
  7206. }
  7207. void BfExprEvaluator::ConstResolve(BfExpression* expr)
  7208. {
  7209. BfConstResolver constResolver(mModule);
  7210. constResolver.Resolve(expr);
  7211. mResult = constResolver.mResult;
  7212. }
  7213. BfTypeInstance* BfExprEvaluator::VerifyBaseDelegateType(BfTypeInstance* baseDelegateType)
  7214. {
  7215. mModule->PopulateType(baseDelegateType, BfPopulateType_DataAndMethods);
  7216. if (baseDelegateType->mFieldInstances.size() != 2)
  7217. {
  7218. mModule->AssertErrorState();
  7219. return NULL;
  7220. }
  7221. return baseDelegateType;
  7222. }
  7223. bool BfExprEvaluator::CanBindDelegate(BfDelegateBindExpression* delegateBindExpr, BfMethodInstance** boundMethod)
  7224. {
  7225. if (mExpectingType == NULL)
  7226. {
  7227. return false;
  7228. }
  7229. auto typeInstance = mExpectingType->ToTypeInstance();
  7230. if ((typeInstance == NULL) || (!typeInstance->mTypeDef->mIsDelegate))
  7231. return false;
  7232. mModule->PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  7233. auto methodInstance = mModule->GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  7234. if (methodInstance == NULL)
  7235. {
  7236. BF_DBG_FATAL("Invoke not found");
  7237. return false;
  7238. }
  7239. if (delegateBindExpr->mTarget == NULL)
  7240. return false;
  7241. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  7242. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  7243. typedValueExprs.resize(methodInstance->GetParamCount());
  7244. SizedArray<BfExpression*, 4> args;
  7245. args.resize(methodInstance->GetParamCount());
  7246. for (int i = 0; i < (int) methodInstance->GetParamCount(); i++)
  7247. {
  7248. auto typedValueExpr = &typedValueExprs[i];
  7249. typedValueExpr->mTypedValue.mType = methodInstance->GetParamType(i);
  7250. typedValueExpr->mRefNode = NULL;
  7251. args[i] = typedValueExpr;
  7252. }
  7253. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  7254. if (delegateBindExpr->mGenericArgs != NULL)
  7255. methodGenericArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  7256. BfFunctionBindResult bindResult;
  7257. bindResult.mSkipMutCheck = true; // Allow operating on copies
  7258. mFunctionBindResult = &bindResult;
  7259. SetAndRestoreValue<bool> ignoreError(mModule->mIgnoreErrors, true);
  7260. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArguments);
  7261. mFunctionBindResult = NULL;
  7262. if (bindResult.mMethodInstance == NULL)
  7263. return false;
  7264. if (boundMethod != NULL)
  7265. *boundMethod = bindResult.mMethodInstance;
  7266. return IsExactMethodMatch(methodInstance, bindResult.mMethodInstance, true);
  7267. }
  7268. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfIdentifierNode* identifierNode)
  7269. {
  7270. String findName = identifierNode->ToString();
  7271. if (mModule->mCurMethodState != NULL)
  7272. {
  7273. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  7274. auto checkMethodState = mModule->mCurMethodState;
  7275. bool isMixinOuterVariablePass = false;
  7276. while (checkMethodState != NULL)
  7277. {
  7278. BP_ZONE("LookupIdentifier:DoImplicitArgCapture");
  7279. BfTypeInstance* closureTypeInst = NULL;
  7280. BfClosureInstanceInfo* closureInstanceInfo = NULL;
  7281. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  7282. {
  7283. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  7284. }
  7285. BfLocalVarEntry* entry;
  7286. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(findName, &entry))
  7287. {
  7288. auto varDecl = entry->mLocalVar;
  7289. while (varDecl != NULL)
  7290. {
  7291. // if ((closureTypeInst != NULL) && (wantName == "this"))
  7292. // break;
  7293. if (varDecl->mNameNode == identifierNode)
  7294. {
  7295. BfTypedValue localResult = LoadLocal(varDecl);
  7296. // auto autoComplete = GetAutoComplete();
  7297. // if (identifierNode != NULL)
  7298. // {
  7299. // if (autoComplete != NULL)
  7300. // autoComplete->CheckLocalRef(identifierNode, varDecl);
  7301. // if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  7302. // (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL))
  7303. // mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, varDecl->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, varDecl->mLocalVarId);
  7304. // }
  7305. //
  7306. if (!isMixinOuterVariablePass)
  7307. {
  7308. mResultLocalVar = varDecl;
  7309. mResultLocalVarRefNode = identifierNode;
  7310. }
  7311. return localResult;
  7312. }
  7313. varDecl = varDecl->mShadowedLocal;
  7314. }
  7315. }
  7316. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  7317. if (closureTypeInst != NULL)
  7318. {
  7319. closureTypeInst->mTypeDef->PopulateMemberSets();
  7320. BfMemberSetEntry* memberSetEntry = NULL;
  7321. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  7322. {
  7323. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  7324. while (fieldDef != NULL)
  7325. {
  7326. BfIdentifierNode* fieldNameNode = NULL;
  7327. if (fieldDef->mIdx < (int)checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries.size())
  7328. fieldNameNode = checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries[fieldDef->mIdx].mNameNode;
  7329. if (fieldNameNode == identifierNode)
  7330. {
  7331. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  7332. if (!field.mResolvedType->IsValuelessType())
  7333. {
  7334. if (mModule->mCurMethodState->mClosureState->mCapturing)
  7335. {
  7336. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  7337. return mModule->GetDefaultTypedValue(field.mResolvedType);
  7338. }
  7339. auto localVar = mModule->mCurMethodState->mLocals[0];
  7340. auto thisValue = localVar->mValue;
  7341. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  7342. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  7343. if (field.mResolvedType->IsRef())
  7344. {
  7345. auto refType = (BfRefType*)field.mResolvedType;
  7346. auto underlyingType = refType->GetUnderlyingType();
  7347. result = BfTypedValue(mModule->mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  7348. }
  7349. else if (fieldDef->mIsReadOnly)
  7350. result = mModule->LoadValue(result);
  7351. mResultLocalVar = localVar;
  7352. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  7353. return result;
  7354. }
  7355. }
  7356. fieldDef = fieldDef->mNextWithSameName;
  7357. }
  7358. }
  7359. }
  7360. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  7361. {
  7362. checkMethodState = checkMethodState->mPrevMethodState;
  7363. continue;
  7364. }
  7365. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  7366. bool isLocalMixinProcessing = false;
  7367. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  7368. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  7369. isLocalMixinProcessing = true;
  7370. if (!isLocalMixinProcessing)
  7371. break;
  7372. isMixinOuterVariablePass = true;
  7373. checkMethodState = checkMethodState->mPrevMethodState;
  7374. }
  7375. }
  7376. return BfTypedValue();
  7377. }
  7378. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfMethodInstance* methodInstance, int paramIdx, bool& failed, BfImplicitParamKind paramKind, const BfTypedValue& methodRefTarget)
  7379. {
  7380. if ((methodRefTarget) && (methodRefTarget.mValue.mId != BfIRValue::ID_IMPLICIT))
  7381. {
  7382. if (methodRefTarget.mType->IsMethodRef())
  7383. {
  7384. BfMethodRefType* methodRefType = (BfMethodRefType*)methodRefTarget.mType;
  7385. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  7386. BF_ASSERT(methodRefMethodInst == methodInstance);
  7387. auto paramType = methodInstance->GetParamType(paramIdx);
  7388. int dataIdx = methodRefType->GetDataIdxFromParamIdx(paramIdx);
  7389. if (dataIdx == -1)
  7390. {
  7391. BF_ASSERT(paramType->IsValuelessType());
  7392. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), paramType);
  7393. }
  7394. if (methodRefTarget.IsSplat())
  7395. {
  7396. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  7397. {
  7398. BF_ASSERT(paramIdx == -1);
  7399. return BfTypedValue(methodRefTarget.mValue, paramType, BfTypedValueKind_SplatHead);
  7400. }
  7401. else
  7402. {
  7403. int splatIdx = dataIdx;
  7404. if (dataIdx > 0)
  7405. {
  7406. if (methodRefType->WantsDataPassedAsSplat(0))
  7407. splatIdx += methodRefType->GetCaptureType(0)->GetSplatCount() - 1;
  7408. }
  7409. bool isAddr = false;
  7410. BfIRValue value = mModule->ExtractSplatValue(methodRefTarget, splatIdx, paramType, &isAddr);
  7411. // We moved the composite load from ExtractSplatValue to here. Hopefully this is correct.
  7412. // 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)
  7413. // if ((paramType->IsComposite()) && (mModule->IsTargetingBeefBackend()))
  7414. // value = mModule->mBfIRBuilder->CreateLoad(value);
  7415. auto lookupVal = BfTypedValue(value, paramType, isAddr);
  7416. if ((isAddr) && (!lookupVal.mType->IsComposite()))
  7417. lookupVal = mModule->LoadValue(lookupVal);
  7418. return lookupVal;
  7419. }
  7420. }
  7421. BF_ASSERT(methodRefTarget.IsAddr());
  7422. if (paramType->IsComposite())
  7423. return BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefTarget.mValue, 0, dataIdx), paramType, true);
  7424. return BfTypedValue(mModule->ExtractValue(methodRefTarget, dataIdx), paramType);
  7425. }
  7426. }
  7427. // 'Default' implicit arg lookup, by identifier. May match field (for lambda), or local variable
  7428. if (paramKind == BfImplicitParamKind_General)
  7429. {
  7430. if (paramIdx == -1)
  7431. {
  7432. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(refNode))
  7433. {
  7434. BfAstNode* thisNode = NULL;
  7435. BfTypedValue thisValue;
  7436. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(delegateBindExpr->mTarget))
  7437. thisNode = memberReferenceExpr->mTarget;
  7438. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(delegateBindExpr->mTarget))
  7439. thisNode = qualifiedNameNode->mLeft;
  7440. else if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(delegateBindExpr->mTarget))
  7441. {
  7442. // Implicit
  7443. thisValue = mModule->GetThis();
  7444. }
  7445. if (auto thisExpr = BfNodeDynCast<BfExpression>(thisNode))
  7446. {
  7447. thisValue = mModule->CreateValueFromExpression(thisExpr);
  7448. if (!thisValue)
  7449. return BfTypedValue();
  7450. }
  7451. if (thisValue)
  7452. {
  7453. //TODO: handle 'mut', throw error if trying to capture from a non-mut, etc...
  7454. return thisValue;
  7455. }
  7456. }
  7457. }
  7458. String captureName = methodInstance->GetParamName(paramIdx);
  7459. BfIdentifierNode* identifierNode = methodInstance->GetParamNameNode(paramIdx);
  7460. BfTypedValue lookupVal;
  7461. if (identifierNode != NULL)
  7462. {
  7463. lookupVal = DoImplicitArgCapture(refNode, identifierNode);
  7464. }
  7465. else
  7466. {
  7467. lookupVal = LookupIdentifier(NULL, captureName);
  7468. }
  7469. if (lookupVal)
  7470. {
  7471. auto paramType = methodInstance->GetParamType(paramIdx);
  7472. if (paramType->IsRef())
  7473. {
  7474. auto refType = (BfRefType*)paramType;
  7475. if (mResultLocalVar != NULL)
  7476. {
  7477. // When we are capturing, we need to note that we require capturing by reference here
  7478. auto localVar = mResultLocalVar;
  7479. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  7480. }
  7481. bool isValid = false;
  7482. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (lookupVal.mKind == BfTypedValueKind_MutableValue))
  7483. isValid = true;
  7484. if ((lookupVal.mType->IsRef()) || (lookupVal.IsAddr()))
  7485. isValid = true;
  7486. if (!isValid)
  7487. {
  7488. // Is there another way this can fail than to be in a lambda?
  7489. auto error = mModule->Fail(StrFormat("Method '%s' requires that '%s' be captured by reference. Consider adding by-reference capture specifier [&] to lambda.",
  7490. mModule->MethodToString(methodInstance).c_str(), captureName.c_str()), refNode, true);
  7491. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  7492. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  7493. failed = true;
  7494. }
  7495. }
  7496. else
  7497. {
  7498. if (lookupVal.mType->IsRef())
  7499. lookupVal = mModule->RemoveRef(lookupVal);
  7500. if (!lookupVal.mType->IsComposite())
  7501. lookupVal = mModule->LoadValue(lookupVal);
  7502. }
  7503. return lookupVal;
  7504. }
  7505. else
  7506. {
  7507. mModule->Fail(StrFormat("Failed to lookup implicit capture '%s'", captureName.c_str()), refNode, true);
  7508. failed = true;
  7509. return BfTypedValue();
  7510. }
  7511. }
  7512. return BfTypedValue();
  7513. }
  7514. void BfExprEvaluator::Visit(BfDelegateBindExpression* delegateBindExpr)
  7515. {
  7516. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  7517. if (mExpectingType == NULL)
  7518. {
  7519. mModule->Fail("Cannot infer delegate type", delegateBindExpr);
  7520. return;
  7521. }
  7522. BfTokenNode* newToken = NULL;
  7523. BfAllocTarget allocTarget = ResolveAllocTarget(delegateBindExpr->mNewToken, newToken);
  7524. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  7525. SizedArray<BfExpression*, 4> args;
  7526. BfTypeInstance* delegateTypeInstance = NULL;
  7527. BfMethodInstance* methodInstance = NULL;
  7528. const char* bindTypeName = NULL;
  7529. bool isMethodRefMatch = false;
  7530. if (mExpectingType->IsMethodRef())
  7531. {
  7532. auto methodRefType = (BfMethodRefType*)mExpectingType;
  7533. BF_ASSERT(delegateBindExpr->mNewToken == NULL);
  7534. methodInstance = methodRefType->mMethodRef;
  7535. isMethodRefMatch = true;
  7536. }
  7537. else
  7538. {
  7539. if (mExpectingType->IsGenericParam())
  7540. {
  7541. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  7542. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsDelegate()))
  7543. {
  7544. delegateTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  7545. }
  7546. }
  7547. else
  7548. delegateTypeInstance = mExpectingType->ToTypeInstance();
  7549. if ((delegateTypeInstance == NULL) ||
  7550. ((!delegateTypeInstance->IsDelegate()) && (!delegateTypeInstance->IsFunction())))
  7551. {
  7552. mModule->Fail(StrFormat("Type '%s' cannot be used for method binding. Only delegate or function types are allowed.", mModule->TypeToString(mExpectingType).c_str()), delegateBindExpr);
  7553. return;
  7554. }
  7555. bindTypeName = (delegateTypeInstance->IsDelegate()) ? "delegate" : "function";
  7556. mModule->PopulateType(delegateTypeInstance, BfPopulateType_DataAndMethods);
  7557. methodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  7558. if (methodInstance == NULL)
  7559. {
  7560. BF_DBG_FATAL("Invoke not found");
  7561. return;
  7562. }
  7563. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(delegateBindExpr->mNewToken))
  7564. {
  7565. if (delegateTypeInstance->IsFunction())
  7566. mModule->Fail("Function bindings are direct assignments, allocation specifier is not applicable", delegateBindExpr->mNewToken);
  7567. else if (tokenNode->GetToken() == BfToken_Append)
  7568. {
  7569. mModule->Fail("Append allocation on delegate bind not supported", delegateBindExpr->mNewToken);
  7570. }
  7571. }
  7572. }
  7573. typedValueExprs.resize(methodInstance->GetParamCount());
  7574. args.resize(methodInstance->GetParamCount());
  7575. for (int i = 0; i < (int)methodInstance->GetParamCount(); i++)
  7576. {
  7577. auto typedValueExpr = &typedValueExprs[i];
  7578. typedValueExpr->mTypedValue.mType = methodInstance->GetParamType(i);
  7579. typedValueExpr->mRefNode = NULL;
  7580. args[i] = typedValueExpr;
  7581. }
  7582. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  7583. if (delegateBindExpr->mGenericArgs != NULL)
  7584. methodGenericArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  7585. if (delegateBindExpr->mTarget == NULL)
  7586. {
  7587. mModule->AssertErrorState();
  7588. return;
  7589. }
  7590. if (GetAutoComplete() != NULL)
  7591. GetAutoComplete()->CheckNode(delegateBindExpr->mTarget);
  7592. if ((!delegateBindExpr->mTarget->IsA<BfIdentifierNode>()) &&
  7593. (!delegateBindExpr->mTarget->IsA<BfMemberReferenceExpression>()))
  7594. {
  7595. mModule->Fail(StrFormat("Invalid %s binding target, %s can only bind to method references. Consider wrapping expression in a lambda.", bindTypeName, bindTypeName), delegateBindExpr->mTarget);
  7596. mModule->CreateValueFromExpression(delegateBindExpr->mTarget);
  7597. return;
  7598. }
  7599. BfFunctionBindResult bindResult;
  7600. bindResult.mSkipMutCheck = true; // Allow operating on copies
  7601. mFunctionBindResult = &bindResult;
  7602. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArguments);
  7603. mFunctionBindResult = NULL;
  7604. SetMethodElementType(delegateBindExpr->mTarget);
  7605. if (bindResult.mMethodInstance == NULL)
  7606. {
  7607. mResult = BfTypedValue();
  7608. return;
  7609. }
  7610. auto bindMethodInstance = bindResult.mMethodInstance;
  7611. if (isMethodRefMatch)
  7612. {
  7613. // WTF- this was always false, what was it supposed to catch?
  7614. // if (bindMethodInstance != bindResult.mMethodInstance)
  7615. // {
  7616. // mResult = BfTypedValue();
  7617. // return;
  7618. // }
  7619. }
  7620. else
  7621. {
  7622. if (!IsExactMethodMatch(methodInstance, bindMethodInstance, true))
  7623. {
  7624. if (bindResult.mCheckedMultipleMethods)
  7625. {
  7626. mModule->Fail(StrFormat("No overload for '%s' matches %s '%s'", bindMethodInstance->mMethodDef->mName.c_str(), bindTypeName,
  7627. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  7628. }
  7629. else
  7630. {
  7631. mModule->Fail(StrFormat("Method '%s' does not match %s '%s'", mModule->MethodToString(bindMethodInstance).c_str(), bindTypeName,
  7632. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  7633. }
  7634. mResult = BfTypedValue();
  7635. return;
  7636. }
  7637. }
  7638. bool isDirectFunction = false;
  7639. if ((bindResult.mMethodInstance->GetOwner()->IsFunction()) && (bindResult.mFunc))
  7640. isDirectFunction = true;
  7641. if (bindMethodInstance->mIsIntrinsic)
  7642. {
  7643. 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);
  7644. mResult = BfTypedValue();
  7645. return;
  7646. }
  7647. bool hasIncompatibleCallingConventions = !mModule->mSystem->IsCompatibleCallingConvention(methodInstance->mMethodDef->mCallingConvention, bindMethodInstance->mMethodDef->mCallingConvention);
  7648. auto _GetInvokeMethodName = [&]()
  7649. {
  7650. String methodName = "Invoke@";
  7651. methodName += mModule->mCurMethodInstance->mMethodDef->mName;
  7652. int prevSepPos = (int)methodName.LastIndexOf('$');
  7653. if (prevSepPos != -1)
  7654. {
  7655. methodName.RemoveToEnd(prevSepPos);
  7656. }
  7657. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  7658. HashContext hashCtx;
  7659. if (delegateBindExpr->mFatArrowToken != NULL)
  7660. {
  7661. hashCtx.Mixin(delegateBindExpr->mFatArrowToken->GetStartCharId());
  7662. }
  7663. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  7664. {
  7665. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  7666. {
  7667. StringT<128> genericTypeName;
  7668. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  7669. hashCtx.MixinStr(genericTypeName);
  7670. }
  7671. }
  7672. Val128 hashVal = hashCtx.Finish128();
  7673. methodName += '$';
  7674. methodName += BfTypeUtils::HashEncode64(hashVal.mLow);
  7675. return methodName;
  7676. };
  7677. if ((delegateBindExpr->mNewToken == NULL) || (delegateTypeInstance->IsFunction()))
  7678. {
  7679. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder != NULL))
  7680. {
  7681. BF_ASSERT(bindResult.mMethodInstance->mHotMethod != NULL);
  7682. mModule->mCurMethodState->mHotDataReferenceBuilder->mFunctionPtrs.Add(bindResult.mMethodInstance->mHotMethod);
  7683. }
  7684. if (isDirectFunction)
  7685. {
  7686. if (delegateTypeInstance->IsFunction())
  7687. {
  7688. auto intPtrVal = mModule->mBfIRBuilder->CreatePtrToInt(bindResult.mFunc, BfTypeCode_IntPtr);
  7689. mResult = BfTypedValue(intPtrVal, mExpectingType);
  7690. return;
  7691. }
  7692. }
  7693. if (mExpectingType->IsFunction())
  7694. {
  7695. BfIRValue result;
  7696. if ((hasIncompatibleCallingConventions) && (mModule->HasCompiledOutput()))
  7697. {
  7698. //
  7699. {
  7700. SetAndRestoreValue<bool> prevIgnore(mModule->mBfIRBuilder->mIgnoreWrites, true);
  7701. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mMethodInstance, mExpectingType);
  7702. }
  7703. if (result)
  7704. {
  7705. String methodName = _GetInvokeMethodName();
  7706. SizedArray<BfIRType, 8> irParamTypes;
  7707. BfIRType irReturnType;
  7708. bindMethodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  7709. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  7710. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  7711. mModule->mBfIRBuilder->SaveDebugLocation();
  7712. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  7713. auto funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  7714. auto srcCallingConv = mModule->GetCallingConvention(methodInstance->GetOwner(), methodInstance->mMethodDef);
  7715. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  7716. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  7717. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  7718. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  7719. SizedArray<BfIRValue, 8> irArgs;
  7720. for (int paramIdx = 0; paramIdx < irParamTypes.size(); paramIdx++)
  7721. {
  7722. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(paramIdx));
  7723. }
  7724. auto bindFuncVal = bindResult.mFunc;
  7725. if (mModule->mCompiler->mOptions.mAllowHotSwapping)
  7726. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  7727. auto callResult = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  7728. auto destCallingConv = mModule->GetCallingConvention(bindMethodInstance->GetOwner(), bindMethodInstance->mMethodDef);
  7729. if (destCallingConv != BfIRCallingConv_CDecl)
  7730. mModule->mBfIRBuilder->SetCallCallingConv(callResult, destCallingConv);
  7731. if (methodInstance->mReturnType->IsValuelessType())
  7732. mModule->mBfIRBuilder->CreateRetVoid();
  7733. else
  7734. mModule->mBfIRBuilder->CreateRet(callResult);
  7735. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  7736. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7737. mModule->mBfIRBuilder->RestoreDebugLocation();
  7738. result = mModule->mBfIRBuilder->CreatePtrToInt(funcValue, BfTypeCode_IntPtr);
  7739. }
  7740. }
  7741. else
  7742. {
  7743. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mMethodInstance, mExpectingType);
  7744. }
  7745. if (result)
  7746. mResult = BfTypedValue(result, mExpectingType);
  7747. return;
  7748. }
  7749. auto methodRefType = mModule->CreateMethodRefType(bindResult.mMethodInstance);
  7750. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  7751. mModule->AddCallDependency(bindResult.mMethodInstance);
  7752. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  7753. {
  7754. mResult = bindResult.mOrigTarget;
  7755. }
  7756. else
  7757. {
  7758. if ((bindResult.mMethodInstance->mMethodDef->mIsLocalMethod) || (!bindResult.mTarget))
  7759. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  7760. else
  7761. {
  7762. auto methodRefPtr = mModule->CreateAlloca(methodRefType, "bindResult");
  7763. auto elemPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefPtr, 0, 0);
  7764. BfTypedValue target;
  7765. if (bindResult.mTarget.IsSplat())
  7766. target = mModule->AggregateSplat(bindResult.mTarget, &bindResult.mIRArgs[0]);
  7767. else
  7768. target = mModule->LoadValue(bindResult.mTarget);
  7769. mModule->mBfIRBuilder->CreateStore(target.mValue, elemPtr);
  7770. mResult = BfTypedValue(methodRefPtr, methodRefType, true);
  7771. }
  7772. }
  7773. return;
  7774. }
  7775. int implicitParamCount = bindMethodInstance->GetImplicitParamCount();
  7776. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  7777. BfClosureType* closureTypeInst = NULL;
  7778. auto origTarget = bindResult.mOrigTarget;
  7779. auto target = bindResult.mTarget;
  7780. BfTypedValue methodRefTarget;
  7781. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  7782. methodRefTarget = bindResult.mOrigTarget;
  7783. bool isStructTarget = (target) && (target.mType->IsStruct());
  7784. bool bindCapturesThis = bindMethodInstance->HasThis() && !isStructTarget;
  7785. bool needsSplat = (isStructTarget) && (!bindMethodInstance->mMethodDef->mIsMutating) && (!bindMethodInstance->mMethodDef->mNoSplat);
  7786. bool captureThisByValue = isStructTarget;
  7787. if (bindMethodInstance->mMethodDef->mIsLocalMethod)
  7788. {
  7789. // Local method captures always capture 'this' by reference
  7790. captureThisByValue = false;
  7791. }
  7792. if ((origTarget.mType != NULL) &&
  7793. ((origTarget.mType->IsRef()) || (origTarget.mType->IsPointer())))
  7794. {
  7795. captureThisByValue = false;
  7796. }
  7797. if (methodRefTarget)
  7798. BF_ASSERT(methodRefTarget.mType->IsMethodRef());
  7799. if (target.IsSplat())
  7800. target = mModule->AggregateSplat(target, &bindResult.mIRArgs[0]);
  7801. bool hasCaptures = false;
  7802. // Do we need a special delegate type for this?
  7803. if (((captureThisByValue) || (needsSplat) || (implicitParamCount > 0) /*|| (hasIncompatibleCallingConventions)*/) &&
  7804. (mModule->HasCompiledOutput()))
  7805. {
  7806. hasCaptures = true;
  7807. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  7808. if (captureThisByValue)
  7809. target = mModule->LoadValue(target);
  7810. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  7811. HashContext hashCtx;
  7812. hashCtx.MixinStr(delegateTypeName);
  7813. // We mix in the project for reasons described in the lambda binding handler
  7814. hashCtx.MixinStr(curProject->mName);
  7815. String structTargetTypeName;
  7816. String structTargetName;
  7817. // Implicit param separator
  7818. for (int implicitParamIdx = bindMethodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  7819. {
  7820. auto paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  7821. if ((implicitParamIdx == -1) && (captureThisByValue))
  7822. {
  7823. if (paramType->IsPointer())
  7824. paramType = paramType->GetUnderlyingType();
  7825. }
  7826. structTargetTypeName = mModule->TypeToString(paramType);
  7827. structTargetName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  7828. hashCtx.MixinStr(structTargetTypeName);
  7829. hashCtx.MixinStr(structTargetName);
  7830. }
  7831. Val128 hash128 = hashCtx.Finish128();
  7832. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  7833. checkClosureType->mContext = mModule->mContext;
  7834. checkClosureType->mBaseType = delegateTypeInstance;
  7835. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_Identity);
  7836. closureTypeInst = (BfClosureType*)resolvedClosureType;
  7837. if (checkClosureType == resolvedClosureType)
  7838. {
  7839. // This is a new closure type
  7840. closureTypeInst->Init(curProject);
  7841. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  7842. {
  7843. String fieldName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  7844. BfType* paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  7845. if ((implicitParamIdx == -1) && (captureThisByValue))
  7846. {
  7847. if (paramType->IsPointer())
  7848. paramType = paramType->GetUnderlyingType();
  7849. }
  7850. if (fieldName == "this")
  7851. fieldName = "__this";
  7852. closureTypeInst->AddField(paramType, fieldName);
  7853. }
  7854. closureTypeInst->Finish();
  7855. mModule->PopulateType(resolvedClosureType, BfPopulateType_Declaration);
  7856. }
  7857. else
  7858. {
  7859. // Already had this entry
  7860. delete checkClosureType;
  7861. }
  7862. useTypeInstance = closureTypeInst;
  7863. }
  7864. mModule->PopulateType(useTypeInstance);
  7865. if (delegateBindExpr->mTarget == NULL)
  7866. {
  7867. mModule->AssertErrorState();
  7868. return;
  7869. }
  7870. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  7871. // Do we need specialized calling code for this?
  7872. BfIRValue funcValue;
  7873. if (((needsSplat) || (implicitParamCount > 0) || (hasIncompatibleCallingConventions)) &&
  7874. (mModule->HasCompiledOutput()))
  7875. {
  7876. int fieldIdx = 0;
  7877. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  7878. {
  7879. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  7880. int gepIdx = fieldInst->mDataIdx;
  7881. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, gepIdx);
  7882. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  7883. if ((implicitParamIdx == -1) && (captureThisByValue))
  7884. {
  7885. if (fieldType->IsPointer())
  7886. fieldType = fieldType->GetUnderlyingType();
  7887. }
  7888. bool failed = false;
  7889. BfTypedValue lookupVal;
  7890. if (implicitParamIdx == -1)
  7891. lookupVal = target;
  7892. else
  7893. lookupVal = DoImplicitArgCapture(delegateBindExpr->mTarget, bindResult.mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_General, methodRefTarget);
  7894. if (!lookupVal)
  7895. continue;
  7896. if ((fieldType->IsPointer()) && (lookupVal.mType != fieldType))
  7897. {
  7898. BF_ASSERT(fieldType->GetUnderlyingType() == lookupVal.mType);
  7899. BF_ASSERT(lookupVal.IsAddr());
  7900. }
  7901. else if (!fieldType->IsRef())
  7902. lookupVal = mModule->LoadOrAggregateValue(lookupVal);
  7903. if (lookupVal)
  7904. mModule->mBfIRBuilder->CreateStore(lookupVal.mValue, fieldPtr);
  7905. fieldIdx++;
  7906. }
  7907. String methodName = _GetInvokeMethodName();
  7908. SizedArray<BfIRType, 8> irParamTypes;
  7909. BfIRType irReturnType;
  7910. bool hasThis = false;
  7911. if (hasCaptures)
  7912. {
  7913. hasThis = true;
  7914. methodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  7915. irParamTypes[0] = mModule->mBfIRBuilder->MapType(useTypeInstance);
  7916. }
  7917. else
  7918. {
  7919. BF_ASSERT(hasIncompatibleCallingConventions);
  7920. bindMethodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  7921. hasThis = bindMethodInstance->HasThis();
  7922. }
  7923. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  7924. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  7925. mModule->mBfIRBuilder->SaveDebugLocation();
  7926. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  7927. funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  7928. auto srcCallingConv = mModule->GetCallingConvention(methodInstance->GetOwner(), methodInstance->mMethodDef);
  7929. if ((!hasThis) && (methodInstance->mMethodDef->mCallingConvention == BfCallingConvention_Stdcall))
  7930. srcCallingConv = BfIRCallingConv_StdCall;
  7931. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  7932. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  7933. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  7934. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  7935. fieldIdx = 0;
  7936. SizedArray<BfIRValue, 8> irArgs;
  7937. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  7938. {
  7939. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  7940. int gepIdx = fieldInst->mDataIdx;
  7941. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  7942. bool disableSplat = false;
  7943. if ((implicitParamIdx == -1) && (captureThisByValue))
  7944. {
  7945. if (fieldType->IsPointer())
  7946. {
  7947. fieldType = fieldType->GetUnderlyingType();
  7948. disableSplat = true;
  7949. }
  7950. }
  7951. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->GetArgument(0), 0, gepIdx);
  7952. BfTypedValue typedVal(fieldPtr, fieldType, true);
  7953. PushArg(typedVal, irArgs, disableSplat);
  7954. fieldIdx++;
  7955. }
  7956. int argIdx = hasThis ? 1 : 0;
  7957. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  7958. {
  7959. auto paramType = methodInstance->GetParamType(paramIdx);
  7960. if (paramType->IsSplattable())
  7961. {
  7962. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++)); }, paramType);
  7963. }
  7964. else if (!paramType->IsValuelessType())
  7965. {
  7966. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++));
  7967. }
  7968. }
  7969. auto bindFuncVal = bindResult.mFunc;
  7970. if (mModule->mCompiler->mOptions.mAllowHotSwapping)
  7971. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  7972. auto result = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  7973. auto destCallingConv = mModule->GetCallingConvention(bindMethodInstance->GetOwner(), bindMethodInstance->mMethodDef);
  7974. if (destCallingConv != BfIRCallingConv_CDecl)
  7975. mModule->mBfIRBuilder->SetCallCallingConv(result, destCallingConv);
  7976. if (methodInstance->mReturnType->IsValuelessType())
  7977. {
  7978. mModule->mBfIRBuilder->CreateRetVoid();
  7979. }
  7980. else
  7981. {
  7982. mModule->mBfIRBuilder->CreateRet(result);
  7983. }
  7984. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  7985. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  7986. mModule->mBfIRBuilder->RestoreDebugLocation();
  7987. }
  7988. else if ((closureTypeInst != NULL) && (captureThisByValue))
  7989. {
  7990. // 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
  7991. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, 1);
  7992. target = mModule->LoadValue(target);
  7993. mModule->mBfIRBuilder->CreateStore(target.mValue, fieldPtr);
  7994. target = BfTypedValue(fieldPtr, target.mType, true);
  7995. }
  7996. BfResolvedArgs resolvedArgs;
  7997. MatchConstructor(delegateBindExpr, delegateBindExpr, mResult, useTypeInstance, resolvedArgs, false, false);
  7998. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  7999. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType, BfIRPopulateType_Full));
  8000. // >> delegate.mTarget = bindResult.mTarget
  8001. BfIRValue valPtr;
  8002. if (mModule->HasCompiledOutput())
  8003. {
  8004. if ((implicitParamCount > 0) || (needsSplat)) // Point back to self, it contains capture data
  8005. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  8006. else if (bindResult.mTarget)
  8007. valPtr = mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  8008. else
  8009. valPtr = mModule->GetDefaultValue(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  8010. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 2);
  8011. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  8012. }
  8013. if (!funcValue)
  8014. {
  8015. funcValue = bindResult.mFunc;
  8016. if (!funcValue)
  8017. {
  8018. if ((mModule->HasCompiledOutput()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  8019. mModule->AssertErrorState();
  8020. return;
  8021. }
  8022. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!bindResult.mMethodInstance->mMethodDef->mIsVirtual))
  8023. {
  8024. funcValue = mModule->mBfIRBuilder->RemapBindFunction(funcValue);
  8025. }
  8026. }
  8027. // >> delegate.mFuncPtr = bindResult.mFunc
  8028. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  8029. valPtr = mModule->mBfIRBuilder->CreateBitCast(funcValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  8030. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 1);
  8031. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  8032. }
  8033. void BfExprEvaluator::VisitLambdaBodies(BfAstNode* body, BfFieldDtorDeclaration* fieldDtor)
  8034. {
  8035. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  8036. mModule->VisitChild(blockBody);
  8037. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  8038. mModule->CreateValueFromExpression(bodyExpr);
  8039. while (fieldDtor != NULL)
  8040. {
  8041. mModule->VisitChild(fieldDtor->mBody);
  8042. fieldDtor = fieldDtor->mNextFieldDtor;
  8043. }
  8044. }
  8045. BfLambdaInstance* BfExprEvaluator::GetLambdaInstance(BfLambdaBindExpression* lambdaBindExpr)
  8046. {
  8047. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  8048. BfLambdaInstance* lambdaInstance = NULL;
  8049. if (rootMethodState->mLambdaCache.TryGetValue(lambdaBindExpr, &lambdaInstance))
  8050. return lambdaInstance;
  8051. static int sBindCount = 0;
  8052. sBindCount++;
  8053. bool isFunctionBind = false;
  8054. BfTypeInstance* delegateTypeInstance = NULL;
  8055. BfMethodInstance* invokeMethodInstance = NULL;
  8056. if (mExpectingType == NULL)
  8057. {
  8058. mModule->Fail("Cannot infer delegate type", lambdaBindExpr);
  8059. delegateTypeInstance = mModule->mContext->mBfObjectType;
  8060. }
  8061. else
  8062. {
  8063. delegateTypeInstance = mExpectingType->ToTypeInstance();
  8064. if ((delegateTypeInstance == NULL) ||
  8065. ((!delegateTypeInstance->mTypeDef->mIsDelegate) && (!delegateTypeInstance->mTypeDef->mIsFunction)))
  8066. {
  8067. if (lambdaBindExpr->mFatArrowToken != NULL)
  8068. mModule->Fail("Can only bind lambdas to delegate types", lambdaBindExpr->mFatArrowToken);
  8069. delegateTypeInstance = mModule->mContext->mBfObjectType;
  8070. }
  8071. else
  8072. {
  8073. invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  8074. }
  8075. isFunctionBind = delegateTypeInstance->mTypeDef->mIsFunction;
  8076. }
  8077. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(lambdaBindExpr->mNewToken))
  8078. {
  8079. if (isFunctionBind)
  8080. {
  8081. mModule->Fail("Function lambda binding does not require allocation", lambdaBindExpr->mNewToken);
  8082. }
  8083. else if (tokenNode->GetToken() == BfToken_Append)
  8084. {
  8085. mModule->Fail("Append allocation on delegate bind not supported", lambdaBindExpr->mNewToken);
  8086. }
  8087. }
  8088. if (invokeMethodInstance != NULL)
  8089. {
  8090. if ((int)lambdaBindExpr->mParams.size() < invokeMethodInstance->GetParamCount())
  8091. {
  8092. BfAstNode* refNode = lambdaBindExpr->mCloseParen;
  8093. if (refNode == NULL)
  8094. refNode = lambdaBindExpr;
  8095. mModule->Fail(StrFormat("Not enough parameters for delegate type '%s'. Expected %d more.",
  8096. mModule->TypeToString(delegateTypeInstance).c_str(), invokeMethodInstance->GetParamCount() - lambdaBindExpr->mParams.size()), refNode);
  8097. }
  8098. else if ((int)lambdaBindExpr->mParams.size() > invokeMethodInstance->GetParamCount())
  8099. {
  8100. BfAstNode* refNode = lambdaBindExpr->mParams[invokeMethodInstance->GetParamCount()];
  8101. mModule->Fail(StrFormat("Too many parameters for delegate type '%s'. Expected %d fewer.",
  8102. mModule->TypeToString(delegateTypeInstance).c_str(), lambdaBindExpr->mParams.size() - invokeMethodInstance->GetParamCount()), refNode);
  8103. }
  8104. }
  8105. auto autoComplete = GetAutoComplete();
  8106. bool wasCapturingMethodInfo = false;
  8107. if ((autoComplete != NULL) && (invokeMethodInstance != NULL))
  8108. {
  8109. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  8110. autoComplete->CheckInvocation(lambdaBindExpr, lambdaBindExpr->mOpenParen, lambdaBindExpr->mCloseParen, lambdaBindExpr->mCommas);
  8111. if (autoComplete->mIsCapturingMethodMatchInfo)
  8112. {
  8113. autoComplete->mMethodMatchInfo->mInstanceList.Clear();
  8114. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  8115. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  8116. methodMatchEntry.mTypeInstance = invokeMethodInstance->GetOwner();
  8117. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  8118. methodMatchEntry.mMethodDef = invokeMethodInstance->mMethodDef;
  8119. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  8120. methodMatchInfo->mBestIdx = 0;
  8121. methodMatchInfo->mMostParamsMatched = 0;
  8122. int cursorIdx = lambdaBindExpr->GetParser()->mCursorIdx;
  8123. if ((lambdaBindExpr->mCloseParen == NULL) || (cursorIdx <= lambdaBindExpr->mCloseParen->GetSrcStart()))
  8124. {
  8125. int paramIdx = 0;
  8126. for (int commaIdx = 0; commaIdx < (int)lambdaBindExpr->mCommas.size(); commaIdx++)
  8127. {
  8128. auto commaNode = lambdaBindExpr->mCommas[commaIdx];
  8129. if ((commaNode != NULL) && (cursorIdx >= commaNode->GetSrcStart()))
  8130. paramIdx = commaIdx + 1;
  8131. }
  8132. bool isEmpty = true;
  8133. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  8134. {
  8135. auto paramNode = lambdaBindExpr->mParams[paramIdx];
  8136. if (paramNode != NULL)
  8137. isEmpty = false;
  8138. }
  8139. if (isEmpty)
  8140. {
  8141. if (paramIdx < (int)invokeMethodInstance->GetParamCount())
  8142. {
  8143. String paramName = invokeMethodInstance->GetParamName(paramIdx);
  8144. autoComplete->mEntriesSet.Clear();
  8145. autoComplete->AddEntry(AutoCompleteEntry("paramName", paramName));
  8146. autoComplete->mInsertStartIdx = cursorIdx;
  8147. autoComplete->mInsertEndIdx = cursorIdx;
  8148. if ((paramIdx == 0) && (lambdaBindExpr->mParams.IsEmpty()))
  8149. {
  8150. String totalNames;
  8151. for (int checkIdx = 0; checkIdx < (int)invokeMethodInstance->GetParamCount(); checkIdx++)
  8152. {
  8153. if (!totalNames.IsEmpty())
  8154. totalNames += ", ";
  8155. totalNames += invokeMethodInstance->GetParamName(checkIdx);
  8156. }
  8157. autoComplete->AddEntry(AutoCompleteEntry("paramNames", totalNames));
  8158. }
  8159. }
  8160. }
  8161. }
  8162. }
  8163. }
  8164. defer
  8165. {
  8166. if (autoComplete != NULL)
  8167. autoComplete->mIsCapturingMethodMatchInfo = (wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo);
  8168. };
  8169. if (lambdaBindExpr->mBody == NULL)
  8170. {
  8171. mModule->AssertErrorState();
  8172. return NULL;
  8173. }
  8174. if (lambdaBindExpr->mNewToken == NULL)
  8175. {
  8176. if (lambdaBindExpr->mDtor != NULL)
  8177. {
  8178. mModule->Fail("Valueless method reference cannot contain destructor. Consider either removing destructor or using an allocated lambda.", lambdaBindExpr->mDtor->mTildeToken);
  8179. // Eat it
  8180. auto fieldDtor = lambdaBindExpr->mDtor;
  8181. while (fieldDtor != NULL)
  8182. {
  8183. mModule->VisitEmbeddedStatement(fieldDtor->mBody);
  8184. fieldDtor = fieldDtor->mNextFieldDtor;
  8185. }
  8186. }
  8187. if (invokeMethodInstance != NULL)
  8188. {
  8189. BfLocalMethod* localMethod = new BfLocalMethod();
  8190. localMethod->mMethodName = "anon";
  8191. localMethod->mSystem = mModule->mSystem;
  8192. localMethod->mModule = mModule;
  8193. localMethod->mExpectedFullName = mModule->GetLocalMethodName(localMethod->mMethodName, lambdaBindExpr->mFatArrowToken, mModule->mCurMethodState, mModule->mCurMethodState->mMixinState);
  8194. localMethod->mLambdaInvokeMethodInstance = invokeMethodInstance;
  8195. localMethod->mLambdaBindExpr = lambdaBindExpr;
  8196. localMethod->mDeclMethodState = mModule->mCurMethodState;
  8197. mModule->mContext->mLocalMethodGraveyard.push_back(localMethod);
  8198. auto moduleMethodInstance = mModule->GetLocalMethodInstance(localMethod, BfTypeVector());
  8199. auto methodRefType = mModule->CreateMethodRefType(moduleMethodInstance.mMethodInstance);
  8200. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  8201. mModule->AddCallDependency(moduleMethodInstance.mMethodInstance);
  8202. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  8203. return NULL;
  8204. }
  8205. }
  8206. //SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites);
  8207. SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites || mModule->mCurMethodInstance->mIsUnspecialized);
  8208. BfTypeInstance* outerClosure = NULL;
  8209. if ((mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  8210. outerClosure = mModule->mCurMethodState->mClosureState->mClosureType;
  8211. Val128 val128(delegateTypeInstance->mTypeId);
  8212. BfMethodState methodState;
  8213. methodState.mPrevMethodState = mModule->mCurMethodState;
  8214. BfIRFunctionType funcType;
  8215. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  8216. SizedArray<BfIRType, 0> paramTypes;
  8217. funcType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), paramTypes, false);
  8218. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  8219. BF_ASSERT(prevInsertBlock);
  8220. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  8221. mModule->mBfIRBuilder->SaveDebugLocation();
  8222. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  8223. BfDeferredLocalAssignData deferredLocalAssignData;
  8224. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  8225. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData);
  8226. SetAndRestoreValue<BfMethodState*> prevMethodState(mModule->mCurMethodState, &methodState);
  8227. methodState.mIRHeadBlock = mModule->mBfIRBuilder->CreateBlock("head", true);
  8228. methodState.mIRInitBlock = mModule->mBfIRBuilder->CreateBlock("init", true);
  8229. methodState.mIREntryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  8230. methodState.mCurScope->mDIScope = prevMethodState.mPrevVal->mCurScope->mDIScope;//invokeMethodInstance->mDIFunction;
  8231. methodState.mCurLocalVarId = -1;
  8232. methodState.mIRFunction = prevMethodState.mPrevVal->mIRFunction;
  8233. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  8234. mModule->mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  8235. BfClosureState closureState;
  8236. if (delegateTypeInstance->IsDelegate())
  8237. closureState.mReturnType = mModule->GetDelegateReturnType(delegateTypeInstance);
  8238. else
  8239. closureState.mReturnType = mModule->mContext->mBfObjectType;
  8240. closureState.mCapturing = true;
  8241. closureState.mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  8242. methodState.mClosureState = &closureState;
  8243. closureState.mClosureType = outerClosure;
  8244. BF_ASSERT(methodState.mCurLocalVarId == -1);
  8245. int outerLocalsCount = (int)methodState.mLocals.size();
  8246. // static int sItrCount = 0;
  8247. // ++sItrCount;
  8248. // int itrCount = sItrCount;
  8249. // if ((itrCount == 8) || (itrCount == 10))
  8250. // {
  8251. // NOP;
  8252. // }
  8253. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  8254. HashContext hashCtx;
  8255. hashCtx.MixinStr(delegateTypeName);
  8256. BfSource* bfSource = delegateTypeInstance->mTypeDef->mSource;
  8257. BfMethodDef* methodDef = new BfMethodDef();
  8258. methodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  8259. Val128 closureMethodHash;
  8260. OwnedVector<BfParameterDeclaration> tempParamDecls;
  8261. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(lambdaBindExpr->mBody)))
  8262. {
  8263. // Don't show outer method match info when our cursor is inside a lambda expression (being passed as a parameter)
  8264. autoComplete->RemoveMethodMatchInfo();
  8265. }
  8266. if (invokeMethodInstance != NULL)
  8267. {
  8268. for (int paramIdx = 0; paramIdx < (int)invokeMethodInstance->mMethodDef->mParams.size(); paramIdx++)
  8269. {
  8270. auto invokeParamDef = invokeMethodInstance->mMethodDef->mParams[paramIdx];
  8271. BfParameterDef* paramDef = new BfParameterDef();
  8272. paramDef->mParamDeclaration = tempParamDecls.Alloc();
  8273. BfLocalVariable* localVar = new BfLocalVariable();
  8274. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  8275. {
  8276. localVar->mName = lambdaBindExpr->mParams[paramIdx]->ToString();
  8277. localVar->mNameNode = lambdaBindExpr->mParams[paramIdx];
  8278. paramDef->mParamDeclaration->mNameNode = lambdaBindExpr->mParams[paramIdx];
  8279. }
  8280. else
  8281. {
  8282. mModule->AssertErrorState();
  8283. localVar->mName = invokeParamDef->mName;
  8284. paramDef->mParamDeclaration->mNameNode = NULL;
  8285. }
  8286. paramDef->mName = localVar->mName;
  8287. methodDef->mParams.push_back(paramDef);
  8288. localVar->mResolvedType = invokeMethodInstance->GetParamType(paramIdx);
  8289. localVar->mIsAssigned = true;
  8290. localVar->mReadFromId = 0;
  8291. auto rootMethodState = methodState.GetRootMethodState();
  8292. localVar->mLocalVarId = rootMethodState->mCurLocalVarId++;
  8293. mModule->DoAddLocalVariable(localVar);
  8294. if (autoComplete != NULL)
  8295. autoComplete->CheckLocalDef(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), methodState.mLocals.back());
  8296. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  8297. if (resolvePassData != NULL)
  8298. resolvePassData->HandleLocalReference(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), mModule->mCurTypeInstance->mTypeDef,
  8299. mModule->mCurMethodInstance->mMethodDef, localVar->mLocalVarId);
  8300. }
  8301. }
  8302. bool isAutocomplete = mModule->mCompiler->IsAutocomplete();
  8303. methodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  8304. methodDef->mBody = lambdaBindExpr->mBody;
  8305. ///
  8306. BfClosureInstanceInfo* closureInstanceInfo = new BfClosureInstanceInfo();
  8307. auto checkInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  8308. closureState.mCaptureStartAccessId = methodState.mPrevMethodState->GetRootMethodState()->mCurAccessId;
  8309. closureState.mCaptureVisitingBody = true;
  8310. closureState.mClosureInstanceInfo = closureInstanceInfo;
  8311. VisitLambdaBodies(lambdaBindExpr->mBody, lambdaBindExpr->mDtor);
  8312. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  8313. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  8314. {
  8315. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  8316. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  8317. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  8318. }
  8319. if (mModule->mCurMethodInstance->mIsUnspecialized)
  8320. {
  8321. prevIgnoreWrites.Restore();
  8322. mModule->mBfIRBuilder->RestoreDebugLocation();
  8323. mResult = mModule->GetDefaultTypedValue(delegateTypeInstance);
  8324. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  8325. if (!prevInsertBlock.IsFake())
  8326. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8327. delete methodDef;
  8328. delete closureInstanceInfo;
  8329. return NULL;
  8330. }
  8331. closureState.mCaptureVisitingBody = false;
  8332. prevIgnoreWrites.Restore();
  8333. mModule->mBfIRBuilder->RestoreDebugLocation();
  8334. BfCaptureType captureType = BfCaptureType_Value;
  8335. if ((lambdaBindExpr->mLambdaCapture != NULL) && (lambdaBindExpr->mLambdaCapture->mCaptureToken != NULL))
  8336. {
  8337. if (lambdaBindExpr->mLambdaCapture->mCaptureToken->GetToken() == BfToken_Ampersand)
  8338. captureType = BfCaptureType_Reference;
  8339. else
  8340. captureType = BfCaptureType_Copy;
  8341. }
  8342. Array<BfClosureCapturedEntry> capturedEntries;
  8343. bool copyOuterCaptures = false;
  8344. {
  8345. auto varMethodState = methodState.mPrevMethodState;
  8346. while (varMethodState != NULL)
  8347. {
  8348. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  8349. {
  8350. auto localVar = varMethodState->mLocals[localIdx];
  8351. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  8352. {
  8353. if ((localVar->mIsThis) && (outerClosure != NULL))
  8354. {
  8355. continue;
  8356. }
  8357. auto outerLocal = localVar;
  8358. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  8359. {
  8360. closureState.mConstLocals.push_back(*outerLocal);
  8361. continue;
  8362. }
  8363. BfClosureCapturedEntry capturedEntry;
  8364. auto capturedType = outerLocal->mResolvedType;
  8365. bool captureByRef = false;
  8366. if (!capturedType->IsRef())
  8367. {
  8368. if (captureType == BfCaptureType_Reference)
  8369. {
  8370. if (outerLocal->mIsThis)
  8371. {
  8372. if ((outerLocal->mResolvedType->IsValueType()) && (mModule->mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  8373. captureByRef = true;
  8374. }
  8375. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  8376. captureByRef = true;
  8377. }
  8378. }
  8379. else
  8380. {
  8381. if ((captureType != BfCaptureType_Reference) || (localVar->mWrittenToId < closureState.mCaptureStartAccessId))
  8382. {
  8383. capturedType = ((BfRefType*)capturedType)->mElementType;
  8384. }
  8385. }
  8386. if (captureByRef)
  8387. {
  8388. capturedType = mModule->CreateRefType(capturedType);
  8389. }
  8390. capturedEntry.mType = capturedType;
  8391. if (outerLocal->mName == "this")
  8392. capturedEntry.mName = "__this";
  8393. else
  8394. capturedEntry.mName = outerLocal->mName;
  8395. capturedEntry.mNameNode = outerLocal->mNameNode;
  8396. capturedEntries.Add(capturedEntry);
  8397. }
  8398. }
  8399. varMethodState = varMethodState->mPrevMethodState;
  8400. if (varMethodState == NULL)
  8401. break;
  8402. if (varMethodState->mMixinState != NULL)
  8403. break;
  8404. if (varMethodState->mClosureState != NULL)
  8405. {
  8406. if (!varMethodState->mClosureState->mCapturing)
  8407. break;
  8408. }
  8409. }
  8410. }
  8411. for (auto copyField : closureState.mReferencedOuterClosureMembers)
  8412. {
  8413. auto fieldDef = copyField->GetFieldDef();
  8414. BfClosureCapturedEntry capturedEntry;
  8415. capturedEntry.mName = fieldDef->mName;
  8416. capturedEntry.mType = copyField->mResolvedType;
  8417. if ((captureType == BfCaptureType_Reference) && (capturedEntry.mType->IsRef()))
  8418. {
  8419. capturedEntry.mExplicitlyByReference = true;
  8420. }
  8421. else if ((captureType != BfCaptureType_Reference) && (capturedEntry.mType->IsRef()))
  8422. {
  8423. auto refType = (BfRefType*)capturedEntry.mType;
  8424. capturedEntry.mType = refType->mElementType;
  8425. }
  8426. else if ((captureType == BfCaptureType_Reference) && (!capturedEntry.mType->IsRef()) && (!fieldDef->mIsReadOnly))
  8427. {
  8428. capturedEntry.mType = mModule->CreateRefType(capturedEntry.mType);
  8429. }
  8430. }
  8431. std::sort(capturedEntries.begin(), capturedEntries.end());
  8432. bool hasCapture = false;
  8433. BfMethodInstanceGroup methodInstanceGroup;
  8434. methodInstanceGroup.mOwner = mModule->mCurTypeInstance;
  8435. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  8436. BfMethodInstance* methodInstance = new BfMethodInstance();
  8437. methodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  8438. methodInstance->GetMethodInfoEx()->mClosureInstanceInfo = closureInstanceInfo;
  8439. if (invokeMethodInstance != NULL)
  8440. methodInstance->mParams = invokeMethodInstance->mParams;
  8441. methodInstance->mIsClosure = true;
  8442. // We want the closure ID to match between hot reloads -- otherwise we wouldn't be able to modify them,
  8443. // so we use the charId from the 'fat arrow' token
  8444. int closureId = 0;
  8445. if (lambdaBindExpr->mFatArrowToken != NULL)
  8446. closureId = lambdaBindExpr->mFatArrowToken->GetStartCharId();
  8447. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  8448. BF_ASSERT(curProject != NULL);
  8449. // We need to make these per-project even though you'd think we might not because we
  8450. // insert generic type specializations in the generic definition's project,
  8451. // BECAUSE: we would need to scan the captured fields the same way we scan the
  8452. // generic arguments to determine if each project can see it or not in the vdata
  8453. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  8454. BfClosureType* closureTypeInst = NULL;
  8455. if ((capturedEntries.size() != 0) || (lambdaBindExpr->mDtor != NULL) || (copyOuterCaptures))
  8456. {
  8457. hashCtx.MixinStr(curProject->mName);
  8458. if (copyOuterCaptures)
  8459. {
  8460. // String typeName = mModule->DoTypeToString(outerClosure, BfTypeNameFlag_DisambiguateDups);
  8461. // hashCtx.MixinStr(typeName);
  8462. hashCtx.Mixin(outerClosure->mTypeId);
  8463. }
  8464. for (auto& capturedEntry : capturedEntries)
  8465. {
  8466. // String typeName = mModule->DoTypeToString(capturedEntry.mType, BfTypeNameFlag_DisambiguateDups);
  8467. // hashCtx.MixinStr(typeName);
  8468. hashCtx.Mixin(capturedEntry.mType->mTypeId);
  8469. hashCtx.MixinStr(capturedEntry.mName);
  8470. hashCtx.Mixin(capturedEntry.mExplicitlyByReference);
  8471. }
  8472. if (lambdaBindExpr->mDtor != NULL)
  8473. {
  8474. // Has DTOR thunk
  8475. bool hasDtorThunk = true;
  8476. hashCtx.Mixin(hasDtorThunk);
  8477. }
  8478. Val128 hash128 = hashCtx.Finish128();
  8479. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  8480. checkClosureType->mContext = mModule->mContext;
  8481. checkClosureType->mBaseType = delegateTypeInstance;
  8482. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_Identity);
  8483. closureTypeInst = (BfClosureType*)resolvedClosureType;
  8484. if (checkClosureType == resolvedClosureType)
  8485. {
  8486. // This is a new closure type
  8487. closureTypeInst->Init(curProject);
  8488. closureTypeInst->mTypeDef->mProject = curProject;
  8489. if (copyOuterCaptures)
  8490. {
  8491. for (auto& fieldInstance : outerClosure->mFieldInstances)
  8492. {
  8493. BfFieldDef* origFieldDef = fieldInstance.GetFieldDef();
  8494. BfFieldDef* fieldDef = closureTypeInst->AddField(fieldInstance.mResolvedType, origFieldDef->mName);
  8495. fieldDef->mIsReadOnly = origFieldDef->mIsReadOnly;
  8496. }
  8497. }
  8498. for (auto& capturedEntry : capturedEntries)
  8499. {
  8500. BfFieldDef* fieldDef = closureTypeInst->AddField(capturedEntry.mType, capturedEntry.mName);
  8501. if (!capturedEntry.mExplicitlyByReference)
  8502. fieldDef->mIsReadOnly = true;
  8503. }
  8504. if (lambdaBindExpr->mDtor != NULL)
  8505. {
  8506. auto dtorDef = closureTypeInst->AddDtor();
  8507. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  8508. auto voidPtrType = mModule->CreatePointerType(voidType);
  8509. closureTypeInst->AddField(voidPtrType, "__dtorThunk");
  8510. }
  8511. closureTypeInst->Finish();
  8512. }
  8513. else
  8514. {
  8515. // Already had this entry
  8516. delete checkClosureType;
  8517. }
  8518. useTypeInstance = closureTypeInst;
  8519. }
  8520. mModule->mBfIRBuilder->PopulateType(useTypeInstance);
  8521. mModule->PopulateType(useTypeInstance);
  8522. // If we are allowing hot swapping, we need to always mangle the name to non-static because if we add a capture
  8523. // later then we need to have the mangled names match
  8524. methodDef->mIsStatic = (closureTypeInst == NULL) && (!mModule->mCompiler->mOptions.mAllowHotSwapping);
  8525. SizedArray<BfIRType, 3> newTypes;
  8526. SizedArray<BfIRType, 8> origParamTypes;
  8527. BfIRType origReturnType;
  8528. if (!methodDef->mIsStatic)
  8529. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  8530. if (invokeMethodInstance != NULL)
  8531. {
  8532. auto invokeFunctionType = mModule->mBfIRBuilder->MapMethod(invokeMethodInstance);
  8533. invokeMethodInstance->GetIRFunctionInfo(mModule, origReturnType, origParamTypes, methodDef->mIsStatic);
  8534. }
  8535. else
  8536. {
  8537. origReturnType = mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_None));
  8538. }
  8539. for (int i = methodDef->mIsStatic ? 0 : 1; i < (int)origParamTypes.size(); i++)
  8540. newTypes.push_back(origParamTypes[i]);
  8541. auto closureFuncType = mModule->mBfIRBuilder->CreateFunctionType(origReturnType, newTypes, false);
  8542. prevMethodState.Restore();
  8543. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  8544. if (!prevInsertBlock.IsFake())
  8545. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8546. // Just a check
  8547. mModule->mBfIRBuilder->GetInsertBlock();
  8548. //auto rootMethodState = mModule->mCurMethodState;
  8549. HashContext closureHashCtx;
  8550. closureHashCtx.Mixin(closureId);
  8551. // When we're a nested lambda, strip off the outer hash and closureTypeInst markers
  8552. methodDef->mName = mModule->mCurMethodInstance->mMethodDef->mName;
  8553. int prevSepPos = (int)methodDef->mName.LastIndexOf('$');
  8554. if (prevSepPos != -1)
  8555. {
  8556. closureHashCtx.Mixin(methodDef->mName.c_str() + prevSepPos, (int)methodDef->mName.length() - prevSepPos);
  8557. methodDef->mName.RemoveToEnd(prevSepPos);
  8558. }
  8559. // if (closureTypeInst != NULL)
  8560. // {
  8561. // StringT<128> typeInstName;
  8562. // BfMangler::Mangle(typeInstName,mModule->mCompiler->GetMangleKind(), closureTypeInst);
  8563. // closureHashCtx.MixinStr(typeInstName);
  8564. // }
  8565. auto checkMethodState = mModule->mCurMethodState;
  8566. while (checkMethodState != NULL)
  8567. {
  8568. if (checkMethodState->mMethodInstance != NULL)
  8569. {
  8570. if (checkMethodState->mMethodInstance->mMethodInfoEx != NULL)
  8571. {
  8572. for (auto methodGenericArg : checkMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  8573. {
  8574. StringT<128> genericTypeName;
  8575. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  8576. closureHashCtx.MixinStr(genericTypeName);
  8577. }
  8578. }
  8579. }
  8580. checkMethodState = checkMethodState->mPrevMethodState;
  8581. }
  8582. uint64 closureHash = closureHashCtx.Finish64();
  8583. methodDef->mName += "$";
  8584. methodDef->mName += BfTypeUtils::HashEncode64(closureHash);
  8585. methodInstance->mMethodDef = methodDef;
  8586. if (invokeMethodInstance != NULL)
  8587. {
  8588. methodInstance->mParams = invokeMethodInstance->mParams;
  8589. methodInstance->mReturnType = invokeMethodInstance->mReturnType;
  8590. }
  8591. else
  8592. methodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  8593. StringT<128> closureFuncName;
  8594. BfMangler::Mangle(closureFuncName, mModule->mCompiler->GetMangleKind(), methodInstance);
  8595. auto closureFunc = mModule->mBfIRBuilder->CreateFunction(closureFuncType, BfIRLinkageType_External, closureFuncName);
  8596. methodInstance->mIRFunction = closureFunc;
  8597. if (methodInstance->mIsReified)
  8598. mModule->CheckHotMethod(methodInstance, closureFuncName);
  8599. if ((methodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  8600. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(methodInstance->mHotMethod);
  8601. methodState.Reset();
  8602. lambdaInstance = new BfLambdaInstance();
  8603. rootMethodState->mLambdaCache[lambdaBindExpr] = lambdaInstance;
  8604. lambdaInstance->mDelegateTypeInstance = delegateTypeInstance;
  8605. lambdaInstance->mUseTypeInstance = useTypeInstance;
  8606. lambdaInstance->mClosureTypeInstance = closureTypeInst;
  8607. lambdaInstance->mOuterClosure = outerClosure;
  8608. lambdaInstance->mCopyOuterCaptures = copyOuterCaptures;
  8609. lambdaInstance->mIsStatic = methodDef->mIsStatic;
  8610. lambdaInstance->mClosureFunc = closureFunc;
  8611. lambdaInstance->mMethodInstance = methodInstance;
  8612. lambdaInstance->mConstLocals = closureState.mConstLocals;
  8613. lambdaInstance->mParamDecls = tempParamDecls;
  8614. lambdaInstance->mDeclMixinState = mModule->mCurMethodState->mMixinState;
  8615. if (lambdaInstance->mDeclMixinState != NULL)
  8616. lambdaInstance->mDeclMixinState->mHasDeferredUsage = true;
  8617. tempParamDecls.ClearWithoutDeleting();
  8618. closureState.mCapturing = false;
  8619. closureState.mClosureType = useTypeInstance;
  8620. closureInstanceInfo->mThisOverride = useTypeInstance;
  8621. mModule->mIncompleteMethodCount++;
  8622. SetAndRestoreValue<BfClosureState*> prevClosureState(mModule->mCurMethodState->mClosureState, &closureState);
  8623. if (mModule->HasCompiledOutput())
  8624. mModule->SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  8625. // This keeps us from giving errors twice. ProcessMethod can give errors when we capture by value but needed to
  8626. // capture by reference, so we still need to do it for resolve-only
  8627. bool processMethods = (mModule->mCompiler->GetAutoComplete() == NULL) && !mModule->mHadBuildError;
  8628. mModule->mBfIRBuilder->SaveDebugLocation();
  8629. //
  8630. {
  8631. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  8632. if (mModule->mCompiler->mResolvePassData != NULL)
  8633. {
  8634. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  8635. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  8636. }
  8637. if (processMethods)
  8638. {
  8639. // If we are in an always-ignored block, we will have mIgnoreWrites set
  8640. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  8641. // mModule->ProcessMethod(methodInstance);
  8642. }
  8643. if (mModule->mCompiler->mResolvePassData != NULL)
  8644. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  8645. }
  8646. mModule->mBfIRBuilder->RestoreDebugLocation();
  8647. if (mModule->mCompiler->IsSkippingExtraResolveChecks())
  8648. closureFunc = BfIRFunction();
  8649. BfIRFunction dtorFunc;
  8650. if (lambdaBindExpr->mDtor != NULL)
  8651. {
  8652. SizedArray<BfIRType, 1> newTypes;
  8653. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  8654. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  8655. auto dtorFuncType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), newTypes, false);
  8656. BfMethodDef* dtorMethodDef = new BfMethodDef();
  8657. dtorMethodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  8658. dtorMethodDef->mName = "~this$";
  8659. dtorMethodDef->mName += methodDef->mName;
  8660. dtorMethodDef->mMethodType = BfMethodType_Normal;
  8661. dtorMethodDef->mBody = lambdaBindExpr->mDtor;
  8662. dtorMethodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  8663. BfMethodInstance* dtorMethodInstance = new BfMethodInstance();
  8664. dtorMethodInstance->mMethodDef = dtorMethodDef;
  8665. dtorMethodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  8666. dtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  8667. StringT<128> dtorMangledName;
  8668. BfMangler::Mangle(dtorMangledName, mModule->mCompiler->GetMangleKind(), dtorMethodInstance);
  8669. dtorFunc = mModule->mBfIRBuilder->CreateFunction(dtorFuncType, BfIRLinkageType_External, dtorMangledName);
  8670. mModule->SetupIRMethod(NULL, dtorFunc, false);
  8671. dtorMethodInstance->mIRFunction = dtorFunc;
  8672. mModule->mIncompleteMethodCount++;
  8673. mModule->mBfIRBuilder->SaveDebugLocation();
  8674. //
  8675. if (processMethods)
  8676. {
  8677. // If we are in an always-ignored block, we will have mIgnoreWrites set
  8678. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  8679. // mModule->ProcessMethod(dtorMethodInstance);
  8680. }
  8681. mModule->mBfIRBuilder->RestoreDebugLocation();
  8682. if (mModule->mCompiler->IsSkippingExtraResolveChecks())
  8683. dtorFunc = BfIRFunction();
  8684. if (dtorMethodInstance->mIsReified)
  8685. mModule->CheckHotMethod(dtorMethodInstance, dtorMangledName);
  8686. if ((dtorMethodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  8687. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(dtorMethodInstance->mHotMethod);
  8688. lambdaInstance->mDtorMethodInstance = dtorMethodInstance;
  8689. lambdaInstance->mDtorFunc = dtorFunc;
  8690. }
  8691. prevClosureState.Restore();
  8692. if (!prevInsertBlock.IsFake())
  8693. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  8694. for (auto& capturedEntry : capturedEntries)
  8695. {
  8696. BfLambdaCaptureInfo lambdaCapture;
  8697. if (capturedEntry.mName == "__this")
  8698. lambdaCapture.mName = "this";
  8699. else
  8700. lambdaCapture.mName = capturedEntry.mName;
  8701. // if (capturedEntry.mLocalVarDef != NULL)
  8702. // lambdaCapture.mLocalIdx = capturedEntry.mLocalVarDef->mLocalVarId;
  8703. // lambdaCapture.mCopyField = capturedEntry.mCopyField;
  8704. lambdaInstance->mCaptures.Add(lambdaCapture);
  8705. closureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  8706. }
  8707. if (processMethods)
  8708. rootMethodState->mDeferredLambdaInstances.Add(lambdaInstance);
  8709. methodInstance->mMethodInstanceGroup = NULL;
  8710. return lambdaInstance;
  8711. }
  8712. void BfExprEvaluator::Visit(BfLambdaBindExpression* lambdaBindExpr)
  8713. {
  8714. // if (lambdaBindExpr->ToString() == "new (addr, byteCount, addrType) => { DoCreateMemoryBreakpoint(addr, byteCount, addrType, showOptions); }")
  8715. // {
  8716. // NOP;
  8717. // }
  8718. BfTokenNode* newToken = NULL;
  8719. BfAllocTarget allocTarget = ResolveAllocTarget(lambdaBindExpr->mNewToken, newToken);
  8720. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mBlindCapturing))
  8721. {
  8722. // We're just capturing. We just need to visit the bodies here. This helps infinite recursion with local methods containing lambdas calling each other
  8723. if (lambdaBindExpr->mBody != NULL)
  8724. mModule->VisitChild(lambdaBindExpr->mBody);
  8725. if ((lambdaBindExpr->mDtor != NULL) && (lambdaBindExpr->mDtor->mBody != NULL))
  8726. mModule->VisitChild(lambdaBindExpr->mDtor->mBody);
  8727. return;
  8728. }
  8729. BfLambdaInstance* lambdaInstance = GetLambdaInstance(lambdaBindExpr);
  8730. if (lambdaInstance == NULL)
  8731. return;
  8732. BfTypeInstance* delegateTypeInstance = lambdaInstance->mDelegateTypeInstance;
  8733. BfTypeInstance* useTypeInstance = lambdaInstance->mUseTypeInstance;
  8734. BfTypeInstance* closureTypeInst = lambdaInstance->mClosureTypeInstance;
  8735. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  8736. if (!delegateTypeInstance->IsDelegate())
  8737. {
  8738. mModule->AssertErrorState();
  8739. return;
  8740. }
  8741. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  8742. if (baseDelegateType == NULL)
  8743. {
  8744. mModule->Fail("Invalid delegate type", lambdaBindExpr);
  8745. return;
  8746. }
  8747. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType));
  8748. // >> delegate.mTarget = bindResult.mTarget
  8749. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  8750. BfIRValue valPtr;
  8751. if (!lambdaInstance->mIsStatic)
  8752. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  8753. else
  8754. valPtr = mModule->GetDefaultValue(nullPtrType);
  8755. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 2);
  8756. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  8757. // >> delegate.mFuncPtr = bindResult.mFunc
  8758. if (lambdaInstance->mClosureFunc)
  8759. {
  8760. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  8761. auto valPtr = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mClosureFunc, mModule->mBfIRBuilder->MapType(nullPtrType));
  8762. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 1);
  8763. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  8764. }
  8765. mModule->AddDependency(useTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  8766. // Copy captures into the delegate
  8767. if (lambdaInstance->mClosureTypeInstance != NULL)
  8768. {
  8769. int fieldIdx = 0;
  8770. if (lambdaInstance->mCopyOuterCaptures)
  8771. {
  8772. for (auto& fieldInstance : lambdaInstance->mOuterClosure->mFieldInstances)
  8773. {
  8774. if (!fieldInstance.mResolvedType->IsValuelessType())
  8775. {
  8776. BF_ASSERT(fieldInstance.mDataIdx == fieldIdx + 1);
  8777. auto localVar = mModule->mCurMethodState->mLocals[0];
  8778. auto capturedValue = mModule->mBfIRBuilder->CreateInBoundsGEP(localVar->mValue, 0, fieldInstance.mDataIdx);
  8779. capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  8780. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance.mDataIdx);
  8781. mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  8782. fieldIdx++;
  8783. }
  8784. }
  8785. }
  8786. // for (auto& capturedEntry : capturedEntries)
  8787. // {
  8788. // BfIRValue capturedValue;
  8789. // if (capturedEntry.mLocalVarDef != NULL)
  8790. // {
  8791. // BfTypedValue localResult = LoadLocal(capturedEntry.mLocalVarDef, true);
  8792. //
  8793. // if (!capturedEntry.mType->IsRef())
  8794. // {
  8795. // if (localResult.IsSplat())
  8796. // {
  8797. // auto aggResult = mModule->AggregateSplat(localResult);
  8798. // capturedValue = aggResult.mValue;
  8799. // }
  8800. // else
  8801. // {
  8802. // localResult = mModule->LoadValue(localResult);
  8803. // capturedValue = localResult.mValue;
  8804. // if ((capturedEntry.mLocalVarDef->mResolvedType->IsRef()) && (!capturedEntry.mType->IsRef()))
  8805. // capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  8806. // }
  8807. // }
  8808. // else
  8809. // {
  8810. // if (capturedEntry.mLocalVarDef->mResolvedType->IsRef())
  8811. // localResult = mModule->LoadValue(localResult);
  8812. // capturedValue = localResult.mValue;
  8813. // }
  8814. // }
  8815. // else
  8816. // {
  8817. // // Read captured field from outer lambda ('this')
  8818. // auto localVar = mModule->mCurMethodState->mLocals[0];
  8819. // capturedValue = mModule->mBfIRBuilder->CreateInBoundsGEP(localVar->mValue, 0, capturedEntry.mCopyField->mDataIdx);
  8820. // if ((capturedEntry.mCopyField->mResolvedType->IsRef()) || (!capturedEntry.mType->IsRef()))
  8821. // {
  8822. // capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  8823. // if ((capturedEntry.mCopyField->mResolvedType->IsRef()) && (!capturedEntry.mType->IsRef()))
  8824. // capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  8825. // }
  8826. // }
  8827. // if (capturedValue)
  8828. // {
  8829. // auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, closureTypeInst->mFieldInstances[fieldIdx].mDataIdx);
  8830. // mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  8831. // }
  8832. // fieldIdx++;
  8833. // }
  8834. int captureIdx = 0;
  8835. //for (auto& capturedEntry : lambdaInstance->mCaptures)
  8836. for (int captureIdx = 0; captureIdx < (int)lambdaInstance->mCaptures.size(); captureIdx++)
  8837. {
  8838. auto& capturedEntry = lambdaInstance->mCaptures[captureIdx];
  8839. BfIdentifierNode* identifierNode = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[captureIdx].mNameNode;
  8840. //if (captureIdx < lambdaInstance->mMethodInstance->mClosureInstanceInfo->mCaptureNodes.size)
  8841. BfIRValue capturedValue;
  8842. // if (capturedEntry.mLocalVarDef != NULL)
  8843. // {
  8844. // BfTypedValue localResult = LoadLocal(capturedEntry.mLocalVarDef, true);
  8845. //
  8846. // if (!capturedEntry.mType->IsRef())
  8847. // {
  8848. // if (localResult.IsSplat())
  8849. // {
  8850. // auto aggResult = mModule->AggregateSplat(localResult);
  8851. // capturedValue = aggResult.mValue;
  8852. // }
  8853. // else
  8854. // {
  8855. // localResult = mModule->LoadValue(localResult);
  8856. // capturedValue = localResult.mValue;
  8857. // if ((capturedEntry.mLocalVarDef->mResolvedType->IsRef()) && (!capturedEntry.mType->IsRef()))
  8858. // capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  8859. // }
  8860. // }
  8861. // else
  8862. // {
  8863. // if (capturedEntry.mLocalVarDef->mResolvedType->IsRef())
  8864. // localResult = mModule->LoadValue(localResult);
  8865. // capturedValue = localResult.mValue;
  8866. // }
  8867. // }
  8868. // else
  8869. // {
  8870. // // Read captured field from outer lambda ('this')
  8871. // auto localVar = mModule->mCurMethodState->mLocals[0];
  8872. // capturedValue = mModule->mBfIRBuilder->CreateInBoundsGEP(localVar->mValue, 0, capturedEntry.mCopyField->mDataIdx);
  8873. // if ((capturedEntry.mCopyField->mResolvedType->IsRef()) || (!capturedEntry.mType->IsRef()))
  8874. // {
  8875. // capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  8876. // if ((capturedEntry.mCopyField->mResolvedType->IsRef()) && (!capturedEntry.mType->IsRef()))
  8877. // capturedValue = mModule->mBfIRBuilder->CreateLoad(capturedValue);
  8878. // }
  8879. // }
  8880. auto fieldInstance = &closureTypeInst->mFieldInstances[fieldIdx];
  8881. BfTypedValue capturedTypedVal;
  8882. if (identifierNode != NULL)
  8883. capturedTypedVal = DoImplicitArgCapture(NULL, identifierNode);
  8884. else
  8885. capturedTypedVal = LookupIdentifier(NULL, capturedEntry.mName);
  8886. if (!fieldInstance->mResolvedType->IsRef())
  8887. capturedTypedVal = mModule->LoadOrAggregateValue(capturedTypedVal);
  8888. else if (!capturedTypedVal.IsAddr())
  8889. {
  8890. mModule->Fail(StrFormat("Unable to capture '%s' by reference", capturedEntry.mName.c_str()), lambdaBindExpr);
  8891. break;
  8892. }
  8893. capturedValue = capturedTypedVal.mValue;
  8894. if (capturedValue)
  8895. {
  8896. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance->mDataIdx);
  8897. mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  8898. }
  8899. else
  8900. {
  8901. mModule->Fail(StrFormat("Unable to capture '%s'", capturedEntry.mName.c_str()), lambdaBindExpr);
  8902. mModule->AssertErrorState();
  8903. }
  8904. fieldIdx++;
  8905. }
  8906. if (lambdaInstance->mDtorFunc)
  8907. {
  8908. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, closureTypeInst->mFieldInstances[fieldIdx].mDataIdx);
  8909. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  8910. auto voidPtrType = mModule->CreatePointerType(voidType);
  8911. auto dtorThunk = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mDtorFunc, mModule->mBfIRBuilder->MapType(voidPtrType));
  8912. mModule->mBfIRBuilder->CreateStore(dtorThunk, fieldPtr);
  8913. fieldIdx++;
  8914. }
  8915. }
  8916. }
  8917. void BfExprEvaluator::ProcessArrayInitializer(BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, int dimensions, SizedArrayImpl<int64>& dimLengths, int dim, bool& hasFailed)
  8918. {
  8919. bool setSize = false;
  8920. if (dim == dimLengths.size())
  8921. {
  8922. dimLengths.push_back((int)valueExprs.size());
  8923. setSize = true;
  8924. }
  8925. else if (dimLengths[dim] == -1)
  8926. {
  8927. dimLengths[dim] = (int)valueExprs.size();
  8928. setSize = true;
  8929. }
  8930. int64 initCountDiff = (int)valueExprs.size() - dimLengths[dim];
  8931. if ((dimLengths[dim] != -1) && (initCountDiff != 0) && (!hasFailed))
  8932. {
  8933. if (initCountDiff > 0)
  8934. {
  8935. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[(int)dimLengths[dim]]);
  8936. hasFailed = true;
  8937. }
  8938. else
  8939. {
  8940. // If it ends with ", ?) or ",)" then allow unsized
  8941. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  8942. (commas.size() < valueExprs.size()))
  8943. {
  8944. BfAstNode* refNode = closeToken;
  8945. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  8946. refNode = mModule->mParentNodeEntry->mNode;
  8947. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  8948. hasFailed = true;
  8949. }
  8950. }
  8951. }
  8952. for (int i = 0; i < (int)valueExprs.size(); i++)
  8953. {
  8954. BfExpression* expr = valueExprs[i];
  8955. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(expr))
  8956. {
  8957. continue;
  8958. }
  8959. auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr);
  8960. if (dim < dimensions - 1)
  8961. {
  8962. if (innerInitExpr == NULL)
  8963. {
  8964. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(expr))
  8965. {
  8966. ProcessArrayInitializer(innerTupleExpr->mOpenParen, innerTupleExpr->mValues, innerTupleExpr->mCommas, innerTupleExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  8967. }
  8968. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  8969. {
  8970. SizedArray<BfExpression*, 1> values;
  8971. values.Add(parenExpr->mExpression);
  8972. SizedArray<BfTokenNode*, 1> commas;
  8973. ProcessArrayInitializer(parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  8974. }
  8975. else
  8976. {
  8977. hasFailed = true;
  8978. mModule->Fail("A nested array initializer is expected", expr);
  8979. continue;
  8980. }
  8981. }
  8982. else
  8983. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  8984. }
  8985. else if (innerInitExpr != NULL)
  8986. {
  8987. hasFailed = true;
  8988. mModule->Fail("Unexpected nested initializer", expr);
  8989. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  8990. }
  8991. else
  8992. {
  8993. //mModule->Fail("Expected initializer", )
  8994. }
  8995. }
  8996. }
  8997. void BfExprEvaluator::CheckObjectCreateTypeRef(BfType* expectingType, BfAstNode* afterNode)
  8998. {
  8999. auto autoComplete = GetAutoComplete();
  9000. if ((autoComplete != NULL) && (afterNode != NULL) && (autoComplete->mIsAutoComplete) &&
  9001. (afterNode->IsFromParser(mModule->mCompiler->mResolvePassData->mParser)) &&
  9002. (afterNode->GetParser()->mCursorIdx == afterNode->GetSrcEnd() + 1))
  9003. {
  9004. BfType* expectingType = mExpectingType;
  9005. BfTypeInstance* expectingTypeInst = NULL;
  9006. if (mExpectingType != NULL)
  9007. {
  9008. expectingTypeInst = mExpectingType->ToTypeInstance();
  9009. }
  9010. if ((mExpectingType != NULL) && (((expectingTypeInst == NULL) || (!expectingTypeInst->mTypeDef->mIsDelegate))))
  9011. {
  9012. // Why were we doing this? It floods the autocomplete with every possible type
  9013. //autoComplete->AddTopLevelTypes(NULL);
  9014. autoComplete->mInsertStartIdx = afterNode->GetSourceData()->ToParser()->mCursorIdx;
  9015. BF_ASSERT(autoComplete->mInsertStartIdx != -1);
  9016. auto expectingType = mExpectingType;
  9017. while (expectingType->IsArray())
  9018. {
  9019. auto arrayType = (BfArrayType*)expectingType;
  9020. expectingType = arrayType->mTypeGenericArguments[0];
  9021. }
  9022. auto expectingTypeInst = expectingType->ToTypeInstance();
  9023. if (expectingTypeInst != NULL)
  9024. {
  9025. autoComplete->AddTypeInstanceEntry(expectingTypeInst);
  9026. }
  9027. else
  9028. autoComplete->mDefaultSelection = mModule->TypeToString(expectingType);
  9029. }
  9030. }
  9031. }
  9032. void BfExprEvaluator::Visit(BfObjectCreateExpression* objCreateExpr)
  9033. {
  9034. auto autoComplete = GetAutoComplete();
  9035. if ((autoComplete != NULL) && (objCreateExpr->mTypeRef != NULL))
  9036. {
  9037. autoComplete->CheckTypeRef(objCreateExpr->mTypeRef, false, true);
  9038. }
  9039. //if (objCreateExpr->mArraySizeSpecifier == NULL)
  9040. CheckObjectCreateTypeRef(mExpectingType, objCreateExpr->mNewNode);
  9041. BfTokenNode* newToken = NULL;
  9042. BfAllocTarget allocTarget = ResolveAllocTarget(objCreateExpr->mNewNode, newToken);
  9043. bool isScopeAlloc = newToken->GetToken() == BfToken_Scope;
  9044. bool isAppendAlloc = newToken->GetToken() == BfToken_Append;
  9045. bool isStackAlloc = (newToken->GetToken() == BfToken_Stack) || (isScopeAlloc);
  9046. bool isArrayAlloc = false;// (objCreateExpr->mArraySizeSpecifier != NULL);
  9047. bool isRawArrayAlloc = (objCreateExpr->mStarToken != NULL);
  9048. if (isScopeAlloc)
  9049. {
  9050. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  9051. {
  9052. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", objCreateExpr->mNewNode);
  9053. }
  9054. if (objCreateExpr->mNewNode == newToken) // Scope, no target specified
  9055. {
  9056. if (mModule->mParentNodeEntry != NULL)
  9057. {
  9058. if (auto assignExpr = BfNodeDynCastExact<BfAssignmentExpression>(mModule->mParentNodeEntry->mNode))
  9059. {
  9060. if (mModule->mCurMethodState->mCurScope->mCloseNode == NULL)
  9061. {
  9062. // 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
  9063. if ((mBfEvalExprFlags & BfEvalExprFlags_PendingPropSet) == 0)
  9064. mModule->Warn(0, "This allocation will immediately go out of scope. Consider specifying a wider scope target such as 'scope::'", objCreateExpr->mNewNode);
  9065. }
  9066. }
  9067. }
  9068. }
  9069. }
  9070. BfAutoParentNodeEntry autoParentNodeEntry(mModule, objCreateExpr);
  9071. SizedArray<BfAstNode*, 2> dimLengthRefs;
  9072. SizedArray<BfIRValue, 2> dimLengthVals;
  9073. BfArrayType* arrayType = NULL;
  9074. BfType* unresolvedTypeRef = NULL;
  9075. BfType* resolvedTypeRef = NULL;
  9076. if (objCreateExpr->mTypeRef == NULL)
  9077. {
  9078. if ((!mExpectingType) || (!mExpectingType->IsArray()))
  9079. {
  9080. mModule->Fail("Cannot imply array type. Explicitly state array type or use array in an assignment to an array type.", objCreateExpr);
  9081. resolvedTypeRef = mModule->mContext->mBfObjectType;
  9082. unresolvedTypeRef = resolvedTypeRef;
  9083. }
  9084. else
  9085. {
  9086. auto arrayType = (BfArrayType*)mExpectingType;
  9087. unresolvedTypeRef = arrayType->GetUnderlyingType();
  9088. resolvedTypeRef = unresolvedTypeRef;
  9089. }
  9090. }
  9091. else
  9092. {
  9093. if ((objCreateExpr->mTypeRef->IsExact<BfDotTypeReference>()) && (mExpectingType != NULL))
  9094. {
  9095. //mModule->SetElementType(objCreateExpr->mTypeRef, BfSourceElementType_TypeRef);
  9096. if (mExpectingType->IsObject())
  9097. {
  9098. unresolvedTypeRef = mExpectingType;
  9099. if (unresolvedTypeRef->IsArray())
  9100. {
  9101. arrayType = (BfArrayType*)unresolvedTypeRef;
  9102. unresolvedTypeRef = unresolvedTypeRef->GetUnderlyingType();
  9103. isArrayAlloc = true;
  9104. }
  9105. }
  9106. else if (mExpectingType->IsPointer())
  9107. {
  9108. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  9109. }
  9110. }
  9111. if (unresolvedTypeRef == NULL)
  9112. {
  9113. if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  9114. {
  9115. isArrayAlloc = true;
  9116. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  9117. {
  9118. if ((mExpectingType != NULL) &&
  9119. ((mExpectingType->IsArray()) || (mExpectingType->IsSizedArray())))
  9120. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  9121. }
  9122. if (unresolvedTypeRef == NULL)
  9123. unresolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  9124. if (unresolvedTypeRef == NULL)
  9125. unresolvedTypeRef = mModule->mContext->mBfObjectType;
  9126. int dimensions = 1;
  9127. if (arrayTypeRef->mParams.size() != 0)
  9128. {
  9129. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  9130. for (auto arg : arrayTypeRef->mParams)
  9131. {
  9132. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  9133. {
  9134. if (tokenNode->GetToken() == BfToken_Comma)
  9135. {
  9136. if (isRawArrayAlloc)
  9137. {
  9138. mModule->Fail("Sized arrays cannot be multidimensional.", tokenNode);
  9139. continue;
  9140. }
  9141. dimensions++;
  9142. if (dimensions == 5)
  9143. {
  9144. mModule->Fail("Too many array dimensions, consider using a jagged array.", tokenNode);
  9145. }
  9146. continue;
  9147. }
  9148. }
  9149. auto expr = BfNodeDynCast<BfExpression>(arg);
  9150. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  9151. {
  9152. mModule->CreateValueFromExpression(expr, intType);
  9153. continue;
  9154. }
  9155. dimLengthRefs.Add(expr);
  9156. BfTypedValue dimLength;
  9157. if (expr == NULL)
  9158. {
  9159. // Not specified
  9160. dimLengthVals.push_back(BfIRValue());
  9161. continue;
  9162. }
  9163. if (arg != NULL)
  9164. {
  9165. dimLength = mModule->CreateValueFromExpression(expr, intType, BfEvalExprFlags_NoCast);
  9166. BfCastFlags castFlags = BfCastFlags_None;
  9167. if ((dimLength) && (dimLength.mType->IsInteger()))
  9168. {
  9169. // Allow uint for size - just force to int
  9170. if (!((BfPrimitiveType*)dimLength.mType)->IsSigned())
  9171. castFlags = BfCastFlags_Explicit;
  9172. }
  9173. if (dimLength)
  9174. dimLength = mModule->Cast(expr, dimLength, intType, castFlags);
  9175. }
  9176. if (!dimLength)
  9177. {
  9178. dimLength = mModule->GetDefaultTypedValue(intType);
  9179. }
  9180. dimLengthVals.push_back(dimLength.mValue);
  9181. }
  9182. }
  9183. if ((arrayTypeRef->mParams.size() == 0) && (objCreateExpr->mOpenToken == NULL))
  9184. mModule->Fail("Array size or array initializer expected", arrayTypeRef->mOpenBracket);
  9185. if (dimensions > 4)
  9186. dimensions = 4;
  9187. if (!isRawArrayAlloc)
  9188. arrayType = mModule->CreateArrayType(unresolvedTypeRef, dimensions);
  9189. }
  9190. if (unresolvedTypeRef == NULL)
  9191. {
  9192. unresolvedTypeRef = ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  9193. }
  9194. }
  9195. resolvedTypeRef = unresolvedTypeRef;
  9196. if ((resolvedTypeRef != NULL) && (resolvedTypeRef->IsVar()))
  9197. resolvedTypeRef = unresolvedTypeRef;
  9198. }
  9199. if (resolvedTypeRef == NULL)
  9200. return;
  9201. auto resultType = resolvedTypeRef;
  9202. if ((resolvedTypeRef->IsInterface()) && (!isArrayAlloc))
  9203. {
  9204. mModule->Fail("Cannot create an instance of an interface", objCreateExpr->mTypeRef);
  9205. resolvedTypeRef = mModule->mContext->mBfObjectType;
  9206. }
  9207. BfTypeInstance* typeInstance = resolvedTypeRef->ToTypeInstance();
  9208. int elementSize = resolvedTypeRef->mSize;
  9209. int elementAlign = resolvedTypeRef->mAlign;
  9210. BfIRType allocType = mModule->mBfIRBuilder->MapType(resolvedTypeRef);
  9211. if (typeInstance != NULL)
  9212. {
  9213. if (!mModule->mCurTypeInstance->mResolvingVarField)
  9214. mModule->PopulateType(typeInstance);
  9215. if ((typeInstance->mTypeDef->mIsDelegate) && (!isArrayAlloc))
  9216. mModule->Fail("Delegates must be constructed through delegate binding", objCreateExpr->mTypeRef);
  9217. elementSize = BF_MAX(0, typeInstance->mInstSize);
  9218. elementAlign = typeInstance->mInstAlign;
  9219. allocType = mModule->mBfIRBuilder->MapTypeInst(typeInstance);
  9220. }
  9221. if (isAppendAlloc)
  9222. {
  9223. if (!mModule->mCurTypeInstance->IsObject())
  9224. {
  9225. mModule->Fail("Append allocations are only allowed in classes", objCreateExpr->mNewNode);
  9226. isAppendAlloc = false;
  9227. }
  9228. else if ((mBfEvalExprFlags & BfEvalExprFlags_VariableDeclaration) == 0)
  9229. {
  9230. mModule->Fail("Append allocations are only allowed as local variable initializers in constructor body", objCreateExpr->mNewNode);
  9231. isAppendAlloc = false;
  9232. }
  9233. else
  9234. {
  9235. auto methodDef = mModule->mCurMethodInstance->mMethodDef;
  9236. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  9237. {
  9238. mModule->Fail("Append allocations are only allowed as local variable declarations in the main method body", objCreateExpr->mNewNode);
  9239. isAppendAlloc = false;
  9240. }
  9241. else if (!methodDef->mHasAppend)
  9242. {
  9243. mModule->Fail("Append allocations can only be used on constructors with [AllowAppend] specified", objCreateExpr->mNewNode);
  9244. isAppendAlloc = false;
  9245. }
  9246. else if (methodDef->mMethodType != BfMethodType_Ctor)
  9247. {
  9248. mModule->Fail("Append allocations are only allowed in constructors", objCreateExpr->mNewNode);
  9249. isAppendAlloc = false;
  9250. }
  9251. else if (methodDef->mIsStatic)
  9252. {
  9253. mModule->Fail("Append allocations are only allowed in non-static constructors", objCreateExpr->mNewNode);
  9254. isAppendAlloc = false;
  9255. }
  9256. }
  9257. }
  9258. if (isArrayAlloc)
  9259. {
  9260. const int MAX_DIMENSIONS = 2;
  9261. int dimensions = 1;
  9262. if (arrayType != NULL)
  9263. {
  9264. dimensions = arrayType->mDimensions;
  9265. mModule->AddDependency(arrayType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  9266. }
  9267. bool zeroMemory = true;
  9268. if (objCreateExpr->mOpenToken != NULL)
  9269. {
  9270. if ((objCreateExpr->mArguments.size() == 1) &&
  9271. (BfNodeDynCastExact<BfUninitializedExpression>(objCreateExpr->mArguments[0]) != NULL))
  9272. {
  9273. // Special case for a single "{ ? }"
  9274. zeroMemory = false;
  9275. }
  9276. else
  9277. {
  9278. SizedArray<int64, 2> dimLengths;
  9279. if (dimLengthVals.size() != 0)
  9280. {
  9281. for (int dim = 0; dim < dimensions; dim++)
  9282. {
  9283. BfIRValue dimLengthVal;
  9284. if (dim < (int)dimLengthVals.size())
  9285. dimLengthVal = dimLengthVals[dim];
  9286. if (!dimLengthVal)
  9287. {
  9288. dimLengths.push_back(-1);
  9289. continue;
  9290. }
  9291. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVal);
  9292. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  9293. {
  9294. int64 dimLength = constant->mInt64;
  9295. dimLengths.push_back(dimLength);
  9296. }
  9297. else
  9298. {
  9299. mModule->Fail("A constant length is required when using an initializer", dimLengthRefs[dim]);
  9300. dimLengths.push_back(-1);
  9301. }
  9302. }
  9303. }
  9304. // Ending in an ", )" means we need to zero-fill ending
  9305. zeroMemory = objCreateExpr->mCommas.size() >= objCreateExpr->mArguments.size();
  9306. bool hasFailed = false;
  9307. ProcessArrayInitializer(objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, dimensions, dimLengths, 0, hasFailed);
  9308. dimLengthVals.resize(dimLengths.size());
  9309. for (int i = 0; i < (int)dimLengthVals.size(); i++)
  9310. {
  9311. if (!dimLengthVals[i])
  9312. {
  9313. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  9314. dimLengthVals[i] = mModule->GetConstValue(dimLengths[i], intType);
  9315. }
  9316. }
  9317. }
  9318. }
  9319. while ((int)dimLengthVals.size() < dimensions)
  9320. dimLengthVals.push_back(mModule->GetConstValue(0));
  9321. BfTypedValue arrayValue;
  9322. BfIRValue arraySize;
  9323. for (BfIRValue dimSize : dimLengthVals)
  9324. {
  9325. if (!arraySize)
  9326. arraySize = dimSize;
  9327. else
  9328. arraySize = mModule->mBfIRBuilder->CreateMul(arraySize, dimSize);
  9329. }
  9330. BfAllocFlags allocFlags = BfAllocFlags_None;
  9331. if (isRawArrayAlloc)
  9332. allocFlags = (BfAllocFlags)(allocFlags | BfAllocFlags_RawArray);
  9333. int writeIdx = 0;
  9334. std::function<void(BfIRValue addr, int curDim, const BfSizedArray<BfExpression*>& valueExprs)> _HandleInitExprs = [&](BfIRValue addr, int curDim, const BfSizedArray<BfExpression*>& valueExprs)
  9335. {
  9336. int exprIdx = 0;
  9337. int dimWriteIdx = 0;
  9338. bool isUninit = false;
  9339. int dimLength = -1;
  9340. if (dimLengthVals[curDim].IsConst())
  9341. {
  9342. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[curDim]);
  9343. dimLength = constant->mInt32;
  9344. }
  9345. while (exprIdx < (int)valueExprs.size())
  9346. {
  9347. auto initExpr = valueExprs[exprIdx];
  9348. exprIdx++;
  9349. if (!initExpr)
  9350. break;
  9351. if (auto unintExpr = BfNodeDynCastExact<BfUninitializedExpression>(initExpr))
  9352. {
  9353. isUninit = true;
  9354. break;
  9355. }
  9356. if (exprIdx > dimLength)
  9357. break;
  9358. if (curDim < dimensions - 1)
  9359. {
  9360. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(initExpr))
  9361. {
  9362. _HandleInitExprs(addr, curDim + 1, innerTupleExpr->mValues);
  9363. }
  9364. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(initExpr))
  9365. {
  9366. SizedArray<BfExpression*, 1> values;
  9367. values.Add(parenExpr->mExpression);
  9368. _HandleInitExprs(addr, curDim + 1, values);
  9369. }
  9370. else if (auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(initExpr))
  9371. {
  9372. _HandleInitExprs(addr, curDim + 1, innerInitExpr->mValues);
  9373. }
  9374. dimWriteIdx++;
  9375. continue;
  9376. }
  9377. auto elemAddr = mModule->CreateIndexedValue(resultType, addr, writeIdx);
  9378. writeIdx++;
  9379. dimWriteIdx++;
  9380. BfTypedValue elemPtrTypedVal = BfTypedValue(elemAddr, resultType, BfTypedValueKind_Addr);
  9381. BfExprEvaluator exprEvaluator(mModule);
  9382. exprEvaluator.mExpectingType = resultType;
  9383. exprEvaluator.mReceivingValue = &elemPtrTypedVal;
  9384. exprEvaluator.Evaluate(initExpr);
  9385. exprEvaluator.GetResult();
  9386. if (exprEvaluator.mReceivingValue == NULL)
  9387. {
  9388. // We wrote directly to the array in-place, we're done with this element
  9389. continue;
  9390. }
  9391. auto storeValue = exprEvaluator.mResult;
  9392. if (!storeValue)
  9393. continue;
  9394. storeValue = mModule->Cast(initExpr, storeValue, resultType);
  9395. if (!storeValue)
  9396. continue;
  9397. if (!resultType->IsValuelessType())
  9398. {
  9399. storeValue = mModule->LoadValue(storeValue);
  9400. mModule->mBfIRBuilder->CreateStore(storeValue.mValue, elemAddr);
  9401. }
  9402. }
  9403. int clearFromIdx = writeIdx;
  9404. int sectionElemCount = 1;
  9405. BfIRValue numElemsLeft = arraySize;
  9406. if (dimLength != -1)
  9407. {
  9408. int clearCount = dimLength - dimWriteIdx;
  9409. if (clearCount > 0)
  9410. {
  9411. for (int checkDim = curDim + 1; checkDim < (int)dimLengthVals.size(); checkDim++)
  9412. {
  9413. if (dimLengthVals[checkDim].IsConst())
  9414. {
  9415. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[checkDim]);
  9416. clearCount *= constant->mInt32;
  9417. sectionElemCount *= constant->mInt32;
  9418. }
  9419. }
  9420. }
  9421. writeIdx += clearCount;
  9422. numElemsLeft = mModule->GetConstValue(clearCount);
  9423. }
  9424. // Actually leave it alone?
  9425. if ((isUninit) && (mModule->IsOptimized()))
  9426. return;
  9427. bool doClear = true;
  9428. if (numElemsLeft.IsConst())
  9429. {
  9430. auto constant = mModule->mBfIRBuilder->GetConstant(numElemsLeft);
  9431. doClear = constant->mInt64 > 0;
  9432. }
  9433. if (doClear)
  9434. {
  9435. // We multiply by GetStride. This relies on the fact that we over-allocate on the array allocation -- the last
  9436. // element doesn't need to be padded out to the element alignment, but we do anyway. Otherwise this would be
  9437. // a more complicated computation
  9438. auto clearBytes = mModule->mBfIRBuilder->CreateMul(numElemsLeft, mModule->GetConstValue(resultType->GetStride()));
  9439. if (isUninit)
  9440. {
  9441. // Limit to a reasonable number of bytes to stomp with 0xCC
  9442. int maxStompBytes = BF_MIN(128, resultType->GetStride() * sectionElemCount);
  9443. if (clearBytes.IsConst())
  9444. {
  9445. auto constant = mModule->mBfIRBuilder->GetConstant(clearBytes);
  9446. if (constant->mInt64 > maxStompBytes)
  9447. clearBytes = mModule->GetConstValue(maxStompBytes);
  9448. }
  9449. else
  9450. {
  9451. auto insertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  9452. auto gtBlock = mModule->mBfIRBuilder->CreateBlock("unint.gt");
  9453. auto contBlock = mModule->mBfIRBuilder->CreateBlock("unint.cont");
  9454. auto cmp = mModule->mBfIRBuilder->CreateCmpLTE(clearBytes, mModule->GetConstValue(maxStompBytes), true);
  9455. mModule->mBfIRBuilder->CreateCondBr(cmp, contBlock, gtBlock);
  9456. mModule->mBfIRBuilder->AddBlock(gtBlock);
  9457. mModule->mBfIRBuilder->SetInsertPoint(gtBlock);
  9458. mModule->mBfIRBuilder->CreateBr(contBlock);
  9459. mModule->mBfIRBuilder->AddBlock(contBlock);
  9460. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  9461. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_IntPtr)), 2);
  9462. mModule->mBfIRBuilder->AddPhiIncoming(phi, clearBytes, insertBlock);
  9463. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(maxStompBytes), gtBlock);
  9464. clearBytes = phi;
  9465. }
  9466. }
  9467. mModule->mBfIRBuilder->PopulateType(resultType);
  9468. mModule->mBfIRBuilder->CreateMemSet(mModule->CreateIndexedValue(resultType, addr, clearFromIdx),
  9469. mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, isUninit ? 0xCC : 0), clearBytes, resultType->mAlign);
  9470. }
  9471. };
  9472. if (isRawArrayAlloc)
  9473. {
  9474. // 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
  9475. BfType* ptrType = mModule->CreatePointerType(resultType);
  9476. if (isAppendAlloc)
  9477. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, false), ptrType);
  9478. else
  9479. {
  9480. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags), ptrType);
  9481. }
  9482. _HandleInitExprs(arrayValue.mValue, 0, objCreateExpr->mArguments);
  9483. mResult = arrayValue;
  9484. return;
  9485. }
  9486. if (dimLengthVals.size() > 4)
  9487. {
  9488. dimLengthVals.RemoveRange(4, dimLengthVals.size() - 4);
  9489. mModule->Fail("Too many array dimensions, consider using a jagged array.", objCreateExpr);
  9490. }
  9491. if (isAppendAlloc)
  9492. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, zeroMemory), arrayType);
  9493. else
  9494. {
  9495. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags), arrayType);
  9496. if (isScopeAlloc)
  9497. {
  9498. // See notes below on "general" SkipObjectAccessCheck usage on why we can do this
  9499. mModule->SkipObjectAccessCheck(arrayValue);
  9500. }
  9501. }
  9502. //mModule->InitTypeInst(arrayValue, scopeData);
  9503. BfAstNode* refNode = objCreateExpr->mTypeRef;
  9504. while (true)
  9505. {
  9506. if (auto arrayRef = BfNodeDynCast<BfElementedTypeRef>(refNode))
  9507. {
  9508. refNode = arrayRef->mElementType;
  9509. continue;
  9510. }
  9511. break;
  9512. }
  9513. BfResolvedArgs resolvedArgs;
  9514. if (autoComplete != NULL)
  9515. {
  9516. SetAndRestoreValue<bool> prevCapturing(autoComplete->mIsCapturingMethodMatchInfo, false);
  9517. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, false);
  9518. }
  9519. else
  9520. {
  9521. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, false);
  9522. }
  9523. //TODO: Assert 'length' var is at slot 1
  9524. mModule->PopulateType(arrayType->mBaseType, BfPopulateType_DataAndMethods);
  9525. mModule->mBfIRBuilder->PopulateType(arrayType);
  9526. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(arrayValue.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(arrayType->mBaseType));
  9527. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  9528. if (arrayLengthBitCount == 0)
  9529. {
  9530. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", objCreateExpr);
  9531. return;
  9532. }
  9533. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, 1/*, "length"*/);
  9534. if (arrayLengthBitCount == 64)
  9535. mModule->mBfIRBuilder->CreateAlignedStore(arraySize, addr, 8);
  9536. else
  9537. {
  9538. auto arraySize32 = mModule->mBfIRBuilder->CreateNumericCast(arraySize, true, BfTypeCode_Int32);
  9539. mModule->mBfIRBuilder->CreateAlignedStore(arraySize32, addr, 4);
  9540. }
  9541. for (int lowerDim = 1; lowerDim < (int)dimLengthVals.size(); lowerDim++)
  9542. {
  9543. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, lowerDim/*, "dimLength"*/); // mDimLengthX
  9544. auto lowerDimVal = mModule->mBfIRBuilder->CreateNumericCast(dimLengthVals[lowerDim], true, (arrayLengthBitCount == 64) ? BfTypeCode_Int64 : BfTypeCode_Int32);
  9545. mModule->mBfIRBuilder->CreateStore(lowerDimVal, addr);
  9546. }
  9547. if (resultType->IsValuelessType())
  9548. addr = mModule->mBfIRBuilder->GetFakeVal();
  9549. else
  9550. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, (int)dimLengthVals.size()/*, "elem"*/); // mFirstElement
  9551. _HandleInitExprs(addr, 0, objCreateExpr->mArguments);
  9552. mResult = arrayValue;
  9553. return;
  9554. }
  9555. else
  9556. {
  9557. if ((!resolvedTypeRef->IsObjectOrInterface()) && (!resolvedTypeRef->IsGenericParam()))
  9558. {
  9559. resultType = mModule->CreatePointerType(resolvedTypeRef);
  9560. }
  9561. }
  9562. if ((isStackAlloc) && (mModule->mCurMethodState == NULL))
  9563. {
  9564. mModule->Fail("Cannot use 'stack' here", objCreateExpr->mNewNode);
  9565. isStackAlloc = false;
  9566. isScopeAlloc = false;
  9567. }
  9568. bool isGenericParam = unresolvedTypeRef->IsGenericParam();
  9569. if (resolvedTypeRef->IsGenericParam())
  9570. {
  9571. auto genericConstraint = mModule->GetGenericParamInstance((BfGenericParamType*)resolvedTypeRef);
  9572. if (genericConstraint->mTypeConstraint == NULL)
  9573. {
  9574. if ((genericConstraint->mGenericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Struct)) == 0)
  9575. {
  9576. mModule->Fail(StrFormat("Must add 'where %s : new' constraint to generic parameter to instantiate type", genericConstraint->GetGenericParamDef()->mName.c_str()), objCreateExpr->mTypeRef);
  9577. }
  9578. if (objCreateExpr->mArguments.size() != 0)
  9579. {
  9580. mModule->Fail(StrFormat("Only default parameterless constructors can be called on generic argument '%s'", genericConstraint->GetGenericParamDef()->mName.c_str()), objCreateExpr->mTypeRef);
  9581. }
  9582. }
  9583. resultType = resolvedTypeRef;
  9584. bool isValueType = ((genericConstraint->mGenericParamFlags & BfGenericParamFlag_Struct) != 0);
  9585. if (genericConstraint->mTypeConstraint != NULL)
  9586. isValueType = genericConstraint->mTypeConstraint->IsValueType();
  9587. if (isValueType)
  9588. resultType = mModule->CreatePointerType(resultType);
  9589. mResult.mType = resultType;
  9590. if (typeInstance == NULL)
  9591. {
  9592. mResult = mModule->GetDefaultTypedValue(resultType);
  9593. return;
  9594. }
  9595. }
  9596. else if (resolvedTypeRef->IsSizedArray())
  9597. {
  9598. // Handle the case of "int[3]* val = new .(1, 2, 3)"
  9599. if (auto dotTypeRef = BfNodeDynCastExact<BfDotTypeReference>(objCreateExpr->mTypeRef))
  9600. {
  9601. BfIRValue allocValue;
  9602. if (isAppendAlloc)
  9603. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, BfIRValue(), 0, BfIRValue(), 0, false, false);
  9604. else
  9605. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None);
  9606. auto result = BfTypedValue(allocValue, resolvedTypeRef, BfTypedValueKind_Addr);
  9607. InitializedSizedArray((BfSizedArrayType*)resolvedTypeRef, objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, &result);
  9608. // Turn from an addr of a sized array to pointer of sized array
  9609. mResult = BfTypedValue(mResult.mValue, resultType);
  9610. return;
  9611. }
  9612. }
  9613. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isGenericParam);
  9614. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  9615. {
  9616. mModule->Fail("Cannot create an instance of an abstract class", objCreateExpr->mTypeRef);
  9617. return;
  9618. }
  9619. BfFunctionBindResult bindResult;
  9620. bindResult.mSkipThis = true;
  9621. bindResult.mWantsArgs = true;
  9622. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, &bindResult);
  9623. BfIRValue appendSizeValue;
  9624. //BfTypedValue emtpyThis(BfIRValue(), resolvedTypeRef, resolvedTypeRef->IsStruct());
  9625. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeRef, resolvedTypeRef->IsStruct());
  9626. BfResolvedArgs argValues(objCreateExpr->mOpenToken, &objCreateExpr->mArguments, &objCreateExpr->mCommas, objCreateExpr->mCloseToken);
  9627. ResolveArgValues(argValues, BfResolveArgFlag_DeferParamEval); ////
  9628. /*SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, mPrefixedAttributeState);
  9629. if (mPrefixedAttributeState != NULL)
  9630. mPrefixedAttributeState->mUsed = true;*/
  9631. if (typeInstance == NULL)
  9632. {
  9633. // No CTOR needed
  9634. if (objCreateExpr->mArguments.size() != 0)
  9635. {
  9636. mModule->Fail(StrFormat("Only default parameterless constructors can be called on primitive type '%s'", mModule->TypeToString(resolvedTypeRef).c_str()), objCreateExpr->mTypeRef);
  9637. }
  9638. }
  9639. else if ((autoComplete != NULL) && (objCreateExpr->mOpenToken != NULL))
  9640. {
  9641. auto wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  9642. autoComplete->CheckInvocation(objCreateExpr, objCreateExpr->mOpenToken, objCreateExpr->mCloseToken, objCreateExpr->mCommas);
  9643. MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInstance, argValues, false, true);
  9644. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  9645. {
  9646. autoComplete->mIsCapturingMethodMatchInfo = true;
  9647. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  9648. }
  9649. else
  9650. autoComplete->mIsCapturingMethodMatchInfo = false;
  9651. }
  9652. else
  9653. {
  9654. MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInstance, argValues, false, true);
  9655. }
  9656. mModule->ValidateAllocation(typeInstance, objCreateExpr->mTypeRef);
  9657. //prevAttributeState.Restore();
  9658. prevBindResult.Restore();
  9659. /*if ((typeInstance != NULL) && (bindResult.mMethodInstance == NULL))
  9660. {
  9661. mModule->AssertErrorState();
  9662. return;
  9663. }*/
  9664. int allocAlign = resolvedTypeRef->mAlign;
  9665. if (typeInstance != NULL)
  9666. allocAlign = typeInstance->mInstAlign;
  9667. int appendAllocAlign = 0;
  9668. if ((bindResult.mMethodInstance != NULL) && (bindResult.mMethodInstance->mMethodDef->mHasAppend))
  9669. {
  9670. if (!bindResult.mFunc)
  9671. {
  9672. BF_ASSERT((!mModule->HasCompiledOutput()) || (mModule->mBfIRBuilder->mIgnoreWrites));
  9673. appendSizeValue = mModule->GetConstValue(0);
  9674. }
  9675. else
  9676. {
  9677. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  9678. SizedArray<BfIRValue, 2> irArgs;
  9679. if (bindResult.mIRArgs.size() > 1)
  9680. irArgs.Insert(0, &bindResult.mIRArgs[1], bindResult.mIRArgs.size() - 1);
  9681. BfTypedValue appendSizeTypedValue = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, irArgs);
  9682. if (!appendSizeTypedValue)
  9683. {
  9684. BF_ASSERT(calcAppendMethodModule.mFunc);
  9685. appendSizeTypedValue = CreateCall(calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, irArgs);
  9686. BF_ASSERT(appendSizeTypedValue.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  9687. }
  9688. appendSizeValue = appendSizeTypedValue.mValue;
  9689. allocAlign = BF_MAX(allocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  9690. appendAllocAlign = calcAppendMethodModule.mMethodInstance->mAppendAllocAlign;
  9691. }
  9692. if (appendAllocAlign != 0)
  9693. {
  9694. int endingAlign = typeInstance->GetEndingInstanceAlignment();
  9695. if (endingAlign % appendAllocAlign != 0)
  9696. {
  9697. int extraSize = appendAllocAlign - (endingAlign % appendAllocAlign);
  9698. appendSizeValue = mModule->mBfIRBuilder->CreateAdd(appendSizeValue, mModule->GetConstValue(extraSize));
  9699. }
  9700. }
  9701. }
  9702. // WTF? I'm not even sure this is correct - add more tests
  9703. appendAllocAlign = BF_MAX(appendAllocAlign, allocAlign);
  9704. BfIRValue allocValue;
  9705. if (isAppendAlloc)
  9706. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, appendSizeValue, appendAllocAlign);
  9707. else
  9708. {
  9709. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, appendSizeValue, BfIRValue(), 0, BfAllocFlags_None, allocAlign);
  9710. }
  9711. mResult = BfTypedValue(allocValue, resultType);
  9712. if (isScopeAlloc)
  9713. {
  9714. // This allows readonly (ie: 'let') local usage to not require an access check. No matter what scope the alloc is tied to, the
  9715. // lifetime of the local variable will be no longer than that of the allocated value
  9716. mModule->SkipObjectAccessCheck(mResult);
  9717. }
  9718. /*if (typeInstance != NULL)
  9719. {
  9720. mModule->InitTypeInst(mResult, scopeData, true);
  9721. }
  9722. if (isStackAlloc)
  9723. {
  9724. mModule->AddStackAlloc(mResult, objCreateExpr, scopeData);
  9725. }*/
  9726. if (mResult)
  9727. {
  9728. if (bindResult.mMethodInstance == NULL)
  9729. {
  9730. // Why did we have this? It was already zeroed right?
  9731. // Zero
  9732. //mModule->mBfIRBuilder->CreateMemSet(mResult.mValue, mModule->GetConstValue8(0), mModule->GetConstValue(resolvedTypeRef->mSize), resolvedTypeRef->mAlign);
  9733. }
  9734. else if (bindResult.mFunc)
  9735. {
  9736. if (typeInstance->IsObject())
  9737. {
  9738. bool wantsCtorClear = true;
  9739. if (mModule->mCompiler->mOptions.mEnableRealtimeLeakCheck)
  9740. {
  9741. // Dbg_ObjectAlloc clears internally so we don't need to call CtorClear for those
  9742. if ((!isStackAlloc) && (!allocTarget.mCustomAllocator) && (allocTarget.mScopedInvocationTarget == NULL))
  9743. wantsCtorClear = false;
  9744. }
  9745. if (wantsCtorClear)
  9746. {
  9747. auto ctorClear = mModule->GetMethodByName(typeInstance, "__BfCtorClear");
  9748. if (!ctorClear)
  9749. {
  9750. mModule->AssertErrorState();
  9751. }
  9752. else
  9753. {
  9754. SizedArray<BfIRValue, 1> irArgs;
  9755. irArgs.push_back(mResult.mValue);
  9756. CreateCall(ctorClear.mMethodInstance, ctorClear.mFunc, false, irArgs);
  9757. }
  9758. }
  9759. if ((isStackAlloc) && (mModule->mCompiler->mOptions.mEnableRealtimeLeakCheck))
  9760. {
  9761. BfMethodInstance* markMethod = mModule->GetRawMethodByName(mModule->mContext->mBfObjectType, "GCMarkMembers");
  9762. BF_ASSERT(markMethod != NULL);
  9763. if (markMethod != NULL)
  9764. {
  9765. auto& vtableEntry = typeInstance->mVirtualMethodTable[markMethod->mVirtualTableIdx];
  9766. if (vtableEntry.mImplementingMethod.mTypeInstance != mModule->mContext->mBfObjectType)
  9767. {
  9768. auto impMethodInstance = (BfMethodInstance*)vtableEntry.mImplementingMethod;
  9769. bool needsCall = false;
  9770. if (impMethodInstance != NULL)
  9771. {
  9772. needsCall = impMethodInstance->mMethodDef->mBody != NULL;
  9773. }
  9774. else
  9775. {
  9776. needsCall = true;
  9777. BF_ASSERT(vtableEntry.mImplementingMethod.mKind == BfMethodRefKind_AmbiguousRef);
  9778. }
  9779. if (needsCall)
  9780. {
  9781. SizedArray<BfIRValue, 1> irArgs;
  9782. irArgs.push_back(mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(mModule->mContext->mBfObjectType)));
  9783. auto gcType = mModule->ResolveTypeDef(mModule->mCompiler->mGCTypeDef);
  9784. BF_ASSERT(gcType != NULL);
  9785. if (gcType != NULL)
  9786. {
  9787. auto addStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "AddStackMarkableObject", 1);
  9788. BF_ASSERT(addStackObjMethod);
  9789. if (addStackObjMethod)
  9790. {
  9791. mModule->mBfIRBuilder->CreateCall(addStackObjMethod.mFunc, irArgs);
  9792. }
  9793. auto removeStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "RemoveStackMarkableObject", 1);
  9794. BF_ASSERT(removeStackObjMethod);
  9795. if (removeStackObjMethod)
  9796. {
  9797. mModule->AddDeferredCall(removeStackObjMethod, irArgs, allocTarget.mScopeData, objCreateExpr);
  9798. }
  9799. }
  9800. }
  9801. }
  9802. }
  9803. }
  9804. }
  9805. if ((bindResult.mMethodInstance->mMethodDef->mHasAppend) && (mResult.mType->IsObject()))
  9806. {
  9807. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  9808. auto typeInst = mResult.mType->ToTypeInstance();
  9809. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  9810. auto thisVal = mResult;
  9811. BfIRValue intPtrVal = mModule->CreateAlloca(intPtrType);
  9812. auto intPtrThisVal = mModule->mBfIRBuilder->CreatePtrToInt(thisVal.mValue, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  9813. auto curValPtr = mModule->mBfIRBuilder->CreateAdd(intPtrThisVal, mModule->GetConstValue(typeInst->mInstSize, intPtrType));
  9814. mModule->mBfIRBuilder->CreateStore(curValPtr, intPtrVal);
  9815. bindResult.mIRArgs[0] = intPtrVal;
  9816. }
  9817. if (!typeInstance->IsValuelessType())
  9818. bindResult.mIRArgs.Insert(0, mResult.mValue);
  9819. CreateCall(bindResult.mMethodInstance, bindResult.mFunc, false, bindResult.mIRArgs);
  9820. }
  9821. }
  9822. // if ((mResult) && (!isArrayAlloc) && (objCreateExpr->mCollectionInitializer != NULL))
  9823. // {
  9824. // for (BfExpression* initExpr : objCreateExpr->mCollectionInitializer->mValues)
  9825. // {
  9826. // SizedArray<ASTREF(BfExpression*), 1> exprs;
  9827. //
  9828. // if (auto groupExpr = BfNodeDynCast<BfCollectionInitializerExpression>(initExpr))
  9829. // {
  9830. // for (BfExpression* argExpr : groupExpr->mValues)
  9831. // exprs.push_back(argExpr);
  9832. // }
  9833. // else
  9834. // {
  9835. // exprs.push_back(initExpr);
  9836. // }
  9837. //
  9838. // BfExprEvaluator exprEvaluator(mModule);
  9839. // SizedArray<BfExpression*, 8> copiedArgs;
  9840. // for (BfExpression* arg : exprs)
  9841. // copiedArgs.push_back(arg);
  9842. // BfResolvedArgs argValues(copiedArgs);
  9843. // exprEvaluator.ResolveArgValues(argValues);
  9844. // exprEvaluator.MatchMethod(initExpr, NULL, mResult, false, false, "Add", argValues, NULL);
  9845. // }
  9846. // }
  9847. }
  9848. void BfExprEvaluator::Visit(BfBoxExpression* boxExpr)
  9849. {
  9850. /*if ((boxExpr->mAllocNode == NULL) || (boxExpr->mExpression == NULL))
  9851. {
  9852. mModule->AssertErrorState();
  9853. return;
  9854. }*/
  9855. BfTokenNode* newToken = NULL;
  9856. BfAllocTarget allocTarget = ResolveAllocTarget(boxExpr->mAllocNode, newToken);
  9857. if ((boxExpr->mAllocNode != NULL) && (boxExpr->mAllocNode->mToken == BfToken_Scope))
  9858. {
  9859. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  9860. {
  9861. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", boxExpr->mAllocNode);
  9862. }
  9863. }
  9864. if (boxExpr->mExpression == NULL)
  9865. {
  9866. mModule->AssertErrorState();
  9867. return;
  9868. }
  9869. auto exprValue = mModule->CreateValueFromExpression(boxExpr->mExpression);
  9870. if (exprValue)
  9871. {
  9872. if (exprValue.mType->IsGenericParam())
  9873. {
  9874. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  9875. auto genericParamTarget = (BfGenericParamType*)exprValue.mType;
  9876. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  9877. bool isBoxable = false;
  9878. if (genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr))
  9879. isBoxable = true;
  9880. if ((genericParamInstance->mTypeConstraint != NULL) && (exprValue.mType->IsValueTypeOrValueTypePtr()))
  9881. isBoxable = true;
  9882. if (isBoxable)
  9883. {
  9884. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  9885. return;
  9886. }
  9887. }
  9888. if (!exprValue.mType->IsValueTypeOrValueTypePtr())
  9889. {
  9890. 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);
  9891. return;
  9892. }
  9893. //BfType* boxedType = mModule->CreateBoxedType(exprValue.mType);
  9894. //auto scopeData = mModule->FindScope(boxExpr->mAllocNode);
  9895. mResult = mModule->BoxValue(boxExpr->mExpression, exprValue, mModule->mContext->mBfObjectType, allocTarget);
  9896. if (!mResult)
  9897. {
  9898. mModule->Fail(StrFormat("Type '%s' is not boxable", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  9899. return;
  9900. }
  9901. }
  9902. }
  9903. BfAllocTarget BfExprEvaluator::ResolveAllocTarget(BfAstNode* allocNode, BfTokenNode*& newToken)
  9904. {
  9905. auto autoComplete = GetAutoComplete();
  9906. BfAllocTarget allocTarget;
  9907. allocTarget.mRefNode = allocNode;
  9908. newToken = BfNodeDynCast<BfTokenNode>(allocNode);
  9909. if (newToken == NULL)
  9910. {
  9911. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(allocNode))
  9912. {
  9913. newToken = scopeNode->mScopeToken;
  9914. allocTarget.mScopeData = mModule->FindScope(scopeNode->mTargetNode, true);
  9915. if (autoComplete != NULL)
  9916. {
  9917. auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(scopeNode->mTargetNode);
  9918. if ((scopeNode->mTargetNode == NULL) || (targetIdentifier != NULL))
  9919. autoComplete->CheckLabel(targetIdentifier, scopeNode->mColonToken);
  9920. }
  9921. }
  9922. if (auto newNode = BfNodeDynCast<BfNewNode>(allocNode))
  9923. {
  9924. newToken = newNode->mNewToken;
  9925. if (auto allocExpr = BfNodeDynCast<BfExpression>(newNode->mAllocNode))
  9926. {
  9927. allocTarget.mCustomAllocator = mModule->CreateValueFromExpression(allocExpr);
  9928. allocTarget.mRefNode = allocExpr;
  9929. }
  9930. else if (auto scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(newNode->mAllocNode))
  9931. {
  9932. allocTarget.mScopedInvocationTarget = scopedInvocationTarget;
  9933. }
  9934. }
  9935. }
  9936. else if (newToken->GetToken() == BfToken_Scope)
  9937. {
  9938. if (mModule->mCurMethodState != NULL)
  9939. allocTarget.mScopeData = mModule->mCurMethodState->mCurScope->GetTargetable();
  9940. }
  9941. else if (newToken->GetToken() == BfToken_Stack)
  9942. {
  9943. if (mModule->mCurMethodState != NULL)
  9944. allocTarget.mScopeData = &mModule->mCurMethodState->mHeadScope;
  9945. }
  9946. return allocTarget;
  9947. }
  9948. BfTypedValue BfExprEvaluator::MakeCallableTarget(BfAstNode* targetSrc, BfTypedValue target)
  9949. {
  9950. if (((target.mType->IsRef()) || (target.mType->IsPointer())) &&
  9951. (target.mType->GetUnderlyingType()->IsStruct()))
  9952. {
  9953. auto pointerType = (BfPointerType*) target.mType;
  9954. target = mModule->LoadValue(target);
  9955. target.mType = pointerType->mElementType;
  9956. target.mKind = BfTypedValueKind_Addr;
  9957. }
  9958. if ((target.mType->IsStruct()) && (!target.IsAddr()))
  9959. {
  9960. target = mModule->MakeAddressable(target);
  9961. }
  9962. if (target.mType->IsVar())
  9963. {
  9964. target.mType = mModule->mContext->mBfObjectType;
  9965. return target;
  9966. }
  9967. if (target.mType->IsWrappableType())
  9968. {
  9969. auto primStructType = mModule->GetWrappedStructType(target.mType);
  9970. if (primStructType != NULL)
  9971. {
  9972. mModule->PopulateType(primStructType);
  9973. target.mType = primStructType;
  9974. if ((primStructType->IsSplattable()) && (!primStructType->IsTypedPrimitive()))
  9975. {
  9976. if (target.IsAddr())
  9977. {
  9978. auto ptrType = mModule->CreatePointerType(primStructType);
  9979. target = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapType(ptrType)), primStructType, true);
  9980. }
  9981. else
  9982. target.mKind = BfTypedValueKind_SplatHead;
  9983. }
  9984. }
  9985. return target;
  9986. }
  9987. if (target.mType->IsGenericParam())
  9988. {
  9989. target.mType = mModule->mContext->mBfObjectType;
  9990. return target;
  9991. }
  9992. if ((!target.mType->IsTypeInstance()) && (!target.mType->IsConcreteInterfaceType()))
  9993. {
  9994. mModule->Fail(StrFormat("Invalid target type: '%s'", mModule->TypeToString(target.mType).c_str()), targetSrc);
  9995. return BfTypedValue();
  9996. }
  9997. return target;
  9998. }
  9999. int BfExprEvaluator::GetMixinVariable()
  10000. {
  10001. auto curMethodState = mModule->mCurMethodState;
  10002. for (int localIdx = (int)curMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  10003. {
  10004. auto varDecl = curMethodState->mLocals[localIdx];
  10005. if (varDecl->mName == "mixin")
  10006. return localIdx;
  10007. }
  10008. return -1;
  10009. }
  10010. BfModuleMethodInstance BfExprEvaluator::GetSelectedMethod(BfAstNode* targetSrc, BfTypeInstance* curTypeInst, BfMethodDef* methodDef, BfMethodMatcher& methodMatcher)
  10011. {
  10012. bool failed = false;
  10013. auto resolvedCurTypeInst = curTypeInst;//mModule->ResolveGenericType(curTypeInst)->ToTypeInstance();
  10014. bool hasDifferentResolvedTypes = resolvedCurTypeInst != curTypeInst;
  10015. BfTypeVector resolvedGenericArguments;
  10016. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  10017. int localInferrableGenericArgCount = -1;
  10018. if ((methodMatcher.mBestMethodGenericArguments.size() == 0) && (!methodMatcher.mExplicitMethodGenericArguments.IsEmpty()))
  10019. {
  10020. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(methodDef);
  10021. int64 genericArgCountDiff = (int)methodMatcher.mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx - (int)methodDef->mGenericParams.size();
  10022. BfInvocationExpression* invocationExpr = NULL;
  10023. if (mModule->mParentNodeEntry != NULL)
  10024. {
  10025. invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode);
  10026. }
  10027. if (genericArgCountDiff > 0)
  10028. {
  10029. BfAstNode* errorNode = targetSrc;
  10030. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL))
  10031. {
  10032. errorNode = invocationExpr->mGenericArgs->mGenericArgs[(int)methodDef->mGenericParams.size()];
  10033. if (errorNode == NULL)
  10034. errorNode = invocationExpr->mGenericArgs->mCommas[(int)methodDef->mGenericParams.size() - 1];
  10035. }
  10036. mModule->Fail(StrFormat("Too many generic arguments, expected %d fewer", genericArgCountDiff), errorNode);
  10037. }
  10038. else if (genericArgCountDiff < 0)
  10039. {
  10040. BfAstNode* errorNode = targetSrc;
  10041. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL) && (invocationExpr->mGenericArgs->mCloseChevron != NULL))
  10042. errorNode = invocationExpr->mGenericArgs->mCloseChevron;
  10043. mModule->Fail(StrFormat("Too few generic arguments, expected %d more", -genericArgCountDiff), errorNode);
  10044. }
  10045. methodMatcher.mBestMethodGenericArguments.resize(methodDef->mGenericParams.size());
  10046. for (int i = 0; i < std::min(methodDef->mGenericParams.size() - uniqueGenericStartIdx, methodMatcher.mExplicitMethodGenericArguments.size()); i++)
  10047. {
  10048. methodMatcher.mBestMethodGenericArguments[i + uniqueGenericStartIdx] = methodMatcher.mExplicitMethodGenericArguments[i];
  10049. }
  10050. }
  10051. BfMethodInstance* unspecializedMethod = NULL;
  10052. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  10053. {
  10054. BfMethodInstance* outerMethodInstance = NULL;
  10055. auto& genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  10056. if (genericArg == NULL)
  10057. {
  10058. if ((methodDef->mIsLocalMethod) && (checkGenericIdx < mModule->mCurMethodInstance->GetNumGenericArguments()))
  10059. {
  10060. // If the root method is generic and we need that param then use that...
  10061. auto rootMethodInstance = rootMethodState->mMethodInstance;
  10062. if (checkGenericIdx < rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size())
  10063. {
  10064. genericArg = rootMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  10065. }
  10066. else
  10067. {
  10068. if (localInferrableGenericArgCount == -1)
  10069. localInferrableGenericArgCount = mModule->GetLocalInferrableGenericArgCount(methodDef);
  10070. // Otherwise we can only infer generics at the level that the called method was contained
  10071. if (checkGenericIdx < localInferrableGenericArgCount)
  10072. genericArg = mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  10073. }
  10074. }
  10075. }
  10076. if (genericArg == NULL)
  10077. {
  10078. if (unspecializedMethod == NULL)
  10079. unspecializedMethod = mModule->GetRawMethodInstance(curTypeInst, methodDef);
  10080. auto genericParam = unspecializedMethod->mMethodInfoEx->mGenericParams[checkGenericIdx];
  10081. if ((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsDelegate()))
  10082. {
  10083. // The only other option was to bind to a MethodRef
  10084. genericArg = genericParam->mTypeConstraint;
  10085. }
  10086. else
  10087. {
  10088. if (((genericParam->mGenericParamFlags & BfGenericParamFlag_Const) != 0) && (genericParam->mTypeConstraint != NULL))
  10089. {
  10090. for (int paramIdx = 0; paramIdx < (int)unspecializedMethod->mDefaultValues.size(); paramIdx++)
  10091. {
  10092. auto defaultVal = unspecializedMethod->mDefaultValues[paramIdx];
  10093. if (!defaultVal)
  10094. continue;
  10095. auto& param = unspecializedMethod->mParams[paramIdx];
  10096. if (param.mResolvedType->IsGenericParam())
  10097. {
  10098. auto genericParamType = (BfGenericParamType*)param.mResolvedType;
  10099. if ((genericParamType->mGenericParamKind == BfGenericParamKind_Method) && (genericParamType->mGenericParamIdx == checkGenericIdx))
  10100. {
  10101. BfTypedValue constExprVal;
  10102. constExprVal.mType = genericParam->mTypeConstraint;
  10103. auto constant = curTypeInst->mConstHolder->GetConstant(defaultVal);
  10104. constExprVal.mValue = mModule->ConstantToCurrent(constant, curTypeInst->mConstHolder, genericParam->mTypeConstraint);
  10105. genericArg = mModule->CreateConstExprValueType(constExprVal);
  10106. }
  10107. }
  10108. }
  10109. }
  10110. if (genericArg == NULL)
  10111. {
  10112. failed = true;
  10113. mModule->Fail(StrFormat("Unable to determine generic argument '%s'", methodDef->mGenericParams[checkGenericIdx]->mName.c_str()).c_str(), targetSrc);
  10114. if ((genericParam->mTypeConstraint != NULL) && (!genericParam->mTypeConstraint->IsUnspecializedType()))
  10115. genericArg = genericParam->mTypeConstraint;
  10116. else
  10117. genericArg = mModule->mContext->mBfObjectType;
  10118. }
  10119. }
  10120. resolvedGenericArguments.push_back(genericArg);
  10121. }
  10122. else
  10123. {
  10124. if (genericArg->IsIntUnknown())
  10125. genericArg = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  10126. auto resolvedGenericArg = genericArg;//mModule->ResolveGenericType(genericArg);
  10127. if (resolvedGenericArg != genericArg)
  10128. hasDifferentResolvedTypes = true;
  10129. resolvedGenericArguments.push_back(resolvedGenericArg);
  10130. }
  10131. }
  10132. BfTypeInstance* foreignType = NULL;
  10133. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  10134. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef)))
  10135. {
  10136. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForceInline);
  10137. }
  10138. if ((!mModule->mCurTypeInstance->IsInterface()) && (methodDef->mBody != NULL))
  10139. {
  10140. if ((methodMatcher.mBypassVirtual) && (methodMatcher.mBestMethodTypeInstance->IsInterface()))
  10141. {
  10142. // This is an explicit 'base' call to a default interface method. We pull the methodDef into our own concrete type.
  10143. foreignType = curTypeInst;
  10144. curTypeInst = mModule->mCurTypeInstance;
  10145. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  10146. }
  10147. else if ((methodDef->mIsStatic) && (curTypeInst->IsInterface()))
  10148. {
  10149. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  10150. {
  10151. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  10152. foreignType = curTypeInst;
  10153. curTypeInst = mModule->mCurTypeInstance;
  10154. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  10155. }
  10156. }
  10157. }
  10158. BfModuleMethodInstance methodInstance;
  10159. if (methodMatcher.mBestMethodInstance)
  10160. {
  10161. methodInstance = methodMatcher.mBestMethodInstance;
  10162. }
  10163. else
  10164. {
  10165. methodInstance = mModule->GetMethodInstance(resolvedCurTypeInst, methodDef, resolvedGenericArguments, flags, foreignType);
  10166. }
  10167. if (mModule->mCompiler->IsSkippingExtraResolveChecks())
  10168. {
  10169. //BF_ASSERT(methodInstance.mFunc == NULL);
  10170. }
  10171. if (methodInstance.mMethodInstance == NULL)
  10172. return NULL;
  10173. if (methodDef->IsEmptyPartial())
  10174. return methodInstance;
  10175. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  10176. {
  10177. auto& genericParams = methodInstance.mMethodInstance->mMethodInfoEx->mGenericParams;
  10178. auto genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  10179. if (genericArg->IsVar())
  10180. continue;
  10181. if (genericArg->IsPrimitiveType())
  10182. {
  10183. auto primType = (BfPrimitiveType*)genericArg;
  10184. genericArg = mModule->GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  10185. }
  10186. BfAstNode* paramSrc;
  10187. if (methodMatcher.mBestMethodGenericArgumentSrcs.size() == 0)
  10188. {
  10189. paramSrc = targetSrc;
  10190. }
  10191. else
  10192. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  10193. BfError* error = NULL;
  10194. if ((!failed) && (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance.mMethodInstance), genericArg, paramSrc, genericParams[checkGenericIdx], &methodMatcher.mBestMethodGenericArguments, &error)))
  10195. {
  10196. if (methodInstance.mMethodInstance->IsSpecializedGenericMethod())
  10197. {
  10198. // We mark this as failed to make sure we don't try to process a method that doesn't even follow the constraints
  10199. methodInstance.mMethodInstance->mFailedConstraints = true;
  10200. }
  10201. if (methodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL)
  10202. {
  10203. if (error != NULL)
  10204. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance.mMethodInstance->mMethodDef->GetRefNode());
  10205. }
  10206. return BfModuleMethodInstance();
  10207. }
  10208. }
  10209. return methodInstance;
  10210. }
  10211. void BfExprEvaluator::CheckLocalMethods(BfAstNode* targetSrc, BfTypeInstance* typeInstance, const StringImpl& methodName, BfMethodMatcher& methodMatcher, BfMethodType methodType)
  10212. {
  10213. auto _GetNodeId = [&]()
  10214. {
  10215. auto parser = targetSrc->GetSourceData()->ToParserData();
  10216. return ((int64)parser->mDataId << 32) + targetSrc->GetSrcStart();
  10217. };
  10218. BfMethodState* ctxMethodState = NULL;
  10219. BfClosureInstanceInfo* ctxClosureInstanceInfo = NULL;
  10220. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL))
  10221. {
  10222. ctxClosureInstanceInfo = mModule->mCurMethodState->mClosureState->mClosureInstanceInfo;
  10223. ctxMethodState = mModule->mCurMethodState;
  10224. }
  10225. bool atCtxMethodState = false;
  10226. auto checkMethodState = mModule->mCurMethodState;
  10227. auto rootMethodState = checkMethodState;
  10228. while (checkMethodState != NULL)
  10229. {
  10230. rootMethodState = checkMethodState;
  10231. if (checkMethodState == ctxMethodState)
  10232. atCtxMethodState = true;
  10233. if ((ctxClosureInstanceInfo != NULL) && (!ctxMethodState->mClosureState->mCapturing))
  10234. {
  10235. BfMethodDef* localMethodDef = NULL;
  10236. if (ctxClosureInstanceInfo->mLocalMethodBindings.TryGetValue(_GetNodeId(), &localMethodDef))
  10237. {
  10238. methodMatcher.CheckMethod(mModule->mCurTypeInstance, localMethodDef, true);
  10239. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  10240. return;
  10241. }
  10242. }
  10243. else
  10244. {
  10245. BfLocalMethod* matchedLocalMethod = NULL;
  10246. BfLocalMethod* localMethod = NULL;
  10247. if (checkMethodState->mLocalMethodMap.TryGetValue(methodName, &localMethod))
  10248. {
  10249. while (localMethod != NULL)
  10250. {
  10251. auto methodDef = mModule->GetLocalMethodDef(localMethod);
  10252. if (methodDef->mMethodType == methodType)
  10253. {
  10254. methodMatcher.CheckMethod(mModule->mCurTypeInstance, methodDef, true);
  10255. if (methodMatcher.mBestMethodDef == methodDef)
  10256. matchedLocalMethod = localMethod;
  10257. }
  10258. localMethod = localMethod->mNextWithSameName;
  10259. }
  10260. }
  10261. if (matchedLocalMethod != NULL)
  10262. {
  10263. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  10264. {
  10265. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, typeInstance, matchedLocalMethod->mMethodDef, methodMatcher);
  10266. auto methodInstance = moduleMethodInstance.mMethodInstance;
  10267. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState != NULL))
  10268. {
  10269. // The called method is calling us from its mLocalMethodRefs set. Stretch our mCaptureStartAccessId back to incorporate its
  10270. // captures as well
  10271. if (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId < mModule->mCurMethodState->mClosureState->mCaptureStartAccessId)
  10272. mModule->mCurMethodState->mClosureState->mCaptureStartAccessId = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId;
  10273. }
  10274. else
  10275. {
  10276. if (methodInstance->mDisallowCalling) // We need to process the captures from this guy
  10277. {
  10278. if (mModule->mCurMethodState->mClosureState->mLocalMethodRefSet.Add(methodInstance))
  10279. mModule->mCurMethodState->mClosureState->mLocalMethodRefs.Add(methodInstance);
  10280. }
  10281. }
  10282. }
  10283. if (ctxClosureInstanceInfo != NULL)
  10284. {
  10285. BF_ASSERT(mModule->mCurMethodState->mClosureState->mCapturing);
  10286. ctxClosureInstanceInfo->mLocalMethodBindings[_GetNodeId()] = methodMatcher.mBestMethodDef;
  10287. }
  10288. break;
  10289. }
  10290. }
  10291. checkMethodState = checkMethodState->mPrevMethodState;
  10292. }
  10293. }
  10294. void BfExprEvaluator::InjectMixin(BfAstNode* targetSrc, BfTypedValue target, bool allowImplicitThis, const StringImpl& name, const BfSizedArray<BfExpression*>& arguments, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArgs)
  10295. {
  10296. BfAstNode* origTargetSrc = targetSrc;
  10297. BfScopedInvocationTarget* scopedInvocationTarget = NULL;
  10298. if (mModule->mParentNodeEntry != NULL)
  10299. {
  10300. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  10301. {
  10302. scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(invocationExpr->mTarget);
  10303. }
  10304. }
  10305. auto targetNameNode = targetSrc;
  10306. if (scopedInvocationTarget != NULL)
  10307. targetNameNode = scopedInvocationTarget->mTarget;
  10308. BfTypeInstance* mixinClass = NULL;
  10309. if (target.mType != NULL)
  10310. mixinClass = target.mType->ToTypeInstance();
  10311. int inLine = mModule->mCurFilePosition.mCurLine;
  10312. SizedArray<BfResolvedArg, 4> args;
  10313. SizedArray<BfExprEvaluator*, 8> argExprEvaluators;
  10314. OnScopeExit freeMem([&]()
  10315. {
  10316. for (auto exprEvaluator : argExprEvaluators)
  10317. delete exprEvaluator;
  10318. });
  10319. auto _AddArg = [&](BfExpression* argExpr)
  10320. {
  10321. BfResolvedArg resolvedArg;
  10322. argExprEvaluators.push_back(new BfExprEvaluator(mModule));
  10323. BfExprEvaluator* exprEvaluator = argExprEvaluators.back();
  10324. exprEvaluator->mResolveGenericParam = false;
  10325. if (argExpr != NULL)
  10326. exprEvaluator->Evaluate(argExpr, false, false, true);
  10327. auto argValue = exprEvaluator->mResult;
  10328. mModule->FixIntUnknown(argValue);
  10329. if (argValue)
  10330. {
  10331. if (argValue.mType->IsRef())
  10332. {
  10333. exprEvaluator->FinishExpressionResult();
  10334. }
  10335. }
  10336. resolvedArg.mTypedValue = argValue;
  10337. resolvedArg.mExpression = argExpr;
  10338. args.push_back(resolvedArg);
  10339. };
  10340. for (BfExpression* argExpr : arguments)
  10341. {
  10342. _AddArg(argExpr);
  10343. }
  10344. auto autoComplete = GetAutoComplete();
  10345. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  10346. autoComplete->mIsCapturingMethodMatchInfo = false;
  10347. BfMethodMatcher methodMatcher(targetSrc, mModule, name, args, methodGenericArgs);
  10348. methodMatcher.mMethodType = BfMethodType_Mixin;
  10349. methodMatcher.mSkipImplicitParams = true;
  10350. auto curTypeInst = mModule->mCurTypeInstance;
  10351. if (mixinClass != NULL)
  10352. curTypeInst = mixinClass;
  10353. if (target.mType == NULL)
  10354. {
  10355. CheckLocalMethods(targetSrc, curTypeInst, name, methodMatcher, BfMethodType_Mixin);
  10356. }
  10357. if (methodMatcher.mBestMethodDef == NULL)
  10358. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  10359. if (methodMatcher.mBestMethodDef == NULL)
  10360. {
  10361. if (mixinClass != NULL)
  10362. methodMatcher.CheckType(mixinClass, BfTypedValue(), false);
  10363. else
  10364. methodMatcher.CheckType(mModule->mCurTypeInstance, BfTypedValue(), false);
  10365. }
  10366. if ((methodMatcher.mBestMethodDef == NULL) && (mModule->mContext->mCurTypeState != NULL))
  10367. {
  10368. BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mTypeInstance);
  10369. BfGlobalLookup globalLookup;
  10370. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  10371. globalLookup.mName = name;
  10372. mModule->PopulateGlobalContainersList(globalLookup);
  10373. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  10374. {
  10375. if (globalContainer.mTypeInst == NULL)
  10376. continue;
  10377. methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false);
  10378. if (methodMatcher.mBestMethodDef != NULL)
  10379. break;
  10380. }
  10381. }
  10382. if (methodMatcher.mBestMethodDef == NULL)
  10383. {
  10384. mModule->Fail("Cannot find mixin", targetSrc);
  10385. return;
  10386. }
  10387. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  10388. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetNameNode)) && (autoComplete->mDefType == NULL))
  10389. {
  10390. autoComplete->mInsertStartIdx = targetNameNode->GetSrcStart();
  10391. autoComplete->mInsertEndIdx = targetNameNode->GetSrcEnd();
  10392. autoComplete->mDefType = methodMatcher.mBestMethodTypeInstance->mTypeDef;
  10393. autoComplete->mDefMethod = methodMatcher.mBestMethodDef;
  10394. autoComplete->SetDefinitionLocation(methodMatcher.mBestMethodDef->GetMethodDeclaration()->mNameNode);
  10395. }
  10396. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method))
  10397. {
  10398. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() - 1);
  10399. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetNameNode, methodMatcher.mBestMethodTypeInstance->mTypeDef, methodMatcher.mBestMethodDef);
  10400. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() + 1);
  10401. }
  10402. auto curMethodState = mModule->mCurMethodState;
  10403. //
  10404. {
  10405. bool hasCircularRef = false;
  10406. auto checkMethodState = curMethodState;
  10407. while (checkMethodState != NULL)
  10408. {
  10409. auto curMixinState = checkMethodState->mMixinState;
  10410. while (curMixinState != NULL)
  10411. {
  10412. if (curMixinState->mSource == targetSrc)
  10413. hasCircularRef = true;
  10414. curMixinState = curMixinState->mPrevMixinState;
  10415. }
  10416. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mActiveDeferredLocalMethod != NULL))
  10417. {
  10418. for (auto& mixinRecord : checkMethodState->mClosureState->mActiveDeferredLocalMethod->mMixinStateRecords)
  10419. {
  10420. if (mixinRecord.mSource == targetSrc)
  10421. hasCircularRef = true;
  10422. }
  10423. }
  10424. checkMethodState = checkMethodState->mPrevMethodState;
  10425. }
  10426. if (hasCircularRef)
  10427. {
  10428. mModule->Fail("Circular reference detected between mixins", targetSrc);
  10429. return;
  10430. }
  10431. }
  10432. auto moduleMethodInstance = GetSelectedMethod(targetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  10433. if (!moduleMethodInstance)
  10434. return;
  10435. auto methodInstance = moduleMethodInstance.mMethodInstance;
  10436. // Check circular ref based on methodInstance
  10437. {
  10438. bool hasCircularRef = false;
  10439. auto checkMethodState = curMethodState;
  10440. while (checkMethodState != NULL)
  10441. {
  10442. if (checkMethodState->mMethodInstance == methodInstance)
  10443. hasCircularRef = true;
  10444. auto curMixinState = checkMethodState->mMixinState;
  10445. while (curMixinState != NULL)
  10446. {
  10447. if (curMixinState->mMixinMethodInstance == methodInstance)
  10448. hasCircularRef = true;
  10449. curMixinState = curMixinState->mPrevMixinState;
  10450. }
  10451. checkMethodState = checkMethodState->mPrevMethodState;
  10452. }
  10453. if (hasCircularRef)
  10454. {
  10455. mModule->Fail("Circular reference detected between mixins", targetSrc);
  10456. return;
  10457. }
  10458. }
  10459. AddCallDependencies(methodInstance);
  10460. if (!methodMatcher.mBestMethodDef->mIsStatic)
  10461. {
  10462. if ((!target) && (allowImplicitThis))
  10463. target = mModule->GetThis();
  10464. if (!target)
  10465. {
  10466. mModule->Fail(StrFormat("An instance reference is required to invoke the non-static mixin '%s'",
  10467. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  10468. }
  10469. }
  10470. else
  10471. {
  10472. if (target)
  10473. {
  10474. mModule->Fail(StrFormat("Mixin '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  10475. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  10476. }
  10477. }
  10478. int methodParamCount = (int)methodInstance->GetParamCount();
  10479. // Implicit params are ignored for calling- they should be resolved at the injection site
  10480. int implicitParamCount = methodInstance->GetImplicitParamCount();
  10481. int explicitParamCount = methodParamCount - implicitParamCount;
  10482. while ((int)args.size() < explicitParamCount)
  10483. {
  10484. int argIdx = (int)args.size();
  10485. BfExpression* expr = methodInstance->GetParamInitializer(argIdx);
  10486. if (expr == NULL)
  10487. break;
  10488. _AddArg(expr);
  10489. }
  10490. if ((int)args.size() < explicitParamCount)
  10491. {
  10492. BfError* error = mModule->Fail(StrFormat("Not enough arguments specified, expected %d more.", explicitParamCount - (int)arguments.size()), targetSrc);
  10493. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  10494. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  10495. return;
  10496. }
  10497. else if ((int)args.size() > explicitParamCount)
  10498. {
  10499. BfError* error = mModule->Fail(StrFormat("Too many arguments specified, expected %d fewer.", (int)arguments.size() - explicitParamCount), targetSrc);
  10500. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  10501. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  10502. return;
  10503. }
  10504. int paramIdx = implicitParamCount;
  10505. auto argExprEvaluatorItr = argExprEvaluators.begin();
  10506. for (int argIdx = 0; argIdx < (int)args.size(); argIdx++)
  10507. {
  10508. auto exprEvaluator = *argExprEvaluatorItr;
  10509. //auto paramType = methodInstance->GetParamKind(paramIdx);
  10510. BfType* wantType = methodInstance->mParams[paramIdx].mResolvedType;
  10511. auto& arg = args[argIdx];
  10512. if (wantType->IsGenericParam())
  10513. {
  10514. //
  10515. }
  10516. else if (!wantType->IsVar())
  10517. {
  10518. if (arg.mTypedValue.mType == NULL)
  10519. {
  10520. mModule->AssertErrorState();
  10521. return;
  10522. }
  10523. if (arg.mTypedValue.mType != wantType)
  10524. {
  10525. exprEvaluator->FinishExpressionResult();
  10526. arg.mTypedValue = mModule->LoadValue(arg.mTypedValue);
  10527. arg.mTypedValue = mModule->Cast(arg.mExpression, arg.mTypedValue, wantType);
  10528. /*// Do this to generate default implicit cast error
  10529. mModule->Fail(StrFormat("Mixin argument type '%s' must match parameter type '%s'.",
  10530. mModule->TypeToString(arg.mTypedValue.mType).c_str(),
  10531. mModule->TypeToString(wantType).c_str()), arg.mExpression);
  10532. return;*/
  10533. }
  10534. }
  10535. paramIdx++;
  10536. argExprEvaluatorItr++;
  10537. }
  10538. mModule->AddDependency(methodInstance->GetOwner(), mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  10539. auto startBlock = mModule->mBfIRBuilder->CreateBlock("mixinStart");
  10540. mModule->mBfIRBuilder->CreateBr(startBlock);
  10541. mModule->mBfIRBuilder->AddBlock(startBlock);
  10542. mModule->mBfIRBuilder->SetInsertPoint(startBlock);
  10543. //auto prevDebugLoc = mModule->mBfIRBuilder->getCurrentDebugLocation();
  10544. // This is so when we debug we can hit a steppoint on the inlined "call line"
  10545. mModule->EmitEnsureInstructionAt();
  10546. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  10547. BfMixinState* mixinState = rootMethodState->mMixinStates.Alloc();
  10548. mixinState->mPrevMixinState = curMethodState->mMixinState;
  10549. mixinState->mLocalsStartIdx = (int)mModule->mCurMethodState->mLocals.size();
  10550. mixinState->mMixinMethodInstance = methodInstance;
  10551. mixinState->mSource = origTargetSrc;
  10552. mixinState->mCallerScope = mModule->mCurMethodState->mCurScope;
  10553. mixinState->mTargetScope = mixinState->mCallerScope;
  10554. mixinState->mResultExpr = NULL;
  10555. mixinState->mHasDeferredUsage = false;
  10556. mixinState->mUsedInvocationScope = false;
  10557. mixinState->mTarget = target;
  10558. auto checkNode = origTargetSrc;
  10559. if (scopedInvocationTarget != NULL)
  10560. {
  10561. auto targetScope = mModule->FindScope(scopedInvocationTarget->mScopeName, curMethodState->mMixinState);
  10562. if (targetScope != NULL)
  10563. mixinState->mTargetScope = targetScope;
  10564. }
  10565. mModule->mBfIRBuilder->SaveDebugLocation();
  10566. SetAndRestoreValue<BfMixinState*> prevMixinState(curMethodState->mMixinState, mixinState);
  10567. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  10568. if (mModule->mCompiler->mResolvePassData != NULL)
  10569. {
  10570. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  10571. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  10572. }
  10573. defer
  10574. {
  10575. if (mModule->mCompiler->mResolvePassData != NULL)
  10576. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  10577. };
  10578. auto methodDef = methodInstance->mMethodDef;
  10579. auto methodDeclaration = methodDef->GetMethodDeclaration();
  10580. BfScopeData scopeData;
  10581. scopeData.mCloseNode = methodDeclaration->mBody;
  10582. if (auto block = BfNodeDynCast<BfBlock>(methodDeclaration->mBody))
  10583. {
  10584. if (block->mCloseBrace != NULL)
  10585. scopeData.mCloseNode = block->mCloseBrace;
  10586. }
  10587. curMethodState->AddScope(&scopeData);
  10588. curMethodState->mCurScope->mMixinDepth++;
  10589. curMethodState->mIsEmbedded = false;
  10590. // We can't flush scope state because we extend params in as arbitrary values
  10591. mModule->NewScopeState(true, false);
  10592. bool wantsDIData = (mModule->mBfIRBuilder->DbgHasInfo()) && (mModule->mHasFullDebugInfo);
  10593. DISubprogram* diFunction = NULL;
  10594. int mixinLocalVarIdx = -1;
  10595. int startLocalIdx = (int)mModule->mCurMethodState->mLocals.size();
  10596. int endLocalIdx = startLocalIdx;
  10597. if (wantsDIData)
  10598. {
  10599. BfIRMDNode diFuncType = mModule->mBfIRBuilder->DbgCreateSubroutineType(SizedArray<BfIRMDNode, 0>());
  10600. //int defLine = mModule->mCurFilePosition.mCurLine;
  10601. int flags = 0;
  10602. curMethodState->mCurScope->mDIInlinedAt = mModule->mBfIRBuilder->DbgGetCurrentLocation();
  10603. // 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
  10604. // definitions, so we need to be consistent and use the actual line
  10605. mModule->UpdateSrcPos(methodDeclaration->mNameNode, BfSrcPosFlag_NoSetDebugLoc);
  10606. int defLine = mModule->mCurFilePosition.mCurLine;
  10607. auto diParentType = mModule->mBfIRBuilder->DbgGetTypeInst(methodInstance->GetOwner());
  10608. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  10609. {
  10610. curMethodState->mCurScope->mDIScope = mModule->mBfIRBuilder->DbgCreateFunction(diParentType, methodDef->mName + "!", "", mModule->mCurFilePosition.mFileInstance->mDIFile,
  10611. defLine + 1, diFuncType, false, true, mModule->mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  10612. scopeData.mAltDIFile = mModule->mCurFilePosition.mFileInstance->mDIFile;
  10613. }
  10614. }
  10615. if (methodDef->mBody != NULL)
  10616. mModule->UpdateSrcPos(methodDef->mBody);
  10617. mModule->SetIllegalSrcPos();
  10618. auto _AddLocalVariable = [&](BfLocalVariable* newLocalVar, BfExprEvaluator* exprEvaluator)
  10619. {
  10620. mModule->SetIllegalSrcPos();
  10621. bool hasConstValue = newLocalVar->mConstValue;
  10622. if (hasConstValue)
  10623. {
  10624. auto constant = mModule->mBfIRBuilder->GetConstant(newLocalVar->mConstValue);
  10625. hasConstValue = constant->mConstType < BfConstType_GlobalVar;
  10626. }
  10627. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL) && (exprEvaluator->mResultLocalVarField == 0))
  10628. {
  10629. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  10630. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  10631. auto inLocalVar = exprEvaluator->mResultLocalVar;
  10632. newLocalVar->mIsAssigned = inLocalVar->mIsAssigned;
  10633. newLocalVar->mUnassignedFieldFlags = inLocalVar->mUnassignedFieldFlags;
  10634. newLocalVar->mReadFromId = inLocalVar->mReadFromId;
  10635. newLocalVar->mIsReadOnly = inLocalVar->mIsReadOnly;
  10636. if ((!newLocalVar->mIsAssigned) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  10637. {
  10638. for (auto deferredAssign : mModule->mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  10639. {
  10640. if (deferredAssign.mLocalVar == inLocalVar)
  10641. newLocalVar->mIsAssigned = true;
  10642. }
  10643. }
  10644. }
  10645. else
  10646. {
  10647. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  10648. }
  10649. if ((wantsDIData) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  10650. {
  10651. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  10652. if (hasConstValue)
  10653. {
  10654. // Already handled
  10655. }
  10656. else if (mModule->IsTargetingBeefBackend())
  10657. {
  10658. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  10659. mModule->SetIllegalSrcPos();
  10660. // With the Beef backend we can assign two variables to the same value, but LLVM does not allow this
  10661. // so we have to create a ref to that variable
  10662. auto diType = mModule->mBfIRBuilder->DbgGetType(newLocalVar->mResolvedType);
  10663. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  10664. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  10665. if (newLocalVar->mIsSplat)
  10666. {
  10667. //TODO: Implement
  10668. }
  10669. else
  10670. {
  10671. BfIRValue value = newLocalVar->mValue;
  10672. if (newLocalVar->mAddr)
  10673. value = newLocalVar->mAddr;
  10674. else if (newLocalVar->mConstValue)
  10675. value = newLocalVar->mConstValue;
  10676. auto aliasValue = mModule->mBfIRBuilder->CreateAliasValue(value);
  10677. if (mModule->WantsLifetimes())
  10678. scopeData.mDeferredLifetimeEnds.Add(aliasValue);
  10679. if (newLocalVar->mAddr)
  10680. mModule->mBfIRBuilder->DbgInsertDeclare(aliasValue, diVariable);
  10681. else
  10682. {
  10683. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(aliasValue, diVariable);
  10684. //mModule->mBfIRBuilder->DbgInsertValueIntrinsic(newLocalVar->mValue, diVariable);
  10685. }
  10686. }
  10687. }
  10688. else if (newLocalVar->mAddr)
  10689. {
  10690. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  10691. mModule->SetIllegalSrcPos();
  10692. auto refType = mModule->CreateRefType(newLocalVar->mResolvedType);
  10693. auto allocaVal = mModule->CreateAlloca(refType);
  10694. mModule->mBfIRBuilder->CreateStore(newLocalVar->mAddr, allocaVal);
  10695. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  10696. {
  10697. auto diType = mModule->mBfIRBuilder->DbgGetType(refType);
  10698. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  10699. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  10700. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  10701. }
  10702. }
  10703. else if (newLocalVar->mValue)
  10704. {
  10705. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  10706. mModule->SetIllegalSrcPos();
  10707. auto localVal = LoadLocal(newLocalVar);
  10708. localVal = mModule->LoadValue(localVal);
  10709. localVal = mModule->AggregateSplat(localVal);
  10710. BfType* allocType = localVal.mType;
  10711. auto allocaVal = mModule->CreateAlloca(allocType);
  10712. mModule->mBfIRBuilder->CreateStore(localVal.mValue, allocaVal);
  10713. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  10714. {
  10715. if (newLocalVar->mIsSplat)
  10716. {
  10717. //TODO: Implement
  10718. }
  10719. else
  10720. {
  10721. auto diType = mModule->mBfIRBuilder->DbgGetType(allocType);
  10722. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  10723. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  10724. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  10725. }
  10726. }
  10727. }
  10728. }
  10729. newLocalVar->mParamIdx = -3;
  10730. };
  10731. argExprEvaluatorItr = argExprEvaluators.begin();
  10732. for (int argIdx = 0; argIdx < (int)explicitParamCount; argIdx++)
  10733. {
  10734. int paramIdx = argIdx;
  10735. auto exprEvaluator = *argExprEvaluatorItr;
  10736. auto paramDef = methodDef->mParams[paramIdx];
  10737. auto arg = &args[argIdx];
  10738. if (!arg->mTypedValue)
  10739. {
  10740. auto wantType = methodInstance->GetParamType(paramIdx);
  10741. if (wantType->IsVar())
  10742. wantType = mModule->mContext->mBfObjectType;
  10743. arg->mTypedValue = mModule->GetDefaultTypedValue(wantType);
  10744. }
  10745. BfLocalVariable* localVar = new BfLocalVariable();
  10746. localVar->mName = paramDef->mName;
  10747. localVar->mResolvedType = arg->mTypedValue.mType;
  10748. if (arg->mTypedValue.mType->IsRef())
  10749. {
  10750. auto refType = (BfRefType*)localVar->mResolvedType;
  10751. localVar->mAddr = mModule->LoadValue(arg->mTypedValue).mValue;
  10752. localVar->mResolvedType = arg->mTypedValue.mType->GetUnderlyingType();
  10753. localVar->mIsAssigned = refType->mRefKind != BfRefType::RefKind_Out;
  10754. }
  10755. else if (arg->mTypedValue.IsAddr())
  10756. localVar->mAddr = arg->mTypedValue.mValue;
  10757. else
  10758. {
  10759. if (!arg->mTypedValue.mValue)
  10760. {
  10761. // Untyped value
  10762. }
  10763. else if (arg->mTypedValue.mValue.IsConst())
  10764. {
  10765. localVar->mConstValue = arg->mTypedValue.mValue;
  10766. }
  10767. else if (arg->mTypedValue.IsSplat())
  10768. {
  10769. localVar->mValue = arg->mTypedValue.mValue;
  10770. localVar->mIsSplat = true;
  10771. }
  10772. else
  10773. {
  10774. if (arg->mTypedValue.IsAddr())
  10775. localVar->mAddr = arg->mTypedValue.mValue;
  10776. else
  10777. localVar->mValue = arg->mTypedValue.mValue;
  10778. }
  10779. localVar->mIsReadOnly = arg->mTypedValue.IsReadOnly();
  10780. }
  10781. _AddLocalVariable(localVar, exprEvaluator);
  10782. endLocalIdx++;
  10783. ++argExprEvaluatorItr;
  10784. }
  10785. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  10786. mModule->VisitCodeBlock(blockBody);
  10787. if (mixinState->mResultExpr != NULL)
  10788. {
  10789. if (auto exprNode = BfNodeDynCast<BfExpression>(mixinState->mResultExpr))
  10790. {
  10791. //if ((exprNode->mTrailingSemicolon == NULL) && (!exprNode->IsA<BfBlock>()))
  10792. if (!exprNode->IsA<BfBlock>())
  10793. {
  10794. // Mixin expression result
  10795. mModule->UpdateSrcPos(exprNode);
  10796. VisitChild(exprNode);
  10797. FinishExpressionResult();
  10798. ResolveGenericType();
  10799. //mResult = mModule->LoadValue(mResult);
  10800. }
  10801. }
  10802. }
  10803. if (!mResult)
  10804. {
  10805. // If we didn't have an expression body then just make the result "void"
  10806. mResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  10807. }
  10808. int localIdx = startLocalIdx;
  10809. if (mixinLocalVarIdx != -1)
  10810. {
  10811. BfLocalVariable* localVar = curMethodState->mLocals[localIdx];
  10812. if (mResultLocalVar != NULL)
  10813. {
  10814. auto inLocalVar = mResultLocalVar;
  10815. if (localVar->mIsAssigned)
  10816. inLocalVar->mIsAssigned = true;
  10817. if (localVar->mReadFromId != -1)
  10818. inLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  10819. }
  10820. localIdx++;
  10821. }
  10822. argExprEvaluatorItr = argExprEvaluators.begin();
  10823. for ( ; localIdx < endLocalIdx; localIdx++)
  10824. {
  10825. auto exprEvaluator = *argExprEvaluatorItr;
  10826. BfLocalVariable* localVar = curMethodState->mLocals[localIdx];
  10827. //TODO: Merge unassigned flags together
  10828. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL))
  10829. {
  10830. auto inLocalVar = exprEvaluator->mResultLocalVar;
  10831. if (localVar->mIsAssigned)
  10832. inLocalVar->mIsAssigned = true;
  10833. if (localVar->mReadFromId != -1)
  10834. inLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  10835. }
  10836. ++argExprEvaluatorItr;
  10837. }
  10838. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  10839. if (blockBody->mCloseBrace != NULL)
  10840. mModule->UpdateSrcPos(blockBody->mCloseBrace);
  10841. mModule->RestoreScopeState();
  10842. prevMixinState.Restore();
  10843. if (mixinState->mHasDeferredUsage)
  10844. {
  10845. // if (target)
  10846. // {
  10847. // if (target.mType->IsValuelessType())
  10848. // mixinState->mTarget = target;
  10849. // else
  10850. // {
  10851. // target = mModule->LoadValue(target);
  10852. // auto savedTarget = BfTypedValue(mModule->CreateAlloca(target.mType, false), target.mType, true);
  10853. // mModule->mBfIRBuilder->CreateStore(target.mValue, savedTarget.mValue);
  10854. // mixinState->mTarget = savedTarget;
  10855. // }
  10856. // }
  10857. mixinState->mTarget = BfTypedValue();
  10858. }
  10859. else
  10860. {
  10861. BF_ASSERT(rootMethodState->mMixinStates.back() == mixinState);
  10862. rootMethodState->mMixinStates.pop_back();
  10863. delete mixinState;
  10864. }
  10865. if ((scopedInvocationTarget != NULL) && (scopedInvocationTarget->mScopeName != NULL) && (!mixinState->mUsedInvocationScope))
  10866. {
  10867. mModule->Warn(0, "Scope specifier was not referenced in mixin", scopedInvocationTarget->mScopeName);
  10868. }
  10869. // It's tempting to do this, but it is really just covering up other issues.
  10870. //mModule->mBfIRBuilder->SetCurrentDebugLocation(prevDebugLoc);
  10871. // But does THIS work?
  10872. mModule->mBfIRBuilder->RestoreDebugLocation();
  10873. }
  10874. void BfExprEvaluator::SetMethodElementType(BfAstNode* target)
  10875. {
  10876. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(target))
  10877. {
  10878. SetMethodElementType(delegateBindExpr->mTarget);
  10879. return;
  10880. }
  10881. if (auto lambdaBindExpr = BfNodeDynCast<BfLambdaBindExpression>(target))
  10882. {
  10883. return;
  10884. }
  10885. if (auto attributedIdentifierNode = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  10886. {
  10887. if (attributedIdentifierNode->mIdentifier != NULL)
  10888. mModule->SetElementType(attributedIdentifierNode->mIdentifier, BfSourceElementType_Method);
  10889. }
  10890. else if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(target))
  10891. {
  10892. if (memberReferenceExpr->mMemberName != NULL)
  10893. SetMethodElementType(memberReferenceExpr->mMemberName);
  10894. }
  10895. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(target))
  10896. SetMethodElementType(qualifiedNameNode->mRight);
  10897. else
  10898. mModule->SetElementType(target, BfSourceElementType_Method);
  10899. }
  10900. void BfExprEvaluator::DoInvocation(BfAstNode* target, BfMethodBoundExpression* methodBoundExpr, const BfSizedArray<BfExpression*>& args, BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments, BfTypedValue* outCascadeValue)
  10901. {
  10902. // Just a check
  10903. mModule->mBfIRBuilder->GetInsertBlock();
  10904. bool wasCapturingMethodInfo = false;
  10905. auto autoComplete = GetAutoComplete();
  10906. if ((autoComplete != NULL) && (methodGenericArguments != NULL))
  10907. {
  10908. for (BfTypeReference* methodGenericArg : *methodGenericArguments)
  10909. autoComplete->CheckTypeRef(methodGenericArg, false, true);
  10910. }
  10911. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  10912. {
  10913. // We don't want to capture a call within the target node
  10914. wasCapturingMethodInfo = true;
  10915. autoComplete->mIsCapturingMethodMatchInfo = false;
  10916. }
  10917. bool allowImplicitThis = false;
  10918. BfAstNode* methodNodeSrc = target;
  10919. BfAttributeState attributeState;
  10920. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  10921. if (auto scopedTarget = BfNodeDynCast<BfScopedInvocationTarget>(target))
  10922. {
  10923. target = scopedTarget->mTarget;
  10924. if (autoComplete != NULL)
  10925. {
  10926. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopedTarget->mScopeName))
  10927. autoComplete->CheckLabel(identifier, scopedTarget->mColonToken);
  10928. }
  10929. //mModule->FindScope(scopedTarget->mScopeName);
  10930. }
  10931. bool isCascade = false;
  10932. BfAstNode* cascadeOperatorToken = NULL;
  10933. bool bypassVirtual = false;
  10934. bool gaveUnqualifiedDotError = false;
  10935. String targetFunctionName;
  10936. BfTypedValue thisValue;
  10937. //TODO: This may just be a fully qualified static method name, so let's check that also
  10938. if (auto memberRefExpression = BfNodeDynCast<BfMemberReferenceExpression>(target))
  10939. {
  10940. if (autoComplete != NULL)
  10941. {
  10942. if (memberRefExpression->mTarget != NULL)
  10943. autoComplete->CheckMemberReference(memberRefExpression->mTarget, memberRefExpression->mDotToken, memberRefExpression->mMemberName, false, mExpectingType);
  10944. else if (mExpectingType != NULL)
  10945. {
  10946. String filter;
  10947. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(memberRefExpression->mDotToken, memberRefExpression->mMemberName, filter)))
  10948. {
  10949. auto typeInst = mExpectingType->ToTypeInstance();
  10950. if (typeInst != NULL)
  10951. {
  10952. String filter;
  10953. if ((memberRefExpression->mMemberName != NULL) && (autoComplete->IsAutocompleteNode(memberRefExpression->mMemberName)))
  10954. filter = autoComplete->GetFilter(memberRefExpression->mMemberName);
  10955. bool allowPrivate = typeInst == mModule->mCurTypeInstance;
  10956. autoComplete->AddEnumTypeMembers(typeInst, filter, false, allowPrivate);
  10957. autoComplete->AddSelfResultTypeMembers(typeInst, typeInst, filter, allowPrivate);
  10958. }
  10959. }
  10960. }
  10961. }
  10962. if ((memberRefExpression->mTarget == NULL) && (memberRefExpression->mMemberName == NULL))
  10963. {
  10964. if (mExpectingType != NULL)
  10965. {
  10966. if (mExpectingType->IsSizedArray())
  10967. {
  10968. if (mModule->mParentNodeEntry != NULL)
  10969. {
  10970. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  10971. {
  10972. InitializedSizedArray((BfSizedArrayType*)mExpectingType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen);
  10973. return;
  10974. }
  10975. }
  10976. }
  10977. else if (mExpectingType->IsStruct())
  10978. {
  10979. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  10980. {
  10981. autoComplete->mIsCapturingMethodMatchInfo = true;
  10982. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  10983. }
  10984. if (mModule->mParentNodeEntry != NULL)
  10985. {
  10986. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  10987. {
  10988. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  10989. BfResolveArgFlags resolveArgsFlags = BfResolveArgFlag_DeferParamEval;
  10990. ResolveArgValues(argValues, resolveArgsFlags);
  10991. if ((mReceivingValue != NULL) && (mReceivingValue->mType == mExpectingType) && (mReceivingValue->IsAddr()))
  10992. {
  10993. mResult = *mReceivingValue;
  10994. mReceivingValue = NULL;
  10995. }
  10996. else
  10997. mResult = BfTypedValue(mModule->CreateAlloca(mExpectingType), mExpectingType, BfTypedValueKind_TempAddr);
  10998. MatchConstructor(target, methodBoundExpr, mResult, mExpectingType->ToTypeInstance(), argValues, false, false);
  10999. mModule->ValidateAllocation(mExpectingType, invocationExpr->mTarget);
  11000. return;
  11001. }
  11002. }
  11003. }
  11004. else
  11005. {
  11006. gaveUnqualifiedDotError = true;
  11007. mModule->Fail(StrFormat("Cannot use inferred constructor on type '%s'", mModule->TypeToString(mExpectingType).c_str()), memberRefExpression->mDotToken);
  11008. }
  11009. }
  11010. }
  11011. if (memberRefExpression->IsA<BfBaseExpression>())
  11012. bypassVirtual = true;
  11013. if (memberRefExpression->mMemberName != NULL)
  11014. methodNodeSrc = memberRefExpression->mMemberName;
  11015. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpression->mMemberName))
  11016. {
  11017. if (attrIdentifier->mIdentifier != NULL)
  11018. methodNodeSrc = attrIdentifier->mIdentifier;
  11019. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  11020. if (attrIdentifier->mIdentifier != NULL)
  11021. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  11022. }
  11023. else if (memberRefExpression->mMemberName != NULL)
  11024. targetFunctionName = memberRefExpression->mMemberName->ToString();
  11025. if (memberRefExpression->mTarget == NULL)
  11026. {
  11027. if (mExpectingType)
  11028. mResult = BfTypedValue(mExpectingType);
  11029. else if (!gaveUnqualifiedDotError)
  11030. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", memberRefExpression->mDotToken);
  11031. }
  11032. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpression->mTarget))
  11033. {
  11034. // Static method
  11035. mResult = BfTypedValue(ResolveTypeRef(typeRef));
  11036. }
  11037. if (auto leftIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpression->mTarget))
  11038. {
  11039. bool hadError = false;
  11040. thisValue = LookupIdentifier(leftIdentifier, true, &hadError);
  11041. CheckResultForReading(thisValue);
  11042. if (mPropDef != NULL)
  11043. thisValue = GetResult(true);
  11044. if (hadError)
  11045. {
  11046. mModule->AssertErrorState();
  11047. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11048. }
  11049. if ((!thisValue) && (mPropDef == NULL))
  11050. {
  11051. // Identifier not found. Static method? Just check speculatively don't throw error
  11052. BfType* type;
  11053. {
  11054. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  11055. type = mModule->ResolveTypeRef(leftIdentifier, NULL, BfPopulateType_DataAndMethods, BfResolveTypeRefFlag_NoResolveGenericParam);
  11056. }
  11057. if (type != NULL)
  11058. thisValue = BfTypedValue(type);
  11059. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(leftIdentifier))
  11060. {
  11061. LookupQualifiedStaticField(qualifiedLeft, true);
  11062. thisValue = mResult;
  11063. mResult = BfTypedValue();
  11064. }
  11065. }
  11066. if (mPropDef != NULL)
  11067. thisValue = GetResult(true);
  11068. if (!thisValue.mType)
  11069. {
  11070. mModule->Fail("Identifier not found", leftIdentifier);
  11071. mModule->CheckTypeRefFixit(leftIdentifier);
  11072. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11073. }
  11074. if (mResult)
  11075. CheckResultForReading(mResult);
  11076. mResult = thisValue;
  11077. }
  11078. else if (auto expr = BfNodeDynCast<BfExpression>(memberRefExpression->mTarget))
  11079. {
  11080. BfType* expectingTargetType = NULL;
  11081. if (memberRefExpression->mDotToken->mToken == BfToken_DotDot)
  11082. expectingTargetType = mExpectingType;
  11083. bool handled = false;
  11084. if (auto subMemberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(expr))
  11085. {
  11086. String findName;
  11087. if (subMemberRefExpr->mMemberName != NULL)
  11088. findName = subMemberRefExpr->mMemberName->ToString();
  11089. if (findName == "base") // Generic IFace<T>.base
  11090. {
  11091. thisValue = mModule->GetThis();
  11092. if (thisValue)
  11093. {
  11094. VisitChild(subMemberRefExpr->mTarget);
  11095. if (mResult.HasType())
  11096. {
  11097. if (mResult.mValue)
  11098. {
  11099. mModule->Fail("Type name expected", subMemberRefExpr->mTarget);
  11100. }
  11101. else
  11102. {
  11103. auto type = mResult.mType;
  11104. if (type != NULL)
  11105. {
  11106. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  11107. {
  11108. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  11109. mModule->TypeToString(type).c_str(),
  11110. mModule->TypeToString(thisValue.mType).c_str()), subMemberRefExpr->mTarget);
  11111. }
  11112. else
  11113. {
  11114. if (type->IsInterface())
  11115. {
  11116. thisValue.mType = type;
  11117. }
  11118. else
  11119. {
  11120. auto castedThis = mModule->Cast(subMemberRefExpr->mMemberName, thisValue, type, BfCastFlags_Explicit);
  11121. if (castedThis)
  11122. thisValue = castedThis;
  11123. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  11124. }
  11125. }
  11126. handled = true;
  11127. }
  11128. bypassVirtual = true;
  11129. }
  11130. }
  11131. }
  11132. }
  11133. }
  11134. if (!handled)
  11135. {
  11136. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  11137. auto flags = (BfEvalExprFlags)(BfEvalExprFlags_PropogateNullConditional | BfEvalExprFlags_NoCast);
  11138. if (mFunctionBindResult != NULL)
  11139. {
  11140. if (auto paranExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  11141. {
  11142. // Allow 'ref' on binding, to indicate we want to capture 'this' by reference
  11143. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowRefExpr);
  11144. expr = paranExpr->mExpression;
  11145. }
  11146. }
  11147. if (expr != NULL)
  11148. mResult = mModule->CreateValueFromExpression(expr, expectingTargetType, flags);
  11149. }
  11150. }
  11151. isCascade = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_DotDot);
  11152. if (isCascade)
  11153. cascadeOperatorToken = memberRefExpression->mDotToken;
  11154. bool isNullCondLookup = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_QuestionDot);
  11155. if (isNullCondLookup)
  11156. mResult = SetupNullConditional(mResult, memberRefExpression->mDotToken);
  11157. if ((mResult.mType == NULL) && (memberRefExpression->mTarget != NULL))
  11158. {
  11159. mModule->AssertErrorState();
  11160. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11161. }
  11162. thisValue = mResult;
  11163. mResult = BfTypedValue();
  11164. }
  11165. else if (auto qualifiedName = BfNodeDynCast<BfQualifiedNameNode>(target))
  11166. {
  11167. if (GetAutoComplete() != NULL)
  11168. GetAutoComplete()->CheckMemberReference(qualifiedName->mLeft, qualifiedName->mDot, qualifiedName->mRight);
  11169. if (qualifiedName->mLeft->GetSrcLength() == 4)
  11170. {
  11171. StringT<16> leftName;
  11172. qualifiedName->mLeft->ToString(leftName);
  11173. if (leftName == "base")
  11174. bypassVirtual = true;
  11175. }
  11176. if (qualifiedName->mRight != NULL)
  11177. methodNodeSrc = qualifiedName->mRight;
  11178. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(qualifiedName->mRight))
  11179. {
  11180. if (attrIdentifier->mIdentifier != NULL)
  11181. methodNodeSrc = attrIdentifier->mIdentifier;
  11182. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  11183. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  11184. }
  11185. else
  11186. targetFunctionName = qualifiedName->mRight->ToString();
  11187. bool hadError = false;
  11188. thisValue = LookupIdentifier(qualifiedName->mLeft, true, &hadError);
  11189. CheckResultForReading(thisValue);
  11190. if (mPropDef != NULL)
  11191. thisValue = GetResult(true);
  11192. if (hadError)
  11193. {
  11194. mModule->AssertErrorState();
  11195. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11196. }
  11197. if ((!thisValue) && (mPropDef == NULL))
  11198. {
  11199. // Identifier not found. Static method? Just check speculatively don't throw error
  11200. BfType* type;
  11201. {
  11202. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  11203. type = mModule->ResolveTypeRef(qualifiedName->mLeft, NULL, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_IgnoreLookupError));
  11204. }
  11205. if (type == NULL)
  11206. {
  11207. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  11208. type = mModule->ResolveTypeRef(qualifiedName, methodGenericArguments, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_IgnoreLookupError));
  11209. if (type != NULL)
  11210. {
  11211. // This is a CTOR call, treat it as such
  11212. targetFunctionName.clear();
  11213. }
  11214. }
  11215. if (type != NULL)
  11216. thisValue = BfTypedValue(type);
  11217. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(qualifiedName->mLeft))
  11218. {
  11219. String findName = qualifiedLeft->mRight->ToString();
  11220. bool handled = false;
  11221. if (findName == "base")
  11222. {
  11223. auto type = mModule->ResolveTypeRef(qualifiedLeft->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  11224. mModule->CheckTypeRefFixit(qualifiedLeft->mLeft);
  11225. thisValue = mModule->GetThis();
  11226. if (type != NULL)
  11227. {
  11228. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  11229. {
  11230. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  11231. mModule->TypeToString(type).c_str(),
  11232. mModule->TypeToString(thisValue.mType).c_str()), qualifiedLeft->mLeft);
  11233. }
  11234. else
  11235. {
  11236. if (type->IsInterface())
  11237. {
  11238. thisValue.mType = type;
  11239. }
  11240. else
  11241. {
  11242. auto castedThis = mModule->Cast(qualifiedLeft->mRight, thisValue, type, BfCastFlags_Explicit);
  11243. if (castedThis)
  11244. thisValue = castedThis;
  11245. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  11246. }
  11247. }
  11248. handled = true;
  11249. }
  11250. bypassVirtual = true;
  11251. }
  11252. if (!handled)
  11253. {
  11254. LookupQualifiedStaticField(qualifiedLeft, true);
  11255. thisValue = mResult;
  11256. mResult = BfTypedValue();
  11257. }
  11258. }
  11259. }
  11260. if (mPropDef != NULL)
  11261. thisValue = GetResult(true);
  11262. if (!thisValue.mType)
  11263. {
  11264. mModule->Fail("Identifier not found", qualifiedName->mLeft);
  11265. mModule->CheckTypeRefFixit(qualifiedName->mLeft);
  11266. mModule->CheckIdentifierFixit(qualifiedName->mLeft);
  11267. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11268. }
  11269. if (mResult)
  11270. CheckResultForReading(mResult);
  11271. mResult = BfTypedValue();
  11272. }
  11273. else if (auto identiferExpr = BfNodeDynCast<BfIdentifierNode>(target))
  11274. {
  11275. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  11276. {
  11277. if (attrIdentifier->mIdentifier != NULL)
  11278. methodNodeSrc = attrIdentifier->mIdentifier;
  11279. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  11280. }
  11281. allowImplicitThis = true;
  11282. if (autoComplete != NULL)
  11283. autoComplete->CheckIdentifier(identiferExpr);
  11284. targetFunctionName = target->ToString();
  11285. if (targetFunctionName == "PrintF") // Just directly call that one
  11286. {
  11287. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  11288. BfType* charPtrType = mModule->CreatePointerType(charType);
  11289. auto func = mModule->GetBuiltInFunc(BfBuiltInFuncType_PrintF);
  11290. SizedArray<BfIRValue, 4> irArgs;
  11291. for (BfExpression* arg : args)
  11292. {
  11293. BfTypedValue value;
  11294. if (arg != NULL)
  11295. value = mModule->CreateValueFromExpression(arg);
  11296. if (!value)
  11297. return;
  11298. auto typeInst = value.mType->ToTypeInstance();
  11299. if ((typeInst != NULL) && (typeInst->mTypeDef == mModule->mCompiler->mStringTypeDef))
  11300. value = mModule->Cast(arg, value, charPtrType);
  11301. if ((value.mType->IsFloat()) && (value.mType->mSize != 8)) // Always cast float to double
  11302. value = mModule->Cast(arg, value, mModule->GetPrimitiveType(BfTypeCode_Double));
  11303. irArgs.push_back(value.mValue);
  11304. }
  11305. if ((targetFunctionName != "PrintF") || (irArgs.size() > 0))
  11306. {
  11307. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCall(func, irArgs/*, targetFunctionName*/),
  11308. mModule->ResolveTypeDef(mModule->mSystem->mTypeInt32));
  11309. }
  11310. return;
  11311. }
  11312. }
  11313. else if (auto expr = BfNodeDynCast<BfExpression>(target))
  11314. {
  11315. auto innerInvocationResult = mModule->CreateValueFromExpression(expr);
  11316. if (!innerInvocationResult)
  11317. {
  11318. mModule->AssertErrorState();
  11319. innerInvocationResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11320. }
  11321. if (innerInvocationResult.mType->IsVar())
  11322. {
  11323. mResult = innerInvocationResult;
  11324. return;
  11325. }
  11326. targetFunctionName = "Invoke";
  11327. if (innerInvocationResult.mType->IsTypeInstance())
  11328. {
  11329. auto invocationTypeInst = innerInvocationResult.mType->ToTypeInstance();
  11330. if (invocationTypeInst->mTypeDef->mIsDelegate)
  11331. {
  11332. thisValue = innerInvocationResult;
  11333. }
  11334. }
  11335. if (!thisValue)
  11336. {
  11337. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(innerInvocationResult.mType).c_str()), expr);
  11338. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11339. }
  11340. }
  11341. else
  11342. {
  11343. mModule->Fail("Invalid invocation target", target);
  11344. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  11345. }
  11346. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  11347. {
  11348. autoComplete->mIsCapturingMethodMatchInfo = true;
  11349. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  11350. }
  11351. SetAndRestoreValue<BfAttributeState*> prevAttributeState;
  11352. if (attributeState.mCustomAttributes != NULL)
  11353. prevAttributeState.Init(mModule->mAttributeState, &attributeState);
  11354. if ((targetFunctionName != "") && (targetFunctionName[targetFunctionName.length() - 1] == '!'))
  11355. {
  11356. targetFunctionName = targetFunctionName.Substring(0, targetFunctionName.length() - 1);
  11357. InjectMixin(methodNodeSrc, thisValue, allowImplicitThis, targetFunctionName, args, methodGenericArguments);
  11358. return;
  11359. }
  11360. //TODO: We removed this... Messed up with PrimStruct 'this' non-mut errors
  11361. // 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
  11362. /*if (thisValue)
  11363. {
  11364. if ((!thisValue.mType->IsGenericParam()) && (!thisValue.IsSplat()) && (!thisValue.mType->IsVar()))
  11365. thisValue = MakeCallableTarget(target, thisValue);
  11366. }*/
  11367. int methodCount = 0;
  11368. bool mayBeSkipCall = false;
  11369. if (thisValue.mType != NULL)
  11370. {
  11371. auto checkTypeInst = thisValue.mType->ToTypeInstance();
  11372. while (checkTypeInst != NULL)
  11373. {
  11374. checkTypeInst->mTypeDef->PopulateMemberSets();
  11375. BfMemberSetEntry* memberSetEntry;
  11376. if (checkTypeInst->mTypeDef->mMethodSet.TryGetWith(targetFunctionName, &memberSetEntry))
  11377. {
  11378. BfMethodDef* methodDef = (BfMethodDef*)memberSetEntry->mMemberDef;
  11379. while (methodDef != NULL)
  11380. {
  11381. if (methodDef->mIsSkipCall)
  11382. mayBeSkipCall = true;
  11383. methodDef = methodDef->mNextWithSameName;
  11384. }
  11385. }
  11386. checkTypeInst = checkTypeInst->mBaseType;
  11387. }
  11388. }
  11389. SizedArray<BfExpression*, 8> copiedArgs;
  11390. for (BfExpression* arg : args)
  11391. copiedArgs.push_back(arg);
  11392. BfSizedArray<BfExpression*> sizedCopiedArgs(copiedArgs);
  11393. BfResolvedArgs argValues(&sizedCopiedArgs);
  11394. if (mModule->mParentNodeEntry != NULL)
  11395. {
  11396. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  11397. {
  11398. argValues.mOpenToken = invocationExpr->mOpenParen;
  11399. argValues.mCommas = &invocationExpr->mCommas;
  11400. argValues.mCloseToken = invocationExpr->mCloseParen;
  11401. }
  11402. }
  11403. BfResolveArgFlags resolveArgsFlags = (BfResolveArgFlags)(BfResolveArgFlag_DeferFixits | BfResolveArgFlag_AllowUnresolvedTypes);
  11404. resolveArgsFlags = (BfResolveArgFlags)(resolveArgsFlags | BfResolveArgFlag_DeferParamEval);
  11405. if (mayBeSkipCall)
  11406. resolveArgsFlags = (BfResolveArgFlags)(resolveArgsFlags | BfResolveArgFlag_DeferParamValues);
  11407. // static int sCallIdx = 0;
  11408. // sCallIdx++;
  11409. // int callIdx = sCallIdx;
  11410. // if (callIdx == 1557)
  11411. // {
  11412. // NOP;
  11413. // }
  11414. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  11415. if (attributeState.mCustomAttributes != NULL)
  11416. {
  11417. if (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  11418. checkedKind = BfCheckedKind_Checked;
  11419. if (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  11420. checkedKind = BfCheckedKind_Unchecked;
  11421. }
  11422. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, mUsedAsStatement || isCascade);
  11423. ResolveArgValues(argValues, resolveArgsFlags);
  11424. mResult = MatchMethod(methodNodeSrc, methodBoundExpr, thisValue, allowImplicitThis, bypassVirtual, targetFunctionName, argValues, methodGenericArguments, checkedKind);
  11425. argValues.HandleFixits(mModule);
  11426. if (isCascade)
  11427. {
  11428. if (outCascadeValue != NULL)
  11429. {
  11430. *outCascadeValue = thisValue;
  11431. }
  11432. else
  11433. {
  11434. mModule->Fail("Invalid use of cascade operator", cascadeOperatorToken);
  11435. }
  11436. }
  11437. }
  11438. void BfExprEvaluator::Visit(BfInvocationExpression* invocationExpr)
  11439. {
  11440. BfAutoParentNodeEntry autoParentNodeEntry(mModule, invocationExpr);
  11441. // We need to check for sized array constructor like "uint8[2](1, 2)"
  11442. if (BfNodeDynCastExact<BfIndexerExpression>(invocationExpr->mTarget) != NULL)
  11443. {
  11444. auto checkTarget = invocationExpr->mTarget;
  11445. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  11446. {
  11447. checkTarget = indexerExpr->mTarget;
  11448. }
  11449. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  11450. auto resolvedType = mModule->ResolveTypeRef(checkTarget, NULL, BfPopulateType_Identity);
  11451. prevIgnoreError.Restore();
  11452. if (resolvedType != NULL)
  11453. {
  11454. BfType* curType = resolvedType;
  11455. auto checkTarget = invocationExpr->mTarget;
  11456. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  11457. {
  11458. checkTarget = indexerExpr->mTarget;
  11459. if (indexerExpr->mCommas.size() != 0)
  11460. 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]);
  11461. int arrSize = 0;
  11462. if (indexerExpr->mArguments.size() != 0)
  11463. {
  11464. BfConstResolver constResolver(mModule);
  11465. auto arg = indexerExpr->mArguments[0];
  11466. if (arg != NULL)
  11467. constResolver.Resolve(arg);
  11468. if (constResolver.mResult.mValue.IsConst())
  11469. {
  11470. auto constant = mModule->mBfIRBuilder->GetConstant(constResolver.mResult.mValue);
  11471. if ((mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 >= 0))
  11472. {
  11473. arrSize = constant->mInt32;
  11474. }
  11475. else
  11476. mModule->Fail("Non-negative integer expected", indexerExpr->mArguments[0]);
  11477. }
  11478. }
  11479. else
  11480. arrSize = invocationExpr->mArguments.size();
  11481. curType = mModule->CreateSizedArrayType(curType, arrSize);
  11482. }
  11483. InitializedSizedArray((BfSizedArrayType*)curType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen, NULL);
  11484. return;
  11485. }
  11486. }
  11487. auto autoComplete = GetAutoComplete();
  11488. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  11489. if (autoComplete != NULL)
  11490. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  11491. mModule->UpdateExprSrcPos(invocationExpr);
  11492. BfSizedArray<ASTREF(BfTypeReference*)>* methodGenericArguments = NULL;
  11493. if (invocationExpr->mGenericArgs != NULL)
  11494. methodGenericArguments = &invocationExpr->mGenericArgs->mGenericArgs;
  11495. SizedArray<BfExpression*, 8> copiedArgs;
  11496. for (BfExpression* arg : invocationExpr->mArguments)
  11497. copiedArgs.push_back(arg);
  11498. BfTypedValue cascadeValue;
  11499. DoInvocation(invocationExpr->mTarget, invocationExpr, copiedArgs, methodGenericArguments, &cascadeValue);
  11500. if (autoComplete != NULL)
  11501. {
  11502. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  11503. {
  11504. if (autoComplete->mMethodMatchInfo != NULL)
  11505. autoComplete->mIsCapturingMethodMatchInfo = true;
  11506. else
  11507. autoComplete->mIsCapturingMethodMatchInfo = false;
  11508. //BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  11509. }
  11510. else
  11511. autoComplete->mIsCapturingMethodMatchInfo = false;
  11512. }
  11513. /// Previous check for discard
  11514. if (cascadeValue)
  11515. mResult = cascadeValue;
  11516. }
  11517. BfMethodDef* BfExprEvaluator::GetPropertyMethodDef(BfPropertyDef* propDef, BfMethodType methodType, BfCheckedKind checkedKind)
  11518. {
  11519. BfMethodDef* matchedMethod = NULL;
  11520. BfMethodDef* backupMethod = NULL;
  11521. for (auto methodDef : propDef->mMethods)
  11522. {
  11523. if (methodDef->mMethodType != methodType)
  11524. continue;
  11525. if (methodDef->mCheckedKind == checkedKind)
  11526. {
  11527. matchedMethod = methodDef;
  11528. break;
  11529. }
  11530. if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  11531. matchedMethod = methodDef;
  11532. else
  11533. backupMethod = methodDef;
  11534. }
  11535. if (matchedMethod == NULL)
  11536. matchedMethod = backupMethod;
  11537. return matchedMethod;
  11538. }
  11539. BfModuleMethodInstance BfExprEvaluator::GetPropertyMethodInstance(BfMethodDef* methodDef)
  11540. {
  11541. if (mPropDefBypassVirtual)
  11542. {
  11543. if (mPropTarget.mType->IsInterface())
  11544. {
  11545. auto curTypeInst = mPropTarget.mType->ToTypeInstance();
  11546. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  11547. {
  11548. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  11549. mPropTarget = mModule->GetThis();
  11550. return mModule->GetMethodInstance(mModule->mCurTypeInstance, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_ForeignMethodDef, curTypeInst);
  11551. }
  11552. else
  11553. {
  11554. mModule->Fail("Property is not implemented by this type", mPropSrc);
  11555. return BfModuleMethodInstance();
  11556. }
  11557. }
  11558. else
  11559. {
  11560. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  11561. auto rawMethodInstance = mModule->GetRawMethodInstance(propTypeInst, methodDef);
  11562. auto useTypeInst = mOrigPropTarget.mType->ToTypeInstance();
  11563. auto virtualMethod = (BfMethodInstance*)useTypeInst->mVirtualMethodTable[rawMethodInstance->mVirtualTableIdx].mImplementingMethod;
  11564. return mModule->ReferenceExternalMethodInstance(virtualMethod);
  11565. }
  11566. }
  11567. if ((mOrigPropTarget) && (mOrigPropTarget.mType != mPropTarget.mType) &&
  11568. ((!mOrigPropTarget.mType->IsGenericParam()) && (mPropTarget.mType->IsInterface())))
  11569. {
  11570. auto checkType = mOrigPropTarget.mType;
  11571. if (checkType->IsPointer())
  11572. checkType = ((BfPointerType*)checkType)->mElementType;
  11573. if (checkType->IsWrappableType())
  11574. checkType = mModule->GetWrappedStructType(checkType);
  11575. if ((checkType != NULL) && (checkType->IsTypeInstance()))
  11576. {
  11577. auto activeTypeDef = mModule->GetActiveTypeDef();
  11578. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  11579. bool checkedUnderlying = false;
  11580. auto checkTypeInst = checkType->ToTypeInstance();
  11581. while (checkTypeInst != NULL)
  11582. {
  11583. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  11584. for (auto& iface : checkTypeInst->mInterfaces)
  11585. {
  11586. if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  11587. continue;
  11588. if (iface.mInterfaceType == mPropTarget.mType)
  11589. {
  11590. if (bestIFaceEntry == NULL)
  11591. {
  11592. bestIFaceEntry = &iface;
  11593. continue;
  11594. }
  11595. bool isBetter;
  11596. bool isWorse;
  11597. mModule->CompareDeclTypes(iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  11598. if (isBetter == isWorse)
  11599. {
  11600. // Failed
  11601. }
  11602. else
  11603. {
  11604. if (isBetter)
  11605. bestIFaceEntry = &iface;
  11606. }
  11607. }
  11608. }
  11609. if (bestIFaceEntry != NULL)
  11610. break;
  11611. checkTypeInst = checkTypeInst->mBaseType;
  11612. if (checkTypeInst == NULL)
  11613. {
  11614. if (!checkedUnderlying)
  11615. {
  11616. checkedUnderlying = true;
  11617. if (checkType->HasWrappedRepresentation())
  11618. {
  11619. auto underlyingType = checkType->GetUnderlyingType();
  11620. if (underlyingType != NULL)
  11621. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  11622. }
  11623. }
  11624. }
  11625. }
  11626. if (bestIFaceEntry != NULL)
  11627. {
  11628. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + methodDef->mIdx];
  11629. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  11630. if (bestMethodInstance != NULL)
  11631. {
  11632. mPropTarget = mOrigPropTarget;
  11633. mPropTarget.mType = checkTypeInst;
  11634. return mModule->GetMethodInstanceAtIdx(ifaceMethodEntry.mMethodRef.mTypeInstance, ifaceMethodEntry.mMethodRef.mMethodNum);
  11635. }
  11636. }
  11637. }
  11638. mModule->AssertErrorState();
  11639. return BfModuleMethodInstance();
  11640. }
  11641. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  11642. if (propTypeInst == NULL)
  11643. {
  11644. propTypeInst = mModule->GetWrappedStructType(mPropTarget.mType);
  11645. }
  11646. if (propTypeInst == NULL)
  11647. {
  11648. mModule->Fail("INTERNAL ERROR: Invalid property target", mPropSrc);
  11649. return BfModuleMethodInstance();
  11650. }
  11651. return mModule->GetMethodInstance(propTypeInst, methodDef, BfTypeVector(), mPropGetMethodFlags);
  11652. }
  11653. void BfExprEvaluator::CheckPropFail(BfMethodDef* propMethodDef, BfMethodInstance* methodInstance)
  11654. {
  11655. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  11656. // If mExplicitInterface is null then we are implicitly calling through an interface
  11657. if ((propTypeInst != NULL) && (methodInstance->GetExplicitInterface() == NULL) && (!mModule->CheckAccessMemberProtection(propMethodDef->mProtection, propTypeInst)))
  11658. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(methodInstance).c_str()), mPropSrc);
  11659. else if (mPropCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  11660. {
  11661. bool passes = true;
  11662. if (mPropCheckedKind != BfCheckedKind_NotSet)
  11663. {
  11664. passes = false;
  11665. }
  11666. else
  11667. {
  11668. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  11669. if (defaultCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  11670. passes = false;
  11671. }
  11672. if (!passes)
  11673. {
  11674. 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);
  11675. if (error != NULL)
  11676. {
  11677. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  11678. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  11679. }
  11680. }
  11681. }
  11682. }
  11683. BfTypedValue BfExprEvaluator::GetResult(bool clearResult, bool resolveGenericType)
  11684. {
  11685. if ((!mResult) && (mPropDef != NULL))
  11686. {
  11687. BfMethodDef* matchedMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind);
  11688. if (matchedMethod == NULL)
  11689. {
  11690. mModule->Fail("Property has no getter", mPropSrc);
  11691. return mResult;
  11692. }
  11693. auto methodInstance = GetPropertyMethodInstance(matchedMethod);
  11694. if (methodInstance.mMethodInstance == NULL)
  11695. return mResult;
  11696. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  11697. {
  11698. BF_ASSERT(!methodInstance.mFunc.IsFake());
  11699. }
  11700. if (mPropSrc != NULL)
  11701. mModule->UpdateExprSrcPos(mPropSrc);
  11702. CheckPropFail(matchedMethod, methodInstance.mMethodInstance);
  11703. PerformCallChecks(methodInstance.mMethodInstance, mPropSrc);
  11704. if (methodInstance.mMethodInstance->IsSkipCall())
  11705. {
  11706. mResult = mModule->GetDefaultTypedValue(methodInstance.mMethodInstance->mReturnType);
  11707. }
  11708. else
  11709. {
  11710. SizedArray<BfIRValue, 4> args;
  11711. if (!matchedMethod->mIsStatic)
  11712. {
  11713. if ((mPropDefBypassVirtual) && (mPropTarget.mType != methodInstance.mMethodInstance->GetOwner()))
  11714. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, methodInstance.mMethodInstance->GetOwner());
  11715. mModule->EmitObjectAccessCheck(mPropTarget);
  11716. PushThis(mPropSrc, mPropTarget, methodInstance.mMethodInstance, args);
  11717. }
  11718. bool failed = false;
  11719. for (int paramIdx = 0; paramIdx < (int)mIndexerValues.size(); paramIdx++)
  11720. {
  11721. auto val = mModule->Cast(mPropSrc, mIndexerValues[paramIdx].mTypedValue, methodInstance.mMethodInstance->GetParamType(paramIdx));
  11722. if (!val)
  11723. failed = true;
  11724. else
  11725. PushArg(val, args);
  11726. }
  11727. if (mPropDefBypassVirtual)
  11728. {
  11729. auto methodDef = methodInstance.mMethodInstance->mMethodDef;
  11730. if ((methodDef->mIsAbstract) && (mPropDefBypassVirtual))
  11731. {
  11732. mModule->Fail(StrFormat("Abstract base property method '%s' cannot be invoked", mModule->MethodToString(methodInstance.mMethodInstance).c_str()), mPropSrc);
  11733. }
  11734. }
  11735. if (failed)
  11736. mResult = mModule->GetDefaultTypedValue(methodInstance.mMethodInstance->mReturnType);
  11737. else
  11738. mResult = CreateCall(methodInstance.mMethodInstance, methodInstance.mFunc, mPropDefBypassVirtual, args);
  11739. if (mResult.mType != NULL)
  11740. {
  11741. if ((mResult.mType->IsVar()) && (mModule->mCompiler->mIsResolveOnly))
  11742. mModule->Fail("Property type reference failed to resolve", mPropSrc);
  11743. BF_ASSERT(!mResult.mType->IsRef());
  11744. }
  11745. }
  11746. mPropDef = NULL;
  11747. mPropDefBypassVirtual = false;
  11748. mIndexerValues.clear();
  11749. mResultLocalVar = NULL;
  11750. }
  11751. if (resolveGenericType)
  11752. ResolveGenericType();
  11753. BfTypedValue result = mResult;
  11754. if (clearResult)
  11755. mResult = BfTypedValue();
  11756. return result;
  11757. }
  11758. void BfExprEvaluator::CheckResultForReading(BfTypedValue& typedValue)
  11759. {
  11760. if (mModule->mCurMethodState == NULL)
  11761. return;
  11762. if ((mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCurMethodState->mAllowUinitReads))
  11763. return;
  11764. if ((mModule->mCurTypeInstance->mResolvingVarField) || (mModule->mCurTypeInstance->mResolvingConstField))
  11765. return;
  11766. if ((typedValue) && (typedValue.IsAddr()))
  11767. {
  11768. if ((mResultLocalVar != NULL) && (mResultLocalVarRefNode != NULL))
  11769. {
  11770. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors);
  11771. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  11772. {
  11773. // These errors can only be detected during capture time, so we don't ignore them on this pass
  11774. mModule->mIgnoreErrors = false;
  11775. }
  11776. int fieldIdx = mResultLocalVarField - 1;
  11777. auto localVar = mResultLocalVar;
  11778. if (localVar->mCompositeCount > 0)
  11779. {
  11780. mModule->Fail(StrFormat("Cannot read from composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  11781. typedValue = BfTypedValue();
  11782. return;
  11783. }
  11784. if (!localVar->mIsAssigned)
  11785. {
  11786. mModule->TryLocalVariableInit(localVar);
  11787. }
  11788. if (!localVar->mIsAssigned)
  11789. {
  11790. auto methodStateForLocal = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  11791. bool isAssigned = false;
  11792. int64 undefinedFieldFlags = localVar->mUnassignedFieldFlags;
  11793. auto deferredLocalAssignData = methodStateForLocal->mDeferredLocalAssignData;
  11794. while ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mIsChained))
  11795. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  11796. if (deferredLocalAssignData != NULL)
  11797. {
  11798. for (auto& assignedVar : deferredLocalAssignData->mAssignedLocals)
  11799. {
  11800. auto assignedLocal = assignedVar.mLocalVar;
  11801. if (assignedLocal == localVar)
  11802. {
  11803. int assignedFieldIdx = (assignedVar.mLocalVarField) - 1;
  11804. if (assignedFieldIdx >= 0)
  11805. undefinedFieldFlags &= ~((int64)1 << assignedFieldIdx);
  11806. else
  11807. undefinedFieldFlags = 0;
  11808. }
  11809. }
  11810. }
  11811. if (fieldIdx == -1)
  11812. {
  11813. if (undefinedFieldFlags == 0)
  11814. isAssigned = true;
  11815. }
  11816. else
  11817. {
  11818. isAssigned = true;
  11819. for (int i = 0; i < mResultLocalVarFieldCount; i++)
  11820. if ((undefinedFieldFlags & (1LL << (fieldIdx + i))) != 0)
  11821. isAssigned = false;
  11822. }
  11823. if (!isAssigned)
  11824. {
  11825. if ((localVar->mIsThis) && (fieldIdx != -1))
  11826. {
  11827. // When we have initializers for fields, they won't all be processed in the autocomplte case
  11828. if (!mModule->mCompiler->IsAutocomplete())
  11829. {
  11830. auto bfError = mModule->Fail(StrFormat("Use of possibly unassigned field '%s'", mResultLocalVarRefNode->ToString().c_str()), mResultLocalVarRefNode, true);
  11831. }
  11832. }
  11833. else
  11834. {
  11835. mModule->Fail(StrFormat("Use of unassigned local variable '%s'", localVar->mName.c_str()), mResultLocalVarRefNode);
  11836. }
  11837. }
  11838. }
  11839. localVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  11840. }
  11841. }
  11842. }
  11843. void BfExprEvaluator::FinishExpressionResult()
  11844. {
  11845. CheckResultForReading(mResult);
  11846. mResultLocalVar = NULL;
  11847. }
  11848. bool BfExprEvaluator::CheckAllowValue(const BfTypedValue& typedValue, BfAstNode* refNode)
  11849. {
  11850. return true;
  11851. }
  11852. void BfExprEvaluator::MarkResultUsed()
  11853. {
  11854. if (mResultLocalVar != NULL)
  11855. {
  11856. mResultLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  11857. }
  11858. }
  11859. void BfExprEvaluator::MarkResultAssigned()
  11860. {
  11861. if (mResultLocalVar != NULL)
  11862. {
  11863. //int localIdx = mResultLocalVarIdx;
  11864. //if (localIdx == 0x7FFF)
  11865. //return;
  11866. auto localVar = mResultLocalVar;
  11867. int fieldIdx = mResultLocalVarField - 1;
  11868. int count = mResultLocalVarFieldCount;
  11869. if (fieldIdx == -1)
  11870. count = 1;
  11871. for (int i = 0; i < count; i++)
  11872. mModule->mCurMethodState->GetMethodStateForLocal(localVar)->LocalDefined(localVar, fieldIdx + i);
  11873. //if (localIdx != 0x7FFF)
  11874. {
  11875. if (localVar->mCompositeCount > 0)
  11876. {
  11877. mModule->Fail(StrFormat("Cannot write to composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  11878. }
  11879. }
  11880. }
  11881. }
  11882. void BfExprEvaluator::MakeResultAsValue()
  11883. {
  11884. // Expressions like parens will turn a variable reference into a simple value
  11885. mResultLocalVar = NULL;
  11886. }
  11887. bool BfExprEvaluator::CheckModifyResult(BfTypedValue typedVal, BfAstNode* refNode, const char* modifyType, bool onlyNeedsMut)
  11888. {
  11889. BfLocalVariable* localVar = NULL;
  11890. bool isCapturedLocal = false;
  11891. if (mResultLocalVar != NULL)
  11892. {
  11893. localVar = mResultLocalVar;
  11894. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  11895. }
  11896. else if (typedVal.IsThis())
  11897. {
  11898. localVar = mModule->GetThisVariable();
  11899. }
  11900. else if (typedVal.IsSplat())
  11901. {
  11902. for (auto checkLocal : mModule->mCurMethodState->mLocals)
  11903. {
  11904. if (checkLocal->mAddr == typedVal.mValue)
  11905. {
  11906. localVar = checkLocal;
  11907. break;
  11908. }
  11909. }
  11910. }
  11911. else if (typedVal.mValue.IsArg())
  11912. {
  11913. auto methodState = mModule->mCurMethodState->GetNonCaptureState();
  11914. localVar = methodState->mLocals[typedVal.mValue.mId];
  11915. }
  11916. if ((typedVal.mKind == BfTypedValueKind_MutableValue) && (onlyNeedsMut))
  11917. {
  11918. return true;
  11919. }
  11920. if (localVar != NULL)
  11921. {
  11922. if (((!typedVal.IsAddr()) && (!typedVal.mType->IsValuelessType())) ||
  11923. (typedVal.IsReadOnly()))
  11924. {
  11925. BfError* error = NULL;
  11926. if (localVar->mIsThis)
  11927. {
  11928. bool isClosure = false;
  11929. BfTypeInstance* checkTypeInst = localVar->mResolvedType->ToTypeInstance();
  11930. int fieldIdx = mResultLocalVarField - 1;
  11931. if ((!isCapturedLocal) && (mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mClosureType != NULL))
  11932. {
  11933. isClosure = true;
  11934. auto closureThis = mModule->mCurMethodState->mClosureState->mClosureType;
  11935. closureThis = checkTypeInst->mFieldInstances[0].mResolvedType->ToTypeInstance();
  11936. if (fieldIdx >= -1)
  11937. {
  11938. checkTypeInst = closureThis;
  11939. }
  11940. else
  11941. {
  11942. fieldIdx = -fieldIdx - 2;
  11943. isCapturedLocal = true;
  11944. }
  11945. }
  11946. if (fieldIdx < 0)
  11947. {
  11948. if (isClosure)
  11949. {
  11950. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  11951. error = mModule->Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType), refNode);
  11952. else
  11953. error = mModule->Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType), refNode);
  11954. }
  11955. else
  11956. {
  11957. error = mModule->Fail(StrFormat("Cannot %s 'this' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  11958. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  11959. }
  11960. return false;
  11961. }
  11962. else
  11963. {
  11964. while (checkTypeInst != NULL)
  11965. {
  11966. for (auto& checkFieldInstance : checkTypeInst->mFieldInstances)
  11967. {
  11968. if (checkFieldInstance.mMergedDataIdx == fieldIdx)
  11969. {
  11970. if (isCapturedLocal)
  11971. {
  11972. error = mModule->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,
  11973. checkFieldInstance.GetFieldDef()->mName.c_str()), refNode);
  11974. }
  11975. else if (isClosure)
  11976. {
  11977. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  11978. error = mModule->Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType,
  11979. mModule->TypeToString(checkFieldInstance.mOwner).c_str(), checkFieldInstance.GetFieldDef()->mName.c_str()), refNode);
  11980. else
  11981. error = mModule->Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType,
  11982. mModule->TypeToString(checkFieldInstance.mOwner).c_str(), checkFieldInstance.GetFieldDef()->mName.c_str()), refNode);
  11983. }
  11984. else
  11985. {
  11986. error = mModule->Fail(StrFormat("Cannot %s field '%s.%s' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  11987. mModule->TypeToString(checkFieldInstance.mOwner).c_str(), checkFieldInstance.GetFieldDef()->mName.c_str(),
  11988. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  11989. }
  11990. return false;
  11991. }
  11992. }
  11993. checkTypeInst = checkTypeInst->mBaseType;
  11994. }
  11995. }
  11996. }
  11997. else if (localVar->IsParam())
  11998. {
  11999. if (!mModule->mCurMethodInstance->IsMixin())
  12000. {
  12001. if ((localVar->mResolvedType->IsGenericParam()) && (onlyNeedsMut))
  12002. error = mModule->Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'mut' or 'ref' specifier to parameter or copying to a local variable.", modifyType,
  12003. localVar->mName.c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  12004. else
  12005. error = mModule->Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'ref' specifier to parameter or copying to a local variable.", modifyType,
  12006. localVar->mName.c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  12007. return false;
  12008. }
  12009. }
  12010. else
  12011. {
  12012. error = mModule->Fail(StrFormat("Cannot %s read-only local variable '%s'.", modifyType,
  12013. localVar->mName.c_str()), refNode);
  12014. return false;
  12015. }
  12016. }
  12017. else
  12018. {
  12019. // When we are capturing, we need to note that we require capturing by reference here
  12020. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  12021. }
  12022. }
  12023. return mModule->CheckModifyValue(typedVal, refNode, modifyType);
  12024. }
  12025. void BfExprEvaluator::Visit(BfConditionalExpression* condExpr)
  12026. {
  12027. static int sCallCount = 0;
  12028. sCallCount++;
  12029. auto condResult = mModule->CreateValueFromExpression(condExpr->mConditionExpression, mModule->GetPrimitiveType(BfTypeCode_Boolean));
  12030. if (!condResult)
  12031. return;
  12032. if (condExpr->mTrueExpression == NULL)
  12033. {
  12034. mModule->AssertErrorState();
  12035. return;
  12036. }
  12037. if (condExpr->mFalseExpression == NULL)
  12038. {
  12039. mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, BfEvalExprFlags_NoCast);
  12040. mModule->AssertErrorState();
  12041. return;
  12042. }
  12043. bool isConstBranch = false;
  12044. bool constResult = false;
  12045. bool constResultUndef = false;
  12046. if (condResult.mValue.IsConst())
  12047. {
  12048. auto constValue = mModule->mBfIRBuilder->GetConstant(condResult.mValue);
  12049. if (constValue->mTypeCode == BfTypeCode_Boolean)
  12050. {
  12051. isConstBranch = true;
  12052. constResult = constValue->mBool;
  12053. }
  12054. else if (constValue->mConstType == BfConstType_Undef)
  12055. {
  12056. isConstBranch = true;
  12057. constResultUndef = true;
  12058. }
  12059. }
  12060. if (isConstBranch)
  12061. {
  12062. BfExpression* actualExpr = (constResult) ? condExpr->mTrueExpression : condExpr->mFalseExpression;
  12063. BfExpression* ignoredExpr = (constResult) ? condExpr->mFalseExpression : condExpr->mTrueExpression;
  12064. BfTypedValue actualValue = mModule->CreateValueFromExpression(actualExpr, mExpectingType, BfEvalExprFlags_NoCast);
  12065. BfTypedValue ignoredValue;
  12066. //
  12067. {
  12068. auto curBlock = mModule->mBfIRBuilder->GetInsertBlock();
  12069. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  12070. ignoredValue = mModule->CreateValueFromExpression(ignoredExpr, mExpectingType, BfEvalExprFlags_NoCast);
  12071. mModule->mBfIRBuilder->SetInsertPoint(curBlock);
  12072. }
  12073. if (!actualValue)
  12074. return;
  12075. if ((ignoredValue) && (ignoredValue.mType != actualValue.mType))
  12076. {
  12077. // Cast to more specific 'ignored' type if applicable
  12078. if (mModule->CanImplicitlyCast(actualValue, ignoredValue.mType))
  12079. {
  12080. actualValue = mModule->Cast(actualExpr, actualValue, ignoredValue.mType);
  12081. }
  12082. else if (!mModule->CanImplicitlyCast(ignoredValue, actualValue.mType))
  12083. {
  12084. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  12085. mModule->TypeToString(actualValue.mType).c_str(), mModule->TypeToString(ignoredValue.mType).c_str()), condExpr);
  12086. }
  12087. }
  12088. mResult = actualValue;
  12089. if (constResultUndef)
  12090. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Undef);
  12091. return;
  12092. }
  12093. auto trueBB = mModule->mBfIRBuilder->CreateBlock("cond.then");
  12094. auto falseBB = mModule->mBfIRBuilder->CreateBlock("cond.else");
  12095. auto endBB = mModule->mBfIRBuilder->CreateBlock("cond.end");
  12096. auto contBB = mModule->mBfIRBuilder->CreateBlock("cond.cont");
  12097. mModule->mBfIRBuilder->CreateCondBr(condResult.mValue, trueBB, falseBB);
  12098. mModule->AddBasicBlock(trueBB);
  12099. auto trueValue = mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  12100. if ((mExpectingType != NULL) && (trueValue) && (trueValue.mType != mExpectingType))
  12101. {
  12102. // In some cases like typed primitives - we CAN individually cast each value which it's a constant still, but not after the merging
  12103. // IE: Color c = isOver ? 0xFF000000 : 0xFFFFFFFF;
  12104. // Otherwise the resulting value would just be 'int' which cannot implicitly convert to Color, but each of those ints can be
  12105. // a uint32 if converted separately
  12106. auto checkTrueValue = mModule->Cast(condExpr->mTrueExpression, trueValue, mExpectingType, BfCastFlags_SilentFail);
  12107. if (checkTrueValue)
  12108. trueValue = checkTrueValue;
  12109. }
  12110. auto trueBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  12111. mModule->AddBasicBlock(falseBB);
  12112. auto falseValue = mModule->CreateValueFromExpression(condExpr->mFalseExpression, mExpectingType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  12113. auto falseBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  12114. if ((mExpectingType != NULL) && (falseValue) && (falseValue.mType != mExpectingType))
  12115. {
  12116. auto checkFalseValue = mModule->Cast(condExpr->mFalseExpression, falseValue, mExpectingType, BfCastFlags_SilentFail);
  12117. if (checkFalseValue)
  12118. falseValue = checkFalseValue;
  12119. }
  12120. bool isValid = trueValue && falseValue;
  12121. if (isValid)
  12122. {
  12123. BfTypedValue falseToTrue;
  12124. {
  12125. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  12126. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  12127. falseToTrue = mModule->Cast(condExpr->mFalseExpression, falseValue, trueValue.mType);
  12128. }
  12129. if (falseToTrue)
  12130. {
  12131. falseValue = falseToTrue;
  12132. }
  12133. else
  12134. {
  12135. BfTypedValue trueToFalse;
  12136. {
  12137. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  12138. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  12139. trueToFalse = mModule->Cast(condExpr->mTrueExpression, trueValue, falseValue.mType);
  12140. }
  12141. if (!trueToFalse)
  12142. {
  12143. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  12144. mModule->TypeToString(trueValue.mType).c_str(), mModule->TypeToString(falseValue.mType).c_str()), condExpr);
  12145. //return;
  12146. isValid = false;
  12147. }
  12148. else
  12149. trueValue = trueToFalse;
  12150. }
  12151. }
  12152. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  12153. if (isValid)
  12154. trueValue = mModule->LoadValue(trueValue);
  12155. mModule->mBfIRBuilder->CreateBr(endBB);
  12156. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  12157. if (isValid)
  12158. falseValue = mModule->LoadValue(falseValue);
  12159. mModule->mBfIRBuilder->CreateBr(endBB);
  12160. mModule->AddBasicBlock(endBB, false);
  12161. if (!isValid)
  12162. return;
  12163. mModule->mBfIRBuilder->SetInsertPoint(endBB);
  12164. BfIRValue phi;
  12165. if (!trueValue.mType->IsValuelessType())
  12166. {
  12167. phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(trueValue.mType), 2);
  12168. mModule->mBfIRBuilder->AddPhiIncoming(phi, trueValue.mValue, trueBlockPos);
  12169. mModule->mBfIRBuilder->AddPhiIncoming(phi, falseValue.mValue, falseBlockPos);
  12170. }
  12171. mModule->mBfIRBuilder->CreateBr(contBB);
  12172. mModule->AddBasicBlock(contBB);
  12173. mResult = BfTypedValue(phi, trueValue.mType);
  12174. }
  12175. void BfExprEvaluator::PopulateDeferrredTupleAssignData(BfTupleExpression* tupleExpr, DeferredTupleAssignData& deferredTupleAssignData)
  12176. {
  12177. BfTypeVector fieldTypes;
  12178. Array<String> fieldNames;
  12179. // We need to evaluate each LHS tuple component in a separate BfExprEvaluator because each one
  12180. // could be a property and the 'mPropDef' target info is tied to a single evaluator
  12181. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  12182. {
  12183. DeferredTupleAssignData::Entry entry;
  12184. entry.mExprEvaluator = NULL;
  12185. entry.mInnerTuple = NULL;
  12186. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  12187. entry.mExpr = valueExpr;
  12188. BfType* fieldType = NULL;
  12189. BfType* resultType = NULL;
  12190. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(valueExpr))
  12191. {
  12192. entry.mInnerTuple = new DeferredTupleAssignData();
  12193. PopulateDeferrredTupleAssignData(innerTupleExpr, *entry.mInnerTuple);
  12194. resultType = entry.mInnerTuple->mTupleType;
  12195. }
  12196. else
  12197. {
  12198. BfExprEvaluator* exprEvaluator = new BfExprEvaluator(mModule);
  12199. entry.mExprEvaluator = exprEvaluator;
  12200. if (valueExpr->IsA<BfUninitializedExpression>())
  12201. {
  12202. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  12203. }
  12204. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(valueExpr))
  12205. {
  12206. if ((varDecl->mTypeRef->IsA<BfLetTypeReference>()) || (varDecl->mTypeRef->IsA<BfVarTypeReference>()))
  12207. {
  12208. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  12209. }
  12210. else
  12211. {
  12212. resultType = ResolveTypeRef(varDecl->mTypeRef);
  12213. if (resultType == NULL)
  12214. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  12215. }
  12216. }
  12217. if (resultType == NULL)
  12218. {
  12219. exprEvaluator->VisitChild(valueExpr);
  12220. if ((!exprEvaluator->mResult) && (exprEvaluator->mPropDef == NULL))
  12221. exprEvaluator->mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  12222. resultType = exprEvaluator->mResult.mType;
  12223. }
  12224. if ((resultType == NULL) && (exprEvaluator->mPropDef != NULL) && (exprEvaluator->mPropTarget.mType != NULL))
  12225. {
  12226. auto propTypeInst = exprEvaluator->mPropTarget.mType->ToTypeInstance();
  12227. if ((propTypeInst == NULL) && (exprEvaluator->mPropTarget.mType->IsPointer()))
  12228. {
  12229. BfPointerType* pointerType = (BfPointerType*)exprEvaluator->mPropTarget.mType;
  12230. propTypeInst = pointerType->mElementType->ToTypeInstance();
  12231. }
  12232. auto setMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertySetter, mPropCheckedKind);
  12233. if (setMethod != NULL)
  12234. {
  12235. auto methodInstance = mModule->GetMethodInstance(propTypeInst, setMethod, BfTypeVector());
  12236. resultType = methodInstance.mMethodInstance->GetParamType(0);
  12237. }
  12238. else
  12239. {
  12240. auto getMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind);
  12241. if (getMethod != NULL)
  12242. {
  12243. auto methodInstance = mModule->GetMethodInstance(propTypeInst, getMethod, BfTypeVector());
  12244. auto retType = methodInstance.mMethodInstance->mReturnType;
  12245. if (retType->IsRef())
  12246. resultType = retType->GetUnderlyingType();
  12247. }
  12248. }
  12249. }
  12250. }
  12251. if (resultType == NULL)
  12252. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  12253. deferredTupleAssignData.mChildren.push_back(entry);
  12254. fieldTypes.push_back(resultType);
  12255. }
  12256. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  12257. {
  12258. if (requestedName == NULL)
  12259. fieldNames.push_back("");
  12260. else
  12261. fieldNames.push_back(requestedName->mNameNode->ToString());
  12262. }
  12263. BfTupleType* tupleType = mModule->CreateTupleType(fieldTypes, fieldNames);
  12264. deferredTupleAssignData.mTupleType = tupleType;
  12265. }
  12266. void BfExprEvaluator::AssignDeferrredTupleAssignData(BfAssignmentExpression* assignExpr, DeferredTupleAssignData& deferredTupleAssignData, BfTypedValue rightValue)
  12267. {
  12268. BF_ASSERT(rightValue.mType->IsTuple());
  12269. auto tupleType = (BfTupleType*)rightValue.mType;
  12270. for (int valueIdx = 0; valueIdx < (int)deferredTupleAssignData.mChildren.size(); valueIdx++)
  12271. {
  12272. auto& child = deferredTupleAssignData.mChildren[valueIdx];
  12273. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[valueIdx];
  12274. BfTypedValue elementValue;
  12275. if (fieldInstance->mDataIdx >= 0)
  12276. {
  12277. auto extractedValue = mModule->mBfIRBuilder->CreateExtractValue(rightValue.mValue, fieldInstance->mDataIdx);
  12278. elementValue = BfTypedValue(extractedValue, fieldInstance->GetResolvedType());
  12279. if (child.mInnerTuple != NULL)
  12280. {
  12281. AssignDeferrredTupleAssignData(assignExpr, *child.mInnerTuple, elementValue);
  12282. delete child.mInnerTuple;
  12283. }
  12284. else
  12285. {
  12286. child.mExprEvaluator->PerformAssignment(assignExpr, true, elementValue);
  12287. }
  12288. }
  12289. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(child.mExpr))
  12290. {
  12291. if (!elementValue)
  12292. elementValue = mModule->GetDefaultTypedValue(fieldInstance->GetResolvedType());
  12293. mModule->HandleVariableDeclaration(varDecl, elementValue);
  12294. }
  12295. }
  12296. }
  12297. void BfExprEvaluator::DoTupleAssignment(BfAssignmentExpression* assignExpr)
  12298. {
  12299. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(assignExpr->mLeft);
  12300. DeferredTupleAssignData deferredTupleAssignData;
  12301. PopulateDeferrredTupleAssignData(tupleExpr, deferredTupleAssignData);
  12302. BfTupleType* tupleType = deferredTupleAssignData.mTupleType;
  12303. BfTypedValue rightValue;
  12304. if (assignExpr->mRight != NULL)
  12305. {
  12306. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, tupleType);
  12307. }
  12308. if (!rightValue)
  12309. {
  12310. tupleType = mModule->SantizeTupleType(tupleType);
  12311. rightValue = mModule->GetDefaultTypedValue(tupleType);
  12312. }
  12313. rightValue = mModule->LoadValue(rightValue);
  12314. AssignDeferrredTupleAssignData(assignExpr, deferredTupleAssignData, rightValue);
  12315. mResult = rightValue;
  12316. }
  12317. void BfExprEvaluator::PerformAssignment(BfAssignmentExpression* assignExpr, bool evaluatedLeft, BfTypedValue rightValue, BfTypedValue* outCascadeValue)
  12318. {
  12319. auto binaryOp = BfAssignOpToBinaryOp(assignExpr->mOp);
  12320. BfExpression* targetNode = assignExpr->mLeft;
  12321. if ((BfNodeIsA<BfMixinExpression>(targetNode)) && (!mModule->mCurMethodInstance->mIsUnspecialized))
  12322. {
  12323. // If we have a "mixin = <X>" but there's no mixin target then ignore the assignment
  12324. int mixinVar = GetMixinVariable();
  12325. if (mixinVar == -1)
  12326. {
  12327. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  12328. return;
  12329. }
  12330. }
  12331. BfAutoComplete* autoComplete = GetAutoComplete();
  12332. bool deferredFixits = false;
  12333. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetFixits))
  12334. {
  12335. SetAndRestoreValue<bool> ignoreFixits(autoComplete->mIgnoreFixits, true);
  12336. VisitChild(targetNode);
  12337. deferredFixits = true;
  12338. }
  12339. else if (!evaluatedLeft)
  12340. {
  12341. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(targetNode))
  12342. {
  12343. DoMemberReference(memberReferenceExpr, outCascadeValue);
  12344. }
  12345. else
  12346. VisitChild(targetNode);
  12347. }
  12348. if ((!mResult) && (mPropDef == NULL))
  12349. {
  12350. if (assignExpr->mRight != NULL)
  12351. {
  12352. auto result = mModule->CreateValueFromExpression(assignExpr->mRight);
  12353. if (deferredFixits)
  12354. {
  12355. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  12356. mExpectingType = result.mType;
  12357. VisitChild(targetNode);
  12358. mResult = BfTypedValue();
  12359. }
  12360. }
  12361. return;
  12362. }
  12363. ResolveGenericType();
  12364. auto ptr = mResult;
  12365. mResult = BfTypedValue();
  12366. if (mPropDef == NULL)
  12367. {
  12368. if (!CheckModifyResult(ptr, assignExpr->mOpToken, "assign to"))
  12369. {
  12370. if (assignExpr->mRight != NULL)
  12371. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, BfEvalExprFlags_NoCast);
  12372. return;
  12373. }
  12374. }
  12375. if (mPropDef != NULL)
  12376. {
  12377. bool hasLeftVal = false;
  12378. auto propDef = mPropDef;
  12379. auto propTarget = mPropTarget;
  12380. auto setMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, mPropCheckedKind);
  12381. if (setMethod == NULL)
  12382. {
  12383. // Allow for a ref return on the getter to be used if a setter is not available
  12384. GetResult();
  12385. if ((mResult) && (mResult.mKind == BfTypedValueKind_Addr))
  12386. {
  12387. ptr = mResult;
  12388. mResult = BfTypedValue();
  12389. hasLeftVal = true;
  12390. }
  12391. else
  12392. {
  12393. mModule->Fail("Property has no setter", mPropSrc);
  12394. if (assignExpr->mRight != NULL)
  12395. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, BfEvalExprFlags_NoCast);
  12396. return;
  12397. }
  12398. }
  12399. if (!hasLeftVal)
  12400. {
  12401. auto methodInstance = GetPropertyMethodInstance(setMethod);
  12402. if (methodInstance.mMethodInstance == NULL)
  12403. return;
  12404. BF_ASSERT(methodInstance.mMethodInstance->mMethodDef == setMethod);
  12405. CheckPropFail(setMethod, methodInstance.mMethodInstance);
  12406. BfTypedValue convVal;
  12407. if (binaryOp != BfBinaryOp_None)
  12408. {
  12409. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType);
  12410. if (!mResult)
  12411. return;
  12412. convVal = mResult;
  12413. mResult = BfTypedValue();
  12414. if (!convVal)
  12415. return;
  12416. }
  12417. else
  12418. {
  12419. auto wantType = methodInstance.mMethodInstance->GetParamType(methodInstance.mMethodInstance->GetParamCount() - 1);
  12420. if (rightValue)
  12421. {
  12422. convVal = mModule->Cast(assignExpr->mRight, rightValue, wantType);
  12423. }
  12424. else
  12425. {
  12426. if (assignExpr->mRight == NULL)
  12427. {
  12428. mModule->AssertErrorState();
  12429. return;
  12430. }
  12431. convVal = mModule->CreateValueFromExpression(assignExpr->mRight, wantType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_PendingPropSet));
  12432. }
  12433. if (!convVal)
  12434. {
  12435. mPropDef = NULL;
  12436. return;
  12437. }
  12438. }
  12439. if (mPropSrc != NULL)
  12440. mModule->UpdateExprSrcPos(mPropSrc);
  12441. SizedArray<BfIRValue, 4> args;
  12442. if (!setMethod->mIsStatic)
  12443. {
  12444. mModule->EmitObjectAccessCheck(mPropTarget);
  12445. PushThis(mPropSrc, mPropTarget, methodInstance.mMethodInstance, args);
  12446. }
  12447. for (int paramIdx = 0; paramIdx < (int)mIndexerValues.size(); paramIdx++)
  12448. {
  12449. auto val = mModule->Cast(mPropSrc, mIndexerValues[paramIdx].mTypedValue, methodInstance.mMethodInstance->GetParamType(paramIdx));
  12450. if (!val)
  12451. {
  12452. mPropDef = NULL;
  12453. return;
  12454. }
  12455. PushArg(val, args);
  12456. }
  12457. PushArg(convVal, args);
  12458. if (methodInstance)
  12459. CreateCall(methodInstance.mMethodInstance, methodInstance.mFunc, mPropDefBypassVirtual, args);
  12460. mPropDef = NULL;
  12461. mResult = convVal;
  12462. return;
  12463. }
  12464. }
  12465. auto toType = ptr.mType;
  12466. if (toType->IsRef())
  12467. {
  12468. auto refType = (BfRefType*)toType;
  12469. toType = refType->mElementType;
  12470. }
  12471. if ((autoComplete != NULL) && (assignExpr->mOpToken != NULL) && (toType != NULL))
  12472. autoComplete->CheckEmptyStart(assignExpr->mOpToken, toType);
  12473. BfExpression* rightExpr = assignExpr->mRight;
  12474. if (rightExpr == NULL)
  12475. {
  12476. mModule->AssertErrorState();
  12477. return;
  12478. }
  12479. bool alreadyWritten = false;
  12480. BfTypedValue convVal;
  12481. if (binaryOp != BfBinaryOp_None)
  12482. {
  12483. auto expectedType = ptr.mType;
  12484. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  12485. expectedType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  12486. if ((!rightValue) && (assignExpr->mRight != NULL))
  12487. {
  12488. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, expectedType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  12489. }
  12490. CheckResultForReading(ptr);
  12491. BfTypedValue leftValue = ptr;
  12492. leftValue = mModule->LoadValue(leftValue);
  12493. if (rightValue)
  12494. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType, leftValue, rightValue);
  12495. convVal = mResult;
  12496. mResult = BfTypedValue();
  12497. if (!convVal)
  12498. return;
  12499. }
  12500. else
  12501. {
  12502. convVal = rightValue;
  12503. if (!convVal)
  12504. {
  12505. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(rightExpr))
  12506. {
  12507. if (mResultLocalVar != NULL)
  12508. {
  12509. MarkResultAssigned();
  12510. return;
  12511. }
  12512. }
  12513. // In the cases like "structVal = GetVal()", the allowDirectStructRetWrite optimization allows us to pass the
  12514. // address of structVal into the sret. We only allow that if structVal is a local, because if it's globally
  12515. // visible then we could see the results of a partially-modified structVal
  12516. //bool allowDirectStructRetWrite = mResultLocalVarIdx != -1;
  12517. // ALTHOUGH- we can only allow this optimization if we can be sure the local value is not aliased- we could
  12518. // have the backend ensure that this local value never gets its address taken.
  12519. bool allowDirectStructWrite = false;
  12520. BfExprEvaluator exprEvaluator(mModule);
  12521. exprEvaluator.mExpectingType = toType;
  12522. if (allowDirectStructWrite)
  12523. exprEvaluator.mReceivingValue = &ptr;
  12524. exprEvaluator.Evaluate(rightExpr, false, false, true);
  12525. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  12526. convVal = exprEvaluator.GetResult();
  12527. mModule->FixIntUnknown(convVal);
  12528. alreadyWritten = (allowDirectStructWrite) && (exprEvaluator.mReceivingValue == NULL);
  12529. if (!convVal)
  12530. convVal = mModule->GetDefaultTypedValue(toType);
  12531. // Did we use mReceivingValue as a mixin result?
  12532. if ((convVal.mValue) && (convVal.mValue == ptr.mValue))
  12533. {
  12534. mResult = convVal;
  12535. return;
  12536. }
  12537. }
  12538. }
  12539. BF_ASSERT(convVal);
  12540. if ((convVal) && (convVal.mType->IsNull()) && (ptr.mType->IsNullable()))
  12541. {
  12542. // Allow this to pass through so we can catch it in the memset later in this function
  12543. }
  12544. else
  12545. {
  12546. if (!convVal.mType->IsComposite())
  12547. convVal = mModule->LoadValue(convVal);
  12548. convVal = mModule->Cast(rightExpr, convVal, toType);
  12549. if (!convVal)
  12550. return;
  12551. convVal = mModule->LoadValue(convVal);
  12552. }
  12553. if (ptr.mType->IsVar())
  12554. {
  12555. mResult = ptr;
  12556. return;
  12557. }
  12558. if (convVal.mValue)
  12559. {
  12560. if ((ptr.mType->IsStruct()) && (!ptr.mType->IsValuelessType()) && (convVal.mValue.IsConst()))
  12561. {
  12562. auto constant = mModule->mBfIRBuilder->GetConstant(convVal.mValue);
  12563. if ((constant->mTypeCode == BfTypeCode_NullPtr) || (constant->mConstType == BfConstType_AggZero))
  12564. {
  12565. auto type = ptr.mType;
  12566. mModule->mBfIRBuilder->CreateMemSet(ptr.mValue, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  12567. mModule->GetConstValue(type->mSize), type->mAlign);
  12568. mResult = ptr;
  12569. MarkResultAssigned();
  12570. return;
  12571. }
  12572. }
  12573. // if (ptr.mType->IsMethodRef())
  12574. // {
  12575. // auto methodRefType = (BfMethodRefType*)ptr.mType;
  12576. // auto methodInstance = methodRefType->mMethodInstance;
  12577. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  12578. // for (int implicitParamIdx = methodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  12579. // {
  12580. // bool failed = false;
  12581. // auto destPtr = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericTypeMember_Addr);
  12582. // auto srcVal = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericMethodMember);
  12583. // if ((destPtr) && (srcVal))
  12584. // {
  12585. // srcVal = mModule->AggregateSplat(srcVal);
  12586. // mModule->mBfIRBuilder->CreateStore(srcVal.mValue, destPtr.mValue);
  12587. // }
  12588. // }
  12589. // }
  12590. // else
  12591. {
  12592. mModule->mBfIRBuilder->PopulateType(ptr.mType);
  12593. if (convVal.IsSplat())
  12594. {
  12595. //convVal = mModule->AggregateSplat(convVal);
  12596. mModule->AggregateSplatIntoAddr(convVal, ptr.mValue);
  12597. }
  12598. else
  12599. {
  12600. if (ptr.mType->IsValuelessType())
  12601. {
  12602. mModule->EmitEnsureInstructionAt();
  12603. }
  12604. else if (!alreadyWritten)
  12605. {
  12606. //ptr = mModule->LoadValue(ptr);
  12607. BF_ASSERT(ptr.IsAddr());
  12608. convVal = mModule->LoadValue(convVal);
  12609. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(convVal.mValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  12610. }
  12611. }
  12612. }
  12613. }
  12614. else
  12615. {
  12616. BF_ASSERT(convVal.mType->IsValuelessType());
  12617. }
  12618. mResult = convVal;
  12619. MarkResultAssigned();
  12620. }
  12621. void BfExprEvaluator::Visit(BfAssignmentExpression* assignExpr)
  12622. {
  12623. if (assignExpr->mLeft->IsA<BfTupleExpression>())
  12624. {
  12625. DoTupleAssignment(assignExpr);
  12626. return;
  12627. }
  12628. BfAutoParentNodeEntry autoParentNodeEntry(mModule, assignExpr);
  12629. BfTypedValue cascadeValue;
  12630. PerformAssignment(assignExpr, false, BfTypedValue(), &cascadeValue);
  12631. if (cascadeValue)
  12632. mResult = cascadeValue;
  12633. }
  12634. void BfExprEvaluator::Visit(BfParenthesizedExpression* parenExpr)
  12635. {
  12636. VisitChild(parenExpr->mExpression);
  12637. MakeResultAsValue();
  12638. }
  12639. void BfExprEvaluator::InitializedSizedArray(BfSizedArrayType* arrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, BfTypedValue* receivingValue)
  12640. {
  12641. struct InitValue
  12642. {
  12643. BfTypedValue mValue;
  12644. bool mIsUninitialized;
  12645. bool mIsDefaultInitializer;
  12646. bool mIsDeferred;
  12647. InitValue()
  12648. {
  12649. mIsUninitialized = false;
  12650. mIsDefaultInitializer = false;
  12651. mIsDeferred = false;
  12652. }
  12653. };
  12654. SizedArray<InitValue, 8> values;
  12655. {
  12656. //bool hasFailed = false;
  12657. HashSet<int> failedAt;
  12658. bool isAllConst = true;
  12659. //bool endUninitialzied = false;
  12660. int depth = 0;
  12661. std::function<void(BfSizedArrayType*, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*, bool)>
  12662. _GetValues = [&](BfSizedArrayType* checkArrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, bool ignore)
  12663. {
  12664. int64 initCountDiff = (int)valueExprs.size() - checkArrayType->mElementCount;
  12665. if ((initCountDiff != 0) && (!failedAt.Contains(depth)))
  12666. {
  12667. if (initCountDiff > 0)
  12668. {
  12669. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[(int)checkArrayType->mElementCount]);
  12670. failedAt.Add(depth);
  12671. }
  12672. else
  12673. {
  12674. // If it ends with ", ?) or ",)" then allow unsized
  12675. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  12676. ((commas.size() < valueExprs.size()) || (valueExprs.size() == 0)))
  12677. {
  12678. BfAstNode* refNode = closeToken;
  12679. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  12680. refNode = mModule->mParentNodeEntry->mNode;
  12681. BF_ASSERT(refNode != NULL);
  12682. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  12683. failedAt.Add(depth);
  12684. }
  12685. }
  12686. }
  12687. for (int idx = 0; idx < BF_MAX(checkArrayType->mElementCount, valueExprs.size()); idx++)
  12688. {
  12689. BfTypedValue elementValue;
  12690. bool deferredValue = false;
  12691. BfExpression* expr = NULL;
  12692. if (idx < (int)valueExprs.size())
  12693. {
  12694. expr = valueExprs[idx];
  12695. if (expr == NULL)
  12696. {
  12697. if (idx == 0)
  12698. mModule->FailAfter("Expression expected", openToken);
  12699. else
  12700. mModule->FailAfter("Expression expected", commas[idx - 1]);
  12701. }
  12702. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  12703. {
  12704. isAllConst = false;
  12705. break;
  12706. }
  12707. if (checkArrayType->mElementType->IsSizedArray())
  12708. {
  12709. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  12710. {
  12711. depth++;
  12712. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen, ignore);
  12713. depth--;
  12714. continue;
  12715. }
  12716. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  12717. {
  12718. depth++;
  12719. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace, ignore);
  12720. depth--;
  12721. continue;
  12722. }
  12723. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  12724. {
  12725. depth++;
  12726. SizedArray<BfExpression*, 1> values;
  12727. values.Add(parenExpr->mExpression);
  12728. SizedArray<BfTokenNode*, 1> commas;
  12729. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, ignore);
  12730. depth--;
  12731. continue;
  12732. }
  12733. }
  12734. if (expr != NULL)
  12735. {
  12736. bool tryDefer = false;
  12737. if ((checkArrayType->IsComposite()) &&
  12738. ((expr->IsA<BfInvocationExpression>()) || (expr->IsExact<BfTupleExpression>())))
  12739. {
  12740. tryDefer = true;
  12741. }
  12742. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || tryDefer);
  12743. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType);
  12744. if (!elementValue)
  12745. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  12746. deferredValue = !prevIgnoreWrites.mPrevVal && elementValue.mValue.IsFake();
  12747. if ((!elementValue) || (!CheckAllowValue(elementValue, expr)))
  12748. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  12749. // For now, we can't properly create const-valued non-size-aligned composites
  12750. if (checkArrayType->mElementType->NeedsExplicitAlignment())
  12751. isAllConst = false;
  12752. if (!elementValue.mValue.IsConst())
  12753. isAllConst = false;
  12754. InitValue initValue;
  12755. initValue.mValue = elementValue;
  12756. initValue.mIsDeferred = deferredValue;
  12757. values.push_back(initValue);
  12758. }
  12759. }
  12760. }
  12761. };
  12762. int valueIdx = 0;
  12763. std::function<void(BfTypedValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  12764. _CreateMemArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  12765. {
  12766. BF_ASSERT(arrayValue.mType->IsSizedArray());
  12767. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  12768. int valIdx = 0;
  12769. bool hasUninit = false;
  12770. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  12771. {
  12772. BfExpression* expr = NULL;
  12773. BfTypedValue elementValue;
  12774. if (idx >= (int)valueExprs.size())
  12775. break;
  12776. expr = valueExprs[idx];
  12777. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  12778. {
  12779. hasUninit = true;
  12780. break;
  12781. }
  12782. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  12783. valIdx++;
  12784. if (checkArrayType->mElementType->IsSizedArray())
  12785. {
  12786. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  12787. {
  12788. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen);
  12789. continue;
  12790. }
  12791. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  12792. {
  12793. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace);
  12794. continue;
  12795. }
  12796. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  12797. {
  12798. depth++;
  12799. SizedArray<BfExpression*, 1> values;
  12800. values.Add(parenExpr->mExpression);
  12801. SizedArray<BfTokenNode*, 1> commas;
  12802. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen);
  12803. depth--;
  12804. continue;
  12805. }
  12806. }
  12807. if (expr != NULL)
  12808. {
  12809. InitValue initValue = values[valueIdx++];
  12810. elementValue = initValue.mValue;
  12811. if (initValue.mIsDeferred)
  12812. {
  12813. BfTypedValue elemePtrTypedVal = BfTypedValue(elemPtrValue, checkArrayType->mElementType, BfTypedValueKind_Addr);
  12814. BfExprEvaluator exprEvaluator(mModule);
  12815. exprEvaluator.mExpectingType = checkArrayType->mElementType;
  12816. exprEvaluator.mReceivingValue = &elemePtrTypedVal;
  12817. exprEvaluator.Evaluate(expr);
  12818. exprEvaluator.GetResult();
  12819. if (exprEvaluator.mReceivingValue == NULL)
  12820. {
  12821. // We wrote directly to the array in-place, we're done with this element
  12822. continue;
  12823. }
  12824. elementValue = exprEvaluator.mResult;
  12825. elementValue = mModule->Cast(expr, elementValue, checkArrayType->mElementType);
  12826. if (!elementValue)
  12827. {
  12828. mModule->AssertErrorState();
  12829. continue;
  12830. }
  12831. }
  12832. elementValue = mModule->LoadValue(elementValue);
  12833. mModule->mBfIRBuilder->CreateAlignedStore(elementValue.mValue, elemPtrValue, checkArrayType->mElementType->mAlign);
  12834. }
  12835. }
  12836. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  12837. if (fillCount > 0)
  12838. {
  12839. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  12840. if (hasUninit)
  12841. {
  12842. if (!mModule->IsOptimized())
  12843. {
  12844. int setSize = std::min(checkArrayType->mElementType->mSize, 128); // Keep it to a reasonable number of bytes to trash
  12845. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0xCC),
  12846. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  12847. }
  12848. }
  12849. else
  12850. {
  12851. int setSize = (int)((checkArrayType->mElementType->GetStride() * (fillCount - 1)) + checkArrayType->mElementType->mSize);
  12852. if (setSize >= 0)
  12853. {
  12854. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0),
  12855. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  12856. }
  12857. }
  12858. }
  12859. };
  12860. std::function<BfIRValue(BfTypedValue, BfTokenNode*, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  12861. _CreateConstArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  12862. {
  12863. SizedArray<BfIRValue, 8> members;
  12864. BF_ASSERT(arrayValue.mType->IsSizedArray());
  12865. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  12866. int valIdx = 0;
  12867. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  12868. {
  12869. BfTypedValue elementValue;
  12870. if (idx >= (int)valueExprs.size())
  12871. break;
  12872. auto expr = valueExprs[idx];
  12873. if (expr == NULL)
  12874. continue;
  12875. valIdx++;
  12876. if (checkArrayType->mElementType->IsSizedArray())
  12877. {
  12878. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  12879. {
  12880. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen));
  12881. continue;
  12882. }
  12883. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  12884. {
  12885. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace));
  12886. continue;
  12887. }
  12888. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  12889. {
  12890. depth++;
  12891. SizedArray<BfExpression*, 1> values;
  12892. values.Add(parenExpr->mExpression);
  12893. SizedArray<BfTokenNode*, 1> commas;
  12894. members.push_back(_CreateConstArray(checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen));
  12895. depth--;
  12896. continue;
  12897. }
  12898. }
  12899. InitValue initValue = values[valueIdx++];
  12900. BF_ASSERT(!initValue.mIsUninitialized);
  12901. elementValue = initValue.mValue;
  12902. members.push_back(elementValue.mValue);
  12903. }
  12904. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  12905. if (fillCount > 0)
  12906. {
  12907. // We just need to insert one default value, it will be duplicated as needed into the backend
  12908. auto defaultVal = mModule->GetDefaultTypedValue(checkArrayType->GetUnderlyingType());
  12909. BF_ASSERT(defaultVal.mValue.IsConst());
  12910. members.push_back(defaultVal.mValue);
  12911. }
  12912. return mModule->mBfIRBuilder->CreateConstArray(mModule->mBfIRBuilder->MapType(checkArrayType), members);
  12913. };
  12914. _GetValues(arrayType, openToken, valueExprs, commas, closeToken, false);
  12915. if (!failedAt.IsEmpty())
  12916. {
  12917. mResult = mModule->GetDefaultTypedValue(arrayType, false, BfDefaultValueKind_Addr);
  12918. return;
  12919. }
  12920. if (receivingValue != NULL)
  12921. {
  12922. BF_ASSERT(receivingValue->mType == arrayType);
  12923. BF_ASSERT(receivingValue->IsAddr());
  12924. mResult = *receivingValue;
  12925. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  12926. }
  12927. else if (isAllConst)
  12928. {
  12929. mResult = BfTypedValue(_CreateConstArray(arrayType, openToken, valueExprs, commas, closeToken), arrayType, BfTypedValueKind_Value);
  12930. }
  12931. else
  12932. {
  12933. if ((mReceivingValue != NULL) && (mReceivingValue->mType == arrayType) && (mReceivingValue->IsAddr()))
  12934. {
  12935. mResult = *mReceivingValue;
  12936. mReceivingValue = NULL;
  12937. }
  12938. else
  12939. {
  12940. auto arrayValue = mModule->CreateAlloca(arrayType);
  12941. mResult = BfTypedValue(arrayValue, arrayType, BfTypedValueKind_TempAddr);
  12942. }
  12943. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  12944. }
  12945. }
  12946. }
  12947. void BfExprEvaluator::Visit(BfTupleExpression* tupleExpr)
  12948. {
  12949. if (mExpectingType != NULL)
  12950. {
  12951. if (mExpectingType->IsSizedArray())
  12952. {
  12953. InitializedSizedArray((BfSizedArrayType*)mExpectingType, tupleExpr->mOpenParen, tupleExpr->mValues, tupleExpr->mCommas, tupleExpr->mCloseParen);
  12954. return;
  12955. }
  12956. }
  12957. BfTupleType* tupleType = NULL;
  12958. bool hadFullMatch = false;
  12959. if ((mExpectingType != NULL) && (mExpectingType->IsTuple()))
  12960. {
  12961. tupleType = (BfTupleType*)mExpectingType;
  12962. hadFullMatch = tupleType->mFieldInstances.size() == tupleExpr->mValues.size();
  12963. }
  12964. struct InitValue
  12965. {
  12966. BfTypedValue mValue;
  12967. bool mIsUninitialized;
  12968. bool mIsDefaultInitializer;
  12969. bool mIsDeferred;
  12970. InitValue()
  12971. {
  12972. mIsUninitialized = false;
  12973. mIsDefaultInitializer = false;
  12974. mIsDeferred = false;
  12975. }
  12976. };
  12977. SizedArray<BfTypedValue, 2> typedValues;
  12978. if ((tupleExpr->mCommas.size() != 0) && (tupleExpr->mCommas.size() >= tupleExpr->mValues.size()))
  12979. {
  12980. // We would normally give this error during syntax parsing, but a TupleExpression can be an array initializer
  12981. mModule->FailAfter("Expression expected", tupleExpr->mCommas.back());
  12982. }
  12983. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  12984. {
  12985. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  12986. BfType* fieldType = NULL;
  12987. BfFieldInstance* fieldInstance = NULL;
  12988. if (tupleType != NULL)
  12989. {
  12990. if (valueIdx < (int)tupleType->mFieldInstances.size())
  12991. {
  12992. fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[valueIdx];
  12993. fieldType = fieldInstance->GetResolvedType();
  12994. if (fieldType->IsVoid())
  12995. {
  12996. typedValues.push_back(BfTypedValue());
  12997. continue;
  12998. }
  12999. if (fieldType->IsVar())
  13000. {
  13001. hadFullMatch = false;
  13002. fieldType = NULL;
  13003. }
  13004. }
  13005. }
  13006. bool tryDefer = false;
  13007. if (((fieldType == NULL) || (fieldType->IsComposite())) &&
  13008. ((valueExpr->IsA<BfInvocationExpression>()) || (valueExpr->IsExact<BfTupleExpression>())))
  13009. {
  13010. tryDefer = true;
  13011. }
  13012. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || tryDefer);
  13013. BfTypedValue value = mModule->CreateValueFromExpression(valueExpr, fieldType);
  13014. if (!value)
  13015. {
  13016. if (fieldType != NULL)
  13017. value = mModule->GetDefaultTypedValue(fieldType);
  13018. else
  13019. value = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  13020. }
  13021. if ((fieldInstance != NULL) && (!fieldInstance->GetFieldDef()->IsUnnamedTupleField()) && (valueIdx < (int)tupleExpr->mNames.size()))
  13022. {
  13023. auto checkName = tupleExpr->mNames[valueIdx];
  13024. if (checkName != NULL)
  13025. {
  13026. if (checkName->ToString() != fieldInstance->GetFieldDef()->mName)
  13027. hadFullMatch = false;
  13028. }
  13029. }
  13030. value = mModule->LoadValue(value);
  13031. typedValues.push_back(value);
  13032. }
  13033. if (!hadFullMatch)
  13034. {
  13035. BfTypeVector fieldTypes;
  13036. Array<String> fieldNames;
  13037. for (auto typedVal : typedValues)
  13038. {
  13039. auto type = typedVal.mType;
  13040. if (type != NULL)
  13041. fieldTypes.push_back(type);
  13042. else
  13043. fieldTypes.push_back(mModule->mContext->mBfObjectType);
  13044. }
  13045. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  13046. {
  13047. if (requestedName == NULL)
  13048. fieldNames.push_back("");
  13049. else
  13050. fieldNames.push_back(requestedName->mNameNode->ToString());
  13051. }
  13052. tupleType = mModule->CreateTupleType(fieldTypes, fieldNames);
  13053. }
  13054. mModule->mBfIRBuilder->PopulateType(tupleType);
  13055. BfIRValue curTupleValue;
  13056. if ((mReceivingValue != NULL) && (mReceivingValue->mType == tupleType) && (mReceivingValue->IsAddr()))
  13057. {
  13058. mResult = *mReceivingValue;
  13059. mReceivingValue = NULL;
  13060. curTupleValue = mResult.mValue;
  13061. }
  13062. else
  13063. {
  13064. curTupleValue = mModule->CreateAlloca(tupleType);
  13065. mResultIsTempComposite = true;
  13066. mResult = BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  13067. }
  13068. for (int valueIdx = 0; valueIdx < (int)typedValues.size(); valueIdx++)
  13069. {
  13070. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[valueIdx];
  13071. if (fieldInstance->mResolvedType->IsValuelessType())
  13072. continue;
  13073. auto typedVal = typedValues[valueIdx];
  13074. if (!typedVal)
  13075. {
  13076. mModule->AssertErrorState();
  13077. continue;
  13078. }
  13079. if (fieldInstance->mDataIdx >= 0)
  13080. {
  13081. auto memberVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curTupleValue, 0, fieldInstance->mDataIdx);
  13082. if ((!mModule->mBfIRBuilder->mIgnoreWrites) && (typedVal.mValue.IsFake()))
  13083. {
  13084. // Value was deferred. Allow us to try to init in place
  13085. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  13086. BfTypedValue memberPtrTypedVal = BfTypedValue(memberVal, fieldInstance->mResolvedType, BfTypedValueKind_Addr);
  13087. BfExprEvaluator exprEvaluator(mModule);
  13088. exprEvaluator.mExpectingType = fieldInstance->mResolvedType;
  13089. exprEvaluator.mReceivingValue = &memberPtrTypedVal;
  13090. exprEvaluator.Evaluate(valueExpr);
  13091. exprEvaluator.GetResult();
  13092. if (exprEvaluator.mReceivingValue == NULL)
  13093. {
  13094. // We wrote directly to the array in-place, we're done with this element
  13095. continue;
  13096. }
  13097. typedVal = exprEvaluator.mResult;
  13098. typedVal = mModule->Cast(valueExpr, typedVal, fieldInstance->mResolvedType);
  13099. if (!typedVal)
  13100. {
  13101. mModule->AssertErrorState();
  13102. continue;
  13103. }
  13104. typedVal = mModule->LoadValue(typedVal);
  13105. }
  13106. if (typedVal.IsSplat())
  13107. mModule->AggregateSplatIntoAddr(typedVal, memberVal);
  13108. else
  13109. mModule->mBfIRBuilder->CreateStore(typedVal.mValue, memberVal);
  13110. }
  13111. }
  13112. }
  13113. BfTypedValue BfExprEvaluator::SetupNullConditional(BfTypedValue thisValue, BfTokenNode* dotToken)
  13114. {
  13115. bool isStaticLookup = (!thisValue) ||
  13116. ((!thisValue.mType->IsValuelessType()) && (!thisValue.mValue));
  13117. if (isStaticLookup)
  13118. {
  13119. mModule->Fail("Null conditional reference not valid for static field references", dotToken);
  13120. return thisValue;
  13121. }
  13122. //TODO: But make null conditional work for Nullable types
  13123. if (thisValue.mType->IsNullable())
  13124. {
  13125. // Success
  13126. }
  13127. else if ((thisValue.mType->IsPointer()) || (thisValue.mType->IsObjectOrInterface()))
  13128. {
  13129. // Also good
  13130. }
  13131. else
  13132. {
  13133. if (thisValue.mType->IsStruct())
  13134. mModule->Warn(0, "Struct lookups can never fail, null conditional reference is unnecessary", dotToken);
  13135. else
  13136. mModule->AssertErrorState();
  13137. return thisValue;
  13138. }
  13139. thisValue = mModule->LoadValue(thisValue);
  13140. BfPendingNullConditional* pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  13141. if (pendingNullCond == NULL)
  13142. {
  13143. pendingNullCond = new BfPendingNullConditional();
  13144. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  13145. }
  13146. if (!pendingNullCond->mPrevBB)
  13147. pendingNullCond->mPrevBB = mModule->mBfIRBuilder->GetInsertBlock();
  13148. if (!pendingNullCond->mDoneBB)
  13149. pendingNullCond->mDoneBB = mModule->mBfIRBuilder->CreateBlock("nullCond.done");
  13150. // We will in the br to checkBB later
  13151. if (!pendingNullCond->mCheckBB)
  13152. {
  13153. pendingNullCond->mCheckBB = mModule->mBfIRBuilder->CreateBlock("nullCond.check");
  13154. mModule->AddBasicBlock(pendingNullCond->mCheckBB);
  13155. }
  13156. BfIRValue isNotNull;
  13157. if (thisValue.mType->IsNullable())
  13158. {
  13159. BfGenericTypeInstance* nullableType = (BfGenericTypeInstance*)thisValue.mType->ToTypeInstance();
  13160. auto elementType = nullableType->GetUnderlyingType();
  13161. if (elementType->IsValuelessType())
  13162. {
  13163. thisValue = mModule->MakeAddressable(thisValue);
  13164. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mHasValue
  13165. isNotNull = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  13166. thisValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), elementType, true);
  13167. }
  13168. else
  13169. {
  13170. thisValue = mModule->MakeAddressable(thisValue);
  13171. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 2); // mHasValue
  13172. isNotNull = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  13173. BfIRValue valuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mValue
  13174. thisValue = BfTypedValue(valuePtr, elementType, true);
  13175. }
  13176. }
  13177. else
  13178. isNotNull = mModule->mBfIRBuilder->CreateIsNotNull(thisValue.mValue);
  13179. BfIRBlock notNullBB = mModule->mBfIRBuilder->CreateBlock("nullCond.notNull");
  13180. mModule->mBfIRBuilder->CreateCondBr(isNotNull, notNullBB, pendingNullCond->mDoneBB);
  13181. mModule->AddBasicBlock(notNullBB);
  13182. return thisValue;
  13183. }
  13184. void BfExprEvaluator::CheckDotToken(BfTokenNode* tokenNode)
  13185. {
  13186. if ((tokenNode != NULL) && (tokenNode->mToken == BfToken_DotDot))
  13187. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", tokenNode);
  13188. }
  13189. void BfExprEvaluator::DoMemberReference(BfMemberReferenceExpression* memberRefExpr, BfTypedValue* outCascadeValue)
  13190. {
  13191. CheckDotToken(memberRefExpr->mDotToken);
  13192. BfAttributeState attributeState;
  13193. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  13194. String findName;
  13195. BfAstNode* nameRefNode = memberRefExpr->mMemberName;
  13196. if (auto attrIdentifierExpr = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpr->mMemberName))
  13197. {
  13198. nameRefNode = attrIdentifierExpr->mIdentifier;
  13199. // Don't validate
  13200. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierExpr->mAttributes, BfAttributeTargets_SkipValidate);
  13201. if (nameRefNode != NULL)
  13202. findName = attrIdentifierExpr->mIdentifier->ToString();
  13203. }
  13204. else if (memberRefExpr->mMemberName != NULL)
  13205. findName = memberRefExpr->mMemberName->ToString();
  13206. defer
  13207. {
  13208. if (attributeState.mCustomAttributes != NULL)
  13209. {
  13210. if (mPropDef != NULL)
  13211. attributeState.mTarget = BfAttributeTargets_Invocation;
  13212. mModule->ValidateCustomAttributes(attributeState.mCustomAttributes, attributeState.mTarget);
  13213. }
  13214. };
  13215. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  13216. BfTypeInstance* expectingTypeInst = NULL;
  13217. if (mExpectingType != NULL)
  13218. {
  13219. expectingTypeInst = mExpectingType->ToTypeInstance();
  13220. if (mExpectingType->IsPointer())
  13221. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  13222. else if (mExpectingType->IsNullable())
  13223. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  13224. else if (mExpectingType->IsConstExprValue())
  13225. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  13226. else if (mExpectingType->IsGenericParam())
  13227. {
  13228. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  13229. if (genericParam->mTypeConstraint != NULL)
  13230. expectingTypeInst = genericParam->mTypeConstraint->ToTypeInstance();
  13231. }
  13232. }
  13233. BfAutoComplete* autoComplete = GetAutoComplete();
  13234. if (autoComplete != NULL)
  13235. {
  13236. SetAndRestoreValue<bool> prevFriendSet(autoComplete->mHasFriendSet, (attributeState.mCustomAttributes != NULL) && (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef)));
  13237. if (memberRefExpr->mTarget == NULL)
  13238. {
  13239. String filter;
  13240. if ((mExpectingType != NULL) &&
  13241. (autoComplete->InitAutocomplete(memberRefExpr->mDotToken, memberRefExpr->mMemberName, filter)))
  13242. {
  13243. if (expectingTypeInst != NULL)
  13244. {
  13245. bool allowPrivate = expectingTypeInst == mModule->mCurTypeInstance;
  13246. if (expectingTypeInst->IsEnum())
  13247. autoComplete->AddEnumTypeMembers(expectingTypeInst, filter, false, allowPrivate);
  13248. autoComplete->AddSelfResultTypeMembers(expectingTypeInst, expectingTypeInst, filter, allowPrivate);
  13249. }
  13250. }
  13251. }
  13252. else
  13253. {
  13254. autoComplete->CheckMemberReference(memberRefExpr->mTarget, memberRefExpr->mDotToken, memberRefExpr->mMemberName);
  13255. if (auto objCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(memberRefExpr->mTarget))
  13256. {
  13257. // This handles a weird case where we have "obj a = new\nWhatever().Thing = 123;".
  13258. // That gets parsed as "Whatever()" being the type we want to create, and then referencing
  13259. // the "Thing" member of that new object.
  13260. //if (objCreateExpr->mArraySizeSpecifier == NULL)
  13261. CheckObjectCreateTypeRef(mExpectingType, objCreateExpr->mNewNode);
  13262. }
  13263. }
  13264. }
  13265. if (memberRefExpr->mTarget == NULL)
  13266. {
  13267. if (mExpectingType == NULL)
  13268. {
  13269. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", nameRefNode);
  13270. return;
  13271. }
  13272. if (expectingTypeInst == NULL)
  13273. {
  13274. mModule->Fail(StrFormat("Unqualified dot syntax cannot be used with type '%s'", mModule->TypeToString(mExpectingType).c_str()), nameRefNode);
  13275. return;
  13276. }
  13277. if (mExpectingType->IsVar())
  13278. {
  13279. mResult = mModule->GetDefaultTypedValue(mExpectingType);
  13280. return;
  13281. }
  13282. BfTypedValue expectingVal(expectingTypeInst);
  13283. mResult = LookupField(memberRefExpr->mMemberName, expectingVal, findName);
  13284. if ((mResult) || (mPropDef != NULL))
  13285. return;
  13286. }
  13287. bool isNullCondLookup = (memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_QuestionDot);
  13288. bool isCascade = ((memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_DotDot));
  13289. BfIdentifierNode* nameLeft = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mTarget);
  13290. BfIdentifierNode* nameRight = BfIdentifierCast(memberRefExpr->mMemberName);
  13291. if ((nameLeft != NULL) && (nameRight != NULL) && (!isNullCondLookup) && (!isCascade))
  13292. {
  13293. bool hadError = false;
  13294. LookupQualifiedName(memberRefExpr, nameLeft, nameRight, true, &hadError);
  13295. if ((mResult) || (mPropDef != NULL))
  13296. return;
  13297. if (hadError)
  13298. return;
  13299. LookupQualifiedStaticField(memberRefExpr, nameLeft, nameRight, false);
  13300. return;
  13301. }
  13302. BfTypedValue thisValue;
  13303. if (auto exprTarget = BfNodeDynCast<BfExpression>(memberRefExpr->mTarget))
  13304. {
  13305. if (auto typeOfExpr = BfNodeDynCast<BfTypeOfExpression>(memberRefExpr->mTarget))
  13306. {
  13307. if (auto nameIdentifer = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  13308. {
  13309. if (LookupTypeProp(typeOfExpr, nameIdentifer))
  13310. return;
  13311. }
  13312. }
  13313. //Hm, not using VisitChild broke our ability to write to a field for a not-initialized local struct
  13314. VisitChild(memberRefExpr->mTarget);
  13315. GetResult();
  13316. thisValue = mResult;
  13317. if (!thisValue)
  13318. {
  13319. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(exprTarget))
  13320. thisValue = BfTypedValue(mModule->ResolveTypeRef(targetIdentifier, NULL));
  13321. }
  13322. if (!thisValue.HasType())
  13323. return;
  13324. //thisValue = mResult;
  13325. }
  13326. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpr->mTarget))
  13327. {
  13328. // Look up static field
  13329. thisValue = BfTypedValue(ResolveTypeRef(typeRef));
  13330. }
  13331. if (nameRefNode == NULL)
  13332. {
  13333. mModule->AssertErrorState();
  13334. return;
  13335. }
  13336. if (isNullCondLookup)
  13337. thisValue = SetupNullConditional(thisValue, memberRefExpr->mDotToken);
  13338. mResult = LookupField(nameRefNode, thisValue, findName);
  13339. if ((!mResult) && (mPropDef == NULL))
  13340. {
  13341. if (thisValue.mType != NULL)
  13342. {
  13343. BfTypeInstance* typeInst = thisValue.mType->ToTypeInstance();
  13344. auto compiler = mModule->mCompiler;
  13345. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(memberRefExpr->mMemberName)))
  13346. {
  13347. FixitAddMember(typeInst, mExpectingType, findName, !thisValue.mValue);
  13348. }
  13349. }
  13350. if ((!thisValue.mValue) && (thisValue.mType != NULL))
  13351. {
  13352. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  13353. {
  13354. mResult.mType = mModule->ResolveInnerType(thisValue.mType, targetIdentifier, BfPopulateType_Declaration);
  13355. }
  13356. }
  13357. if (mResult.mType == NULL)
  13358. mModule->Fail("Unable to find member", nameRefNode);
  13359. }
  13360. if (isNullCondLookup)
  13361. mResult = GetResult();
  13362. if (isCascade)
  13363. {
  13364. if (outCascadeValue != NULL)
  13365. *outCascadeValue = thisValue;
  13366. else
  13367. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", memberRefExpr->mDotToken);
  13368. }
  13369. }
  13370. void BfExprEvaluator::Visit(BfMemberReferenceExpression* memberRefExpr)
  13371. {
  13372. DoMemberReference(memberRefExpr, NULL);
  13373. }
  13374. void BfExprEvaluator::Visit(BfIndexerExpression* indexerExpr)
  13375. {
  13376. VisitChild(indexerExpr->mTarget);
  13377. ResolveGenericType();
  13378. auto target = GetResult(true);
  13379. if (!target)
  13380. return;
  13381. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  13382. bool isInlined = false;
  13383. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  13384. {
  13385. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  13386. {
  13387. isInlined = true;
  13388. mModule->mAttributeState->mUsed = true;
  13389. }
  13390. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  13391. {
  13392. checkedKind = BfCheckedKind_Checked;
  13393. mModule->mAttributeState->mUsed = true;
  13394. }
  13395. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  13396. {
  13397. checkedKind = BfCheckedKind_Unchecked;
  13398. mModule->mAttributeState->mUsed = true;
  13399. }
  13400. }
  13401. bool isNullCondLookup = (indexerExpr->mOpenBracket != NULL) && (indexerExpr->mOpenBracket->GetToken() == BfToken_QuestionLBracket);
  13402. if (isNullCondLookup)
  13403. target = SetupNullConditional(target, indexerExpr->mOpenBracket);
  13404. if (target.mType->IsVar())
  13405. {
  13406. mResult = BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  13407. return;
  13408. }
  13409. if (target.mType->IsTypeInstance())
  13410. {
  13411. mIndexerValues.clear();
  13412. for (BfExpression* expr : indexerExpr->mArguments)
  13413. {
  13414. if (expr == NULL)
  13415. return;
  13416. auto argVal = mModule->CreateValueFromExpression(expr);
  13417. if (!argVal)
  13418. {
  13419. mModule->AssertErrorState();
  13420. argVal = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  13421. }
  13422. BfResolvedArg resolvedArg;
  13423. resolvedArg.mTypedValue = argVal;
  13424. mIndexerValues.push_back(resolvedArg);
  13425. }
  13426. BfMethodMatcher methodMatcher(indexerExpr->mTarget, mModule, "[]", mIndexerValues, NULL);
  13427. methodMatcher.mCheckedKind = checkedKind;
  13428. //methodMatcher.CheckType(target.mType->ToTypeInstance(), target, false);
  13429. BfMethodDef* methodDef = NULL;
  13430. auto startCheckTypeInst = target.mType->ToTypeInstance();
  13431. for (int pass = 0; pass < 2; pass++)
  13432. {
  13433. bool isFailurePass = pass == 1;
  13434. auto curCheckType = startCheckTypeInst;
  13435. while (curCheckType != NULL)
  13436. {
  13437. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  13438. BfPropertyDef* foundProp = NULL;
  13439. BfTypeInstance* foundPropTypeInst = NULL;
  13440. int matchedIndexCount = 0;
  13441. curCheckType->mTypeDef->PopulateMemberSets();
  13442. BfMemberSetEntry* entry;
  13443. BfPropertyDef* matchedProp = NULL;
  13444. BfPropertyDef* nextProp = NULL;
  13445. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(String("[]"), &entry))
  13446. nextProp = (BfPropertyDef*)entry->mMemberDef;
  13447. while (nextProp != NULL)
  13448. {
  13449. auto prop = nextProp;
  13450. nextProp = nextProp->mNextWithSameName;
  13451. //TODO: Match against setMethod (minus last param) if we have no 'get' method
  13452. for (auto checkMethod : prop->mMethods)
  13453. {
  13454. if (checkMethod->mMethodType != BfMethodType_PropertyGetter)
  13455. continue;
  13456. // For generic params - check interface constraints for an indexer, call that method
  13457. BF_ASSERT(!target.mType->IsGenericParam());
  13458. if (checkMethod->mExplicitInterface != NULL)
  13459. continue;
  13460. if (checkMethod->mIsOverride)
  13461. continue;
  13462. auto autoComplete = GetAutoComplete();
  13463. bool wasCapturingMethodMatchInfo = false;
  13464. if (autoComplete != NULL)
  13465. {
  13466. // Set to false to make sure we don't capture method match info from 'params' array creation
  13467. wasCapturingMethodMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  13468. autoComplete->mIsCapturingMethodMatchInfo = false;
  13469. }
  13470. defer
  13471. {
  13472. if (autoComplete != NULL)
  13473. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMethodMatchInfo;
  13474. };
  13475. if ((!isFailurePass) && (!methodMatcher.WantsCheckMethod(protectionCheckFlags, startCheckTypeInst, curCheckType, checkMethod)))
  13476. continue;
  13477. methodMatcher.mCheckedKind = checkedKind;
  13478. methodMatcher.CheckMethod(curCheckType, checkMethod, false);
  13479. if ((methodMatcher.mBestMethodDef == checkMethod) ||
  13480. ((foundProp == NULL) && (methodMatcher.mBackupMethodDef == checkMethod)))
  13481. {
  13482. foundPropTypeInst = curCheckType;
  13483. foundProp = prop;
  13484. matchedIndexCount = (int)checkMethod->mParams.size();
  13485. }
  13486. }
  13487. }
  13488. if (foundProp != NULL)
  13489. {
  13490. int indexDiff = matchedIndexCount - (int)mIndexerValues.size();
  13491. if (indexDiff > 0)
  13492. {
  13493. mModule->Fail(StrFormat("Expected %d more indices", indexDiff), indexerExpr->mTarget);
  13494. //mModule->mCompiler->mPassInstance->MoreInfo("See method declaration", methodInstance->mMethodDef->mMethodDeclaration);
  13495. }
  13496. else if (indexDiff < 0)
  13497. {
  13498. mModule->Fail(StrFormat("Expected %d fewer indices", indexDiff), indexerExpr->mTarget);
  13499. }
  13500. else
  13501. {
  13502. mPropSrc = indexerExpr->mOpenBracket;
  13503. mPropDef = foundProp;
  13504. if (foundProp->mIsStatic)
  13505. {
  13506. mPropTarget = BfTypedValue(curCheckType);
  13507. }
  13508. else
  13509. {
  13510. if (target.mType != foundPropTypeInst)
  13511. mPropTarget = mModule->Cast(indexerExpr->mTarget, target, foundPropTypeInst);
  13512. else
  13513. mPropTarget = target;
  13514. }
  13515. mOrigPropTarget = mPropTarget;
  13516. if (isInlined)
  13517. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  13518. mPropCheckedKind = checkedKind;
  13519. }
  13520. return;
  13521. }
  13522. curCheckType = curCheckType->mBaseType;
  13523. }
  13524. }
  13525. mModule->Fail("Unable to find indexer property", indexerExpr->mTarget);
  13526. return;
  13527. }
  13528. //target.mType = mModule->ResolveGenericType(target.mType);
  13529. if (target.mType->IsVar())
  13530. {
  13531. mResult = target;
  13532. return;
  13533. }
  13534. if ((!target.mType->IsPointer()) && (!target.mType->IsSizedArray()))
  13535. {
  13536. mModule->Fail("Expected pointer or array type", indexerExpr->mTarget);
  13537. return;
  13538. }
  13539. auto _GetDefaultResult = [&]()
  13540. {
  13541. return mModule->GetDefaultTypedValue(target.mType->GetUnderlyingType(), false, BfDefaultValueKind_Addr);
  13542. };
  13543. if (indexerExpr->mArguments.size() != 1)
  13544. {
  13545. mModule->Fail("Expected single index", indexerExpr->mOpenBracket);
  13546. mResult = _GetDefaultResult();
  13547. return;
  13548. }
  13549. if (indexerExpr->mArguments[0] == NULL)
  13550. {
  13551. mModule->AssertErrorState();
  13552. mResult = _GetDefaultResult();
  13553. return;
  13554. }
  13555. bool isUndefIndex = false;
  13556. auto indexArgument = mModule->CreateValueFromExpression(indexerExpr->mArguments[0]);
  13557. if (!indexArgument)
  13558. return;
  13559. if (!indexArgument.mType->IsIntegral())
  13560. {
  13561. if (indexArgument.mType->IsVar())
  13562. {
  13563. isUndefIndex = true;
  13564. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr), false, BfDefaultValueKind_Undef);
  13565. }
  13566. else
  13567. {
  13568. mModule->Fail("Expected integer index", indexerExpr->mArguments[0]);
  13569. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  13570. }
  13571. }
  13572. if (indexArgument.mType->IsPrimitiveType())
  13573. {
  13574. auto primType = (BfPrimitiveType*)indexArgument.mType;
  13575. if ((!primType->IsSigned()) && (primType->mSize < 8))
  13576. {
  13577. // GEP will always do a signed upcast so we need to cast manually if we are unsigned
  13578. indexArgument = BfTypedValue(mModule->mBfIRBuilder->CreateNumericCast(indexArgument.mValue, false, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  13579. }
  13580. }
  13581. mModule->PopulateType(target.mType);
  13582. if (target.mType->IsSizedArray())
  13583. {
  13584. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)target.mType;
  13585. auto underlyingType = sizedArrayType->mElementType;
  13586. if (indexArgument.mValue.IsConst())
  13587. {
  13588. auto indexConst = mModule->mBfIRBuilder->GetConstant(indexArgument.mValue);
  13589. if (indexConst->mUInt64 >= (uint64)sizedArrayType->mElementCount)
  13590. {
  13591. mModule->Fail(StrFormat("Index '%d' is out of bounds for type '%s'", indexConst->mInt32, mModule->TypeToString(target.mType).c_str()), indexerExpr->mArguments[0]);
  13592. mResult = _GetDefaultResult();
  13593. return;
  13594. }
  13595. }
  13596. else if (mModule->HasCompiledOutput())
  13597. {
  13598. if (checkedKind == BfCheckedKind_NotSet)
  13599. checkedKind = mModule->GetDefaultCheckedKind();
  13600. if (checkedKind == BfCheckedKind_Checked)
  13601. {
  13602. auto oobBlock = mModule->mBfIRBuilder->CreateBlock("oob", true);
  13603. auto contBlock = mModule->mBfIRBuilder->CreateBlock("cont", true);
  13604. auto indexType = (BfPrimitiveType*)indexArgument.mType;
  13605. if (!mModule->mSystem->DoesLiteralFit(indexType->mTypeDef->mTypeCode, sizedArrayType->mElementCount))
  13606. {
  13607. // We need to upsize the index so we can compare it against the larger elementCount
  13608. indexType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  13609. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, indexType);
  13610. }
  13611. auto cmpRes = mModule->mBfIRBuilder->CreateCmpGTE(indexArgument.mValue, mModule->mBfIRBuilder->CreateConst(indexType->mTypeDef->mTypeCode, (uint64)sizedArrayType->mElementCount), false);
  13612. mModule->mBfIRBuilder->CreateCondBr(cmpRes, oobBlock, contBlock);
  13613. mModule->mBfIRBuilder->SetInsertPoint(oobBlock);
  13614. auto internalType = mModule->ResolveTypeDef(mModule->mCompiler->mInternalTypeDef);
  13615. auto oobFunc = mModule->GetMethodByName(internalType->ToTypeInstance(), "ThrowIndexOutOfRange");
  13616. if (oobFunc.mFunc)
  13617. {
  13618. /*if (!mModule->mCompiler->mIsResolveOnly)
  13619. {
  13620. OutputDebugStrF("-OOB %d %d\n", oobFunc.mFunc.mId, oobFunc.mFunc.mFlags);
  13621. }*/
  13622. SizedArray<BfIRValue, 1> args;
  13623. args.push_back(mModule->GetConstValue(0));
  13624. mModule->mBfIRBuilder->CreateCall(oobFunc.mFunc, args);
  13625. mModule->mBfIRBuilder->CreateUnreachable();
  13626. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  13627. }
  13628. else
  13629. {
  13630. mModule->Fail("System.Internal class must contain method 'ThrowIndexOutOfRange'");
  13631. }
  13632. }
  13633. }
  13634. // If this is a 'bag of bytes', we should try hard not to have to make this addressable
  13635. if ((!target.IsAddr()) && (!target.mType->IsSizeAligned()))
  13636. mModule->MakeAddressable(target);
  13637. mModule->PopulateType(underlyingType);
  13638. if (sizedArrayType->IsUnknownSizedArray())
  13639. {
  13640. mResult = mModule->GetDefaultTypedValue(underlyingType);
  13641. }
  13642. else if (sizedArrayType->IsValuelessType())
  13643. {
  13644. if (underlyingType->IsValuelessType())
  13645. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), underlyingType, true);
  13646. else
  13647. {
  13648. mResult = mModule->GetDefaultTypedValue(underlyingType);
  13649. if (sizedArrayType->mElementCount != 0)
  13650. mModule->AssertErrorState();
  13651. }
  13652. }
  13653. else if (target.IsAddr())
  13654. {
  13655. if (target.mType->IsSizeAligned())
  13656. {
  13657. auto ptrType = mModule->CreatePointerType(underlyingType);
  13658. auto ptrValue = mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapType(ptrType));
  13659. auto gepResult = mModule->mBfIRBuilder->CreateInBoundsGEP(ptrValue, indexArgument.mValue);
  13660. mResult = BfTypedValue(gepResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  13661. }
  13662. else
  13663. {
  13664. auto indexResult = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  13665. mResult = BfTypedValue(indexResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  13666. }
  13667. }
  13668. else
  13669. {
  13670. if ((!target.mValue.IsConst()) && (!indexArgument.mValue.IsConst()))
  13671. {
  13672. mModule->Fail("Unable to index value", indexerExpr->mTarget);
  13673. return;
  13674. }
  13675. mModule->mBfIRBuilder->PopulateType(target.mType);
  13676. auto gepResult = mModule->mBfIRBuilder->CreateExtractValue(target.mValue, indexArgument.mValue);
  13677. if ((underlyingType->IsString()) || (underlyingType->IsPointer()))
  13678. {
  13679. auto resultConst = mModule->mBfIRBuilder->GetConstant(gepResult);
  13680. if ((resultConst != NULL) && (resultConst->mTypeCode == BfTypeCode_Int32))
  13681. {
  13682. int strId = resultConst->mInt32;
  13683. const StringImpl& str = mModule->mContext->mStringObjectIdMap[strId].mString;
  13684. if (underlyingType->IsString())
  13685. gepResult = mModule->GetStringObjectValue(str, false);
  13686. else
  13687. gepResult = mModule->GetStringCharPtr(strId);
  13688. }
  13689. }
  13690. mResult = BfTypedValue(gepResult, underlyingType, BfTypedValueKind_Value);
  13691. }
  13692. }
  13693. else
  13694. {
  13695. target = mModule->LoadValue(target);
  13696. BfPointerType* pointerType = (BfPointerType*)target.mType;
  13697. auto underlyingType = pointerType->mElementType;
  13698. mModule->mBfIRBuilder->PopulateType(underlyingType);
  13699. if (isUndefIndex)
  13700. {
  13701. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  13702. }
  13703. else
  13704. {
  13705. BfIRValue result = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  13706. mResult = BfTypedValue(result, underlyingType, true);
  13707. }
  13708. }
  13709. }
  13710. void BfExprEvaluator::Visit(BfUnaryOperatorExpression* unaryOpExpr)
  13711. {
  13712. BfAutoParentNodeEntry autoParentNodeEntry(mModule, unaryOpExpr);
  13713. PerformUnaryOperation(unaryOpExpr->mExpression, unaryOpExpr->mOp, unaryOpExpr->mOpToken);
  13714. }
  13715. void BfExprEvaluator::PerformUnaryOperation(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken)
  13716. {
  13717. {
  13718. // If this is a cast, we don't want the value to be coerced before the unary operator is applied.
  13719. // WAIT: Why not?
  13720. //SetAndRestoreValue<BfType*> prevExpectingType(mExpectingType, NULL);
  13721. BfType* prevExpedcting = mExpectingType;
  13722. switch (unaryOp)
  13723. {
  13724. case BfUnaryOp_Negate:
  13725. case BfUnaryOp_Positive:
  13726. case BfUnaryOp_InvertBits:
  13727. // If we're expecting an int64 or uint64 then just leave the type as unknown
  13728. if ((mExpectingType != NULL) && (mExpectingType->IsInteger()) && (mExpectingType->mSize == 8))
  13729. mExpectingType = NULL;
  13730. // Otherwise keep expecting type
  13731. break;
  13732. default:
  13733. mExpectingType = NULL;
  13734. }
  13735. VisitChild(unaryOpExpr);
  13736. mExpectingType = prevExpedcting;
  13737. }
  13738. BfAstNode* propSrc = mPropSrc;
  13739. BfTypedValue propTarget = mPropTarget;
  13740. BfPropertyDef* propDef = mPropDef;
  13741. SizedArray<BfResolvedArg, 2> indexerVals = mIndexerValues;
  13742. BfTypedValue writeToProp;
  13743. GetResult();
  13744. if (!mResult)
  13745. return;
  13746. if (mResult.mType->IsRef())
  13747. mResult.mType = mResult.mType->GetUnderlyingType();
  13748. if (mResult.mType->IsVar())
  13749. {
  13750. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType);
  13751. return;
  13752. }
  13753. if ((mResult.mType->IsTypeInstance()) || (mResult.mType->IsGenericParam()))
  13754. {
  13755. SizedArray<BfResolvedArg, 1> args;
  13756. BfResolvedArg resolvedArg;
  13757. resolvedArg.mTypedValue = mResult;
  13758. args.push_back(resolvedArg);
  13759. BfMethodMatcher methodMatcher(opToken, mModule, "", args, NULL);
  13760. BfBaseClassWalker baseClassWalker(mResult.mType, NULL, mModule);
  13761. BfUnaryOp findOp = unaryOp;
  13762. bool isPostOp = false;
  13763. if (findOp == BfUnaryOp_PostIncrement)
  13764. {
  13765. findOp = BfUnaryOp_Increment;
  13766. isPostOp = true;
  13767. }
  13768. if (findOp == BfUnaryOp_PostDecrement)
  13769. {
  13770. findOp = BfUnaryOp_Decrement;
  13771. isPostOp = true;
  13772. }
  13773. BfType* bestSelfType = NULL;
  13774. while (true)
  13775. {
  13776. auto entry = baseClassWalker.Next();
  13777. auto checkType = entry.mTypeInstance;
  13778. if (checkType == NULL)
  13779. break;
  13780. for (auto operatorDef : checkType->mTypeDef->mOperators)
  13781. {
  13782. if (operatorDef->mOperatorDeclaration->mUnaryOp == findOp)
  13783. if (methodMatcher.CheckMethod(checkType, operatorDef, false))
  13784. methodMatcher.mSelfType = entry.mSrcType;
  13785. }
  13786. }
  13787. if (methodMatcher.mBestMethodDef != NULL)
  13788. {
  13789. if (!baseClassWalker.mMayBeFromInterface)
  13790. mModule->SetElementType(opToken, BfSourceElementType_Method);
  13791. auto methodDef = methodMatcher.mBestMethodDef;
  13792. auto autoComplete = GetAutoComplete();
  13793. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  13794. {
  13795. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  13796. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  13797. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  13798. }
  13799. SizedArray<BfExpression*, 2> argSrcs;
  13800. argSrcs.push_back(unaryOpExpr);
  13801. mResult = CreateCall(&methodMatcher, BfTypedValue());
  13802. if ((mResult.mType != NULL) && (methodMatcher.mSelfType != NULL) && (mResult.mType->IsSelf()))
  13803. {
  13804. BF_ASSERT(mModule->IsInGeneric());
  13805. mResult = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  13806. }
  13807. if (isPostOp)
  13808. mResult = args[0].mTypedValue;
  13809. return;
  13810. }
  13811. }
  13812. bool numericFail = false;
  13813. switch (unaryOp)
  13814. {
  13815. case BfUnaryOp_Not:
  13816. {
  13817. CheckResultForReading(mResult);
  13818. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  13819. auto value = mModule->LoadValue(mResult);
  13820. value = mModule->Cast(unaryOpExpr, value, boolType);
  13821. if (!value)
  13822. return;
  13823. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), boolType);
  13824. }
  13825. break;
  13826. case BfUnaryOp_Positive:
  13827. return;
  13828. case BfUnaryOp_Negate:
  13829. {
  13830. CheckResultForReading(mResult);
  13831. auto value = mModule->LoadValue(mResult);
  13832. if (!value)
  13833. return;
  13834. BfType* origType = value.mType;
  13835. if (value.mType->IsTypedPrimitive())
  13836. value.mType = value.mType->GetUnderlyingType();
  13837. if (value.mType->IsIntegral())
  13838. {
  13839. auto primType = (BfPrimitiveType*)value.mType;
  13840. auto wantType = primType;
  13841. auto constant = mModule->mBfIRBuilder->GetConstant(value.mValue);
  13842. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  13843. {
  13844. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (constant->mInt64 == 0x80000000LL))
  13845. {
  13846. mResult = BfTypedValue(mModule->GetConstValue32(-0x80000000LL), mModule->GetPrimitiveType(BfTypeCode_Int32));
  13847. return;
  13848. }
  13849. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt64) && (constant->mInt64 == 0x8000000000000000LL))
  13850. {
  13851. mResult = BfTypedValue(mModule->GetConstValue64(-0x8000000000000000LL), mModule->GetPrimitiveType(BfTypeCode_Int64));
  13852. return;
  13853. }
  13854. }
  13855. /*if (auto constantInt = dyn_cast<ConstantInt>((Value*)value.mValue))
  13856. {
  13857. int64 i64Val = constantInt->getSExtValue();
  13858. // This is a special case where the user entered -0x80000000 (maxint) but we thought "0x80000000" was a uint in the parser
  13859. // which would get upcasted to an int64 for this negate. Properly bring back down to an int32
  13860. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (i64Val == -0x80000000LL))
  13861. {
  13862. mResult = BfTypedValue(mModule->GetConstValue((int)i64Val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  13863. return;
  13864. }
  13865. }*/
  13866. if (!primType->IsSigned())
  13867. {
  13868. if (primType->mSize == 1)
  13869. wantType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  13870. else if (primType->mSize == 2)
  13871. wantType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  13872. else if (primType->mSize == 4)
  13873. wantType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  13874. else
  13875. mModule->Fail("Operator '-' cannot be applied to uint64", opToken);
  13876. }
  13877. if (primType != wantType)
  13878. {
  13879. value = mModule->Cast(unaryOpExpr, value, wantType, BfCastFlags_Explicit);
  13880. if (!value)
  13881. return;
  13882. }
  13883. if (origType->mSize == wantType->mSize) // Allow negative of primitive typed but not if we had to upsize
  13884. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  13885. else
  13886. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), wantType);
  13887. }
  13888. else if (value.mType->IsFloat())
  13889. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  13890. else
  13891. numericFail = true;
  13892. }
  13893. break;
  13894. case BfUnaryOp_InvertBits:
  13895. {
  13896. CheckResultForReading(mResult);
  13897. auto value = mModule->LoadValue(mResult);
  13898. if (!value)
  13899. return;
  13900. bool isInteger = value.mType->IsIntegral();
  13901. if (value.mType->IsTypedPrimitive())
  13902. isInteger = value.mType->GetUnderlyingType()->IsIntegral();
  13903. if (!isInteger)
  13904. {
  13905. mModule->Fail("Operator can only be used on integer types", opToken);
  13906. return;
  13907. }
  13908. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), value.mType);
  13909. }
  13910. break;
  13911. case BfUnaryOp_AddressOf:
  13912. {
  13913. MarkResultUsed();
  13914. mModule->FixIntUnknown(mResult);
  13915. auto ptrType = mModule->CreatePointerType(mResult.mType);
  13916. if ((!CheckModifyResult(mResult, unaryOpExpr, "take address of")) || (mResult.mType->IsValuelessType()))
  13917. {
  13918. // Sentinel value
  13919. auto val = mModule->mBfIRBuilder->CreateIntToPtr(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mModule->mBfIRBuilder->MapType(ptrType));
  13920. mResult = BfTypedValue(val, ptrType);
  13921. }
  13922. else
  13923. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  13924. }
  13925. break;
  13926. case BfUnaryOp_Dereference:
  13927. {
  13928. CheckResultForReading(mResult);
  13929. if (!mResult.mType->IsPointer())
  13930. {
  13931. mResult = BfTypedValue();
  13932. mModule->Fail("Cannot dereference non-pointer type", unaryOpExpr);
  13933. return;
  13934. }
  13935. auto derefTarget = mModule->LoadValue(mResult);
  13936. BfPointerType* pointerType = (BfPointerType*)derefTarget.mType;
  13937. auto resolvedType = mModule->ResolveType(pointerType->mElementType);
  13938. if (resolvedType == NULL)
  13939. {
  13940. mResult = BfTypedValue();
  13941. return;
  13942. }
  13943. if (resolvedType->IsValuelessType())
  13944. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedType, true);
  13945. else
  13946. mResult = BfTypedValue(derefTarget.mValue, resolvedType, true);
  13947. }
  13948. break;
  13949. case BfUnaryOp_PostIncrement:
  13950. case BfUnaryOp_Increment:
  13951. {
  13952. CheckResultForReading(mResult);
  13953. auto ptr = mResult;
  13954. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  13955. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "increment")))
  13956. return;
  13957. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  13958. BfIRValue origVal = origTypedVal.mValue;
  13959. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  13960. BfIRValue resultValue;
  13961. if (ptr.mType->IsPointer())
  13962. {
  13963. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  13964. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  13965. constValue = mModule->GetConstValue(ptrType->mElementType->GetStride(), intPtrType);
  13966. BfIRValue origIntValue = mModule->mBfIRBuilder->CreatePtrToInt(origVal, BfTypeCode_IntPtr);
  13967. BfIRValue newIntValue = mModule->mBfIRBuilder->CreateAdd(origIntValue, constValue/*, "inc"*/);
  13968. resultValue = mModule->mBfIRBuilder->CreateIntToPtr(newIntValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  13969. }
  13970. else
  13971. {
  13972. constValue = mModule->GetConstValue(1, ptr.mType);
  13973. if (!constValue)
  13974. {
  13975. numericFail = true;
  13976. break;
  13977. }
  13978. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()) || (ptr.mType->IsFloat()))
  13979. {
  13980. resultValue = mModule->mBfIRBuilder->CreateAdd(origVal, constValue/*, "inc"*/);
  13981. }
  13982. else
  13983. {
  13984. numericFail = true;
  13985. break;
  13986. }
  13987. }
  13988. if ((propDef != NULL) && (!ptr.IsAddr()))
  13989. writeToProp = BfTypedValue(resultValue, ptr.mType);
  13990. else
  13991. mModule->mBfIRBuilder->CreateStore(resultValue, ptr.mValue, mIsVolatileReference);
  13992. if (unaryOp == BfUnaryOp_PostIncrement)
  13993. mResult = BfTypedValue(origVal, ptr.mType, false);
  13994. else
  13995. mResult = BfTypedValue(resultValue, ptr.mType, false);
  13996. }
  13997. break;
  13998. case BfUnaryOp_PostDecrement:
  13999. case BfUnaryOp_Decrement:
  14000. {
  14001. CheckResultForReading(mResult);
  14002. auto ptr = mResult;
  14003. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  14004. //return;
  14005. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "decrement")))
  14006. return;
  14007. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  14008. BfIRValue origVal = origTypedVal.mValue;
  14009. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  14010. BfIRValue resultValue;
  14011. if (ptr.mType->IsPointer())
  14012. {
  14013. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  14014. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  14015. constValue = mModule->GetConstValue(ptrType->mElementType->GetStride(), intPtrType);
  14016. BfIRValue origIntValue = mModule->mBfIRBuilder->CreatePtrToInt(origVal, BfTypeCode_IntPtr);
  14017. BfIRValue newIntValue = mModule->mBfIRBuilder->CreateSub(origIntValue, constValue);
  14018. resultValue = mModule->mBfIRBuilder->CreateIntToPtr(newIntValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  14019. }
  14020. else
  14021. {
  14022. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  14023. if (!constValue)
  14024. {
  14025. numericFail = true;
  14026. break;
  14027. }
  14028. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()))
  14029. {
  14030. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  14031. }
  14032. else if (ptr.mType->IsFloat())
  14033. {
  14034. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  14035. }
  14036. else
  14037. {
  14038. numericFail = true;
  14039. break;
  14040. }
  14041. }
  14042. if ((propDef != NULL) && (!ptr.IsAddr()))
  14043. writeToProp = BfTypedValue(resultValue, ptr.mType);
  14044. else
  14045. mModule->mBfIRBuilder->CreateStore(resultValue, ptr.mValue, mIsVolatileReference);
  14046. if (unaryOp == BfUnaryOp_PostDecrement)
  14047. mResult = BfTypedValue(origVal, ptr.mType, false);
  14048. else
  14049. mResult = BfTypedValue(resultValue, ptr.mType, false);
  14050. }
  14051. break;
  14052. case BfUnaryOp_Ref:
  14053. case BfUnaryOp_Mut:
  14054. {
  14055. if (mAllowReadOnlyReference)
  14056. {
  14057. if (mResult.mKind == BfTypedValueKind_ReadOnlyAddr)
  14058. mResult.mKind = BfTypedValueKind_Addr;
  14059. }
  14060. CheckResultForReading(mResult);
  14061. if ((unaryOp == BfUnaryOp_Mut) && (!mResult.mType->IsComposite()) && (!mResult.mType->IsGenericParam()))
  14062. {
  14063. // Non-composite types are already mutable, leave them alone...
  14064. break;
  14065. }
  14066. if ((unaryOp != BfUnaryOp_Mut) || (mResult.mKind != BfTypedValueKind_MutableValue))
  14067. {
  14068. if (!CheckModifyResult(mResult, unaryOpExpr, StrFormat("use '%s' on", BfGetOpName(unaryOp)).c_str()))
  14069. {
  14070. // Just leave the non-ref version in mResult
  14071. return;
  14072. }
  14073. }
  14074. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowRefExpr) == 0)
  14075. {
  14076. mModule->Fail(StrFormat("Invalid usage of '%s' expression", BfGetOpName(unaryOp)), opToken);
  14077. return;
  14078. }
  14079. ResolveGenericType();
  14080. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, (unaryOp == BfUnaryOp_Ref) ? BfRefType::RefKind_Ref : BfRefType::RefKind_Mut));
  14081. }
  14082. break;
  14083. case BfUnaryOp_Out:
  14084. {
  14085. if (!CheckModifyResult(mResult, unaryOpExpr, "use 'out' on"))
  14086. {
  14087. // Just leave the non-ref version in mResult
  14088. return;
  14089. }
  14090. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowOutExpr) == 0)
  14091. {
  14092. mModule->Fail("Invalid usage of 'out' expression", opToken);
  14093. return;
  14094. }
  14095. MarkResultAssigned();
  14096. MarkResultUsed();
  14097. ResolveGenericType();
  14098. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, BfRefType::RefKind_Out));
  14099. }
  14100. break;
  14101. case BfUnaryOp_Params:
  14102. {
  14103. bool allowParams = (mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) != 0;
  14104. if (mResultLocalVar == NULL)
  14105. allowParams = false;
  14106. if (allowParams)
  14107. {
  14108. if (mResultLocalVar->mCompositeCount >= 0) // Delegate params
  14109. {
  14110. allowParams = true;
  14111. }
  14112. else
  14113. {
  14114. auto isValid = false;
  14115. auto genericTypeInst = mResult.mType->ToGenericTypeInstance();
  14116. if ((genericTypeInst != NULL) && (genericTypeInst->mTypeDef == mModule->mCompiler->mSpanTypeDef))
  14117. isValid = true;
  14118. else if (mResult.mType->IsArray())
  14119. isValid = true;
  14120. if (!isValid)
  14121. {
  14122. mModule->Fail(StrFormat("A 'params' expression cannot be used on type '%s'", mModule->TypeToString(mResult.mType).c_str()), opToken);
  14123. }
  14124. }
  14125. }
  14126. if (allowParams)
  14127. {
  14128. mResult = mModule->LoadValue(mResult);
  14129. if (mResult.IsSplat())
  14130. mResult.mKind = BfTypedValueKind_ParamsSplat;
  14131. else
  14132. mResult.mKind = BfTypedValueKind_Params;
  14133. }
  14134. else
  14135. {
  14136. mModule->Fail("Illegal use of 'params' expression", opToken);
  14137. }
  14138. }
  14139. break;
  14140. default:
  14141. mModule->Fail("INTERNAL ERROR: Unhandled unary operator", unaryOpExpr);
  14142. break;
  14143. }
  14144. if (numericFail)
  14145. {
  14146. mModule->Fail("Operator can only be used on numeric types", opToken);
  14147. mResult = BfTypedValue();
  14148. }
  14149. if (writeToProp)
  14150. {
  14151. auto setMethod = GetPropertyMethodDef(propDef, BfMethodType_PropertySetter, mPropCheckedKind);
  14152. if (setMethod == NULL)
  14153. {
  14154. mModule->Fail("Property has no setter", propSrc);
  14155. return;
  14156. }
  14157. auto methodInstance = GetPropertyMethodInstance(setMethod);
  14158. if (!methodInstance.mFunc)
  14159. return;
  14160. if (propSrc != NULL)
  14161. mModule->UpdateExprSrcPos(propSrc);
  14162. SizedArray<BfIRValue, 4> args;
  14163. if (!setMethod->mIsStatic)
  14164. PushThis(propSrc, propTarget, methodInstance.mMethodInstance, args);
  14165. //args.push_back(propTarget.mValue);
  14166. for (int paramIdx = 0; paramIdx < (int)indexerVals.size(); paramIdx++)
  14167. {
  14168. auto val = mModule->Cast(propSrc, indexerVals[paramIdx].mTypedValue, methodInstance.mMethodInstance->GetParamType(paramIdx));
  14169. if (!val)
  14170. return;
  14171. PushArg(val, args);
  14172. }
  14173. PushArg(writeToProp, args);
  14174. CreateCall(methodInstance.mMethodInstance, methodInstance.mFunc, false, args);
  14175. }
  14176. }
  14177. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue)
  14178. {
  14179. BfTypedValue rightValue;
  14180. if (rightExpression == NULL)
  14181. {
  14182. mModule->AssertErrorState();
  14183. return;
  14184. }
  14185. if (!leftValue)
  14186. {
  14187. if (!rightValue)
  14188. mModule->CreateValueFromExpression(rightExpression);
  14189. return;
  14190. }
  14191. if (leftValue.mType->IsRef())
  14192. leftValue.mType = leftValue.mType->GetUnderlyingType();
  14193. if ((binaryOp == BfBinaryOp_ConditionalAnd) || (binaryOp == BfBinaryOp_ConditionalOr))
  14194. {
  14195. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  14196. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  14197. bool isAnd = binaryOp == BfBinaryOp_ConditionalAnd;
  14198. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  14199. leftValue = mModule->Cast(leftExpression, leftValue, boolType);
  14200. if (!leftValue)
  14201. {
  14202. mModule->CreateValueFromExpression(rightExpression);
  14203. return;
  14204. }
  14205. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  14206. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mInConditionalBlock, true);
  14207. // The RHS is not guaranteed to be executed
  14208. if ((mModule->mCurMethodState->mDeferredLocalAssignData != NULL) &&
  14209. (mModule->mCurMethodState->mDeferredLocalAssignData->mIsIfCondition))
  14210. mModule->mCurMethodState->mDeferredLocalAssignData->mIfMayBeSkipped = true;
  14211. if (isAnd)
  14212. {
  14213. bool isConstBranch = false;
  14214. bool constResult = false;
  14215. if (leftValue.mValue.IsConst())
  14216. {
  14217. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  14218. if (constValue->mTypeCode == BfTypeCode_Boolean)
  14219. {
  14220. isConstBranch = true;
  14221. constResult = constValue->mBool;
  14222. }
  14223. }
  14224. if (isConstBranch)
  14225. {
  14226. if ((constResult) || (HasVariableDeclaration(rightExpression)))
  14227. {
  14228. // Only right side
  14229. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  14230. mResult = rightValue;
  14231. }
  14232. else
  14233. {
  14234. // Always false
  14235. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  14236. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  14237. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolType);
  14238. }
  14239. }
  14240. else
  14241. {
  14242. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("land.rhs");
  14243. auto endBB = mModule->mBfIRBuilder->CreateBlock("land.end");
  14244. // This makes any 'scope' allocs be dyn since we aren't sure if this will be short-circuited
  14245. SetAndRestoreValue<bool> prevIsConditional(mModule->mCurMethodState->mCurScope->mIsConditional, true);
  14246. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, rhsBB, endBB);
  14247. mModule->AddBasicBlock(rhsBB);
  14248. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  14249. mModule->mBfIRBuilder->CreateBr(endBB);
  14250. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  14251. mModule->AddBasicBlock(endBB);
  14252. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  14253. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(0, boolType), prevBB);
  14254. if (rightValue)
  14255. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  14256. mResult = BfTypedValue(phi, boolType);
  14257. }
  14258. }
  14259. else
  14260. {
  14261. // Put variables in here into a 'possibly assigned' but never commit it.
  14262. // Because if we had "if ((Get(out a)) || (GetOther(out a))" then the LHS would already set it as defined, so
  14263. // the RHS is inconsequential
  14264. BfDeferredLocalAssignData deferredLocalAssignData;
  14265. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData, false);
  14266. deferredLocalAssignData.mVarIdBarrier = mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  14267. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mModule->mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  14268. bool isConstBranch = false;
  14269. bool constResult = false;
  14270. if (leftValue.mValue.IsConst())
  14271. {
  14272. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  14273. if (constValue->mTypeCode == BfTypeCode_Boolean)
  14274. {
  14275. isConstBranch = true;
  14276. constResult = constValue->mBool;
  14277. }
  14278. }
  14279. if (isConstBranch)
  14280. {
  14281. if ((constResult) && (!HasVariableDeclaration(rightExpression)))
  14282. {
  14283. // Always true
  14284. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  14285. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  14286. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  14287. }
  14288. else
  14289. {
  14290. // Only right side
  14291. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  14292. mResult = rightValue;
  14293. }
  14294. }
  14295. else
  14296. {
  14297. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("lor.rhs");
  14298. auto endBB = mModule->mBfIRBuilder->CreateBlock("lor.end");
  14299. // This makes any 'scope' allocs be dyn since we aren't sure if this will be short-circuited
  14300. SetAndRestoreValue<bool> prevIsConditional(mModule->mCurMethodState->mCurScope->mIsConditional, true);
  14301. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, endBB, rhsBB);
  14302. mModule->AddBasicBlock(rhsBB);
  14303. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType);
  14304. mModule->mBfIRBuilder->CreateBr(endBB);
  14305. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  14306. mModule->AddBasicBlock(endBB);
  14307. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  14308. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(1, boolType), prevBB);
  14309. if (rightValue)
  14310. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  14311. mResult = BfTypedValue(phi, boolType);
  14312. }
  14313. }
  14314. return;
  14315. }
  14316. BfType* wantType = leftValue.mType;
  14317. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  14318. wantType = NULL; // Don't presume
  14319. rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, BfEvalExprFlags_NoCast);
  14320. if ((!leftValue) || (!rightValue))
  14321. return;
  14322. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue);
  14323. }
  14324. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags)
  14325. {
  14326. BfTypedValue leftValue;
  14327. if (leftExpression != NULL)
  14328. {
  14329. leftValue = mModule->CreateValueFromExpression(leftExpression, mExpectingType, (BfEvalExprFlags)(BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  14330. }
  14331. return PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue);
  14332. }
  14333. bool BfExprEvaluator::CheckConstCompare(BfBinaryOp binaryOp, BfAstNode* opToken, const BfTypedValue& leftValue, const BfTypedValue& rightValue)
  14334. {
  14335. if ((binaryOp < BfBinaryOp_Equality) || (binaryOp > BfBinaryOp_LessThanOrEqual))
  14336. return false;
  14337. // LHS is expected to be a value and RHS is expected to be a const
  14338. if (!leftValue.mType->IsIntegral())
  14339. return false;
  14340. BF_ASSERT(rightValue.mValue.IsConst());
  14341. auto rightConst = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  14342. if (!mModule->mBfIRBuilder->IsInt(rightConst->mTypeCode))
  14343. return false;
  14344. BfType* checkType = leftValue.mType;
  14345. if (checkType->IsTypedPrimitive())
  14346. checkType = checkType->GetUnderlyingType();
  14347. if (!checkType->IsPrimitiveType())
  14348. return false;
  14349. BfTypeCode typeCode = ((BfPrimitiveType*)checkType)->mTypeDef->mTypeCode;
  14350. int64 minValue = 0;
  14351. int64 maxValue = 0;
  14352. switch (typeCode)
  14353. {
  14354. case BfTypeCode_Int8:
  14355. minValue = -0x80;
  14356. maxValue = 0x7F;
  14357. break;
  14358. case BfTypeCode_Int16:
  14359. minValue = -0x8000;
  14360. maxValue = 0x7FFF;
  14361. break;
  14362. case BfTypeCode_Int32:
  14363. minValue = -0x80000000LL;
  14364. maxValue = 0x7FFFFFFF;
  14365. break;
  14366. case BfTypeCode_Int64:
  14367. minValue = -0x8000000000000000LL;
  14368. maxValue = 0x7FFFFFFFFFFFFFFFLL;
  14369. break;
  14370. case BfTypeCode_UInt8:
  14371. maxValue = 0xFF;
  14372. break;
  14373. case BfTypeCode_UInt16:
  14374. maxValue = 0xFFFF;
  14375. break;
  14376. case BfTypeCode_UInt32:
  14377. maxValue = 0xFFFFFFFF;
  14378. break;
  14379. default:
  14380. return false;
  14381. }
  14382. int constResult = -1;
  14383. if (typeCode == BfTypeCode_UInt64)
  14384. {
  14385. switch (binaryOp)
  14386. {
  14387. case BfBinaryOp_Equality:
  14388. if (rightConst->mInt64 < minValue)
  14389. constResult = 0;
  14390. break;
  14391. case BfBinaryOp_InEquality:
  14392. if (rightConst->mInt64 < minValue)
  14393. constResult = 1;
  14394. break;
  14395. case BfBinaryOp_LessThan:
  14396. if (rightConst->mInt64 <= minValue)
  14397. constResult = 0;
  14398. break;
  14399. case BfBinaryOp_LessThanOrEqual:
  14400. if (rightConst->mInt64 < minValue)
  14401. constResult = 0;
  14402. break;
  14403. default: break;
  14404. }
  14405. return false;
  14406. }
  14407. else
  14408. {
  14409. switch (binaryOp)
  14410. {
  14411. case BfBinaryOp_Equality:
  14412. if (rightConst->mInt64 < minValue)
  14413. constResult = 0;
  14414. else if (rightConst->mInt64 > maxValue)
  14415. constResult = 0;
  14416. break;
  14417. case BfBinaryOp_InEquality:
  14418. if (rightConst->mInt64 < minValue)
  14419. constResult = 1;
  14420. else if (rightConst->mInt64 > maxValue)
  14421. constResult = 1;
  14422. break;
  14423. case BfBinaryOp_LessThan:
  14424. if (rightConst->mInt64 <= minValue)
  14425. constResult = 0;
  14426. else if (rightConst->mInt64 > maxValue)
  14427. constResult = 1;
  14428. break;
  14429. case BfBinaryOp_LessThanOrEqual:
  14430. if (rightConst->mInt64 < minValue)
  14431. constResult = 0;
  14432. else if (rightConst->mInt64 >= maxValue)
  14433. constResult = 1;
  14434. break;
  14435. case BfBinaryOp_GreaterThan:
  14436. if (rightConst->mInt64 >= maxValue)
  14437. constResult = 0;
  14438. else if (rightConst->mInt64 < minValue)
  14439. constResult = 1;
  14440. break;
  14441. case BfBinaryOp_GreaterThanOrEqual:
  14442. if (rightConst->mInt64 > maxValue)
  14443. constResult = 0;
  14444. else if (rightConst->mInt64 <= minValue)
  14445. constResult = 1;
  14446. break;
  14447. default: break;
  14448. }
  14449. }
  14450. if (constResult == 0)
  14451. {
  14452. mModule->Warn(0, "The result of this operation is always 'false'", opToken);
  14453. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  14454. return true;
  14455. }
  14456. else if (constResult == 1)
  14457. {
  14458. mModule->Warn(0, "The result of this operation is always 'true'", opToken);
  14459. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  14460. return true;
  14461. }
  14462. return false;
  14463. }
  14464. void BfExprEvaluator::PerformBinaryOperation(BfAstNode* leftExpression, BfAstNode* rightExpression, BfBinaryOp binaryOp, BfAstNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue, BfTypedValue rightValue)
  14465. {
  14466. bool noClassify = (flags & BfBinOpFlag_NoClassify) != 0;
  14467. bool forceLeftType = (flags & BfBinOpFlag_ForceLeftType) != 0;
  14468. if ((rightValue.mValue.IsConst()) && (!leftValue.mValue.IsConst()))
  14469. {
  14470. if (CheckConstCompare(binaryOp, opToken, leftValue, rightValue))
  14471. return;
  14472. }
  14473. else if ((leftValue.mValue.IsConst()) && (!rightValue.mValue.IsConst()))
  14474. {
  14475. if (CheckConstCompare(GetOppositeBinaryOp(binaryOp), opToken, rightValue, leftValue))
  14476. return;
  14477. }
  14478. if ((binaryOp == BfBinaryOp_NullCoalesce) && ((leftValue.mType->IsPointer()) || (leftValue.mType->IsObject())))
  14479. {
  14480. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  14481. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("nullc.rhs");
  14482. auto endBB = mModule->mBfIRBuilder->CreateBlock("nullc.end");
  14483. auto isNull = mModule->mBfIRBuilder->CreateIsNull(leftValue.mValue);
  14484. mModule->mBfIRBuilder->CreateCondBr(isNull, rhsBB, endBB);
  14485. mModule->AddBasicBlock(rhsBB);
  14486. if (!rightValue)
  14487. {
  14488. mModule->AssertErrorState();
  14489. return;
  14490. }
  14491. else
  14492. {
  14493. auto rightToLeftValue = mModule->CastToValue(rightExpression, rightValue, leftValue.mType, BfCastFlags_SilentFail);
  14494. if (rightToLeftValue)
  14495. {
  14496. rightValue = BfTypedValue(rightToLeftValue, leftValue.mType);
  14497. }
  14498. else
  14499. {
  14500. auto leftToRightValue = mModule->CastToValue(leftExpression, leftValue, rightValue.mType, BfCastFlags_SilentFail);
  14501. if (leftToRightValue)
  14502. {
  14503. leftValue = BfTypedValue(leftToRightValue, rightValue.mType);
  14504. }
  14505. else
  14506. {
  14507. // Note: Annoying trigraph split for '??'
  14508. mModule->Fail(StrFormat("Operator '?" "?' cannot be applied to operands of type '%s' and '%s'",
  14509. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  14510. leftValue = mModule->GetDefaultTypedValue(rightValue.mType);
  14511. }
  14512. }
  14513. }
  14514. mModule->mBfIRBuilder->CreateBr(endBB);
  14515. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  14516. mModule->AddBasicBlock(endBB);
  14517. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(leftValue.mType), 2);
  14518. mModule->mBfIRBuilder->AddPhiIncoming(phi, leftValue.mValue, prevBB);
  14519. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  14520. mResult = BfTypedValue(phi, leftValue.mType);
  14521. return;
  14522. }
  14523. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  14524. {
  14525. forceLeftType = true;
  14526. }
  14527. if (rightValue.mType->IsRef())
  14528. rightValue.mType = rightValue.mType->GetUnderlyingType();
  14529. mModule->FixIntUnknown(leftValue, rightValue);
  14530. // Prefer floats, prefer chars
  14531. int leftCompareSize = leftValue.mType->mSize;
  14532. if (leftValue.mType->IsFloat())
  14533. leftCompareSize += 0x10;
  14534. if (leftValue.mType->IsChar())
  14535. leftCompareSize += 0x100;
  14536. if (!leftValue.mType->IsPrimitiveType())
  14537. leftCompareSize += 0x1000;
  14538. int rightCompareSize = rightValue.mType->mSize;
  14539. if (rightValue.mType->IsFloat())
  14540. rightCompareSize += 0x10;
  14541. if (rightValue.mType->IsChar())
  14542. rightCompareSize += 0x100;
  14543. if (!rightValue.mType->IsPrimitiveType())
  14544. rightCompareSize += 0x1000;
  14545. if ((leftValue.mType->IsTypeInstance()) && (rightValue.mType->IsTypeInstance()))
  14546. {
  14547. int leftInheritDepth = leftValue.mType->ToTypeInstance()->mInheritDepth;
  14548. int rightInheritDepth = rightValue.mType->ToTypeInstance()->mInheritDepth;
  14549. if (leftInheritDepth < rightInheritDepth)
  14550. {
  14551. // If both are type instances then choose the type with the lowest inherit depth
  14552. // so we will choose the base type when applicable
  14553. forceLeftType = true;
  14554. }
  14555. }
  14556. auto resultType = leftValue.mType;
  14557. if (!forceLeftType)
  14558. {
  14559. bool handled = false;
  14560. // If one of these is a constant that can be converted into a smaller type, then do that
  14561. if (rightValue.mValue.IsConst())
  14562. {
  14563. if (mModule->CanImplicitlyCast(rightValue, leftValue.mType))
  14564. {
  14565. resultType = leftValue.mType;
  14566. handled = true;
  14567. }
  14568. }
  14569. // If left is an IntUnknown, allow the right to inform the type
  14570. if (leftValue.mType->IsIntUnknown())
  14571. {
  14572. if (leftValue.mValue.IsConst())
  14573. {
  14574. if (mModule->CanImplicitlyCast(leftValue, rightValue.mType))
  14575. {
  14576. resultType = rightValue.mType;
  14577. handled = true;
  14578. }
  14579. }
  14580. }
  14581. if (!handled)
  14582. {
  14583. if ((resultType->IsNull()) ||
  14584. (rightCompareSize > leftCompareSize) ||
  14585. (((rightCompareSize == leftCompareSize) && (!rightValue.mType->IsSigned()))) ||
  14586. (rightValue.mType->IsTypedPrimitive()))
  14587. {
  14588. // Select the type with the "most information"
  14589. if (!rightValue.mType->IsNull())
  14590. resultType = rightValue.mType;
  14591. }
  14592. if ((!resultType->IsPointer()) && (rightValue.mType->IsPointer()))
  14593. resultType = rightValue.mType;
  14594. }
  14595. }
  14596. bool explicitCast = false;
  14597. BfTypedValue* resultTypedValue;
  14598. BfTypedValue* otherTypedValue;
  14599. BfType* otherType;
  14600. BfAstNode* resultTypeSrc;
  14601. BfAstNode* otherTypeSrc;
  14602. if (resultType == leftValue.mType)
  14603. {
  14604. resultTypedValue = &leftValue;
  14605. resultTypeSrc = leftExpression;
  14606. otherTypedValue = &rightValue;
  14607. otherTypeSrc = rightExpression;
  14608. otherType = otherTypedValue->mType;
  14609. }
  14610. else
  14611. {
  14612. resultTypedValue = &rightValue;
  14613. resultTypeSrc = rightExpression;
  14614. otherTypedValue = &leftValue;
  14615. otherTypeSrc = leftExpression;
  14616. otherType = otherTypedValue->mType;
  14617. }
  14618. auto _OpFail = [&]()
  14619. {
  14620. if ((rightValue.mType != NULL) && (leftValue.mType != NULL))
  14621. {
  14622. if (rightValue.mType != leftValue.mType)
  14623. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between types '%s' and '%s'",
  14624. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  14625. else
  14626. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between two instances of type '%s'",
  14627. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  14628. }
  14629. else
  14630. mModule->Fail(StrFormat("Cannot perform binary operation '%s'", BfGetOpName(binaryOp)), opToken);
  14631. };
  14632. // This case fixes cases like "c == 0" where "0" is technically an int but can be reduced
  14633. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  14634. {
  14635. if ((resultType != otherType) && (resultTypedValue->mValue.IsConst()) && (mModule->CanImplicitlyCast(*resultTypedValue, otherType)))
  14636. {
  14637. std::swap(resultTypedValue, otherTypedValue);
  14638. std::swap(resultTypeSrc, otherTypeSrc);
  14639. std::swap(resultType, otherType);
  14640. }
  14641. }
  14642. BfIRValue convLeftValue;
  14643. BfIRValue convRightValue;
  14644. if ((resultType->IsVar()) || (otherType->IsVar()))
  14645. {
  14646. mResult = BfTypedValue(mModule->GetDefaultValue(resultType), mModule->GetPrimitiveType(BfTypeCode_Var));
  14647. return;
  14648. }
  14649. if ((otherType->IsNull()) && ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality)))
  14650. {
  14651. bool isEquality = (binaryOp == BfBinaryOp_Equality);
  14652. if ((resultType->IsValueType()) && (!resultType->IsFunction()))
  14653. {
  14654. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  14655. if (resultType->IsNullable())
  14656. {
  14657. auto elementType = resultType->GetUnderlyingType();
  14658. if (elementType->IsValuelessType())
  14659. {
  14660. mModule->mBfIRBuilder->PopulateType(resultType);
  14661. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  14662. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 1);
  14663. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  14664. if (isEquality)
  14665. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  14666. mResult = BfTypedValue(hasValueValue, boolType);
  14667. }
  14668. else
  14669. {
  14670. mModule->mBfIRBuilder->PopulateType(resultType);
  14671. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  14672. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 2);
  14673. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateLoad(hasValuePtr);
  14674. if (isEquality)
  14675. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  14676. mResult = BfTypedValue(hasValueValue, boolType);
  14677. }
  14678. return;
  14679. }
  14680. if (resultType->IsNull())
  14681. {
  14682. // Null always equals null
  14683. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 1 : 0, boolType), boolType);
  14684. return;
  14685. }
  14686. if (!mModule->IsInSpecializedSection())
  14687. {
  14688. //CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type '<null>'
  14689. mModule->Warn(BfWarning_CS0472_ValueTypeNullCompare,
  14690. StrFormat("The result of the expression is always '%s' since a value of type '%s' can never be null",
  14691. isEquality ? "false" : "true", mModule->TypeToString(resultType).c_str()), otherTypeSrc);
  14692. }
  14693. // Valuetypes never equal null
  14694. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 0 : 1, boolType), boolType);
  14695. return;
  14696. }
  14697. }
  14698. if ((leftValue.mType->IsTypeInstance()) || (leftValue.mType->IsGenericParam()) ||
  14699. (rightValue.mType->IsTypeInstance()) || (rightValue.mType->IsGenericParam()))
  14700. {
  14701. // As an optimization, we don't call user operator overloads for null checks
  14702. bool skipOpOverload = false;
  14703. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  14704. {
  14705. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  14706. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  14707. if ((leftConstant != NULL) && (leftConstant->IsNull()))
  14708. skipOpOverload = true;
  14709. if ((rightConstant != NULL) && (rightConstant->IsNull()))
  14710. skipOpOverload = true;
  14711. }
  14712. if (!skipOpOverload)
  14713. {
  14714. BfBinaryOp findBinaryOp = binaryOp;
  14715. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  14716. for (int pass = 0; pass < 2; pass++)
  14717. {
  14718. bool foundOp = false;
  14719. SizedArray<BfResolvedArg, 2> args;
  14720. BfResolvedArg leftArg;
  14721. leftArg.mExpression = leftExpression;
  14722. leftArg.mTypedValue = leftValue;
  14723. BfResolvedArg rightArg;
  14724. rightArg.mExpression = rightExpression;
  14725. rightArg.mTypedValue = rightValue;
  14726. if (pass == 0)
  14727. {
  14728. args.push_back(leftArg);
  14729. args.push_back(rightArg);
  14730. }
  14731. else
  14732. {
  14733. args.push_back(rightArg);
  14734. args.push_back(leftArg);
  14735. }
  14736. BfMethodMatcher methodMatcher(opToken, mModule, "", args, NULL);
  14737. BfBaseClassWalker baseClassWalker(leftValue.mType, rightValue.mType, mModule);
  14738. bool invertResult = false;
  14739. BfBinaryOp oppositeBinaryOp = GetOppositeBinaryOp(findBinaryOp);
  14740. while (true)
  14741. {
  14742. auto entry = baseClassWalker.Next();
  14743. auto checkType = entry.mTypeInstance;
  14744. if (checkType == NULL)
  14745. break;
  14746. bool foundExactMatch = false;
  14747. Array<BfMethodDef*> oppositeOperatorDefs;
  14748. for (auto operatorDef : checkType->mTypeDef->mOperators)
  14749. {
  14750. bool allowOp = operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp;
  14751. if ((isComparison) && (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare))
  14752. allowOp = true;
  14753. if (allowOp)
  14754. {
  14755. foundOp = true;
  14756. if (methodMatcher.CheckMethod(checkType, operatorDef, false))
  14757. {
  14758. methodMatcher.mSelfType = entry.mSrcType;
  14759. if (operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp)
  14760. foundExactMatch = true;
  14761. }
  14762. }
  14763. else if (operatorDef->mOperatorDeclaration->mBinOp == oppositeBinaryOp)
  14764. oppositeOperatorDefs.Add(operatorDef);
  14765. }
  14766. if (((methodMatcher.mBestMethodDef == NULL) || (!foundExactMatch)) && (!oppositeOperatorDefs.IsEmpty()))
  14767. {
  14768. foundOp = true;
  14769. for (auto oppositeOperatorDef : oppositeOperatorDefs)
  14770. {
  14771. if (methodMatcher.CheckMethod(checkType, oppositeOperatorDef, false))
  14772. methodMatcher.mSelfType = entry.mSrcType;
  14773. }
  14774. }
  14775. }
  14776. if (methodMatcher.mBestMethodDef != NULL)
  14777. {
  14778. methodMatcher.FlushAmbiguityError();
  14779. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  14780. bool invertResult = matchedOp == oppositeBinaryOp;
  14781. auto methodDef = methodMatcher.mBestMethodDef;
  14782. auto autoComplete = GetAutoComplete();
  14783. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  14784. {
  14785. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  14786. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  14787. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  14788. }
  14789. if (opToken != NULL)
  14790. {
  14791. if ((opToken->IsA<BfTokenNode>()) && (!noClassify) && (!baseClassWalker.mMayBeFromInterface))
  14792. mModule->SetElementType(opToken, BfSourceElementType_Method);
  14793. }
  14794. mResult = CreateCall(&methodMatcher, BfTypedValue());
  14795. if ((mResult.mType != NULL) && (methodMatcher.mSelfType != NULL) && (mResult.mType->IsSelf()))
  14796. {
  14797. BF_ASSERT(mModule->IsInGeneric());
  14798. mResult = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  14799. }
  14800. if ((invertResult) && (mResult.mType == mModule->GetPrimitiveType(BfTypeCode_Boolean)))
  14801. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  14802. if (pass == 1)
  14803. {
  14804. if (findBinaryOp == BfBinaryOp_Compare)
  14805. {
  14806. mResult = mModule->LoadValue(mResult);
  14807. if (mResult.mType->IsIntegral())
  14808. mResult.mValue = mModule->mBfIRBuilder->CreateNeg(mResult.mValue);
  14809. }
  14810. }
  14811. if ((isComparison) && (matchedOp == BfBinaryOp_Compare))
  14812. {
  14813. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  14814. mResult = mModule->LoadValue(mResult);
  14815. if (mResult.mType != intType)
  14816. mResult = mModule->GetDefaultTypedValue(intType);
  14817. auto zeroVal = mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  14818. auto useBinaryOp = binaryOp;
  14819. if (pass == 1)
  14820. useBinaryOp = GetFlippedBinaryOp(useBinaryOp);
  14821. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  14822. switch (useBinaryOp)
  14823. {
  14824. case BfBinaryOp_Equality:
  14825. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mResult.mValue, zeroVal), boolType);
  14826. break;
  14827. case BfBinaryOp_InEquality:
  14828. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mResult.mValue, zeroVal), boolType);
  14829. break;
  14830. case BfBinaryOp_GreaterThan:
  14831. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(mResult.mValue, zeroVal, true), boolType);
  14832. break;
  14833. case BfBinaryOp_LessThan:
  14834. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(mResult.mValue, zeroVal, true), boolType);
  14835. break;
  14836. case BfBinaryOp_GreaterThanOrEqual:
  14837. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(mResult.mValue, zeroVal, true), boolType);
  14838. break;
  14839. case BfBinaryOp_LessThanOrEqual:
  14840. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(mResult.mValue, zeroVal, true), boolType);
  14841. break;
  14842. default: break;
  14843. }
  14844. }
  14845. return;
  14846. }
  14847. if ((!foundOp) || (pass == 1))
  14848. break;
  14849. switch (findBinaryOp)
  14850. {
  14851. case BfBinaryOp_Add:
  14852. case BfBinaryOp_Multiply:
  14853. case BfBinaryOp_Equality:
  14854. case BfBinaryOp_InEquality:
  14855. case BfBinaryOp_BitwiseAnd:
  14856. case BfBinaryOp_BitwiseOr:
  14857. case BfBinaryOp_ConditionalAnd:
  14858. case BfBinaryOp_ConditionalOr:
  14859. case BfBinaryOp_Compare:
  14860. // Still works
  14861. break;
  14862. case BfBinaryOp_LessThan:
  14863. findBinaryOp = BfBinaryOp_GreaterThanOrEqual;
  14864. break;
  14865. case BfBinaryOp_LessThanOrEqual:
  14866. findBinaryOp = BfBinaryOp_GreaterThan;
  14867. break;
  14868. case BfBinaryOp_GreaterThan:
  14869. findBinaryOp = BfBinaryOp_LessThanOrEqual;
  14870. break;
  14871. case BfBinaryOp_GreaterThanOrEqual:
  14872. findBinaryOp = BfBinaryOp_LessThan;
  14873. break;
  14874. default:
  14875. findBinaryOp = BfBinaryOp_None;
  14876. break;
  14877. }
  14878. if (findBinaryOp == BfBinaryOp_None)
  14879. break;
  14880. }
  14881. }
  14882. }
  14883. if (mModule->IsUnboundGeneric(resultType))
  14884. {
  14885. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  14886. return;
  14887. }
  14888. if (resultType->IsPointer() && otherType->IsPointer())
  14889. {
  14890. //TODO: Allow all pointer comparisons, but only allow SUBTRACTION between equal pointer types
  14891. if (binaryOp == BfBinaryOp_Subtract)
  14892. {
  14893. if (resultType != otherType)
  14894. {
  14895. mModule->Fail(StrFormat("Operands must be the same type, '%s' doesn't match '%s'",
  14896. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()),
  14897. opToken);
  14898. return;
  14899. }
  14900. BfPointerType* resultPointerType = (BfPointerType*)resultType;
  14901. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  14902. convLeftValue = mModule->CastToValue(leftExpression, leftValue, intPtrType, BfCastFlags_Explicit);
  14903. convRightValue = mModule->CastToValue(rightExpression, rightValue, intPtrType, BfCastFlags_Explicit);
  14904. BfIRValue diffValue = mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue);
  14905. diffValue = mModule->mBfIRBuilder->CreateDiv(diffValue, mModule->GetConstValue(resultPointerType->mElementType->mSize, intPtrType), true);
  14906. mResult = BfTypedValue(diffValue, intPtrType);
  14907. return;
  14908. }
  14909. else if ((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_InEquality) &&
  14910. (binaryOp != BfBinaryOp_LessThan) && (binaryOp != BfBinaryOp_LessThanOrEqual) &&
  14911. (binaryOp != BfBinaryOp_GreaterThan) && (binaryOp != BfBinaryOp_GreaterThanOrEqual))
  14912. {
  14913. mModule->Fail("Invalid operation on pointers", opToken);
  14914. return;
  14915. }
  14916. if (((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_InEquality)) ||
  14917. (resultType != otherType))
  14918. {
  14919. resultType = mModule->GetPrimitiveType(BfTypeCode_UIntPtr);
  14920. explicitCast = true;
  14921. }
  14922. }
  14923. else if (resultType->IsPointer())
  14924. {
  14925. if (otherType->IsNull())
  14926. {
  14927. if ((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_InEquality))
  14928. {
  14929. mModule->Fail(StrFormat("Invalid operation between '%s' and null", mModule->TypeToString(resultType).c_str()), opToken);
  14930. return;
  14931. }
  14932. if (binaryOp == BfBinaryOp_Equality)
  14933. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  14934. else
  14935. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  14936. return;
  14937. }
  14938. // One pointer
  14939. if ((!otherType->IsIntegral()) ||
  14940. ((binaryOp != BfBinaryOp_Add) && (binaryOp != BfBinaryOp_Subtract)))
  14941. {
  14942. _OpFail();
  14943. return;
  14944. }
  14945. auto underlyingType = resultType->GetUnderlyingType();
  14946. BfIRValue addValue = otherTypedValue->mValue;
  14947. if ((!otherTypedValue->mType->IsSigned()) && (otherTypedValue->mType->mSize < mModule->mSystem->mPtrSize))
  14948. addValue = mModule->mBfIRBuilder->CreateNumericCast(addValue, false, BfTypeCode_UIntPtr);
  14949. if (binaryOp == BfBinaryOp_Subtract)
  14950. {
  14951. if (resultTypeSrc == rightExpression)
  14952. mModule->Fail("Cannot subtract a pointer from an integer", resultTypeSrc);
  14953. addValue = mModule->mBfIRBuilder->CreateNeg(addValue);
  14954. }
  14955. if (underlyingType->IsValuelessType())
  14956. {
  14957. if (!mModule->IsInSpecializedSection())
  14958. {
  14959. mModule->Warn(0, "Adding to a pointer to a zero-sized element has no effect", opToken);
  14960. }
  14961. mResult = *resultTypedValue;
  14962. return;
  14963. }
  14964. mModule->mBfIRBuilder->PopulateType(underlyingType);
  14965. mResult = BfTypedValue(mModule->CreateIndexedValue(underlyingType, resultTypedValue->mValue, addValue), resultType);
  14966. return;
  14967. }
  14968. if ((resultType->IsFunction()) || (resultType->IsPointer()) || (resultType->IsObject()) || (resultType->IsInterface()) || (resultType->IsGenericParam()))
  14969. {
  14970. //if ((resultType->IsFunction()) || (resultType->IsObject()) || (resultType->IsInterface()) || (resultType->IsGenericParam()))
  14971. {
  14972. if ((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_InEquality))
  14973. {
  14974. //mModule->Fail("Invalid operation for objects", opToken);
  14975. _OpFail();
  14976. return;
  14977. }
  14978. }
  14979. if (resultType->IsInterface())
  14980. {
  14981. // Compare as objects instead
  14982. resultType = mModule->mContext->mBfObjectType;
  14983. *resultTypedValue = mModule->Cast(resultTypeSrc, *resultTypedValue, resultType);
  14984. }
  14985. if (otherType->IsNull())
  14986. {
  14987. if (resultType->IsFunction())
  14988. {
  14989. if (binaryOp == BfBinaryOp_Equality)
  14990. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  14991. else
  14992. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  14993. }
  14994. else
  14995. {
  14996. if (binaryOp == BfBinaryOp_Equality)
  14997. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  14998. else
  14999. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15000. }
  15001. }
  15002. else
  15003. {
  15004. auto convertedValue = mModule->CastToValue(otherTypeSrc, *otherTypedValue, resultType);
  15005. if (!convertedValue)
  15006. return;
  15007. if (binaryOp == BfBinaryOp_Equality)
  15008. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(resultTypedValue->mValue, convertedValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15009. else
  15010. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(resultTypedValue->mValue, convertedValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15011. }
  15012. return;
  15013. }
  15014. if (resultType->IsTypedPrimitive())
  15015. {
  15016. bool needsOtherCast = true;
  15017. if (otherType != resultType)
  15018. {
  15019. if ((otherType->IsPrimitiveType()) && (!otherType->IsValuelessType()))
  15020. {
  15021. // Allow zero comparisons to match all typed primitives
  15022. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  15023. {
  15024. auto constant = mModule->mBfIRBuilder->GetConstant(otherTypedValue->mValue);
  15025. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 == 0))
  15026. needsOtherCast = false;
  15027. }
  15028. // Allow integer offsetting
  15029. if ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract))
  15030. {
  15031. if (otherType->IsIntegral())
  15032. needsOtherCast = false;
  15033. }
  15034. }
  15035. if (needsOtherCast)
  15036. {
  15037. // The only purpose of this cast is to potentially throw a casting error
  15038. BfIRValue otherCastResult = mModule->CastToValue(otherTypeSrc, *otherTypedValue, resultType, explicitCast ? BfCastFlags_Explicit : BfCastFlags_None);
  15039. if (!otherCastResult)
  15040. return;
  15041. }
  15042. }
  15043. auto underlyingType = resultType->GetUnderlyingType();
  15044. BfIRValue convResultValue = mModule->CastToValue(resultTypeSrc, *resultTypedValue, underlyingType, BfCastFlags_Explicit);
  15045. BfIRValue convOtherValue = mModule->CastToValue(otherTypeSrc, *otherTypedValue, underlyingType, BfCastFlags_Explicit);
  15046. if ((!underlyingType->IsValuelessType()) && ((!convResultValue) || (!convOtherValue)))
  15047. return;
  15048. if (resultTypedValue == &leftValue)
  15049. PerformBinaryOperation(underlyingType, convResultValue, convOtherValue, binaryOp, opToken);
  15050. else
  15051. PerformBinaryOperation(underlyingType, convOtherValue, convResultValue, binaryOp, opToken);
  15052. if (mResult.mType == underlyingType)
  15053. mResult.mType = resultType;
  15054. return;
  15055. }
  15056. auto _CallValueTypeEquals = [&]()
  15057. {
  15058. BfModuleMethodInstance moduleMethodInstance;
  15059. auto typeInst = leftValue.mType->ToTypeInstance();
  15060. if (typeInst != NULL)
  15061. {
  15062. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_EQUALS);
  15063. }
  15064. else
  15065. {
  15066. BF_ASSERT(leftValue.mType->IsSizedArray() || leftValue.mType->IsMethodRef());
  15067. auto valueTypeInst = mModule->ResolveTypeDef(mModule->mCompiler->mValueTypeTypeDef)->ToTypeInstance();
  15068. BfMethodDef* equalsMethodDef = mModule->mCompiler->mValueTypeTypeDef->GetMethodByName("Equals");
  15069. BfTypeVector typeVec;
  15070. typeVec.push_back(leftValue.mType);
  15071. moduleMethodInstance = mModule->GetMethodInstance(valueTypeInst, equalsMethodDef, typeVec);
  15072. }
  15073. if (moduleMethodInstance)
  15074. {
  15075. if ((opToken != NULL) && (!noClassify))
  15076. mModule->SetElementType(opToken, BfSourceElementType_Method);
  15077. SizedArray<BfResolvedArg, 4> argValues;
  15078. BfResolvedArg resolvedArg;
  15079. resolvedArg.mTypedValue = leftValue;
  15080. argValues.push_back(resolvedArg);
  15081. resolvedArg.mTypedValue = rightValue;
  15082. argValues.push_back(resolvedArg);
  15083. mResult = CreateCall(opToken, BfTypedValue(), BfTypedValue(), moduleMethodInstance.mMethodInstance->mMethodDef, moduleMethodInstance, false, argValues);
  15084. if ((mResult) && (binaryOp == BfBinaryOp_InEquality))
  15085. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  15086. return true;
  15087. }
  15088. return false;
  15089. };
  15090. if (((leftValue.mType->IsComposite()) || (leftValue.mType->IsObject())))
  15091. {
  15092. bool areEquivalentTuples = false;
  15093. if ((leftValue.mType->IsTuple()) && (rightValue.mType->IsTuple()))
  15094. {
  15095. auto leftTupleType = (BfTupleType*)leftValue.mType;
  15096. auto rightTupleType = (BfTupleType*)rightValue.mType;
  15097. // We only do this for tuples, because we would allow an implicit struct
  15098. // truncation if we allow it for all structs, which would result in only
  15099. // the base class's fields being compared
  15100. if (mModule->CanImplicitlyCast(rightValue, leftValue.mType))
  15101. rightValue = mModule->Cast(opToken, rightValue, leftValue.mType, BfCastFlags_Explicit);
  15102. else if (mModule->CanImplicitlyCast(leftValue, rightValue.mType))
  15103. leftValue = mModule->Cast(opToken, leftValue, rightValue.mType, BfCastFlags_Explicit);
  15104. }
  15105. if (leftValue.mType == rightValue.mType)
  15106. {
  15107. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  15108. {
  15109. auto intCoercibleType = mModule->GetIntCoercibleType(leftValue.mType);
  15110. if (intCoercibleType != NULL)
  15111. {
  15112. auto intLHS = mModule->GetIntCoercible(leftValue);
  15113. auto intRHS = mModule->GetIntCoercible(rightValue);
  15114. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  15115. if (binaryOp == BfBinaryOp_Equality)
  15116. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(intLHS.mValue, intRHS.mValue), boolType);
  15117. else
  15118. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(intLHS.mValue, intRHS.mValue), boolType);
  15119. return;
  15120. }
  15121. if (_CallValueTypeEquals())
  15122. return;
  15123. }
  15124. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s'",
  15125. BfGetOpName(binaryOp),
  15126. mModule->TypeToString(leftValue.mType).c_str()), opToken);
  15127. }
  15128. else
  15129. {
  15130. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s' and '%s'",
  15131. BfGetOpName(binaryOp),
  15132. mModule->TypeToString(leftValue.mType).c_str(),
  15133. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  15134. }
  15135. return;
  15136. }
  15137. if (resultType->IsMethodRef() && otherType->IsMethodRef())
  15138. {
  15139. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  15140. {
  15141. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  15142. BfMethodRefType* lhsMethodRefType = (BfMethodRefType*)leftValue.mType;
  15143. BfMethodRefType* rhsMethodRefType = (BfMethodRefType*)rightValue.mType;
  15144. if (lhsMethodRefType->mMethodRef != rhsMethodRefType->mMethodRef)
  15145. {
  15146. mResult = BfTypedValue(mModule->GetConstValue((binaryOp == BfBinaryOp_Equality) ? 0 : 1, boolType), boolType);
  15147. return;
  15148. }
  15149. if (_CallValueTypeEquals())
  15150. return;
  15151. }
  15152. }
  15153. if (resultType->IsIntegral())
  15154. {
  15155. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  15156. {
  15157. if (rightValue.mValue.IsConst())
  15158. {
  15159. auto constVal = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  15160. if ((constVal->mInt64 < 0) || (constVal->mInt64 >= 8 * resultType->mSize))
  15161. {
  15162. mModule->Fail(StrFormat("Shift value '%lld' is out of range for type '%s'", constVal->mInt64, mModule->TypeToString(resultType).c_str()), opToken);
  15163. }
  15164. }
  15165. }
  15166. // We're trying a simplified scheme that doesn't always try to up-convert into an 'int'
  15167. if (leftValue.mType != rightValue.mType)
  15168. {
  15169. bool isBitwiseExpr =
  15170. (binaryOp == BfBinaryOp_BitwiseAnd) |
  15171. (binaryOp == BfBinaryOp_BitwiseOr) |
  15172. (binaryOp == BfBinaryOp_ExclusiveOr) |
  15173. (binaryOp == BfBinaryOp_LeftShift) |
  15174. (binaryOp == BfBinaryOp_RightShift) |
  15175. (binaryOp == BfBinaryOp_Equality) |
  15176. (binaryOp == BfBinaryOp_InEquality);
  15177. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  15178. {
  15179. // For shifts we have more lenient rules - shifts are naturally limited so any int type is equally valid
  15180. if (rightValue.mType->IsIntegral())
  15181. explicitCast = true;
  15182. }
  15183. else if (((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract)) && (resultType->IsChar()) && (otherType->IsInteger()))
  15184. {
  15185. // charVal += intVal;
  15186. explicitCast = true;
  15187. }
  15188. else if ((!resultType->IsSigned()) && (otherType->IsSigned()))
  15189. {
  15190. if (mModule->CanImplicitlyCast(*otherTypedValue, resultType))
  15191. {
  15192. // If we can convert the 'other' value implicitly then it's a convertible literal, leave as uint
  15193. }
  15194. else
  15195. {
  15196. mModule->Fail(StrFormat("Operator cannot be applied to operands of type '%s' and '%s'",
  15197. mModule->TypeToString(leftValue.mType).c_str(),
  15198. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  15199. return;
  15200. }
  15201. }
  15202. else if ((isBitwiseExpr) && (otherType->IsIntegral()) && (resultType->mSize == otherType->mSize))
  15203. {
  15204. // Forget about signed/unsigned mismatches for bitwise operations
  15205. explicitCast = true;
  15206. }
  15207. else
  15208. {
  15209. if ((binaryOp == BfBinaryOp_Subtract) && (resultType->IsChar()) && (otherType->IsChar()))
  15210. {
  15211. // "wchar - char" subtraction will always fit into int32, because of unicode range
  15212. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  15213. explicitCast = true;
  15214. }
  15215. else if ((otherType->IsChar()) &&
  15216. ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract)))
  15217. {
  15218. mModule->Fail(StrFormat("Cannot perform operation between types '%s' and '%s'",
  15219. mModule->TypeToString(leftValue.mType).c_str(),
  15220. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  15221. }
  15222. }
  15223. }
  15224. else if ((!resultType->IsSigned()) && (binaryOp == BfBinaryOp_Subtract) && (!forceLeftType))
  15225. {
  15226. if ((mExpectingType == NULL) || (mExpectingType->IsSigned()) || (resultType->IsChar()))
  15227. {
  15228. if ((resultType->IsChar()) && (resultType->mSize == 4))
  15229. {
  15230. // "wchar - wchar" subtraction will always fit into int32, because of unicode range
  15231. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  15232. }
  15233. else
  15234. {
  15235. // The result of uint8 - uint8 is int16 (for example)
  15236. switch (resultType->mSize)
  15237. {
  15238. case 1:
  15239. resultType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  15240. break;
  15241. case 2:
  15242. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  15243. break;
  15244. case 4:
  15245. resultType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  15246. break;
  15247. }
  15248. }
  15249. explicitCast = true;
  15250. }
  15251. }
  15252. else if (resultType->IsChar())
  15253. {
  15254. bool canDoOp =
  15255. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  15256. (binaryOp == BfBinaryOp_BitwiseOr) ||
  15257. ((binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_Compare));
  15258. if (!canDoOp)
  15259. {
  15260. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  15261. return;
  15262. }
  15263. }
  15264. }
  15265. if (!convLeftValue)
  15266. convLeftValue = mModule->CastToValue(leftExpression, leftValue, resultType,
  15267. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  15268. if (!convRightValue)
  15269. convRightValue = mModule->CastToValue(rightExpression, rightValue, resultType,
  15270. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  15271. PerformBinaryOperation(resultType, convLeftValue, convRightValue, binaryOp, opToken);
  15272. }
  15273. void BfExprEvaluator::PerformBinaryOperation(BfType* resultType, BfIRValue convLeftValue, BfIRValue convRightValue, BfBinaryOp binaryOp, BfAstNode* opToken)
  15274. {
  15275. if (resultType->IsValuelessType())
  15276. {
  15277. switch (binaryOp)
  15278. {
  15279. case BfBinaryOp_Equality:
  15280. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1),
  15281. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15282. break;
  15283. case BfBinaryOp_InEquality:
  15284. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0),
  15285. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15286. break;
  15287. default:
  15288. mModule->Fail("Invalid operation for void", opToken);
  15289. break;
  15290. }
  15291. return;
  15292. }
  15293. if ((!convLeftValue) || (!convRightValue))
  15294. return;
  15295. if (resultType->IsPrimitiveType())
  15296. {
  15297. auto primType = (BfPrimitiveType*)resultType;
  15298. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  15299. {
  15300. switch (binaryOp)
  15301. {
  15302. case BfBinaryOp_Equality:
  15303. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  15304. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15305. break;
  15306. case BfBinaryOp_InEquality:
  15307. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  15308. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15309. break;
  15310. case BfBinaryOp_BitwiseAnd:
  15311. case BfBinaryOp_ConditionalAnd:
  15312. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue),
  15313. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15314. break;
  15315. case BfBinaryOp_BitwiseOr:
  15316. case BfBinaryOp_ConditionalOr:
  15317. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue),
  15318. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15319. break;
  15320. case BfBinaryOp_ExclusiveOr:
  15321. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue),
  15322. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15323. break;
  15324. default:
  15325. mModule->Fail("Invalid operation for booleans", opToken);
  15326. break;
  15327. }
  15328. return;
  15329. }
  15330. }
  15331. if ((!resultType->IsIntegral()) && (!resultType->IsFloat()))
  15332. {
  15333. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  15334. return;
  15335. }
  15336. if (resultType->IsIntegral())
  15337. {
  15338. switch (binaryOp)
  15339. {
  15340. case BfBinaryOp_BitwiseAnd:
  15341. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue), resultType);
  15342. return;
  15343. case BfBinaryOp_BitwiseOr:
  15344. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue), resultType);
  15345. return;
  15346. case BfBinaryOp_ExclusiveOr:
  15347. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue), resultType);
  15348. return;
  15349. case BfBinaryOp_LeftShift:
  15350. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShl(convLeftValue, convRightValue), resultType);
  15351. mModule->CheckRangeError(resultType, opToken);
  15352. return;
  15353. case BfBinaryOp_RightShift:
  15354. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShr(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  15355. return;
  15356. }
  15357. }
  15358. if ((resultType->IsChar()) &&
  15359. ((binaryOp == BfBinaryOp_Multiply) ||
  15360. (binaryOp == BfBinaryOp_Divide) ||
  15361. (binaryOp == BfBinaryOp_Modulus)))
  15362. {
  15363. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  15364. return;
  15365. }
  15366. switch (binaryOp)
  15367. {
  15368. case BfBinaryOp_Add:
  15369. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAdd(convLeftValue, convRightValue), resultType);
  15370. mModule->CheckRangeError(resultType, opToken);
  15371. break;
  15372. case BfBinaryOp_Subtract:
  15373. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue), resultType);
  15374. mModule->CheckRangeError(resultType, opToken);
  15375. break;
  15376. case BfBinaryOp_Multiply:
  15377. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateMul(convLeftValue, convRightValue), resultType);
  15378. mModule->CheckRangeError(resultType, opToken);
  15379. break;
  15380. case BfBinaryOp_Divide:
  15381. {
  15382. bool isZero = false;
  15383. if (convRightValue.IsConst())
  15384. {
  15385. auto constVal = mModule->mBfIRBuilder->GetConstant(convRightValue);
  15386. if (BfIRBuilder::IsInt(constVal->mTypeCode))
  15387. isZero = constVal->mInt64 == 0;
  15388. }
  15389. if (isZero)
  15390. {
  15391. mModule->Fail("Divide by zero", opToken);
  15392. mResult = mModule->GetDefaultTypedValue(resultType);
  15393. }
  15394. else
  15395. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateDiv(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  15396. }
  15397. break;
  15398. case BfBinaryOp_Modulus:
  15399. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateRem(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  15400. break;
  15401. case BfBinaryOp_Equality:
  15402. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  15403. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15404. break;
  15405. case BfBinaryOp_InEquality:
  15406. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  15407. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15408. break;
  15409. case BfBinaryOp_LessThan:
  15410. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSignedInt()),
  15411. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15412. break;
  15413. case BfBinaryOp_LessThanOrEqual:
  15414. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(convLeftValue, convRightValue, resultType->IsSignedInt()),
  15415. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15416. break;
  15417. case BfBinaryOp_GreaterThan:
  15418. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSignedInt()),
  15419. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15420. break;
  15421. case BfBinaryOp_GreaterThanOrEqual:
  15422. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(convLeftValue, convRightValue, resultType->IsSignedInt()),
  15423. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  15424. break;
  15425. case BfBinaryOp_Compare:
  15426. {
  15427. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  15428. BfIRBlock checkGtBlock = mModule->mBfIRBuilder->CreateBlock("cmpCheckGt");
  15429. BfIRBlock eqBlock = mModule->mBfIRBuilder->CreateBlock("cmpEq");
  15430. BfIRBlock endBlock = mModule->mBfIRBuilder->CreateBlock("cmpEnd");
  15431. auto startBlock = mModule->mBfIRBuilder->GetInsertBlock();
  15432. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSignedInt());
  15433. mModule->mBfIRBuilder->CreateCondBr(cmpLtVal, endBlock, checkGtBlock);
  15434. mModule->mBfIRBuilder->AddBlock(checkGtBlock);
  15435. mModule->mBfIRBuilder->SetInsertPoint(checkGtBlock);
  15436. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSignedInt());
  15437. mModule->mBfIRBuilder->CreateCondBr(cmpGtVal, endBlock, eqBlock);
  15438. mModule->mBfIRBuilder->AddBlock(eqBlock);
  15439. mModule->mBfIRBuilder->SetInsertPoint(eqBlock);
  15440. mModule->mBfIRBuilder->CreateBr(endBlock);
  15441. mModule->mBfIRBuilder->AddBlock(endBlock);
  15442. mModule->mBfIRBuilder->SetInsertPoint(endBlock);
  15443. auto phiVal = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(intType), 3);
  15444. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, -1), startBlock);
  15445. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), checkGtBlock);
  15446. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), eqBlock);
  15447. mResult = BfTypedValue(phiVal, intType);
  15448. }
  15449. break;
  15450. default:
  15451. mModule->Fail("Invalid operation", opToken);
  15452. break;
  15453. }
  15454. }
  15455. void BfExprEvaluator::Visit(BfBinaryOperatorExpression* binOpExpr)
  15456. {
  15457. BfAutoParentNodeEntry autoParentNodeEntry(mModule, binOpExpr);
  15458. // There are a few binary operations that could actually be casts followed by an unary operation
  15459. // We can't determine that until we know whether the identifier in the parens is a typename or not
  15460. // (double)-1.0 (intptr)&val (BaseStruct)*val
  15461. BfUnaryOp unaryOp = BfUnaryOp_None;
  15462. switch (binOpExpr->mOp)
  15463. {
  15464. case BfBinaryOp_Add: unaryOp = BfUnaryOp_Positive; break;
  15465. case BfBinaryOp_Subtract: unaryOp = BfUnaryOp_Negate; break;
  15466. case BfBinaryOp_Multiply: unaryOp = BfUnaryOp_Dereference; break;
  15467. case BfBinaryOp_BitwiseAnd: unaryOp = BfUnaryOp_AddressOf; break;
  15468. default: break;
  15469. }
  15470. if (unaryOp != BfUnaryOp_None)
  15471. {
  15472. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(binOpExpr->mLeft))
  15473. {
  15474. if (auto castTypeExpr = BfNodeDynCast<BfIdentifierNode>(parenExpr->mExpression))
  15475. {
  15476. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  15477. auto resolvedType = mModule->ResolveTypeRef(castTypeExpr, NULL);
  15478. prevIgnoreError.Restore();
  15479. if (resolvedType != NULL)
  15480. {
  15481. if (auto rightBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>(binOpExpr->mRight))
  15482. {
  15483. int leftPrecedence = BfGetBinaryOpPrecendence(binOpExpr->mOp);
  15484. int rightPrecedence = BfGetBinaryOpPrecendence(rightBinOpExpr->mOp);
  15485. // Do we have a precedence order issue due to mis-parsing this?
  15486. // An example is: "(int)-5.5 * 10"
  15487. if (rightPrecedence > leftPrecedence)
  15488. {
  15489. mModule->FailAfter("Cast target must be wrapped in parentheses", binOpExpr->mLeft);
  15490. }
  15491. }
  15492. PerformUnaryOperation(binOpExpr->mRight, unaryOp, binOpExpr->mOpToken);
  15493. if (mResult)
  15494. {
  15495. mResult = mModule->LoadValue(mResult);
  15496. mResult = mModule->Cast(binOpExpr, mResult, resolvedType, BfCastFlags_Explicit);
  15497. }
  15498. return;
  15499. }
  15500. }
  15501. }
  15502. }
  15503. if (binOpExpr->mRight == NULL)
  15504. {
  15505. // We visit the children for autocompletion only
  15506. if (binOpExpr->mLeft != NULL)
  15507. VisitChild(binOpExpr->mLeft);
  15508. if (mResult)
  15509. {
  15510. auto autoComplete = GetAutoComplete();
  15511. if (autoComplete != NULL)
  15512. autoComplete->CheckEmptyStart(binOpExpr->mOpToken, mResult.mType);
  15513. }
  15514. if (binOpExpr->mRight != NULL)
  15515. VisitChild(binOpExpr->mRight);
  15516. return;
  15517. }
  15518. PerformBinaryOperation(binOpExpr->mLeft, binOpExpr->mRight, binOpExpr->mOp, binOpExpr->mOpToken, BfBinOpFlag_None);
  15519. }