BfExprEvaluator.cpp 851 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044
  1. #pragma warning(push)
  2. #pragma warning(disable:4800)
  3. #pragma warning(disable:4244)
  4. #pragma warning(disable:4141)
  5. #pragma warning(disable:4624)
  6. #pragma warning(disable:4146)
  7. #pragma warning(disable:4267)
  8. #pragma warning(disable:4291)
  9. #include "BfExprEvaluator.h"
  10. #include "BfConstResolver.h"
  11. #include "BfAutoComplete.h"
  12. #include "BeefySysLib/util/PerfTimer.h"
  13. #include "BeefySysLib/util/BeefPerf.h"
  14. #include "BfParser.h"
  15. #include "BfMangler.h"
  16. #include "BfDemangler.h"
  17. #include "BfResolvePass.h"
  18. #include "BfUtil.h"
  19. #include "BfDeferEvalChecker.h"
  20. #include "BfVarDeclChecker.h"
  21. #include "BfFixits.h"
  22. #include "CeMachine.h"
  23. #include "BfDefBuilder.h"
  24. #include "CeMachine.h"
  25. #include "CeDebugger.h"
  26. #pragma warning(pop)
  27. #pragma warning(disable:4996)
  28. #include "BeefySysLib/util/AllocDebug.h"
  29. USING_NS_BF;
  30. using namespace llvm;
  31. //////////////////////////////////////////////////////////////////////////
  32. DeferredTupleAssignData::~DeferredTupleAssignData()
  33. {
  34. for (auto entry : mChildren)
  35. {
  36. delete entry.mExprEvaluator;
  37. delete entry.mInnerTuple;
  38. }
  39. }
  40. //////////////////////////////////////////////////////////////////////////
  41. BfBaseClassWalker::BfBaseClassWalker(BfType* typeA, BfType* typeB, BfModule* module)
  42. {
  43. mMayBeFromInterface = false;
  44. if (typeB == typeA)
  45. typeB = NULL;
  46. if ((typeA != NULL) && (!typeA->IsInterface()))
  47. mTypes[0] = typeA->ToTypeInstance();
  48. else
  49. mTypes[0] = NULL;
  50. if ((typeB != NULL) && (!typeB->IsInterface()))
  51. mTypes[1] = typeB->ToTypeInstance();
  52. else
  53. mTypes[1] = NULL;
  54. if ((typeA != NULL) && (typeA->IsGenericParam()))
  55. {
  56. mMayBeFromInterface = true;
  57. AddConstraints(typeA, module->GetGenericParamInstance((BfGenericParamType*)typeA));
  58. }
  59. if ((typeB != NULL) && (typeB->IsGenericParam()))
  60. {
  61. mMayBeFromInterface = true;
  62. AddConstraints(typeB, module->GetGenericParamInstance((BfGenericParamType*)typeB));
  63. }
  64. }
  65. /*BfBaseClassWalker::BfBaseClassWalker(BfTypeInstance* typeA, BfTypeInstance* typeB)
  66. {
  67. mTypes[0] = typeA;
  68. mTypes[1] = typeB;
  69. }*/
  70. BfBaseClassWalker::BfBaseClassWalker()
  71. {
  72. mMayBeFromInterface = false;
  73. mTypes[0] = NULL;
  74. mTypes[1] = NULL;
  75. }
  76. void BfBaseClassWalker::AddConstraints(BfType* srcType, BfGenericParamInstance* genericParam)
  77. {
  78. if (genericParam->mTypeConstraint != NULL)
  79. {
  80. auto typeInst = genericParam->mTypeConstraint->ToTypeInstance();
  81. {
  82. Entry entry(srcType, typeInst);
  83. if ((typeInst != NULL) && (!mManualList.Contains(entry)))
  84. mManualList.Add(entry);
  85. }
  86. }
  87. for (auto typeInst : genericParam->mInterfaceConstraints)
  88. {
  89. Entry entry(srcType, typeInst);
  90. if ((typeInst != NULL) && (!mManualList.Contains(entry)))
  91. mManualList.Add(entry);
  92. }
  93. }
  94. BfBaseClassWalker::Entry BfBaseClassWalker::Next()
  95. {
  96. if (!mManualList.IsEmpty())
  97. {
  98. auto entry = mManualList.back();
  99. mManualList.pop_back();
  100. return entry;
  101. }
  102. // Check the most specific type instance first (highest inheritance level)
  103. auto checkInstance = mTypes[0];
  104. if (mTypes[0] == NULL)
  105. checkInstance = mTypes[1];
  106. else if ((mTypes[1] != NULL) && (mTypes[1]->mInheritDepth > mTypes[0]->mInheritDepth))
  107. checkInstance = mTypes[1];
  108. if (checkInstance == NULL)
  109. return Entry();
  110. // Do it this was so if we reach the same base class for both types that we only handle each base type once
  111. if (checkInstance == mTypes[0])
  112. mTypes[0] = checkInstance->mBaseType;
  113. if (checkInstance == mTypes[1])
  114. mTypes[1] = checkInstance->mBaseType;
  115. Entry entry;
  116. entry.mSrcType = checkInstance;
  117. entry.mTypeInstance = checkInstance;
  118. return entry;
  119. }
  120. //////////////////////////////////////////////////////////////////////////
  121. BfMethodMatcher::BfMethodMatcher(BfAstNode* targetSrc, BfModule* module, const StringImpl& methodName, SizedArrayImpl<BfResolvedArg>& arguments, const BfMethodGenericArguments& methodGenericArguments) :
  122. mArguments(arguments)
  123. {
  124. mTargetSrc = targetSrc;
  125. mModule = module;
  126. mMethodName = methodName;
  127. Init(/*arguments, */methodGenericArguments);
  128. }
  129. BfMethodMatcher::BfMethodMatcher(BfAstNode* targetSrc, BfModule* module, BfMethodInstance* interfaceMethodInstance, SizedArrayImpl<BfResolvedArg>& arguments, const BfMethodGenericArguments& methodGenericArguments) :
  130. mArguments(arguments)
  131. {
  132. mTargetSrc = targetSrc;
  133. mModule = module;
  134. Init(/*arguments, */methodGenericArguments);
  135. mInterfaceMethodInstance = interfaceMethodInstance;
  136. mMethodName = mInterfaceMethodInstance->mMethodDef->mName;
  137. }
  138. void BfMethodMatcher::Init(const BfMethodGenericArguments& methodGenericArguments)
  139. {
  140. //mArguments = arguments;
  141. mUsingLists = NULL;
  142. mActiveTypeDef = NULL;
  143. mBestMethodDef = NULL;
  144. mBackupMethodDef = NULL;
  145. mBackupMatchKind = BackupMatchKind_None;
  146. mBestRawMethodInstance = NULL;
  147. mBestMethodTypeInstance = NULL;
  148. mExplicitInterfaceCheck = NULL;
  149. mSelfType = NULL;
  150. mMethodType = BfMethodType_Normal;
  151. mCheckReturnType = NULL;
  152. mHasArgNames = false;
  153. mHadExplicitGenericArguments = false;
  154. mHadOpenGenericArguments = methodGenericArguments.mIsOpen;
  155. mHadPartialGenericArguments = methodGenericArguments.mIsPartial;
  156. mHasVarArguments = false;
  157. mInterfaceMethodInstance = NULL;
  158. mFakeConcreteTarget = false;
  159. mBypassVirtual = false;
  160. mAllowStatic = true;
  161. mAllowNonStatic = true;
  162. mSkipImplicitParams = false;
  163. mAllowImplicitThis = false;
  164. mAllowImplicitRef = false;
  165. mAllowImplicitWrap = false;
  166. mHadVarConflictingReturnType = false;
  167. mAutoFlushAmbiguityErrors = true;
  168. mMethodCheckCount = 0;
  169. mCheckedKind = BfCheckedKind_NotSet;
  170. mMatchFailKind = MatchFailKind_None;
  171. mBfEvalExprFlags = BfEvalExprFlags_None;
  172. for (auto& arg : mArguments)
  173. {
  174. auto bfType = arg.mTypedValue.mType;
  175. if (bfType != NULL)
  176. {
  177. mHasVarArguments |= bfType->IsVar();
  178. if (bfType->IsGenericParam())
  179. {
  180. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)bfType);
  181. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  182. mHasVarArguments = true;
  183. }
  184. }
  185. if (arg.mNameNode != NULL)
  186. mHasArgNames = true;
  187. }
  188. if (methodGenericArguments.mArguments != NULL)
  189. {
  190. for (BfAstNode* genericArg : *(methodGenericArguments.mArguments))
  191. {
  192. BfType* genericArgType = NULL;
  193. if (BfNodeIsA<BfUninitializedExpression>(genericArg))
  194. {
  195. // Allow a null here
  196. BF_ASSERT(mHadPartialGenericArguments);
  197. }
  198. else
  199. {
  200. genericArgType = mModule->ResolveTypeRef(genericArg, NULL, BfPopulateType_Identity, BfResolveTypeRefFlag_AllowImplicitConstExpr);
  201. if ((genericArgType != NULL) && (genericArgType->IsGenericParam()))
  202. {
  203. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)genericArgType);
  204. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  205. mHasVarArguments = true;
  206. }
  207. }
  208. mExplicitMethodGenericArguments.push_back(genericArgType);
  209. }
  210. mHadExplicitGenericArguments = true;
  211. }
  212. }
  213. bool BfMethodMatcher::IsMemberAccessible(BfTypeInstance* typeInst, BfTypeDef* declaringType)
  214. {
  215. if (!declaringType->mIsPartial)
  216. return true;
  217. if (mActiveTypeDef == NULL)
  218. mActiveTypeDef = mModule->GetActiveTypeDef();
  219. // Note that mActiveTypeDef does not pose a constraint here
  220. if (!typeInst->IsTypeMemberIncluded(declaringType, mActiveTypeDef, mModule))
  221. return false;
  222. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  223. if ((visibleProjectSet != NULL) && (!typeInst->IsTypeMemberAccessible(declaringType, visibleProjectSet)))
  224. {
  225. return false;
  226. }
  227. return true;
  228. }
  229. bool BfGenericInferContext::AddToCheckedSet(BfType* argType, BfType* wantType)
  230. {
  231. int64 idPair = ((int64)argType->mTypeId << 32) | (wantType->mTypeId);
  232. return mCheckedTypeSet.Add(idPair);
  233. }
  234. bool BfGenericInferContext::InferGenericArgument(BfMethodInstance* methodInstance, BfType* argType, BfType* wantType, BfIRValue argValue, bool checkCheckedSet)
  235. {
  236. if (argType == NULL)
  237. return false;
  238. if (!wantType->IsUnspecializedType())
  239. return true;
  240. if (checkCheckedSet)
  241. {
  242. if (!AddToCheckedSet(argType, wantType))
  243. return true;
  244. }
  245. if (wantType->IsGenericParam())
  246. {
  247. auto wantGenericParam = (BfGenericParamType*)wantType;
  248. BfType* methodGenericTypeConstraint = NULL;
  249. auto _SetGeneric = [&]()
  250. {
  251. if (argType != NULL)
  252. {
  253. // Disallow illegal types
  254. if (argType->IsRef())
  255. return;
  256. if (argType->IsNull())
  257. return;
  258. }
  259. if ((*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] != argType)
  260. {
  261. if (methodGenericTypeConstraint != NULL)
  262. {
  263. if (methodGenericTypeConstraint->IsGenericTypeInstance())
  264. {
  265. auto wantGenericType = (BfTypeInstance*)methodGenericTypeConstraint;
  266. auto checkArgType = argType;
  267. while (checkArgType != NULL)
  268. {
  269. if (checkArgType->IsGenericTypeInstance())
  270. {
  271. auto argGenericType = (BfTypeInstance*)checkArgType;
  272. if (argGenericType->mTypeDef->GetLatest() == wantGenericType->mTypeDef->GetLatest())
  273. {
  274. for (int genericArgIdx = 0; genericArgIdx < (int)argGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  275. InferGenericArgument(methodInstance, argGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], wantGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], BfIRValue(), true);
  276. }
  277. }
  278. else if (checkArgType->IsSizedArray())
  279. {
  280. auto sizedArrayType = (BfSizedArrayType*)checkArgType;
  281. if (wantGenericType->IsInstanceOf(mModule->mCompiler->mSizedArrayTypeDef))
  282. {
  283. InferGenericArgument(methodInstance, sizedArrayType->mElementType, wantGenericType->mGenericTypeInfo->mTypeGenericArguments[0], BfIRValue());
  284. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  285. BfTypedValue arraySize = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, (uint64)sizedArrayType->mElementCount), intType);
  286. InferGenericArgument(methodInstance, mModule->CreateConstExprValueType(arraySize), wantGenericType->mGenericTypeInfo->mTypeGenericArguments[1], BfIRValue(), true);
  287. }
  288. }
  289. else if (checkArgType->IsPointer())
  290. {
  291. auto pointerType = (BfPointerType*)checkArgType;
  292. if (wantGenericType->IsInstanceOf(mModule->mCompiler->mPointerTTypeDef))
  293. {
  294. InferGenericArgument(methodInstance, pointerType->mElementType, wantGenericType->mGenericTypeInfo->mTypeGenericArguments[0], BfIRValue(), true);
  295. }
  296. }
  297. auto checkTypeInst = checkArgType->ToTypeInstance();
  298. if ((checkTypeInst == NULL) || (!checkTypeInst->mHasParameterizedBase))
  299. break;
  300. checkArgType = checkTypeInst->mBaseType;
  301. }
  302. }
  303. }
  304. }
  305. if ((*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] == NULL)
  306. mInferredCount++;
  307. (*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] = argType;
  308. if (!mPrevArgValues.IsEmpty())
  309. mPrevArgValues[wantGenericParam->mGenericParamIdx] = argValue;
  310. };
  311. if (argType->IsVar())
  312. {
  313. _SetGeneric();
  314. return true;
  315. }
  316. if (wantGenericParam->mGenericParamKind == BfGenericParamKind_Method)
  317. {
  318. auto genericParamInst = methodInstance->mMethodInfoEx->mGenericParams[wantGenericParam->mGenericParamIdx];
  319. methodGenericTypeConstraint = genericParamInst->mTypeConstraint;
  320. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  321. {
  322. if (argValue.IsConst())
  323. {
  324. argType = mModule->CreateConstExprValueType(BfTypedValue(argValue, argType));
  325. }
  326. else if (!argType->IsConstExprValue())
  327. {
  328. return false;
  329. }
  330. }
  331. if (argType == mModule->mContext->mBfObjectType)
  332. {
  333. if ((genericParamInst->mTypeConstraint != NULL) && (genericParamInst->mTypeConstraint->IsDelegate()))
  334. {
  335. argType = mModule->ResolveGenericType(genericParamInst->mTypeConstraint, NULL, mCheckMethodGenericArguments, mModule->mCurTypeInstance);
  336. if (argType == NULL)
  337. return true;
  338. }
  339. }
  340. if (mPrevArgValues.IsEmpty())
  341. {
  342. _SetGeneric();
  343. return true;
  344. }
  345. auto prevGenericMethodArg = (*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx];
  346. auto prevArgValue = mPrevArgValues[wantGenericParam->mGenericParamIdx];
  347. if (prevGenericMethodArg == NULL)
  348. {
  349. _SetGeneric();
  350. return true;
  351. }
  352. if ((prevGenericMethodArg->IsIntUnknown()) && (!argType->IsIntUnknown()))
  353. {
  354. // Old int fits into new argType, that's good
  355. if (mModule->CanCast(BfTypedValue(prevArgValue, prevGenericMethodArg), argType))
  356. {
  357. _SetGeneric();
  358. return true;
  359. }
  360. // Doesn't fit, upgrade type to 'int'
  361. argType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  362. if (mModule->CanCast(BfTypedValue(prevArgValue, prevGenericMethodArg), argType))
  363. {
  364. _SetGeneric();
  365. return true;
  366. }
  367. }
  368. if (argType->IsIntUnknown())
  369. {
  370. // New int fits into previous arg type, that's good
  371. if (mModule->CanCast(BfTypedValue(argValue, argType), prevGenericMethodArg))
  372. return true;
  373. // Doesn't fit, upgrade type to 'int'
  374. argType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  375. }
  376. else
  377. {
  378. // Prev is already best
  379. if (mModule->CanCast(mModule->GetFakeTypedValue(argType), prevGenericMethodArg))
  380. return true;
  381. }
  382. // New best?
  383. if (mModule->CanCast(mModule->GetFakeTypedValue(prevGenericMethodArg), argType))
  384. {
  385. _SetGeneric();
  386. return true;
  387. }
  388. // No implicit conversion, FAIL!
  389. (*mCheckMethodGenericArguments)[wantGenericParam->mGenericParamIdx] = NULL;
  390. return false;
  391. }
  392. return true;
  393. }
  394. if (wantType->IsTuple())
  395. {
  396. if (argType->IsTuple())
  397. {
  398. auto wantTupleType = (BfTupleType*)wantType;
  399. auto argTupleType = (BfTupleType*)argType;
  400. if (wantTupleType->mFieldInstances.size() == argTupleType->mFieldInstances.size())
  401. {
  402. for (int fieldIdx = 0; fieldIdx < (int)wantTupleType->mFieldInstances.size(); fieldIdx++)
  403. {
  404. InferGenericArgument(methodInstance, argTupleType->mFieldInstances[fieldIdx].mResolvedType,
  405. wantTupleType->mFieldInstances[fieldIdx].mResolvedType, BfIRValue());
  406. }
  407. }
  408. }
  409. }
  410. if ((wantType->IsGenericTypeInstance()) && (wantType->IsUnspecializedTypeVariation()))
  411. {
  412. auto wantGenericType = (BfTypeInstance*)wantType;
  413. if (argType->IsGenericParam())
  414. {
  415. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)argType);
  416. if ((genericParam->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  417. {
  418. InferGenericArgument(methodInstance, mModule->GetPrimitiveType(BfTypeCode_Var), wantType, BfIRValue());
  419. return true;
  420. }
  421. if ((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsGenericTypeInstance()))
  422. InferGenericArgument(methodInstance, genericParam->mTypeConstraint, wantType, BfIRValue());
  423. }
  424. if (argType->IsVar())
  425. {
  426. for (int genericArgIdx = 0; genericArgIdx < (int)wantGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  427. {
  428. BfType* wantGenericArgument = wantGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx];
  429. if (!wantGenericArgument->IsUnspecializedType())
  430. continue;
  431. InferGenericArgument(methodInstance, mModule->GetPrimitiveType(BfTypeCode_Var), wantGenericArgument, BfIRValue());
  432. }
  433. return true;
  434. }
  435. auto typeInstance = argType->ToTypeInstance();
  436. if (typeInstance == NULL)
  437. return true;
  438. if (wantGenericType->IsInterface())
  439. {
  440. for (auto& ifaceEntry : typeInstance->mInterfaces)
  441. InferGenericArgument(methodInstance, ifaceEntry.mInterfaceType, wantType, BfIRValue());
  442. }
  443. else if (typeInstance->mBaseType != NULL)
  444. InferGenericArgument(methodInstance, typeInstance->mBaseType, wantType, BfIRValue());
  445. if (!argType->IsGenericTypeInstance())
  446. return true;
  447. auto argGenericType = (BfTypeInstance*)argType;
  448. if (argGenericType->mTypeDef->GetDefinition() != wantGenericType->mTypeDef->GetDefinition())
  449. return true;
  450. for (int genericArgIdx = 0; genericArgIdx < (int)argGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  451. {
  452. BfType* wantGenericArgument = wantGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx];
  453. if (!wantGenericArgument->IsUnspecializedType())
  454. continue;
  455. InferGenericArgument(methodInstance, argGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], wantGenericArgument, BfIRValue(), true);
  456. }
  457. return true;
  458. }
  459. if (wantType->IsRef())
  460. {
  461. auto wantRefType = (BfRefType*)wantType;
  462. if (!argType->IsRef())
  463. {
  464. // Match to non-ref
  465. InferGenericArgument(methodInstance, argType, wantRefType->mElementType, BfIRValue());
  466. return true;
  467. }
  468. auto argRefType = (BfRefType*)argType;
  469. //TODO: We removed this check so we still infer even if we have the wrong ref kind
  470. //if (wantRefType->mRefKind != argRefType->mRefKind)
  471. //return true;
  472. return InferGenericArgument(methodInstance, argRefType->mElementType, wantRefType->mElementType, BfIRValue());
  473. }
  474. if (wantType->IsPointer())
  475. {
  476. if (!argType->IsPointer())
  477. return true;
  478. auto wantPointerType = (BfPointerType*) wantType;
  479. auto argPointerType = (BfPointerType*) argType;
  480. return InferGenericArgument(methodInstance, argPointerType->mElementType, wantPointerType->mElementType, BfIRValue());
  481. }
  482. if (wantType->IsUnknownSizedArrayType())
  483. {
  484. auto wantArrayType = (BfUnknownSizedArrayType*)wantType;
  485. if (argType->IsUnknownSizedArrayType())
  486. {
  487. auto argArrayType = (BfUnknownSizedArrayType*)argType;
  488. InferGenericArgument(methodInstance, argArrayType->mElementCountSource, wantArrayType->mElementCountSource, BfIRValue());
  489. }
  490. else if (argType->IsSizedArray())
  491. {
  492. auto argArrayType = (BfSizedArrayType*)argType;
  493. BfTypedValue sizeValue(mModule->GetConstValue(argArrayType->mElementCount), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  494. auto sizedType = mModule->CreateConstExprValueType(sizeValue);
  495. InferGenericArgument(methodInstance, sizedType, wantArrayType->mElementCountSource, BfIRValue());
  496. }
  497. }
  498. if (wantType->IsSizedArray())
  499. {
  500. if (argType->IsSizedArray())
  501. {
  502. auto wantArrayType = (BfSizedArrayType*)wantType;
  503. auto argArrayType = (BfSizedArrayType*)argType;
  504. InferGenericArgument(methodInstance, argArrayType->mElementType, wantArrayType->mElementType, BfIRValue());
  505. }
  506. }
  507. if ((wantType->IsDelegate()) || (wantType->IsFunction()))
  508. {
  509. if (((argType->IsDelegate()) || (argType->IsFunction())) &&
  510. (wantType->IsDelegate() == argType->IsDelegate()))
  511. {
  512. if (!AddToCheckedSet(argType, wantType))
  513. return true;
  514. auto argInvokeMethod = mModule->GetRawMethodByName(argType->ToTypeInstance(), "Invoke");
  515. auto wantInvokeMethod = mModule->GetRawMethodByName(wantType->ToTypeInstance(), "Invoke");
  516. if ((argInvokeMethod != NULL) && (wantInvokeMethod != NULL) && (argInvokeMethod->GetParamCount() == wantInvokeMethod->GetParamCount()))
  517. {
  518. InferGenericArgument(methodInstance, argInvokeMethod->mReturnType, wantInvokeMethod->mReturnType, BfIRValue());
  519. for (int argIdx = 0; argIdx < (int)argInvokeMethod->GetParamCount(); argIdx++)
  520. InferGenericArgument(methodInstance, argInvokeMethod->GetParamType(argIdx), wantInvokeMethod->GetParamType(argIdx), BfIRValue());
  521. }
  522. }
  523. else if (argType->IsMethodRef())
  524. {
  525. auto methodTypeRef = (BfMethodRefType*)argType;
  526. if (!AddToCheckedSet(argType, wantType))
  527. return true;
  528. auto argInvokeMethod = methodTypeRef->mMethodRef;
  529. auto delegateInfo = wantType->GetDelegateInfo();
  530. auto wantInvokeMethod = mModule->GetRawMethodByName(wantType->ToTypeInstance(), "Invoke");
  531. if ((delegateInfo->mHasExplicitThis) && (argInvokeMethod->HasThis()))
  532. InferGenericArgument(methodInstance, argInvokeMethod->GetParamType(-1), delegateInfo->mParams[0], BfIRValue());
  533. int wantInvokeOffset = delegateInfo->mHasExplicitThis ? 1 : 0;
  534. if ((argInvokeMethod != NULL) && (wantInvokeMethod != NULL) && (argInvokeMethod->GetParamCount() == wantInvokeMethod->GetParamCount() - wantInvokeOffset))
  535. {
  536. InferGenericArgument(methodInstance, argInvokeMethod->mReturnType, wantInvokeMethod->mReturnType, BfIRValue());
  537. for (int argIdx = 0; argIdx < (int)argInvokeMethod->GetParamCount(); argIdx++)
  538. InferGenericArgument(methodInstance, argInvokeMethod->GetParamType(argIdx), wantInvokeMethod->GetParamType(argIdx + wantInvokeOffset), BfIRValue());
  539. }
  540. }
  541. }
  542. return true;
  543. }
  544. bool BfGenericInferContext::InferGenericArguments(BfMethodInstance* methodInstance, int srcGenericIdx)
  545. {
  546. auto& srcGenericArg = (*mCheckMethodGenericArguments)[srcGenericIdx];
  547. if (srcGenericArg == NULL)
  548. return false;
  549. int startInferCount = mInferredCount;
  550. auto srcGenericParam = methodInstance->mMethodInfoEx->mGenericParams[srcGenericIdx];
  551. for (auto ifaceConstraint : srcGenericParam->mInterfaceConstraints)
  552. {
  553. if ((ifaceConstraint->IsUnspecializedTypeVariation()) && (ifaceConstraint->IsGenericTypeInstance()))
  554. {
  555. InferGenericArgument(methodInstance, srcGenericArg, ifaceConstraint, BfIRValue());
  556. auto typeInstance = srcGenericArg->ToTypeInstance();
  557. if ((typeInstance == NULL) && (srcGenericArg->IsWrappableType()))
  558. typeInstance = mModule->GetWrappedStructType(srcGenericArg);
  559. if (typeInstance != NULL)
  560. {
  561. for (auto ifaceEntry : typeInstance->mInterfaces)
  562. InferGenericArgument(methodInstance, ifaceEntry.mInterfaceType, ifaceConstraint, BfIRValue());
  563. }
  564. if (srcGenericArg->IsGenericParam())
  565. {
  566. auto genericParamType = (BfGenericParamType*)srcGenericArg;
  567. BfGenericParamInstance* genericParam = NULL;
  568. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  569. genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  570. else
  571. genericParam = mModule->GetGenericParamInstance(genericParamType);
  572. if (genericParam->mTypeConstraint != NULL)
  573. InferGenericArgument(methodInstance, genericParam->mTypeConstraint, ifaceConstraint, BfIRValue());
  574. for (auto argIfaceConstraint : genericParam->mInterfaceConstraints)
  575. InferGenericArgument(methodInstance, argIfaceConstraint, ifaceConstraint, BfIRValue());
  576. }
  577. }
  578. }
  579. return mInferredCount != startInferCount;
  580. }
  581. void BfGenericInferContext::InferGenericArguments(BfMethodInstance* methodInstance)
  582. {
  583. // Attempt to infer from other generic args
  584. for (int srcGenericIdx = 0; srcGenericIdx < (int)mCheckMethodGenericArguments->size(); srcGenericIdx++)
  585. {
  586. InferGenericArguments(methodInstance, srcGenericIdx);
  587. }
  588. }
  589. int BfMethodMatcher::GetMostSpecificType(BfType* lhs, BfType* rhs)
  590. {
  591. if ((lhs->IsRef()) && (rhs->IsRef()))
  592. return GetMostSpecificType(lhs->GetUnderlyingType(), rhs->GetUnderlyingType());
  593. if ((lhs->IsPointer()) && (rhs->IsPointer()))
  594. return GetMostSpecificType(lhs->GetUnderlyingType(), rhs->GetUnderlyingType());
  595. if ((lhs->IsSizedArray()) && (rhs->IsSizedArray()))
  596. return GetMostSpecificType(lhs->GetUnderlyingType(), rhs->GetUnderlyingType());
  597. if (lhs->IsGenericParam())
  598. return rhs->IsGenericParam() ? -1 : 1;
  599. if (rhs->IsGenericParam())
  600. return 0;
  601. if ((lhs->IsUnspecializedType()) && (lhs->IsGenericTypeInstance()))
  602. {
  603. if ((!rhs->IsUnspecializedType()) || (!rhs->IsGenericTypeInstance()))
  604. return 1;
  605. auto lhsTypeInst = lhs->ToTypeInstance();
  606. auto rhsTypeInst = rhs->ToTypeInstance();
  607. if ((rhsTypeInst == NULL) || (lhsTypeInst == NULL) || (lhsTypeInst->mTypeDef != rhsTypeInst->mTypeDef))
  608. return -1;
  609. bool hadLHSMoreSpecific = false;
  610. bool hadRHSMoreSpecific = false;
  611. for (int generigArgIdx = 0; generigArgIdx < (int)lhsTypeInst->mGenericTypeInfo->mTypeGenericArguments.size(); generigArgIdx++)
  612. {
  613. int argMoreSpecific = GetMostSpecificType(lhsTypeInst->mGenericTypeInfo->mTypeGenericArguments[generigArgIdx],
  614. rhsTypeInst->mGenericTypeInfo->mTypeGenericArguments[generigArgIdx]);
  615. if (argMoreSpecific == 0)
  616. hadLHSMoreSpecific = true;
  617. else if (argMoreSpecific == 1)
  618. hadRHSMoreSpecific = true;
  619. }
  620. if ((hadLHSMoreSpecific) && (!hadRHSMoreSpecific))
  621. return 0;
  622. if ((hadRHSMoreSpecific) && (!hadLHSMoreSpecific))
  623. return 1;
  624. return -1;
  625. }
  626. if (rhs->IsUnspecializedType())
  627. return 0;
  628. return -1;
  629. }
  630. void BfMethodMatcher::CompareMethods(BfMethodInstance* prevMethodInstance, BfTypeVector* prevGenericArgumentsSubstitute,
  631. BfMethodInstance* newMethodInstance, BfTypeVector* genericArgumentsSubstitute,
  632. bool* outNewIsBetter, bool* outNewIsWorse, bool allowSpecializeFail)
  633. {
  634. if (prevMethodInstance == newMethodInstance)
  635. {
  636. *outNewIsBetter = false;
  637. *outNewIsWorse = true;
  638. return;
  639. }
  640. #define SET_BETTER_OR_WORSE(lhs, rhs) \
  641. if ((!isBetter) && (lhs) && !(rhs)) isBetter = true; \
  642. if ((!isWorse) && !(lhs) && (rhs)) isWorse = true;
  643. #define RETURN_BETTER_OR_WORSE(lhs, rhs) \
  644. if ((!isBetter) && (lhs) && !(rhs)) { *outNewIsBetter = true; *outNewIsWorse = false; return; } \
  645. if ((!isWorse) && !(lhs) && (rhs)) { *outNewIsBetter = false; *outNewIsWorse = true; return; };
  646. #define RETURN_RESULTS \
  647. *outNewIsBetter = isBetter; \
  648. *outNewIsWorse = isWorse; \
  649. return;
  650. int numUsedParams = 0;
  651. int prevNumUsedParams = 0;
  652. bool usedExtendedForm = false;
  653. bool prevUsedExtendedForm = false;
  654. bool isBetter = false;
  655. bool isWorse = false;
  656. int argIdx;
  657. BfMethodDef* prevMethodDef = prevMethodInstance->mMethodDef;
  658. BfMethodDef* newMethodDef = newMethodInstance->mMethodDef;
  659. if (prevMethodDef == mBackupMethodDef)
  660. {
  661. // This can happen for extension methods and such
  662. *outNewIsBetter = true;
  663. *outNewIsWorse = false;
  664. return;
  665. }
  666. if (newMethodDef->mExplicitInterface != prevMethodDef->mExplicitInterface)
  667. {
  668. if (mModule->CompareMethodSignatures(newMethodInstance, prevMethodInstance))
  669. {
  670. SET_BETTER_OR_WORSE(newMethodDef->mExplicitInterface != NULL, prevMethodDef->mExplicitInterface != NULL);
  671. *outNewIsBetter = isBetter;
  672. *outNewIsWorse = isWorse;
  673. return;
  674. }
  675. }
  676. bool anyIsExtension = false;
  677. int newImplicitParamCount = newMethodInstance->GetImplicitParamCount();
  678. if (newMethodInstance->mMethodDef->mHasAppend)
  679. newImplicitParamCount++;
  680. if (newMethodInstance->mMethodDef->mMethodType == BfMethodType_Extension)
  681. {
  682. newImplicitParamCount++;
  683. anyIsExtension = true;
  684. }
  685. int prevImplicitParamCount = prevMethodInstance->GetImplicitParamCount();
  686. if (prevMethodInstance->mMethodDef->mHasAppend)
  687. prevImplicitParamCount++;
  688. if (prevMethodInstance->mMethodDef->mMethodType == BfMethodType_Extension)
  689. {
  690. prevImplicitParamCount++;
  691. anyIsExtension = true;
  692. }
  693. BfCastFlags implicitCastFlags = ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp) != 0) ? BfCastFlags_NoConversionOperator : BfCastFlags_None;
  694. int newMethodParamCount = newMethodInstance->GetParamCount();
  695. int prevMethodParamCount = prevMethodInstance->GetParamCount();
  696. bool hadEnoughArgs = newMethodParamCount - newImplicitParamCount < (int)mArguments.size();
  697. bool prevHadEnoughArgs = prevMethodParamCount - prevImplicitParamCount < (int)mArguments.size();
  698. RETURN_BETTER_OR_WORSE(hadEnoughArgs, prevHadEnoughArgs);
  699. bool chainSkip = (newMethodInstance->mChainType == BfMethodChainType_ChainMember) || (newMethodInstance->mChainType == BfMethodChainType_ChainSkip);
  700. bool prevChainSkip = (prevMethodInstance->mChainType == BfMethodChainType_ChainMember) || (prevMethodInstance->mChainType == BfMethodChainType_ChainSkip);
  701. RETURN_BETTER_OR_WORSE(!chainSkip, !prevChainSkip);
  702. if ((!isBetter) && (!isWorse))
  703. {
  704. bool betterByGenericParam = false;
  705. bool worseByGenericParam = false;
  706. bool betterByConstExprParam = false;
  707. bool worseByConstExprParam = false;
  708. bool someArgWasBetter = false;
  709. bool someArgWasWorse = false;
  710. for (argIdx = anyIsExtension ? -1 : 0; argIdx < (int)mArguments.size(); argIdx++)
  711. {
  712. BfTypedValue arg;
  713. BfResolvedArg* resolvedArg = NULL;
  714. bool wasArgDeferred = false;
  715. if (argIdx == -1)
  716. {
  717. arg = mTarget;
  718. }
  719. else
  720. {
  721. resolvedArg = &mArguments[argIdx];
  722. wasArgDeferred = resolvedArg->mArgFlags != 0;
  723. arg = resolvedArg->mTypedValue;
  724. }
  725. int newArgIdx = argIdx + newImplicitParamCount;
  726. int prevArgIdx = argIdx + prevImplicitParamCount;
  727. if (newArgIdx >= newMethodParamCount)
  728. break;
  729. if (prevArgIdx >= prevMethodParamCount)
  730. break;
  731. bool wasGenericParam = (newArgIdx >= 0) && newMethodInstance->WasGenericParam(newArgIdx);
  732. bool prevWasGenericParam = (prevArgIdx >= 0) && prevMethodInstance->WasGenericParam(prevArgIdx);
  733. BfType* paramType = newMethodInstance->GetParamType(newArgIdx, true);
  734. BfType* prevParamType = prevMethodInstance->GetParamType(prevArgIdx, true);
  735. numUsedParams++;
  736. prevNumUsedParams++;
  737. BfType* origParamType = paramType;
  738. BfType* origPrevParamType = prevParamType;
  739. bool paramWasConstExpr = false;
  740. bool prevParamWasConstExpr = false;
  741. bool paramWasUnspecialized = paramType->IsUnspecializedType();
  742. if ((genericArgumentsSubstitute != NULL) && (paramWasUnspecialized))
  743. {
  744. paramType = mModule->ResolveGenericType(paramType, NULL, genericArgumentsSubstitute, mModule->mCurTypeInstance, allowSpecializeFail);
  745. paramType = mModule->FixIntUnknown(paramType);
  746. }
  747. if (paramType->IsConstExprValue())
  748. {
  749. prevParamWasConstExpr = true;
  750. paramType = ((BfConstExprValueType*)paramType)->mType;
  751. }
  752. bool prevParamWasUnspecialized = prevParamType->IsUnspecializedType();
  753. if ((prevGenericArgumentsSubstitute != NULL) && (prevParamWasUnspecialized))
  754. {
  755. prevParamType = mModule->ResolveGenericType(prevParamType, NULL, prevGenericArgumentsSubstitute, mModule->mCurTypeInstance, allowSpecializeFail);
  756. prevParamType = mModule->FixIntUnknown(prevParamType);
  757. }
  758. if (prevParamType->IsConstExprValue())
  759. {
  760. prevParamWasConstExpr = true;
  761. prevParamType = ((BfConstExprValueType*)prevParamType)->mType;
  762. }
  763. bool paramsEquivalent = paramType == prevParamType;
  764. if ((prevParamType == NULL) || (paramType == NULL))
  765. {
  766. SET_BETTER_OR_WORSE(paramType != NULL, prevParamType != NULL);
  767. }
  768. else if (paramType != prevParamType)
  769. {
  770. bool isUnspecializedParam = paramType->IsUnspecializedType();
  771. bool isPrevUnspecializedParam = prevParamType->IsUnspecializedType();
  772. SET_BETTER_OR_WORSE((!isUnspecializedParam) && (!paramType->IsVar()),
  773. (!isPrevUnspecializedParam) && (!prevParamType->IsVar()));
  774. if ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp_Explicit) != 0)
  775. {
  776. // Pick the one that can implicitly cast
  777. SET_BETTER_OR_WORSE(
  778. mModule->CanCast(arg, paramType, implicitCastFlags),
  779. mModule->CanCast(arg, prevParamType, implicitCastFlags));
  780. }
  781. // Why did we have this !isUnspecializedParam check? We need the 'canCast' logic still
  782. if ((!isBetter) && (!isWorse) /*&& (!isUnspecializedParam) && (!isPrevUnspecializedParam)*/)
  783. {
  784. SET_BETTER_OR_WORSE((paramType != NULL) && (!paramType->IsUnspecializedType()),
  785. (prevParamType != NULL) && (!prevParamType->IsUnspecializedType()));
  786. if ((!isBetter) && (!isWorse))
  787. {
  788. // The resolved argument type may actually match for both considered functions. IE:
  789. // Method(int8 val) and Method(int16 val) called with Method(0) will create arguments that match their param types
  790. if ((!wasArgDeferred) && (!wasGenericParam) && (IsType(arg, paramType)) && ((resolvedArg == NULL) || (prevParamType != resolvedArg->mBestBoundType)))
  791. isBetter = true;
  792. //else if ((!prevWasGenericParam) && (IsType(arg, prevParamType)) && (!IsType(arg, paramType)))
  793. else if ((!wasArgDeferred) && (!prevWasGenericParam) && (IsType(arg, prevParamType)) && ((resolvedArg == NULL) || (paramType != resolvedArg->mBestBoundType)))
  794. isWorse = true;
  795. else
  796. {
  797. bool canCastFromCurToPrev = mModule->CanCast(mModule->GetFakeTypedValue(paramType), prevParamType, implicitCastFlags);
  798. bool canCastFromPrevToCur = mModule->CanCast(mModule->GetFakeTypedValue(prevParamType), paramType, implicitCastFlags);
  799. if ((canCastFromCurToPrev) && (canCastFromPrevToCur))
  800. paramsEquivalent = true;
  801. if ((canCastFromCurToPrev) && (!canCastFromPrevToCur))
  802. isBetter = true;
  803. else if ((canCastFromPrevToCur) && (!canCastFromCurToPrev))
  804. isWorse = true;
  805. else if ((paramType->IsIntegral()) && (prevParamType->IsIntegral()))
  806. {
  807. if (paramType == arg.mType)
  808. isBetter = true;
  809. else if (prevParamType == arg.mType)
  810. isWorse = true;
  811. else
  812. {
  813. if (paramType->mSize < prevParamType->mSize)
  814. isBetter = true;
  815. else if (paramType->mSize > prevParamType->mSize)
  816. isWorse = true;
  817. else if (paramType->IsSigned())
  818. isBetter = true;
  819. else
  820. isWorse = true;
  821. }
  822. }
  823. else if ((wasArgDeferred) && ((paramType->IsIntegral()) || (prevParamType->IsIntegral())))
  824. {
  825. SET_BETTER_OR_WORSE(paramType->IsIntegral(), prevParamType->IsIntegral());
  826. }
  827. }
  828. }
  829. }
  830. }
  831. if ((!isBetter) && (!isWorse) && (paramsEquivalent))
  832. {
  833. if ((origParamType != origPrevParamType) && (paramWasConstExpr) && (!prevParamWasConstExpr))
  834. betterByConstExprParam = true;
  835. else if ((origParamType != origPrevParamType) && (!paramWasConstExpr) && (prevParamWasConstExpr))
  836. worseByConstExprParam = true;
  837. else if (((paramWasUnspecialized) || (prevParamWasUnspecialized)))
  838. {
  839. int origTypeMoreSpecific = GetMostSpecificType(origParamType, origPrevParamType);
  840. if (origTypeMoreSpecific == 0)
  841. betterByGenericParam = true;
  842. else if (origTypeMoreSpecific == 1)
  843. worseByGenericParam = true;
  844. }
  845. }
  846. if ((newArgIdx >= 0) && (newMethodInstance->GetParamKind(newArgIdx) == BfParamKind_Params))
  847. usedExtendedForm = true;
  848. if ((prevArgIdx >= 0) && (prevMethodInstance->GetParamKind(prevArgIdx) == BfParamKind_Params))
  849. prevUsedExtendedForm = true;
  850. if ((usedExtendedForm) || (prevUsedExtendedForm))
  851. break;
  852. someArgWasBetter |= isBetter;
  853. someArgWasWorse |= isWorse;
  854. isBetter = false;
  855. isWorse = false;
  856. }
  857. isBetter |= someArgWasBetter;
  858. isWorse |= someArgWasWorse;
  859. if ((!isBetter) && (!isWorse))
  860. {
  861. // Don't allow ambiguity
  862. if ((betterByGenericParam && !worseByGenericParam) ||
  863. (!betterByGenericParam && worseByGenericParam))
  864. {
  865. isBetter = betterByGenericParam;
  866. isWorse = worseByGenericParam;
  867. }
  868. }
  869. if ((!isBetter) && (!isWorse))
  870. {
  871. // Don't allow ambiguity
  872. if ((betterByConstExprParam && !worseByConstExprParam) ||
  873. (!betterByConstExprParam && worseByConstExprParam))
  874. {
  875. isBetter = betterByConstExprParam;
  876. isWorse = worseByConstExprParam;
  877. }
  878. }
  879. if ((isBetter) || (isWorse))
  880. {
  881. RETURN_RESULTS;
  882. }
  883. }
  884. // Choose by return type for conversion operators
  885. if (((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp) != 0) && (!isBetter) && (!isWorse))
  886. {
  887. auto returnType = newMethodInstance->mReturnType;
  888. auto prevReturnType = prevMethodInstance->mReturnType;
  889. if ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp_Explicit) != 0)
  890. {
  891. // Pick the one that can implicitly cast
  892. SET_BETTER_OR_WORSE(
  893. mModule->CanCast(mModule->GetFakeTypedValue(returnType), mCheckReturnType, implicitCastFlags),
  894. mModule->CanCast(mModule->GetFakeTypedValue(prevReturnType), mCheckReturnType, implicitCastFlags));
  895. }
  896. if ((!isBetter) && (!isWorse))
  897. {
  898. bool canCastFromCurToPrev = mModule->CanCast(mModule->GetFakeTypedValue(returnType), prevReturnType, implicitCastFlags);
  899. bool canCastFromPrevToCur = mModule->CanCast(mModule->GetFakeTypedValue(prevReturnType), returnType, implicitCastFlags);
  900. if ((canCastFromCurToPrev) && (!canCastFromPrevToCur))
  901. isWorse = true;
  902. else if ((canCastFromPrevToCur) && (!canCastFromCurToPrev))
  903. isBetter = true;
  904. }
  905. if ((isBetter) || (isWorse))
  906. {
  907. RETURN_RESULTS;
  908. }
  909. }
  910. // Check for unused extended params as next param - that still counts as using extended form
  911. usedExtendedForm = newMethodInstance->HasParamsArray();
  912. prevUsedExtendedForm = prevMethodInstance->HasParamsArray();
  913. RETURN_BETTER_OR_WORSE(newMethodInstance->GetNumGenericArguments() == 0, prevMethodInstance->GetNumGenericArguments() == 0);
  914. // Not using generic delegate params is better
  915. RETURN_BETTER_OR_WORSE(!newMethodInstance->mHadGenericDelegateParams, !prevMethodInstance->mHadGenericDelegateParams);
  916. // Normal form trumps extended form
  917. RETURN_BETTER_OR_WORSE(!usedExtendedForm, !prevUsedExtendedForm);
  918. // More used params trumps less params
  919. int paramDiff = (int) numUsedParams - (int) prevNumUsedParams;
  920. RETURN_BETTER_OR_WORSE(paramDiff > 0, paramDiff < 0);
  921. // Fewer defaults trumps more defaults
  922. // Since we know the number of used params is the same (previous check), we infer that the rest are defaults
  923. paramDiff = (int) newMethodInstance->GetParamCount() - (int) prevMethodInstance->GetParamCount();
  924. RETURN_BETTER_OR_WORSE(paramDiff < 0, paramDiff > 0);
  925. BfMethodInstance* typeUnspecNewMethodInstance = mModule->GetUnspecializedMethodInstance(newMethodInstance, true);
  926. BfMethodInstance* typeUnspecPrevMethodInstance = mModule->GetUnspecializedMethodInstance(prevMethodInstance, true);
  927. // Check specificity of args
  928. std::function<void(BfType*, BfType*)> _CompareParamTypes = [&](BfType* newType, BfType* prevType)
  929. {
  930. if ((newType->IsGenericParam()) && (prevType->IsGenericParam()))
  931. {
  932. auto newGenericParamType = (BfGenericParamType*)newType;
  933. auto prevGenericParamType = (BfGenericParamType*)prevType;
  934. if ((newGenericParamType->mGenericParamKind == BfGenericParamKind_Method) && (prevGenericParamType->mGenericParamKind == BfGenericParamKind_Method))
  935. {
  936. auto newMethodGenericParam = typeUnspecNewMethodInstance->mMethodInfoEx->mGenericParams[newGenericParamType->mGenericParamIdx];
  937. auto prevMethodGenericParam = typeUnspecPrevMethodInstance->mMethodInfoEx->mGenericParams[prevGenericParamType->mGenericParamIdx];
  938. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  939. }
  940. }
  941. else if (newType == prevType)
  942. {
  943. if ((newType->IsUnspecializedType()) && (newType->IsGenericTypeInstance()))
  944. {
  945. BfTypeInstance* newGenericType = (BfTypeInstance*)newType;
  946. BfTypeInstance* prevGenericType = (BfTypeInstance*)prevType;
  947. for (int genericArgIdx = 0; genericArgIdx < (int)newGenericType->mGenericTypeInfo->mTypeGenericArguments.size(); genericArgIdx++)
  948. {
  949. _CompareParamTypes(newGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx], prevGenericType->mGenericTypeInfo->mTypeGenericArguments[genericArgIdx]);
  950. }
  951. }
  952. }
  953. else
  954. {
  955. //TODO: Why did we need this?
  956. //isBetter |= mModule->IsTypeMoreSpecific(newType, prevType);
  957. //isWorse |= mModule->IsTypeMoreSpecific(prevType, newType);
  958. }
  959. };
  960. int paramCheckCount = (int)BF_MIN(newMethodInstance->GetParamCount() - newImplicitParamCount, prevMethodInstance->GetParamCount() - prevImplicitParamCount);
  961. for (argIdx = 0; argIdx < (int)paramCheckCount/*mArguments.size()*/; argIdx++)
  962. {
  963. int newArgIdx = argIdx + newImplicitParamCount;
  964. int prevArgIdx = argIdx + prevImplicitParamCount;
  965. _CompareParamTypes(typeUnspecNewMethodInstance->GetParamType(newArgIdx), typeUnspecPrevMethodInstance->GetParamType(prevArgIdx));
  966. }
  967. // Do generic constraint subset test directly to handle cases like "NotDisposed<T>()" vs "NotDisposed<T>() where T : IDisposable"
  968. if ((newMethodInstance->GetNumGenericArguments() > 0) && (newMethodInstance->GetNumGenericArguments() == prevMethodInstance->GetNumGenericArguments()))
  969. {
  970. for (int genericParamIdx = 0; genericParamIdx < (int)newMethodInstance->GetNumGenericArguments(); genericParamIdx++)
  971. {
  972. auto newMethodGenericParam = newMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  973. auto prevMethodGenericParam = prevMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  974. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  975. }
  976. if ((!isBetter) && (!isWorse))
  977. {
  978. SET_BETTER_OR_WORSE(newMethodInstance->HasExternConstraints(), prevMethodInstance->HasExternConstraints());
  979. }
  980. }
  981. if ((isBetter) || (isWorse))
  982. {
  983. RETURN_RESULTS;
  984. }
  985. // For operators, prefer explicit comparison over '<=>' comparison operator
  986. if ((!isBetter) && (!isWorse))
  987. {
  988. if ((prevMethodDef->mIsOperator) && (newMethodDef->mIsOperator))
  989. {
  990. bool newIsComparison = ((BfOperatorDeclaration*)newMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  991. bool prevIsComparison = ((BfOperatorDeclaration*)prevMethodDef->mMethodDeclaration)->mBinOp == BfBinaryOp_Compare;
  992. RETURN_BETTER_OR_WORSE(!newIsComparison, !prevIsComparison);
  993. }
  994. }
  995. if ((newMethodInstance->mMethodDef->mExternalConstraints.size() != 0) || (prevMethodInstance->mMethodDef->mExternalConstraints.size() != 0))
  996. {
  997. struct GenericParamPair
  998. {
  999. BfGenericMethodParamInstance* mParams[2];
  1000. GenericParamPair()
  1001. {
  1002. mParams[0] = NULL;
  1003. mParams[1] = NULL;
  1004. }
  1005. };
  1006. Dictionary<BfType*, GenericParamPair> externConstraints;
  1007. auto _GetParams = [&](int idx, BfMethodInstance* methodInstance)
  1008. {
  1009. for (int externConstraintIdx = 0; externConstraintIdx < (int)methodInstance->mMethodDef->mExternalConstraints.size(); externConstraintIdx++)
  1010. {
  1011. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[methodInstance->mMethodDef->mGenericParams.size() + externConstraintIdx];
  1012. BF_ASSERT(genericParam->mExternType != NULL);
  1013. GenericParamPair* pairPtr = NULL;
  1014. externConstraints.TryAdd(genericParam->mExternType, NULL, &pairPtr);
  1015. pairPtr->mParams[idx] = genericParam;
  1016. }
  1017. };
  1018. _GetParams(0, newMethodInstance);
  1019. _GetParams(1, prevMethodInstance);
  1020. for (auto kv : externConstraints)
  1021. {
  1022. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(kv.mValue.mParams[1], kv.mValue.mParams[0]), mModule->AreConstraintsSubset(kv.mValue.mParams[0], kv.mValue.mParams[1]));
  1023. }
  1024. if ((isBetter) || (isWorse))
  1025. {
  1026. RETURN_RESULTS;
  1027. }
  1028. }
  1029. // Does one have a body and one doesn't? Obvious!
  1030. isBetter = prevMethodDef->IsEmptyPartial();
  1031. isWorse = newMethodDef->IsEmptyPartial();
  1032. if ((isBetter) && (isWorse))
  1033. {
  1034. // If both are empty partials then just bind to either
  1035. isWorse = true;
  1036. RETURN_RESULTS;
  1037. }
  1038. // For extensions, select the version in the most-specific project (only applicable for ctors)
  1039. if ((!isBetter) && (!isWorse))
  1040. {
  1041. auto newProject = newMethodDef->mDeclaringType->mProject;
  1042. auto prevProject = prevMethodDef->mDeclaringType->mProject;
  1043. if (newProject != prevProject)
  1044. {
  1045. RETURN_BETTER_OR_WORSE(newProject->ContainsReference(prevProject), prevProject->ContainsReference(newProject));
  1046. }
  1047. }
  1048. // If we have conditional type extensions that both define an implementation for a method, use the most-specific conditional extension constraints
  1049. auto owner = newMethodInstance->GetOwner();
  1050. if ((newMethodDef->mDeclaringType != prevMethodDef->mDeclaringType) && (owner->IsGenericTypeInstance()))
  1051. {
  1052. auto genericOwner = (BfTypeInstance*)owner;
  1053. if (genericOwner->mGenericTypeInfo->mGenericExtensionInfo != NULL)
  1054. {
  1055. BfGenericExtensionEntry* newGenericExtesionEntry = NULL;
  1056. BfGenericExtensionEntry* prevGenericExtesionEntry = NULL;
  1057. if ((genericOwner->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.TryGetValue(newMethodDef->mDeclaringType, &newGenericExtesionEntry)) &&
  1058. (genericOwner->mGenericTypeInfo->mGenericExtensionInfo->mExtensionMap.TryGetValue(prevMethodDef->mDeclaringType, &prevGenericExtesionEntry)))
  1059. {
  1060. if ((newGenericExtesionEntry->mGenericParams.size() == prevGenericExtesionEntry->mGenericParams.size()))
  1061. {
  1062. for (int genericParamIdx = 0; genericParamIdx < (int)newGenericExtesionEntry->mGenericParams.size(); genericParamIdx++)
  1063. {
  1064. auto newMethodGenericParam = newGenericExtesionEntry->mGenericParams[genericParamIdx];
  1065. auto prevMethodGenericParam = prevGenericExtesionEntry->mGenericParams[genericParamIdx];
  1066. SET_BETTER_OR_WORSE(mModule->AreConstraintsSubset(prevMethodGenericParam, newMethodGenericParam), mModule->AreConstraintsSubset(newMethodGenericParam, prevMethodGenericParam));
  1067. }
  1068. }
  1069. if ((isBetter) || (isWorse))
  1070. {
  1071. RETURN_RESULTS;
  1072. }
  1073. }
  1074. }
  1075. }
  1076. RETURN_BETTER_OR_WORSE(newMethodDef->mCheckedKind == mCheckedKind, prevMethodDef->mCheckedKind == mCheckedKind);
  1077. RETURN_BETTER_OR_WORSE(newMethodDef->mCommutableKind != BfCommutableKind_Reverse, prevMethodDef->mCommutableKind != BfCommutableKind_Reverse);
  1078. // If one of these methods is local to the current extension then choose that one
  1079. auto activeDef = mModule->GetActiveTypeDef();
  1080. RETURN_BETTER_OR_WORSE(newMethodDef->mDeclaringType == activeDef, prevMethodDef->mDeclaringType == activeDef);
  1081. RETURN_BETTER_OR_WORSE(newMethodDef->mDeclaringType->IsExtension(), prevMethodDef->mDeclaringType->IsExtension());
  1082. RETURN_BETTER_OR_WORSE(newMethodDef->mIsMutating, prevMethodDef->mIsMutating);
  1083. if (newMethodDef->mHasComptime != prevMethodDef->mHasComptime)
  1084. {
  1085. bool isComptime = (mModule->mIsComptimeModule) || ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  1086. RETURN_BETTER_OR_WORSE(newMethodDef->mHasComptime == isComptime, prevMethodDef->mHasComptime == isComptime);
  1087. }
  1088. RETURN_RESULTS;
  1089. }
  1090. BfTypedValue BfMethodMatcher::ResolveArgTypedValue(BfResolvedArg& resolvedArg, BfType* checkType, BfTypeVector* genericArgumentsSubstitute, BfType *origCheckType, BfResolveArgFlags flags)
  1091. {
  1092. BfTypedValue argTypedValue = resolvedArg.mTypedValue;
  1093. if ((resolvedArg.mArgFlags & BfArgFlag_DelegateBindAttempt) != 0)
  1094. {
  1095. BfExprEvaluator exprEvaluator(mModule);
  1096. exprEvaluator.mExpectingType = checkType;
  1097. BF_ASSERT(resolvedArg.mExpression->IsA<BfDelegateBindExpression>());
  1098. auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(resolvedArg.mExpression);
  1099. BfMethodInstance* boundMethodInstance = NULL;
  1100. auto bindType = checkType;
  1101. if ((bindType == NULL) && (origCheckType != NULL) && (!origCheckType->IsUnspecializedTypeVariation()))
  1102. bindType = checkType;
  1103. if (exprEvaluator.CanBindDelegate(delegateBindExpr, &boundMethodInstance, bindType, genericArgumentsSubstitute))
  1104. {
  1105. if (delegateBindExpr->mNewToken == NULL)
  1106. {
  1107. if (boundMethodInstance->GetOwner()->IsFunction())
  1108. {
  1109. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), boundMethodInstance->GetOwner());
  1110. }
  1111. else if ((boundMethodInstance->mDisallowCalling) || ((flags & BfResolveArgFlag_FromGeneric) == 0))
  1112. {
  1113. argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), checkType);
  1114. }
  1115. else
  1116. {
  1117. resolvedArg.mExpectedType = checkType;
  1118. auto methodRefType = mModule->CreateMethodRefType(boundMethodInstance);
  1119. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  1120. mModule->AddCallDependency(boundMethodInstance);
  1121. argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodRefType);
  1122. }
  1123. }
  1124. else
  1125. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1126. }
  1127. }
  1128. else if ((resolvedArg.mArgFlags & BfArgFlag_LambdaBindAttempt) != 0)
  1129. {
  1130. if ((argTypedValue) && (argTypedValue.mType->IsMethodRef()) &&
  1131. ((checkType == NULL) || (!checkType->IsMethodRef())))
  1132. {
  1133. // This may be from a previous checkMethod, clear it out
  1134. argTypedValue = BfTypedValue();
  1135. }
  1136. BfExprEvaluator exprEvaluator(mModule);
  1137. exprEvaluator.mExpectingType = checkType;
  1138. BF_ASSERT(resolvedArg.mExpression->IsA<BfLambdaBindExpression>());
  1139. auto lambdaBindExpr = (BfLambdaBindExpression*)resolvedArg.mExpression;
  1140. if ((checkType != NULL) && (checkType->IsDelegate()))
  1141. {
  1142. BfMethodInstance* methodInstance = mModule->GetRawMethodInstanceAtIdx(checkType->ToTypeInstance(), 0, "Invoke");
  1143. if (methodInstance != NULL)
  1144. {
  1145. if (methodInstance->GetParamCount() == (int)lambdaBindExpr->mParams.size())
  1146. {
  1147. if (lambdaBindExpr->mNewToken == NULL)
  1148. {
  1149. if (!resolvedArg.mTypedValue)
  1150. {
  1151. // Resolve for real
  1152. resolvedArg.mTypedValue = mModule->CreateValueFromExpression(lambdaBindExpr, checkType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_NoAutoComplete));
  1153. }
  1154. argTypedValue = resolvedArg.mTypedValue;
  1155. }
  1156. else
  1157. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1158. //argTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), checkType);
  1159. }
  1160. }
  1161. }
  1162. else if ((checkType == NULL) && (origCheckType != NULL) && (origCheckType->IsUnspecializedTypeVariation()) && (genericArgumentsSubstitute != NULL) && (origCheckType->IsDelegateOrFunction()))
  1163. {
  1164. BfMethodInstance* methodInstance = mModule->GetRawMethodInstanceAtIdx(origCheckType->ToTypeInstance(), 0, "Invoke");
  1165. if (methodInstance != NULL)
  1166. {
  1167. if ((methodInstance->mReturnType->IsGenericParam()) && (((BfGenericParamType*)methodInstance->mReturnType)->mGenericParamKind == BfGenericParamKind_Method))
  1168. {
  1169. bool isValid = true;
  1170. int returnMethodGenericArgIdx = ((BfGenericParamType*)methodInstance->mReturnType)->mGenericParamIdx;
  1171. if ((*genericArgumentsSubstitute)[returnMethodGenericArgIdx] != NULL)
  1172. {
  1173. isValid = false;
  1174. }
  1175. if (methodInstance->mParams.size() != (int)lambdaBindExpr->mParams.size())
  1176. isValid = false;
  1177. for (auto& param : methodInstance->mParams)
  1178. {
  1179. if (param.mResolvedType->IsGenericParam())
  1180. {
  1181. auto genericParamType = (BfGenericParamType*)param.mResolvedType;
  1182. if ((genericParamType->mGenericParamKind == BfGenericParamKind_Method) && ((*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx] == NULL))
  1183. {
  1184. isValid = false;
  1185. }
  1186. }
  1187. }
  1188. if (isValid)
  1189. {
  1190. bool success = false;
  1191. (*genericArgumentsSubstitute)[returnMethodGenericArgIdx] = mModule->GetPrimitiveType(BfTypeCode_None);
  1192. auto tryType = mModule->ResolveGenericType(origCheckType, NULL, genericArgumentsSubstitute, mModule->mCurTypeInstance);
  1193. if (tryType != NULL)
  1194. {
  1195. auto inferredReturnType = mModule->CreateValueFromExpression(lambdaBindExpr, tryType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_InferReturnType | BfEvalExprFlags_NoAutoComplete));
  1196. if (inferredReturnType.mType != NULL)
  1197. {
  1198. (*genericArgumentsSubstitute)[returnMethodGenericArgIdx] = inferredReturnType.mType;
  1199. if (((flags & BfResolveArgFlag_FromGenericParam) != 0) && (lambdaBindExpr->mNewToken == NULL))
  1200. {
  1201. auto resolvedType = mModule->ResolveGenericType(origCheckType, NULL, genericArgumentsSubstitute, mModule->mCurTypeInstance);
  1202. if (resolvedType != NULL)
  1203. {
  1204. // Resolve for real
  1205. resolvedArg.mTypedValue = mModule->CreateValueFromExpression(lambdaBindExpr, resolvedType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_NoAutoComplete));
  1206. argTypedValue = resolvedArg.mTypedValue;
  1207. }
  1208. }
  1209. success = true;
  1210. }
  1211. }
  1212. if (!success)
  1213. {
  1214. // Put back
  1215. (*genericArgumentsSubstitute)[returnMethodGenericArgIdx] = NULL;
  1216. }
  1217. }
  1218. }
  1219. }
  1220. }
  1221. }
  1222. else if ((resolvedArg.mArgFlags & BfArgFlag_UnqualifiedDotAttempt) != 0)
  1223. {
  1224. if ((checkType != NULL) && (checkType->IsPayloadEnum()))
  1225. {
  1226. // Should we actually check the member name?
  1227. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1228. }
  1229. }
  1230. else if ((resolvedArg.mArgFlags & BfArgFlag_UntypedDefault) != 0)
  1231. {
  1232. if (checkType != NULL)
  1233. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1234. }
  1235. else if ((resolvedArg.mArgFlags & BfArgFlag_DeferredEval) != 0)
  1236. {
  1237. if (resolvedArg.mExpression != NULL)
  1238. {
  1239. if ((resolvedArg.mExpectedType != checkType) || (resolvedArg.mExpectedType == NULL)) // Did our last check match for this type?
  1240. {
  1241. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  1242. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  1243. bool prevNoBind = false;
  1244. if (mModule->mCurMethodState != NULL)
  1245. {
  1246. prevNoBind = mModule->mCurMethodState->mNoBind;
  1247. mModule->mCurMethodState->mNoBind = true;
  1248. }
  1249. auto prevBlock = mModule->mBfIRBuilder->GetInsertBlock();
  1250. BfExprEvaluator exprEvaluator(mModule);
  1251. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags);
  1252. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowIntUnknown | BfEvalExprFlags_NoAutoComplete);
  1253. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1254. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  1255. auto expectType = checkType;
  1256. if (expectType != NULL)
  1257. {
  1258. if (expectType->IsRef())
  1259. {
  1260. auto refType = (BfRefType*)expectType;
  1261. expectType = refType->mElementType;
  1262. }
  1263. if ((genericArgumentsSubstitute != NULL) && (expectType->IsUnspecializedType()))
  1264. expectType = mModule->ResolveGenericType(expectType, NULL, genericArgumentsSubstitute, mModule->mCurTypeInstance, true);
  1265. }
  1266. exprEvaluator.mExpectingType = expectType;
  1267. exprEvaluator.Evaluate(resolvedArg.mExpression);
  1268. argTypedValue = exprEvaluator.GetResult();
  1269. if ((argTypedValue) && (argTypedValue.mType->IsVar()))
  1270. argTypedValue = BfTypedValue();
  1271. if (mModule->mCurMethodState != NULL)
  1272. mModule->mCurMethodState->mNoBind = prevNoBind;
  1273. if ((argTypedValue) && (!argTypedValue.mType->IsVar()))
  1274. {
  1275. if (checkType != NULL)
  1276. resolvedArg.mExpectedType = checkType;
  1277. auto storeTypedValue = argTypedValue;
  1278. if ((storeTypedValue.mValue) & (!storeTypedValue.mValue.IsFake()))
  1279. {
  1280. // We actually want to ensure that this cached value is a fake val. There are potential cases where a fake val
  1281. // won't be generated but we should throw an error, so we need to make sure we actually re-evaluate when the call
  1282. // is generated
  1283. //storeTypedValue.mValue = mModule->mBfIRBuilder->GetFakeVal();
  1284. resolvedArg.mWantsRecalc = true;
  1285. }
  1286. resolvedArg.mTypedValue = storeTypedValue;
  1287. //BF_ASSERT(argTypedValue.mValue.mId != -1);
  1288. }
  1289. mModule->mBfIRBuilder->SetInsertPoint(prevBlock);
  1290. }
  1291. }
  1292. }
  1293. else if ((resolvedArg.mArgFlags & BfArgFlag_VariableDeclaration) != 0)
  1294. {
  1295. if ((checkType != NULL) && (checkType->IsRef()))
  1296. argTypedValue = BfTypedValue(BfTypedValueKind_UntypedValue);
  1297. }
  1298. return argTypedValue;
  1299. }
  1300. bool BfMethodMatcher::WantsCheckMethod(BfProtectionCheckFlags& flags, BfTypeInstance* startTypeInstance, BfTypeInstance* checkTypeInstance, BfMethodDef* checkMethod)
  1301. {
  1302. MatchFailKind matchFailKind = MatchFailKind_None;
  1303. if (!mModule->CheckProtection(flags, checkTypeInstance, checkMethod->mDeclaringType->mProject, checkMethod->mProtection, startTypeInstance))
  1304. {
  1305. if ((mBypassVirtual) &&
  1306. ((checkMethod->mProtection == BfProtection_Protected) || (checkMethod->mProtection == BfProtection_ProtectedInternal)) &&
  1307. (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, startTypeInstance)))
  1308. {
  1309. // Allow explicit 'base' call
  1310. }
  1311. else
  1312. {
  1313. return false;
  1314. }
  1315. }
  1316. if (mCheckedKind != checkMethod->mCheckedKind)
  1317. {
  1318. bool passes = true;
  1319. if (mCheckedKind != BfCheckedKind_NotSet)
  1320. {
  1321. passes = false;
  1322. }
  1323. else
  1324. {
  1325. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  1326. if (defaultCheckedKind != checkMethod->mCheckedKind)
  1327. passes = false;
  1328. }
  1329. if (!passes)
  1330. {
  1331. return false;
  1332. }
  1333. }
  1334. return true;
  1335. }
  1336. bool BfMethodMatcher::InferFromGenericConstraints(BfMethodInstance* methodInstance, BfGenericParamInstance* genericParamInst, BfTypeVector* methodGenericArgs)
  1337. {
  1338. if (!genericParamInst->mExternType->IsGenericParam())
  1339. return false;
  1340. auto genericParamType = (BfGenericParamType*)genericParamInst->mExternType;
  1341. if (genericParamType->mGenericParamKind != BfGenericParamKind_Method)
  1342. return false;
  1343. BfType* checkArgType = NULL;
  1344. for (auto& checkOpConstraint : genericParamInst->mOperatorConstraints)
  1345. {
  1346. auto leftType = checkOpConstraint.mLeftType;
  1347. if ((leftType != NULL) && (leftType->IsUnspecializedType()))
  1348. leftType = mModule->ResolveGenericType(leftType, NULL, methodGenericArgs, mModule->mCurTypeInstance);
  1349. if (leftType != NULL)
  1350. leftType = mModule->FixIntUnknown(leftType);
  1351. auto rightType = checkOpConstraint.mRightType;
  1352. if ((rightType != NULL) && (rightType->IsUnspecializedType()))
  1353. rightType = mModule->ResolveGenericType(rightType, NULL, methodGenericArgs, mModule->mCurTypeInstance);
  1354. if (rightType != NULL)
  1355. rightType = mModule->FixIntUnknown(rightType);
  1356. BfConstraintState constraintSet;
  1357. constraintSet.mPrevState = mModule->mContext->mCurConstraintState;
  1358. constraintSet.mGenericParamInstance = genericParamInst;
  1359. constraintSet.mLeftType = leftType;
  1360. constraintSet.mRightType = rightType;
  1361. SetAndRestoreValue<BfConstraintState*> prevConstraintSet(mModule->mContext->mCurConstraintState, &constraintSet);
  1362. if (!mModule->CheckConstraintState(NULL))
  1363. return false;
  1364. if (checkOpConstraint.mBinaryOp != BfBinaryOp_None)
  1365. {
  1366. if ((leftType == NULL) || (rightType == NULL))
  1367. continue;
  1368. BfExprEvaluator exprEvaluator(mModule);
  1369. BfTypedValue leftValue(mModule->mBfIRBuilder->GetFakeVal(), leftType);
  1370. BfTypedValue rightValue(mModule->mBfIRBuilder->GetFakeVal(), rightType);
  1371. //
  1372. {
  1373. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  1374. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  1375. exprEvaluator.PerformBinaryOperation(NULL, NULL, checkOpConstraint.mBinaryOp, NULL, BfBinOpFlag_NoClassify, leftValue, rightValue);
  1376. }
  1377. if (exprEvaluator.mResult)
  1378. checkArgType = exprEvaluator.mResult.mType;
  1379. }
  1380. else
  1381. {
  1382. if (rightType == NULL)
  1383. continue;
  1384. BfTypedValue rightValue(mModule->mBfIRBuilder->GetFakeVal(), rightType);
  1385. StringT<128> failedOpName;
  1386. if (checkOpConstraint.mCastToken == BfToken_Implicit)
  1387. {
  1388. }
  1389. else
  1390. {
  1391. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  1392. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  1393. if (checkOpConstraint.mCastToken == BfToken_Explicit)
  1394. {
  1395. }
  1396. else
  1397. {
  1398. BfExprEvaluator exprEvaluator(mModule);
  1399. exprEvaluator.mResult = rightValue;
  1400. exprEvaluator.PerformUnaryOperation(NULL, checkOpConstraint.mUnaryOp, NULL, BfUnaryOpFlag_IsConstraintCheck);
  1401. if (exprEvaluator.mResult)
  1402. checkArgType = exprEvaluator.mResult.mType;
  1403. }
  1404. }
  1405. }
  1406. }
  1407. if ((checkArgType == NULL) && ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_ComptypeExpr) != 0))
  1408. {
  1409. for (auto comptypeConstraint : genericParamInst->mComptypeConstraint)
  1410. {
  1411. checkArgType = mModule->ResolveGenericMethodTypeRef(comptypeConstraint, methodInstance, genericParamInst, methodGenericArgs);
  1412. if (checkArgType == NULL)
  1413. return false;
  1414. }
  1415. }
  1416. if (checkArgType == NULL)
  1417. return false;
  1418. if (checkArgType->IsVar())
  1419. return false;
  1420. (*methodGenericArgs)[genericParamType->mGenericParamIdx] = checkArgType;
  1421. return true;
  1422. }
  1423. bool BfMethodMatcher::CheckMethod(BfTypeInstance* targetTypeInstance, BfTypeInstance* typeInstance, BfMethodDef* checkMethod, bool isFailurePass)
  1424. {
  1425. BP_ZONE("BfMethodMatcher::CheckMethod");
  1426. BackupMatchKind curMatchKind = BackupMatchKind_None;
  1427. bool hadMatch = false;
  1428. // Never consider overrides - they only get found at original method declaration
  1429. // mBypassVirtual gets set when we are doing an explicit "base" call, or when we are a struct --
  1430. // because on structs we know the exact type
  1431. if ((checkMethod->mIsOverride) && (!mBypassVirtual) && (!typeInstance->IsValueType()))
  1432. return false;
  1433. mMethodCheckCount++;
  1434. BfMethodInstance* methodInstance = mModule->GetRawMethodInstance(typeInstance, checkMethod);
  1435. if (methodInstance == NULL)
  1436. return false;
  1437. BfMethodInstance* typeUnspecMethodInstance = mModule->GetUnspecializedMethodInstance(methodInstance, true);
  1438. BfTypeVector* typeGenericArguments = NULL;
  1439. if (typeInstance->mGenericTypeInfo != NULL)
  1440. typeGenericArguments = &typeInstance->mGenericTypeInfo->mTypeGenericArguments;
  1441. if ((mInterfaceMethodInstance != NULL) && (methodInstance->GetExplicitInterface() != NULL))
  1442. {
  1443. BfTypeInstance* wantInterface = mInterfaceMethodInstance->mMethodInstanceGroup->mOwner;
  1444. if (wantInterface != methodInstance->GetExplicitInterface())
  1445. return false;
  1446. }
  1447. if ((checkMethod->mIsVirtual) && (!checkMethod->mIsOverride) && (!mBypassVirtual) &&
  1448. (targetTypeInstance != NULL) && (targetTypeInstance->IsObject()))
  1449. {
  1450. mModule->PopulateType(targetTypeInstance, BfPopulateType_DataAndMethods);
  1451. if ((methodInstance->mVirtualTableIdx < targetTypeInstance->mVirtualMethodTable.mSize) && (methodInstance->mVirtualTableIdx >= 0))
  1452. {
  1453. BfVirtualMethodEntry& vEntry = targetTypeInstance->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  1454. if ((vEntry.mImplementingMethod.mTypeInstance != NULL) && (vEntry.mImplementingMethod.mTypeInstance->mDefineState < BfTypeDefineState_DefinedAndMethodsSlotted) &&
  1455. (mModule->mCompiler->IsAutocomplete()))
  1456. {
  1457. // Silently ignore
  1458. }
  1459. else
  1460. {
  1461. auto implMethod = (BfMethodInstance*)vEntry.mImplementingMethod;
  1462. if ((implMethod != methodInstance) && (implMethod != NULL))
  1463. {
  1464. SetAndRestoreValue<bool> prevBypassVirtual(mBypassVirtual, true);
  1465. return CheckMethod(targetTypeInstance, implMethod->GetOwner(), implMethod->mMethodDef, isFailurePass);
  1466. }
  1467. }
  1468. }
  1469. else
  1470. {
  1471. // Being in autocomplete mode is the only excuse for not having the virtual method table slotted
  1472. if ((!mModule->mCompiler->IsAutocomplete()) && (!targetTypeInstance->mTypeFailed) && (!targetTypeInstance->IsUnspecializedTypeVariation()))
  1473. {
  1474. mModule->AssertErrorState();
  1475. }
  1476. }
  1477. }
  1478. BfGenericInferContext genericInferContext;
  1479. genericInferContext.mModule = mModule;
  1480. genericInferContext.mCheckMethodGenericArguments = &mCheckMethodGenericArguments;
  1481. HashSet<int> allowEmptyGenericSet;
  1482. BfAutoComplete* autoComplete = NULL;
  1483. if ((mModule->mCompiler->mResolvePassData != NULL) && (!isFailurePass) && ((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) == 0))
  1484. autoComplete = mModule->mCompiler->mResolvePassData->mAutoComplete;
  1485. if (checkMethod->mMethodType != BfMethodType_Extension)
  1486. {
  1487. if (((checkMethod->mIsStatic) && (!mAllowStatic)) ||
  1488. ((!checkMethod->mIsStatic) && (!mAllowNonStatic)))
  1489. {
  1490. if (!typeInstance->IsFunction())
  1491. autoComplete = NULL;
  1492. }
  1493. }
  1494. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1495. {
  1496. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  1497. methodMatchEntry.mMethodDef = checkMethod;
  1498. methodMatchEntry.mTypeInstance = typeInstance;
  1499. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  1500. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  1501. }
  1502. BfTypeVector* genericArgumentsSubstitute = NULL;
  1503. int argIdx = 0;
  1504. int argMatchCount = 0;
  1505. bool needInferGenericParams = (checkMethod->mGenericParams.size() != 0) &&
  1506. ((!mHadExplicitGenericArguments) || (mHadPartialGenericArguments));
  1507. int paramIdx = 0;
  1508. BfType* paramsElementType = NULL;
  1509. if (checkMethod->mHasAppend)
  1510. paramIdx++;
  1511. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(checkMethod);
  1512. if (mHadExplicitGenericArguments)
  1513. {
  1514. int genericArgDelta = (int)(checkMethod->mGenericParams.size() - (mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx));
  1515. if (mHadOpenGenericArguments)
  1516. {
  1517. if (genericArgDelta <= 0)
  1518. goto NoMatch;
  1519. }
  1520. else
  1521. {
  1522. if (genericArgDelta != 0)
  1523. goto NoMatch;
  1524. }
  1525. }
  1526. if (mHasArgNames)
  1527. {
  1528. checkMethod->BuildParamNameMap();
  1529. bool prevWasNull = false;
  1530. for (int argIdx = (int)mArguments.mSize - 1; argIdx >= 0; argIdx--)
  1531. {
  1532. auto& arg = mArguments[argIdx];
  1533. if (arg.mNameNode != NULL)
  1534. {
  1535. if (prevWasNull)
  1536. {
  1537. if (argIdx >= checkMethod->mParams.mSize)
  1538. goto NoMatch;
  1539. if (checkMethod->mParams[argIdx]->mName != arg.mNameNode->ToStringView())
  1540. goto NoMatch;
  1541. }
  1542. else
  1543. {
  1544. if (!checkMethod->mParamNameMap->ContainsKey(arg.mNameNode->ToStringView()))
  1545. goto NoMatch;
  1546. }
  1547. prevWasNull = false;
  1548. }
  1549. else
  1550. {
  1551. prevWasNull = true;
  1552. }
  1553. }
  1554. }
  1555. for (auto& checkGenericArgRef : mCheckMethodGenericArguments)
  1556. checkGenericArgRef = NULL;
  1557. mCheckMethodGenericArguments.resize(checkMethod->mGenericParams.size());
  1558. for (auto& genericArgRef : mCheckMethodGenericArguments)
  1559. genericArgRef = NULL;
  1560. if (mHadExplicitGenericArguments)
  1561. {
  1562. if (uniqueGenericStartIdx > 0)
  1563. {
  1564. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1565. mCheckMethodGenericArguments.clear();
  1566. mCheckMethodGenericArguments.reserve(mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx);
  1567. for (int i = 0; i < uniqueGenericStartIdx; i++)
  1568. mCheckMethodGenericArguments.Add(NULL);
  1569. for (int i = 0; i < (int)mExplicitMethodGenericArguments.size(); i++)
  1570. mCheckMethodGenericArguments.Add(mExplicitMethodGenericArguments[i]);
  1571. }
  1572. else
  1573. {
  1574. genericArgumentsSubstitute = &mExplicitMethodGenericArguments;
  1575. }
  1576. if ((mHadPartialGenericArguments) && (needInferGenericParams))
  1577. {
  1578. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1579. for (int i = 0; i < (int)mExplicitMethodGenericArguments.mSize; i++)
  1580. mCheckMethodGenericArguments[i] = mExplicitMethodGenericArguments[i];
  1581. }
  1582. }
  1583. else if (needInferGenericParams)
  1584. genericArgumentsSubstitute = &mCheckMethodGenericArguments;
  1585. if ((checkMethod->mIsMutating) && (targetTypeInstance != NULL) && (targetTypeInstance->IsValueType()) &&
  1586. ((mTarget.IsReadOnly()) || (!mTarget.IsAddr())) &&
  1587. (!targetTypeInstance->IsValuelessType()))
  1588. {
  1589. goto NoMatch;
  1590. }
  1591. if (mSkipImplicitParams)
  1592. {
  1593. //paramOfs = methodInstance->GetImplicitParamCount();
  1594. //paramIdx += paramOfs;
  1595. }
  1596. if (needInferGenericParams)
  1597. {
  1598. genericInferContext.mPrevArgValues.resize(checkMethod->mGenericParams.size());
  1599. int paramOfs = methodInstance->GetImplicitParamCount();
  1600. int paramCount = methodInstance->GetParamCount();
  1601. SizedArray<int, 8> deferredArgs;
  1602. int argIdx = 0;
  1603. int paramIdx = 0;
  1604. if (checkMethod->mHasAppend)
  1605. paramIdx++;
  1606. if (checkMethod->mMethodType == BfMethodType_Extension)
  1607. {
  1608. argIdx--;
  1609. }
  1610. paramIdx += paramOfs;
  1611. bool hadInferFailure = false;
  1612. int inferParamOffset = paramOfs - argIdx;
  1613. int paramsParamIdx = -1;
  1614. enum ResultKind
  1615. {
  1616. ResultKind_Ok,
  1617. ResultKind_Failed,
  1618. ResultKind_Deferred,
  1619. };
  1620. auto _CheckArg = [&](int argIdx)
  1621. {
  1622. paramIdx = argIdx + inferParamOffset;
  1623. if ((paramsParamIdx != -1) && (paramIdx > paramsParamIdx))
  1624. paramIdx = paramsParamIdx;
  1625. auto wantType = methodInstance->GetParamType(paramIdx);
  1626. auto checkType = wantType;
  1627. auto origCheckType = checkType;
  1628. if (checkType->IsGenericParam())
  1629. {
  1630. BfGenericParamInstance* genericParamInstance = NULL;
  1631. auto genericParamType = (BfGenericParamType*)checkType;
  1632. checkType = NULL;
  1633. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1634. {
  1635. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  1636. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  1637. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1638. }
  1639. else
  1640. genericParamInstance = mModule->GetGenericParamInstance(genericParamType);
  1641. if (checkType == NULL)
  1642. {
  1643. checkType = genericParamInstance->mTypeConstraint;
  1644. origCheckType = checkType; // We can do "ResolveGenericType" on this type
  1645. }
  1646. }
  1647. bool attemptedGenericResolve = false;
  1648. if ((checkType != NULL) && (genericArgumentsSubstitute != NULL) && (checkType->IsUnspecializedType()))
  1649. {
  1650. attemptedGenericResolve = true;
  1651. checkType = mModule->ResolveGenericType(origCheckType, NULL, genericArgumentsSubstitute, mModule->mCurTypeInstance);
  1652. }
  1653. if (wantType->IsUnspecializedType())
  1654. {
  1655. BfTypedValue argTypedValue;
  1656. if (argIdx == -1)
  1657. {
  1658. if (mOrigTarget)
  1659. argTypedValue = mOrigTarget;
  1660. else
  1661. argTypedValue = mTarget;
  1662. }
  1663. else
  1664. {
  1665. BfResolveArgFlags flags = BfResolveArgFlag_FromGeneric;
  1666. if (wantType->IsGenericParam())
  1667. flags = (BfResolveArgFlags)(flags | BfResolveArgFlag_FromGenericParam);
  1668. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], checkType, genericArgumentsSubstitute, origCheckType, flags);
  1669. }
  1670. if (!argTypedValue.IsUntypedValue())
  1671. {
  1672. auto type = argTypedValue.mType;
  1673. if (!argTypedValue)
  1674. {
  1675. if ((checkType == NULL) && (attemptedGenericResolve) && (genericInferContext.GetUnresolvedCount() >= 2))
  1676. {
  1677. deferredArgs.Add(argIdx);
  1678. return ResultKind_Deferred;
  1679. }
  1680. return ResultKind_Failed;
  1681. }
  1682. if (type->IsVar())
  1683. mHasVarArguments = true;
  1684. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_Params)
  1685. {
  1686. paramsParamIdx = paramIdx;
  1687. if ((wantType->IsArray()) || (wantType->IsSizedArray()) || (wantType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  1688. wantType = wantType->GetUnderlyingType();
  1689. }
  1690. if (!genericInferContext.InferGenericArgument(methodInstance, type, wantType, argTypedValue.mValue))
  1691. return ResultKind_Failed;
  1692. }
  1693. }
  1694. return ResultKind_Ok;
  1695. };
  1696. for (; argIdx < (int)mArguments.size(); argIdx++)
  1697. {
  1698. paramIdx = argIdx + inferParamOffset;
  1699. if ((paramIdx >= paramCount) && (paramsParamIdx == -1))
  1700. break; // Possible for delegate 'params' type methods
  1701. auto resultKind = _CheckArg(argIdx);
  1702. if (resultKind == ResultKind_Failed)
  1703. goto NoMatch;
  1704. }
  1705. if ((methodInstance->mParams.mSize > 0) && (methodInstance->GetParamKind(methodInstance->mParams.mSize - 1) == BfParamKind_Params))
  1706. {
  1707. // Handle `params int[C]` generic sized array params case
  1708. auto paramsType = methodInstance->GetParamType(methodInstance->mParams.mSize - 1);
  1709. if (paramsType->IsUnknownSizedArrayType())
  1710. {
  1711. auto unknownSizedArray = (BfUnknownSizedArrayType*)paramsType;
  1712. if (unknownSizedArray->mElementCountSource->IsMethodGenericParam())
  1713. {
  1714. auto genericParam = (BfGenericParamType*)unknownSizedArray->mElementCountSource;
  1715. if ((*genericArgumentsSubstitute)[genericParam->mGenericParamIdx] == NULL)
  1716. {
  1717. int paramsCount = (int)mArguments.mSize - inferParamOffset;
  1718. (*genericArgumentsSubstitute)[genericParam->mGenericParamIdx] = mModule->CreateConstExprValueType(
  1719. BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, paramsCount), mModule->GetPrimitiveType(BfTypeCode_IntPtr)));
  1720. }
  1721. }
  1722. }
  1723. }
  1724. if (!deferredArgs.IsEmpty())
  1725. {
  1726. genericInferContext.InferGenericArguments(methodInstance);
  1727. }
  1728. while (!deferredArgs.IsEmpty())
  1729. {
  1730. int prevDeferredSize = (int)deferredArgs.size();
  1731. for (int i = 0; i < prevDeferredSize; i++)
  1732. {
  1733. auto resultKind = _CheckArg(deferredArgs[i]);
  1734. if (resultKind == ResultKind_Failed)
  1735. goto NoMatch;
  1736. }
  1737. deferredArgs.RemoveRange(0, prevDeferredSize);
  1738. if (prevDeferredSize == deferredArgs.size())
  1739. {
  1740. // No progress
  1741. goto NoMatch;
  1742. }
  1743. }
  1744. //
  1745. {
  1746. int paramIdx = (int)mArguments.size() + paramOfs;
  1747. while (paramIdx < checkMethod->mParams.size())
  1748. {
  1749. if ((paramIdx < methodInstance->mDefaultValues.size()) && (methodInstance->mDefaultValues[paramIdx]))
  1750. {
  1751. auto wantType = methodInstance->GetParamType(paramIdx);
  1752. auto checkType = wantType;
  1753. if (checkType->IsGenericParam())
  1754. {
  1755. BfGenericParamInstance* genericParamInstance = NULL;
  1756. auto genericParamType = (BfGenericParamType*)checkType;
  1757. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  1758. {
  1759. if ((genericArgumentsSubstitute != NULL) && (genericParamType->mGenericParamIdx < (int)genericArgumentsSubstitute->size()))
  1760. checkType = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  1761. genericParamInstance = methodInstance->mMethodInfoEx->mGenericParams[genericParamType->mGenericParamIdx];
  1762. if ((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  1763. {
  1764. if (mCheckMethodGenericArguments[genericParamType->mGenericParamIdx] == NULL)
  1765. allowEmptyGenericSet.Add(genericParamType->mGenericParamIdx);
  1766. }
  1767. }
  1768. }
  1769. }
  1770. paramIdx++;
  1771. }
  1772. }
  1773. if ((mCheckReturnType != NULL) && (methodInstance->mReturnType->IsUnspecializedType()))
  1774. {
  1775. if (!genericInferContext.InferGenericArgument(methodInstance, mCheckReturnType, methodInstance->mReturnType, BfIRValue()))
  1776. return ResultKind_Failed;
  1777. }
  1778. bool failed = false;
  1779. bool inferredAllGenericArguments = false;
  1780. for (int pass = 0; true; pass++)
  1781. {
  1782. bool madeProgress = false;
  1783. bool hasUninferred = false;
  1784. failed = false;
  1785. for (int genericArgIdx = uniqueGenericStartIdx; genericArgIdx < (int)checkMethod->mGenericParams.size(); genericArgIdx++)
  1786. {
  1787. auto& genericArg = mCheckMethodGenericArguments[genericArgIdx];
  1788. if (genericArg == NULL)
  1789. {
  1790. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[genericArgIdx];
  1791. InferFromGenericConstraints(methodInstance, genericParam, &mCheckMethodGenericArguments);
  1792. if (genericArg != NULL)
  1793. {
  1794. if (inferredAllGenericArguments)
  1795. genericInferContext.InferGenericArguments(methodInstance, genericArgIdx);
  1796. madeProgress = true;
  1797. }
  1798. hasUninferred = true;
  1799. if (!allowEmptyGenericSet.Contains(genericArgIdx))
  1800. failed = true;
  1801. }
  1802. }
  1803. if (!hasUninferred)
  1804. break;
  1805. if (inferredAllGenericArguments)
  1806. {
  1807. if (!madeProgress)
  1808. break;
  1809. }
  1810. genericInferContext.InferGenericArguments(methodInstance);
  1811. inferredAllGenericArguments = true;
  1812. }
  1813. if (failed)
  1814. goto NoMatch;
  1815. }
  1816. if (checkMethod->mMethodType == BfMethodType_Extension)
  1817. argIdx--;
  1818. // Iterate through params
  1819. while (true)
  1820. {
  1821. // Too many arguments
  1822. if (paramIdx >= (int)methodInstance->GetParamCount())
  1823. {
  1824. break;
  1825. }
  1826. bool isDeferredEval = false;
  1827. if ((argIdx >= 0) && (methodInstance->GetParamKind(paramIdx) == BfParamKind_Params) && (paramsElementType == NULL))
  1828. {
  1829. if (argIdx >= (int) mArguments.size())
  1830. break; // No params
  1831. BfTypedValue argTypedValue = ResolveArgTypedValue(mArguments[argIdx], NULL, genericArgumentsSubstitute);
  1832. if (!argTypedValue)
  1833. goto NoMatch;
  1834. if ((!argTypedValue.HasType()) && (!mArguments[argIdx].IsDeferredEval()))
  1835. goto NoMatch;
  1836. auto paramsArrayType = methodInstance->GetParamType(paramIdx);
  1837. paramsArrayType = mModule->ResolveGenericType(paramsArrayType, NULL, genericArgumentsSubstitute, mModule->mCurTypeInstance);
  1838. if (paramsArrayType == NULL)
  1839. goto NoMatch;
  1840. if ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0)
  1841. {
  1842. // Direct-pass params
  1843. if ((argTypedValue.IsUntypedValue()) || (mModule->CanCast(argTypedValue, paramsArrayType)))
  1844. {
  1845. argIdx++;
  1846. argMatchCount++;
  1847. paramIdx++;
  1848. break;
  1849. }
  1850. goto NoMatch;
  1851. }
  1852. if ((paramsArrayType->IsArray()) || (paramsArrayType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  1853. {
  1854. paramsElementType = paramsArrayType->GetUnderlyingType();
  1855. while (argIdx < (int)mArguments.size())
  1856. {
  1857. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], paramsElementType, genericArgumentsSubstitute);
  1858. if (!argTypedValue.HasType())
  1859. goto NoMatch;
  1860. BfCastFlags castFlags = ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp) != 0) ? BfCastFlags_NoConversionOperator : BfCastFlags_None;
  1861. if ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp_Explicit) != 0)
  1862. castFlags = (BfCastFlags)(castFlags | BfCastFlags_Explicit);
  1863. if (!mModule->CanCast(argTypedValue, paramsElementType, castFlags))
  1864. goto NoMatch;
  1865. argIdx++;
  1866. argMatchCount++;
  1867. }
  1868. }
  1869. else
  1870. goto NoMatch;
  1871. break;
  1872. }
  1873. if (methodInstance->IsImplicitCapture(paramIdx))
  1874. {
  1875. paramIdx++;
  1876. continue;
  1877. }
  1878. if (argIdx >= (int) mArguments.size())
  1879. {
  1880. // We have defaults the rest of the way, so that's cool
  1881. if (methodInstance->GetParamInitializer(paramIdx) != NULL)
  1882. break;
  1883. // We have unused params left over
  1884. goto NoMatch;
  1885. }
  1886. auto wantType = methodInstance->GetParamType(paramIdx);
  1887. if ((genericArgumentsSubstitute != NULL) && (wantType->IsUnspecializedType()))
  1888. {
  1889. wantType = typeUnspecMethodInstance->GetParamType(paramIdx);
  1890. auto resolvedType = mModule->ResolveGenericType(wantType, typeGenericArguments, genericArgumentsSubstitute, mModule->mCurTypeInstance, false);
  1891. if (resolvedType == NULL)
  1892. goto NoMatch;
  1893. wantType = resolvedType;
  1894. }
  1895. wantType = mModule->ResolveSelfType(wantType, typeInstance);
  1896. if ((argIdx >= 0) && ((mArguments[argIdx].mArgFlags & BfArgFlag_ParamsExpr) != 0))
  1897. {
  1898. // We had a 'params' expression but this method didn't have a params slot in this parameter
  1899. goto NoMatch;
  1900. }
  1901. BfTypedValue argTypedValue;
  1902. if (argIdx == -1)
  1903. argTypedValue = mTarget;
  1904. else
  1905. argTypedValue = ResolveArgTypedValue(mArguments[argIdx], wantType, genericArgumentsSubstitute);
  1906. if (!argTypedValue.IsUntypedValue())
  1907. {
  1908. if (!argTypedValue.HasType())
  1909. {
  1910. // Check to see if this is the last argument and that it's a potential enum match
  1911. if ((wantType->IsEnum()) && (argIdx == mArguments.size() - 1))
  1912. {
  1913. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(mArguments[argIdx].mExpression))
  1914. {
  1915. if (memberRefExpr->mTarget == NULL)
  1916. {
  1917. // Is dot expression
  1918. curMatchKind = BackupMatchKind_PartialLastArgMatch;
  1919. }
  1920. }
  1921. }
  1922. bool matches = false;
  1923. if (wantType->IsOut())
  1924. {
  1925. if (auto memberRefExpr = BfNodeDynCast<BfUninitializedExpression>(mArguments[argIdx].mExpression))
  1926. matches = true;
  1927. }
  1928. if (!matches)
  1929. goto NoMatch;
  1930. }
  1931. else
  1932. {
  1933. if ((wantType->IsRef()) && (!argTypedValue.mType->IsRef()) &&
  1934. ((mAllowImplicitRef) || (wantType->IsIn())))
  1935. wantType = wantType->GetUnderlyingType();
  1936. BfCastFlags castFlags = ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp) != 0) ? BfCastFlags_NoConversionOperator : BfCastFlags_None;
  1937. if ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp_Explicit) != 0)
  1938. castFlags = (BfCastFlags)(castFlags | BfCastFlags_Explicit);
  1939. if ((mCheckReturnType != NULL) && (wantType->IsVar()))
  1940. {
  1941. // If we allowed this then it would allow too many matches (and allow conversion from any type during CastToValue)
  1942. goto NoMatch;
  1943. }
  1944. if (!mModule->CanCast(argTypedValue, wantType, castFlags))
  1945. {
  1946. if ((mAllowImplicitWrap) && (argTypedValue.mType->IsWrappableType()) && (mModule->GetWrappedStructType(argTypedValue.mType) == wantType))
  1947. {
  1948. // Is wrapped type
  1949. }
  1950. else
  1951. goto NoMatch;
  1952. }
  1953. }
  1954. }
  1955. paramIdx++;
  1956. argIdx++;
  1957. argMatchCount++;
  1958. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  1959. {
  1960. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  1961. if (!methodMatchInfo->mHadExactMatch)
  1962. {
  1963. bool isBetter = false;
  1964. bool isWorse = false;
  1965. int methodIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  1966. if ((methodMatchInfo->mBestIdx != -1) && (methodMatchInfo->mBestIdx < (int)methodMatchInfo->mInstanceList.size()))
  1967. {
  1968. auto prevMethodMatchEntry = &methodMatchInfo->mInstanceList[methodMatchInfo->mBestIdx];
  1969. if (checkMethod->mParams.size() < mArguments.size())
  1970. {
  1971. isWorse = true;
  1972. }
  1973. else if ((prevMethodMatchEntry->mMethodDef != NULL) && (prevMethodMatchEntry->mMethodDef->mParams.size() < (int) mArguments.size()))
  1974. {
  1975. isBetter = true;
  1976. }
  1977. }
  1978. }
  1979. }
  1980. }
  1981. // Too many arguments (not all incoming arguments processed)
  1982. if (argIdx < (int)mArguments.size())
  1983. {
  1984. if (!methodInstance->IsVarArgs())
  1985. goto NoMatch;
  1986. }
  1987. if (mCheckReturnType != NULL)
  1988. {
  1989. auto returnType = methodInstance->mReturnType;
  1990. if (returnType->IsVar())
  1991. {
  1992. // If we allowed this then it would allow too many matches (and allow conversion to any type during CastToValue)
  1993. goto NoMatch;
  1994. }
  1995. if ((genericArgumentsSubstitute != NULL) && (returnType->IsUnspecializedType()))
  1996. {
  1997. auto resolvedType = mModule->ResolveGenericType(returnType, typeGenericArguments, genericArgumentsSubstitute, mModule->mCurTypeInstance, false);
  1998. if (resolvedType == NULL)
  1999. goto NoMatch;
  2000. returnType = resolvedType;
  2001. }
  2002. returnType = mModule->ResolveSelfType(returnType, typeInstance);
  2003. BfCastFlags castFlags = ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp) != 0) ? (BfCastFlags)(BfCastFlags_NoConversionOperator | BfCastFlags_NoInterfaceImpl) : BfCastFlags_None;
  2004. if ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp_Explicit) != 0)
  2005. castFlags = (BfCastFlags)(castFlags | BfCastFlags_Explicit);
  2006. if (!mModule->CanCast(mModule->GetFakeTypedValue(returnType), mCheckReturnType, castFlags))
  2007. goto NoMatch;
  2008. }
  2009. if ((genericArgumentsSubstitute != NULL) && (genericArgumentsSubstitute->size() != 0))
  2010. {
  2011. for (int checkGenericIdx = uniqueGenericStartIdx; checkGenericIdx < (int)genericArgumentsSubstitute->size(); checkGenericIdx++)
  2012. {
  2013. auto& genericParams = methodInstance->mMethodInfoEx->mGenericParams;
  2014. auto genericArg = (*genericArgumentsSubstitute)[checkGenericIdx];
  2015. if (genericArg == NULL)
  2016. {
  2017. if (allowEmptyGenericSet.Contains(checkGenericIdx))
  2018. continue;
  2019. goto NoMatch;
  2020. }
  2021. if (genericArg == NULL)
  2022. goto NoMatch;
  2023. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericArg, NULL, genericParams[checkGenericIdx], genericArgumentsSubstitute, NULL))
  2024. goto NoMatch;
  2025. }
  2026. }
  2027. for (int externConstraintIdx = 0; externConstraintIdx < (int)checkMethod->mExternalConstraints.size(); externConstraintIdx++)
  2028. {
  2029. auto genericParam = methodInstance->mMethodInfoEx->mGenericParams[checkMethod->mGenericParams.size() + externConstraintIdx];
  2030. BF_ASSERT(genericParam->mExternType != NULL);
  2031. auto externType = genericParam->mExternType;
  2032. BfTypeVector* externGenericArgumentsSubstitute = genericArgumentsSubstitute;
  2033. if (externType->IsVar())
  2034. {
  2035. auto& externConstraint = checkMethod->mExternalConstraints[externConstraintIdx];
  2036. if (externConstraint.mTypeRef != NULL)
  2037. {
  2038. externType = mModule->ResolveGenericMethodTypeRef(externConstraint.mTypeRef, methodInstance, genericParam, genericArgumentsSubstitute);
  2039. if (externType == NULL)
  2040. goto NoMatch;
  2041. }
  2042. }
  2043. if (externType->IsGenericParam())
  2044. {
  2045. auto genericParamType = (BfGenericParamType*)externType;
  2046. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  2047. {
  2048. if (genericArgumentsSubstitute != NULL)
  2049. {
  2050. auto genericArg = (*genericArgumentsSubstitute)[genericParamType->mGenericParamIdx];
  2051. if (genericArg == NULL)
  2052. {
  2053. if (allowEmptyGenericSet.Contains(genericParamType->mGenericParamIdx))
  2054. continue;
  2055. goto NoMatch;
  2056. }
  2057. externType = genericArg;
  2058. }
  2059. }
  2060. }
  2061. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), externType, NULL, genericParam, externGenericArgumentsSubstitute, NULL))
  2062. goto NoMatch;
  2063. }
  2064. // if (auto methodDecl = BfNodeDynCast<BfMethodDeclaration>(checkMethod->mMethodDeclaration))
  2065. // {
  2066. // if ((methodDecl->mGenericConstraintsDeclaration != NULL) && (methodDecl->mGenericConstraintsDeclaration->mHasExpressions))
  2067. // {
  2068. // for (auto genericConstraint : methodDecl->mGenericConstraintsDeclaration->mGenericConstraints)
  2069. // {
  2070. // if (auto genericConstraintExpr = BfNodeDynCast<BfGenericConstraintExpression>(genericConstraint))
  2071. // {
  2072. // if (genericConstraintExpr->mExpression == NULL)
  2073. // continue;
  2074. // BfConstResolver constResolver(mModule);
  2075. // constResolver.mExpectingType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  2076. // constResolver.Resolve(genericConstraintExpr->mExpression, constResolver.mExpectingType);
  2077. // }
  2078. // }
  2079. // }
  2080. // }
  2081. // Method is applicable, check to see which method is better
  2082. if (mBestMethodDef != NULL)
  2083. {
  2084. bool isBetter = false;
  2085. bool isWorse = false;
  2086. BfMethodInstance* prevMethodInstance = mModule->GetRawMethodInstance(mBestMethodTypeInstance, mBestMethodDef);
  2087. bool allowSpecializeFail = mModule->mCurTypeInstance->IsUnspecializedType();
  2088. if (mModule->mCurMethodInstance != NULL)
  2089. allowSpecializeFail = mModule->mCurMethodInstance->mIsUnspecialized;
  2090. CompareMethods(prevMethodInstance, &mBestMethodGenericArguments, methodInstance, genericArgumentsSubstitute, &isBetter, &isWorse, allowSpecializeFail);
  2091. // If we had both a 'better' and 'worse', that's ambiguous because the methods are each better in different ways (not allowed)
  2092. // And if neither better nor worse then they are equally good, which is not allowed either
  2093. if (((!isBetter) && (!isWorse)) || ((isBetter) && (isWorse)))
  2094. {
  2095. if (!mHasVarArguments)
  2096. {
  2097. // If we are ambiguous based on a subset of an extern 'var' constraint then don't throw an error
  2098. auto _CheckMethodInfo = [&](BfMethodInstance* checkMethodInstance)
  2099. {
  2100. if (checkMethodInstance->mMethodInfoEx == NULL)
  2101. return;
  2102. for (auto genericParam : checkMethodInstance->mMethodInfoEx->mGenericParams)
  2103. {
  2104. if ((genericParam->mExternType == NULL) || (!genericParam->mExternType->IsGenericParam()))
  2105. continue;
  2106. auto genericParamType = (BfGenericParamType*)genericParam->mExternType;
  2107. if (genericParamType->mGenericParamKind != BfGenericParamKind_Type)
  2108. continue;
  2109. auto externGenericParam = mModule->GetGenericParamInstance(genericParamType);
  2110. if ((externGenericParam->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  2111. mHasVarArguments = true;
  2112. }
  2113. };
  2114. _CheckMethodInfo(methodInstance);
  2115. _CheckMethodInfo(prevMethodInstance);
  2116. }
  2117. if (mHasVarArguments)
  2118. {
  2119. if (methodInstance->mReturnType != prevMethodInstance->mReturnType)
  2120. mHadVarConflictingReturnType = true;
  2121. }
  2122. else
  2123. {
  2124. BfAmbiguousEntry ambiguousEntry;
  2125. ambiguousEntry.mMethodInstance = methodInstance;
  2126. if (genericArgumentsSubstitute != NULL)
  2127. ambiguousEntry.mBestMethodGenericArguments = *genericArgumentsSubstitute;
  2128. if (methodInstance->mMethodDef->mGenericParams.size() != 0)
  2129. {
  2130. BF_ASSERT(!ambiguousEntry.mBestMethodGenericArguments.empty());
  2131. }
  2132. mAmbiguousEntries.push_back(ambiguousEntry);
  2133. goto Done;
  2134. }
  2135. }
  2136. if (!isBetter)
  2137. goto Done;
  2138. }
  2139. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  2140. {
  2141. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  2142. // Try to persist with previous partial match, if we have one - this keeps us from locking onto
  2143. // an incorrect method just because it had the current number of params that we've typed so far
  2144. if (methodMatchInfo->mPrevBestIdx == -1)
  2145. {
  2146. methodMatchInfo->mHadExactMatch = true;
  2147. methodMatchInfo->mBestIdx = (int) methodMatchInfo->mInstanceList.size() - 1;
  2148. }
  2149. }
  2150. mAmbiguousEntries.Clear();
  2151. hadMatch = true;
  2152. mBestMethodDef = checkMethod;
  2153. mBestRawMethodInstance = methodInstance;
  2154. for (auto& arg : mArguments)
  2155. arg.mBestBoundType = arg.mTypedValue.mType;
  2156. NoMatch:
  2157. if (!hadMatch)
  2158. {
  2159. if (mBestMethodDef != NULL)
  2160. return false;
  2161. if (checkMethod->mMethodType == BfMethodType_Extension)
  2162. {
  2163. auto thisParam = methodInstance->GetParamType(0);
  2164. auto resolveThisParam = mModule->ResolveGenericType(thisParam, NULL, &mCheckMethodGenericArguments, mModule->mCurTypeInstance);
  2165. if (resolveThisParam == NULL)
  2166. return false;
  2167. if (!mModule->CanCast(mTarget, resolveThisParam,
  2168. ((mBfEvalExprFlags & BfEvalExprFlags_FromConversionOp) != 0) ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_NoConversionOperator) : BfCastFlags_Explicit))
  2169. return false;
  2170. }
  2171. if (mBackupMethodDef != NULL)
  2172. {
  2173. int prevParamDiff = (int)mBackupMethodDef->GetExplicitParamCount() - (int)mArguments.size();
  2174. int paramDiff = (int)checkMethod->GetExplicitParamCount() - (int)mArguments.size();
  2175. if ((prevParamDiff < 0) && (prevParamDiff > paramDiff))
  2176. return false;
  2177. if ((prevParamDiff >= 0) && (paramDiff < 0))
  2178. return false;
  2179. if (argMatchCount < mBackupArgMatchCount)
  2180. return false;
  2181. else if (argMatchCount == mBackupArgMatchCount)
  2182. {
  2183. if (curMatchKind < mBackupMatchKind)
  2184. return false;
  2185. // We search from the most specific type, so don't prefer a less specific type
  2186. if (mBestMethodTypeInstance != typeInstance)
  2187. return false;
  2188. }
  2189. }
  2190. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  2191. {
  2192. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  2193. if ((methodMatchInfo->mPrevBestIdx == -1) && (!methodMatchInfo->mHadExactMatch))
  2194. {
  2195. methodMatchInfo->mBestIdx = (int)methodMatchInfo->mInstanceList.size() - 1;
  2196. }
  2197. }
  2198. mBackupMatchKind = curMatchKind;
  2199. mBackupMethodDef = checkMethod;
  2200. mBackupArgMatchCount = argMatchCount;
  2201. // Lie temporarily to store at least one candidate (but mBestMethodDef is still NULL)
  2202. hadMatch = true;
  2203. }
  2204. if (hadMatch)
  2205. {
  2206. mBestMethodTypeInstance = typeInstance;
  2207. if (genericArgumentsSubstitute != &mBestMethodGenericArguments)
  2208. {
  2209. if (genericArgumentsSubstitute != NULL)
  2210. {
  2211. for (auto& genericArg : *genericArgumentsSubstitute)
  2212. genericArg = mModule->FixIntUnknown(genericArg);
  2213. mBestMethodGenericArguments = *genericArgumentsSubstitute;
  2214. // #ifdef _DEBUG
  2215. // for (auto arg : mBestMethodGenericArguments)
  2216. // BF_ASSERT((arg == NULL) || (!arg->IsVar()));
  2217. // #endif
  2218. }
  2219. else
  2220. mBestMethodGenericArguments.clear();
  2221. }
  2222. }
  2223. Done:
  2224. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (genericArgumentsSubstitute != NULL))
  2225. {
  2226. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  2227. if (!methodMatchInfo->mInstanceList.IsEmpty())
  2228. {
  2229. methodMatchInfo->mInstanceList[methodMatchInfo->mInstanceList.size() - 1].mGenericArguments = *genericArgumentsSubstitute;
  2230. }
  2231. }
  2232. return mBestMethodDef == checkMethod;
  2233. }
  2234. void BfMethodMatcher::FlushAmbiguityError()
  2235. {
  2236. if (!mAmbiguousEntries.empty())
  2237. {
  2238. if (mModule->PreFail())
  2239. {
  2240. BfError* error;
  2241. if (!mMethodName.empty())
  2242. error = mModule->Fail(StrFormat("Ambiguous method call for '%s'", mMethodName.c_str()), mTargetSrc);
  2243. else
  2244. error = mModule->Fail("Ambiguous method call", mTargetSrc);
  2245. if (error != NULL)
  2246. {
  2247. BfMethodInstance* bestMethodInstance = mModule->GetUnspecializedMethodInstance(mBestRawMethodInstance, true);
  2248. BfTypeVector* typeGenericArguments = NULL;
  2249. if (mBestMethodTypeInstance->mGenericTypeInfo != NULL)
  2250. typeGenericArguments = &mBestMethodTypeInstance->mGenericTypeInfo->mTypeGenericArguments;
  2251. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(bestMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  2252. typeGenericArguments, mBestMethodGenericArguments.empty() ? NULL : &mBestMethodGenericArguments).c_str()),
  2253. bestMethodInstance->mMethodDef->GetRefNode());
  2254. for (auto& ambiguousEntry : mAmbiguousEntries)
  2255. {
  2256. auto typeInstance = ambiguousEntry.mMethodInstance->GetOwner();
  2257. auto unspecTypeMethodInstance = mModule->GetUnspecializedMethodInstance(ambiguousEntry.mMethodInstance, true);
  2258. BfTypeVector* typeGenericArguments = NULL;
  2259. if (typeInstance->mGenericTypeInfo != NULL)
  2260. typeGenericArguments = &typeInstance->mGenericTypeInfo->mTypeGenericArguments;
  2261. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' is a candidate", mModule->MethodToString(unspecTypeMethodInstance, BfMethodNameFlag_ResolveGenericParamNames,
  2262. typeGenericArguments, ambiguousEntry.mBestMethodGenericArguments.empty() ? NULL : &ambiguousEntry.mBestMethodGenericArguments).c_str()),
  2263. ambiguousEntry.mMethodInstance->mMethodDef->GetRefNode());
  2264. }
  2265. }
  2266. }
  2267. mAmbiguousEntries.Clear();
  2268. }
  2269. }
  2270. bool BfMethodMatcher::IsType(BfTypedValue& typedVal, BfType* type)
  2271. {
  2272. if (typedVal.mType == type)
  2273. return true;
  2274. if (!typedVal)
  2275. return false;
  2276. if (!typedVal.mType->IsPrimitiveType())
  2277. return false;
  2278. if (!type->IsPrimitiveType())
  2279. return false;
  2280. auto fromPrimType = typedVal.mType->ToPrimitiveType();
  2281. if ((fromPrimType->mTypeDef->mTypeCode != BfTypeCode_IntUnknown) &&
  2282. (fromPrimType->mTypeDef->mTypeCode != BfTypeCode_UIntUnknown))
  2283. return false;
  2284. auto constant = mModule->mBfIRBuilder->GetConstant(typedVal.mValue);
  2285. if (constant == NULL)
  2286. return false;
  2287. auto toPrimType = type->ToPrimitiveType();
  2288. if (!mModule->mBfIRBuilder->IsInt(toPrimType->mTypeDef->mTypeCode))
  2289. return false;
  2290. if (type->mSize == 8)
  2291. return false;
  2292. int64 minVal = -(1LL << (8 * type->mSize - 1));
  2293. int64 maxVal = (1LL << (8 * type->mSize - 1)) - 1;
  2294. if ((constant->mInt64 >= minVal) && (constant->mInt64 <= maxVal))
  2295. return true;
  2296. return false;
  2297. }
  2298. // This method checks all base classes before checking interfaces. Is that correct?
  2299. bool BfMethodMatcher::CheckType(BfTypeInstance* typeInstance, BfTypedValue target, bool isFailurePass, bool forceOuterCheck)
  2300. {
  2301. BfMethodDef* prevBestMethodDef = mBestMethodDef;
  2302. auto curTypeInst = typeInstance;
  2303. auto curTypeDef = typeInstance->mTypeDef;
  2304. int checkInterfaceIdx = 0;
  2305. bool targetIsBase = target.IsBase();
  2306. bool checkExtensionBase = false;
  2307. if (targetIsBase)
  2308. {
  2309. if ((curTypeInst == mModule->mCurTypeInstance) && (curTypeInst->mTypeDef->mIsCombinedPartial))
  2310. {
  2311. checkExtensionBase = true;
  2312. }
  2313. else
  2314. {
  2315. curTypeInst = curTypeInst->mBaseType;
  2316. }
  2317. }
  2318. BfTypeInstance* targetTypeInstance = NULL;
  2319. if (target.mType != NULL)
  2320. targetTypeInstance = target.mType->ToTypeInstance();
  2321. while (true)
  2322. {
  2323. bool doSearch = true;
  2324. if ((mMethodType == BfMethodType_Extension) && (!curTypeDef->mHasExtensionMethods))
  2325. doSearch = false;
  2326. BfMethodDef* nextMethodDef = NULL;
  2327. if (doSearch)
  2328. {
  2329. curTypeDef->PopulateMemberSets();
  2330. BfMemberSetEntry* entry;
  2331. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  2332. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  2333. }
  2334. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  2335. if (target)
  2336. {
  2337. if (mBypassVirtual)
  2338. {
  2339. // Not an "instance lookup"
  2340. }
  2341. else
  2342. {
  2343. protectionCheckFlags = (BfProtectionCheckFlags)(protectionCheckFlags | BfProtectionCheckFlag_InstanceLookup);
  2344. }
  2345. }
  2346. while (nextMethodDef != NULL)
  2347. {
  2348. bool allowExplicitInterface = curTypeInst->IsInterface() && mBypassVirtual;
  2349. auto activeTypeDef = mModule->GetActiveTypeDef();
  2350. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  2351. bool isDelegate = typeInstance->IsDelegate();
  2352. auto checkMethod = nextMethodDef;
  2353. nextMethodDef = nextMethodDef->mNextWithSameName;
  2354. if (mModule->mContext->mResolvingVarField)
  2355. {
  2356. bool isResolvingVarField = false;
  2357. auto checkTypeState = mModule->mContext->mCurTypeState;
  2358. while (checkTypeState != NULL)
  2359. {
  2360. if ((checkTypeState->mResolveKind == BfTypeState::ResolveKind_ResolvingVarType) &&
  2361. (checkTypeState->mType == typeInstance))
  2362. isResolvingVarField = true;
  2363. checkTypeState = checkTypeState->mPrevState;
  2364. }
  2365. if (isResolvingVarField)
  2366. {
  2367. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  2368. // Don't even consider - we can't do method calls on ourselves when we are resolving var fields, because
  2369. // we are not allowed to generate methods when our field types are unknown. We may fix this in the future,
  2370. // but currently it breaks out expected order of operations. One issue is that our call signatures change
  2371. // depending on whether we are valueless or splattable, which depend on underlying type information
  2372. break;
  2373. }
  2374. }
  2375. if ((checkExtensionBase) && (curTypeInst == mModule->mCurTypeInstance))
  2376. {
  2377. // Accept either a method in the same project but that's the root definition, OR a method that's in a dependent project
  2378. bool accept = false;
  2379. if (activeTypeDef->mProject == checkMethod->mDeclaringType->mProject)
  2380. accept = (activeTypeDef->IsExtension()) && (!checkMethod->mDeclaringType->IsExtension());
  2381. else
  2382. accept = activeTypeDef->mProject->ContainsReference(checkMethod->mDeclaringType->mProject);
  2383. if (!accept)
  2384. continue;
  2385. }
  2386. if ((!allowExplicitInterface) && (checkMethod->mExplicitInterface != NULL) && (mInterfaceMethodInstance == NULL))
  2387. {
  2388. continue;
  2389. }
  2390. if (checkMethod->mMethodType != mMethodType)
  2391. continue;
  2392. // if (checkMethod->mName != mMethodName)
  2393. // continue;
  2394. if ((checkMethod->mDeclaringType->IsExtension()) && (mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) &&
  2395. (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoExtensionAttributeTypeDef)))
  2396. {
  2397. mModule->mAttributeState->mUsed = true;
  2398. continue;
  2399. }
  2400. if (!isDelegate)
  2401. {
  2402. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  2403. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, visibleProjectSet)))
  2404. continue;
  2405. }
  2406. MatchFailKind matchFailKind = MatchFailKind_None;
  2407. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkMethod->mDeclaringType->mProject, checkMethod->mProtection, typeInstance))
  2408. {
  2409. if ((mBypassVirtual) &&
  2410. ((checkMethod->mProtection == BfProtection_Protected) || (checkMethod->mProtection == BfProtection_ProtectedInternal)) &&
  2411. (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, typeInstance)))
  2412. {
  2413. // Allow explicit 'base' call
  2414. }
  2415. else
  2416. {
  2417. if (!isFailurePass)
  2418. continue;
  2419. matchFailKind = MatchFailKind_Protection;
  2420. }
  2421. }
  2422. if (mCheckedKind != checkMethod->mCheckedKind)
  2423. {
  2424. bool passes = true;
  2425. if (mCheckedKind != BfCheckedKind_NotSet)
  2426. {
  2427. passes = false;
  2428. }
  2429. else
  2430. {
  2431. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  2432. if (defaultCheckedKind != checkMethod->mCheckedKind)
  2433. passes = false;
  2434. }
  2435. if (!passes)
  2436. {
  2437. if (!isFailurePass)
  2438. continue;
  2439. matchFailKind = MatchFailKind_CheckedMismatch;
  2440. }
  2441. }
  2442. CheckMethod(targetTypeInstance, curTypeInst, checkMethod, isFailurePass);
  2443. if ((isFailurePass) &&
  2444. ((mBestMethodDef == checkMethod) || (mBackupMethodDef == checkMethod)))
  2445. mMatchFailKind = matchFailKind;
  2446. }
  2447. if ((mBestMethodDef != NULL) && (mMethodType != BfMethodType_Extension))
  2448. {
  2449. if ((mUsingLists != NULL) && (mUsingLists->mSize != 0))
  2450. mUsingLists->Clear();
  2451. if (mAutoFlushAmbiguityErrors)
  2452. FlushAmbiguityError();
  2453. return true;
  2454. }
  2455. if ((mUsingLists != NULL) && (curTypeInst->mTypeDef->mHasUsingFields))
  2456. mModule->PopulateUsingFieldData(curTypeInst);
  2457. if (mUsingLists != NULL)
  2458. {
  2459. auto _CheckUsingData = [&](BfUsingFieldData* usingData)
  2460. {
  2461. BfUsingFieldData::Entry* entry = NULL;
  2462. if (!usingData->mMethods.TryGetValue(mMethodName, &entry))
  2463. return;
  2464. for (int listIdx = 0; listIdx < entry->mLookups.mSize; listIdx++)
  2465. {
  2466. bool passesProtection = true;
  2467. auto& entryList = entry->mLookups[listIdx];
  2468. for (int entryIdx = 0; entryIdx < entryList.mSize; entryIdx++)
  2469. {
  2470. auto& entry = entryList[entryIdx];
  2471. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  2472. if (!mModule->CheckProtection(protectionCheckFlags, entry.mTypeInstance, entry.GetDeclaringType(mModule)->mProject,
  2473. (entryIdx < entryList.mSize - 1) ? entry.GetUsingProtection() : entry.GetProtection(), curTypeInst))
  2474. {
  2475. passesProtection = false;
  2476. break;
  2477. }
  2478. }
  2479. if (!passesProtection)
  2480. continue;
  2481. auto& entry = entryList.back();
  2482. BF_ASSERT(entry.mKind == BfUsingFieldData::MemberRef::Kind_Method);
  2483. auto methodDef = entry.mTypeInstance->mTypeDef->mMethods[entry.mIdx];
  2484. CheckMethod(curTypeInst, entry.mTypeInstance, methodDef, isFailurePass);
  2485. if ((mBestMethodDef != methodDef) && (mBackupMethodDef != methodDef))
  2486. {
  2487. bool foundAmbiguous = false;
  2488. for (int checkIdx = 0; checkIdx < mAmbiguousEntries.mSize; checkIdx++)
  2489. {
  2490. if (mAmbiguousEntries[checkIdx].mMethodInstance->mMethodDef == methodDef)
  2491. {
  2492. mAmbiguousEntries.RemoveAt(checkIdx);
  2493. foundAmbiguous = true;
  2494. break;
  2495. }
  2496. }
  2497. if (!foundAmbiguous)
  2498. continue;
  2499. }
  2500. if (mUsingLists->mSize == 0)
  2501. {
  2502. mUsingLists->Add(&entryList);
  2503. }
  2504. else
  2505. {
  2506. if (entryList.mSize < (*mUsingLists)[0]->mSize)
  2507. {
  2508. // New is shorter
  2509. mUsingLists->Clear();
  2510. mUsingLists->Add(&entryList);
  2511. }
  2512. else if (entryList.mSize > (*mUsingLists)[0]->mSize)
  2513. {
  2514. // Ignore longer
  2515. }
  2516. else
  2517. {
  2518. mUsingLists->Add(&entryList);
  2519. }
  2520. }
  2521. }
  2522. };
  2523. if ((curTypeInst->mTypeInfoEx != NULL) && (curTypeInst->mTypeInfoEx->mUsingFieldData != NULL))
  2524. _CheckUsingData(curTypeInst->mTypeInfoEx->mUsingFieldData);
  2525. if (mBestMethodDef != NULL)
  2526. break;
  2527. }
  2528. auto baseType = curTypeInst->mBaseType;
  2529. if (baseType == NULL)
  2530. {
  2531. //TODO: Why were we doing the interface checking?
  2532. if ((curTypeInst->IsInterface()) && (curTypeInst == target.mType))
  2533. {
  2534. // When we are directly calling on interfaces rather than indirectly matching through binding
  2535. baseType = mModule->mContext->mBfObjectType;
  2536. }
  2537. else if ((curTypeInst != mModule->mContext->mBfObjectType) && (!curTypeInst->IsInterface()))
  2538. {
  2539. // This can happen for structs
  2540. baseType = mModule->mContext->mBfObjectType;
  2541. }
  2542. else if ((typeInstance->IsInterface()) && (checkInterfaceIdx < (int)typeInstance->mInterfaces.size()))
  2543. {
  2544. baseType = typeInstance->mInterfaces[checkInterfaceIdx].mInterfaceType;
  2545. checkInterfaceIdx++;
  2546. }
  2547. else
  2548. {
  2549. break;
  2550. }
  2551. }
  2552. curTypeDef = baseType->mTypeDef;
  2553. curTypeInst = baseType;
  2554. if ((isFailurePass) && (mBackupMethodDef != NULL))
  2555. break;
  2556. }
  2557. if (mBestMethodDef == NULL)
  2558. {
  2559. // FAILED, but select the first method which will fire an actual error on param type matching
  2560. mBestMethodDef = mBackupMethodDef;
  2561. }
  2562. if (((mBestMethodDef == NULL) && (!target) && (mAllowImplicitThis)) ||
  2563. (forceOuterCheck))
  2564. {
  2565. // No explicit target - maybe this was a static call in the outer type?
  2566. auto outerType = mModule->GetOuterType(typeInstance);
  2567. if (outerType != NULL)
  2568. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  2569. }
  2570. if (mAutoFlushAmbiguityErrors)
  2571. FlushAmbiguityError();
  2572. return mBestMethodDef != prevBestMethodDef;
  2573. }
  2574. void BfMethodMatcher::TryDevirtualizeCall(BfTypedValue target, BfTypedValue* origTarget, BfTypedValue* staticResult)
  2575. {
  2576. if ((mBestMethodDef == NULL) || (target.mType == NULL))
  2577. return;
  2578. if ((mModule->mCompiler->IsAutocomplete()) || (mModule->mContext->mResolvingVarField))
  2579. return;
  2580. if ((mModule->mBfIRBuilder->mIgnoreWrites) && (!mBestMethodDef->mIsConcrete) && (!mBestMethodTypeInstance->IsInterface()))
  2581. return;
  2582. if (mBestMethodTypeInstance->IsInterface())
  2583. {
  2584. mModule->PopulateType(mBestMethodTypeInstance, BfPopulateType_DataAndMethods);
  2585. auto activeTypeDef = mModule->GetActiveTypeDef();
  2586. // Statically map this call
  2587. auto checkType = target.mType;
  2588. if (checkType->IsPointer())
  2589. checkType = ((BfPointerType*)checkType)->mElementType;
  2590. if (checkType->IsWrappableType())
  2591. checkType = mModule->GetWrappedStructType(checkType);
  2592. if ((checkType != NULL) && (checkType->IsTypeInstance()) && (!checkType->IsInterface()))
  2593. {
  2594. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  2595. auto checkTypeInst = checkType->ToTypeInstance();
  2596. if (mBestMethodTypeInstance->IsInstanceOf(mModule->mCompiler->mIHashableTypeDef))
  2597. {
  2598. if ((origTarget != NULL) && (origTarget->mType->IsPointer()) && (staticResult != NULL))
  2599. {
  2600. BfTypedValue ptrVal = mModule->LoadValue(*origTarget);
  2601. *staticResult = BfTypedValue(mModule->mBfIRBuilder->CreatePtrToInt(ptrVal.mValue, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  2602. return;
  2603. }
  2604. }
  2605. while (checkTypeInst != NULL)
  2606. {
  2607. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  2608. for (auto&& iface : checkTypeInst->mInterfaces)
  2609. {
  2610. //TODO: Why did we have this check? This caused Dictionary to not be able to devirtualize
  2611. // calls to TKey GetHashCode when TKey was from a user's project...
  2612. /*if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  2613. continue;*/
  2614. if (iface.mInterfaceType == mBestMethodTypeInstance)
  2615. {
  2616. if (bestIFaceEntry == NULL)
  2617. {
  2618. bestIFaceEntry = &iface;
  2619. continue;
  2620. }
  2621. bool isBetter;
  2622. bool isWorse;
  2623. mModule->CompareDeclTypes(NULL, iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  2624. if (isBetter == isWorse)
  2625. {
  2626. // Failed
  2627. }
  2628. else
  2629. {
  2630. if (isBetter)
  2631. bestIFaceEntry = &iface;
  2632. }
  2633. }
  2634. }
  2635. if (bestIFaceEntry != NULL)
  2636. break;
  2637. checkTypeInst = checkTypeInst->mBaseType;
  2638. if ((checkTypeInst == NULL) && (checkType->HasWrappedRepresentation()))
  2639. {
  2640. auto underlyingType = checkType->GetUnderlyingType();
  2641. if ((underlyingType != NULL) && (underlyingType->IsWrappableType()))
  2642. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  2643. if (checkTypeInst == checkType)
  2644. break;
  2645. }
  2646. }
  2647. if (bestIFaceEntry != NULL)
  2648. {
  2649. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + mBestMethodDef->mIdx];
  2650. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  2651. if (bestMethodInstance != NULL)
  2652. {
  2653. bool isMissingArg = false;
  2654. for (auto genericArg : mBestMethodGenericArguments)
  2655. {
  2656. if (genericArg == NULL)
  2657. isMissingArg = true;
  2658. }
  2659. if (!isMissingArg)
  2660. {
  2661. // Assert error state?
  2662. mBestMethodTypeInstance = ifaceMethodEntry.mMethodRef.mTypeInstance;
  2663. mBestMethodDef = bestMethodInstance->mMethodDef;
  2664. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, bestMethodInstance->mMethodDef, mBestMethodGenericArguments,
  2665. bestMethodInstance->mIsForeignMethodDef ? BfGetMethodInstanceFlag_ForeignMethodDef : BfGetMethodInstanceFlag_None,
  2666. bestMethodInstance->GetForeignType());
  2667. }
  2668. }
  2669. else
  2670. {
  2671. // Failed
  2672. mFakeConcreteTarget = true;
  2673. }
  2674. }
  2675. }
  2676. }
  2677. if ((target.mType->IsValueType()) && (mBestMethodTypeInstance->IsObject()) && (mBestMethodDef->mIsVirtual))
  2678. {
  2679. auto structType = target.mType->ToTypeInstance();
  2680. auto virtualMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, mBestMethodDef, BfTypeVector());
  2681. BF_ASSERT(virtualMethodInstance.mMethodInstance->mVirtualTableIdx != -1);
  2682. BfTypeInstance* boxedType;
  2683. if (structType->HasOverrideMethods())
  2684. {
  2685. // We don't actually need this boxed type, so just resolve it unreified
  2686. auto useModule = mModule->mContext->mUnreifiedModule;
  2687. boxedType = useModule->CreateBoxedType(target.mType);
  2688. useModule->PopulateType(boxedType, BfPopulateType_DataAndMethods);
  2689. useModule->AddDependency(boxedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_WeakReference);
  2690. }
  2691. else
  2692. {
  2693. boxedType = mModule->mContext->mBfObjectType;
  2694. }
  2695. auto methodRef = boxedType->mVirtualMethodTable[virtualMethodInstance.mMethodInstance->mVirtualTableIdx];
  2696. if (methodRef.mImplementingMethod.mTypeInstance->IsBoxed())
  2697. {
  2698. auto useModule = mModule->mContext->mUnreifiedModule;
  2699. auto boxedMethodInstance = useModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  2700. BfBoxedType* vBoxedType = (BfBoxedType*)methodRef.mImplementingMethod.mTypeInstance;
  2701. mBestMethodTypeInstance = vBoxedType->mElementType->ToTypeInstance();
  2702. mBestMethodInstance = mModule->GetMethodInstance(mBestMethodTypeInstance, boxedMethodInstance.mMethodInstance->mMethodDef, BfTypeVector());
  2703. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  2704. }
  2705. else
  2706. {
  2707. mBestMethodTypeInstance = methodRef.mImplementingMethod.mTypeInstance;
  2708. mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodRef.mImplementingMethod);
  2709. mBestMethodDef = mBestMethodInstance.mMethodInstance->mMethodDef;
  2710. }
  2711. mBypassVirtual = true;
  2712. }
  2713. }
  2714. bool BfMethodMatcher::HasVarGenerics()
  2715. {
  2716. for (auto genericArg : mBestMethodGenericArguments)
  2717. if (genericArg->IsVar())
  2718. return true;
  2719. for (auto genericArg : mExplicitMethodGenericArguments)
  2720. if (genericArg->IsVar())
  2721. return true;
  2722. return false;
  2723. }
  2724. void BfMethodMatcher::CheckOuterTypeStaticMethods(BfTypeInstance* typeInstance, bool isFailurePass)
  2725. {
  2726. bool allowPrivate = true;
  2727. bool allowProtected = true;
  2728. auto curTypeInst = typeInstance;
  2729. auto curTypeDef = typeInstance->mTypeDef;
  2730. while (true)
  2731. {
  2732. curTypeDef->PopulateMemberSets();
  2733. BfMethodDef* nextMethodDef = NULL;
  2734. BfMemberSetEntry* entry;
  2735. if (curTypeDef->mMethodSet.TryGetWith(mMethodName, &entry))
  2736. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  2737. while (nextMethodDef != NULL)
  2738. {
  2739. auto checkMethod = nextMethodDef;
  2740. nextMethodDef = nextMethodDef->mNextWithSameName;
  2741. // These can only be invoked when the target itself is the interface
  2742. if (checkMethod->mExplicitInterface != NULL)
  2743. continue;
  2744. if ((checkMethod->mMethodType != mMethodType) || (!checkMethod->mIsStatic))
  2745. continue;
  2746. if (checkMethod->mName != mMethodName)
  2747. continue;
  2748. if ((!isFailurePass) && (!mModule->CheckProtection(checkMethod->mProtection, NULL, allowProtected, allowPrivate)))
  2749. continue;
  2750. CheckMethod(typeInstance, curTypeInst, checkMethod, isFailurePass);
  2751. }
  2752. if (mBestMethodDef != NULL)
  2753. return;
  2754. auto baseType = curTypeInst->mBaseType;
  2755. if (baseType == NULL)
  2756. break;
  2757. curTypeDef = baseType->mTypeDef;
  2758. curTypeInst = baseType;
  2759. allowPrivate = false;
  2760. if ((isFailurePass) && (mBackupMethodDef != NULL))
  2761. break;
  2762. }
  2763. if (mBestMethodDef == NULL)
  2764. {
  2765. // FAILED, but select the first method which will fire an actual error on param type matching
  2766. mBestMethodDef = mBackupMethodDef;
  2767. }
  2768. if (mBestMethodDef == NULL)
  2769. {
  2770. // No explicit target - maybe this was a static call in the outer type?
  2771. auto outerType = mModule->GetOuterType(typeInstance);
  2772. if (outerType != NULL)
  2773. CheckOuterTypeStaticMethods(outerType, isFailurePass);
  2774. }
  2775. }
  2776. //////////////////////////////////////////////////////////////////////////
  2777. void BfResolvedArgs::HandleFixits(BfModule* module)
  2778. {
  2779. auto compiler = module->mCompiler;
  2780. if ((!compiler->IsAutocomplete()) || (compiler->mResolvePassData->mResolveType != BfResolveType_GetFixits))
  2781. return;
  2782. SetAndRestoreValue<bool> ignoreErrors(module->mIgnoreErrors, true);
  2783. for (int argIdx = 0; argIdx < (int)mResolvedArgs.size(); argIdx++)
  2784. {
  2785. auto& resolvedArg = mResolvedArgs[argIdx];
  2786. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  2787. if (expr != NULL)
  2788. {
  2789. module->CreateValueFromExpression(expr, resolvedArg.mExpectedType);
  2790. }
  2791. }
  2792. }
  2793. //////////////////////////////////////////////////////////////////////////
  2794. BfExprEvaluator::BfExprEvaluator(BfModule* module)
  2795. {
  2796. mBfEvalExprFlags = BfEvalExprFlags_None;
  2797. mModule = module;
  2798. mPropDef = NULL;
  2799. mPropSrc = NULL;
  2800. mPropGetMethodFlags = BfGetMethodInstanceFlag_None;
  2801. mPropCheckedKind = BfCheckedKind_NotSet;
  2802. mUsedAsStatement = false;
  2803. mPropDefBypassVirtual = false;
  2804. mExpectingType = NULL;
  2805. mFunctionBindResult = NULL;
  2806. mExplicitCast = false;
  2807. mDeferCallRef = NULL;
  2808. mDeferScopeAlloc = NULL;
  2809. mPrefixedAttributeState = NULL;
  2810. mResolveGenericParam = true;
  2811. mNoBind = false;
  2812. mResultLocalVar = NULL;
  2813. mResultFieldInstance = NULL;
  2814. mResultLocalVarField = 0;
  2815. mResultLocalVarFieldCount = 0;
  2816. mResultLocalVarRefNode = NULL;
  2817. mIsVolatileReference = false;
  2818. mIsHeapReference = false;
  2819. mResultIsTempComposite = false;
  2820. mAllowReadOnlyReference = false;
  2821. mInsidePendingNullable = false;
  2822. mReceivingValue = NULL;
  2823. }
  2824. BfExprEvaluator::~BfExprEvaluator()
  2825. {
  2826. }
  2827. BfAutoComplete* BfExprEvaluator::GetAutoComplete()
  2828. {
  2829. if (mModule->mCompiler->mResolvePassData == NULL)
  2830. return NULL;
  2831. if ((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) != 0)
  2832. return NULL;
  2833. // For local methods- only process autocomplete on capture phase
  2834. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  2835. return NULL;
  2836. // if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod))
  2837. // return NULL;
  2838. return mModule->mCompiler->mResolvePassData->mAutoComplete;
  2839. }
  2840. bool BfExprEvaluator::IsComptime()
  2841. {
  2842. return (mModule->mIsComptimeModule) || ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  2843. }
  2844. bool BfExprEvaluator::IsConstEval()
  2845. {
  2846. return ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  2847. }
  2848. bool BfExprEvaluator::IsComptimeEntry()
  2849. {
  2850. if (mModule->mIsComptimeModule)
  2851. return false;
  2852. return ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  2853. }
  2854. int BfExprEvaluator::GetStructRetIdx(BfMethodInstance* methodInstance, bool forceStatic)
  2855. {
  2856. if (IsComptime())
  2857. return -1;
  2858. return methodInstance->GetStructRetIdx(forceStatic);
  2859. }
  2860. BfType* BfExprEvaluator::BindGenericType(BfAstNode* node, BfType* bindType)
  2861. {
  2862. if ((mModule->mCurMethodState == NULL) || (mModule->mCurMethodInstance == NULL) || (bindType == NULL))
  2863. return bindType;
  2864. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  2865. return bindType;
  2866. if ((mBfEvalExprFlags & BfEvalExprFlags_DeclType) != 0)
  2867. return bindType;
  2868. BF_ASSERT((!mModule->mCurMethodInstance->mIsUnspecializedVariation) || (mModule->mIsComptimeModule));
  2869. auto parser = node->GetSourceData()->ToParserData();
  2870. if (parser == NULL)
  2871. return bindType;
  2872. int64 nodeId = ((int64)parser->mDataId << 32) + node->GetSrcStart();
  2873. auto genericTypeBindings = mModule->mCurMethodState->GetRootMethodState()->mGenericTypeBindings;
  2874. auto methodInstance = mModule->mCurMethodInstance;
  2875. bool isMixinBind = false;
  2876. if (mModule->mCurMethodState->mMixinState != NULL)
  2877. {
  2878. auto mixinMethodInstance = mModule->mCurMethodState->mMixinState->mMixinMethodInstance;
  2879. if (!mixinMethodInstance->mMethodDef->mGenericParams.IsEmpty())
  2880. {
  2881. auto unspecMixinMethodInstance = mModule->GetUnspecializedMethodInstance(mixinMethodInstance, false);
  2882. if (!unspecMixinMethodInstance->mHasBeenProcessed)
  2883. {
  2884. // Make sure the unspecialized method is processed so we can take its bindings
  2885. // Clear mCurMethodState so we don't think we're in a local method
  2886. SetAndRestoreValue<BfMethodState*> prevMethodState_Unspec(mModule->mCurMethodState, NULL);
  2887. if (unspecMixinMethodInstance->mMethodProcessRequest == NULL)
  2888. unspecMixinMethodInstance->mDeclModule->mIncompleteMethodCount++;
  2889. mModule->mContext->ProcessMethod(unspecMixinMethodInstance);
  2890. }
  2891. isMixinBind = true;
  2892. methodInstance = mixinMethodInstance;
  2893. genericTypeBindings = &unspecMixinMethodInstance->mMethodInfoEx->mGenericTypeBindings;
  2894. }
  2895. }
  2896. if ((methodInstance->mIsUnspecialized) && (!methodInstance->mIsUnspecializedVariation))
  2897. {
  2898. if (isMixinBind)
  2899. return bindType;
  2900. if (!bindType->IsGenericParam())
  2901. return bindType;
  2902. if (genericTypeBindings == NULL)
  2903. return bindType;
  2904. (*genericTypeBindings)[nodeId] = bindType;
  2905. return bindType;
  2906. }
  2907. else
  2908. {
  2909. if (genericTypeBindings == NULL)
  2910. return bindType;
  2911. BfType** typePtr = NULL;
  2912. if (genericTypeBindings->TryGetValue(nodeId, &typePtr))
  2913. return *typePtr;
  2914. return bindType;
  2915. }
  2916. }
  2917. BfType * BfExprEvaluator::ResolveTypeRef(BfTypeReference* typeRef, BfPopulateType populateType, BfResolveTypeRefFlags resolveFlags)
  2918. {
  2919. if (mExpectingType != NULL)
  2920. {
  2921. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(typeRef))
  2922. {
  2923. if (namedTypeRef->ToString() == "ExpectedType")
  2924. {
  2925. return mModule->ResolveTypeResult(typeRef, mExpectingType, populateType, resolveFlags);
  2926. }
  2927. }
  2928. }
  2929. return mModule->ResolveTypeRef(typeRef, populateType, resolveFlags);
  2930. }
  2931. void BfExprEvaluator::ResolveGenericType()
  2932. {
  2933. if (mResult)
  2934. {
  2935. if (mModule->IsUnboundGeneric(mResult.mType))
  2936. mResult.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  2937. //mResult.mType = mModule->ResolveGenericType(mResult.mType, true);
  2938. }
  2939. }
  2940. void BfExprEvaluator::Evaluate(BfAstNode* astNode, bool propogateNullConditional, bool ignoreNullConditional, bool allowSplat)
  2941. {
  2942. BP_ZONE("BfExprEvaluator::Evaluate");
  2943. // ParenthesizedExpression breaks null conditional chain
  2944. if (astNode->IsExact<BfParenthesizedExpression>())
  2945. propogateNullConditional = false;
  2946. bool scopeWasConditional = false;
  2947. BfPendingNullConditional* pendingNullCond = NULL;
  2948. mInsidePendingNullable = false;
  2949. if (mModule->mCurMethodState != NULL)
  2950. {
  2951. scopeWasConditional = mModule->mCurMethodState->mCurScope->mIsConditional;
  2952. pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  2953. if (!propogateNullConditional)
  2954. mModule->mCurMethodState->mPendingNullConditional = NULL;
  2955. if (pendingNullCond != NULL)
  2956. {
  2957. mInsidePendingNullable = true;
  2958. mModule->mCurMethodState->mCurScope->mIsConditional = true;
  2959. }
  2960. }
  2961. astNode->Accept(this);
  2962. GetResult();
  2963. if ((mResultIsTempComposite) && (mResult.IsAddr()))
  2964. mResult.mKind = BfTypedValueKind_TempAddr;
  2965. if ((!allowSplat) && (mResult.IsSplat()))
  2966. mResult = mModule->AggregateSplat(mResult);
  2967. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowIntUnknown) == 0)
  2968. mModule->FixIntUnknown(mResult);
  2969. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  2970. {
  2971. if (mResult.mValue.IsConst())
  2972. {
  2973. auto constant = mModule->mBfIRBuilder->GetConstant(mResult.mValue);
  2974. if (constant->mConstType == BfConstType_TypeOf)
  2975. {
  2976. auto typeOfConst = (BfTypeOf_Const*)constant;
  2977. mResult.mValue = mModule->CreateTypeDataRef(typeOfConst->mType);
  2978. }
  2979. }
  2980. }
  2981. if (mModule->mCurMethodState != NULL)
  2982. {
  2983. if (mInsidePendingNullable)
  2984. mModule->mCurMethodState->mCurScope->mIsConditional = scopeWasConditional;
  2985. if (!propogateNullConditional)
  2986. {
  2987. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  2988. mResult = mModule->FlushNullConditional(mResult, ignoreNullConditional);
  2989. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  2990. }
  2991. }
  2992. }
  2993. void BfExprEvaluator::Visit(BfErrorNode* errorNode)
  2994. {
  2995. mModule->Fail("Invalid token", errorNode);
  2996. auto autoComplete = GetAutoComplete();
  2997. if (autoComplete != NULL)
  2998. {
  2999. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(errorNode->mRefNode))
  3000. return;
  3001. autoComplete->CheckIdentifier(errorNode->mRefNode, true);
  3002. }
  3003. }
  3004. void BfExprEvaluator::Visit(BfTypeReference* typeRef)
  3005. {
  3006. mResult.mType = ResolveTypeRef(typeRef, BfPopulateType_Declaration);
  3007. }
  3008. void BfExprEvaluator::Visit(BfAttributedExpression* attribExpr)
  3009. {
  3010. BfAttributeState attributeState;
  3011. attributeState.mSrc = attribExpr->mAttributes;
  3012. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  3013. if (auto block = BfNodeDynCast<BfBlock>(attribExpr->mExpression))
  3014. attributeState.mTarget = BfAttributeTargets_Block;
  3015. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attribExpr->mAttributes, attributeState.mTarget);
  3016. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  3017. if (auto ignoreErrorsAttrib = attributeState.mCustomAttributes->Get(mModule->mCompiler->mIgnoreErrorsAttributeTypeDef))
  3018. {
  3019. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  3020. if (!ignoreErrorsAttrib->mCtorArgs.IsEmpty())
  3021. {
  3022. auto constant = mModule->mCurTypeInstance->mConstHolder->GetConstant(ignoreErrorsAttrib->mCtorArgs[0]);
  3023. if (constant->mBool)
  3024. attributeState.mFlags = BfAttributeState::Flag_StopOnError;
  3025. }
  3026. VisitChild(attribExpr->mExpression);
  3027. attributeState.mUsed = true;
  3028. if ((!mResult) ||
  3029. ((mResult) && (mResult.mType->IsVar())))
  3030. {
  3031. if (!mResult)
  3032. mModule->Fail("Expression did not result in a value", attribExpr->mExpression);
  3033. // Make empty or 'var' resolve as 'false' because var is only valid if we threw errors
  3034. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Boolean));
  3035. }
  3036. }
  3037. else if (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mConstSkipAttributeTypeDef))
  3038. {
  3039. if ((mModule->mCurMethodState == NULL) || (mModule->mCurMethodState->mCurScope == NULL) || (!mModule->mCurMethodState->mCurScope->mInConstIgnore))
  3040. {
  3041. VisitChild(attribExpr->mExpression);
  3042. }
  3043. else
  3044. {
  3045. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  3046. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  3047. }
  3048. attributeState.mUsed = true;
  3049. }
  3050. else
  3051. {
  3052. VisitChild(attribExpr->mExpression);
  3053. }
  3054. mModule->FinishAttributeState(&attributeState);
  3055. }
  3056. void BfExprEvaluator::Visit(BfNamedExpression* namedExpr)
  3057. {
  3058. if (namedExpr->mExpression != NULL)
  3059. VisitChild(namedExpr->mExpression);
  3060. }
  3061. void BfExprEvaluator::Visit(BfBlock* blockExpr)
  3062. {
  3063. if (mModule->mCurMethodState == NULL)
  3064. {
  3065. mModule->Fail("Illegal use of block expression", blockExpr);
  3066. return;
  3067. }
  3068. auto autoComplete = GetAutoComplete();
  3069. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(blockExpr)))
  3070. {
  3071. // Don't show outer method match info when our cursor is inside a block (being passed as a parameter)
  3072. autoComplete->RemoveMethodMatchInfo();
  3073. }
  3074. if (blockExpr->mChildArr.IsEmpty())
  3075. {
  3076. mModule->Fail("An empty block cannot be used as an expression", blockExpr);
  3077. return;
  3078. }
  3079. bool lastWasResultExpr = false;
  3080. if (auto lastExpr = BfNodeDynCast<BfExpressionStatement>(blockExpr->mChildArr.GetLast()))
  3081. {
  3082. if (!lastExpr->IsMissingSemicolon())
  3083. mModule->Fail("Expression blocks must end in an expression which is missing its terminating semicolon", lastExpr->mTrailingSemicolon);
  3084. }
  3085. else if (blockExpr->mChildArr.GetLast()->IsExpression())
  3086. {
  3087. // Expression
  3088. }
  3089. else
  3090. {
  3091. mModule->Fail("Expression blocks must end with an expression", blockExpr);
  3092. }
  3093. mModule->VisitEmbeddedStatement(blockExpr, this, BfNodeIsA<BfUnscopedBlock>(blockExpr) ? BfEmbeddedStatementFlags_Unscoped : BfEmbeddedStatementFlags_None);
  3094. }
  3095. bool BfExprEvaluator::CheckVariableDeclaration(BfAstNode* checkNode, bool requireSimpleIfExpr, bool exprMustBeTrue, bool silentFail)
  3096. {
  3097. if (BfNodeIsA<BfUninitializedExpression>(checkNode))
  3098. return true;
  3099. BfAstNode* checkChild = checkNode;
  3100. bool childWasAndRHS = false;
  3101. bool foundIf = false;
  3102. auto parentNodeEntry = mModule->mParentNodeEntry;
  3103. if (parentNodeEntry != NULL)
  3104. {
  3105. if (BfNodeIsA<BfInvocationExpression>(parentNodeEntry->mNode))
  3106. {
  3107. checkChild = parentNodeEntry->mNode;
  3108. parentNodeEntry = parentNodeEntry->mPrev;
  3109. }
  3110. }
  3111. auto _Fail = [&](const StringImpl& errorStr, BfAstNode* node)
  3112. {
  3113. if (!silentFail)
  3114. {
  3115. auto error = mModule->Fail(errorStr, node);
  3116. if ((error != NULL) && (node != checkNode))
  3117. {
  3118. mModule->mCompiler->mPassInstance->MoreInfo("See variable declaration", checkNode);
  3119. }
  3120. }
  3121. return false;
  3122. };
  3123. while (parentNodeEntry != NULL)
  3124. {
  3125. BfAstNode* checkParent = parentNodeEntry->mNode;
  3126. if (auto binOpExpr = BfNodeDynCastExact<BfBinaryOperatorExpression>(checkParent))
  3127. {
  3128. if (binOpExpr->mOp == BfBinaryOp_ConditionalAnd)
  3129. {
  3130. // This is always okay
  3131. childWasAndRHS = (binOpExpr->mRight != NULL) && (binOpExpr->mRight->Contains(checkChild));
  3132. }
  3133. else if ((binOpExpr->mOp == BfBinaryOp_ConditionalOr) && (!exprMustBeTrue))
  3134. {
  3135. if ((binOpExpr->mRight != NULL) && (binOpExpr->mRight->Contains(checkChild)))
  3136. {
  3137. return _Fail("Conditional short-circuiting may skip variable initialization", binOpExpr->mOpToken);
  3138. }
  3139. }
  3140. else
  3141. {
  3142. if (exprMustBeTrue)
  3143. {
  3144. return _Fail("Operator cannot be used with variable initialization", binOpExpr->mOpToken);
  3145. }
  3146. }
  3147. }
  3148. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(checkParent))
  3149. {
  3150. // This is okay
  3151. }
  3152. else if (auto unaryOp = BfNodeDynCast<BfUnaryOperatorExpression>(checkParent))
  3153. {
  3154. if (exprMustBeTrue)
  3155. {
  3156. return _Fail("Operator cannot be used with variable initialization", unaryOp->mOpToken);
  3157. return false;
  3158. }
  3159. if (childWasAndRHS)
  3160. {
  3161. return _Fail("Operator may allow conditional short-circuiting to skip variable initialization", unaryOp->mOpToken);
  3162. }
  3163. }
  3164. else if (auto ifStmt = BfNodeDynCast<BfIfStatement>(checkParent))
  3165. {
  3166. // Done
  3167. foundIf = true;
  3168. break;
  3169. }
  3170. else
  3171. {
  3172. if (requireSimpleIfExpr)
  3173. {
  3174. return _Fail("Variable declaration expression can only be contained in simple 'if' expressions", checkNode);
  3175. }
  3176. break;
  3177. }
  3178. checkChild = parentNodeEntry->mNode;
  3179. parentNodeEntry = parentNodeEntry->mPrev;
  3180. }
  3181. return foundIf;
  3182. }
  3183. bool BfExprEvaluator::HasVariableDeclaration(BfAstNode* checkNode)
  3184. {
  3185. BfVarDeclChecker checker;
  3186. checker.VisitChild(checkNode);
  3187. return checker.mHasVarDecl;
  3188. }
  3189. void BfExprEvaluator::Visit(BfVariableDeclaration* varDecl)
  3190. {
  3191. mModule->UpdateExprSrcPos(varDecl);
  3192. if ((mModule->mCurMethodState == NULL) || (!mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations))
  3193. {
  3194. mModule->Fail("Variable declarations are not allowed in this context", varDecl);
  3195. if (varDecl->mInitializer != NULL)
  3196. {
  3197. VisitChild(varDecl->mInitializer);
  3198. }
  3199. return;
  3200. }
  3201. CheckVariableDeclaration(varDecl, true, false, false);
  3202. if (varDecl->mInitializer == NULL)
  3203. {
  3204. mModule->Fail("Variable declarations used as expressions must have an initializer", varDecl);
  3205. }
  3206. BfTupleExpression* tupleVariableDeclaration = BfNodeDynCast<BfTupleExpression>(varDecl->mNameNode);
  3207. if (tupleVariableDeclaration != NULL)
  3208. {
  3209. mModule->Fail("Tuple variable declarations cannot be used as expressions", varDecl);
  3210. mModule->HandleTupleVariableDeclaration(varDecl);
  3211. }
  3212. else
  3213. mModule->HandleVariableDeclaration(varDecl, this);
  3214. }
  3215. void BfExprEvaluator::Visit(BfCaseExpression* caseExpr)
  3216. {
  3217. if (caseExpr->mEqualsNode != NULL)
  3218. {
  3219. mModule->Warn(0, "Deprecated case syntax", caseExpr->mEqualsNode);
  3220. }
  3221. BfTypedValue caseValAddr;
  3222. if (caseExpr->mValueExpression != NULL)
  3223. caseValAddr = mModule->CreateValueFromExpression(caseExpr->mValueExpression, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  3224. if ((caseValAddr.mType != NULL) && (caseValAddr.mType->IsPointer()))
  3225. {
  3226. caseValAddr = mModule->LoadValue(caseValAddr);
  3227. caseValAddr = BfTypedValue(caseValAddr.mValue, caseValAddr.mType->GetUnderlyingType(), true);
  3228. }
  3229. if (caseValAddr.mType != NULL)
  3230. mModule->mBfIRBuilder->PopulateType(caseValAddr.mType);
  3231. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  3232. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  3233. if (auto bindExpr = BfNodeDynCast<BfEnumCaseBindExpression>(caseExpr->mCaseExpression))
  3234. {
  3235. if (caseValAddr)
  3236. {
  3237. BfTypedValue enumTagVal;
  3238. if (caseValAddr.mType->IsPayloadEnum())
  3239. {
  3240. int dscrDataIdx;
  3241. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  3242. enumTagVal = BfTypedValue(mModule->ExtractValue(caseValAddr, dscrDataIdx), dscrType);
  3243. }
  3244. else
  3245. enumTagVal = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Int32));
  3246. mResult = mModule->HandleCaseBind(caseValAddr, enumTagVal, bindExpr);
  3247. return;
  3248. }
  3249. }
  3250. bool isPayloadEnum = (caseValAddr.mType != NULL) && (caseValAddr.mType->IsPayloadEnum());
  3251. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(caseExpr->mCaseExpression);
  3252. if ((caseValAddr) &&
  3253. ((isPayloadEnum) || (tupleExpr != NULL)))
  3254. {
  3255. bool hasVariable = false;
  3256. bool hasOut = false;
  3257. bool clearOutOnMismatch = false;
  3258. if (auto invocateExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression))
  3259. {
  3260. for (auto arg : invocateExpr->mArguments)
  3261. {
  3262. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(arg))
  3263. {
  3264. hasVariable = true;
  3265. }
  3266. else if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(arg))
  3267. {
  3268. if ((unaryOpExpr->mOpToken != NULL) && (unaryOpExpr->mOpToken->mToken == BfToken_Out))
  3269. {
  3270. hasOut = true;
  3271. }
  3272. }
  3273. }
  3274. }
  3275. if (hasVariable)
  3276. {
  3277. CheckVariableDeclaration(caseExpr, false, true, false);
  3278. }
  3279. // We can avoid clearing on mismatch if we can be sure we ONLY enter the true block on a match.
  3280. // An example of requiring clearing is: if ((result case .Ok(out val)) || (force))
  3281. if (hasOut)
  3282. clearOutOnMismatch = !CheckVariableDeclaration(caseExpr, true, true, true);
  3283. bool hadConditional = false;
  3284. if (isPayloadEnum)
  3285. {
  3286. int dscrDataIdx;
  3287. auto dscrType = caseValAddr.mType->ToTypeInstance()->GetDiscriminatorType(&dscrDataIdx);
  3288. auto enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  3289. int uncondTagId = -1;
  3290. mResult = mModule->TryCaseEnumMatch(caseValAddr, enumTagVal, caseExpr->mCaseExpression, NULL, NULL, NULL, uncondTagId, hadConditional, clearOutOnMismatch, false);
  3291. }
  3292. else
  3293. {
  3294. mResult = mModule->TryCaseTupleMatch(caseValAddr, tupleExpr, NULL, NULL, NULL, hadConditional, clearOutOnMismatch, false);
  3295. }
  3296. if (mResult)
  3297. return;
  3298. }
  3299. if ((caseValAddr) && (IsVar(caseValAddr.mType)))
  3300. {
  3301. auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(caseExpr->mCaseExpression);
  3302. if (invocationExpr != NULL)
  3303. {
  3304. for (auto expr : invocationExpr->mArguments)
  3305. {
  3306. if (expr == NULL)
  3307. continue;
  3308. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(expr))
  3309. {
  3310. auto localVar = mModule->HandleVariableDeclaration(varDecl, BfTypedValue());
  3311. if (localVar != NULL)
  3312. localVar->mReadFromId = 0;
  3313. }
  3314. }
  3315. }
  3316. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  3317. mResult = mModule->GetDefaultTypedValue(boolType);
  3318. return;
  3319. }
  3320. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  3321. BfTypedValue caseMatch;
  3322. if (caseExpr->mCaseExpression != NULL)
  3323. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, caseValAddr.mType, BfEvalExprFlags_AllowEnumId);
  3324. if ((!caseMatch) || (!caseValAddr))
  3325. {
  3326. mResult = mModule->GetDefaultTypedValue(boolType);
  3327. return;
  3328. }
  3329. if (caseValAddr.mType == caseMatch.mType)
  3330. {
  3331. if (((caseValAddr.mType->IsEnum()) && (caseValAddr.mType->IsStruct())) &&
  3332. ((caseMatch) && (caseMatch.mType->IsPayloadEnum()) && (caseMatch.mValue.IsConst())))
  3333. {
  3334. BfTypedValue enumTagVal = mModule->LoadValue(mModule->ExtractValue(caseValAddr, NULL, 2));
  3335. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(enumTagVal.mValue, caseMatch.mValue), boolType);
  3336. return;
  3337. }
  3338. }
  3339. else
  3340. {
  3341. // We need to get rid of the int-const for the 'scalar match'. We get a full payload enum value so we can
  3342. // possibly use it in a user-defined comparison operator
  3343. if ((caseMatch.mType->IsStruct()) && (caseMatch.mValue.IsConst()))
  3344. {
  3345. // Is it possible this could throw an error twice? Hope not.
  3346. caseMatch = mModule->CreateValueFromExpression(caseExpr->mCaseExpression, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  3347. }
  3348. }
  3349. PerformBinaryOperation(caseExpr->mCaseExpression, caseExpr->mValueExpression, BfBinaryOp_Equality, caseExpr->mEqualsNode, BfBinOpFlag_None, caseValAddr, caseMatch);
  3350. }
  3351. void BfExprEvaluator::Visit(BfTypedValueExpression* typedValueExpr)
  3352. {
  3353. mResult = typedValueExpr->mTypedValue;
  3354. }
  3355. static bool IsCharType(BfTypeCode typeCode)
  3356. {
  3357. switch (typeCode)
  3358. {
  3359. case BfTypeCode_Char8:
  3360. case BfTypeCode_Char16:
  3361. case BfTypeCode_Char32:
  3362. return true;
  3363. default:
  3364. return false;
  3365. }
  3366. }
  3367. bool BfExprEvaluator::CheckForMethodName(BfAstNode* refNode, BfTypeInstance* typeInst, const StringImpl& findName)
  3368. {
  3369. BF_ASSERT((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0);
  3370. auto autoComplete = GetAutoComplete();
  3371. while (typeInst != NULL)
  3372. {
  3373. auto typeDef = typeInst->mTypeDef;
  3374. typeDef->PopulateMemberSets();
  3375. BfMemberSetEntry* memberSetEntry;
  3376. if (typeDef->mMethodSet.TryGetWith(findName, &memberSetEntry))
  3377. {
  3378. if (mModule->mCompiler->mResolvePassData != NULL)
  3379. mModule->mCompiler->mResolvePassData->HandleMethodReference(refNode, typeDef, (BfMethodDef*)memberSetEntry->mMemberDef);
  3380. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(refNode)))
  3381. {
  3382. autoComplete->SetDefinitionLocation(((BfMethodDef*)memberSetEntry->mMemberDef)->GetRefNode());
  3383. if ((autoComplete->mResolveType == BfResolveType_GetSymbolInfo) && (autoComplete->mDefType == NULL))
  3384. {
  3385. autoComplete->mDefType = typeDef;
  3386. autoComplete->mDefMethod = (BfMethodDef*)memberSetEntry->mMemberDef;
  3387. }
  3388. }
  3389. if (mModule->mCompiler->mResolvePassData != NULL)
  3390. {
  3391. if (auto sourceClassifier = mModule->mCompiler->mResolvePassData->GetSourceClassifier(refNode))
  3392. sourceClassifier->SetElementType(refNode, BfSourceElementType_Method);
  3393. }
  3394. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NameOfSuccess);
  3395. return true;
  3396. }
  3397. typeInst = typeInst->mBaseType;
  3398. }
  3399. return false;
  3400. }
  3401. bool BfExprEvaluator::IsVar(BfType* type, bool forceIgnoreWrites)
  3402. {
  3403. if (type->IsVar())
  3404. return true;
  3405. if ((type->IsGenericParam()) && (!forceIgnoreWrites) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  3406. {
  3407. BF_ASSERT(mModule->mIsComptimeModule);
  3408. return true;
  3409. }
  3410. return false;
  3411. }
  3412. void BfExprEvaluator::GetLiteral(BfAstNode* refNode, const BfVariant& variant)
  3413. {
  3414. switch (variant.mTypeCode)
  3415. {
  3416. case BfTypeCode_NullPtr:
  3417. {
  3418. auto nullType = mModule->ResolveTypeDef(mModule->mSystem->mTypeNullPtr);
  3419. /*mResult = BfTypedValue(ConstantPointerNull::get((PointerType*) nullType->mIRType), nullType);*/
  3420. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstNull(), nullType);
  3421. }
  3422. break;
  3423. case BfTypeCode_CharPtr:
  3424. {
  3425. if ((mExpectingType != NULL) && (mExpectingType->IsSizedArray()))
  3426. {
  3427. auto sizedArray = (BfSizedArrayType*)mExpectingType;
  3428. if (sizedArray->mElementType == mModule->GetPrimitiveType(BfTypeCode_Char8))
  3429. {
  3430. if (variant.mString->GetLength() > sizedArray->mElementCount)
  3431. {
  3432. mModule->Fail(StrFormat("String literal is too long to fit into '%s'", mModule->TypeToString(sizedArray).c_str()), refNode);
  3433. }
  3434. Array<BfIRValue> charValues;
  3435. for (int i = 0; i < (int)BF_MIN(variant.mString->GetLength(), sizedArray->mElementCount); i++)
  3436. {
  3437. char c = (*variant.mString)[i];
  3438. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, (int)(uint8)c));
  3439. }
  3440. if (sizedArray->mElementCount > charValues.size())
  3441. charValues.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Char8, 0));
  3442. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(sizedArray), charValues), sizedArray);
  3443. return;
  3444. }
  3445. }
  3446. if ((mExpectingType == NULL) || (!mExpectingType->IsPointer()))
  3447. {
  3448. mResult = BfTypedValue(mModule->GetStringObjectValue(*variant.mString),
  3449. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  3450. }
  3451. else
  3452. {
  3453. auto charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  3454. auto charPtrType = mModule->CreatePointerType(charType);
  3455. mResult = BfTypedValue(mModule->GetStringCharPtr(*variant.mString),
  3456. charPtrType);
  3457. }
  3458. }
  3459. break;
  3460. case BfTypeCode_Boolean:
  3461. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  3462. break;
  3463. case BfTypeCode_Char8:
  3464. case BfTypeCode_Char16:
  3465. case BfTypeCode_Char32:
  3466. case BfTypeCode_Int8:
  3467. case BfTypeCode_UInt8:
  3468. case BfTypeCode_Int16:
  3469. case BfTypeCode_UInt16:
  3470. case BfTypeCode_Int32:
  3471. case BfTypeCode_UInt32:
  3472. case BfTypeCode_Int64:
  3473. case BfTypeCode_UInt64:
  3474. case BfTypeCode_IntPtr:
  3475. case BfTypeCode_UIntPtr:
  3476. case BfTypeCode_IntUnknown:
  3477. case BfTypeCode_UIntUnknown:
  3478. if ((mExpectingType != NULL) && (mExpectingType->IsIntegral()) && (mExpectingType->IsChar() == IsCharType(variant.mTypeCode)))
  3479. {
  3480. auto primType = (BfPrimitiveType*)mExpectingType;
  3481. if (mModule->mSystem->DoesLiteralFit(primType->mTypeDef->mTypeCode, variant.mUInt64))
  3482. {
  3483. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, variant.mUInt64), mExpectingType);
  3484. break;
  3485. }
  3486. }
  3487. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->GetPrimitiveType(variant.mTypeCode));
  3488. break;
  3489. case BfTypeCode_Float:
  3490. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mSingle), mModule->GetPrimitiveType(variant.mTypeCode));
  3491. break;
  3492. case BfTypeCode_Double:
  3493. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mDouble), mModule->GetPrimitiveType(variant.mTypeCode));
  3494. break;
  3495. case BfTypeCode_StringId:
  3496. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(variant.mTypeCode, variant.mUInt64), mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  3497. break;
  3498. case BfTypeCode_Let:
  3499. if (mExpectingType != NULL)
  3500. {
  3501. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateUndefValue(mModule->mBfIRBuilder->MapType(mExpectingType)), mExpectingType);
  3502. break;
  3503. }
  3504. mModule->Fail("Invalid undef literal", refNode);
  3505. break;
  3506. default:
  3507. mModule->Fail("Invalid literal", refNode);
  3508. break;
  3509. }
  3510. }
  3511. void BfExprEvaluator::Visit(BfLiteralExpression* literalExpr)
  3512. {
  3513. switch (literalExpr->mValue.mWarnType)
  3514. {
  3515. case BfWarning_BF4201_Only7Hex:
  3516. mModule->Warn(BfWarning_BF4201_Only7Hex, "Only 7 hex digits specified. Add a leading zero to clarify intention.", literalExpr);
  3517. break;
  3518. case BfWarning_BF4202_TooManyHexForInt:
  3519. mModule->Warn(BfWarning_BF4202_TooManyHexForInt, "Nine hex digits specified. If an 8-digit hex literal was not intended then add a leading zero to clarify.", literalExpr);
  3520. break;
  3521. }
  3522. GetLiteral(literalExpr, literalExpr->mValue);
  3523. }
  3524. void BfExprEvaluator::Visit(BfStringInterpolationExpression* stringInterpolationExpression)
  3525. {
  3526. if ((mBfEvalExprFlags & BfEvalExprFlags_StringInterpolateFormat) != 0)
  3527. {
  3528. BfVariant variant;
  3529. variant.mTypeCode = BfTypeCode_CharPtr;
  3530. variant.mString = stringInterpolationExpression->mString;
  3531. GetLiteral(stringInterpolationExpression, variant);
  3532. return;
  3533. }
  3534. //
  3535. {
  3536. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlag(mBfEvalExprFlags);
  3537. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mConstEvalAttributeTypeDef)))
  3538. {
  3539. mModule->mAttributeState->mUsed = true;
  3540. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  3541. }
  3542. if (IsConstEval())
  3543. {
  3544. auto stringType = mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef);
  3545. if (stringType != NULL)
  3546. {
  3547. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, true);
  3548. SizedArray<BfExpression*, 2> argExprs;
  3549. argExprs.Add(stringInterpolationExpression);
  3550. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  3551. BfResolvedArgs argValues(&sizedArgExprs);
  3552. ResolveArgValues(argValues, BfResolveArgsFlag_InsideStringInterpolationAlloc);
  3553. auto result = MatchMethod(stringInterpolationExpression, NULL, BfTypedValue(stringType), false, false, "ConstF", argValues, BfMethodGenericArguments());
  3554. if (result.mType == stringType)
  3555. {
  3556. mResult = result;
  3557. return;
  3558. }
  3559. }
  3560. mModule->Fail("Const evaluation of string interpolation not allowed", stringInterpolationExpression);
  3561. }
  3562. }
  3563. if (stringInterpolationExpression->mAllocNode != NULL)
  3564. {
  3565. auto stringType = mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef)->ToTypeInstance();
  3566. BfTokenNode* newToken = NULL;
  3567. BfAllocTarget allocTarget;
  3568. ResolveAllocTarget(allocTarget, stringInterpolationExpression->mAllocNode, newToken);
  3569. //
  3570. {
  3571. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  3572. CreateObject(NULL, stringInterpolationExpression->mAllocNode, stringType);
  3573. }
  3574. BfTypedValue newString = mResult;
  3575. BF_ASSERT(newString);
  3576. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, true);
  3577. SizedArray<BfExpression*, 2> argExprs;
  3578. argExprs.Add(stringInterpolationExpression);
  3579. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  3580. BfResolvedArgs argValues(&sizedArgExprs);
  3581. ResolveArgValues(argValues, BfResolveArgsFlag_InsideStringInterpolationAlloc);
  3582. MatchMethod(stringInterpolationExpression, NULL, newString, false, false, "AppendF", argValues, BfMethodGenericArguments());
  3583. mResult = newString;
  3584. return;
  3585. }
  3586. mModule->Fail("Invalid use of string interpolation expression. Consider adding an allocation specifier such as 'scope'.", stringInterpolationExpression);
  3587. for (auto block : stringInterpolationExpression->mExpressions)
  3588. {
  3589. VisitChild(block);
  3590. }
  3591. }
  3592. BfTypedValue BfExprEvaluator::LoadLocal(BfLocalVariable* varDecl, bool allowRef)
  3593. {
  3594. if (!mModule->mIsInsideAutoComplete)
  3595. varDecl->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  3596. // The Beef backend prefers readonly addrs since that reduces register pressure, whereas
  3597. // LLVM prefers values to avoid memory loads. This only applies to primitive types...
  3598. bool preferValue = (varDecl->mResolvedType->IsPrimitiveType()) && (!mModule->IsTargetingBeefBackend());
  3599. BfTypedValue localResult;
  3600. if (varDecl->mIsThis)
  3601. {
  3602. return mModule->GetThis();
  3603. }
  3604. else if (varDecl->mConstValue)
  3605. {
  3606. localResult = BfTypedValue(varDecl->mConstValue, varDecl->mResolvedType, false);
  3607. }
  3608. else if (varDecl->mIsSplat)
  3609. {
  3610. if ((!preferValue) && (varDecl->mAddr))
  3611. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  3612. else if (!varDecl->mResolvedType->IsValuelessType())
  3613. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, BfTypedValueKind_SplatHead);
  3614. else if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3615. {
  3616. BF_ASSERT(varDecl->mResolvedType->IsValuelessType());
  3617. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType->GetUnderlyingType());
  3618. }
  3619. else
  3620. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType);
  3621. //BF_ASSERT(varDecl->mValue.IsArg());
  3622. }
  3623. else if ((varDecl->mValue) && ((varDecl->mIsReadOnly && preferValue) || (!varDecl->mAddr)))
  3624. {
  3625. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3626. {
  3627. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3628. BfType* innerType = refType->mElementType;
  3629. if (innerType->IsGenericParam())
  3630. {
  3631. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3632. {
  3633. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_MutableValue);
  3634. return localResult;
  3635. }
  3636. else
  3637. {
  3638. localResult = BfTypedValue(varDecl->mValue, innerType, BfTypedValueKind_Addr);
  3639. return localResult;
  3640. }
  3641. }
  3642. localResult = BfTypedValue(varDecl->mValue, innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3643. }
  3644. else
  3645. {
  3646. BfTypedValueKind kind;
  3647. if ((varDecl->mResolvedType->IsComposite()) && (varDecl->mValue.IsArg()))
  3648. {
  3649. kind = varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr;
  3650. }
  3651. else
  3652. kind = BfTypedValueKind_Value;
  3653. localResult = BfTypedValue(varDecl->mValue, varDecl->mResolvedType, kind);
  3654. }
  3655. }
  3656. else if (varDecl->mAddr)
  3657. {
  3658. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3659. {
  3660. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3661. BfType* innerType = refType->mElementType;
  3662. if (innerType->IsValuelessType())
  3663. {
  3664. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3665. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, BfTypedValueKind_MutableValue);
  3666. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3667. }
  3668. if (refType->mRefKind == BfRefType::RefKind_Mut)
  3669. {
  3670. if (innerType->IsGenericParam())
  3671. {
  3672. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, BfTypedValueKind_MutableValue);
  3673. return localResult;
  3674. }
  3675. }
  3676. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), innerType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3677. }
  3678. else if (varDecl->mHasLocalStructBacking)
  3679. {
  3680. // varDecl->mAddr is a "struct**"
  3681. localResult = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(varDecl->mAddr, varDecl->mResolvedType->mAlign), varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3682. }
  3683. else
  3684. localResult = BfTypedValue(varDecl->mAddr, varDecl->mResolvedType, varDecl->mIsReadOnly ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3685. }
  3686. else if (varDecl->mResolvedType->IsValuelessType())
  3687. {
  3688. if ((varDecl->mResolvedType->IsRef()) && (!allowRef))
  3689. {
  3690. BfRefType* refType = (BfRefType*)varDecl->mResolvedType;
  3691. BfType* innerType = refType->mElementType;
  3692. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), innerType, true);
  3693. return localResult;
  3694. }
  3695. localResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), varDecl->mResolvedType, true);
  3696. }
  3697. else if (varDecl->mCompositeCount >= 0)
  3698. {
  3699. localResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  3700. }
  3701. else
  3702. {
  3703. BF_ASSERT((mModule->mCurMethodState->mClosureState != NULL) || (mModule->mBfIRBuilder->mIgnoreWrites));
  3704. // Just temporary
  3705. auto varType = varDecl->mResolvedType;
  3706. auto allocType = varType;
  3707. if (varType->IsRef())
  3708. {
  3709. BfRefType* refType = (BfRefType*)varType;
  3710. allocType = refType->mElementType;
  3711. }
  3712. auto declType = varDecl->mResolvedType;
  3713. if (declType->IsRef())
  3714. {
  3715. BfRefType* refType = (BfRefType*)declType;
  3716. declType = refType->mElementType;
  3717. }
  3718. mModule->PopulateType(allocType);
  3719. varDecl->mAddr = mModule->mBfIRBuilder->CreateAlloca(mModule->mBfIRBuilder->MapType(allocType));
  3720. localResult = BfTypedValue(varDecl->mAddr, declType, true);
  3721. return localResult;
  3722. }
  3723. if ((varDecl->mIsThis) && (localResult.mKind == BfTypedValueKind_Value))
  3724. localResult.mKind = BfTypedValueKind_ThisValue;
  3725. return localResult;
  3726. }
  3727. BfTypedValue BfExprEvaluator::LookupIdentifier(BfAstNode* refNode, const StringImpl& findName, bool ignoreInitialError, bool* hadError)
  3728. {
  3729. int varSkipCount = 0;
  3730. StringT<128> wantName;
  3731. wantName.Reference(findName);
  3732. if (findName.StartsWith('@'))
  3733. {
  3734. wantName = findName;
  3735. while (wantName.StartsWith("@"))
  3736. {
  3737. if (wantName != "@return")
  3738. varSkipCount++;
  3739. wantName.Remove(0);
  3740. }
  3741. }
  3742. if (wantName.IsEmpty())
  3743. {
  3744. mModule->Fail("Shadowed variable name expected after '@'", refNode);
  3745. }
  3746. if ((mModule->mCompiler->mCeMachine != NULL) && (mModule->mCompiler->mCeMachine->mDebugger != NULL) && (mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  3747. {
  3748. auto ceDebugger = mModule->mCompiler->mCeMachine->mDebugger;
  3749. auto ceContext = ceDebugger->mCurDbgState->mCeContext;
  3750. auto activeFrame = ceDebugger->mCurDbgState->mActiveFrame;
  3751. if (activeFrame->mFunction->mDbgInfo != NULL)
  3752. {
  3753. int varSkipCountLeft = varSkipCount;
  3754. int instIdx = activeFrame->GetInstIdx();
  3755. for (int i = activeFrame->mFunction->mDbgInfo->mVariables.mSize - 1; i >= 0; i--)
  3756. {
  3757. auto& dbgVar = activeFrame->mFunction->mDbgInfo->mVariables[i];
  3758. if (dbgVar.mName == wantName)
  3759. {
  3760. if (varSkipCountLeft > 0)
  3761. {
  3762. varSkipCountLeft--;
  3763. }
  3764. else if ((dbgVar.mValue.mKind == CeOperandKind_AllocaAddr) || (dbgVar.mValue.mKind == CeOperandKind_FrameOfs))
  3765. {
  3766. if ((instIdx >= dbgVar.mStartCodePos) && (instIdx < dbgVar.mEndCodePos))
  3767. {
  3768. return BfTypedValue(mModule->mBfIRBuilder->CreateConstAggCE(mModule->mBfIRBuilder->MapType(dbgVar.mType), activeFrame->mFrameAddr + dbgVar.mValue.mFrameOfs),
  3769. dbgVar.mType, dbgVar.mIsConst ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  3770. }
  3771. }
  3772. }
  3773. }
  3774. }
  3775. if (findName == "FR")
  3776. {
  3777. auto ptrType = mModule->CreatePointerType(mModule->GetPrimitiveType(BfTypeCode_UInt8));
  3778. auto intVal = mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, activeFrame->mFrameAddr);
  3779. auto ptrVal = mModule->mBfIRBuilder->CreateIntToPtr(intVal, mModule->mBfIRBuilder->MapType(ptrType));
  3780. return BfTypedValue(ptrVal, ptrType);
  3781. }
  3782. }
  3783. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(refNode);
  3784. if (mModule->mCurMethodState != NULL)
  3785. {
  3786. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  3787. auto checkMethodState = mModule->mCurMethodState;
  3788. bool isMixinOuterVariablePass = false;
  3789. while (checkMethodState != NULL)
  3790. {
  3791. BP_ZONE("LookupIdentifier:LocalVar");
  3792. BfTypeInstance* closureTypeInst = NULL;
  3793. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  3794. {
  3795. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  3796. }
  3797. int varSkipCountLeft = varSkipCount;
  3798. BfLocalVarEntry* entry;
  3799. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(wantName, &entry))
  3800. {
  3801. auto varDecl = entry->mLocalVar;
  3802. if (varDecl != NULL)
  3803. varSkipCountLeft -= varDecl->mNamePrefixCount;
  3804. while ((varSkipCountLeft > 0) && (varDecl != NULL))
  3805. {
  3806. varDecl = varDecl->mShadowedLocal;
  3807. varSkipCountLeft--;
  3808. }
  3809. if ((varDecl != NULL) && (varDecl->mNotCaptured))
  3810. {
  3811. mModule->Fail("Local variable is not captured", refNode);
  3812. }
  3813. if ((varSkipCountLeft == 0) && (varDecl != NULL))
  3814. {
  3815. if ((closureTypeInst != NULL) && (wantName == "this"))
  3816. break;
  3817. if ((varDecl->mCompositeCount >= 0) && ((mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) == 0))
  3818. {
  3819. mModule->Fail("Invalid use of 'params' parameter", refNode);
  3820. }
  3821. if (varDecl->mResolvedType->IsVoid())
  3822. {
  3823. if ((varDecl->mIsReadOnly) && (varDecl->mParamIdx == -2) && (varDecl->mParamFailed))
  3824. {
  3825. BF_ASSERT(mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend);
  3826. 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);
  3827. }
  3828. }
  3829. BfTypedValue localResult = LoadLocal(varDecl);
  3830. auto autoComplete = GetAutoComplete();
  3831. if (identifierNode != NULL)
  3832. {
  3833. if (autoComplete != NULL)
  3834. autoComplete->CheckLocalRef(identifierNode, varDecl);
  3835. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  3836. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL) && (!mModule->mCurMethodState->IsTemporary()))
  3837. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, varDecl->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, varDecl->mLocalVarId);
  3838. }
  3839. if (!isMixinOuterVariablePass)
  3840. {
  3841. mResultLocalVar = varDecl;
  3842. mResultFieldInstance = NULL;
  3843. mResultLocalVarRefNode = identifierNode;
  3844. }
  3845. return localResult;
  3846. }
  3847. }
  3848. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  3849. if (closureTypeInst != NULL)
  3850. {
  3851. int varSkipCountLeft = varSkipCount;
  3852. closureTypeInst->mTypeDef->PopulateMemberSets();
  3853. BfMemberSetEntry* memberSetEntry = NULL;
  3854. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith((StringImpl&)findName, &memberSetEntry))
  3855. {
  3856. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  3857. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  3858. if (!field.mResolvedType->IsValuelessType())
  3859. {
  3860. if (mModule->mCurMethodState->mClosureState->mCapturing)
  3861. {
  3862. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  3863. return mModule->GetDefaultTypedValue(field.mResolvedType);
  3864. }
  3865. auto localVar = mModule->mCurMethodState->mLocals[0];
  3866. auto thisValue = localVar->mValue;
  3867. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  3868. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  3869. if (field.mResolvedType->IsRef())
  3870. {
  3871. auto refType = (BfRefType*)field.mResolvedType;
  3872. auto underlyingType = refType->GetUnderlyingType();
  3873. result = BfTypedValue(mModule->mBfIRBuilder->CreateLoad(result.mValue), underlyingType, true);
  3874. }
  3875. else if (fieldDef->mIsReadOnly)
  3876. result = mModule->LoadValue(result);
  3877. mResultLocalVar = localVar;
  3878. mResultFieldInstance = &field;
  3879. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  3880. return result;
  3881. }
  3882. }
  3883. }
  3884. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  3885. {
  3886. checkMethodState = checkMethodState->mPrevMethodState;
  3887. continue;
  3888. }
  3889. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  3890. bool isLocalMixinProcessing = false;
  3891. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  3892. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  3893. isLocalMixinProcessing = true;
  3894. if (!isLocalMixinProcessing)
  3895. break;
  3896. isMixinOuterVariablePass = true;
  3897. checkMethodState = checkMethodState->mPrevMethodState;
  3898. }
  3899. }
  3900. if ((mModule->mCurMethodInstance == NULL) && (mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->IsEnum()))
  3901. {
  3902. if (findName == "_")
  3903. {
  3904. BfFieldDef* resolvingFieldDef = NULL;
  3905. auto checkTypeState = mModule->mContext->mCurTypeState;
  3906. while (checkTypeState != NULL)
  3907. {
  3908. if (checkTypeState->mCurFieldDef != NULL)
  3909. {
  3910. if (checkTypeState->mType == mModule->mCurTypeInstance)
  3911. resolvingFieldDef = checkTypeState->mCurFieldDef;
  3912. }
  3913. checkTypeState = checkTypeState->mPrevState;
  3914. }
  3915. if ((resolvingFieldDef != NULL) &&
  3916. (mModule->mCompiler->mResolvePassData != NULL) &&
  3917. (!mModule->mCompiler->mResolvePassData->mParsers.IsEmpty()) &&
  3918. (mModule->mCompiler->mResolvePassData->mParsers[0] == resolvingFieldDef->mFieldDeclaration->GetParser()) &&
  3919. (GetAutoComplete() != NULL))
  3920. {
  3921. return mModule->GetDefaultTypedValue(mModule->mCurTypeInstance);
  3922. }
  3923. else if ((resolvingFieldDef != NULL) && (resolvingFieldDef->mIdx > 0))
  3924. {
  3925. auto enumType = mModule->mCurTypeInstance;
  3926. if (!enumType->mFieldInstances.IsEmpty())
  3927. {
  3928. auto fieldInstance = &mModule->mCurTypeInstance->mFieldInstances[resolvingFieldDef->mIdx - 1];
  3929. if ((fieldInstance->mConstIdx != -1) &&
  3930. (fieldInstance->mResolvedType == mModule->mCurTypeInstance))
  3931. {
  3932. auto foreignConst = enumType->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  3933. auto retVal = mModule->ConstantToCurrent(foreignConst, enumType->mConstHolder, enumType);
  3934. return BfTypedValue(retVal, enumType);
  3935. }
  3936. }
  3937. }
  3938. }
  3939. }
  3940. BfTypedValue thisValue = mModule->GetThis(false);
  3941. bool forcedIFaceLookup = false;
  3942. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef))
  3943. {
  3944. thisValue.mType = mModule->mCurMethodInstance->GetForeignType();
  3945. forcedIFaceLookup = true;
  3946. }
  3947. if (thisValue)
  3948. {
  3949. if (findName == "this")
  3950. {
  3951. mModule->MarkUsingThis();
  3952. return thisValue;
  3953. }
  3954. if (findName == "base")
  3955. {
  3956. auto baseValue = thisValue;
  3957. if (baseValue.IsThis())
  3958. baseValue.ToBase();
  3959. if (mModule->GetActiveTypeDef()->mTypeCode != BfTypeCode_Extension)
  3960. {
  3961. MakeBaseConcrete(baseValue);
  3962. }
  3963. mModule->MarkUsingThis();
  3964. return baseValue;
  3965. }
  3966. if (!mModule->mCurMethodState->HasNonStaticMixin())
  3967. {
  3968. mResultLocalVar = mModule->GetThisVariable();
  3969. mResultFieldInstance = NULL;
  3970. mResultLocalVarRefNode = identifierNode;
  3971. }
  3972. }
  3973. if (!thisValue.HasType())
  3974. {
  3975. if ((mModule->mContext->mCurTypeState != NULL) && (mModule->mContext->mCurTypeState->mType == mModule->mCurTypeInstance) &&
  3976. (mModule->mContext->mCurTypeState->mResolveKind == BfTypeState::ResolveKind_Attributes))
  3977. {
  3978. // Can't do static lookups yet
  3979. }
  3980. else
  3981. thisValue = BfTypedValue(mModule->mCurTypeInstance);
  3982. }
  3983. BfTypedValue result;
  3984. if (thisValue.HasType())
  3985. {
  3986. result = LookupField(identifierNode, thisValue, findName, BfLookupFieldFlag_IsImplicitThis);
  3987. if (mResultFieldInstance == NULL)
  3988. {
  3989. mResultLocalVar = NULL;
  3990. mResultLocalVarRefNode = NULL;
  3991. }
  3992. }
  3993. if (mPropDef != NULL)
  3994. {
  3995. if (forcedIFaceLookup)
  3996. {
  3997. if (mPropTarget == thisValue)
  3998. {
  3999. mPropDefBypassVirtual = true;
  4000. mOrigPropTarget = mModule->GetThis();
  4001. }
  4002. }
  4003. }
  4004. if ((!result) && (mPropDef == NULL))
  4005. {
  4006. if (mModule->mContext->mCurTypeState != NULL)
  4007. {
  4008. // This is not necessarily true since we changed ConstResolver
  4009. //BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mTypeInstance);
  4010. BfGlobalLookup globalLookup;
  4011. globalLookup.mKind = BfGlobalLookup::Kind_Field;
  4012. globalLookup.mName = findName;
  4013. mModule->PopulateGlobalContainersList(globalLookup);
  4014. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  4015. {
  4016. if (globalContainer.mTypeInst == NULL)
  4017. continue;
  4018. thisValue = BfTypedValue(globalContainer.mTypeInst);
  4019. result = LookupField(identifierNode, thisValue, findName);
  4020. if ((result) || (mPropDef != NULL))
  4021. return result;
  4022. }
  4023. }
  4024. auto staticSearch = mModule->GetStaticSearch();
  4025. if (staticSearch != NULL)
  4026. {
  4027. for (auto typeInst : staticSearch->mStaticTypes)
  4028. {
  4029. thisValue = BfTypedValue(typeInst);
  4030. result = LookupField(identifierNode, thisValue, findName);
  4031. if ((result) || (mPropDef != NULL))
  4032. return result;
  4033. }
  4034. }
  4035. }
  4036. if ((!result) && (identifierNode != NULL))
  4037. {
  4038. result = mModule->TryLookupGenericConstVaue(identifierNode, mExpectingType);
  4039. if ((mBfEvalExprFlags & (BfEvalExprFlags_Comptime | BfEvalExprFlags_AllowGenericConstValue)) == BfEvalExprFlags_Comptime)
  4040. {
  4041. if (result.mKind == BfTypedValueKind_GenericConstValue)
  4042. {
  4043. auto genericParamDef = mModule->GetGenericParamInstance((BfGenericParamType*)result.mType);
  4044. if ((genericParamDef->mGenericParamFlags & BfGenericParamFlag_Const) != 0)
  4045. {
  4046. auto genericTypeConstraint = genericParamDef->mTypeConstraint;
  4047. if (genericTypeConstraint != NULL)
  4048. {
  4049. auto primType = genericTypeConstraint->ToPrimitiveType();
  4050. if (primType != NULL)
  4051. {
  4052. BfTypedValue result;
  4053. result.mKind = BfTypedValueKind_Value;
  4054. result.mType = genericTypeConstraint;
  4055. result.mValue = mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->GetPrimitiveType(primType->mTypeDef->mTypeCode));
  4056. return result;
  4057. }
  4058. }
  4059. else
  4060. {
  4061. BF_FATAL("Error");
  4062. }
  4063. }
  4064. }
  4065. }
  4066. mModule->FixValueActualization(result);
  4067. }
  4068. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (findName == "@this"))
  4069. {
  4070. if (mModule->mCurMethodState->mClosureState->mCapturing)
  4071. {
  4072. if (mModule->mCurMethodState->mClosureState->mDelegateType != NULL)
  4073. {
  4074. mModule->mCurMethodState->mClosureState->mCapturedDelegateSelf = true;
  4075. return mModule->GetDefaultTypedValue(mModule->mCurMethodState->mClosureState->mDelegateType);
  4076. }
  4077. }
  4078. else
  4079. {
  4080. if (!mModule->mCurMethodState->mLocals.IsEmpty())
  4081. {
  4082. auto thisLocal = mModule->mCurMethodState->mLocals[0];
  4083. if (thisLocal->mIsThis)
  4084. return BfTypedValue(mModule->mBfIRBuilder->CreateLoad(thisLocal->mAddr), thisLocal->mResolvedType);
  4085. }
  4086. }
  4087. }
  4088. return result;
  4089. }
  4090. BfTypedValue BfExprEvaluator::LookupIdentifier(BfIdentifierNode* identifierNode, bool ignoreInitialError, bool* hadError)
  4091. {
  4092. auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode);
  4093. if (qualifiedNameNode != NULL)
  4094. {
  4095. LookupQualifiedName(qualifiedNameNode, ignoreInitialError, hadError);
  4096. auto qualifiedResult = mResult;
  4097. mResult = BfTypedValue();
  4098. return qualifiedResult;
  4099. }
  4100. StringT<128> identifierStr;
  4101. identifierNode->ToString(identifierStr);
  4102. return LookupIdentifier(identifierNode, identifierStr, ignoreInitialError, hadError);
  4103. }
  4104. void BfExprEvaluator::Visit(BfIdentifierNode* identifierNode)
  4105. {
  4106. auto autoComplete = GetAutoComplete();
  4107. if (autoComplete != NULL)
  4108. autoComplete->CheckIdentifier(identifierNode, true);
  4109. mResult = LookupIdentifier(identifierNode);
  4110. if ((!mResult) && (mPropDef == NULL))
  4111. {
  4112. mModule->CheckTypeRefFixit(identifierNode);
  4113. if ((autoComplete != NULL) && (autoComplete->CheckFixit(identifierNode)))
  4114. {
  4115. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  4116. {
  4117. // During this phase we don't have lambda and local method params available so they would result in erroneous fixits
  4118. }
  4119. else if (mModule->mCurMethodInstance != NULL)
  4120. {
  4121. BfType* fieldType = mExpectingType;
  4122. if (fieldType == NULL)
  4123. fieldType = mModule->mContext->mBfObjectType;
  4124. autoComplete->FixitAddMember(mModule->mCurTypeInstance, fieldType, identifierNode->ToString(), true, mModule->mCurTypeInstance);
  4125. if (!mModule->mCurMethodInstance->mMethodDef->mIsStatic)
  4126. autoComplete->FixitAddMember(mModule->mCurTypeInstance, fieldType, identifierNode->ToString(), false, mModule->mCurTypeInstance);
  4127. for (auto typeDef : mModule->mSystem->mTypeDefs)
  4128. {
  4129. if (!typeDef->mIsCombinedPartial)
  4130. continue;
  4131. if (!typeDef->IsGlobalsContainer())
  4132. continue;
  4133. typeDef->PopulateMemberSets();
  4134. String findName = identifierNode->ToString();
  4135. BfMemberSetEntry* memberSetEntry;
  4136. if ((typeDef->mMethodSet.TryGetWith(findName, &memberSetEntry)) ||
  4137. (typeDef->mFieldSet.TryGetWith(findName, &memberSetEntry)) ||
  4138. (typeDef->mPropertySet.TryGetWith(findName, &memberSetEntry)))
  4139. {
  4140. if (mModule->GetActiveTypeDef()->mProject->ContainsReference(typeDef->mProject))
  4141. autoComplete->FixitAddNamespace(identifierNode, typeDef->mNamespace.ToString());
  4142. }
  4143. }
  4144. }
  4145. }
  4146. if (((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0) && (mModule->mCurTypeInstance != NULL) && (CheckForMethodName(identifierNode, mModule->mCurTypeInstance, identifierNode->ToString())))
  4147. return;
  4148. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  4149. mModule->Fail("Identifier not found", identifierNode);
  4150. }
  4151. }
  4152. void BfExprEvaluator::Visit(BfAttributedIdentifierNode* attrIdentifierNode)
  4153. {
  4154. if ((mModule->mAttributeState != NULL))
  4155. {
  4156. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  4157. VisitChild(attrIdentifierNode->mIdentifier);
  4158. }
  4159. else
  4160. {
  4161. BfAttributeState attributeState;
  4162. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  4163. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  4164. mModule->mAttributeState->mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierNode->mAttributes, mModule->mAttributeState->mTarget);
  4165. VisitChild(attrIdentifierNode->mIdentifier);
  4166. }
  4167. }
  4168. static int gPropIdx = 0;
  4169. void BfExprEvaluator::FixitAddMember(BfTypeInstance* typeInst, BfType* fieldType, const StringImpl& fieldName, bool isStatic)
  4170. {
  4171. if (fieldType == NULL)
  4172. {
  4173. fieldType = mExpectingType;
  4174. }
  4175. if (fieldType != NULL)
  4176. {
  4177. if (fieldType->IsRef())
  4178. fieldType = fieldType->GetUnderlyingType();
  4179. }
  4180. mModule->mCompiler->mResolvePassData->mAutoComplete->FixitAddMember(typeInst, fieldType, fieldName, isStatic, mModule->mCurTypeInstance);
  4181. }
  4182. BfTypedValue BfExprEvaluator::TryArrowLookup(BfTypedValue typedValue, BfTokenNode* arrowToken)
  4183. {
  4184. auto arrowValue = PerformUnaryOperation_TryOperator(typedValue, NULL, BfUnaryOp_Arrow, arrowToken, BfUnaryOpFlag_None);
  4185. if (arrowValue)
  4186. return arrowValue;
  4187. if (mModule->PreFail())
  4188. mModule->Fail(StrFormat("Type '%s' does not contain a '->' operator", mModule->TypeToString(typedValue.mType).c_str()), arrowToken);
  4189. return typedValue;
  4190. }
  4191. BfTypedValue BfExprEvaluator::LoadProperty(BfAstNode* targetSrc, BfTypedValue target, BfTypeInstance* typeInstance, BfPropertyDef* prop, BfLookupFieldFlags flags, BfCheckedKind checkedKind, bool isInlined)
  4192. {
  4193. if ((flags & BfLookupFieldFlag_IsAnonymous) == 0)
  4194. mModule->SetElementType(targetSrc, BfSourceElementType_Method);
  4195. if ((!prop->mIsStatic) && ((flags & BfLookupFieldFlag_IsImplicitThis) != 0))
  4196. mModule->MarkUsingThis();
  4197. mPropSrc = targetSrc;
  4198. mPropDef = prop;
  4199. mPropCheckedKind = checkedKind;
  4200. if (isInlined)
  4201. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  4202. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  4203. {
  4204. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef))
  4205. {
  4206. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_Friend);
  4207. mModule->mAttributeState->mUsed = true;
  4208. }
  4209. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef))
  4210. {
  4211. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_DisableObjectAccessChecks);
  4212. mModule->mAttributeState->mUsed = true;
  4213. }
  4214. }
  4215. if (mPropDef->mIsStatic)
  4216. {
  4217. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!typeInstance->mTypeDef->IsGlobalsContainer()))
  4218. {
  4219. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  4220. mModule->Fail(StrFormat("Property '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  4221. mModule->TypeToString(typeInstance).c_str(), mPropDef->mName.c_str()), targetSrc);
  4222. }
  4223. }
  4224. bool isBaseLookup = (target.mType) && (typeInstance != target.mType);
  4225. if ((isBaseLookup) && (target.mType->IsWrappableType()))
  4226. isBaseLookup = false;
  4227. if (prop->mIsStatic)
  4228. mPropTarget = BfTypedValue(typeInstance);
  4229. else if (isBaseLookup)
  4230. {
  4231. if (target.mValue.IsFake())
  4232. {
  4233. mPropTarget = BfTypedValue(target.mValue, typeInstance, target.mKind);
  4234. }
  4235. else
  4236. {
  4237. mPropTarget = mModule->Cast(targetSrc, target, typeInstance);
  4238. BF_ASSERT(mPropTarget);
  4239. }
  4240. }
  4241. else
  4242. mPropTarget = target;
  4243. if (mPropTarget.mType->IsStructPtr())
  4244. {
  4245. mPropTarget = mModule->LoadValue(mPropTarget);
  4246. mPropTarget = BfTypedValue(mPropTarget.mValue, mPropTarget.mType->GetUnderlyingType(), mPropTarget.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  4247. }
  4248. mOrigPropTarget = mPropTarget;
  4249. if (prop->mIsStatic)
  4250. mOrigPropTarget = target;
  4251. if ((flags & BfLookupFieldFlag_IsAnonymous) == 0)
  4252. {
  4253. auto autoComplete = GetAutoComplete();
  4254. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  4255. if (((autoComplete != NULL) && (autoComplete->mIsGetDefinition)) ||
  4256. ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Property)))
  4257. {
  4258. BfPropertyDef* basePropDef = mPropDef;
  4259. BfTypeInstance* baseTypeInst = typeInstance;
  4260. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  4261. resolvePassData->HandlePropertyReference(targetSrc, baseTypeInst->mTypeDef, basePropDef);
  4262. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetSrc)))
  4263. {
  4264. if (autoComplete->mIsGetDefinition)
  4265. {
  4266. //NOTE: passing 'force=true' in here causes https://github.com/beefytech/Beef/issues/1064
  4267. autoComplete->SetDefinitionLocation(basePropDef->GetRefNode());
  4268. }
  4269. autoComplete->mDefProp = basePropDef;
  4270. autoComplete->mDefType = baseTypeInst->mTypeDef;
  4271. }
  4272. }
  4273. if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)))
  4274. {
  4275. BfPropertyDef* basePropDef = mPropDef;
  4276. BfTypeInstance* baseTypeInst = typeInstance;
  4277. mModule->GetBasePropertyDef(basePropDef, baseTypeInst);
  4278. autoComplete->mResultString = ":";
  4279. autoComplete->mResultString += mModule->TypeToString(baseTypeInst);
  4280. autoComplete->mResultString += ".";
  4281. autoComplete->mResultString += basePropDef->mName;
  4282. }
  4283. }
  4284. // Check for direct auto-property access
  4285. if ((target.mType == mModule->mCurTypeInstance) && ((flags & BfLookupFieldFlag_BindOnly) == 0))
  4286. {
  4287. if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(mPropDef->mFieldDeclaration))
  4288. {
  4289. if ((typeInstance->mTypeDef->HasAutoProperty(propertyDeclaration)) && (propertyDeclaration->mVirtualSpecifier == NULL))
  4290. {
  4291. BfMethodDef* getter = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, BfCheckedKind_NotSet, mPropTarget);
  4292. BfMethodDef* setter = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, BfCheckedKind_NotSet, mPropTarget);
  4293. bool optAllowed = true;
  4294. if ((getter != NULL) && (getter->mBody != NULL))
  4295. optAllowed = false;
  4296. if ((setter != NULL) && (setter->mBody != NULL))
  4297. optAllowed = false;
  4298. if (optAllowed)
  4299. {
  4300. auto autoFieldName = typeInstance->mTypeDef->GetAutoPropertyName(propertyDeclaration);
  4301. auto result = LookupField(targetSrc, target, autoFieldName, (BfLookupFieldFlags)(BfLookupFieldFlag_IgnoreProtection | BfLookupFieldFlag_IsImplicitThis));
  4302. if (result)
  4303. {
  4304. bool needsCopy = true;
  4305. if (BfNodeIsA<BfRefTypeRef>(prop->mTypeRef))
  4306. {
  4307. // Allow full ref
  4308. }
  4309. else
  4310. {
  4311. if (setter == NULL)
  4312. {
  4313. if (((mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)) &&
  4314. (target.mType == mModule->mCurTypeInstance))
  4315. {
  4316. // Allow writing inside ctor
  4317. }
  4318. else
  4319. {
  4320. result.MakeReadOnly();
  4321. needsCopy = false;
  4322. }
  4323. }
  4324. if (result.mKind == BfTypedValueKind_Addr)
  4325. result.mKind = BfTypedValueKind_CopyOnMutateAddr;
  4326. }
  4327. mPropDef = NULL;
  4328. mPropSrc = NULL;
  4329. mOrigPropTarget = BfTypedValue();
  4330. return result;
  4331. }
  4332. }
  4333. }
  4334. }
  4335. }
  4336. SetAndRestoreValue<BfTypedValue> prevResult(mResult, target);
  4337. CheckResultForReading(mResult);
  4338. return BfTypedValue();
  4339. }
  4340. BfTypedValue BfExprEvaluator::LoadField(BfAstNode* targetSrc, BfTypedValue target, BfTypeInstance* typeInstance, BfFieldDef* fieldDef, BfLookupFieldFlags flags)
  4341. {
  4342. if (fieldDef->mIsProperty)
  4343. {
  4344. BfPropertyDef* propDef = (BfPropertyDef*)fieldDef;
  4345. return LoadProperty(targetSrc, target, typeInstance, propDef, flags, BfCheckedKind_NotSet, false);
  4346. }
  4347. bool isFailurePass = (flags & BfLookupFieldFlag_IsFailurePass) != 0;
  4348. auto fieldInstance = &typeInstance->mFieldInstances[fieldDef->mIdx];
  4349. bool isResolvingFields = typeInstance->mResolvingConstField || typeInstance->mResolvingVarField;
  4350. if (fieldDef->mIsVolatile)
  4351. mIsVolatileReference = true;
  4352. if (isFailurePass)
  4353. {
  4354. if (mModule->GetCeDbgState() == NULL)
  4355. mModule->Fail(StrFormat("'%s.%s' is inaccessible due to its protection level", mModule->TypeToString(typeInstance).c_str(), fieldDef->mName.c_str()), targetSrc);
  4356. }
  4357. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  4358. if ((resolvePassData != NULL) && (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field) && ((flags & BfLookupFieldFlag_IsAnonymous) == 0))
  4359. {
  4360. resolvePassData->HandleFieldReference(targetSrc, typeInstance->mTypeDef, fieldDef);
  4361. }
  4362. if ((!typeInstance->mTypeFailed) && (!isResolvingFields) && (typeInstance->IsIncomplete()))
  4363. {
  4364. if ((fieldInstance->mResolvedType == NULL) ||
  4365. (!fieldDef->mIsStatic))
  4366. mModule->PopulateType(typeInstance, BfPopulateType_Data);
  4367. }
  4368. if (fieldInstance->mResolvedType == NULL)
  4369. {
  4370. if (mModule->mCompiler->EnsureCeUnpaused(typeInstance))
  4371. {
  4372. BF_ASSERT((typeInstance->mTypeFailed) || (isResolvingFields));
  4373. }
  4374. return BfTypedValue();
  4375. }
  4376. if (fieldInstance->mFieldIdx == -1)
  4377. {
  4378. mModule->AssertErrorState();
  4379. return BfTypedValue();
  4380. }
  4381. if ((!fieldDef->mIsStatic) && ((flags & BfLookupFieldFlag_IsImplicitThis) != 0))
  4382. mModule->MarkUsingThis();
  4383. mResultFieldInstance = fieldInstance;
  4384. // Are we accessing a 'var' field that has not yet been resolved?
  4385. if (IsVar(fieldInstance->mResolvedType))
  4386. {
  4387. // This can happen if we have one var field referencing another var field
  4388. fieldInstance->mResolvedType = mModule->ResolveVarFieldType(typeInstance, fieldInstance, fieldDef);
  4389. if (fieldInstance->mResolvedType == NULL)
  4390. return BfTypedValue();
  4391. }
  4392. auto resolvedFieldType = fieldInstance->mResolvedType;
  4393. if (fieldInstance->mIsEnumPayloadCase)
  4394. {
  4395. resolvedFieldType = typeInstance;
  4396. }
  4397. mModule->PopulateType(resolvedFieldType, BfPopulateType_Data);
  4398. mModule->AddDependency(typeInstance, mModule->mCurTypeInstance, fieldDef->mIsConst ? BfDependencyMap::DependencyFlag_ConstValue : BfDependencyMap::DependencyFlag_ReadFields);
  4399. if (fieldInstance->mHadConstEval)
  4400. {
  4401. mModule->AddDependency(typeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ConstEvalConstField);
  4402. if ((mModule->mContext->mCurTypeState != NULL) && (mModule->mContext->mCurTypeState->mCurFieldDef != NULL))
  4403. {
  4404. // If we're initializing another const field then also set it as having const eval
  4405. auto resolvingFieldInstance = &mModule->mContext->mCurTypeState->mType->ToTypeInstance()->mFieldInstances[mModule->mContext->mCurTypeState->mCurFieldDef->mIdx];
  4406. if (resolvingFieldInstance->GetFieldDef()->mIsConst)
  4407. resolvingFieldInstance->mHadConstEval = true;
  4408. }
  4409. }
  4410. if ((flags & BfLookupFieldFlag_IsAnonymous) == 0)
  4411. {
  4412. auto autoComplete = GetAutoComplete();
  4413. if (autoComplete != NULL)
  4414. {
  4415. autoComplete->CheckFieldRef(BfNodeDynCast<BfIdentifierNode>(targetSrc), fieldInstance);
  4416. if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)))
  4417. {
  4418. autoComplete->mResultString = ":";
  4419. autoComplete->mResultString += mModule->TypeToString(fieldInstance->mResolvedType);
  4420. autoComplete->mResultString += " ";
  4421. autoComplete->mResultString += mModule->TypeToString(typeInstance);
  4422. autoComplete->mResultString += ".";
  4423. autoComplete->mResultString += fieldDef->mName;
  4424. if (fieldInstance->mConstIdx != -1)
  4425. {
  4426. String constStr = autoComplete->ConstantToString(typeInstance->mConstHolder, BfIRValue(BfIRValueFlags_Const, fieldInstance->mConstIdx));
  4427. if (!constStr.IsEmpty())
  4428. {
  4429. autoComplete->mResultString += " = ";
  4430. if (constStr.StartsWith(':'))
  4431. autoComplete->mResultString.Append(StringView(constStr, 1, constStr.mLength - 1));
  4432. else
  4433. autoComplete->mResultString += constStr;
  4434. }
  4435. }
  4436. auto fieldDecl = fieldInstance->GetFieldDef()->GetFieldDeclaration();
  4437. if ((fieldDecl != NULL) && (fieldDecl->mDocumentation != NULL))
  4438. {
  4439. String docString;
  4440. fieldDecl->mDocumentation->GetDocString(docString);
  4441. autoComplete->mResultString += "\x03";
  4442. autoComplete->mResultString += docString;
  4443. }
  4444. }
  4445. }
  4446. }
  4447. if (fieldDef->mIsStatic)
  4448. {
  4449. if ((target) && ((flags & BfLookupFieldFlag_IsImplicitThis) == 0) && (!typeInstance->mTypeDef->IsGlobalsContainer()))
  4450. {
  4451. //CS0176: Member 'Program.sVal' cannot be accessed with an instance reference; qualify it with a type name instead
  4452. mModule->Fail(StrFormat("Member '%s.%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  4453. mModule->TypeToString(typeInstance).c_str(), fieldDef->mName.c_str()), targetSrc);
  4454. }
  4455. // Target must be an implicit 'this', or an error (accessing a static with a non-static target).
  4456. // Not actually needed in either case since this is a static lookup.
  4457. mResultLocalVar = NULL;
  4458. }
  4459. bool isConst = false;
  4460. if (fieldDef->mIsConst)
  4461. {
  4462. isConst = true;
  4463. auto fieldDef = fieldInstance->GetFieldDef();
  4464. if ((resolvedFieldType->IsPointer()) && (fieldDef->mIsExtern))
  4465. isConst = false;
  4466. }
  4467. if (isConst)
  4468. {
  4469. if (fieldInstance->mIsEnumPayloadCase)
  4470. {
  4471. auto dscrType = typeInstance->GetDiscriminatorType();
  4472. mModule->mBfIRBuilder->PopulateType(typeInstance);
  4473. int tagIdx = -fieldInstance->mDataIdx - 1;
  4474. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowEnumId) != 0)
  4475. {
  4476. return BfTypedValue(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), fieldInstance->mOwner);
  4477. }
  4478. mModule->PopulateType(fieldInstance->mOwner, BfPopulateType_Data);
  4479. if (auto fieldTypeInstance = fieldInstance->mResolvedType->ToTypeInstance())
  4480. {
  4481. bool hasFields = false;
  4482. for (auto& fieldInstance : fieldTypeInstance->mFieldInstances)
  4483. {
  4484. if (!fieldInstance.mResolvedType->IsVoid())
  4485. hasFields = true;
  4486. }
  4487. if (hasFields)
  4488. mModule->FailAfter("Enum payload arguments expected", targetSrc);
  4489. }
  4490. SizedArray<BfIRValue, 3> values;
  4491. values.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(typeInstance->mBaseType)));
  4492. values.Add(mModule->GetDefaultValue(typeInstance->GetUnionInnerType()));
  4493. values.Add(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx));
  4494. return BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(typeInstance), values), typeInstance);
  4495. }
  4496. if (fieldInstance->mConstIdx == -1)
  4497. {
  4498. if ((mBfEvalExprFlags & BfEvalExprFlags_DeclType) != 0)
  4499. {
  4500. // We don't need a real value
  4501. return BfTypedValue(mModule->GetDefaultValue(resolvedFieldType), resolvedFieldType);
  4502. }
  4503. typeInstance->mModule->ResolveConstField(typeInstance, fieldInstance, fieldDef);
  4504. if (fieldInstance->mConstIdx == -1)
  4505. return BfTypedValue(mModule->GetDefaultValue(resolvedFieldType), resolvedFieldType);
  4506. }
  4507. BF_ASSERT(fieldInstance->mConstIdx != -1);
  4508. auto foreignConst = typeInstance->mConstHolder->GetConstantById(fieldInstance->mConstIdx);
  4509. auto retVal = mModule->ConstantToCurrent(foreignConst, typeInstance->mConstHolder, resolvedFieldType);
  4510. return BfTypedValue(retVal, resolvedFieldType);
  4511. }
  4512. else if (fieldDef->mIsStatic)
  4513. {
  4514. mModule->CheckStaticAccess(typeInstance);
  4515. auto retVal = mModule->ReferenceStaticField(fieldInstance);
  4516. bool isStaticCtor = (mModule->mCurMethodInstance != NULL) &&
  4517. (mModule->mCurMethodInstance->mMethodDef->IsCtorOrInit()) &&
  4518. (mModule->mCurMethodInstance->mMethodDef->mIsStatic);
  4519. if ((mModule->mCompiler->mOptions.mRuntimeChecks) && (fieldInstance->IsAppendedObject()) && (!mModule->mBfIRBuilder->mIgnoreWrites) &&
  4520. (!mModule->IsSkippingExtraResolveChecks()))
  4521. {
  4522. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  4523. auto intPtrType = mModule->CreatePointerType(intType);
  4524. auto intPtrVal = mModule->mBfIRBuilder->CreateBitCast(retVal.mValue, mModule->mBfIRBuilder->MapType(intPtrType));
  4525. auto intVal = mModule->mBfIRBuilder->CreateLoad(intPtrVal);
  4526. auto oobBlock = mModule->mBfIRBuilder->CreateBlock("oob", true);
  4527. auto contBlock = mModule->mBfIRBuilder->CreateBlock("cont", true);
  4528. auto cmpRes = mModule->mBfIRBuilder->CreateCmpEQ(intVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0));
  4529. mModule->mBfIRBuilder->CreateCondBr(cmpRes, oobBlock, contBlock);
  4530. mModule->mBfIRBuilder->SetInsertPoint(oobBlock);
  4531. auto internalType = mModule->ResolveTypeDef(mModule->mCompiler->mInternalTypeDef);
  4532. auto oobFunc = mModule->GetMethodByName(internalType->ToTypeInstance(), "ThrowObjectNotInitialized");
  4533. if (oobFunc.mFunc)
  4534. {
  4535. if (mModule->mIsComptimeModule)
  4536. mModule->mCompiler->mCeMachine->QueueMethod(oobFunc.mMethodInstance, oobFunc.mFunc);
  4537. SizedArray<BfIRValue, 1> args;
  4538. args.push_back(mModule->GetConstValue(0));
  4539. mModule->mBfIRBuilder->CreateCall(oobFunc.mFunc, args);
  4540. mModule->mBfIRBuilder->CreateUnreachable();
  4541. }
  4542. else
  4543. {
  4544. mModule->Fail("System.Internal class must contain method 'ThrowObjectNotInitialized'", fieldDef->GetRefNode());
  4545. }
  4546. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  4547. }
  4548. if ((fieldDef->mIsReadOnly) && (!isStaticCtor))
  4549. {
  4550. if (retVal.IsAddr())
  4551. retVal.mKind = BfTypedValueKind_ReadOnlyAddr;
  4552. }
  4553. else
  4554. mIsHeapReference = true;
  4555. return retVal;
  4556. }
  4557. else if (!target)
  4558. {
  4559. if (((mBfEvalExprFlags & BfEvalExprFlags_NameOf) == 0) && (mModule->PreFail()))
  4560. {
  4561. if ((flags & BfLookupFieldFlag_CheckingOuter) != 0)
  4562. mModule->Fail(StrFormat("An instance reference is required to reference non-static outer field '%s.%s'", mModule->TypeToString(typeInstance).c_str(), fieldDef->mName.c_str()),
  4563. targetSrc);
  4564. else if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_CtorCalcAppend))
  4565. {
  4566. if ((mBfEvalExprFlags & BfEvalExprFlags_DeclType) == 0)
  4567. mModule->Fail(StrFormat("Cannot reference field '%s' before append allocations", fieldDef->mName.c_str()), targetSrc);
  4568. }
  4569. else
  4570. mModule->Fail(StrFormat("Cannot reference non-static field '%s' from a static method", fieldDef->mName.c_str()), targetSrc);
  4571. }
  4572. return mModule->GetDefaultTypedValue(resolvedFieldType, false, BfDefaultValueKind_Addr);
  4573. }
  4574. if (resolvedFieldType->IsValuelessType())
  4575. {
  4576. return BfTypedValue(BfIRValue::sValueless, resolvedFieldType, true);
  4577. }
  4578. if ((mResultLocalVar != NULL) && (fieldInstance->mMergedDataIdx != -1))
  4579. {
  4580. if (mResultLocalVarFieldCount != 1)
  4581. {
  4582. fieldInstance->GetDataRange(mResultLocalVarField, mResultLocalVarFieldCount);
  4583. mResultLocalVarRefNode = targetSrc;
  4584. }
  4585. }
  4586. if ((typeInstance->IsIncomplete()) && (!typeInstance->mNeedsMethodProcessing))
  4587. {
  4588. BF_ASSERT(typeInstance->mTypeFailed || (mModule->mCurMethodState == NULL) || (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCompiler->IsAutocomplete()));
  4589. return mModule->GetDefaultTypedValue(resolvedFieldType);
  4590. }
  4591. bool isTemporary = target.IsTempAddr();
  4592. bool wantsLoadValue = false;
  4593. bool wantsReadOnly = false;
  4594. if ((fieldDef->mIsReadOnly) && (mModule->mCurMethodInstance != NULL) && ((!mModule->mCurMethodInstance->mMethodDef->IsCtorOrInit()) || (!target.IsThis())))
  4595. wantsReadOnly = true;
  4596. bool isComposite = target.mType->IsComposite();
  4597. if ((isComposite) && (!target.mType->IsTypedPrimitive()) && (!target.IsAddr()))
  4598. isTemporary = true;
  4599. if ((isComposite) && (!target.IsAddr()))
  4600. wantsLoadValue = true;
  4601. if ((target.mType->IsWrappableType()) && (!target.mType->IsPointer()))
  4602. {
  4603. BfTypeInstance* primStructType = mModule->GetWrappedStructType(target.mType);
  4604. BfIRValue allocaInst = mModule->CreateAlloca(primStructType, true, "tmpStruct");
  4605. BfIRValue elementAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1);
  4606. mModule->mBfIRBuilder->CreateStore(target.mValue, elementAddr);
  4607. target = BfTypedValue(allocaInst, primStructType, true);
  4608. }
  4609. BfTypedValue targetValue;
  4610. if ((target.mType != typeInstance) && (!target.IsSplat()))
  4611. {
  4612. if ((!isComposite) || (target.IsAddr()))
  4613. targetValue = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(typeInstance)), typeInstance);
  4614. else
  4615. {
  4616. BfIRValue curVal = target.mValue;
  4617. auto baseCheckType = target.mType->ToTypeInstance();
  4618. while (baseCheckType != typeInstance)
  4619. {
  4620. curVal = mModule->mBfIRBuilder->CreateExtractValue(curVal, 0);
  4621. baseCheckType = baseCheckType->mBaseType;
  4622. }
  4623. targetValue = BfTypedValue(curVal, typeInstance);
  4624. }
  4625. }
  4626. else
  4627. targetValue = target;
  4628. bool doAccessCheck = true;
  4629. if ((flags & BfLookupFieldFlag_BindOnly) != 0)
  4630. doAccessCheck = false;
  4631. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  4632. doAccessCheck = false;
  4633. if (target.IsThis())
  4634. {
  4635. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  4636. doAccessCheck = false;
  4637. }
  4638. if (doAccessCheck)
  4639. mModule->EmitObjectAccessCheck(target);
  4640. if (fieldInstance->mDataIdx < 0)
  4641. {
  4642. BF_ASSERT(typeInstance->mTypeFailed);
  4643. return mModule->GetDefaultTypedValue(resolvedFieldType);
  4644. }
  4645. BfTypedValue retVal;
  4646. if (target.IsSplat())
  4647. {
  4648. retVal = mModule->ExtractValue(targetValue, fieldInstance, fieldInstance->mDataIdx);
  4649. }
  4650. else if ((target.mType->IsStruct()) && (!target.IsAddr()))
  4651. {
  4652. mModule->mBfIRBuilder->PopulateType(targetValue.mType);
  4653. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateExtractValue(targetValue.mValue, fieldInstance->mDataIdx/*, fieldDef->mName*/),
  4654. resolvedFieldType);
  4655. }
  4656. else
  4657. {
  4658. mModule->mBfIRBuilder->PopulateType(typeInstance);
  4659. if ((targetValue.IsAddr()) && (!typeInstance->IsValueType()))
  4660. targetValue = mModule->LoadValue(targetValue);
  4661. if (fieldInstance->IsAppendedObject())
  4662. {
  4663. auto elemPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(targetValue.mValue, 0, fieldInstance->mDataIdx);
  4664. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(elemPtr, mModule->mBfIRBuilder->MapType(resolvedFieldType)), resolvedFieldType);
  4665. }
  4666. else
  4667. {
  4668. retVal = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(targetValue.mValue, 0, fieldInstance->mDataIdx/*, fieldDef->mName*/),
  4669. resolvedFieldType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  4670. }
  4671. }
  4672. if (!retVal.IsSplat())
  4673. {
  4674. if (typeInstance->mIsUnion)
  4675. {
  4676. BfIRType llvmPtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(resolvedFieldType));
  4677. retVal.mValue = mModule->mBfIRBuilder->CreateBitCast(retVal.mValue, llvmPtrType);
  4678. }
  4679. }
  4680. if ((fieldDef->mIsVolatile) && (retVal.IsAddr()))
  4681. retVal.mKind = BfTypedValueKind_VolatileAddr;
  4682. if (wantsLoadValue)
  4683. retVal = mModule->LoadValue(retVal, NULL, mIsVolatileReference);
  4684. else
  4685. {
  4686. if ((wantsReadOnly) && (retVal.IsAddr()) && (!retVal.IsReadOnly()))
  4687. retVal.mKind = BfTypedValueKind_ReadOnlyAddr;
  4688. else if ((target.IsCopyOnMutate()) && (retVal.IsAddr()))
  4689. retVal.mKind = BfTypedValueKind_CopyOnMutateAddr_Derived;
  4690. mIsHeapReference = true;
  4691. }
  4692. if (isTemporary)
  4693. {
  4694. if (retVal.IsAddr())
  4695. retVal.mKind = BfTypedValueKind_TempAddr;
  4696. }
  4697. return retVal;
  4698. }
  4699. BfTypedValue BfExprEvaluator::LookupField(BfAstNode* targetSrc, BfTypedValue target, const StringImpl& fieldName, BfLookupFieldFlags flags)
  4700. {
  4701. if ((target.mType != NULL && (target.mType->IsGenericParam())))
  4702. {
  4703. auto genericParamType = (BfGenericParamType*)target.mType;
  4704. auto genericParamInst = mModule->GetGenericParamInstance(genericParamType);
  4705. if (target.mValue)
  4706. {
  4707. for (auto iface : genericParamInst->mInterfaceConstraints)
  4708. {
  4709. auto result = LookupField(targetSrc, BfTypedValue(target.mValue, iface), fieldName, flags);
  4710. if ((result) || (mPropDef != NULL))
  4711. {
  4712. return result;
  4713. }
  4714. }
  4715. }
  4716. bool isUnspecializedSection = false;
  4717. if (genericParamType->mGenericParamKind == BfGenericParamKind_Method)
  4718. isUnspecializedSection = (mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized);
  4719. else
  4720. isUnspecializedSection = (mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->IsUnspecializedType());
  4721. if (isUnspecializedSection)
  4722. {
  4723. auto origTarget = target;
  4724. if (genericParamInst->mTypeConstraint != NULL)
  4725. {
  4726. target.mType = genericParamInst->mTypeConstraint;
  4727. }
  4728. else
  4729. target.mType = mModule->mContext->mBfObjectType;
  4730. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  4731. {
  4732. target.mType = mModule->GetPrimitiveType(BfTypeCode_Var);
  4733. }
  4734. if (origTarget.mType->IsTypeGenericParam())
  4735. {
  4736. // Check for extern constraint in method generic params
  4737. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  4738. {
  4739. for (auto genericParam : mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams)
  4740. {
  4741. if (genericParam->mExternType == origTarget.mType)
  4742. {
  4743. if (genericParam->mTypeConstraint != NULL)
  4744. {
  4745. target.mType = genericParam->mTypeConstraint;
  4746. break;
  4747. }
  4748. }
  4749. }
  4750. }
  4751. }
  4752. if (target.mType->IsWrappableType())
  4753. target.mType = mModule->GetWrappedStructType(target.mType);
  4754. }
  4755. else
  4756. {
  4757. if ((genericParamInst->mGenericParamFlags & BfGenericParamFlag_Var) != 0)
  4758. {
  4759. //target.mType = mModule->ResolveGenericType(mResult.mType);
  4760. }
  4761. else if (genericParamInst->mTypeConstraint != NULL)
  4762. {
  4763. target = mModule->Cast(targetSrc, target, genericParamInst->mTypeConstraint);
  4764. BF_ASSERT(target);
  4765. }
  4766. else
  4767. {
  4768. // This shouldn't occur - this would infer that we are accessing a member of Object or something...
  4769. //target.mType = mModule->ResolveGenericType(mResult.mType);
  4770. }
  4771. }
  4772. }
  4773. if ((target.mType != NULL) && (IsVar(target.mType, (flags & BfLookupFieldFlag_BindOnly) != 0)))
  4774. return BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  4775. BfTypeInstance* startCheckType = mModule->mCurTypeInstance;
  4776. mPropDef = NULL;
  4777. mPropDefBypassVirtual = false;
  4778. if (target)
  4779. {
  4780. if ((!target.mType->IsValueType()) && (target.IsAddr()))
  4781. target = mModule->LoadValue(target);
  4782. if (target.mType->IsPrimitiveType())
  4783. {
  4784. auto primType = (BfPrimitiveType*)target.mType;
  4785. startCheckType = mModule->GetPrimitiveStructType(primType->mTypeDef->mTypeCode);
  4786. }
  4787. else
  4788. {
  4789. startCheckType = target.mType->ToTypeInstance();
  4790. if ((startCheckType == NULL) && (target.mType->IsPointer()))
  4791. {
  4792. startCheckType = ((BfPointerType*)target.mType)->mElementType->ToTypeInstance();
  4793. if ((startCheckType != NULL) && (!startCheckType->IsValueType()))
  4794. return BfTypedValue();
  4795. }
  4796. }
  4797. //BF_ASSERT(startCheckType != NULL);
  4798. }
  4799. else if (target.mType != NULL)
  4800. {
  4801. startCheckType = target.mType->ToTypeInstance();
  4802. }
  4803. if ((startCheckType != NULL) && (startCheckType->mBaseType == NULL))
  4804. {
  4805. if (startCheckType->mDefineState == BfTypeDefineState_ResolvingBaseType)
  4806. {
  4807. // Fixes cases where we have something like 'Base[Value]' as a base typeref
  4808. return BfTypedValue();
  4809. }
  4810. mModule->PopulateType(startCheckType, BfPopulateType_BaseType);
  4811. }
  4812. String findName;
  4813. int varSkipCount = 0;
  4814. if (fieldName.StartsWith('@'))
  4815. {
  4816. findName = fieldName;
  4817. while (findName.StartsWith('@'))
  4818. {
  4819. findName.Remove(0);
  4820. varSkipCount++;
  4821. }
  4822. }
  4823. else
  4824. findName.Reference(fieldName);
  4825. auto activeTypeDef = mModule->GetActiveTypeDef();
  4826. for (int pass = 0; pass < 2; pass++)
  4827. {
  4828. auto curCheckType = startCheckType;
  4829. bool isFailurePass = pass == 1;
  4830. if (isFailurePass)
  4831. flags = (BfLookupFieldFlags)(flags | BfLookupFieldFlag_IsFailurePass);
  4832. bool isBaseLookup = false;
  4833. while (curCheckType != NULL)
  4834. {
  4835. ///
  4836. {
  4837. bool isPopulatingType = false;
  4838. auto checkTypeState = mModule->mContext->mCurTypeState;
  4839. while (checkTypeState != NULL)
  4840. {
  4841. if (curCheckType == checkTypeState->mType)
  4842. {
  4843. isPopulatingType = true;
  4844. if (checkTypeState->mResolveKind == BfTypeState::ResolveKind_Attributes)
  4845. {
  4846. // Don't allow lookups yet
  4847. return BfTypedValue();
  4848. }
  4849. }
  4850. checkTypeState = checkTypeState->mPrevState;
  4851. }
  4852. if ((!isPopulatingType) && (curCheckType->mDefineState < Beefy::BfTypeDefineState_Defined))
  4853. {
  4854. // We MAY have emitted fields so we need to do this
  4855. mModule->mContext->mUnreifiedModule->PopulateType(curCheckType, Beefy::BfPopulateType_Interfaces_All);
  4856. }
  4857. }
  4858. curCheckType->mTypeDef->PopulateMemberSets();
  4859. BfFieldDef* nextField = NULL;
  4860. BfMemberSetEntry* entry;
  4861. if (curCheckType->mTypeDef->mFieldSet.TryGetWith(findName, &entry))
  4862. nextField = (BfFieldDef*)entry->mMemberDef;
  4863. if (nextField != NULL)
  4864. varSkipCount -= nextField->mNamePrefixCount;
  4865. while ((varSkipCount > 0) && (nextField != NULL))
  4866. {
  4867. nextField = nextField->mNextWithSameName;
  4868. varSkipCount--;
  4869. }
  4870. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  4871. if (target)
  4872. {
  4873. if ((flags & (BfLookupFieldFlag_IsImplicitThis | BfLookupFieldFlag_BaseLookup)) != 0)
  4874. {
  4875. // Not an "instance lookup"
  4876. }
  4877. else
  4878. {
  4879. protectionCheckFlags = (BfProtectionCheckFlags)(protectionCheckFlags | BfProtectionCheckFlag_InstanceLookup);
  4880. }
  4881. }
  4882. BfFieldDef* matchedField = NULL;
  4883. while (nextField != NULL)
  4884. {
  4885. if ((flags & BfLookupFieldFlag_BindOnly) != 0)
  4886. break;
  4887. auto field = nextField;
  4888. nextField = nextField->mNextWithSameName;
  4889. auto checkProtection = field->mProtection;
  4890. if (checkProtection == BfProtection_Hidden)
  4891. {
  4892. // Allow acessing hidden fields
  4893. checkProtection = BfProtection_Private;
  4894. }
  4895. if (((flags & BfLookupFieldFlag_IgnoreProtection) == 0) && (!isFailurePass) &&
  4896. (!mModule->CheckProtection(protectionCheckFlags, curCheckType, field->mDeclaringType->mProject, checkProtection, startCheckType)))
  4897. {
  4898. continue;
  4899. }
  4900. bool isResolvingFields = curCheckType->mResolvingConstField || curCheckType->mResolvingVarField;
  4901. if (curCheckType->mFieldInstances.IsEmpty())
  4902. {
  4903. mModule->PopulateType(curCheckType, BfPopulateType_Data);
  4904. }
  4905. if (field->mIdx >= (int)curCheckType->mFieldInstances.size())
  4906. {
  4907. if (mModule->mCompiler->EnsureCeUnpaused(curCheckType))
  4908. {
  4909. BF_DBG_FATAL("OOB in DoLookupField");
  4910. }
  4911. return mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  4912. }
  4913. BF_ASSERT(field->mIdx < (int)curCheckType->mFieldInstances.size());
  4914. auto fieldInstance = &curCheckType->mFieldInstances[field->mIdx];
  4915. if (!fieldInstance->mFieldIncluded)
  4916. continue;
  4917. if (curCheckType->IsUnspecializedType())
  4918. {
  4919. // The check for non-unspecialized types is already handled in mFieldIncluded
  4920. if (!curCheckType->IsTypeMemberIncluded(field->mDeclaringType, activeTypeDef, mModule))
  4921. continue;
  4922. }
  4923. if (!mModule->IsInSpecializedSection())
  4924. {
  4925. if (!curCheckType->IsTypeMemberAccessible(field->mDeclaringType, activeTypeDef))
  4926. continue;
  4927. }
  4928. if (matchedField != NULL)
  4929. {
  4930. auto error = mModule->Fail(StrFormat("Ambiguous reference to field '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  4931. if (error != NULL)
  4932. {
  4933. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", matchedField->mDeclaringType->mProject->mName.c_str()), matchedField->mFieldDeclaration);
  4934. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See field declaration in project '%s'", field->mDeclaringType->mProject->mName.c_str()), field->mFieldDeclaration);
  4935. break;
  4936. }
  4937. }
  4938. matchedField = field;
  4939. }
  4940. if (matchedField != NULL)
  4941. return LoadField(targetSrc, target, curCheckType, matchedField, flags);
  4942. BfPropertyDef* nextProp = NULL;
  4943. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(fieldName, &entry))
  4944. nextProp = (BfPropertyDef*)entry->mMemberDef;
  4945. if (nextProp != NULL)
  4946. {
  4947. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  4948. bool isInlined = false;
  4949. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  4950. {
  4951. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  4952. {
  4953. isInlined = true;
  4954. mModule->mAttributeState->mUsed = true;
  4955. }
  4956. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  4957. {
  4958. checkedKind = BfCheckedKind_Checked;
  4959. mModule->mAttributeState->mUsed = true;
  4960. }
  4961. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  4962. {
  4963. checkedKind = BfCheckedKind_Unchecked;
  4964. mModule->mAttributeState->mUsed = true;
  4965. }
  4966. }
  4967. BfPropertyDef* matchedProp = NULL;
  4968. while (nextProp != NULL)
  4969. {
  4970. auto prop = nextProp;
  4971. nextProp = nextProp->mNextWithSameName;
  4972. if ((!isFailurePass) && ((mBfEvalExprFlags & BfEvalExprFlags_NameOf) == 0) && (!mModule->CheckProtection(protectionCheckFlags, curCheckType, prop->mDeclaringType->mProject, prop->mProtection, startCheckType)))
  4973. {
  4974. continue;
  4975. }
  4976. if (!prop->mMethods.IsEmpty())
  4977. {
  4978. BfMethodDef* checkMethod = prop->mMethods[0];
  4979. // Properties with explicit interfaces or marked as overrides can only be called indirectly
  4980. if ((checkMethod->mExplicitInterface != NULL) || (checkMethod->mIsOverride))
  4981. continue;
  4982. }
  4983. if ((!target.IsStatic()) || (prop->mIsStatic) || ((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0))
  4984. {
  4985. if (!mModule->IsInSpecializedSection())
  4986. {
  4987. if ((!curCheckType->IsTypeMemberIncluded(prop->mDeclaringType, activeTypeDef, mModule)) ||
  4988. (!curCheckType->IsTypeMemberAccessible(prop->mDeclaringType, mModule->GetVisibleProjectSet())))
  4989. continue;
  4990. }
  4991. if (matchedProp != NULL)
  4992. {
  4993. if (mModule->PreFail())
  4994. {
  4995. auto error = mModule->Fail(StrFormat("Ambiguous reference to property '%s.%s'", mModule->TypeToString(curCheckType).c_str(), fieldName.c_str()), targetSrc);
  4996. if (error != NULL)
  4997. {
  4998. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", matchedProp->mDeclaringType->mProject->mName.c_str()), matchedProp->mFieldDeclaration);
  4999. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See property declaration in project '%s'", prop->mDeclaringType->mProject->mName.c_str()), prop->mFieldDeclaration);
  5000. break;
  5001. }
  5002. }
  5003. }
  5004. matchedProp = prop;
  5005. }
  5006. }
  5007. if (matchedProp != NULL)
  5008. return LoadProperty(targetSrc, target, curCheckType, matchedProp, flags, checkedKind, isInlined);
  5009. }
  5010. if (curCheckType->mTypeDef->mHasUsingFields)
  5011. mModule->PopulateUsingFieldData(curCheckType);
  5012. ///
  5013. {
  5014. Array<SizedArray<BfUsingFieldData::MemberRef, 1>*> foundLists;
  5015. auto _CheckUsingData = [&](BfUsingFieldData* usingData)
  5016. {
  5017. BfUsingFieldData::Entry* entry = NULL;
  5018. if (!usingData->mEntries.TryGetValue(findName, &entry))
  5019. return;
  5020. for (int listIdx = 0; listIdx < entry->mLookups.mSize; listIdx++)
  5021. {
  5022. bool passesProtection = true;
  5023. auto& entryList = entry->mLookups[listIdx];
  5024. for (int entryIdx = 0; entryIdx < entryList.mSize; entryIdx++)
  5025. {
  5026. auto& entry = entryList[entryIdx];
  5027. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  5028. if (!mModule->CheckProtection(protectionCheckFlags, entry.mTypeInstance, entry.GetDeclaringType(mModule)->mProject,
  5029. (entryIdx < entryList.mSize - 1) ? entry.GetUsingProtection() : entry.GetProtection(), curCheckType))
  5030. {
  5031. passesProtection = false;
  5032. break;
  5033. }
  5034. }
  5035. if (!passesProtection)
  5036. continue;
  5037. if (foundLists.mSize == 0)
  5038. {
  5039. foundLists.Add(&entryList);
  5040. }
  5041. else
  5042. {
  5043. if (entryList.mSize < foundLists[0]->mSize)
  5044. {
  5045. // New is shorter
  5046. foundLists.Clear();
  5047. foundLists.Add(&entryList);
  5048. }
  5049. else if (entryList.mSize > foundLists[0]->mSize)
  5050. {
  5051. // Ignore longer
  5052. }
  5053. else
  5054. {
  5055. foundLists.Add(&entryList);
  5056. }
  5057. }
  5058. }
  5059. };
  5060. if ((curCheckType->mTypeInfoEx != NULL) && (curCheckType->mTypeInfoEx->mUsingFieldData != NULL))
  5061. _CheckUsingData(curCheckType->mTypeInfoEx->mUsingFieldData);
  5062. if (!foundLists.IsEmpty())
  5063. {
  5064. auto foundList = foundLists[0];
  5065. if (foundLists.mSize > 1)
  5066. {
  5067. BfError* error = mModule->Fail("Ambiguous 'using' field reference", targetSrc);
  5068. if (error != NULL)
  5069. {
  5070. for (auto checkList : foundLists)
  5071. {
  5072. String errorStr = "'";
  5073. for (int entryIdx = 0; entryIdx < checkList->mSize; entryIdx++)
  5074. {
  5075. if (entryIdx == 0)
  5076. errorStr += (*checkList)[entryIdx].GetFullName(mModule);
  5077. else
  5078. {
  5079. errorStr += ".";
  5080. errorStr += (*checkList)[entryIdx].GetName(mModule);
  5081. }
  5082. }
  5083. errorStr += "' is a candidate";
  5084. mModule->mCompiler->mPassInstance->MoreInfo(errorStr, (*checkList)[0].GetRefNode(mModule));
  5085. }
  5086. }
  5087. }
  5088. BfTypedValue curResult = target;
  5089. for (int entryIdx = 0; entryIdx < foundList->mSize; entryIdx++)
  5090. {
  5091. if ((entryIdx == 0) && (foundList->back().IsStatic()))
  5092. entryIdx = (int)foundList->mSize - 1;
  5093. auto& entry = (*foundList)[entryIdx];
  5094. if (mPropDef != NULL)
  5095. {
  5096. SetAndRestoreValue<BfTypedValue> prevResult(mResult, BfTypedValue());
  5097. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_Friend);
  5098. curResult = GetResult();
  5099. if (!curResult)
  5100. return curResult;
  5101. }
  5102. auto useFlags = flags;
  5103. if (entryIdx < foundList->mSize - 1)
  5104. useFlags = (BfLookupFieldFlags)(flags | BfLookupFieldFlag_IsAnonymous);
  5105. if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Field)
  5106. {
  5107. curResult = LoadField(targetSrc, curResult, entry.mTypeInstance, entry.mTypeInstance->mTypeDef->mFields[entry.mIdx], useFlags);
  5108. }
  5109. else if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Property)
  5110. {
  5111. curResult = LoadProperty(targetSrc, curResult, entry.mTypeInstance, entry.mTypeInstance->mTypeDef->mProperties[entry.mIdx], useFlags, BfCheckedKind_NotSet, false);
  5112. }
  5113. else if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Local)
  5114. {
  5115. auto localDef = mModule->mCurMethodState->mLocals[entry.mIdx];
  5116. curResult = LoadLocal(localDef);
  5117. }
  5118. if ((!curResult) && (mPropDef == NULL))
  5119. return curResult;
  5120. if (entryIdx == foundList->mSize - 1)
  5121. {
  5122. auto autoComplete = GetAutoComplete();
  5123. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetSrc)))
  5124. autoComplete->SetDefinitionLocation(entry.GetRefNode(mModule));
  5125. if ((autoComplete != NULL) && (autoComplete->CheckFixit(targetSrc)))
  5126. autoComplete->FixitAddFullyQualify(targetSrc, findName, *foundList);
  5127. }
  5128. }
  5129. return curResult;
  5130. }
  5131. }
  5132. isBaseLookup = true;
  5133. curCheckType = curCheckType->mBaseType;
  5134. }
  5135. }
  5136. auto outerTypeDef = mModule->GetOuterType(startCheckType);
  5137. if (outerTypeDef != NULL)
  5138. {
  5139. // Check statics in outer type
  5140. return LookupField(targetSrc, BfTypedValue(outerTypeDef), fieldName, BfLookupFieldFlag_CheckingOuter);
  5141. }
  5142. return BfTypedValue();
  5143. }
  5144. void BfExprEvaluator::ResolveArgValues(BfResolvedArgs& resolvedArgs, BfResolveArgsFlags flags)
  5145. {
  5146. static int idx = 0;
  5147. idx++;
  5148. int curIdx = idx;
  5149. if (resolvedArgs.mArguments == NULL)
  5150. return;
  5151. int argCount = (int)resolvedArgs.mArguments->size();
  5152. if ((resolvedArgs.mCommas != NULL) && (resolvedArgs.mCommas->size() != 0) && (resolvedArgs.mCommas->size() >= resolvedArgs.mArguments->size()))
  5153. {
  5154. //mModule->FailAfter("Expression expected", resolvedArgs.mCommas->back());
  5155. argCount++;
  5156. }
  5157. BfAutoComplete* autoComplete = GetAutoComplete();
  5158. bool hadIgnoredFixits = false;
  5159. if (autoComplete != NULL)
  5160. {
  5161. hadIgnoredFixits = autoComplete->mIgnoreFixits;
  5162. if (flags & BfResolveArgsFlag_DeferFixits)
  5163. autoComplete->mIgnoreFixits = true;
  5164. }
  5165. int deferredArgIdx = 0;
  5166. SizedArray<BfExpression*, 8> deferredArgs;
  5167. int argIdx = 0;
  5168. while (true)
  5169. {
  5170. //printf("Args: %p %p %d\n", resolvedArgs.mArguments, resolvedArgs.mArguments->mVals, resolvedArgs.mArguments->mSize);
  5171. BfExpression* argExpr = NULL;
  5172. bool isDeferredArg = false;
  5173. int curArgIdx = -1;
  5174. if (deferredArgIdx < deferredArgs.size())
  5175. {
  5176. argExpr = deferredArgs[deferredArgIdx++];
  5177. isDeferredArg = true;
  5178. }
  5179. else if (argIdx >= argCount)
  5180. {
  5181. break;
  5182. }
  5183. else
  5184. {
  5185. curArgIdx = argIdx++;
  5186. if (curArgIdx < resolvedArgs.mArguments->size())
  5187. argExpr = (*resolvedArgs.mArguments)[curArgIdx];
  5188. }
  5189. if (argExpr == NULL)
  5190. {
  5191. if (curArgIdx == 0)
  5192. {
  5193. if (resolvedArgs.mOpenToken != NULL)
  5194. mModule->FailAfter("Expression expected", resolvedArgs.mOpenToken);
  5195. }
  5196. else if (resolvedArgs.mCommas != NULL)
  5197. mModule->FailAfter("Expression expected", (*resolvedArgs.mCommas)[curArgIdx - 1]);
  5198. }
  5199. if (auto typedValueExpr = BfNodeDynCast<BfTypedValueExpression>(argExpr))
  5200. {
  5201. BfResolvedArg resolvedArg;
  5202. resolvedArg.mTypedValue = typedValueExpr->mTypedValue;
  5203. resolvedArg.mExpression = typedValueExpr->mRefNode;
  5204. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  5205. continue;
  5206. }
  5207. BfResolvedArg resolvedArg;
  5208. if (isDeferredArg)
  5209. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_StringInterpolateArg);
  5210. BfExprEvaluator exprEvaluator(mModule);
  5211. exprEvaluator.mResolveGenericParam = (flags & BfResolveArgsFlag_AllowUnresolvedTypes) == 0;
  5212. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr |
  5213. (mBfEvalExprFlags & (BfEvalExprFlags_Comptime)));
  5214. bool handled = false;
  5215. bool evaluated = false;
  5216. if (auto namedExpression = BfNodeDynCastExact<BfNamedExpression>(argExpr))
  5217. {
  5218. resolvedArg.mNameNode = namedExpression->mNameNode;
  5219. argExpr = namedExpression->mExpression;
  5220. }
  5221. if (auto interpolateExpr = BfNodeDynCastExact<BfStringInterpolationExpression>(argExpr))
  5222. {
  5223. if ((interpolateExpr->mAllocNode == NULL) || ((flags & BfResolveArgsFlag_InsideStringInterpolationAlloc) != 0))
  5224. {
  5225. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_StringInterpolateFormat);
  5226. for (auto innerExpr : interpolateExpr->mExpressions)
  5227. deferredArgs.Add(innerExpr);
  5228. }
  5229. }
  5230. if (auto unaryOpExpr = BfNodeDynCastExact<BfUnaryOperatorExpression>(argExpr))
  5231. {
  5232. if ((unaryOpExpr->mOp == BfUnaryOp_Cascade) && ((flags & BfResolveArgsFlag_FromIndexer) == 0))
  5233. {
  5234. if ((mBfEvalExprFlags & BfEvalExprFlags_InCascade) != 0)
  5235. mModule->Fail("Cascade already specified on call target", unaryOpExpr->mOpToken);
  5236. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_Cascade);
  5237. argExpr = unaryOpExpr->mExpression;
  5238. }
  5239. }
  5240. bool deferParamEval = false;
  5241. if ((flags & BfResolveArgsFlag_DeferParamEval) != 0)
  5242. {
  5243. if (argExpr != NULL)
  5244. {
  5245. BfDeferEvalChecker deferEvalChecker;
  5246. deferEvalChecker.mDeferDelegateBind = false;
  5247. deferEvalChecker.Check(argExpr);
  5248. deferParamEval = deferEvalChecker.mNeedsDeferEval;
  5249. }
  5250. }
  5251. if (deferParamEval)
  5252. {
  5253. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredEval);
  5254. handled = true;
  5255. }
  5256. else if (auto delegateBindExpression = BfNodeDynCast<BfDelegateBindExpression>(argExpr))
  5257. {
  5258. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DelegateBindAttempt);
  5259. handled = true;
  5260. }
  5261. else if (auto lambdaBindExpression = BfNodeDynCast<BfLambdaBindExpression>(argExpr))
  5262. {
  5263. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_LambdaBindAttempt);
  5264. handled = true;
  5265. }
  5266. else if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(argExpr))
  5267. {
  5268. if (memberRef->mTarget == NULL)
  5269. {
  5270. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  5271. handled = true;
  5272. }
  5273. }
  5274. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(argExpr))
  5275. {
  5276. if (auto memberRef = BfNodeDynCast<BfMemberReferenceExpression>(invokeExpr->mTarget))
  5277. {
  5278. if (memberRef->mTarget == NULL)
  5279. {
  5280. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UnqualifiedDotAttempt);
  5281. handled = true;
  5282. }
  5283. }
  5284. }
  5285. else if (auto defaultExpr = BfNodeDynCast<BfDefaultExpression>(argExpr))
  5286. {
  5287. if (defaultExpr->mTypeRef == NULL)
  5288. {
  5289. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UntypedDefault);
  5290. handled = true;
  5291. }
  5292. }
  5293. else if (auto varDeclExpr = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  5294. {
  5295. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  5296. handled = true;
  5297. }
  5298. else if (auto unaryExpr = BfNodeDynCast<BfUnaryOperatorExpression>(argExpr))
  5299. {
  5300. if (unaryExpr->mOp == BfUnaryOp_Params)
  5301. {
  5302. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ParamsExpr);
  5303. }
  5304. }
  5305. else if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(argExpr))
  5306. {
  5307. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_UninitializedExpr);
  5308. handled = true;
  5309. }
  5310. /*else if (auto castExpr = BfNodeDynCast<BfCastExpression>(argExpr))
  5311. {
  5312. if (auto namedTypeRef = BfNodeDynCastExact<BfNamedTypeReference>(castExpr->mTypeRef))
  5313. {
  5314. if (namedTypeRef->ToString() == "ExpectedType")
  5315. {
  5316. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_ExpectedTypeCast);
  5317. handled = true;
  5318. }
  5319. }
  5320. }*/
  5321. if ((argExpr != NULL) && (!handled))
  5322. {
  5323. bool deferParamValues = (flags & BfResolveArgsFlag_DeferParamValues) != 0;
  5324. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || deferParamValues);
  5325. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  5326. if (deferParamValues)
  5327. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_DeferredValue);
  5328. if (!evaluated)
  5329. {
  5330. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_AllowParamsExpr);
  5331. if ((resolvedArg.mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  5332. exprEvaluator.mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator.mBfEvalExprFlags | BfEvalExprFlags_StringInterpolateFormat);
  5333. exprEvaluator.Evaluate(argExpr, false, false, true);
  5334. }
  5335. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  5336. {
  5337. auto localVar = exprEvaluator.mResultLocalVar;
  5338. int fieldIdx = mResultLocalVarField - 1;
  5339. auto methodState = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  5340. if (localVar->mCompositeCount >= 0)
  5341. {
  5342. if ((resolvedArg.mArgFlags & BfArgFlag_ParamsExpr) == 0)
  5343. mModule->Warn(0, "'params' token expected", argExpr);
  5344. for (int compositeIdx = 0; compositeIdx < localVar->mCompositeCount; compositeIdx++)
  5345. {
  5346. BfResolvedArg compositeResolvedArg;
  5347. auto compositeLocalVar = methodState->mLocals[localVar->mLocalVarIdx + compositeIdx + 1];
  5348. auto argValue = exprEvaluator.LoadLocal(compositeLocalVar, true);
  5349. if (argValue)
  5350. {
  5351. if (!argValue.mType->IsStruct())
  5352. argValue = mModule->LoadValue(argValue, NULL, exprEvaluator.mIsVolatileReference);
  5353. }
  5354. resolvedArg.mTypedValue = argValue;
  5355. resolvedArg.mExpression = argExpr;
  5356. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_FromParamComposite);
  5357. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  5358. }
  5359. continue;
  5360. }
  5361. }
  5362. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  5363. auto argValue = exprEvaluator.mResult;
  5364. if (argValue)
  5365. {
  5366. mModule->mBfIRBuilder->PopulateType(argValue.mType);
  5367. resolvedArg.mResolvedType = argValue.mType;
  5368. if (resolvedArg.mResolvedType->IsRef())
  5369. argValue.mKind = BfTypedValueKind_Value;
  5370. if (exprEvaluator.mIsVolatileReference)
  5371. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_Volatile);
  5372. }
  5373. resolvedArg.mUncastedTypedValue = argValue;
  5374. resolvedArg.mTypedValue = argValue;
  5375. if (deferParamValues)
  5376. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  5377. }
  5378. resolvedArg.mExpression = argExpr;
  5379. resolvedArgs.mResolvedArgs.push_back(resolvedArg);
  5380. }
  5381. if (autoComplete != NULL)
  5382. autoComplete->mIgnoreFixits = hadIgnoredFixits;
  5383. }
  5384. void BfExprEvaluator::PerformCallChecks(BfMethodInstance* methodInstance, BfAstNode* targetSrc)
  5385. {
  5386. BfCustomAttributes* customAttributes = methodInstance->GetCustomAttributes();
  5387. if (customAttributes != NULL)
  5388. mModule->CheckErrorAttributes(methodInstance->GetOwner(), methodInstance, customAttributes, targetSrc);
  5389. }
  5390. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, BfMethodInstance* methodInstance, BfIRValue func, bool bypassVirtual, SizedArrayImpl<BfIRValue>& irArgs, BfTypedValue* sret, BfCreateCallFlags callFlags, BfType* origTargetType)
  5391. {
  5392. // static int sCallIdx = 0;
  5393. // if (!mModule->mCompiler->mIsResolveOnly)
  5394. // sCallIdx++;
  5395. // int callIdx = sCallIdx;
  5396. // if (callIdx == 0x000000E8)
  5397. // {
  5398. // NOP;
  5399. // }
  5400. auto methodDef = methodInstance->mMethodDef;
  5401. BfIRValue funcCallInst = func;
  5402. auto importCallKind = methodInstance->GetImportCallKind();
  5403. if ((funcCallInst) && (importCallKind != BfImportCallKind_None))
  5404. {
  5405. if ((funcCallInst.IsFake()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  5406. {
  5407. mModule->mFuncReferences.TryGetValue(methodInstance, &funcCallInst);
  5408. }
  5409. if ((importCallKind == BfImportCallKind_GlobalVar) &&
  5410. (methodInstance->mHotMethod == NULL) &&
  5411. (mModule->mCompiler->IsHotCompile()))
  5412. {
  5413. // This may actually be a BfImportCallKind_GlobalVar_Hot, so check it...
  5414. mModule->CheckHotMethod(methodInstance, "");
  5415. importCallKind = methodInstance->GetImportCallKind();
  5416. }
  5417. if (importCallKind == BfImportCallKind_GlobalVar_Hot)
  5418. {
  5419. //TODO: Check against NULL for calling BfLoadSharedLibraries
  5420. auto checkVal = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  5421. BfIRBlock nullBlock = mModule->mBfIRBuilder->CreateBlock("importNull");
  5422. BfIRBlock doneBlock = mModule->mBfIRBuilder->CreateBlock("importLoad");
  5423. auto condVal = mModule->mBfIRBuilder->CreateIsNull(checkVal);
  5424. mModule->mBfIRBuilder->CreateCondBr(condVal, nullBlock, doneBlock);
  5425. mModule->mBfIRBuilder->AddBlock(nullBlock);
  5426. mModule->mBfIRBuilder->SetInsertPoint(nullBlock);
  5427. auto loadSharedLibsFunc = mModule->GetBuiltInFunc(BfBuiltInFuncType_LoadSharedLibraries);
  5428. mModule->mBfIRBuilder->CreateCall(loadSharedLibsFunc, SizedArray<BfIRValue, 0>());
  5429. mModule->mBfIRBuilder->CreateBr(doneBlock);
  5430. mModule->mBfIRBuilder->AddBlock(doneBlock);
  5431. mModule->mBfIRBuilder->SetInsertPoint(doneBlock);
  5432. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  5433. }
  5434. else
  5435. {
  5436. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcCallInst);
  5437. }
  5438. }
  5439. if ((methodInstance->GetOwner()->IsInstanceOf(mModule->mCompiler->mDeferredCallTypeDef)) &&
  5440. (methodInstance->mMethodDef->mName == "Cancel"))
  5441. {
  5442. if (mModule->mCurMethodState != NULL)
  5443. mModule->mCurMethodState->mCancelledDeferredCall = true;
  5444. }
  5445. if (methodDef->mIsNoReturn)
  5446. {
  5447. mModule->mCurMethodState->SetHadReturn(true);
  5448. mModule->mCurMethodState->mLeftBlockUncond = true;
  5449. mModule->MarkScopeLeft(&mModule->mCurMethodState->mHeadScope, true);
  5450. }
  5451. if (mModule->mCurTypeInstance != NULL)
  5452. {
  5453. bool isVirtual = (methodInstance->mVirtualTableIdx != -1) && (!bypassVirtual);
  5454. mModule->AddDependency(methodInstance->mMethodInstanceGroup->mOwner, mModule->mCurTypeInstance, isVirtual ? BfDependencyMap::DependencyFlag_VirtualCall : BfDependencyMap::DependencyFlag_Calls);
  5455. mModule->AddCallDependency(methodInstance, bypassVirtual);
  5456. }
  5457. if (methodInstance->GetOwner()->IsUnspecializedType())
  5458. {
  5459. BF_ASSERT((!methodInstance->mIRFunction) || (methodInstance == mModule->mCurMethodInstance) || (methodInstance->mMethodDef->mIsLocalMethod));
  5460. }
  5461. if (mFunctionBindResult != NULL)
  5462. {
  5463. BF_ASSERT(mFunctionBindResult->mMethodInstance == NULL);
  5464. mFunctionBindResult->mMethodInstance = methodInstance;
  5465. for (auto arg : irArgs)
  5466. mFunctionBindResult->mIRArgs.push_back(arg);
  5467. }
  5468. BfType* origReturnType = methodInstance->mReturnType;
  5469. /*if (origReturnType->IsSelf())
  5470. {
  5471. origReturnType = methodInstance->GetOwner();
  5472. BF_ASSERT(origReturnType->IsInterface());
  5473. }*/
  5474. BfType* returnType = origReturnType;
  5475. BfTypedValue sretVal;
  5476. auto _GetDefaultReturnValue = [&]()
  5477. {
  5478. if (methodInstance->mVirtualTableIdx == -1)
  5479. {
  5480. if (methodInstance->GetOwner()->IsInterface())
  5481. {
  5482. // We're attempting to directly invoke a non-virtual interface method, if we're return an interface then
  5483. // it is a concrete interface
  5484. if (returnType->IsInterface())
  5485. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  5486. }
  5487. }
  5488. if ((returnType->IsVar()) && (mExpectingType != NULL))
  5489. returnType = mExpectingType;
  5490. if (returnType->IsRef())
  5491. {
  5492. auto result = mModule->GetDefaultTypedValue(returnType->GetUnderlyingType(), true, BfDefaultValueKind_Addr);
  5493. if (methodDef->mIsReadOnly)
  5494. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  5495. return result;
  5496. }
  5497. else
  5498. {
  5499. auto val = mModule->GetDefaultTypedValue(returnType, true, (GetStructRetIdx(methodInstance) != -1) ? BfDefaultValueKind_Addr : BfDefaultValueKind_Value);
  5500. if (val.mKind == BfTypedValueKind_Addr)
  5501. val.mKind = BfTypedValueKind_RestrictedTempAddr;
  5502. return val;
  5503. }
  5504. };
  5505. mModule->PopulateType(origReturnType, BfPopulateType_Data);
  5506. if (GetStructRetIdx(methodInstance) != -1)
  5507. {
  5508. // We need to ensure that mReceivingValue has the correct type, otherwise it's possible that a conversion operator needs to be applied
  5509. // This happens for returning Result<T>'s with a 'T' value
  5510. if ((sret == NULL) && (mReceivingValue != NULL) && (mReceivingValue->mType == returnType))
  5511. {
  5512. sretVal = *mReceivingValue;
  5513. sret = &sretVal;
  5514. auto ptrType = mModule->CreatePointerType(returnType);
  5515. if (returnType != sret->mType)
  5516. {
  5517. sret->mValue = mModule->mBfIRBuilder->CreateBitCast(sret->mValue, mModule->mBfIRBuilder->MapType(ptrType));
  5518. sret->mType = returnType;
  5519. }
  5520. mReceivingValue = NULL;
  5521. }
  5522. if (sret == NULL)
  5523. {
  5524. sretVal = BfTypedValue(mModule->CreateAlloca(returnType), returnType, BfTypedValueKind_RestrictedTempAddr);
  5525. sret = &sretVal;
  5526. }
  5527. }
  5528. else
  5529. {
  5530. BF_ASSERT(sret == NULL);
  5531. }
  5532. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  5533. {
  5534. if ((methodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0)
  5535. {
  5536. // We need to perform call such as Compiler.Mixin and String.ConstF
  5537. }
  5538. else
  5539. return _GetDefaultReturnValue();
  5540. }
  5541. BF_ASSERT(!methodInstance->mDisallowCalling);
  5542. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mAutoComplete != NULL))
  5543. {
  5544. bool wantQuickEval = true;
  5545. if (IsComptime())
  5546. {
  5547. auto autoComplete = mModule->mCompiler->mResolvePassData->mAutoComplete;
  5548. wantQuickEval =
  5549. ((autoComplete->mResolveType != BfResolveType_Autocomplete) &&
  5550. (autoComplete->mResolveType != BfResolveType_Autocomplete_HighPri) &&
  5551. (autoComplete->mResolveType != BfResolveType_GetResultString));
  5552. for (auto& entry : mModule->mCompiler->mResolvePassData->mEmitEmbedEntries)
  5553. {
  5554. if (entry.mValue.mCursorIdx >= 0)
  5555. {
  5556. // Needed for Go To Definition in Compiler.Mixin
  5557. wantQuickEval = false;
  5558. }
  5559. }
  5560. }
  5561. if (wantQuickEval)
  5562. {
  5563. // In an autocomplete pass we may have stale method references that need to be resolved
  5564. // in the full classify pass, and in the full classify pass while just refreshing internals, we
  5565. // may have NULL funcs temporarily. We simply skip generating the method call here.
  5566. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  5567. {
  5568. if (methodInstance->mReturnType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  5569. {
  5570. if ((mExpectingType != NULL) && (mExpectingType->IsSizedArray()))
  5571. {
  5572. return BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(mExpectingType)), mExpectingType);
  5573. }
  5574. }
  5575. auto returnType = methodInstance->mReturnType;
  5576. if ((returnType->IsVar()) && (mExpectingType != NULL))
  5577. returnType = mExpectingType;
  5578. if (methodInstance->mReturnType->IsValuelessType())
  5579. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  5580. return BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(returnType)), returnType);
  5581. }
  5582. BfTypedValue result;
  5583. if (sret != NULL)
  5584. result = *sret;
  5585. else
  5586. result = _GetDefaultReturnValue();
  5587. return result;
  5588. }
  5589. }
  5590. bool forceBind = false;
  5591. if (mModule->mCompiler->mCeMachine != NULL)
  5592. {
  5593. bool doConstReturn = false;
  5594. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  5595. {
  5596. if (mFunctionBindResult != NULL)
  5597. {
  5598. forceBind = true;
  5599. }
  5600. else if ((mBfEvalExprFlags & BfEvalExprFlags_InCascade) != 0)
  5601. {
  5602. mModule->Fail("Const evaluation not allowed with cascade operator", targetSrc);
  5603. }
  5604. else if (((methodInstance->mComptimeFlags & BfComptimeFlag_OnlyFromComptime) != 0) && (!mModule->mIsComptimeModule))
  5605. {
  5606. // This either generated an error already or this is just the non-const type check pass for a comptime-only method
  5607. doConstReturn = true;
  5608. }
  5609. else if ((mBfEvalExprFlags & BfEvalExprFlags_DisallowComptime) != 0)
  5610. {
  5611. doConstReturn = true;
  5612. }
  5613. else if (((callFlags & BfCreateCallFlags_GenericParamThis) != 0) && (methodInstance->GetOwner()->IsInterface()))
  5614. {
  5615. mModule->Warn(0, "Concrete method may fail to comptime during specialization", targetSrc);
  5616. doConstReturn = true;
  5617. }
  5618. else if (methodDef->mIsVirtual)
  5619. {
  5620. // This could only really be the case for a Type, since no other 'this' could qualify as const
  5621. }
  5622. else
  5623. {
  5624. CeEvalFlags evalFlags = CeEvalFlags_None;
  5625. if ((mBfEvalExprFlags & BfEvalExprFlags_NoCeRebuildFlags) != 0)
  5626. evalFlags = (CeEvalFlags)(evalFlags | CeEvalFlags_NoRebuild);
  5627. if ((mModule->mIsComptimeModule) && (mModule->mCompiler->mCeMachine->mDebugger != NULL) && (mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  5628. {
  5629. auto ceDbgState = mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState;
  5630. if ((ceDbgState->mDbgExpressionFlags & DwEvalExpressionFlag_AllowCalls) != 0)
  5631. {
  5632. ceDbgState->mHadSideEffects = true;
  5633. //SetAndRestoreValue<CeDebugger*> prevDebugger(mModule->mCompiler->mCeMachine->mDebugger, NULL);
  5634. evalFlags = (CeEvalFlags)(evalFlags | CeEvalFlags_DbgCall);
  5635. auto result = ceDbgState->mCeContext->Call(targetSrc, mModule, methodInstance, irArgs, evalFlags, mExpectingType);
  5636. if (result)
  5637. return result;
  5638. }
  5639. else
  5640. {
  5641. ceDbgState->mBlockedSideEffects = true;
  5642. }
  5643. }
  5644. else
  5645. {
  5646. CeCallSource ceCallSource(targetSrc);
  5647. ceCallSource.mOrigCalleeType = origTargetType;
  5648. auto constRet = mModule->mCompiler->mCeMachine->Call(ceCallSource, mModule, methodInstance, irArgs, evalFlags, mExpectingType);
  5649. if (constRet)
  5650. {
  5651. auto constant = mModule->mBfIRBuilder->GetConstant(constRet.mValue);
  5652. BF_ASSERT(!constRet.mType->IsVar());
  5653. return constRet;
  5654. }
  5655. if (mModule->mCompiler->mFastFinish)
  5656. {
  5657. if ((mModule->mCurMethodInstance == NULL) || (!mModule->mCurMethodInstance->mIsAutocompleteMethod))
  5658. {
  5659. // We didn't properly resolve this so queue for a rebuild later
  5660. mModule->DeferRebuildType(mModule->mCurTypeInstance);
  5661. }
  5662. }
  5663. doConstReturn = true;
  5664. }
  5665. }
  5666. }
  5667. else if (mModule->mIsComptimeModule)
  5668. {
  5669. if (methodInstance->mIsUnspecialized)
  5670. {
  5671. doConstReturn = true;
  5672. }
  5673. else
  5674. {
  5675. mModule->mCompiler->mCeMachine->QueueMethod(methodInstance, func);
  5676. }
  5677. }
  5678. if (doConstReturn)
  5679. {
  5680. if ((returnType->IsVar()) && (mExpectingType != NULL))
  5681. returnType = mExpectingType;
  5682. if (returnType->IsRef())
  5683. {
  5684. return _GetDefaultReturnValue();
  5685. }
  5686. else
  5687. {
  5688. if (returnType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  5689. {
  5690. if ((mExpectingType != NULL) && (mExpectingType->IsUndefSizedArray()))
  5691. {
  5692. if (returnType->GetUnderlyingType() == mExpectingType->GetUnderlyingType())
  5693. return mModule->GetDefaultTypedValue(mExpectingType, true, BfDefaultValueKind_Undef);
  5694. }
  5695. }
  5696. if (methodInstance->mReturnType->IsValuelessType())
  5697. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  5698. return mModule->GetDefaultTypedValue(returnType, true, BfDefaultValueKind_Undef);
  5699. }
  5700. return _GetDefaultReturnValue();
  5701. }
  5702. }
  5703. if (!forceBind)
  5704. {
  5705. if (((!func) && (methodInstance->mIsUnspecialized)) || (mModule->mBfIRBuilder->mIgnoreWrites))
  5706. {
  5707. // We don't actually submit method calls for unspecialized methods
  5708. // - this includes all methods in unspecialized types
  5709. return _GetDefaultReturnValue();
  5710. }
  5711. }
  5712. if (methodInstance->mVirtualTableIdx != -1)
  5713. {
  5714. if ((!bypassVirtual) && (mDeferCallRef == NULL))
  5715. {
  5716. if ((methodDef->mIsOverride) && (mModule->mCurMethodInstance->mIsReified))
  5717. {
  5718. // Ensure that declaring method gets referenced
  5719. auto typeInstance = methodInstance->GetOwner();
  5720. auto& vEntry = typeInstance->mVirtualMethodTable[methodInstance->mVirtualTableIdx];
  5721. BfMethodInstance* declaringMethodInstance = vEntry.mDeclaringMethod;
  5722. if ((declaringMethodInstance->mMethodInstanceGroup->mOnDemandKind < BfMethodOnDemandKind_InWorkList) || (!declaringMethodInstance->mIsReified))
  5723. mModule->GetMethodInstance(declaringMethodInstance);
  5724. }
  5725. auto funcType = mModule->mBfIRBuilder->MapMethod(methodInstance);
  5726. auto funcPtrType1 = mModule->mBfIRBuilder->GetPointerTo(funcType);
  5727. auto funcPtrType2 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType1);
  5728. auto funcPtrType3 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType2);
  5729. auto funcPtrType4 = mModule->mBfIRBuilder->GetPointerTo(funcPtrType3);
  5730. if (methodInstance->mMethodInstanceGroup->mOwner->IsInterface())
  5731. {
  5732. if (mModule->mIsComptimeModule)
  5733. {
  5734. funcCallInst = mModule->mBfIRBuilder->Comptime_GetInterfaceFunc(irArgs[0], methodInstance->mMethodInstanceGroup->mOwner->mTypeId, methodInstance->mMethodDef->mIdx, funcPtrType1);
  5735. }
  5736. else
  5737. {
  5738. // IFace dispatch
  5739. auto ifaceTypeInst = methodInstance->mMethodInstanceGroup->mOwner;
  5740. BfIRValue slotOfs = mModule->GetInterfaceSlotNum(methodInstance->mMethodInstanceGroup->mOwner);
  5741. auto vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  5742. auto vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  5743. auto ifacePtrPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, slotOfs/*, "iface"*/);
  5744. auto ifacePtr = mModule->mBfIRBuilder->CreateLoad(ifacePtrPtr);
  5745. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(ifacePtr, methodInstance->mVirtualTableIdx/*, "vfn"*/);
  5746. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  5747. }
  5748. }
  5749. else if (mModule->mIsComptimeModule)
  5750. {
  5751. funcCallInst = mModule->mBfIRBuilder->Comptime_GetVirtualFunc(irArgs[0], methodInstance->mVirtualTableIdx, funcPtrType1);
  5752. }
  5753. else
  5754. {
  5755. mModule->HadSlotCountDependency();
  5756. // Virtual dispatch
  5757. // int vDataIdx = 0;
  5758. // vDataIdx += 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots;
  5759. BfIRValue vDataPtr;
  5760. BfIRValue vDataIdx;
  5761. if ((mModule->mCompiler->mOptions.mHasVDataExtender) && (mModule->mCompiler->IsHotCompile()))
  5762. {
  5763. auto typeInst = methodInstance->mMethodInstanceGroup->mOwner;
  5764. int extMethodIdx = (methodInstance->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) - typeInst->GetOrigSelfVTableSize();
  5765. if (extMethodIdx >= 0)
  5766. {
  5767. BF_ASSERT(mModule->mCompiler->IsHotCompile());
  5768. // We have grown outside our original virtual table, Load the new vdataPtr from the mHasVDataExtender
  5769. // vDataPtr = obj.vtable.extension.entry[curVersion]
  5770. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType4);
  5771. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr));
  5772. // The offset of the vExt is one past the base vtable. When a base class extends its virtual table, an entry
  5773. // for that new method is inserted in mVirtualMethodTable (thus increasing the index relative to GetBaseVTableSize()),
  5774. // but the actual written vtable position doesn't change, hence offsetting from GetOrigBaseVTableSize()
  5775. #ifdef _DEBUG
  5776. int vExtIdx = typeInst->GetImplBaseVTableSize();
  5777. BF_ASSERT(typeInst->mVirtualMethodTable[vExtIdx].mDeclaringMethod.mMethodNum == -1); // A type entry with a -1 mMethodNum means it's a vtable ext slot
  5778. #endif
  5779. int vExtOfs = typeInst->GetOrigImplBaseVTableSize();
  5780. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + mModule->mCompiler->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  5781. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, vExtOfs));
  5782. BfIRValue extendPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx);
  5783. vDataPtr = mModule->mBfIRBuilder->CreateLoad(extendPtr);
  5784. vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, extMethodIdx);
  5785. }
  5786. else
  5787. {
  5788. // Map this new virtual index back to the original index
  5789. //vDataIdx += (methodInstance->mVirtualTableIdx - typeInst->GetBaseVTableSize()) + typeInst->GetOrigBaseVTableSize();
  5790. //vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  5791. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  5792. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32,
  5793. (methodInstance->mVirtualTableIdx - typeInst->GetImplBaseVTableSize()) + typeInst->GetOrigImplBaseVTableSize()));
  5794. }
  5795. }
  5796. else
  5797. {
  5798. //vDataIdx += methodInstance->mVirtualTableIdx;
  5799. //vDataIdx = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 1 + methodInstance->GetOwner()->GetDynCastVDataCount() + mModule->mCompiler->mMaxInterfaceSlots);
  5800. vDataIdx = mModule->mBfIRBuilder->GetConfigConst(BfIRConfigConst_VirtualMethodOfs, BfTypeCode_Int32);
  5801. vDataIdx = mModule->mBfIRBuilder->CreateAdd(vDataIdx, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, methodInstance->mVirtualTableIdx));
  5802. }
  5803. if (!vDataPtr)
  5804. {
  5805. BfIRValue vDataPtrPtr = mModule->mBfIRBuilder->CreateBitCast(irArgs[0], funcPtrType3);
  5806. vDataPtr = mModule->FixClassVData(mModule->mBfIRBuilder->CreateLoad(vDataPtrPtr/*, "vtable"*/));
  5807. }
  5808. auto funcPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(vDataPtr, vDataIdx/*, "vfn"*/);
  5809. funcCallInst = mModule->mBfIRBuilder->CreateLoad(funcPtr);
  5810. }
  5811. }
  5812. }
  5813. else // non-virtual
  5814. {
  5815. if (methodInstance->GetOwner()->IsInterface())
  5816. {
  5817. // We're attempting to directly invoke a non-virtual interface method, this will happen during the unspecialized pass
  5818. // OR if we had an error and didn't find an implementing member in the actual target
  5819. if ((!mModule->mCurMethodInstance->mIsUnspecialized) && (!mModule->mCurTypeInstance->IsInterface()))
  5820. mModule->AssertErrorState();
  5821. if (returnType->IsInterface())
  5822. returnType = mModule->CreateConcreteInterfaceType(returnType->ToTypeInstance());
  5823. return _GetDefaultReturnValue();
  5824. }
  5825. }
  5826. if (mFunctionBindResult != NULL)
  5827. {
  5828. mFunctionBindResult->mFunc = funcCallInst;
  5829. if (irArgs.size() != 0)
  5830. {
  5831. auto targetType = methodInstance->mMethodInstanceGroup->mOwner;
  5832. if ((targetType->IsValueType()) && (targetType->IsSplattable()) && (!methodDef->HasNoThisSplat()) && (!IsComptime()))
  5833. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, BfTypedValueKind_SplatHead);
  5834. else
  5835. mFunctionBindResult->mTarget = BfTypedValue(irArgs[0], targetType, targetType->IsComposite() ? BfTypedValueKind_Addr : BfTypedValueKind_Value);
  5836. }
  5837. else
  5838. {
  5839. mFunctionBindResult->mTarget = BfTypedValue();
  5840. }
  5841. return BfTypedValue();
  5842. }
  5843. if (methodInstance->mReturnType == NULL)
  5844. {
  5845. mModule->AssertErrorState();
  5846. return BfTypedValue();
  5847. }
  5848. if (((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized)) && (mModule->mBfIRBuilder->mIgnoreWrites))
  5849. {
  5850. // Don't actually do the call - our target may be a generic param
  5851. return _GetDefaultReturnValue();
  5852. }
  5853. if (mDeferCallRef != NULL)
  5854. {
  5855. mModule->AddDeferredCall(BfModuleMethodInstance(methodInstance, func), irArgs, mDeferScopeAlloc, mDeferCallRef, bypassVirtual);
  5856. return mModule->GetFakeTypedValue(returnType);
  5857. }
  5858. if (!funcCallInst)
  5859. {
  5860. if ((mModule->HasCompiledOutput()) || (mModule->mCompiler->mOptions.mExtraResolveChecks))
  5861. {
  5862. // This can happen either from an error, or from the resolver while doing Internals_Changed processing
  5863. mModule->AssertErrorState();
  5864. }
  5865. return _GetDefaultReturnValue();
  5866. }
  5867. bool hasResult = !methodInstance->mReturnType->IsValuelessType();
  5868. BfIRValue firstArg;
  5869. if (irArgs.size() != 0)
  5870. firstArg = irArgs[0];
  5871. auto methodInstOwner = methodInstance->GetOwner();
  5872. auto expectCallingConvention = mModule->GetIRCallingConvention(methodInstance);
  5873. if ((methodInstOwner->IsFunction()) && (methodInstance->GetParamCount() > 0) && (methodInstance->GetParamName(0) == "this"))
  5874. {
  5875. auto paramType = methodInstance->GetParamType(0);
  5876. if (!paramType->IsValueType())
  5877. expectCallingConvention = BfIRCallingConv_ThisCall;
  5878. }
  5879. if ((methodInstance->mAlwaysInline) && (mModule->mCompiler->mOptions.mEmitLineInfo))
  5880. {
  5881. // Emit a NOP so we always have a "step over" point
  5882. mModule->EmitEnsureInstructionAt();
  5883. }
  5884. if (returnType->IsComposite())
  5885. mModule->mBfIRBuilder->PopulateType(returnType);
  5886. methodInstance->mMethodInstanceGroup->mHasEmittedReference = true;
  5887. BfIRValue callInst;
  5888. int callIRArgCount = (int)irArgs.size();
  5889. if (sret != NULL)
  5890. {
  5891. SizedArray<BfIRValue, 8> sretIRArgs;
  5892. int sretIdx = GetStructRetIdx(methodInstance);
  5893. int inIdx = 0;
  5894. for (int outIdx = 0; outIdx < irArgs.size() + 1; outIdx++)
  5895. {
  5896. if (outIdx == sretIdx)
  5897. {
  5898. sretIRArgs.Add(sret->mValue);
  5899. continue;
  5900. }
  5901. sretIRArgs.Add(irArgs[inIdx++]);
  5902. }
  5903. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, sretIRArgs);
  5904. callIRArgCount++;
  5905. }
  5906. else
  5907. {
  5908. callInst = mModule->mBfIRBuilder->CreateCall(funcCallInst, irArgs);
  5909. if ((hasResult) && (!methodDef->mName.IsEmpty()) && (!methodInstance->mIsIntrinsic))
  5910. mModule->mBfIRBuilder->SetName(callInst, methodDef->mName);
  5911. }
  5912. if ((expectCallingConvention != BfIRCallingConv_CDecl) && (!methodInstance->mIsIntrinsic))
  5913. mModule->mBfIRBuilder->SetCallCallingConv(callInst, expectCallingConvention);
  5914. if ((methodDef->mIsNoReturn) && (!methodInstance->mIsIntrinsic))
  5915. mModule->mBfIRBuilder->Call_AddAttribute(callInst, -1, BfIRAttribute_NoReturn);
  5916. bool hadAttrs = false;
  5917. int paramIdx = 0;
  5918. bool doingThis = methodInstance->HasThis();
  5919. int argIdx = 0;
  5920. if (methodDef->mHasExplicitThis)
  5921. paramIdx++;
  5922. int paramCount = methodInstance->GetParamCount();
  5923. for ( ; argIdx < callIRArgCount ; )
  5924. {
  5925. if (methodInstance->mIsIntrinsic)
  5926. break;
  5927. if (argIdx == GetStructRetIdx(methodInstance))
  5928. {
  5929. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_StructRet);
  5930. argIdx++;
  5931. continue;
  5932. }
  5933. auto _HandleParamType = [&] (BfType* paramType)
  5934. {
  5935. if (paramType->IsStruct())
  5936. {
  5937. if ((!doingThis) || (!methodDef->mIsMutating && methodInstance->AllowsSplatting(paramIdx)))
  5938. {
  5939. BfTypeCode loweredTypeCode = BfTypeCode_None;
  5940. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  5941. if (paramType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  5942. {
  5943. argIdx++;
  5944. if (loweredTypeCode2 != BfTypeCode_None)
  5945. argIdx++;
  5946. return; // Lowering never requires attributes
  5947. }
  5948. }
  5949. }
  5950. int addDeref = -1;
  5951. if (paramType->IsRef())
  5952. {
  5953. auto refType = (BfRefType*)paramType;
  5954. auto elementType = refType->mElementType;
  5955. mModule->PopulateType(elementType, BfPopulateType_Data);
  5956. addDeref = elementType->mSize;
  5957. if ((addDeref <= 0) && (!elementType->IsValuelessType()))
  5958. mModule->AssertErrorState();
  5959. }
  5960. if ((paramType->IsComposite()) && (!paramType->IsTypedPrimitive()))
  5961. {
  5962. if (mModule->mCompiler->mOptions.mAllowStructByVal)
  5963. {
  5964. //byval
  5965. }
  5966. else
  5967. {
  5968. mModule->PopulateType(paramType, BfPopulateType_Data);
  5969. auto typeInst = paramType->ToTypeInstance();
  5970. if ((typeInst != NULL) && (typeInst->mIsCRepr) && (typeInst->IsSplattable()) && (!IsComptime()))
  5971. {
  5972. // We're splatting
  5973. }
  5974. else
  5975. {
  5976. if (doingThis)
  5977. {
  5978. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_NoCapture);
  5979. addDeref = paramType->mSize;
  5980. }
  5981. else if (methodInstance->WantsStructsAttribByVal(paramType))
  5982. {
  5983. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ByVal, mModule->mSystem->mPtrSize);
  5984. }
  5985. }
  5986. }
  5987. }
  5988. else if (paramType->IsPrimitiveType())
  5989. {
  5990. auto primType = (BfPrimitiveType*)paramType;
  5991. if ((primType->mTypeDef->mTypeCode == BfTypeCode_Boolean) && (!methodInstance->mIsIntrinsic))
  5992. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_ZExt);
  5993. }
  5994. if (addDeref >= 0)
  5995. {
  5996. mModule->mBfIRBuilder->Call_AddAttribute(callInst, argIdx + 1, BfIRAttribute_Dereferencable, addDeref);
  5997. }
  5998. argIdx++;
  5999. };
  6000. BfType* paramType = NULL;
  6001. if (doingThis)
  6002. {
  6003. int thisIdx = methodInstance->GetThisIdx();
  6004. paramType = methodInstance->GetThisType();
  6005. if (paramType->IsValuelessType())
  6006. {
  6007. doingThis = false;
  6008. continue;
  6009. }
  6010. bool isSplatted = methodInstance->GetParamIsSplat(thisIdx) && (!IsComptime()); // (resolvedTypeRef->IsSplattable()) && (!methodDef->mIsMutating);
  6011. if (isSplatted)
  6012. {
  6013. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  6014. doingThis = false;
  6015. continue;
  6016. }
  6017. else
  6018. _HandleParamType(paramType);
  6019. }
  6020. else
  6021. {
  6022. if (paramIdx >= methodInstance->GetParamCount())
  6023. break;
  6024. paramType = methodInstance->GetParamType(paramIdx);
  6025. BfTypeCode loweredTypeCode = BfTypeCode_None;
  6026. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  6027. if (paramType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  6028. {
  6029. argIdx++;
  6030. paramIdx++;
  6031. if (loweredTypeCode2 != BfTypeCode_None)
  6032. argIdx++;
  6033. continue;
  6034. }
  6035. if ((paramType->IsValuelessType()) && (!paramType->IsMethodRef()))
  6036. {
  6037. paramIdx++;
  6038. continue;
  6039. }
  6040. if ((methodInstance->GetParamIsSplat(paramIdx)) && (!IsComptime()))
  6041. {
  6042. BfTypeUtils::SplatIterate(_HandleParamType, paramType);
  6043. paramIdx++;
  6044. continue;
  6045. }
  6046. else
  6047. _HandleParamType(methodInstance->GetParamType(paramIdx));
  6048. }
  6049. if (doingThis)
  6050. doingThis = false;
  6051. else
  6052. paramIdx++;
  6053. //argIdx++;
  6054. }
  6055. if ((callFlags & BfCreateCallFlags_TailCall) != 0)
  6056. mModule->mBfIRBuilder->SetTailCall(callInst);
  6057. if (methodDef->mIsNoReturn)
  6058. {
  6059. mModule->mBfIRBuilder->CreateUnreachable();
  6060. // For debuggability when looking back at stack trace
  6061. //mModule->ExtendLocalLifetimes(0);
  6062. if (mModule->IsTargetingBeefBackend())
  6063. {
  6064. auto checkScope = mModule->mCurMethodState->mCurScope;
  6065. while (checkScope != NULL)
  6066. {
  6067. mModule->EmitLifetimeEnds(checkScope);
  6068. checkScope = checkScope->mPrevScope;
  6069. }
  6070. // This 'fake' branch extends lifetimes of outer variable scopes
  6071. if (mModule->mCurMethodState->mIRExitBlock)
  6072. mModule->mBfIRBuilder->CreateBr_Fake(mModule->mCurMethodState->mIRExitBlock);
  6073. }
  6074. }
  6075. else
  6076. {
  6077. if (mModule->mCurMethodState != NULL)
  6078. mModule->mCurMethodState->mMayNeedThisAccessCheck = true;
  6079. }
  6080. BfTypedValue result;
  6081. if (sret != NULL)
  6082. result = *sret;
  6083. else if (hasResult)
  6084. {
  6085. BfTypeCode loweredRetType = BfTypeCode_None;
  6086. BfTypeCode loweredRetType2 = BfTypeCode_None;
  6087. if ((!IsComptime()) && (methodInstance->GetLoweredReturnType(&loweredRetType, &loweredRetType2)) && (loweredRetType != BfTypeCode_None))
  6088. {
  6089. auto retVal = mModule->CreateAlloca(methodInstance->mReturnType);
  6090. BfIRType loweredIRType = mModule->GetIRLoweredType(loweredRetType, loweredRetType2);
  6091. loweredIRType = mModule->mBfIRBuilder->GetPointerTo(loweredIRType);
  6092. auto castedRetVal = mModule->mBfIRBuilder->CreateBitCast(retVal, loweredIRType);
  6093. mModule->mBfIRBuilder->CreateStore(callInst, castedRetVal);
  6094. result = BfTypedValue(retVal, methodInstance->mReturnType, BfTypedValueKind_RestrictedTempAddr);
  6095. }
  6096. else
  6097. result = BfTypedValue(callInst, methodInstance->mReturnType);
  6098. }
  6099. else
  6100. result = mModule->GetFakeTypedValue(methodInstance->mReturnType);
  6101. if (result.mType->IsRef())
  6102. {
  6103. result = mModule->RemoveRef(result);
  6104. if (methodDef->mIsReadOnly)
  6105. {
  6106. if (result.mKind == BfTypedValueKind_Addr)
  6107. result.mKind = BfTypedValueKind_ReadOnlyAddr;
  6108. }
  6109. }
  6110. return result;
  6111. }
  6112. BfTypedValue BfExprEvaluator::CreateCall(BfMethodMatcher* methodMatcher, BfTypedValue target)
  6113. {
  6114. auto moduleMethodInstance = GetSelectedMethod(*methodMatcher);
  6115. if (moduleMethodInstance.mMethodInstance == NULL)
  6116. return BfTypedValue();
  6117. if ((target) && (target.mType != moduleMethodInstance.mMethodInstance->GetOwner()))
  6118. {
  6119. auto castedTarget = mModule->Cast(methodMatcher->mTargetSrc, target, moduleMethodInstance.mMethodInstance->GetOwner());
  6120. BF_ASSERT(castedTarget);
  6121. target = castedTarget;
  6122. }
  6123. PerformCallChecks(moduleMethodInstance.mMethodInstance, methodMatcher->mTargetSrc);
  6124. BfCreateCallFlags callFlags = BfCreateCallFlags_None;
  6125. if (methodMatcher->mAllowImplicitRef)
  6126. callFlags = (BfCreateCallFlags)(callFlags | BfCreateCallFlags_AllowImplicitRef);
  6127. return CreateCall(methodMatcher->mTargetSrc, target, BfTypedValue(), methodMatcher->mBestMethodDef, moduleMethodInstance, callFlags, methodMatcher->mArguments);
  6128. }
  6129. void BfExprEvaluator::MakeBaseConcrete(BfTypedValue& typedValue)
  6130. {
  6131. if (typedValue.IsBase())
  6132. {
  6133. auto baseType = mModule->mCurTypeInstance->mBaseType;
  6134. if (baseType == NULL)
  6135. baseType = mModule->mContext->mBfObjectType;
  6136. mModule->PopulateType(baseType, BfPopulateType_Data);
  6137. typedValue = mModule->Cast(NULL, typedValue, baseType, BfCastFlags_Explicit);
  6138. }
  6139. }
  6140. void BfExprEvaluator::SplatArgs(BfTypedValue value, SizedArrayImpl<BfIRValue>& irArgs)
  6141. {
  6142. if (value.IsSplat())
  6143. {
  6144. int componentIdx = 0;
  6145. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->ExtractSplatValue(value, componentIdx++, checkType)); }, value.mType);
  6146. return;
  6147. }
  6148. mModule->mBfIRBuilder->PopulateType(value.mType);
  6149. std::function<void(BfTypedValue)> checkTypeLambda = [&](BfTypedValue curValue)
  6150. {
  6151. BfType* checkType = curValue.mType;
  6152. if (checkType->IsStruct())
  6153. {
  6154. auto checkTypeInstance = checkType->ToTypeInstance();
  6155. if ((checkTypeInstance->mBaseType != NULL) && (!checkTypeInstance->mBaseType->IsValuelessType()))
  6156. {
  6157. BfTypedValue baseValue;
  6158. if (curValue.IsAddr())
  6159. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, 0), checkTypeInstance->mBaseType, true);
  6160. else
  6161. baseValue = BfTypedValue((!curValue.mValue) ? BfIRValue() : mModule->mBfIRBuilder->CreateExtractValue(curValue.mValue, 0), checkTypeInstance->mBaseType);
  6162. checkTypeLambda(baseValue);
  6163. }
  6164. if (checkTypeInstance->mIsUnion)
  6165. {
  6166. auto unionInnerType = checkTypeInstance->GetUnionInnerType();
  6167. if (!unionInnerType->IsValuelessType())
  6168. {
  6169. BfTypedValue unionValue = mModule->ExtractValue(curValue, NULL, 1);
  6170. checkTypeLambda(unionValue);
  6171. }
  6172. if (checkTypeInstance->IsEnum())
  6173. {
  6174. BfTypedValue dscrValue = mModule->ExtractValue(curValue, NULL, 2);
  6175. checkTypeLambda(dscrValue);
  6176. }
  6177. }
  6178. else
  6179. {
  6180. for (int fieldIdx = 0; fieldIdx < (int)checkTypeInstance->mFieldInstances.size(); fieldIdx++)
  6181. {
  6182. auto fieldInstance = (BfFieldInstance*)&checkTypeInstance->mFieldInstances[fieldIdx];
  6183. if (fieldInstance->mDataIdx >= 0)
  6184. {
  6185. BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  6186. checkTypeLambda(fieldValue);
  6187. }
  6188. }
  6189. }
  6190. }
  6191. else if (checkType->IsMethodRef())
  6192. {
  6193. BF_ASSERT(curValue.IsAddr());
  6194. BfMethodRefType* methodRefType = (BfMethodRefType*)checkType;
  6195. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  6196. {
  6197. auto checkType = methodRefType->GetCaptureType(dataIdx);
  6198. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  6199. {
  6200. BF_ASSERT(dataIdx == 0);
  6201. auto ptrType = mModule->CreatePointerType(checkType);
  6202. auto elemPtr = mModule->mBfIRBuilder->CreateBitCast(curValue.mValue, mModule->mBfIRBuilder->MapType(ptrType));
  6203. checkTypeLambda(BfTypedValue(elemPtr, checkType, BfTypedValueKind_Addr));
  6204. //BfTypedValue fieldValue = mModule->ExtractValue(curValue, fieldInstance, fieldInstance->mDataIdx);
  6205. //checkTypeLambda(fieldValue);
  6206. }
  6207. else
  6208. {
  6209. auto elemVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curValue.mValue, 0, dataIdx);
  6210. if (!checkType->IsComposite())
  6211. elemVal = mModule->mBfIRBuilder->CreateLoad(elemVal);
  6212. irArgs.Add(elemVal);
  6213. //irArgs.Add(mModule->ExtractValue(curValue, dataIdx));
  6214. }
  6215. }
  6216. }
  6217. else if (!checkType->IsValuelessType())
  6218. {
  6219. auto loadedVal = mModule->LoadValue(curValue);
  6220. loadedVal = mModule->PrepareConst(loadedVal);
  6221. irArgs.push_back(loadedVal.mValue);
  6222. }
  6223. };
  6224. checkTypeLambda(value);
  6225. }
  6226. void BfExprEvaluator::PushArg(BfTypedValue argVal, SizedArrayImpl<BfIRValue>& irArgs, bool disableSplat, bool disableLowering, bool isIntrinsic, bool createCompositeCopy)
  6227. {
  6228. MakeBaseConcrete(argVal);
  6229. if (IsVar(argVal.mType))
  6230. {
  6231. argVal = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  6232. }
  6233. if (argVal.mType->IsValuelessType())
  6234. return;
  6235. bool wantSplat = false;
  6236. if ((argVal.mType->IsSplattable()) && (!disableSplat) && (!IsComptime()))
  6237. {
  6238. disableLowering = true;
  6239. auto argTypeInstance = argVal.mType->ToTypeInstance();
  6240. if (!disableSplat)
  6241. {
  6242. if ((argTypeInstance != NULL) && (argTypeInstance->mIsCRepr))
  6243. wantSplat = true;
  6244. else if ((int)irArgs.size() + argVal.mType->GetSplatCount() <= mModule->mCompiler->mOptions.mMaxSplatRegs)
  6245. wantSplat = true;
  6246. }
  6247. }
  6248. if (wantSplat)
  6249. {
  6250. SplatArgs(argVal, irArgs);
  6251. }
  6252. else
  6253. {
  6254. if (argVal.mType->IsComposite())
  6255. {
  6256. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  6257. {
  6258. // Const eval entry - we want any incoming consts as they are
  6259. }
  6260. else if (isIntrinsic)
  6261. {
  6262. // We can handle composites either by value or not
  6263. }
  6264. else
  6265. argVal = mModule->MakeAddressable(argVal);
  6266. if ((!IsComptime()) && (!disableLowering) && (!isIntrinsic))
  6267. {
  6268. BfTypeCode loweredTypeCode = BfTypeCode_None;
  6269. BfTypeCode loweredTypeCode2 = BfTypeCode_None;
  6270. if (argVal.mType->GetLoweredType(BfTypeUsage_Parameter, &loweredTypeCode, &loweredTypeCode2))
  6271. {
  6272. BfIRValue argPtrVal = argVal.mValue;
  6273. int loweredSize = mModule->mBfIRBuilder->GetSize(loweredTypeCode) + mModule->mBfIRBuilder->GetSize(loweredTypeCode2);
  6274. if (argVal.mType->mSize < loweredSize)
  6275. {
  6276. auto allocaVal = mModule->CreateAlloca(mModule->GetPrimitiveType(BfTypeCode_UInt8), true, NULL, mModule->GetConstValue(loweredSize));
  6277. mModule->mBfIRBuilder->SetAllocaAlignment(allocaVal,
  6278. BF_MAX(argVal.mType->mAlign,
  6279. BF_MAX(mModule->mBfIRBuilder->GetSize(loweredTypeCode), mModule->mBfIRBuilder->GetSize(loweredTypeCode2))));
  6280. auto castedPtr = mModule->mBfIRBuilder->CreateBitCast(allocaVal, mModule->mBfIRBuilder->MapType(mModule->CreatePointerType(argVal.mType)));
  6281. auto argIRVal = mModule->mBfIRBuilder->CreateAlignedLoad(argVal.mValue, argVal.mType->mAlign);
  6282. mModule->mBfIRBuilder->CreateAlignedStore(argIRVal, castedPtr, argVal.mType->mAlign);
  6283. argPtrVal = castedPtr;
  6284. }
  6285. auto primType = mModule->mBfIRBuilder->GetPrimitiveType(loweredTypeCode);
  6286. auto ptrType = mModule->mBfIRBuilder->GetPointerTo(primType);
  6287. BfIRValue primPtrVal = mModule->mBfIRBuilder->CreateBitCast(argPtrVal, ptrType);
  6288. auto primVal = mModule->mBfIRBuilder->CreateLoad(primPtrVal);
  6289. irArgs.push_back(primVal);
  6290. if (loweredTypeCode2 != BfTypeCode_None)
  6291. {
  6292. auto primType2 = mModule->mBfIRBuilder->GetPrimitiveType(loweredTypeCode2);
  6293. auto ptrType2 = mModule->mBfIRBuilder->GetPointerTo(primType2);
  6294. BfIRValue primPtrVal2;
  6295. if (mModule->mBfIRBuilder->GetSize(loweredTypeCode) < mModule->mBfIRBuilder->GetSize(loweredTypeCode2))
  6296. primPtrVal2 = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->CreateBitCast(primPtrVal, ptrType2), 1);
  6297. else
  6298. primPtrVal2 = mModule->mBfIRBuilder->CreateBitCast(mModule->mBfIRBuilder->CreateInBoundsGEP(primPtrVal, 1), ptrType2);
  6299. auto primVal2 = mModule->mBfIRBuilder->CreateLoad(primPtrVal2);
  6300. irArgs.Add(primVal2);
  6301. }
  6302. return;
  6303. }
  6304. }
  6305. if ((createCompositeCopy) && (!argVal.IsTempAddr()))
  6306. {
  6307. // Non-Beef calling conventions require copies of composites
  6308. auto copyAddr = mModule->CreateAlloca(argVal.mType);
  6309. mModule->mBfIRBuilder->CreateStore(mModule->LoadValue(argVal).mValue, copyAddr);
  6310. argVal = BfTypedValue(copyAddr, argVal.mType, BfTypedValueKind_TempAddr);
  6311. }
  6312. }
  6313. else
  6314. argVal = mModule->LoadValue(argVal);
  6315. irArgs.Add(argVal.mValue);
  6316. }
  6317. }
  6318. void BfExprEvaluator::PushThis(BfAstNode* targetSrc, BfTypedValue argVal, BfMethodInstance* methodInstance, SizedArrayImpl<BfIRValue>& irArgs, bool skipMutCheck)
  6319. {
  6320. MakeBaseConcrete(argVal);
  6321. auto methodDef = methodInstance->mMethodDef;
  6322. if (methodInstance->IsSkipCall())
  6323. return;
  6324. if (!argVal)
  6325. {
  6326. //BF_ASSERT(mFunctionBindResult != NULL);
  6327. return;
  6328. }
  6329. if (methodDef->mIsMutating)
  6330. {
  6331. bool checkMut = false;
  6332. if (argVal.mType->IsGenericParam())
  6333. {
  6334. // For capturing mutability
  6335. if (mResultLocalVar != NULL)
  6336. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  6337. }
  6338. if (((argVal.mType->IsComposite()) || (argVal.mType->IsTypedPrimitive())))
  6339. {
  6340. if (argVal.IsCopyOnMutate())
  6341. argVal = mModule->CopyValue(argVal);
  6342. if ((argVal.IsReadOnly()) || (!argVal.IsAddr()))
  6343. {
  6344. if (!skipMutCheck)
  6345. {
  6346. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(methodInstance).c_str());
  6347. CheckModifyResult(argVal, targetSrc, err.c_str());
  6348. }
  6349. if (argVal.IsSplat())
  6350. {
  6351. argVal = mModule->AggregateSplat(argVal);
  6352. argVal = mModule->MakeAddressable(argVal);
  6353. }
  6354. }
  6355. else
  6356. {
  6357. if (mResultLocalVar != NULL)
  6358. {
  6359. // When we are capturing, we need to note that we require capturing by reference here
  6360. mResultLocalVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  6361. }
  6362. }
  6363. }
  6364. }
  6365. if (argVal.mType->IsValuelessType())
  6366. return;
  6367. auto owner = methodInstance->GetOwner();
  6368. bool allowThisSplatting;
  6369. if (mModule->mIsComptimeModule)
  6370. allowThisSplatting = owner->IsTypedPrimitive() || owner->IsValuelessType();
  6371. else
  6372. allowThisSplatting = methodInstance->AllowsSplatting(-1);
  6373. if ((!allowThisSplatting) || (methodDef->mIsMutating))
  6374. {
  6375. argVal = mModule->MakeAddressable(argVal);
  6376. irArgs.push_back(argVal.mValue);
  6377. return;
  6378. }
  6379. auto thisType = methodInstance->GetThisType();
  6380. PushArg(argVal, irArgs, !methodInstance->AllowsSplatting(-1), thisType->IsPointer());
  6381. }
  6382. void BfExprEvaluator::FinishDeferredEvals(SizedArrayImpl<BfResolvedArg>& argValues)
  6383. {
  6384. for (int argIdx = 0; argIdx < argValues.size(); argIdx++)
  6385. {
  6386. auto& argValue = argValues[argIdx].mTypedValue;
  6387. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  6388. {
  6389. if (!argValue)
  6390. {
  6391. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  6392. if (expr != NULL)
  6393. argValue = mModule->CreateValueFromExpression(expr);
  6394. }
  6395. }
  6396. }
  6397. }
  6398. void BfExprEvaluator::FinishDeferredEvals(BfResolvedArgs& argValues)
  6399. {
  6400. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  6401. {
  6402. auto& argValue = argValues.mResolvedArgs[argIdx].mTypedValue;
  6403. if ((argValues.mResolvedArgs[argIdx].mArgFlags & (BfArgFlag_VariableDeclaration)) != 0)
  6404. {
  6405. auto variableDeclaration = BfNodeDynCast<BfVariableDeclaration>((*argValues.mArguments)[argIdx]);
  6406. if ((variableDeclaration != NULL) && (variableDeclaration->mNameNode != NULL))
  6407. {
  6408. if (mModule->mCurMethodState == NULL)
  6409. {
  6410. mModule->Fail("Illegal local variable", variableDeclaration);
  6411. }
  6412. else
  6413. {
  6414. BfLocalVariable* localVar = new BfLocalVariable();
  6415. localVar->mName = variableDeclaration->mNameNode->ToString();
  6416. localVar->mResolvedType = mModule->GetPrimitiveType(BfTypeCode_Var);
  6417. localVar->mAddr = mModule->mBfIRBuilder->GetFakeVal();
  6418. localVar->mReadFromId = 0;
  6419. localVar->mWrittenToId = 0;
  6420. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  6421. mModule->CheckVariableDef(localVar);
  6422. localVar->Init();
  6423. mModule->AddLocalVariableDef(localVar, true);
  6424. }
  6425. }
  6426. }
  6427. }
  6428. FinishDeferredEvals(argValues.mResolvedArgs);
  6429. }
  6430. void BfExprEvaluator::AddCallDependencies(BfMethodInstance* methodInstance)
  6431. {
  6432. if (methodInstance->mReturnType != NULL)
  6433. mModule->AddDependency(methodInstance->mReturnType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  6434. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  6435. {
  6436. auto paramType = methodInstance->GetParamType(paramIdx);
  6437. mModule->AddDependency(paramType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  6438. }
  6439. if (methodInstance->mMethodInfoEx != NULL)
  6440. {
  6441. for (auto genericArg : methodInstance->mMethodInfoEx->mMethodGenericArguments)
  6442. {
  6443. if (genericArg->IsWrappableType())
  6444. genericArg = mModule->GetWrappedStructType(genericArg);
  6445. if (genericArg != NULL)
  6446. mModule->AddDependency(genericArg, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  6447. }
  6448. }
  6449. }
  6450. //TODO: delete argumentsZ
  6451. BfTypedValue BfExprEvaluator::CreateCall(BfAstNode* targetSrc, const BfTypedValue& inTarget, const BfTypedValue& origTarget, BfMethodDef* methodDef, BfModuleMethodInstance moduleMethodInstance, BfCreateCallFlags callFlags, SizedArrayImpl<BfResolvedArg>& argValues, BfTypedValue* argCascade)
  6452. {
  6453. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlag(mBfEvalExprFlags);
  6454. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mConstEvalAttributeTypeDef)))
  6455. {
  6456. mModule->mAttributeState->mUsed = true;
  6457. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  6458. }
  6459. else if ((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_ConstEval) != 0)
  6460. {
  6461. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  6462. }
  6463. else if (((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_Comptime) != 0) && (!mModule->mIsComptimeModule))
  6464. {
  6465. if ((mModule->mCurMethodInstance == NULL) || (mModule->mCurMethodInstance->mComptimeFlags == BfComptimeFlag_None))
  6466. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  6467. }
  6468. if (((moduleMethodInstance.mMethodInstance->mComptimeFlags & BfComptimeFlag_OnlyFromComptime) != 0) &&
  6469. ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) &&
  6470. ((mModule->mCurMethodInstance == NULL) || (mModule->mCurMethodInstance->mComptimeFlags == BfComptimeFlag_None)) &&
  6471. (!mModule->mIsComptimeModule))
  6472. {
  6473. mModule->Fail(StrFormat("Method '%s' can only be invoked at comptime. Consider adding [Comptime] to the current method.", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  6474. }
  6475. bool bypassVirtual = (callFlags & BfCreateCallFlags_BypassVirtual) != 0;
  6476. bool skipThis = (callFlags & BfCreateCallFlags_SkipThis) != 0;;
  6477. static int sCallIdx = 0;
  6478. if (!mModule->mCompiler->mIsResolveOnly)
  6479. sCallIdx++;
  6480. int callIdx = sCallIdx;
  6481. if (callIdx == 0x000015CB)
  6482. {
  6483. NOP;
  6484. }
  6485. // Temporarily disable so we don't capture calls in params
  6486. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  6487. SetAndRestoreValue<bool> prevAllowVariableDeclarations;
  6488. if (mModule->mCurMethodState != NULL)
  6489. prevAllowVariableDeclarations.Init(mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations, false);
  6490. BfMethodInstance* methodInstance = moduleMethodInstance.mMethodInstance;
  6491. SizedArray<BfIRValue, 4> irArgs;
  6492. if ((methodDef->mIsAbstract) && (bypassVirtual))
  6493. {
  6494. mModule->Fail(StrFormat("Abstract base method '%s' cannot be invoked", mModule->MethodToString(methodInstance).c_str()), targetSrc);
  6495. }
  6496. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  6497. BfType* returnType = methodInstance->mReturnType;
  6498. /*if (returnType->IsSelf())
  6499. {
  6500. returnType = methodInstance->GetOwner();
  6501. BF_ASSERT(returnType->IsInterface());
  6502. }*/
  6503. Array<BfTypedValue> argCascades;
  6504. BfTypedValue target = inTarget;
  6505. if (!skipThis)
  6506. {
  6507. if ((target) && (target.mType->IsFunction()) && (methodInstance->GetOwner() == target.mType))
  6508. {
  6509. CheckResultForReading(target);
  6510. target = mModule->LoadValue(target);
  6511. auto funcType = mModule->mBfIRBuilder->MapMethod(moduleMethodInstance.mMethodInstance);
  6512. auto funcPtrType = mModule->mBfIRBuilder->GetPointerTo(funcType);
  6513. moduleMethodInstance.mFunc = mModule->mBfIRBuilder->CreateIntToPtr(target.mValue, funcPtrType);
  6514. }
  6515. else if (!methodDef->mIsStatic)
  6516. {
  6517. if ((!target) && (prevBindResult.mPrevVal != NULL))
  6518. {
  6519. auto bindResult = prevBindResult.mPrevVal;
  6520. if (bindResult->mBindType != NULL)
  6521. {
  6522. // Allow binding a function to a 'this' type even if no target is specified
  6523. auto delegateInfo = bindResult->mBindType->GetDelegateInfo();
  6524. if (delegateInfo != NULL)
  6525. {
  6526. if (delegateInfo->mHasExplicitThis)
  6527. {
  6528. target = mModule->GetDefaultTypedValue(delegateInfo->mParams[0], false, BfDefaultValueKind_Addr);
  6529. bypassVirtual = true;
  6530. }
  6531. }
  6532. else if (bindResult->mBindType->IsFunction())
  6533. {
  6534. BfMethodInstance* invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(bindResult->mBindType->ToTypeInstance(), 0, "Invoke");
  6535. if (!invokeMethodInstance->mMethodDef->mIsStatic)
  6536. {
  6537. target = mModule->GetDefaultTypedValue(invokeMethodInstance->GetThisType(), false, BfDefaultValueKind_Addr);
  6538. }
  6539. }
  6540. }
  6541. }
  6542. if (!target)
  6543. {
  6544. FinishDeferredEvals(argValues);
  6545. auto error = mModule->Fail(StrFormat("An instance reference is required to %s the non-static method '%s'",
  6546. (prevBindResult.mPrevVal != NULL) ? "bind" : "invoke",
  6547. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  6548. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  6549. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  6550. return mModule->GetDefaultTypedValue(returnType);
  6551. }
  6552. auto prevResult = mResult;
  6553. mResult = target;
  6554. CheckResultForReading(mResult);
  6555. mResult = prevResult;
  6556. if (methodDef->mMethodType != BfMethodType_Ctor)
  6557. {
  6558. bool doAccessCheck = true;
  6559. if (target.IsThis())
  6560. {
  6561. if (!mModule->mCurMethodState->mMayNeedThisAccessCheck)
  6562. doAccessCheck = false;
  6563. }
  6564. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mDisableObjectAccessChecksAttributeTypeDef)))
  6565. doAccessCheck = false;
  6566. if ((doAccessCheck) && (!isSkipCall) && (prevBindResult.mPrevVal == NULL))
  6567. mModule->EmitObjectAccessCheck(target);
  6568. }
  6569. if (((prevBindResult.mPrevVal == NULL) || (!prevBindResult.mPrevVal->mSkipThis)) &&
  6570. (!isSkipCall))
  6571. {
  6572. bool skipMutCheck = false;
  6573. if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mSkipMutCheck))
  6574. {
  6575. // If we are binding a delegate, then we will end up making a copy of the target anyway
  6576. // so we don't need to do a mutability check
  6577. skipMutCheck = true;
  6578. }
  6579. if (methodDef->mMethodType == BfMethodType_Extension)
  6580. PushArg(target, irArgs);
  6581. else
  6582. PushThis(targetSrc, target, moduleMethodInstance.mMethodInstance, irArgs, skipMutCheck);
  6583. }
  6584. }
  6585. else if (methodDef->mMethodType == BfMethodType_Extension)
  6586. {
  6587. // Handled in args
  6588. }
  6589. else
  6590. {
  6591. mModule->CheckStaticAccess(methodInstance->mMethodInstanceGroup->mOwner);
  6592. if (target)
  6593. {
  6594. FinishDeferredEvals(argValues);
  6595. mModule->Fail(StrFormat("Method '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  6596. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  6597. return mModule->GetDefaultTypedValue(returnType);
  6598. }
  6599. }
  6600. }
  6601. if (isSkipCall)
  6602. {
  6603. FinishDeferredEvals(argValues);
  6604. mModule->EmitEnsureInstructionAt();
  6605. return mModule->GetDefaultTypedValue(returnType);
  6606. }
  6607. bool hasNamedArgs = false;
  6608. for (auto& arg : argValues)
  6609. if (arg.mNameNode != NULL)
  6610. hasNamedArgs = true;
  6611. if (hasNamedArgs)
  6612. {
  6613. methodDef->BuildParamNameMap();
  6614. BfIdentifierNode* outOfPlaceName = NULL;
  6615. int curParamIdx = 0;
  6616. SizedArrayImpl<BfResolvedArg> origArgValues = argValues;
  6617. argValues.Clear();
  6618. for (int argIdx = 0; argIdx < origArgValues.mSize; argIdx++)
  6619. {
  6620. int paramIdx = curParamIdx;
  6621. auto& argValue = origArgValues[argIdx];
  6622. if (argValue.mNameNode != NULL)
  6623. {
  6624. int namedParamIdx = -1;
  6625. if (methodDef->mParamNameMap->TryGetValue(argValue.mNameNode->ToStringView(), &namedParamIdx))
  6626. {
  6627. paramIdx = namedParamIdx;
  6628. }
  6629. else
  6630. {
  6631. if (mModule->PreFail())
  6632. {
  6633. mModule->Fail(StrFormat("The best overload for '%s' does not have a parameter named '%s'", methodInstance->mMethodDef->mName.c_str(),
  6634. argValue.mNameNode->ToString().c_str()), argValue.mNameNode);
  6635. }
  6636. }
  6637. if (paramIdx != curParamIdx)
  6638. outOfPlaceName = argValue.mNameNode;
  6639. }
  6640. else if (outOfPlaceName != NULL)
  6641. {
  6642. if (mModule->PreFail())
  6643. mModule->Fail(StrFormat("Named argument '%s' is used out-of-position but is followed by an unnamed argument", outOfPlaceName->ToString().c_str()), outOfPlaceName);
  6644. outOfPlaceName = NULL;
  6645. }
  6646. if ((paramIdx < methodInstance->GetParamCount()) && (paramIdx != argIdx))
  6647. {
  6648. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_Normal)
  6649. {
  6650. auto wantType = methodInstance->GetParamType(paramIdx);
  6651. auto resolvedValue = ResolveArgValue(argValue, wantType);
  6652. if (resolvedValue)
  6653. {
  6654. argValue.mTypedValue = resolvedValue;
  6655. argValue.mArgFlags = (BfArgFlags)(argValue.mArgFlags | BfArgFlag_Finalized);
  6656. }
  6657. }
  6658. }
  6659. while (paramIdx >= argValues.mSize)
  6660. argValues.Add(BfResolvedArg());
  6661. if (argValues[paramIdx].mExpression != NULL)
  6662. {
  6663. if (argValue.mNameNode != NULL)
  6664. {
  6665. if (mModule->PreFail())
  6666. mModule->Fail(StrFormat("Named argument '%s' cannot be specified multiple times", argValue.mNameNode->ToString().c_str()), argValue.mNameNode);
  6667. }
  6668. }
  6669. argValues[paramIdx] = argValue;
  6670. curParamIdx++;
  6671. }
  6672. }
  6673. int argIdx = 0;
  6674. int paramIdx = 0;
  6675. BfIRValue expandedParamAlloca;
  6676. BfTypedValue expandedParamsArray;
  6677. BfType* expandedParamsElementType = NULL;
  6678. int extendedParamIdx = 0;
  6679. AddCallDependencies(methodInstance);
  6680. bool wasCapturingMatchInfo = false;
  6681. auto autoComplete = GetAutoComplete();
  6682. if (autoComplete != NULL)
  6683. {
  6684. // Set to false to make sure we don't capture method match info from 'params' array creation
  6685. wasCapturingMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  6686. autoComplete->mIsCapturingMethodMatchInfo = false;
  6687. }
  6688. defer(
  6689. {
  6690. if (autoComplete != NULL)
  6691. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMatchInfo;
  6692. });
  6693. BfScopeData* boxScopeData = mDeferScopeAlloc;
  6694. if ((boxScopeData == NULL) && (mModule->mCurMethodState != NULL))
  6695. boxScopeData = mModule->mCurMethodState->mCurScope;
  6696. bool failed = false;
  6697. while (true)
  6698. {
  6699. int argExprIdx = argIdx;
  6700. if (methodDef->mMethodType == BfMethodType_Extension)
  6701. argExprIdx--;
  6702. bool isThis = (paramIdx == -1) || ((methodDef->mHasExplicitThis) && (paramIdx == 0));
  6703. bool isDirectPass = false;
  6704. if (paramIdx >= (int)methodInstance->GetParamCount())
  6705. {
  6706. if (methodInstance->IsVarArgs())
  6707. {
  6708. if (argExprIdx >= (int)argValues.size())
  6709. break;
  6710. BfTypedValue argValue = ResolveArgValue(argValues[argExprIdx], NULL);
  6711. if (argValue)
  6712. {
  6713. auto typeInst = argValue.mType->ToTypeInstance();
  6714. if (argValue.mType == mModule->GetPrimitiveType(BfTypeCode_Float))
  6715. argValue = mModule->Cast(argValues[argExprIdx].mExpression, argValue, mModule->GetPrimitiveType(BfTypeCode_Double));
  6716. if ((typeInst != NULL) && (typeInst->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  6717. {
  6718. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  6719. BfType* charPtrType = mModule->CreatePointerType(charType);
  6720. argValue = mModule->Cast(argValues[argExprIdx].mExpression, argValue, charPtrType);
  6721. }
  6722. PushArg(argValue, irArgs, true, false);
  6723. }
  6724. argIdx++;
  6725. continue;
  6726. }
  6727. if (argExprIdx < (int)argValues.size())
  6728. {
  6729. if (mModule->PreFail())
  6730. {
  6731. BfAstNode* errorRef = argValues[argExprIdx].mExpression;
  6732. if (errorRef == NULL)
  6733. errorRef = targetSrc;
  6734. BfError* error;
  6735. if ((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0)
  6736. {
  6737. int checkIdx = argExprIdx - 1;
  6738. while (checkIdx >= 0)
  6739. {
  6740. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  6741. {
  6742. errorRef = argValues[checkIdx].mExpression;
  6743. break;
  6744. }
  6745. checkIdx--;
  6746. }
  6747. error = mModule->Fail("Expanded string interpolation generates too many arguments. If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  6748. }
  6749. else if ((prevBindResult.mPrevVal != NULL) && (prevBindResult.mPrevVal->mBindType != NULL))
  6750. error = mModule->Fail(StrFormat("Method '%s' has too few parameters to bind to '%s'.", mModule->MethodToString(methodInstance).c_str(), mModule->TypeToString(prevBindResult.mPrevVal->mBindType).c_str()), errorRef);
  6751. else
  6752. error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", (int)argValues.size() - argExprIdx), errorRef);
  6753. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  6754. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  6755. }
  6756. failed = true;
  6757. break;
  6758. }
  6759. break;
  6760. }
  6761. // Only create actual params if we're not just trying to bind the function
  6762. if ((prevBindResult.mPrevVal != NULL) && (!prevBindResult.mPrevVal->mWantsArgs))
  6763. break;
  6764. BfType* wantType = NULL;
  6765. bool wantsSplat = false;
  6766. if (expandedParamsElementType != NULL)
  6767. {
  6768. wantType = expandedParamsElementType;
  6769. }
  6770. else
  6771. {
  6772. wantsSplat = methodInstance->GetParamIsSplat(paramIdx) && (!IsComptime());
  6773. if (methodInstance->IsImplicitCapture(paramIdx))
  6774. {
  6775. auto paramType = methodInstance->GetParamType(paramIdx);
  6776. if (mModule->mCurMethodInstance->IsMixin())
  6777. {
  6778. // Don't bother, also- can fail on captures
  6779. }
  6780. else
  6781. {
  6782. // static int captureIdx = 0;
  6783. // captureIdx++;
  6784. // int curCaptureIdx = captureIdx;
  6785. //
  6786. // if (curCaptureIdx == 0x91)
  6787. // {
  6788. // NOP;
  6789. // }
  6790. auto lookupVal = DoImplicitArgCapture(targetSrc, methodInstance, paramIdx, failed, BfImplicitParamKind_General, origTarget);
  6791. if (lookupVal)
  6792. {
  6793. if (wantsSplat)
  6794. {
  6795. SplatArgs(lookupVal, irArgs);
  6796. }
  6797. else if (paramType->IsRef())
  6798. {
  6799. irArgs.push_back(lookupVal.mValue);
  6800. }
  6801. else
  6802. PushArg(lookupVal, irArgs, true);
  6803. }
  6804. }
  6805. paramIdx++;
  6806. continue;
  6807. }
  6808. wantType = methodInstance->GetParamType(paramIdx);
  6809. if (!mModule->mCurTypeInstance->IsInterface())
  6810. {
  6811. // Resolve `Self` types
  6812. if (wantType->IsUnspecializedTypeVariation())
  6813. {
  6814. wantType = mModule->ResolveSelfType(wantType, methodInstance->GetOwner());
  6815. }
  6816. }
  6817. if (IsVar(wantType))
  6818. {
  6819. // Case happens when we can't find the argument type
  6820. failed = true;
  6821. }
  6822. BfParamKind paramKind = methodInstance->GetParamKind(paramIdx);
  6823. if (paramKind == BfParamKind_Params)
  6824. {
  6825. //TODO: Check to see if it's a direct array pass
  6826. if (argIdx < (int)argValues.size())
  6827. {
  6828. auto argValue = argValues[argIdx].mTypedValue;
  6829. if ((argValue.IsParams()) /*&& (mModule->CanCast(argValue, wantType))*/)
  6830. isDirectPass = true;
  6831. }
  6832. if (!isDirectPass)
  6833. {
  6834. int numElements = BF_MAX((int)argValues.size() - argIdx, 0);
  6835. if (methodDef->mMethodType == BfMethodType_Extension)
  6836. numElements++;
  6837. if (IsConstEval())
  6838. {
  6839. if ((wantType->IsArray()) || (wantType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  6840. {
  6841. auto genericTypeInst = wantType->ToGenericTypeInstance();
  6842. expandedParamsElementType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  6843. auto irSizedArrayType = mModule->mBfIRBuilder->GetSizedArrayType(mModule->mBfIRBuilder->MapType(expandedParamsElementType), numElements);
  6844. Array<BfIRValue> values;
  6845. for (int i = 0; i < numElements; i++)
  6846. values.Add(mModule->mBfIRBuilder->GetFakeVal());
  6847. expandedParamsArray = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(irSizedArrayType, values), wantType);
  6848. PushArg(expandedParamsArray, irArgs);
  6849. }
  6850. continue;
  6851. }
  6852. else if (wantType->IsArray())
  6853. {
  6854. BfArrayType* arrayType = (BfArrayType*)wantType;
  6855. mModule->PopulateType(arrayType, BfPopulateType_DataAndMethods);
  6856. expandedParamsElementType = arrayType->mGenericTypeInfo->mTypeGenericArguments[0];
  6857. int arrayClassSize = arrayType->mInstSize - expandedParamsElementType->mSize;
  6858. expandedParamsArray = BfTypedValue(mModule->AllocFromType(arrayType->GetUnderlyingType(), boxScopeData, BfIRValue(), mModule->GetConstValue(numElements), 1, BfAllocFlags_None),
  6859. arrayType, false);
  6860. BfResolvedArgs resolvedArgs;
  6861. MatchConstructor(targetSrc, NULL, expandedParamsArray, arrayType, resolvedArgs, false, false);
  6862. //TODO: Assert 'length' var is at slot 1
  6863. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(expandedParamsArray.mValue, mModule->mBfIRBuilder->MapType(arrayType->mBaseType));
  6864. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  6865. if (arrayLengthBitCount == 0)
  6866. {
  6867. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", targetSrc);
  6868. return BfTypedValue();
  6869. }
  6870. auto& fieldInstance = arrayType->mBaseType->mFieldInstances[0];
  6871. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, fieldInstance.mDataIdx);
  6872. if (arrayLengthBitCount == 64)
  6873. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue64(numElements), addr, 8);
  6874. else
  6875. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue32(numElements), addr, 4);
  6876. PushArg(expandedParamsArray, irArgs);
  6877. continue;
  6878. }
  6879. else if (wantType->IsInstanceOf(mModule->mCompiler->mSpanTypeDef))
  6880. {
  6881. mModule->PopulateType(wantType);
  6882. mModule->mBfIRBuilder->PopulateType(wantType);
  6883. auto genericTypeInst = wantType->ToGenericTypeInstance();
  6884. expandedParamsElementType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0];
  6885. expandedParamsArray = BfTypedValue(mModule->CreateAlloca(wantType), wantType, true);
  6886. expandedParamAlloca = mModule->CreateAlloca(genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[0], true, NULL, mModule->GetConstValue(numElements));
  6887. mModule->mBfIRBuilder->CreateAlignedStore(expandedParamAlloca, mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 1), mModule->mSystem->mPtrSize);
  6888. mModule->mBfIRBuilder->CreateAlignedStore(mModule->GetConstValue(numElements), mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, 2), mModule->mSystem->mPtrSize);
  6889. PushArg(expandedParamsArray, irArgs, !wantsSplat);
  6890. continue;
  6891. }
  6892. else if (wantType->IsSizedArray())
  6893. {
  6894. mModule->PopulateType(wantType);
  6895. mModule->mBfIRBuilder->PopulateType(wantType);
  6896. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)wantType;
  6897. expandedParamsElementType = wantType->GetUnderlyingType();
  6898. if (numElements != sizedArrayType->mElementCount)
  6899. {
  6900. BfAstNode* refNode = targetSrc;
  6901. if (argExprIdx < (int)argValues.size())
  6902. refNode = argValues[argExprIdx].mExpression;
  6903. mModule->Fail(StrFormat("Incorrect number of arguments to match params type '%s'", mModule->TypeToString(wantType).c_str()), refNode);
  6904. }
  6905. expandedParamsArray = BfTypedValue(mModule->CreateAlloca(wantType), wantType, true);
  6906. expandedParamAlloca = mModule->mBfIRBuilder->CreateBitCast(expandedParamsArray.mValue, mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(expandedParamsElementType)));
  6907. PushArg(expandedParamsArray, irArgs, !wantsSplat);
  6908. continue;
  6909. }
  6910. }
  6911. }
  6912. }
  6913. BfAstNode* arg = NULL;
  6914. bool hadMissingArg = false;
  6915. if (argExprIdx == -1)
  6916. arg = targetSrc;
  6917. if (argExprIdx >= 0)
  6918. {
  6919. if (argExprIdx < (int)argValues.size())
  6920. {
  6921. arg = argValues[argExprIdx].mExpression;
  6922. if (((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0) && (!expandedParamsArray))
  6923. {
  6924. BfAstNode* errorRef = arg;
  6925. int checkIdx = argExprIdx - 1;
  6926. while (checkIdx >= 0)
  6927. {
  6928. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  6929. {
  6930. errorRef = argValues[checkIdx].mExpression;
  6931. break;
  6932. }
  6933. checkIdx--;
  6934. }
  6935. mModule->Warn(BfWarning_BF4205_StringInterpolationParam, "Expanded string interpolation argument not used as 'params'. If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  6936. }
  6937. // if ((arg == NULL) && (argValues[argExprIdx].mExpression != NULL))
  6938. // hadMissingArg = true;
  6939. if ((arg == NULL) && (!argValues[argExprIdx].mTypedValue))
  6940. hadMissingArg = true;
  6941. }
  6942. else
  6943. hadMissingArg = true;
  6944. }
  6945. BfTypedValue argValue;
  6946. if (hadMissingArg)
  6947. {
  6948. if (expandedParamsArray)
  6949. break;
  6950. if ((argIdx >= (int) methodInstance->mDefaultValues.size()) || (!methodInstance->mDefaultValues[argIdx]))
  6951. {
  6952. BfAstNode* refNode = targetSrc;
  6953. if (argValues.size() > 0)
  6954. {
  6955. auto checkExpr = argValues.back().mExpression;
  6956. if (checkExpr != NULL)
  6957. refNode = checkExpr;
  6958. }
  6959. BfAstNode* prevNode = NULL;
  6960. if (targetSrc == NULL)
  6961. {
  6962. // We must be in BfModule::EmitCtorBody
  6963. }
  6964. else if (auto tupleExpr = BfNodeDynCastExact<BfTupleExpression>(targetSrc))
  6965. {
  6966. if (tupleExpr->mCommas.size() > 0)
  6967. prevNode = tupleExpr->mCommas.back();
  6968. else
  6969. prevNode = tupleExpr->mOpenParen;
  6970. if (tupleExpr->mCloseParen != NULL)
  6971. refNode = tupleExpr->mCloseParen;
  6972. }
  6973. else if (mModule->mParentNodeEntry != NULL)
  6974. {
  6975. if (auto objectCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(mModule->mParentNodeEntry->mNode))
  6976. {
  6977. if (objectCreateExpr->mCommas.size() > 0)
  6978. prevNode = objectCreateExpr->mCommas.back();
  6979. else
  6980. prevNode = objectCreateExpr->mOpenToken;
  6981. if (objectCreateExpr->mCloseToken != NULL)
  6982. refNode = objectCreateExpr->mCloseToken;
  6983. if (auto newNode = BfNodeDynCast<BfNewNode>(objectCreateExpr->mNewNode))
  6984. {
  6985. if (newNode->mAllocNode == targetSrc)
  6986. refNode = targetSrc;
  6987. }
  6988. }
  6989. else if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  6990. {
  6991. if (invokeExpr->mCommas.size() > 0)
  6992. prevNode = invokeExpr->mCommas.back();
  6993. else
  6994. prevNode = invokeExpr->mOpenParen;
  6995. if (invokeExpr->mCloseParen != NULL)
  6996. refNode = invokeExpr->mCloseParen;
  6997. }
  6998. }
  6999. if ((autoComplete != NULL) && (prevNode != NULL))
  7000. autoComplete->CheckEmptyStart(prevNode, wantType);
  7001. BfError* error = NULL;
  7002. if (mModule->mParentNodeEntry != NULL)
  7003. {
  7004. bool showCtorError = false;
  7005. if (auto ctorDeclaration = BfNodeDynCast<BfConstructorDeclaration>(mModule->mParentNodeEntry->mNode))
  7006. {
  7007. if (ctorDeclaration->mInitializer == NULL)
  7008. showCtorError = true;
  7009. }
  7010. if (auto typerDecl = BfNodeDynCast<BfTypeDeclaration>(mModule->mParentNodeEntry->mNode))
  7011. showCtorError = true;
  7012. if (showCtorError)
  7013. {
  7014. if (mModule->PreFail())
  7015. {
  7016. error = mModule->Fail(StrFormat("No parameterless constructor is available for base class. Consider calling base constructor '%s'.",
  7017. mModule->MethodToString(methodInstance).c_str()), refNode);
  7018. }
  7019. auto srcNode = mModule->mCurMethodInstance->mMethodDef->GetRefNode();
  7020. if ((autoComplete != NULL) && (autoComplete->CheckFixit(srcNode)))
  7021. autoComplete->FixitAddConstructor(mModule->mCurTypeInstance);
  7022. }
  7023. }
  7024. if (mModule->PreFail())
  7025. {
  7026. if (error == NULL)
  7027. {
  7028. if (hasNamedArgs)
  7029. error = mModule->Fail(StrFormat("There is no argument given that corresponds to the required formal parameter '%s' of '%s'.",
  7030. methodInstance->GetParamName(paramIdx).c_str(), mModule->MethodToString(methodInstance).c_str()), refNode);
  7031. else
  7032. error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", methodInstance->GetParamCount() - paramIdx), refNode);
  7033. }
  7034. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  7035. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  7036. }
  7037. failed = true;
  7038. break;
  7039. }
  7040. auto foreignDefaultVal = methodInstance->mDefaultValues[argIdx];
  7041. auto foreignConst = methodInstance->GetOwner()->mConstHolder->GetConstant(foreignDefaultVal.mValue);
  7042. if (foreignConst->mConstType == BfConstType_AggZero)
  7043. {
  7044. // Allow this
  7045. }
  7046. else if (foreignConst->mTypeCode == BfTypeCode_NullPtr)
  7047. {
  7048. if (wantType->IsNullable())
  7049. {
  7050. argValue = mModule->GetDefaultTypedValue(wantType, false, BfDefaultValueKind_Addr);
  7051. }
  7052. }
  7053. else if (foreignConst->mConstType == BfConstType_GlobalVar)
  7054. {
  7055. auto globalVar = (BfGlobalVar*)foreignConst;
  7056. if (globalVar->mName[0] == '#')
  7057. {
  7058. if (strcmp(globalVar->mName, "#CallerLineNum") == 0)
  7059. {
  7060. argValue = BfTypedValue(mModule->GetConstValue(mModule->mCurFilePosition.mCurLine + 1), mModule->GetPrimitiveType(BfTypeCode_Int32));
  7061. }
  7062. else if (strcmp(globalVar->mName, "#CallerFilePath") == 0)
  7063. {
  7064. String filePath = "";
  7065. if (mModule->mCurFilePosition.mFileInstance != NULL)
  7066. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  7067. argValue = BfTypedValue(mModule->GetStringObjectValue(filePath),
  7068. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7069. }
  7070. else if (strcmp(globalVar->mName, "#CallerFileName") == 0)
  7071. {
  7072. String filePath = "";
  7073. if (mModule->mCurFilePosition.mFileInstance != NULL)
  7074. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  7075. argValue = BfTypedValue(mModule->GetStringObjectValue(GetFileName(filePath)),
  7076. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7077. }
  7078. else if (strcmp(globalVar->mName, "#CallerFileDir") == 0)
  7079. {
  7080. String filePath = "";
  7081. if (mModule->mCurFilePosition.mFileInstance != NULL)
  7082. filePath = mModule->mCurFilePosition.mFileInstance->mParser->mFileName;
  7083. argValue = BfTypedValue(mModule->GetStringObjectValue(GetFileDir(filePath)),
  7084. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7085. }
  7086. else if (strcmp(globalVar->mName, "#CallerTypeName") == 0)
  7087. {
  7088. String typeName = "";
  7089. if (mModule->mCurTypeInstance != NULL)
  7090. typeName = mModule->TypeToString(mModule->mCurTypeInstance);
  7091. argValue = BfTypedValue(mModule->GetStringObjectValue(typeName),
  7092. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7093. }
  7094. else if (strcmp(globalVar->mName, "#CallerType") == 0)
  7095. {
  7096. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  7097. BfType* type = mModule->mCurTypeInstance;
  7098. if (type != NULL)
  7099. {
  7100. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  7101. argValue = BfTypedValue(mModule->CreateTypeDataRef(type), typeType);
  7102. }
  7103. }
  7104. else if (strcmp(globalVar->mName, "#CallerMemberName") == 0)
  7105. {
  7106. String memberName = "";
  7107. if (mModule->mCurMethodInstance != NULL)
  7108. memberName = mModule->MethodToString(mModule->mCurMethodInstance);
  7109. argValue = BfTypedValue(mModule->GetStringObjectValue(memberName),
  7110. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7111. }
  7112. else if (strcmp(globalVar->mName, "#CallerProject") == 0)
  7113. {
  7114. String projectName = "";
  7115. if (mModule->mCurMethodInstance != NULL)
  7116. projectName = mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mProject->mName;
  7117. argValue = BfTypedValue(mModule->GetStringObjectValue(projectName),
  7118. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7119. }
  7120. else if (strcmp(globalVar->mName, "#ProjectName") == 0)
  7121. {
  7122. String projectName = methodInstance->mMethodDef->mDeclaringType->mProject->mName;
  7123. argValue = BfTypedValue(mModule->GetStringObjectValue(projectName),
  7124. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7125. }
  7126. else
  7127. {
  7128. argValue = mModule->GetCompilerFieldValue(globalVar->mName);
  7129. }
  7130. }
  7131. }
  7132. else if (foreignConst->mConstType == BfConstType_GEP32_2)
  7133. {
  7134. auto constGep32_2 = (BfConstantGEP32_2*)foreignConst;
  7135. auto gepTarget = methodInstance->GetOwner()->mConstHolder->GetConstantById(constGep32_2->mTarget);
  7136. if (gepTarget->mConstType == BfConstType_GlobalVar)
  7137. {
  7138. auto globalVar = (BfGlobalVar*)gepTarget;
  7139. if (globalVar->mName[0] == '#')
  7140. {
  7141. if (strcmp(globalVar->mName, "#CallerExpression") == 0)
  7142. {
  7143. int exprIdx = constGep32_2->mIdx1;
  7144. if ((exprIdx >= 0) && (exprIdx < (int)argValues.size()))
  7145. {
  7146. auto expr = argValues[exprIdx].mExpression;
  7147. if (expr != NULL)
  7148. {
  7149. argValue = BfTypedValue(mModule->GetStringObjectValue(expr->ToString()),
  7150. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7151. }
  7152. }
  7153. else
  7154. {
  7155. mModule->Fail("CallerExpression index out of bounds", targetSrc);
  7156. argValue = BfTypedValue(mModule->GetStringObjectValue(""),
  7157. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  7158. }
  7159. }
  7160. }
  7161. }
  7162. }
  7163. if (!argValue)
  7164. {
  7165. argValue = mModule->GetTypedValueFromConstant(foreignConst, methodInstance->GetOwner()->mConstHolder, foreignDefaultVal.mType);
  7166. if (!argValue)
  7167. mModule->Fail("Default parameter value failed", targetSrc);
  7168. mModule->mBfIRBuilder->PopulateType(foreignDefaultVal.mType);
  7169. }
  7170. }
  7171. else
  7172. {
  7173. if (argExprIdx == -1)
  7174. argValue = target;
  7175. else
  7176. argValue = argValues[argExprIdx].mTypedValue;
  7177. if ((argValue.IsParams()) && (!isDirectPass))
  7178. {
  7179. BfAstNode* refNode = arg;
  7180. if (auto unaryOperatorExpr = BfNodeDynCast<BfUnaryOperatorExpression>(refNode))
  7181. refNode = unaryOperatorExpr->mOpToken;
  7182. mModule->Warn(0, "Unused 'params' expression", refNode);
  7183. }
  7184. if (wantType->IsMethodRef())
  7185. {
  7186. auto expr = argValues[argExprIdx].mExpression;
  7187. if (expr != NULL)
  7188. SetMethodElementType(expr);
  7189. if (!argValue)
  7190. argValue = mModule->CreateValueFromExpression(BfNodeDynCast<BfExpression>(arg), wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  7191. // Add any implicit captures now
  7192. auto methodRefType = (BfMethodRefType*)wantType;
  7193. BfMethodInstance* useMethodInstance = methodRefType->mMethodRef;
  7194. for (int dataIdx = 0; dataIdx < methodRefType->GetCaptureDataCount(); dataIdx++)
  7195. {
  7196. int paramIdx = methodRefType->GetParamIdxFromDataIdx(dataIdx);
  7197. auto lookupVal = DoImplicitArgCapture(arg, useMethodInstance, paramIdx, failed, BfImplicitParamKind_General, argValue);
  7198. if (lookupVal)
  7199. {
  7200. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  7201. SplatArgs(lookupVal, irArgs);
  7202. else
  7203. {
  7204. if (lookupVal.mType->IsComposite())
  7205. lookupVal = mModule->MakeAddressable(lookupVal, false);
  7206. irArgs.push_back(lookupVal.mValue);
  7207. }
  7208. }
  7209. }
  7210. paramIdx++;
  7211. argIdx++;
  7212. continue;
  7213. }
  7214. else if (argExprIdx >= 0)
  7215. {
  7216. BfParamKind paramKind = BfParamKind_Normal;
  7217. BfIdentifierNode* paramNameNode = NULL;
  7218. if (paramIdx < methodInstance->GetParamCount())
  7219. {
  7220. paramKind = methodInstance->GetParamKind(paramIdx);
  7221. paramNameNode = methodInstance->GetParamNameNode(paramIdx);
  7222. }
  7223. argValues[argExprIdx].mExpectedType = wantType;
  7224. argValue = ResolveArgValue(argValues[argExprIdx], wantType, NULL, paramKind, paramNameNode);
  7225. }
  7226. }
  7227. if (!argValue)
  7228. {
  7229. failed = true;
  7230. }
  7231. if ((arg != NULL) && (autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(arg)))
  7232. {
  7233. if (!autoComplete->mResultString.Contains('\r'))
  7234. {
  7235. String str;
  7236. str += methodInstance->GetParamName(paramIdx);
  7237. str += " @ ";
  7238. bool isCtor = methodInstance->mMethodDef->mMethodType == BfMethodType_Ctor;
  7239. if (isCtor)
  7240. str += methodInstance->GetOwner()->mTypeDef->mName->ToString();
  7241. else
  7242. str += methodInstance->mMethodDef->mName;
  7243. str += "(";
  7244. for (int i = isCtor ? 1 : 0; i < methodInstance->GetParamCount(); i++)
  7245. {
  7246. if (i > (isCtor ? 1 : 0))
  7247. str += ",";
  7248. if (i == paramIdx)
  7249. {
  7250. if (methodInstance->GetParamKind(paramIdx) == BfParamKind_Params)
  7251. str += "params ";
  7252. str += mModule->TypeToString(methodInstance->GetParamType(paramIdx));
  7253. }
  7254. }
  7255. str += ")";
  7256. if (!autoComplete->mResultString.StartsWith(":"))
  7257. autoComplete->mResultString.Clear();
  7258. int crPos = (int)autoComplete->mResultString.IndexOf('\n');
  7259. if (crPos == -1)
  7260. crPos = autoComplete->mResultString.mLength;
  7261. int insertPos = BF_MAX(1, crPos);
  7262. if (autoComplete->mResultString.IsEmpty())
  7263. autoComplete->mResultString += ":";
  7264. if (insertPos > 1)
  7265. str.Insert(0, '\r');
  7266. autoComplete->mResultString.Insert(insertPos, str);
  7267. }
  7268. }
  7269. if (argValue)
  7270. {
  7271. if ((isThis) && (argValue.mType->IsRef()))
  7272. {
  7273. // Convert a 'ref this' to a 'this*'
  7274. argValue.mType = mModule->CreatePointerType(argValue.mType->GetUnderlyingType());
  7275. }
  7276. BfAstNode* refNode = arg;
  7277. if (refNode == NULL)
  7278. refNode = targetSrc;
  7279. if ((wantType->IsRef()) && (!argValue.mType->IsRef()) &&
  7280. (((callFlags & BfCreateCallFlags_AllowImplicitRef) != 0) || (wantType->IsIn())))
  7281. {
  7282. auto underlyingType = wantType->GetUnderlyingType();
  7283. if (mModule->mCurMethodState != NULL)
  7284. {
  7285. SetAndRestoreValue<BfScopeData*> prevScopeData(mModule->mCurMethodState->mOverrideScope, boxScopeData);
  7286. argValue = mModule->Cast(refNode, argValue, underlyingType);
  7287. }
  7288. else
  7289. argValue = mModule->Cast(refNode, argValue, underlyingType, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  7290. if (argValue)
  7291. argValue = mModule->ToRef(argValue, (BfRefType*)wantType);
  7292. }
  7293. else
  7294. {
  7295. if (mModule->mCurMethodState != NULL)
  7296. {
  7297. SetAndRestoreValue<BfScopeData*> prevScopeData(mModule->mCurMethodState->mOverrideScope, boxScopeData);
  7298. argValue = mModule->Cast(refNode, argValue, wantType, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  7299. }
  7300. else
  7301. argValue = mModule->Cast(refNode, argValue, wantType, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  7302. }
  7303. if (!argValue)
  7304. {
  7305. if ((argExprIdx < (int)argValues.size()) && ((argValues[argExprIdx].mArgFlags & BfArgFlag_StringInterpolateArg) != 0))
  7306. {
  7307. BfAstNode* errorRef = NULL;
  7308. int checkIdx = argExprIdx - 1;
  7309. while (checkIdx >= 0)
  7310. {
  7311. if ((argValues[checkIdx].mArgFlags & BfArgFlag_StringInterpolateFormat) != 0)
  7312. {
  7313. errorRef = argValues[checkIdx].mExpression;
  7314. break;
  7315. }
  7316. checkIdx--;
  7317. }
  7318. if (errorRef != NULL)
  7319. mModule->Warn(0, "If string allocation was intended then consider adding a specifier such as 'scope'.", errorRef);
  7320. }
  7321. failed = true;
  7322. }
  7323. else if ((wantType->IsComposite()) && (!expandedParamsArray))
  7324. {
  7325. if (methodInstance->mIsIntrinsic)
  7326. {
  7327. // Intrinsics can handle structs either by value or address
  7328. }
  7329. else
  7330. {
  7331. // We need to make a temp and get the addr of that
  7332. if ((!wantsSplat) && (!argValue.IsValuelessType()) && (!argValue.IsAddr()) && (!IsConstEval()))
  7333. {
  7334. argValue = mModule->MakeAddressable(argValue);
  7335. }
  7336. }
  7337. }
  7338. else if (!wantType->IsRef())
  7339. argValue = mModule->LoadValue(argValue);
  7340. }
  7341. if ((argExprIdx != -1) && (argExprIdx < (int)argValues.size()) && ((argValues[argExprIdx].mArgFlags & BfArgFlag_Cascade) != 0))
  7342. {
  7343. mUsedAsStatement = true;
  7344. if (argValues[argExprIdx].mUncastedTypedValue)
  7345. argCascades.Add(argValues[argExprIdx].mUncastedTypedValue);
  7346. else
  7347. argCascades.Add(argValue);
  7348. }
  7349. if (expandedParamsArray)
  7350. {
  7351. if (argValue)
  7352. {
  7353. if (IsConstEval())
  7354. {
  7355. auto constant = mModule->mBfIRBuilder->GetConstant(expandedParamsArray.mValue);
  7356. BF_ASSERT(constant->mConstType == BfConstType_Agg);
  7357. auto constAgg = (BfConstantAgg*)constant;
  7358. constAgg->mValues[extendedParamIdx] = argValue.mValue;
  7359. }
  7360. else if (expandedParamAlloca)
  7361. {
  7362. argValue = mModule->LoadValue(argValue);
  7363. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamAlloca, extendedParamIdx);
  7364. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, addr, argValue.mType->mAlign);
  7365. }
  7366. else
  7367. {
  7368. auto firstElem = mModule->GetFieldByName(expandedParamsArray.mType->ToTypeInstance(), "mFirstElement");
  7369. if (firstElem != NULL)
  7370. {
  7371. argValue = mModule->LoadValue(argValue);
  7372. auto firstAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(expandedParamsArray.mValue, 0, firstElem->mDataIdx);
  7373. auto indexedAddr = mModule->CreateIndexedValue(argValue.mType, firstAddr, extendedParamIdx);
  7374. if (argValue.IsSplat())
  7375. mModule->AggregateSplatIntoAddr(argValue, indexedAddr);
  7376. else
  7377. mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, indexedAddr, argValue.mType->mAlign);
  7378. }
  7379. }
  7380. }
  7381. extendedParamIdx++;
  7382. }
  7383. else
  7384. {
  7385. if ((paramIdx == 0) && (methodInstance->GetParamName(paramIdx) == "this") && (wantType->IsPointer()))
  7386. {
  7387. auto underlyingType = wantType->GetUnderlyingType();
  7388. mModule->PopulateType(underlyingType, BfPopulateType_Data);
  7389. if ((underlyingType->IsValuelessType()) && (!underlyingType->IsVoid()))
  7390. {
  7391. // We don't actually pass a 'this' pointer for mut methods on valueless structs
  7392. argIdx++;
  7393. paramIdx++;
  7394. continue;
  7395. }
  7396. }
  7397. if (argValue)
  7398. {
  7399. if (isThis)
  7400. PushThis(targetSrc, argValue, methodInstance, irArgs);
  7401. else if (wantsSplat)
  7402. SplatArgs(argValue, irArgs);
  7403. else
  7404. PushArg(argValue, irArgs, true, false, methodInstance->mIsIntrinsic, methodInstance->mCallingConvention != BfCallingConvention_Unspecified);
  7405. }
  7406. paramIdx++;
  7407. }
  7408. argIdx++;
  7409. }
  7410. if (failed)
  7411. {
  7412. // Process the other unused arguments
  7413. while (argIdx < argValues.size())
  7414. {
  7415. mModule->AssertErrorState();
  7416. auto argValue = argValues[argIdx].mTypedValue;
  7417. if ((argValues[argIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval | BfArgFlag_VariableDeclaration | BfArgFlag_UninitializedExpr)) != 0)
  7418. {
  7419. if (!argValue)
  7420. {
  7421. auto expr = BfNodeDynCast<BfExpression>(argValues[argIdx].mExpression);
  7422. if (expr != NULL)
  7423. argValue = mModule->CreateValueFromExpression(expr);
  7424. }
  7425. }
  7426. argIdx++;
  7427. }
  7428. return mModule->GetDefaultTypedValue(returnType, false, BfDefaultValueKind_Addr);
  7429. }
  7430. prevBindResult.Restore();
  7431. if (!methodDef->mIsStatic)
  7432. {
  7433. bool ignoreVirtualError = (mModule->mBfIRBuilder->mIgnoreWrites) && (mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef);
  7434. if ((methodInstance->GetOwner()->IsInterface()) && (!target.mType->IsGenericParam()) && (!target.mType->IsConcreteInterfaceType()) &&
  7435. (!mModule->mCurTypeInstance->IsInterface()) && (!ignoreVirtualError))
  7436. {
  7437. if (methodInstance->mVirtualTableIdx == -1)
  7438. {
  7439. mModule->PopulateType(methodInstance->GetOwner(), BfPopulateType_DataAndMethods);
  7440. }
  7441. if (methodInstance->mVirtualTableIdx == -1)
  7442. {
  7443. if (methodInstance->mMethodDef->mIsConcrete)
  7444. {
  7445. 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);
  7446. }
  7447. else if (methodInstance->HasSelf())
  7448. {
  7449. 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);
  7450. }
  7451. else
  7452. {
  7453. if ((bypassVirtual) && (mModule->mCurTypeInstance->IsInterface()))
  7454. {
  7455. // Allow a base call to be defined
  7456. }
  7457. else if ((methodInstance->IsSpecializedGenericMethod()) && (origTarget) && (!origTarget.mType->IsInterface()))
  7458. {
  7459. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  7460. mModule->AssertErrorState();
  7461. }
  7462. else if ((!mModule->mCurMethodInstance->mIsUnspecialized))
  7463. {
  7464. // Compiler error?
  7465. String errorString = "Unable to dynamically dispatch '%s'";
  7466. if (methodInstance->IsSpecializedGenericMethod())
  7467. errorString = "Unable to dynamically dispatch '%s' because generic methods can only be directly dispatched";
  7468. if (methodInstance->mReturnType->IsConcreteInterfaceType())
  7469. errorString = "Unable to dynamically dispatch '%s' because the concrete return type is unknown";
  7470. mModule->Fail(StrFormat(errorString.c_str(), mModule->MethodToString(methodInstance).c_str()), targetSrc);
  7471. }
  7472. //BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  7473. }
  7474. if (mFunctionBindResult != NULL)
  7475. {
  7476. mFunctionBindResult->mMethodInstance = methodInstance;
  7477. mFunctionBindResult->mTarget = target;
  7478. mFunctionBindResult->mFunc = moduleMethodInstance.mFunc;
  7479. for (auto arg : irArgs)
  7480. mFunctionBindResult->mIRArgs.push_back(arg);
  7481. }
  7482. return mModule->GetDefaultTypedValue(returnType);
  7483. }
  7484. }
  7485. }
  7486. else
  7487. {
  7488. //BF_ASSERT(!methodInstance->GetOwner()->IsInterface());
  7489. }
  7490. if (target.mType != NULL)
  7491. {
  7492. // When we call a method from a static ctor, that method could access static fields so we need to make sure
  7493. // the type has been initialized
  7494. auto targetTypeInst = target.mType->ToTypeInstance();
  7495. if (targetTypeInst != NULL)
  7496. mModule->CheckStaticAccess(targetTypeInst);
  7497. }
  7498. if (methodInstance->mReturnType == NULL)
  7499. {
  7500. mModule->AssertErrorState();
  7501. mModule->Fail("Circular reference in method instance", targetSrc);
  7502. return BfTypedValue();
  7503. }
  7504. BfCreateCallFlags physCallFlags = BfCreateCallFlags_None;
  7505. if ((origTarget.mType != NULL) && (origTarget.mType->IsGenericParam()))
  7506. physCallFlags = (BfCreateCallFlags)(physCallFlags | BfCreateCallFlags_GenericParamThis);
  7507. auto func = moduleMethodInstance.mFunc;
  7508. BfTypedValue callResult = CreateCall(targetSrc, methodInstance, func, bypassVirtual, irArgs, NULL, physCallFlags, origTarget.mType);
  7509. if ((methodInstance->mMethodDef->mIsNoReturn) && ((mBfEvalExprFlags & BfEvalExprFlags_IsExpressionBody) != 0) &&
  7510. (mExpectingType != NULL) && (callResult.mType != mExpectingType))
  7511. {
  7512. callResult = mModule->GetDefaultTypedValue(mExpectingType);
  7513. }
  7514. // This gets triggered for non-sret (ie: comptime) composite returns so they aren't considered readonly
  7515. if ((callResult.mKind == BfTypedValueKind_Value) && (!callResult.mValue.IsConst()) &&
  7516. (!callResult.mType->IsValuelessType()) && (callResult.mType->IsComposite()) && (!methodInstance->GetLoweredReturnType()))
  7517. {
  7518. bool makeAddressable = true;
  7519. auto typeInstance = callResult.mType->ToTypeInstance();
  7520. if ((typeInstance != NULL) && (typeInstance->mHasUnderlyingArray))
  7521. makeAddressable = false;
  7522. if (makeAddressable)
  7523. {
  7524. callResult = mModule->MakeAddressable(callResult, true);
  7525. }
  7526. }
  7527. if (argCascades.mSize == 1)
  7528. {
  7529. if (argCascade == NULL)
  7530. return argCascades[0];
  7531. *argCascade = argCascades[0];
  7532. }
  7533. if (argCascades.mSize > 1)
  7534. {
  7535. if (argCascade == NULL)
  7536. return mModule->CreateTuple(argCascades, {});
  7537. *argCascade = mModule->CreateTuple(argCascades, {});
  7538. }
  7539. return callResult;
  7540. }
  7541. BfTypedValue BfExprEvaluator::MatchConstructor(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, BfTypeInstance* targetType, BfResolvedArgs& argValues, bool callCtorBodyOnly, bool allowAppendAlloc, BfTypedValue* appendIndexValue)
  7542. {
  7543. // Temporarily disable so we don't capture calls in params
  7544. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  7545. static int sCtorCount = 0;
  7546. sCtorCount++;
  7547. BfMethodMatcher methodMatcher(targetSrc, mModule, "", argValues.mResolvedArgs, BfMethodGenericArguments());
  7548. methodMatcher.mBfEvalExprFlags = mBfEvalExprFlags;
  7549. BfTypeVector typeGenericArguments;
  7550. auto curTypeInst = targetType;
  7551. auto curTypeDef = targetType->mTypeDef;
  7552. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  7553. auto activeTypeDef = mModule->GetActiveTypeDef();
  7554. auto visibleProjectSet = mModule->GetVisibleProjectSet();
  7555. bool isFailurePass = false;
  7556. for (int pass = 0; pass < 2; pass++)
  7557. {
  7558. isFailurePass = pass == 1;
  7559. curTypeDef->PopulateMemberSets();
  7560. BfMethodDef* nextMethodDef = NULL;
  7561. BfMemberSetEntry* entry;
  7562. if (curTypeDef->mMethodSet.TryGetWith(String("__BfCtor"), &entry))
  7563. nextMethodDef = (BfMethodDef*)entry->mMemberDef;
  7564. while (nextMethodDef != NULL)
  7565. {
  7566. auto checkMethod = nextMethodDef;
  7567. nextMethodDef = nextMethodDef->mNextWithSameName;
  7568. if ((isFailurePass) && (checkMethod->mMethodDeclaration == NULL))
  7569. continue; // Don't match private default ctor if there's a user-defined one
  7570. if (checkMethod->mIsStatic)
  7571. continue;
  7572. if ((checkMethod->mDeclaringType->IsExtension()) && (mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) &&
  7573. (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mNoExtensionAttributeTypeDef)))
  7574. {
  7575. mModule->mAttributeState->mUsed = true;
  7576. continue;
  7577. }
  7578. if (!mModule->IsInSpecializedSection())
  7579. {
  7580. if ((!curTypeInst->IsTypeMemberIncluded(checkMethod->mDeclaringType, activeTypeDef, mModule)) ||
  7581. (!curTypeInst->IsTypeMemberAccessible(checkMethod->mDeclaringType, visibleProjectSet)))
  7582. continue;
  7583. }
  7584. auto checkProt = checkMethod->mProtection;
  7585. if (!isFailurePass)
  7586. {
  7587. if (callCtorBodyOnly)
  7588. {
  7589. if (curTypeDef != mModule->mCurTypeInstance->mTypeDef)
  7590. {
  7591. // We're calling the base class's ctor from a derived class
  7592. if (checkProt <= BfProtection_Private)
  7593. continue;
  7594. }
  7595. }
  7596. else
  7597. {
  7598. if ((checkProt == BfProtection_Protected) || (checkProt == BfProtection_ProtectedInternal)) // Treat protected constructors as private
  7599. checkProt = BfProtection_Private;
  7600. if (!mModule->CheckProtection(protectionCheckFlags, curTypeInst, checkMethod->mDeclaringType->mProject, checkProt, curTypeInst))
  7601. continue;
  7602. }
  7603. }
  7604. methodMatcher.CheckMethod(NULL, curTypeInst, checkMethod, isFailurePass);
  7605. }
  7606. if ((methodMatcher.mBestMethodDef != NULL) || (methodMatcher.mBackupMethodDef != NULL))
  7607. break;
  7608. }
  7609. if (methodMatcher.mBestMethodDef == NULL)
  7610. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  7611. if (methodMatcher.mBestMethodDef == NULL)
  7612. {
  7613. mModule->Fail("No constructor available", targetSrc);
  7614. return BfTypedValue();
  7615. }
  7616. auto methodDef = methodMatcher.mBestMethodDef;
  7617. if (mModule->mCompiler->mResolvePassData != NULL)
  7618. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetSrc, curTypeInst->mTypeDef->GetDefinition(), methodDef);
  7619. // There should always be a constructor
  7620. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  7621. auto moduleMethodInstance = mModule->GetMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher.mBestMethodGenericArguments);
  7622. if (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc))
  7623. {
  7624. return BfTypedValue();
  7625. }
  7626. BfAutoComplete* autoComplete = GetAutoComplete();
  7627. if (autoComplete != NULL)
  7628. {
  7629. BfTypeInstance* resolvedTypeInstance = target.mType->ToTypeInstance();
  7630. auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(methodDef->mMethodDeclaration);
  7631. if ((autoComplete->mIsGetDefinition) && (autoComplete->IsAutocompleteNode(targetSrc)) && (!BfNodeIsA<BfDelegateBindExpression>(targetSrc)))
  7632. {
  7633. if ((autoComplete->mDefMethod == NULL) && (autoComplete->mDefField == NULL) &&
  7634. (autoComplete->mDefProp == NULL)
  7635. && ((autoComplete->mDefType == NULL) || (autoComplete->mDefType == resolvedTypeInstance->mTypeDef)))
  7636. {
  7637. // Do we need to do this mDefType setting? If we do, then make sure we only get the element type of generics and such
  7638. //autoComplete->mDefType = resolvedTypeInstance->mTypeDef;
  7639. if (ctorDecl != NULL)
  7640. autoComplete->SetDefinitionLocation(ctorDecl->mThisToken, true);
  7641. else if (resolvedTypeInstance->mTypeDef->mTypeDeclaration != NULL)
  7642. autoComplete->SetDefinitionLocation(resolvedTypeInstance->mTypeDef->mTypeDeclaration->mNameNode, true);
  7643. }
  7644. }
  7645. else if ((autoComplete->mResolveType == BfResolveType_GetResultString) && (autoComplete->IsAutocompleteNode(targetSrc)) &&
  7646. (moduleMethodInstance.mMethodInstance != NULL))
  7647. {
  7648. autoComplete->mResultString = ":";
  7649. autoComplete->mResultString += mModule->MethodToString(moduleMethodInstance.mMethodInstance);
  7650. }
  7651. }
  7652. BfConstructorDeclaration* ctorDecl = (BfConstructorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration;
  7653. if ((methodMatcher.mBestMethodDef->mHasAppend) && (targetType->IsObject()))
  7654. {
  7655. if (!allowAppendAlloc)
  7656. {
  7657. if (mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration == NULL)
  7658. mModule->Fail("Constructors with append allocations cannot be called from a default constructor. Considering adding an explicit default constructor with the [AllowAppend] specifier.", targetSrc);
  7659. else
  7660. mModule->Fail("Constructors with append allocations cannot be called from a constructor without [AllowAppend] specified.", targetSrc);
  7661. }
  7662. else
  7663. {
  7664. BfResolvedArg resolvedArg;
  7665. if (appendIndexValue != NULL)
  7666. {
  7667. resolvedArg.mTypedValue = *appendIndexValue;
  7668. }
  7669. else
  7670. {
  7671. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  7672. auto intPtrRefType = mModule->CreateRefType(intPtrType);
  7673. if (target.mValue.IsFake())
  7674. {
  7675. resolvedArg.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), intPtrRefType);
  7676. }
  7677. else
  7678. {
  7679. BFMODULE_FATAL(mModule, "Bad");
  7680. }
  7681. }
  7682. methodMatcher.mArguments.Insert(0, resolvedArg);
  7683. }
  7684. }
  7685. if (isFailurePass)
  7686. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  7687. prevBindResult.Restore();
  7688. return CreateCall(methodMatcher.mTargetSrc, target, BfTypedValue(), methodMatcher.mBestMethodDef, moduleMethodInstance, BfCreateCallFlags_None, methodMatcher.mArguments);
  7689. }
  7690. static int sInvocationIdx = 0;
  7691. BfTypedValue BfExprEvaluator::ResolveArgValue(BfResolvedArg& resolvedArg, BfType* wantType, BfTypedValue* receivingValue, BfParamKind paramKind, BfIdentifierNode* paramNameNode)
  7692. {
  7693. BfTypedValue argValue = resolvedArg.mTypedValue;
  7694. if ((resolvedArg.mArgFlags & BfArgFlag_Finalized) != 0)
  7695. return argValue;
  7696. if ((resolvedArg.mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt | BfArgFlag_DeferredEval)) != 0)
  7697. {
  7698. if ((!argValue) || (argValue.mValue.IsFake()) || (resolvedArg.mWantsRecalc))
  7699. {
  7700. resolvedArg.mWantsRecalc = false;
  7701. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  7702. if (expr != NULL)
  7703. {
  7704. BfExprEvaluator exprEvaluator(mModule);
  7705. exprEvaluator.mReceivingValue = receivingValue;
  7706. BfEvalExprFlags flags = (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast);
  7707. if ((paramKind == BfParamKind_Params) || (paramKind == BfParamKind_DelegateParam))
  7708. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowParamsExpr);
  7709. argValue = mModule->CreateValueFromExpression(exprEvaluator, expr, wantType, flags);
  7710. if ((argValue) && (argValue.mType != wantType) && (wantType != NULL))
  7711. {
  7712. if ((mDeferScopeAlloc != NULL) && (wantType == mModule->mContext->mBfObjectType))
  7713. {
  7714. BfAllocTarget allocTarget(mDeferScopeAlloc);
  7715. argValue = mModule->BoxValue(expr, argValue, wantType, allocTarget, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  7716. }
  7717. else
  7718. argValue = mModule->Cast(expr, argValue, wantType, ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) ? BfCastFlags_WantsConst : BfCastFlags_None);
  7719. }
  7720. }
  7721. }
  7722. }
  7723. else if ((resolvedArg.mArgFlags & (BfArgFlag_DeferredValue)) != 0)
  7724. {
  7725. // We should have already had an error on the first call
  7726. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, mModule->mHadBuildError);
  7727. auto expr = BfNodeDynCast<BfExpression>(resolvedArg.mExpression);
  7728. BF_ASSERT(expr != NULL);
  7729. argValue = mModule->CreateValueFromExpression(expr, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr));
  7730. resolvedArg.mUncastedTypedValue = argValue;
  7731. if ((argValue) && (wantType != NULL))
  7732. argValue = mModule->Cast(expr, argValue, wantType);
  7733. }
  7734. else if ((resolvedArg.mArgFlags & (BfArgFlag_UntypedDefault)) != 0)
  7735. {
  7736. argValue = mModule->GetDefaultTypedValue(wantType);
  7737. }
  7738. else if ((resolvedArg.mArgFlags & (BfArgFlag_VariableDeclaration | BfArgFlag_UninitializedExpr)) != 0)
  7739. {
  7740. auto variableDeclaration = BfNodeDynCast<BfVariableDeclaration>(resolvedArg.mExpression);
  7741. auto variableType = wantType;
  7742. bool isLet = (variableDeclaration != NULL) && (variableDeclaration->mTypeRef->IsExact<BfLetTypeReference>());
  7743. bool isVar = (variableDeclaration == NULL) || (variableDeclaration->mTypeRef->IsExact<BfVarTypeReference>());
  7744. if (mModule->mCurMethodState->mPendingNullConditional != NULL)
  7745. {
  7746. mModule->Fail("Variables cannot be declared in method arguments inside null conditional expressions", variableDeclaration);
  7747. }
  7748. if ((!isLet) && (!isVar))
  7749. {
  7750. if (variableType->IsVar())
  7751. {
  7752. auto resolvedType = mModule->ResolveTypeRef(variableDeclaration->mTypeRef);
  7753. if (resolvedType != NULL)
  7754. variableType = resolvedType;
  7755. }
  7756. else
  7757. {
  7758. mModule->Fail("Only 'ref' or 'var' variables can be declared in method arguments", variableDeclaration);
  7759. auto autoComplete = GetAutoComplete();
  7760. if (autoComplete != NULL)
  7761. autoComplete->CheckTypeRef(variableDeclaration->mTypeRef, true, true);
  7762. }
  7763. }
  7764. else
  7765. {
  7766. if (variableType->IsVar())
  7767. {
  7768. mModule->Fail("Variable type required for 'var' parameter types", variableDeclaration);
  7769. }
  7770. }
  7771. if (wantType->IsRef())
  7772. {
  7773. auto refType = (BfRefType*)wantType;
  7774. variableType = refType->mElementType;
  7775. }
  7776. if ((variableDeclaration != NULL) && (variableDeclaration->mInitializer != NULL))
  7777. {
  7778. mModule->Fail("Initializers cannot be used when declaring variables for 'out' parameters", variableDeclaration->mEqualsNode);
  7779. mModule->CreateValueFromExpression(variableDeclaration->mInitializer, variableType, BfEvalExprFlags_NoCast);
  7780. }
  7781. BfLocalVariable* localVar = new BfLocalVariable();
  7782. if ((variableDeclaration != NULL) && (variableDeclaration->mNameNode != NULL))
  7783. {
  7784. localVar->mName = variableDeclaration->mNameNode->ToString();
  7785. localVar->mNameNode = BfNodeDynCast<BfIdentifierNode>(variableDeclaration->mNameNode);
  7786. }
  7787. else
  7788. {
  7789. if (paramNameNode != NULL)
  7790. {
  7791. localVar->mName = "__";
  7792. paramNameNode->ToString(localVar->mName);
  7793. localVar->mName += "_";
  7794. localVar->mName += StrFormat("%d", mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  7795. }
  7796. else
  7797. localVar->mName = "__" + StrFormat("%d", mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId);
  7798. }
  7799. localVar->mResolvedType = variableType;
  7800. if (!variableType->IsValuelessType())
  7801. localVar->mAddr = mModule->CreateAlloca(variableType);
  7802. localVar->mIsReadOnly = isLet;
  7803. localVar->mReadFromId = 0;
  7804. localVar->mWrittenToId = 0;
  7805. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  7806. mModule->CheckVariableDef(localVar);
  7807. localVar->Init();
  7808. mModule->AddLocalVariableDef(localVar, true);
  7809. CheckVariableDeclaration(resolvedArg.mExpression, false, false, false);
  7810. argValue = BfTypedValue(localVar->mAddr, mModule->CreateRefType(variableType, BfRefType::RefKind_Out));
  7811. auto curScope = mModule->mCurMethodState->mCurScope;
  7812. if (curScope->mScopeKind == BfScopeKind_StatementTarget)
  7813. {
  7814. // Move this variable into the parent scope
  7815. curScope->mLocalVarStart = (int)mModule->mCurMethodState->mLocals.size();
  7816. }
  7817. }
  7818. return argValue;
  7819. }
  7820. BfTypedValue BfExprEvaluator::CheckEnumCreation(BfAstNode* targetSrc, BfTypeInstance* enumType, const StringImpl& caseName, BfResolvedArgs& argValues)
  7821. {
  7822. auto activeTypeDef = mModule->GetActiveTypeDef();
  7823. mModule->PopulateType(enumType);
  7824. mModule->mBfIRBuilder->PopulateType(enumType);
  7825. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  7826. // if (resolvePassData != NULL)
  7827. // {
  7828. // if (mModule->mParentNodeEntry != NULL)
  7829. // {
  7830. // if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  7831. // {
  7832. // if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(invocationExpr->mTarget))
  7833. // {
  7834. // BfAstNode* dotNode = memberRefExpr->mDotToken;
  7835. // BfAstNode* nameNode = targetSrc;
  7836. // String filter;
  7837. // auto autoComplete = resolvePassData->mAutoComplete;
  7838. // if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(dotNode, nameNode, filter)))
  7839. // autoComplete->AddEnumTypeMembers(enumType, caseName, false, enumType == mModule->mCurTypeInstance);
  7840. // }
  7841. // }
  7842. // }
  7843. // }
  7844. for (int fieldIdx = 0; fieldIdx < (int)enumType->mFieldInstances.size(); fieldIdx++)
  7845. {
  7846. auto fieldInstance = &enumType->mFieldInstances[fieldIdx];
  7847. auto fieldDef = fieldInstance->GetFieldDef();
  7848. if (fieldDef == NULL)
  7849. continue;
  7850. if ((fieldInstance->mIsEnumPayloadCase) && (fieldDef->mName == caseName))
  7851. {
  7852. if ((!enumType->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, mModule)) ||
  7853. (!enumType->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  7854. continue;
  7855. auto autoComplete = GetAutoComplete();
  7856. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  7857. {
  7858. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  7859. methodMatchEntry.mPayloadEnumField = fieldInstance;
  7860. methodMatchEntry.mTypeInstance = enumType;
  7861. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  7862. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  7863. }
  7864. if (resolvePassData != NULL)
  7865. {
  7866. BfAstNode* nameNode = targetSrc;
  7867. if (resolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Field)
  7868. resolvePassData->HandleFieldReference(nameNode, enumType->mTypeDef, fieldDef);
  7869. }
  7870. BfIRValue enumValue;
  7871. BfTypedValue result;
  7872. bool wantConst = IsConstEval();
  7873. if (wantConst)
  7874. {
  7875. NOP;
  7876. }
  7877. else if ((mReceivingValue != NULL) && (mReceivingValue->mType == enumType) && (mReceivingValue->IsAddr()))
  7878. {
  7879. result = *mReceivingValue;
  7880. mReceivingValue = NULL;
  7881. enumValue = result.mValue;
  7882. }
  7883. else
  7884. {
  7885. mResultIsTempComposite = true;
  7886. enumValue = mModule->CreateAlloca(enumType);
  7887. result = BfTypedValue(enumValue, fieldInstance->mOwner, BfTypedValueKind_TempAddr);
  7888. }
  7889. BF_ASSERT(fieldInstance->mResolvedType->IsTuple());
  7890. auto tupleType = (BfTypeInstance*)fieldInstance->mResolvedType;
  7891. mModule->mBfIRBuilder->PopulateType(tupleType);
  7892. bool constFailed = false;
  7893. SizedArray<BfIRValue, 8> constTupleMembers;
  7894. BfIRValue fieldPtr;
  7895. BfIRValue tuplePtr;
  7896. if (wantConst)
  7897. {
  7898. constTupleMembers.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(tupleType->mBaseType)));
  7899. }
  7900. else if (!tupleType->IsValuelessType())
  7901. {
  7902. fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, 1);
  7903. auto tuplePtrType = mModule->CreatePointerType(tupleType);
  7904. auto mappedPtrType = mModule->mBfIRBuilder->MapType(tuplePtrType);
  7905. tuplePtr = mModule->mBfIRBuilder->CreateBitCast(fieldPtr, mappedPtrType);
  7906. }
  7907. for (int tupleFieldIdx = 0; tupleFieldIdx < (int)tupleType->mFieldInstances.size(); tupleFieldIdx++)
  7908. {
  7909. auto tupleFieldInstance = &tupleType->mFieldInstances[tupleFieldIdx];
  7910. auto resolvedFieldType = tupleFieldInstance->GetResolvedType();
  7911. if (tupleFieldIdx >= argValues.mResolvedArgs.size())
  7912. {
  7913. BfAstNode* refNode = targetSrc;
  7914. BfAstNode* prevNode = NULL;
  7915. if (mModule->mParentNodeEntry != NULL)
  7916. {
  7917. if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  7918. {
  7919. if (invokeExpr->mCloseParen != NULL)
  7920. refNode = invokeExpr->mCloseParen;
  7921. }
  7922. }
  7923. BfError* error = mModule->Fail(StrFormat("Not enough parameters specified, expected %d more.", tupleType->mFieldInstances.size() - (int)argValues.mArguments->size()), refNode);
  7924. if (error != NULL)
  7925. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  7926. if (wantConst)
  7927. constFailed = true;
  7928. break;
  7929. }
  7930. BfTypedValue receivingValue;
  7931. BfIRValue tupleFieldPtr;
  7932. if (tuplePtr)
  7933. {
  7934. tupleFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(tuplePtr, 0, tupleFieldInstance->mDataIdx);
  7935. receivingValue = BfTypedValue(tupleFieldPtr, tupleFieldInstance->mResolvedType, true);
  7936. }
  7937. auto argValue = ResolveArgValue(argValues.mResolvedArgs[tupleFieldIdx], resolvedFieldType, &receivingValue);
  7938. if (!argValue)
  7939. {
  7940. if (wantConst)
  7941. constFailed = true;
  7942. continue;
  7943. }
  7944. if (resolvedFieldType->IsValuelessType())
  7945. continue;
  7946. // Used receiving value?
  7947. if (argValue.mValue == receivingValue.mValue)
  7948. continue;
  7949. argValue = mModule->AggregateSplat(argValue);
  7950. argValues.mResolvedArgs[tupleFieldIdx].mExpectedType = resolvedFieldType;
  7951. if ((argValues.mResolvedArgs[tupleFieldIdx].mArgFlags & (BfArgFlag_DelegateBindAttempt | BfArgFlag_LambdaBindAttempt | BfArgFlag_UnqualifiedDotAttempt)) != 0)
  7952. {
  7953. auto expr = BfNodeDynCast<BfExpression>(argValues.mResolvedArgs[tupleFieldIdx].mExpression);
  7954. BF_ASSERT(expr != NULL);
  7955. argValue = mModule->CreateValueFromExpression(expr, resolvedFieldType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  7956. }
  7957. if (argValue)
  7958. {
  7959. if ((argValue.mType->IsRef()) && (argValue.mType->GetUnderlyingType() == resolvedFieldType))
  7960. {
  7961. if (auto unaryOperator = BfNodeDynCast<BfUnaryOperatorExpression>(argValues.mResolvedArgs[tupleFieldIdx].mExpression))
  7962. {
  7963. mModule->Fail(StrFormat("Invalid use of '%s'. Enum payloads can only be retrieved through 'case' expressions.", BfGetOpName(unaryOperator->mOp)), unaryOperator->mOpToken);
  7964. argValue = mModule->GetDefaultTypedValue(resolvedFieldType);
  7965. }
  7966. else if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(argValues.mResolvedArgs[tupleFieldIdx].mExpression))
  7967. {
  7968. mModule->Fail("Invalid variable declaration. Enum payloads can only be retrieved through 'case' expressions.", varDecl);
  7969. argValue = mModule->GetDefaultTypedValue(resolvedFieldType);
  7970. }
  7971. }
  7972. // argValue can have a value even if tuplePtr does not have a value. This can happen if we are assigning to a (void) tuple,
  7973. // but we have a value that needs to be attempted to be casted to void
  7974. argValue = mModule->Cast(argValues.mResolvedArgs[tupleFieldIdx].mExpression, argValue, resolvedFieldType, wantConst ? BfCastFlags_WantsConst : BfCastFlags_None);
  7975. if (wantConst)
  7976. {
  7977. if (!argValue.mValue.IsConst())
  7978. {
  7979. mModule->Fail("Field not const", argValues.mResolvedArgs[tupleFieldIdx].mExpression);
  7980. constFailed = true;
  7981. }
  7982. constTupleMembers.Add(argValue.mValue);
  7983. }
  7984. else if (tupleFieldPtr)
  7985. {
  7986. argValue = mModule->LoadValue(argValue);
  7987. if (argValue)
  7988. mModule->mBfIRBuilder->CreateAlignedStore(argValue.mValue, tupleFieldPtr, resolvedFieldType->mAlign);
  7989. }
  7990. }
  7991. else if (wantConst)
  7992. constFailed = true;
  7993. }
  7994. if ((intptr)argValues.mResolvedArgs.size() > tupleType->mFieldInstances.size())
  7995. {
  7996. BfAstNode* errorRef = argValues.mResolvedArgs[tupleType->mFieldInstances.size()].mExpression;
  7997. if (errorRef == NULL)
  7998. errorRef = targetSrc;
  7999. BfError* error = mModule->Fail(StrFormat("Too many arguments, expected %d fewer.", argValues.mResolvedArgs.size() - tupleType->mFieldInstances.size()), errorRef);
  8000. if (error != NULL)
  8001. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See enum declaration"), fieldDef->mFieldDeclaration);
  8002. if (wantConst)
  8003. constFailed = true;
  8004. }
  8005. auto dscrType = enumType->GetDiscriminatorType();
  8006. auto dscrField = &enumType->mFieldInstances.back();
  8007. int tagIdx = -fieldInstance->mDataIdx - 1;
  8008. if ((wantConst) && (!constFailed))
  8009. {
  8010. auto unionType = enumType->GetUnionInnerType();
  8011. auto constTuple = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(tupleType, BfIRPopulateType_Full), constTupleMembers);
  8012. Array<uint8> memArr;
  8013. memArr.Resize(unionType->mSize);
  8014. if (!mModule->mBfIRBuilder->WriteConstant(constTuple, memArr.mVals, tupleType))
  8015. {
  8016. constFailed = true;
  8017. }
  8018. else
  8019. {
  8020. auto unionValue = mModule->mBfIRBuilder->ReadConstant(memArr.mVals, unionType);
  8021. if (!unionValue)
  8022. {
  8023. constFailed = true;
  8024. }
  8025. else
  8026. {
  8027. SizedArray<BfIRValue, 3> constEnumMembers;
  8028. constEnumMembers.Add(mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(enumType->mBaseType, BfIRPopulateType_Full)));
  8029. constEnumMembers.Add(unionValue);
  8030. constEnumMembers.Add(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx));
  8031. return BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(enumType, BfIRPopulateType_Full), constEnumMembers), enumType);
  8032. }
  8033. }
  8034. }
  8035. if (constFailed)
  8036. {
  8037. return mModule->GetDefaultTypedValue(enumType, false, BfDefaultValueKind_Addr);
  8038. }
  8039. auto dscFieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(enumValue, 0, dscrField->mDataIdx);
  8040. mModule->mBfIRBuilder->CreateAlignedStore(mModule->mBfIRBuilder->CreateConst(dscrType->mTypeDef->mTypeCode, tagIdx), dscFieldPtr, 4);
  8041. return result;
  8042. }
  8043. }
  8044. return BfTypedValue();
  8045. }
  8046. bool BfExprEvaluator::CheckGenericCtor(BfGenericParamType* genericParamType, BfResolvedArgs& argValues, BfAstNode* targetSrc)
  8047. {
  8048. BfGenericParamFlags genericParamFlags = BfGenericParamFlag_None;
  8049. BfType* typeConstraint = NULL;
  8050. auto genericParam = mModule->GetMergedGenericParamData((BfGenericParamType*)genericParamType, genericParamFlags, typeConstraint);
  8051. bool success = true;
  8052. if ((argValues.mArguments != NULL) && (argValues.mArguments->size() != 0))
  8053. {
  8054. mModule->Fail(StrFormat("Only default parameterless constructors can be called on generic argument '%s'", genericParam->GetGenericParamDef()->mName.c_str()), targetSrc);
  8055. success = false;
  8056. }
  8057. else if ((genericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0)
  8058. {
  8059. mModule->Fail(StrFormat("Must add 'where %s : new, struct' constraint to generic parameter to instantiate type", genericParam->GetGenericParamDef()->mName.c_str()), targetSrc);
  8060. success = false;
  8061. }
  8062. else if ((genericParamFlags & (BfGenericParamFlag_New | BfGenericParamFlag_Var)) == 0)
  8063. {
  8064. mModule->Fail(StrFormat("Must add 'where %s : new' constraint to generic parameter to instantiate type", genericParam->GetGenericParamDef()->mName.c_str()), targetSrc);
  8065. success = false;
  8066. }
  8067. else if ((genericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_Var)) == 0)
  8068. {
  8069. mModule->Fail(StrFormat("Must add 'where %s : struct' constraint to generic parameter to instantiate type without allocator", genericParam->GetGenericParamDef()->mName.c_str()), targetSrc);
  8070. success = false;
  8071. }
  8072. return success;
  8073. }
  8074. BfTypedValue BfExprEvaluator::MatchMethod(BfAstNode* targetSrc, BfMethodBoundExpression* methodBoundExpr, BfTypedValue target, bool allowImplicitThis, bool bypassVirtual, const StringImpl& methodName,
  8075. BfResolvedArgs& argValues, const BfMethodGenericArguments& methodGenericArgs, BfCheckedKind checkedKind)
  8076. {
  8077. BP_ZONE("MatchMethod");
  8078. auto methodGenericArguments = methodGenericArgs.mArguments;
  8079. if (bypassVirtual)
  8080. {
  8081. // "bypassVirtual" means that we know for sure that the target is EXACTLY the specified target type,
  8082. // not derived from (or implementing) the target type. This cannot apply to interfaces.
  8083. BF_ASSERT(!target.mType->IsInterface());
  8084. }
  8085. auto origTarget = target;
  8086. if (mFunctionBindResult != NULL)
  8087. {
  8088. BF_ASSERT(!mFunctionBindResult->mOrigTarget);
  8089. mFunctionBindResult->mOrigTarget = origTarget;
  8090. }
  8091. if (target)
  8092. {
  8093. if (target.mType->IsConcreteInterfaceType())
  8094. target.mType = target.mType->GetUnderlyingType();
  8095. // Turn T* into a T, if we can
  8096. if ((target.mType->IsPointer()) && (target.mType->GetUnderlyingType()->IsGenericParam()))
  8097. {
  8098. auto underlyingType = target.mType->GetUnderlyingType();
  8099. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)underlyingType);
  8100. if (((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsValueType())) ||
  8101. ((genericParam->mGenericParamFlags & (BfGenericParamFlag_Struct)) != 0))
  8102. {
  8103. target.mType = underlyingType;
  8104. }
  8105. }
  8106. if ((!target.mType->IsGenericParam()) && (!target.IsSplat()) && (!IsVar(target.mType)))
  8107. target = MakeCallableTarget(targetSrc, target);
  8108. }
  8109. // static int sCallIdx = 0;
  8110. // if (!mModule->mCompiler->mIsResolveOnly)
  8111. // sCallIdx++;
  8112. // int callIdx = sCallIdx;
  8113. // if (callIdx == 118)
  8114. // {
  8115. // NOP;
  8116. // }
  8117. bool prevAllowVariableDeclarations = true;
  8118. if (mModule->mCurMethodState != NULL)
  8119. {
  8120. // Don't allow variable declarations in arguments for this method call
  8121. prevAllowVariableDeclarations = mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations;
  8122. mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations = false;
  8123. }
  8124. defer
  8125. (
  8126. if (mModule->mCurMethodState != NULL)
  8127. mModule->mCurMethodState->mCurScope->mAllowVariableDeclarations = prevAllowVariableDeclarations;
  8128. );
  8129. // Temporarily disable so we don't capture calls in params
  8130. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, NULL);
  8131. sInvocationIdx++;
  8132. bool wantCtor = methodName.IsEmpty();
  8133. BfAutoComplete::MethodMatchInfo* restoreCapturingMethodMatchInfo = NULL;
  8134. auto autoComplete = GetAutoComplete();
  8135. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  8136. {
  8137. if ((!targetSrc->IsFromParser(mModule->mCompiler->mResolvePassData->mParsers[0])) ||
  8138. ((autoComplete->mMethodMatchInfo->mInvocationSrcIdx != -1) && (autoComplete->mMethodMatchInfo->mInvocationSrcIdx != targetSrc->GetSrcStart())))
  8139. {
  8140. autoComplete->mIsCapturingMethodMatchInfo = false;
  8141. restoreCapturingMethodMatchInfo = autoComplete->mMethodMatchInfo;
  8142. }
  8143. }
  8144. defer(
  8145. {
  8146. if ((restoreCapturingMethodMatchInfo != NULL) && (autoComplete->mMethodMatchInfo == restoreCapturingMethodMatchInfo))
  8147. autoComplete->mIsCapturingMethodMatchInfo = true;
  8148. });
  8149. /*if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  8150. autoComplete->mIsCapturingMethodMatchInfo = false;*/
  8151. bool isUnboundCall = false;
  8152. if (target.mType != NULL)
  8153. {
  8154. if (target.mType->IsGenericParam())
  8155. {
  8156. auto genericParamTarget = (BfGenericParamType*) target.mType;
  8157. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  8158. isUnboundCall = (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var) != 0;
  8159. if (isUnboundCall)
  8160. {
  8161. if (mModule->mCurMethodInstance->mIsUnspecialized)
  8162. {
  8163. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  8164. target.mType = varType;
  8165. }
  8166. }
  8167. }
  8168. else if (IsVar(target.mType))
  8169. isUnboundCall = true;
  8170. }
  8171. /*if (mPrefixedAttributeState != NULL)
  8172. {
  8173. auto customAttr = mPrefixedAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  8174. if (customAttr != NULL)
  8175. {
  8176. if (!mModule->IsInGeneric())
  8177. {
  8178. mModule->Fail("'Unbound' can only be used within generics");
  8179. }
  8180. mPrefixedAttributeState->mUsed = true;
  8181. isUnboundCall = true;
  8182. }
  8183. }*/
  8184. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  8185. {
  8186. auto customAttr = mModule->mAttributeState->mCustomAttributes->Get(mModule->mCompiler->mUnboundAttributeTypeDef);
  8187. if (customAttr != NULL)
  8188. {
  8189. if (!mModule->IsInGeneric())
  8190. {
  8191. mModule->Fail("'Unbound' can only be used within generics");
  8192. }
  8193. mModule->mAttributeState->mUsed = true;
  8194. isUnboundCall = true;
  8195. }
  8196. }
  8197. if (isUnboundCall)
  8198. {
  8199. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  8200. {
  8201. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  8202. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  8203. {
  8204. if ((argValues.mResolvedArgs[argIdx].mArgFlags & BfArgFlag_DeferredEval) != 0)
  8205. {
  8206. mModule->CreateValueFromExpression((*argValues.mArguments)[argIdx], varType);
  8207. }
  8208. }
  8209. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  8210. }
  8211. }
  8212. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isUnboundCall);
  8213. bool wantsExtensionCheck = target;
  8214. auto targetType = target.mType;
  8215. BfTypeDef* curTypeDef = NULL;
  8216. BfType* selfType = NULL;
  8217. BfTypeInstance* targetTypeInst = NULL;
  8218. bool checkNonStatic = true;
  8219. if (target)
  8220. {
  8221. if (IsVar(targetType))
  8222. return mModule->GetDefaultTypedValue(targetType);
  8223. targetTypeInst = targetType->ToTypeInstance();
  8224. if (targetTypeInst != NULL)
  8225. curTypeDef = targetTypeInst->mTypeDef;
  8226. }
  8227. else if (targetType != NULL) // Static targeted
  8228. {
  8229. if (targetType->IsWrappableType())
  8230. {
  8231. if ((targetType->IsPrimitiveType()) && (methodName.IsEmpty()))
  8232. {
  8233. if (argValues.mArguments->IsEmpty())
  8234. {
  8235. return mModule->GetDefaultTypedValue(targetType);
  8236. }
  8237. else if (argValues.mArguments->mSize == 1)
  8238. {
  8239. FinishDeferredEvals(argValues);
  8240. // This is just a primitive cast
  8241. auto& resolvedArg = argValues.mResolvedArgs[0];
  8242. BfTypedValue castedValue;
  8243. BfTypedValue castTarget = resolvedArg.mTypedValue;
  8244. if (resolvedArg.mTypedValue)
  8245. {
  8246. castTarget = mModule->LoadValue(castTarget);
  8247. castedValue = mModule->Cast(targetSrc, castTarget, targetType, BfCastFlags_Explicit);
  8248. }
  8249. if (!castedValue)
  8250. castedValue = mModule->GetDefaultTypedValue(targetType);
  8251. return castedValue;
  8252. }
  8253. }
  8254. targetTypeInst = mModule->GetWrappedStructType(targetType);
  8255. }
  8256. else if (targetType->IsGenericParam())
  8257. {
  8258. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)targetType);
  8259. if (genericParamInstance->mTypeConstraint != NULL)
  8260. targetTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  8261. if (genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Var)
  8262. {
  8263. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  8264. return BfTypedValue(mModule->GetDefaultValue(varType), varType);
  8265. }
  8266. }
  8267. else
  8268. targetTypeInst = targetType->ToTypeInstance();
  8269. if (targetTypeInst == NULL)
  8270. {
  8271. //mModule->Fail("No static methods available", targetSrc);
  8272. //return BfTypedValue();
  8273. }
  8274. else
  8275. {
  8276. curTypeDef = targetTypeInst->mTypeDef;
  8277. checkNonStatic = false;
  8278. }
  8279. }
  8280. else // Current scopeData
  8281. {
  8282. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsForeignMethodDef) && (mModule->mCurMethodInstance->mMethodInfoEx->mForeignType->IsInterface()))
  8283. {
  8284. targetTypeInst = mModule->mCurMethodInstance->mMethodInfoEx->mForeignType;
  8285. curTypeDef = targetTypeInst->mTypeDef;
  8286. checkNonStatic = true;
  8287. target = mModule->GetThis();
  8288. selfType = mModule->mCurTypeInstance;
  8289. //target.mType = targetTypeInst;
  8290. }
  8291. else
  8292. {
  8293. curTypeDef = mModule->mCurTypeInstance->mTypeDef;
  8294. targetTypeInst = mModule->mCurTypeInstance;
  8295. if (mModule->mCurMethodState == NULL)
  8296. {
  8297. checkNonStatic = false;
  8298. }
  8299. else
  8300. {
  8301. if (mModule->mCurMethodState->mMixinState != NULL)
  8302. {
  8303. targetTypeInst = mModule->mCurMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  8304. curTypeDef = targetTypeInst->mTypeDef;
  8305. }
  8306. if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  8307. {
  8308. checkNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  8309. }
  8310. else
  8311. checkNonStatic = !mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  8312. }
  8313. }
  8314. }
  8315. bool isIndirectMethodCall = false;
  8316. BfType* lookupType = targetType;
  8317. BfTypeInstance* lookupTypeInst = targetTypeInst;
  8318. if (targetType != NULL)
  8319. {
  8320. lookupType = BindGenericType(targetSrc, targetType);
  8321. if (lookupType->IsGenericParam())
  8322. lookupTypeInst = NULL;
  8323. }
  8324. if ((mModule->mIsReified) && (targetTypeInst != NULL) && (!targetTypeInst->mIsReified) && (!targetTypeInst->mModule->mReifyQueued))
  8325. mModule->PopulateType(targetTypeInst);
  8326. BfMethodDef* methodDef = NULL;
  8327. BfTypeVector checkMethodGenericArguments;
  8328. BfTypeInstance* curTypeInst = targetTypeInst;
  8329. Array<SizedArray<BfUsingFieldData::MemberRef, 1>*> methodUsingLists;
  8330. BfMethodMatcher methodMatcher(targetSrc, mModule, methodName, argValues.mResolvedArgs, methodGenericArgs);
  8331. methodMatcher.mUsingLists = &methodUsingLists;
  8332. methodMatcher.mOrigTarget = origTarget;
  8333. methodMatcher.mTarget = target;
  8334. methodMatcher.mCheckedKind = checkedKind;
  8335. methodMatcher.mAllowImplicitThis = allowImplicitThis;
  8336. methodMatcher.mAllowStatic = !target.mValue;
  8337. methodMatcher.mAllowNonStatic = !methodMatcher.mAllowStatic;
  8338. methodMatcher.mAutoFlushAmbiguityErrors = !wantsExtensionCheck;
  8339. if (allowImplicitThis)
  8340. {
  8341. if (mModule->mCurMethodState == NULL)
  8342. {
  8343. methodMatcher.mAllowStatic = true;
  8344. methodMatcher.mAllowNonStatic = false;
  8345. }
  8346. else if (mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None)
  8347. {
  8348. methodMatcher.mAllowNonStatic = mModule->mCurMethodState->mTempKind == BfMethodState::TempKind_NonStatic;
  8349. methodMatcher.mAllowStatic = true;
  8350. }
  8351. else
  8352. {
  8353. if (!mModule->mCurMethodInstance->mMethodDef->mIsStatic)
  8354. methodMatcher.mAllowNonStatic = true;
  8355. methodMatcher.mAllowStatic = true;
  8356. if (mModule->mCurMethodInstance->mMethodDef->mIsLocalMethod)
  8357. {
  8358. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  8359. methodMatcher.mAllowNonStatic = !rootMethodState->mMethodInstance->mMethodDef->mIsStatic;
  8360. }
  8361. }
  8362. }
  8363. if (methodName == BF_METHODNAME_CALCAPPEND)
  8364. methodMatcher.mMethodType = BfMethodType_CtorCalcAppend;
  8365. BF_ASSERT(methodMatcher.mBestMethodDef == NULL);
  8366. BfLocalMethod* matchedLocalMethod = NULL;
  8367. if (target.mType == NULL)
  8368. {
  8369. CheckLocalMethods(targetSrc, curTypeInst, methodName, methodMatcher, BfMethodType_Normal);
  8370. if (methodMatcher.mBestMethodDef == NULL)
  8371. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  8372. if (methodMatcher.mBestMethodDef != NULL)
  8373. {
  8374. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  8375. auto methodDef = methodMatcher.mBestMethodDef;
  8376. if (mModule->mCompiler->mResolvePassData != NULL)
  8377. {
  8378. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  8379. mModule->mCompiler->mResolvePassData->HandleLocalReference(identifierNode, curTypeInst->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, ~methodDef->mIdx);
  8380. auto autoComplete = GetAutoComplete();
  8381. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  8382. {
  8383. autoComplete->SetDefinitionLocation(methodDef->GetRefNode(), true);
  8384. if (autoComplete->mDefType == NULL)
  8385. {
  8386. autoComplete->mDefMethod = mModule->mCurMethodState->GetRootMethodState()->mMethodInstance->mMethodDef;
  8387. autoComplete->mDefType = curTypeDef;
  8388. autoComplete->mReplaceLocalId = ~methodDef->mIdx;
  8389. }
  8390. }
  8391. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  8392. {
  8393. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  8394. methodMatchEntry.mMethodDef = methodDef;
  8395. methodMatchEntry.mTypeInstance = mModule->mCurTypeInstance;
  8396. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  8397. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  8398. }
  8399. }
  8400. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  8401. {
  8402. auto methodInstance = mModule->GetRawMethodInstance(methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef);
  8403. if (methodInstance->mReturnType == NULL)
  8404. {
  8405. FinishDeferredEvals(argValues);
  8406. // If we are recursive then we won't even have a completed methodInstance yet to look at
  8407. return mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  8408. }
  8409. }
  8410. }
  8411. }
  8412. if (methodMatcher.mBestMethodDef == NULL)
  8413. {
  8414. if (lookupTypeInst == NULL)
  8415. {
  8416. if ((lookupType != NULL) && (lookupType->IsConcreteInterfaceType()))
  8417. {
  8418. auto concreteInterfaceType = (BfConcreteInterfaceType*)lookupType;
  8419. lookupTypeInst = concreteInterfaceType->mInterface;
  8420. }
  8421. else if (isUnboundCall)
  8422. {
  8423. //auto resolvedType = mModule->ResolveGenericType(lookupType);
  8424. }
  8425. else if (lookupType->IsGenericParam())
  8426. {
  8427. auto genericParamTarget = (BfGenericParamType*)lookupType;
  8428. auto _HandleGenericParamInstance = [&](BfGenericParamInstance* genericParamInstance)
  8429. {
  8430. if (genericParamInstance->mTypeConstraint != NULL)
  8431. lookupTypeInst = genericParamInstance->mTypeConstraint->ToTypeInstance();
  8432. else
  8433. lookupTypeInst = mModule->mContext->mBfObjectType;
  8434. for (BfType* ifaceInst : genericParamInstance->mInterfaceConstraints)
  8435. {
  8436. BfTypeInstance* typeInst = ifaceInst->ToTypeInstance();
  8437. BF_ASSERT(typeInst != NULL);
  8438. if (methodMatcher.CheckType(typeInst, target, false))
  8439. methodMatcher.mSelfType = lookupType;
  8440. }
  8441. };
  8442. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget, true);
  8443. _HandleGenericParamInstance(genericParamInstance);
  8444. // Check method generic constraints
  8445. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  8446. {
  8447. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  8448. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  8449. {
  8450. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  8451. if (genericParam->mExternType == lookupType)
  8452. _HandleGenericParamInstance(genericParam);
  8453. }
  8454. }
  8455. }
  8456. }
  8457. if ((lookupTypeInst != NULL) && (!wantCtor))
  8458. {
  8459. methodMatcher.mBypassVirtual = bypassVirtual;
  8460. methodMatcher.CheckType(lookupTypeInst, target, false);
  8461. }
  8462. if ((lookupType != NULL) && (lookupType->IsGenericParam()))
  8463. {
  8464. //lookupType = mModule->ResolveGenericType(lookupType);
  8465. if (!lookupType->IsGenericParam())
  8466. {
  8467. target = MakeCallableTarget(targetSrc, target);
  8468. if (target)
  8469. {
  8470. lookupTypeInst = lookupType->ToTypeInstance();
  8471. }
  8472. }
  8473. }
  8474. }
  8475. bool isFailurePass = false;
  8476. if (methodMatcher.mBestMethodDef == NULL)
  8477. {
  8478. isFailurePass = true;
  8479. if (lookupTypeInst != NULL)
  8480. methodMatcher.CheckType(lookupTypeInst, target, true);
  8481. }
  8482. BfTypedValue staticResult;
  8483. //
  8484. {
  8485. auto devirtTarget = target;
  8486. if ((devirtTarget.mType == NULL) && (selfType != NULL))
  8487. devirtTarget.mType = selfType;
  8488. methodMatcher.TryDevirtualizeCall(devirtTarget, &origTarget, &staticResult);
  8489. }
  8490. if (staticResult)
  8491. return staticResult;
  8492. bypassVirtual |= methodMatcher.mBypassVirtual;
  8493. if (methodMatcher.mBestMethodDef != NULL)
  8494. {
  8495. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  8496. methodDef = methodMatcher.mBestMethodDef;
  8497. }
  8498. if ((methodDef) && (!methodDef->mIsStatic) && (!target) && (allowImplicitThis))
  8499. {
  8500. target = mModule->GetThis();
  8501. }
  8502. if (!methodUsingLists.IsEmpty())
  8503. {
  8504. auto foundList = methodUsingLists[0];
  8505. if (methodUsingLists.mSize > 1)
  8506. {
  8507. BfError* error = mModule->Fail("Ambiguous 'using' method reference", targetSrc);
  8508. if (error != NULL)
  8509. {
  8510. for (auto checkList : methodUsingLists)
  8511. {
  8512. String errorStr = "'";
  8513. for (int entryIdx = 0; entryIdx < checkList->mSize; entryIdx++)
  8514. {
  8515. if (entryIdx == 0)
  8516. errorStr += (*checkList)[entryIdx].GetFullName(mModule);
  8517. else
  8518. {
  8519. errorStr += ".";
  8520. errorStr += (*checkList)[entryIdx].GetName(mModule);
  8521. }
  8522. }
  8523. errorStr += "' is a candidate";
  8524. mModule->mCompiler->mPassInstance->MoreInfo(errorStr, (*checkList)[0].GetRefNode(mModule));
  8525. }
  8526. }
  8527. }
  8528. BfTypedValue curResult = target;
  8529. for (int entryIdx = 0; entryIdx < foundList->mSize; entryIdx++)
  8530. {
  8531. if ((entryIdx == 0) && (foundList->back().IsStatic()))
  8532. entryIdx = (int)foundList->mSize - 1;
  8533. auto& entry = (*foundList)[entryIdx];
  8534. if (mPropDef != NULL)
  8535. {
  8536. SetAndRestoreValue<BfTypedValue> prevResult(mResult, BfTypedValue());
  8537. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_Friend);
  8538. curResult = GetResult();
  8539. if (!curResult)
  8540. break;
  8541. }
  8542. auto useFlags = BfLookupFieldFlag_None;
  8543. if (entryIdx < foundList->mSize - 1)
  8544. useFlags = (BfLookupFieldFlags)(useFlags | BfLookupFieldFlag_IsAnonymous);
  8545. if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Field)
  8546. {
  8547. curResult = LoadField(targetSrc, curResult, entry.mTypeInstance, entry.mTypeInstance->mTypeDef->mFields[entry.mIdx], useFlags);
  8548. }
  8549. else if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Property)
  8550. {
  8551. curResult = LoadProperty(targetSrc, curResult, entry.mTypeInstance, entry.mTypeInstance->mTypeDef->mProperties[entry.mIdx], useFlags, BfCheckedKind_NotSet, false);
  8552. }
  8553. else if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Local)
  8554. {
  8555. auto localDef = mModule->mCurMethodState->mLocals[entry.mIdx];
  8556. curResult = LoadLocal(localDef);
  8557. }
  8558. else if (entry.mKind == BfUsingFieldData::MemberRef::Kind_Local)
  8559. {
  8560. auto checkMethodDef = entry.mTypeInstance->mTypeDef->mMethods[entry.mIdx];
  8561. BF_ASSERT(methodDef == checkMethodDef);
  8562. break;
  8563. }
  8564. if ((!curResult) && (mPropDef == NULL))
  8565. break;
  8566. if (entryIdx == foundList->mSize - 1)
  8567. {
  8568. auto autoComplete = GetAutoComplete();
  8569. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetSrc)))
  8570. autoComplete->SetDefinitionLocation(entry.GetRefNode(mModule));
  8571. if ((autoComplete != NULL) && (autoComplete->CheckFixit(targetSrc)))
  8572. autoComplete->FixitAddFullyQualify(targetSrc, methodName, *foundList);
  8573. }
  8574. }
  8575. if (methodDef->mIsStatic)
  8576. target = BfTypedValue(curTypeInst);
  8577. else if (curResult)
  8578. target = curResult;
  8579. else if ((!methodDef->mIsStatic) && (curTypeInst != NULL))
  8580. target = mModule->GetDefaultTypedValue(curTypeInst);
  8581. }
  8582. // If we call "GetType" on a value type, statically determine the type rather than boxing and then dispatching
  8583. if ((methodDef) && (target) && (curTypeInst == mModule->mContext->mBfObjectType) &&
  8584. (methodDef->mName == "GetType") && (target.mType->IsValueType()) && (argValues.mArguments->IsEmpty()))
  8585. {
  8586. BfType* targetType = target.mType;
  8587. if (origTarget)
  8588. targetType = origTarget.mType;
  8589. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  8590. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  8591. return BfTypedValue(mModule->CreateTypeDataRef(targetType), typeType);
  8592. }
  8593. bool skipThis = false;
  8594. BfTypedValue fieldVal;
  8595. bool hasFieldVal = false;
  8596. // Fail, check for delegate field invocation
  8597. if ((methodDef == NULL) && ((methodGenericArguments == NULL) || (methodGenericArguments->size() == 0)))
  8598. {
  8599. // Check for payload enum initialization first
  8600. BfTypedValue enumResult;
  8601. BfTypeInstance* enumType = NULL;
  8602. if ((!target) && (target.HasType()) && (targetType->IsPayloadEnum()))
  8603. {
  8604. enumType = targetType->ToTypeInstance();
  8605. }
  8606. else if ((!target) && (!target.HasType()) && (mModule->mCurTypeInstance->IsPayloadEnum()))
  8607. {
  8608. enumType = mModule->mCurTypeInstance;
  8609. }
  8610. if (enumType != NULL)
  8611. {
  8612. enumResult = CheckEnumCreation(targetSrc, enumType, methodName, argValues);
  8613. }
  8614. if (enumResult)
  8615. {
  8616. if (mModule->mCompiler->mResolvePassData != NULL)
  8617. {
  8618. if (auto sourceClassifier = mModule->mCompiler->mResolvePassData->GetSourceClassifier(targetSrc))
  8619. {
  8620. sourceClassifier->SetElementType(targetSrc, BfSourceElementType_Normal);
  8621. }
  8622. }
  8623. return enumResult;
  8624. }
  8625. if (allowImplicitThis)
  8626. {
  8627. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  8628. if (identifierNode != NULL)
  8629. fieldVal = LookupIdentifier(identifierNode);
  8630. }
  8631. else
  8632. {
  8633. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags & ~BfEvalExprFlags_AllowEnumId));
  8634. fieldVal = LookupField(targetSrc, target, methodName);
  8635. }
  8636. if (fieldVal)
  8637. {
  8638. hasFieldVal = true;
  8639. wantsExtensionCheck = !fieldVal.mType->IsDelegate() && !fieldVal.mType->IsFunction();
  8640. }
  8641. else if (mPropDef != NULL)
  8642. {
  8643. hasFieldVal = true;
  8644. BfMethodDef* matchedMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  8645. if (matchedMethod != NULL)
  8646. {
  8647. auto getMethodInstance = mModule->GetRawMethodInstance(mPropTarget.mType->ToTypeInstance(), matchedMethod);
  8648. if ((getMethodInstance != NULL) &&
  8649. ((getMethodInstance->mReturnType->IsDelegate()) || (getMethodInstance->mReturnType->IsFunction())))
  8650. wantsExtensionCheck = false;
  8651. }
  8652. }
  8653. }
  8654. if ((!methodDef) && (!target.mValue))
  8655. {
  8656. // Check to see if we're constructing a struct via a call like: "Struct structVal = Struct()"
  8657. int wantNumGenericArgs = 0;
  8658. if ((methodGenericArguments != NULL) && (methodGenericArguments->size() > 0))
  8659. wantNumGenericArgs = (int)methodGenericArguments->size();
  8660. BfTypeInstance* resolvedTypeInstance = NULL;
  8661. if (wantCtor)
  8662. {
  8663. resolvedTypeInstance = targetTypeInst;
  8664. }
  8665. else if (targetType != NULL)
  8666. {
  8667. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(methodBoundExpr))
  8668. {
  8669. auto resolvedType = mModule->ResolveTypeRef(invocationExpr->mTarget, methodGenericArguments);
  8670. if (resolvedType != NULL)
  8671. resolvedTypeInstance = resolvedType->ToTypeInstance();
  8672. }
  8673. }
  8674. else
  8675. {
  8676. BfIdentifierNode* identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  8677. if (identifierNode != NULL)
  8678. {
  8679. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  8680. BfType* refType;
  8681. if (methodGenericArguments != NULL)
  8682. {
  8683. refType = mModule->ResolveTypeRef(identifierNode, methodGenericArguments);
  8684. }
  8685. else
  8686. refType = mModule->ResolveTypeRef(identifierNode, NULL);
  8687. prevIgnoreErrors.Restore();
  8688. if ((refType != NULL) && (refType->IsPrimitiveType()))
  8689. {
  8690. FinishDeferredEvals(argValues);
  8691. if (argValues.mResolvedArgs.IsEmpty())
  8692. return mModule->GetDefaultTypedValue(refType);
  8693. if (argValues.mResolvedArgs.size() != 1)
  8694. {
  8695. mModule->Fail("Cast requires one parameter", targetSrc);
  8696. return BfTypedValue();
  8697. }
  8698. // This is just a primitive cast
  8699. auto& resolvedArg = argValues.mResolvedArgs[0];
  8700. BfTypedValue castedValue;
  8701. BfTypedValue castTarget = resolvedArg.mTypedValue;
  8702. if (resolvedArg.mTypedValue)
  8703. {
  8704. castTarget = mModule->LoadValue(castTarget);
  8705. castedValue = mModule->Cast(targetSrc, castTarget, refType, BfCastFlags_Explicit);
  8706. }
  8707. if (!castedValue)
  8708. castedValue = mModule->GetDefaultTypedValue(refType);
  8709. return castedValue;
  8710. }
  8711. if (refType != NULL)
  8712. {
  8713. resolvedTypeInstance = refType->ToTypeInstance();
  8714. if (refType->IsGenericParam())
  8715. {
  8716. CheckGenericCtor((BfGenericParamType*)refType, argValues, targetSrc);
  8717. return mModule->GetDefaultTypedValue(refType);
  8718. }
  8719. }
  8720. }
  8721. }
  8722. if (resolvedTypeInstance != NULL)
  8723. {
  8724. if ((mBfEvalExprFlags & BfEvalExprFlags_AppendFieldInitializer) == 0)
  8725. {
  8726. if ((!resolvedTypeInstance->IsStruct()) && (!resolvedTypeInstance->IsTypedPrimitive()))
  8727. {
  8728. if (mModule->PreFail())
  8729. mModule->Fail("Objects must be allocated through 'new' or 'scope'", targetSrc);
  8730. return BfTypedValue();
  8731. }
  8732. }
  8733. if (auto identifier = BfNodeDynCastExact<BfIdentifierNode>(targetSrc))
  8734. {
  8735. auto elementType = resolvedTypeInstance->IsEnum() ? BfSourceElementType_Type : BfSourceElementType_Struct;
  8736. if (resolvedTypeInstance->IsObject())
  8737. elementType = BfSourceElementType_RefType;
  8738. mModule->SetElementType(identifier, elementType);
  8739. }
  8740. if (mModule->mCompiler->mResolvePassData != NULL)
  8741. {
  8742. if (!BfNodeIsA<BfMemberReferenceExpression>(targetSrc))
  8743. mModule->mCompiler->mResolvePassData->HandleTypeReference(targetSrc, resolvedTypeInstance->mTypeDef);
  8744. }
  8745. BfTypedValue structInst;
  8746. mModule->PopulateType(resolvedTypeInstance);
  8747. if (!resolvedTypeInstance->IsValuelessType())
  8748. {
  8749. if ((mReceivingValue != NULL) && (mReceivingValue->mType == resolvedTypeInstance) && (mReceivingValue->IsAddr()))
  8750. {
  8751. structInst = *mReceivingValue;
  8752. mReceivingValue = NULL;
  8753. }
  8754. else
  8755. {
  8756. auto allocaInst = mModule->CreateAlloca(resolvedTypeInstance);
  8757. structInst = BfTypedValue(allocaInst, resolvedTypeInstance, true);
  8758. }
  8759. mResultIsTempComposite = true;
  8760. }
  8761. else
  8762. {
  8763. structInst = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeInstance, true);
  8764. }
  8765. mResultLocalVar = NULL;
  8766. mResultFieldInstance = NULL;
  8767. mResultLocalVarRefNode = NULL;
  8768. auto result = MatchConstructor(targetSrc, methodBoundExpr, structInst, resolvedTypeInstance, argValues, false, resolvedTypeInstance->IsObject());
  8769. if ((result) && (!result.mType->IsVoid()))
  8770. return result;
  8771. mModule->ValidateAllocation(resolvedTypeInstance, targetSrc);
  8772. mModule->AddDependency(resolvedTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  8773. if (mUsedAsStatement)
  8774. {
  8775. mModule->Warn(0, "Struct constructor being used as a statement", targetSrc);
  8776. }
  8777. return structInst;
  8778. }
  8779. }
  8780. // For for extensions in current type
  8781. if (wantsExtensionCheck)
  8782. {
  8783. auto checkTypeInst = mModule->mCurTypeInstance;
  8784. methodMatcher.mMethodType = BfMethodType_Extension;
  8785. if (methodMatcher.CheckType(checkTypeInst, BfTypedValue(), false, true))
  8786. {
  8787. isFailurePass = false;
  8788. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  8789. methodDef = methodMatcher.mBestMethodDef;
  8790. }
  8791. }
  8792. // Look in globals. Always check for extension methods.
  8793. if ((((methodDef == NULL) && (!target.HasType())) ||
  8794. (wantsExtensionCheck)))
  8795. {
  8796. if (mModule->mContext->mCurTypeState != NULL)
  8797. {
  8798. BfGlobalLookup globalLookup;
  8799. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  8800. globalLookup.mName = methodName;
  8801. mModule->PopulateGlobalContainersList(globalLookup);
  8802. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  8803. {
  8804. if (globalContainer.mTypeInst == NULL)
  8805. continue;
  8806. methodMatcher.mMethodType = wantsExtensionCheck ? BfMethodType_Extension : BfMethodType_Normal;
  8807. if (methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false))
  8808. {
  8809. isFailurePass = false;
  8810. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  8811. methodDef = methodMatcher.mBestMethodDef;
  8812. }
  8813. }
  8814. }
  8815. }
  8816. // Look in static search. Always check for extension methods.
  8817. if ((methodDef == NULL) || (wantsExtensionCheck))
  8818. {
  8819. BfStaticSearch* staticSearch = mModule->GetStaticSearch();
  8820. if (staticSearch != NULL)
  8821. {
  8822. for (auto typeInst : staticSearch->mStaticTypes)
  8823. {
  8824. methodMatcher.mMethodType = wantsExtensionCheck ? BfMethodType_Extension : BfMethodType_Normal;
  8825. if (methodMatcher.CheckType(typeInst, BfTypedValue(), false))
  8826. {
  8827. isFailurePass = false;
  8828. curTypeInst = methodMatcher.mBestMethodTypeInstance;
  8829. methodDef = methodMatcher.mBestMethodDef;
  8830. }
  8831. }
  8832. }
  8833. }
  8834. if ((methodDef == NULL) && (hasFieldVal))
  8835. {
  8836. if (mPropDef != NULL)
  8837. fieldVal = GetResult();
  8838. if (fieldVal)
  8839. {
  8840. if (fieldVal.mType->IsGenericParam())
  8841. {
  8842. bool delegateFailed = true;
  8843. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  8844. BfTypeInstance* typeInstConstraint = NULL;
  8845. if (genericParamInstance->mTypeConstraint != NULL)
  8846. typeInstConstraint = genericParamInstance->mTypeConstraint->ToTypeInstance();
  8847. if ((typeInstConstraint != NULL) &&
  8848. ((typeInstConstraint->IsInstanceOf(mModule->mCompiler->mDelegateTypeDef)) || (typeInstConstraint->IsInstanceOf(mModule->mCompiler->mFunctionTypeDef))))
  8849. {
  8850. MarkResultUsed();
  8851. if (argValues.mArguments->size() == 1)
  8852. {
  8853. BfExprEvaluator exprEvaluator(mModule);
  8854. exprEvaluator.mBfEvalExprFlags = BfEvalExprFlags_AllowParamsExpr;
  8855. auto argExpr = (*argValues.mArguments)[0];
  8856. if (argExpr != NULL)
  8857. exprEvaluator.Evaluate(argExpr);
  8858. if ((mModule->mCurMethodState != NULL) && (exprEvaluator.mResultLocalVar != NULL) && (exprEvaluator.mResultLocalVarRefNode != NULL))
  8859. {
  8860. auto localVar = exprEvaluator.mResultLocalVar;
  8861. if ((localVar->mCompositeCount >= 0) && (localVar->mResolvedType == fieldVal.mType))
  8862. {
  8863. delegateFailed = false;
  8864. if (mModule->mCurMethodInstance->mIsUnspecialized)
  8865. {
  8866. auto retTypeType = mModule->CreateModifiedTypeType(fieldVal.mType, BfToken_RetType);
  8867. return mModule->GetFakeTypedValue(retTypeType);
  8868. }
  8869. }
  8870. }
  8871. }
  8872. if (delegateFailed)
  8873. {
  8874. mModule->Fail(StrFormat("Generic delegates can only be invoked with 'params %s' composite parameters", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  8875. return BfTypedValue();
  8876. }
  8877. }
  8878. }
  8879. if (fieldVal.mType->IsTypeInstance())
  8880. {
  8881. prevBindResult.Restore();
  8882. auto fieldTypeInst = fieldVal.mType->ToTypeInstance();
  8883. MarkResultUsed();
  8884. if (mFunctionBindResult != NULL)
  8885. {
  8886. mFunctionBindResult->mOrigTarget = BfTypedValue();
  8887. }
  8888. return MatchMethod(targetSrc, NULL, fieldVal, false, false, "Invoke", argValues, methodGenericArgs, checkedKind);
  8889. }
  8890. if (IsVar(fieldVal.mType))
  8891. {
  8892. FinishDeferredEvals(argValues);
  8893. return BfTypedValue(mModule->GetDefaultValue(fieldVal.mType), fieldVal.mType);
  8894. }
  8895. if (fieldVal.mType->IsGenericParam())
  8896. {
  8897. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)fieldVal.mType);
  8898. BfType* typeConstraint = genericParam->mTypeConstraint;
  8899. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  8900. {
  8901. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  8902. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  8903. {
  8904. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  8905. if ((genericParam->mExternType == fieldVal.mType) && (genericParam->mTypeConstraint != NULL))
  8906. typeConstraint = genericParam->mTypeConstraint;
  8907. }
  8908. }
  8909. if ((typeConstraint != NULL) &&
  8910. ((typeConstraint->IsDelegate()) || (typeConstraint->IsFunction())))
  8911. {
  8912. BfMethodInstance* invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(typeConstraint->ToTypeInstance(), 0, "Invoke");
  8913. methodDef = invokeMethodInstance->mMethodDef;
  8914. methodMatcher.mBestMethodInstance = invokeMethodInstance;
  8915. methodMatcher.mBestMethodTypeInstance = invokeMethodInstance->GetOwner();
  8916. methodMatcher.mBestMethodDef = invokeMethodInstance->mMethodDef;
  8917. target = mModule->GetDefaultTypedValue(methodMatcher.mBestMethodTypeInstance);
  8918. isFailurePass = false;
  8919. isIndirectMethodCall = true;
  8920. }
  8921. }
  8922. else if (fieldVal.mType->IsMethodRef())
  8923. {
  8924. auto functionBindResults = prevBindResult.mPrevVal;
  8925. if (functionBindResults != NULL)
  8926. {
  8927. functionBindResults->mOrigTarget = fieldVal;
  8928. }
  8929. origTarget = fieldVal;
  8930. auto methodRefType = (BfMethodRefType*)fieldVal.mType;
  8931. BfMethodInstance* methodInstance = methodRefType->mMethodRef;
  8932. methodDef = methodInstance->mMethodDef;
  8933. if (methodDef->mIsLocalMethod)
  8934. {
  8935. methodMatcher.mBestMethodInstance = mModule->ReferenceExternalMethodInstance(methodInstance);
  8936. }
  8937. else
  8938. {
  8939. BfTypeVector methodGenericArguments;
  8940. if (methodInstance->mMethodInfoEx != NULL)
  8941. methodGenericArguments = methodInstance->mMethodInfoEx->mMethodGenericArguments;
  8942. methodMatcher.mBestMethodInstance = mModule->GetMethodInstance(methodInstance->GetOwner(), methodInstance->mMethodDef, methodGenericArguments);
  8943. }
  8944. methodMatcher.mBestMethodTypeInstance = methodInstance->GetOwner();
  8945. if (methodInstance->HasThis())
  8946. {
  8947. bool failed = false;
  8948. target = DoImplicitArgCapture(targetSrc, methodInstance, -1, failed, BfImplicitParamKind_General, origTarget);
  8949. }
  8950. else if (!methodDef->mIsStatic)
  8951. {
  8952. auto thisType = methodInstance->GetParamType(-1);
  8953. BF_ASSERT(thisType->IsValuelessType());
  8954. target = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), methodMatcher.mBestMethodTypeInstance);
  8955. }
  8956. else
  8957. target = BfTypedValue(methodMatcher.mBestMethodTypeInstance);
  8958. methodMatcher.mBypassVirtual = true;
  8959. bypassVirtual = true;
  8960. isFailurePass = false;
  8961. isIndirectMethodCall = true;
  8962. }
  8963. if (methodDef == NULL)
  8964. {
  8965. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(fieldVal.mType).c_str()), targetSrc);
  8966. return BfTypedValue();
  8967. }
  8968. }
  8969. }
  8970. if (methodDef == NULL)
  8971. {
  8972. }
  8973. // This will flush out any new ambiguity errors from extension methods
  8974. methodMatcher.FlushAmbiguityError();
  8975. if (methodDef == NULL)
  8976. {
  8977. FinishDeferredEvals(argValues);
  8978. auto compiler = mModule->mCompiler;
  8979. if ((autoComplete != NULL) && (autoComplete->CheckFixit(targetSrc)))
  8980. {
  8981. mModule->CheckTypeRefFixit(targetSrc);
  8982. bool wantStatic = !target.mValue;
  8983. if ((targetType == NULL) && (allowImplicitThis))
  8984. {
  8985. targetType = mModule->mCurTypeInstance;
  8986. if (mModule->mCurMethodInstance != NULL)
  8987. wantStatic = mModule->mCurMethodInstance->mMethodDef->mIsStatic;
  8988. }
  8989. if (targetType != NULL)
  8990. {
  8991. auto typeInst = targetType->ToTypeInstance();
  8992. if ((typeInst != NULL) && (!methodName.IsEmpty()))
  8993. {
  8994. BfTypeVector paramTypes;
  8995. for (int argIdx = 0; argIdx < (int)argValues.mResolvedArgs.size(); argIdx++)
  8996. {
  8997. auto& resolvedArg = argValues.mResolvedArgs[argIdx];
  8998. paramTypes.Add(resolvedArg.mTypedValue.mType);
  8999. }
  9000. autoComplete->FixitAddMethod(typeInst, methodName, mExpectingType, paramTypes, wantStatic);
  9001. }
  9002. }
  9003. }
  9004. if (methodName.IsEmpty())
  9005. {
  9006. // Would have caused a parsing error
  9007. }
  9008. else if (target.mType != NULL)
  9009. {
  9010. if (mModule->PreFail())
  9011. {
  9012. if ((origTarget.mType->IsPointer()) && (origTarget.mType->GetUnderlyingType()->IsObjectOrInterface()))
  9013. {
  9014. mModule->Fail(StrFormat("Methods cannot be called on type '%s' because the type is a pointer to a reference type (ie: a double-reference).",
  9015. mModule->TypeToString(origTarget.mType).c_str()), targetSrc);
  9016. }
  9017. else
  9018. mModule->Fail(StrFormat("Method '%s' does not exist in type '%s'", methodName.c_str(), mModule->TypeToString(target.mType).c_str()), targetSrc);
  9019. }
  9020. }
  9021. else
  9022. {
  9023. if (mModule->PreFail())
  9024. mModule->Fail(StrFormat("Method '%s' does not exist", methodName.c_str()), targetSrc);
  9025. }
  9026. return BfTypedValue();
  9027. }
  9028. if ((prevBindResult.mPrevVal != NULL) && (methodMatcher.mMethodCheckCount > 1))
  9029. prevBindResult.mPrevVal->mCheckedMultipleMethods = true;
  9030. BfType* overrideReturnType = NULL;
  9031. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, curTypeInst, methodDef, methodMatcher, &overrideReturnType);
  9032. if ((mModule->mAttributeState != NULL) && ((mModule->mAttributeState->mFlags & (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)) ==
  9033. (BfAttributeState::Flag_StopOnError | BfAttributeState::Flag_HadError)))
  9034. {
  9035. FinishDeferredEvals(argValues);
  9036. return BfTypedValue();
  9037. }
  9038. if ((moduleMethodInstance.mMethodInstance != NULL) && (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc)))
  9039. {
  9040. FinishDeferredEvals(argValues);
  9041. return BfTypedValue();
  9042. }
  9043. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized))
  9044. {
  9045. if (methodMatcher.mHasVarArguments)
  9046. {
  9047. BfType* retType = mModule->GetPrimitiveType(BfTypeCode_Var);
  9048. if ((!methodMatcher.mHadVarConflictingReturnType) && (methodMatcher.mBestRawMethodInstance != NULL) && (!methodMatcher.mBestRawMethodInstance->mReturnType->IsUnspecializedTypeVariation()) &&
  9049. (prevBindResult.mPrevVal == NULL))
  9050. {
  9051. if ((!methodMatcher.mBestRawMethodInstance->mReturnType->IsGenericParam()) ||
  9052. (((BfGenericParamType*)methodMatcher.mBestRawMethodInstance->mReturnType)->mGenericParamKind != BfGenericParamKind_Method))
  9053. retType = methodMatcher.mBestRawMethodInstance->mReturnType;
  9054. }
  9055. return mModule->GetDefaultTypedValue(retType, true, BfDefaultValueKind_Addr);
  9056. }
  9057. }
  9058. if ((bypassVirtual) && (!target.mValue) && (target.mType->IsInterface()))
  9059. {
  9060. target = mModule->GetThis();
  9061. }
  9062. if (!moduleMethodInstance)
  9063. {
  9064. FinishDeferredEvals(argValues);
  9065. if (mModule->IsInUnspecializedGeneric())
  9066. return mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  9067. return BfTypedValue();
  9068. }
  9069. bool isSkipCall = moduleMethodInstance.mMethodInstance->IsSkipCall(bypassVirtual);
  9070. if ((moduleMethodInstance.mMethodInstance->IsOrInUnspecializedVariation()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  9071. {
  9072. // Invalid methods such as types with a HasVar tuple generic arg will be marked as mIsUnspecializedVariation and shouldn't actually be called
  9073. FinishDeferredEvals(argValues);
  9074. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  9075. }
  9076. if (methodDef->IsEmptyPartial())
  9077. {
  9078. // Ignore call
  9079. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  9080. }
  9081. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mIsStatic) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  9082. {
  9083. bool isConstrained = false;
  9084. if (target.mType != NULL)
  9085. isConstrained = target.mType->IsGenericParam();
  9086. if ((target.mType == NULL) && ((mModule->mCurMethodInstance->mIsForeignMethodDef) || (mModule->mCurTypeInstance->IsInterface())))
  9087. isConstrained = true;
  9088. // If mIgnoreWrites is off then we skip devirtualization, so allow this
  9089. if ((target.mType != NULL) && (!target.mType->IsInterface()) && (mModule->mBfIRBuilder->mIgnoreWrites))
  9090. isConstrained = true;
  9091. if (!isConstrained)
  9092. {
  9093. if (mModule->mCurTypeInstance->IsInterface())
  9094. {
  9095. if (methodDef->mBody == NULL)
  9096. mModule->Fail(StrFormat("Interface method '%s' must provide a body to be explicitly invoked", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  9097. }
  9098. else
  9099. 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);
  9100. FinishDeferredEvals(argValues);
  9101. return mModule->GetDefaultTypedValue(moduleMethodInstance.mMethodInstance->mReturnType, true, BfDefaultValueKind_Addr);
  9102. }
  9103. }
  9104. // 'base' could really mean 'this' if we're in an extension
  9105. if ((target.IsBase()) && (targetTypeInst == mModule->mCurTypeInstance))
  9106. target.ToThis();
  9107. else
  9108. MakeBaseConcrete(target);
  9109. BfType* callTargetType = curTypeInst;
  9110. if (methodDef->mMethodType == BfMethodType_Extension)
  9111. {
  9112. callTargetType = moduleMethodInstance.mMethodInstance->GetParamType(0);
  9113. if ((callTargetType->IsRef()) && (target.IsAddr()) && (!target.IsReadOnly()) && (target.mType->IsValueType()))
  9114. {
  9115. target = BfTypedValue(target.mValue, mModule->CreateRefType(target.mType));
  9116. }
  9117. }
  9118. BfTypedValue callTarget;
  9119. if (isSkipCall)
  9120. {
  9121. // Just a fake value so we can continue on without generating any code (boxing, conversion, etc)
  9122. if (target)
  9123. {
  9124. if (((target.mType->IsComposite()) || (target.mType->IsTypedPrimitive())))
  9125. {
  9126. if ((moduleMethodInstance.mMethodInstance->mMethodDef->mIsMutating) &&
  9127. ((target.IsReadOnly()) || (!target.IsAddr())))
  9128. {
  9129. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str());
  9130. CheckModifyResult(target, targetSrc, err.c_str());
  9131. }
  9132. }
  9133. callTarget = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), targetTypeInst);
  9134. }
  9135. }
  9136. else if (targetTypeInst == callTargetType)
  9137. {
  9138. if ((target) && (methodDef->HasNoThisSplat()))
  9139. {
  9140. callTarget = mModule->MakeAddressable(target);
  9141. }
  9142. else
  9143. callTarget = target;
  9144. if ((callTarget) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  9145. {
  9146. auto wantThis = moduleMethodInstance.mMethodInstance->GetParamType(-1);
  9147. if ((callTarget.mType != wantThis) && (wantThis->IsInterface()))
  9148. callTarget = mModule->Cast(targetSrc, callTarget, wantThis, BfCastFlags_Explicit);
  9149. }
  9150. }
  9151. else if (target)
  9152. {
  9153. if (methodMatcher.mFakeConcreteTarget)
  9154. {
  9155. BF_ASSERT(callTargetType->IsInterface());
  9156. callTarget = mModule->GetDefaultTypedValue(mModule->CreateConcreteInterfaceType(callTargetType->ToTypeInstance()));
  9157. }
  9158. else if (((target.mType->IsGenericParam()) || (target.mType->IsConcreteInterfaceType())) && (callTargetType->IsInterface()))
  9159. {
  9160. // Leave as generic
  9161. callTarget = target;
  9162. }
  9163. else
  9164. {
  9165. bool handled = false;
  9166. if ((target.mType->IsTypedPrimitive()) && (callTargetType->IsTypedPrimitive()))
  9167. {
  9168. handled = true;
  9169. callTarget = target;
  9170. }
  9171. else if ((target.mType->IsStructOrStructPtr()) || (target.mType->IsTypedPrimitive()))
  9172. {
  9173. //BF_ASSERT(target.IsAddr());
  9174. if (callTargetType->IsObjectOrInterface())
  9175. {
  9176. // Box it
  9177. callTarget = mModule->Cast(targetSrc, target, callTargetType, BfCastFlags_Explicit);
  9178. handled = true;
  9179. }
  9180. else
  9181. {
  9182. //BF_ASSERT(target.IsAddr() || target.IsSplat() || target.mType->IsPointer());
  9183. }
  9184. }
  9185. else
  9186. target = mModule->LoadValue(target);
  9187. if (!handled)
  9188. {
  9189. // Could we have just unconditionally done this?
  9190. callTarget = mModule->Cast(targetSrc, target, callTargetType, BfCastFlags_Explicit);
  9191. }
  9192. }
  9193. }
  9194. if (isFailurePass)
  9195. {
  9196. BfError* error;
  9197. if (methodMatcher.mMatchFailKind == BfMethodMatcher::MatchFailKind_CheckedMismatch)
  9198. 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);
  9199. else
  9200. error = mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str()), targetSrc);
  9201. if (error != NULL)
  9202. {
  9203. if ((error != NULL) && (moduleMethodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL))
  9204. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), moduleMethodInstance.mMethodInstance->mMethodDef->GetRefNode());
  9205. }
  9206. }
  9207. if ((mModule->mCompiler->mResolvePassData != NULL) && (methodDef != NULL))
  9208. {
  9209. auto identifierNode = BfNodeDynCast<BfIdentifierNode>(targetSrc);
  9210. while (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(identifierNode))
  9211. identifierNode = qualifiedNameNode->mRight;
  9212. if ((identifierNode != NULL) && (methodDef->mIdx >= 0) && (!isIndirectMethodCall) &&
  9213. ((targetTypeInst == NULL) || (!targetTypeInst->IsDelegateOrFunction())))
  9214. {
  9215. auto refMethodInstance = moduleMethodInstance.mMethodInstance;
  9216. if (refMethodInstance->mVirtualTableIdx != -1)
  9217. {
  9218. auto& virtualEntry = refMethodInstance->GetOwner()->mVirtualMethodTable[refMethodInstance->mVirtualTableIdx];
  9219. refMethodInstance = virtualEntry.mDeclaringMethod;
  9220. }
  9221. mModule->mCompiler->mResolvePassData->HandleMethodReference(identifierNode, refMethodInstance->GetOwner()->mTypeDef, refMethodInstance->mMethodDef);
  9222. auto autoComplete = GetAutoComplete();
  9223. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  9224. {
  9225. autoComplete->SetDefinitionLocation(methodDef->GetRefNode(), true);
  9226. int virtualIdx = moduleMethodInstance.mMethodInstance->mVirtualTableIdx;
  9227. if ((autoComplete->mResolveType == BfResolveType_GoToDefinition) &&
  9228. (virtualIdx != -1) && (targetTypeInst != NULL) && (!targetTypeInst->IsStruct()) && (!targetTypeInst->IsTypedPrimitive()) && (!targetTypeInst->IsInterface()) &&
  9229. // 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
  9230. (targetTypeInst->mVirtualMethodTable.size() != 0))
  9231. {
  9232. auto methodEntry = targetTypeInst->mVirtualMethodTable[virtualIdx];
  9233. if (methodEntry.mImplementingMethod.mMethodNum != -1)
  9234. {
  9235. BfMethodInstance* callingMethodInstance = methodEntry.mImplementingMethod;
  9236. if (callingMethodInstance != NULL)
  9237. {
  9238. auto callingMethodDef = callingMethodInstance->mMethodDef;
  9239. auto callingMethodDeclaration = callingMethodDef->GetMethodDeclaration();
  9240. if ((callingMethodDeclaration != NULL) && (callingMethodDeclaration->mNameNode != NULL))
  9241. autoComplete->SetDefinitionLocation(callingMethodDeclaration->mNameNode, true);
  9242. }
  9243. }
  9244. }
  9245. if (autoComplete->mDefType == NULL)
  9246. {
  9247. autoComplete->mDefMethod = refMethodInstance->mMethodDef;
  9248. autoComplete->mDefType = refMethodInstance->GetOwner()->mTypeDef;
  9249. }
  9250. if (autoComplete->mResolveType == BfResolveType_GetResultString)
  9251. {
  9252. autoComplete->mResultString = ":";
  9253. autoComplete->mResultString += mModule->MethodToString(moduleMethodInstance.mMethodInstance);
  9254. auto methodDecl = moduleMethodInstance.mMethodInstance->mMethodDef->GetMethodDeclaration();
  9255. if ((methodDecl != NULL) && (methodDecl->mDocumentation != NULL))
  9256. {
  9257. autoComplete->mResultString += "\x03";
  9258. methodDecl->mDocumentation->GetDocString(autoComplete->mResultString);
  9259. }
  9260. }
  9261. }
  9262. }
  9263. }
  9264. // This was causing forward-backward-forward steps when we just used 'targetSrc'. Using closeParen is undesirable because most of the time
  9265. // we DO just want it to just go to the targetSrc... do we even need this?
  9266. /*if (auto invokeExpr = BfNodeDynCast<BfInvocationExpression>(targetSrc->mParent))
  9267. {
  9268. // We set the srcPos to the close paren right before the call so we keep a forward progression of src positions in the case
  9269. // where some of the params are method calls and such
  9270. if (invokeExpr->mCloseParen != NULL)
  9271. mModule->UpdateExprSrcPos(invokeExpr->mCloseParen);
  9272. else
  9273. mModule->UpdateExprSrcPos(targetSrc);
  9274. }
  9275. else
  9276. mModule->UpdateExprSrcPos(targetSrc);*/
  9277. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  9278. {
  9279. //BF_ASSERT(!callTarget.mValue.IsFake());
  9280. }
  9281. prevBindResult.Restore();
  9282. // Check mut
  9283. if ((callTarget.mType != NULL) &&
  9284. (callTarget.mType->IsGenericParam()) &&
  9285. ((!callTarget.IsAddr()) || (callTarget.IsReadOnly())) &&
  9286. (callTarget.mKind != BfTypedValueKind_MutableValue) &&
  9287. (moduleMethodInstance.mMethodInstance->mMethodDef->mIsMutating))
  9288. {
  9289. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)callTarget.mType);
  9290. bool needsMut = true;
  9291. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class | BfGenericParamFlag_Var)) != 0)
  9292. needsMut = false;
  9293. if (genericParamInstance->mTypeConstraint != NULL)
  9294. {
  9295. auto typeConstaintTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  9296. if ((typeConstaintTypeInstance != NULL) && (!typeConstaintTypeInstance->IsComposite()))
  9297. needsMut = false;
  9298. }
  9299. if ((mFunctionBindResult != NULL) && (mFunctionBindResult->mSkipMutCheck))
  9300. needsMut = false;
  9301. if (needsMut)
  9302. {
  9303. String err = StrFormat("call mutating method '%s' on", mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str());
  9304. CheckModifyResult(callTarget, targetSrc, err.c_str(), true);
  9305. }
  9306. }
  9307. // Check mut on interface
  9308. if ((callTarget.mType != NULL) &&
  9309. (callTarget.mType->IsInterface()) &&
  9310. (target.IsThis()) &&
  9311. (mModule->mCurTypeInstance) &&
  9312. (!mModule->mCurMethodInstance->mMethodDef->mIsMutating) &&
  9313. (methodDef->mIsMutating))
  9314. {
  9315. mModule->Fail(StrFormat("Cannot call mutating method '%s' within default interface method '%s'. Consider adding 'mut' specifier to this method.",
  9316. mModule->MethodToString(moduleMethodInstance.mMethodInstance).c_str(), mModule->MethodToString(mModule->mCurMethodInstance).c_str()), targetSrc);
  9317. }
  9318. BfTypedValue result;
  9319. BfTypedValue argCascade;
  9320. BfCreateCallFlags subCallFlags = BfCreateCallFlags_None;
  9321. if (bypassVirtual)
  9322. subCallFlags = (BfCreateCallFlags)(subCallFlags | BfCreateCallFlags_BypassVirtual);
  9323. if (skipThis)
  9324. subCallFlags = (BfCreateCallFlags)(subCallFlags | BfCreateCallFlags_SkipThis);
  9325. result = CreateCall(targetSrc, callTarget, origTarget, methodDef, moduleMethodInstance, subCallFlags, argValues.mResolvedArgs, &argCascade);
  9326. if (overrideReturnType != NULL)
  9327. {
  9328. BF_ASSERT(moduleMethodInstance.mMethodInstance->mIsUnspecializedVariation);
  9329. result = mModule->GetDefaultTypedValue(overrideReturnType, false, BfDefaultValueKind_Addr);
  9330. }
  9331. if (result)
  9332. {
  9333. if (result.mType->IsRef())
  9334. result = mModule->RemoveRef(result);
  9335. }
  9336. PerformCallChecks(moduleMethodInstance.mMethodInstance, targetSrc);
  9337. if (result)
  9338. {
  9339. bool discardedReturnValue = mUsedAsStatement;
  9340. if (discardedReturnValue)
  9341. {
  9342. auto _ShowDiscardWaring = [&](const String& text, BfCustomAttributes* customAttributes, BfIRConstHolder* constHolder, BfAstNode* refNode)
  9343. {
  9344. if (customAttributes != NULL)
  9345. {
  9346. auto customAttribute = customAttributes->Get(mModule->mCompiler->mNoDiscardAttributeTypeDef);
  9347. if (!customAttribute->mCtorArgs.IsEmpty())
  9348. {
  9349. String* str = mModule->GetStringPoolString(customAttribute->mCtorArgs[0], constHolder);
  9350. if ((str != NULL) && (!str->IsEmpty()))
  9351. {
  9352. mModule->Warn(0, text + ": " + *str, targetSrc);
  9353. return;
  9354. }
  9355. }
  9356. }
  9357. mModule->Warn(0, text, targetSrc);
  9358. };
  9359. bool showedWarning = false;
  9360. if (moduleMethodInstance.mMethodInstance->mMethodDef->mIsNoDiscard)
  9361. {
  9362. _ShowDiscardWaring("Discarding return value of method with [NoDiscard] attribute", moduleMethodInstance.mMethodInstance->GetCustomAttributes(),
  9363. moduleMethodInstance.mMethodInstance->GetOwner()->mConstHolder, targetSrc);
  9364. showedWarning = true;
  9365. }
  9366. auto typeInst = result.mType->ToTypeInstance();
  9367. if (typeInst != NULL)
  9368. {
  9369. if ((typeInst->mTypeDef->mIsNoDiscard) && (!showedWarning))
  9370. {
  9371. _ShowDiscardWaring("Discarding return value whose type has [NoDiscard] attribute", typeInst->mCustomAttributes, typeInst->mConstHolder, targetSrc);
  9372. }
  9373. BfModuleMethodInstance moduleMethodInstance = mModule->GetMethodByName(typeInst, "ReturnValueDiscarded", 0, true);
  9374. if (moduleMethodInstance)
  9375. {
  9376. bool wasCapturingMethodMatchInfo = false;
  9377. if (autoComplete != NULL)
  9378. {
  9379. wasCapturingMethodMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  9380. autoComplete->mIsCapturingMethodMatchInfo = false;
  9381. }
  9382. defer
  9383. (
  9384. if (autoComplete != NULL)
  9385. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMethodMatchInfo;
  9386. );
  9387. auto wasGetDefinition = (autoComplete != NULL) && (autoComplete->mIsGetDefinition);
  9388. if (wasGetDefinition)
  9389. autoComplete->mIsGetDefinition = false;
  9390. result = mModule->MakeAddressable(result);
  9391. BfResolvedArgs resolvedArgs;
  9392. MatchMethod(targetSrc, NULL, result, false, false, "ReturnValueDiscarded", resolvedArgs, BfMethodGenericArguments());
  9393. if (wasGetDefinition)
  9394. autoComplete->mIsGetDefinition = true;
  9395. }
  9396. }
  9397. }
  9398. }
  9399. if (argCascade)
  9400. {
  9401. if (argCascade.mType->IsRef())
  9402. argCascade = mModule->RemoveRef(argCascade);
  9403. result = argCascade;
  9404. }
  9405. if (result)
  9406. {
  9407. if ((result.mType->IsUnspecializedTypeVariation()) && (moduleMethodInstance.mMethodInstance->GetOwner()->IsInterface()))
  9408. {
  9409. BfType* selfType = NULL;
  9410. if (methodMatcher.mSelfType != NULL)
  9411. {
  9412. BF_ASSERT(mModule->IsInGeneric());
  9413. selfType = methodMatcher.mSelfType;
  9414. }
  9415. else
  9416. {
  9417. // Will be an error
  9418. selfType = methodMatcher.mBestMethodTypeInstance;
  9419. }
  9420. if ((selfType != NULL) && (!selfType->IsInterface()))
  9421. {
  9422. auto resolvedType = mModule->ResolveSelfType(result.mType, selfType);
  9423. if ((resolvedType != NULL) && (resolvedType != result.mType))
  9424. result = mModule->GetDefaultTypedValue(resolvedType);
  9425. }
  9426. }
  9427. }
  9428. return result;
  9429. }
  9430. void BfExprEvaluator::LookupQualifiedName(BfQualifiedNameNode* nameNode, bool ignoreInitialError, bool* hadError)
  9431. {
  9432. BfIdentifierNode* nameLeft = nameNode->mLeft;
  9433. BfIdentifierNode* nameRight = nameNode->mRight;
  9434. StringT<64> fieldName;
  9435. if (nameNode->mRight != NULL)
  9436. nameNode->mRight->ToString(fieldName);
  9437. bool wasBaseLookup = false;
  9438. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  9439. {
  9440. if (CheckIsBase(qualifiedLeftName->mRight))
  9441. {
  9442. wasBaseLookup = true;
  9443. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  9444. if (type == NULL)
  9445. return;
  9446. auto fieldName = nameNode->mRight->ToString();
  9447. auto target = mModule->GetThis();
  9448. target.mType = type;
  9449. mResult = LookupField(nameNode->mRight, target, fieldName);
  9450. if ((mPropDef != NULL) && (mPropDef->IsVirtual()))
  9451. mPropDefBypassVirtual = true;
  9452. return;
  9453. }
  9454. }
  9455. if (!wasBaseLookup)
  9456. mResult = LookupIdentifier(nameNode->mLeft, ignoreInitialError, hadError);
  9457. GetResult();
  9458. if (!mResult)
  9459. {
  9460. if (!ignoreInitialError)
  9461. mModule->Fail("Identifier not found", nameNode->mLeft);
  9462. return;
  9463. }
  9464. if (mResult.mType->IsObject())
  9465. {
  9466. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  9467. }
  9468. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  9469. {
  9470. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  9471. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  9472. mResult.mType = structPtrType->mElementType;
  9473. if (mResult.mKind == BfTypedValueKind_ThisValue)
  9474. mResult.mKind = BfTypedValueKind_ThisAddr;
  9475. else
  9476. mResult.mKind = BfTypedValueKind_Addr;
  9477. }
  9478. mIsVolatileReference = false;
  9479. mIsHeapReference = false;
  9480. if (!mResult)
  9481. return;
  9482. auto origResult = mResult;
  9483. auto lookupType = BindGenericType(nameNode, mResult.mType);
  9484. if (IsVar(mResult.mType))
  9485. {
  9486. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType, true);
  9487. return;
  9488. }
  9489. if ((!mResult.mType->IsTypeInstance()) && (!mResult.mType->IsGenericParam()))
  9490. {
  9491. if (hadError != NULL)
  9492. *hadError = true;
  9493. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  9494. mResult = BfTypedValue();
  9495. return;
  9496. }
  9497. BfTypedValue lookupVal = mResult;
  9498. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  9499. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  9500. {
  9501. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType, true);
  9502. SizedArray<BfTypeInstance*, 8> searchConstraints;
  9503. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  9504. {
  9505. if (!searchConstraints.Contains(ifaceConstraint))
  9506. {
  9507. searchConstraints.push_back(ifaceConstraint);
  9508. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  9509. {
  9510. auto innerIFace = innerIFaceEntry.mInterfaceType;
  9511. if (!searchConstraints.Contains(innerIFace))
  9512. {
  9513. searchConstraints.push_back(innerIFace);
  9514. }
  9515. }
  9516. }
  9517. }
  9518. BfTypedValue prevTarget;
  9519. BfPropertyDef* prevDef = NULL;
  9520. for (auto ifaceConstraint : searchConstraints)
  9521. {
  9522. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  9523. mResult = LookupField(nameNode->mRight, lookupVal, fieldName);
  9524. if (mPropDef != NULL)
  9525. {
  9526. if (prevDef != NULL)
  9527. {
  9528. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  9529. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  9530. if ((isWorse) && (!isBetter))
  9531. continue;
  9532. if (isBetter == isWorse)
  9533. {
  9534. auto error = mModule->Fail("Ambiguous property reference", nameNode->mRight);
  9535. if (error != NULL)
  9536. {
  9537. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  9538. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  9539. }
  9540. }
  9541. }
  9542. prevDef = mPropDef;
  9543. prevTarget = mPropTarget;
  9544. }
  9545. }
  9546. /*if ((mResult) || (mPropDef != NULL))
  9547. break;*/
  9548. }
  9549. if (mPropDef != NULL)
  9550. {
  9551. mOrigPropTarget = origResult;
  9552. if (((CheckIsBase(nameNode->mLeft)) || (wasBaseLookup)) && (mPropDef->IsVirtual()))
  9553. mPropDefBypassVirtual = true;
  9554. }
  9555. if ((mResult) || (mPropDef != NULL))
  9556. return;
  9557. if (hadError != NULL)
  9558. *hadError = true;
  9559. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  9560. auto compiler = mModule->mCompiler;
  9561. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  9562. {
  9563. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), false);
  9564. }
  9565. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(lookupType).c_str()), nameNode->mRight);
  9566. }
  9567. void BfExprEvaluator::LookupQualifiedName(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreInitialError, bool* hadError)
  9568. {
  9569. String fieldName;
  9570. if (nameRight != NULL)
  9571. fieldName = nameRight->ToString();
  9572. bool wasBaseLookup = false;
  9573. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  9574. {
  9575. if (CheckIsBase(qualifiedLeftName->mRight))
  9576. {
  9577. wasBaseLookup = true;
  9578. auto type = mModule->ResolveTypeRef(qualifiedLeftName->mLeft, NULL);
  9579. if (type == NULL)
  9580. return;
  9581. auto fieldName = nameRight->ToString();
  9582. auto target = mModule->GetThis();
  9583. target.mType = type;
  9584. mResult = LookupField(nameRight, target, fieldName);
  9585. if ((mPropDef != NULL) && (mPropDef->IsVirtual()))
  9586. mPropDefBypassVirtual = true;
  9587. return;
  9588. }
  9589. }
  9590. if (!wasBaseLookup)
  9591. {
  9592. mResult = LookupIdentifier(nameLeft, ignoreInitialError, hadError);
  9593. if ((mResult) && (!mResult.mType->IsComposite()))
  9594. CheckResultForReading(mResult);
  9595. }
  9596. GetResult();
  9597. if (!mResult)
  9598. {
  9599. if (!ignoreInitialError)
  9600. mModule->Fail("Identifier not found", nameLeft);
  9601. return;
  9602. }
  9603. if (mResult.mType->IsObject())
  9604. {
  9605. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  9606. }
  9607. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  9608. {
  9609. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  9610. mResult = mModule->LoadValue(mResult, 0, mIsVolatileReference);
  9611. mResult.mType = structPtrType->mElementType;
  9612. if (mResult.mKind == BfTypedValueKind_ThisValue)
  9613. mResult.mKind = BfTypedValueKind_ThisAddr;
  9614. else
  9615. mResult.mKind = BfTypedValueKind_Addr;
  9616. }
  9617. mIsVolatileReference = false;
  9618. mIsHeapReference = false;
  9619. if (!mResult)
  9620. return;
  9621. if (mResult.mType->IsAllocType())
  9622. mResult.mType = mResult.mType->GetUnderlyingType();
  9623. auto origResult = mResult;
  9624. if (IsVar(mResult.mType))
  9625. {
  9626. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  9627. mResult = BfTypedValue(mModule->GetDefaultValue(varType), varType, true);
  9628. return;
  9629. }
  9630. if ((!mResult.mType->IsTypeInstance()) && (!mResult.mType->IsGenericParam()))
  9631. {
  9632. if (mResult.mType->IsSizedArray())
  9633. {
  9634. if (mResult.mType->IsValuelessType())
  9635. {
  9636. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  9637. mResult.mValue = mModule->mBfIRBuilder->GetFakeVal();
  9638. }
  9639. else
  9640. {
  9641. mResult = mModule->MakeAddressable(mResult);
  9642. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  9643. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  9644. }
  9645. }
  9646. else if (mResult.mType->IsWrappableType())
  9647. {
  9648. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  9649. }
  9650. else
  9651. {
  9652. if (hadError != NULL)
  9653. *hadError = true;
  9654. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  9655. mResult = BfTypedValue();
  9656. return;
  9657. }
  9658. }
  9659. BfTypedValue lookupVal = mResult;
  9660. auto lookupType = BindGenericType(nameNode, mResult.mType);
  9661. if ((lookupType->IsGenericParam()) && (!mResult.mType->IsGenericParam()))
  9662. {
  9663. bool prevUseMixinGenerics = false;
  9664. if (mModule->mCurMethodState->mMixinState != NULL)
  9665. {
  9666. prevUseMixinGenerics = mModule->mCurMethodState->mMixinState->mUseMixinGenerics;
  9667. mModule->mCurMethodState->mMixinState->mUseMixinGenerics = true;
  9668. }
  9669. // Try to lookup from generic binding
  9670. mResult = LookupField(nameRight, BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), lookupType), fieldName, BfLookupFieldFlag_BindOnly);
  9671. if (mModule->mCurMethodState->mMixinState != NULL)
  9672. mModule->mCurMethodState->mMixinState->mUseMixinGenerics = prevUseMixinGenerics;
  9673. if (mPropDef != NULL)
  9674. {
  9675. mOrigPropTarget = lookupVal;
  9676. return;
  9677. }
  9678. }
  9679. if (mPropDef == NULL)
  9680. mResult = LookupField(nameRight, lookupVal, fieldName, CheckIsBase(nameLeft) ? BfLookupFieldFlag_BaseLookup : BfLookupFieldFlag_None);
  9681. if ((!mResult) && (mPropDef == NULL) && (lookupType->IsGenericParam()))
  9682. {
  9683. auto genericParamInst = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType, true);
  9684. SizedArray<BfTypeInstance*, 8> searchConstraints;
  9685. for (auto ifaceConstraint : genericParamInst->mInterfaceConstraints)
  9686. {
  9687. if (!searchConstraints.Contains(ifaceConstraint))
  9688. {
  9689. searchConstraints.push_back(ifaceConstraint);
  9690. for (auto& innerIFaceEntry : ifaceConstraint->mInterfaces)
  9691. {
  9692. auto innerIFace = innerIFaceEntry.mInterfaceType;
  9693. if (!searchConstraints.Contains(innerIFace))
  9694. {
  9695. searchConstraints.push_back(innerIFace);
  9696. }
  9697. }
  9698. }
  9699. }
  9700. BfTypedValue prevTarget;
  9701. BfPropertyDef* prevDef = NULL;
  9702. for (auto ifaceConstraint : searchConstraints)
  9703. {
  9704. BfTypedValue lookupVal = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), ifaceConstraint);
  9705. mResult = LookupField(nameRight, lookupVal, fieldName);
  9706. if (mPropDef != NULL)
  9707. {
  9708. if (prevDef != NULL)
  9709. {
  9710. bool isBetter = mModule->TypeIsSubTypeOf(mPropTarget.mType->ToTypeInstance(), prevTarget.mType->ToTypeInstance());
  9711. bool isWorse = mModule->TypeIsSubTypeOf(prevTarget.mType->ToTypeInstance(), mPropTarget.mType->ToTypeInstance());
  9712. if ((isWorse) && (!isBetter))
  9713. continue;
  9714. if (isBetter == isWorse)
  9715. {
  9716. auto error = mModule->Fail("Ambiguous property reference", nameRight);
  9717. if (error != NULL)
  9718. {
  9719. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(prevTarget.mType).c_str()), prevDef->GetRefNode());
  9720. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("'%s' has a candidate", mModule->TypeToString(mPropTarget.mType).c_str()), mPropDef->GetRefNode());
  9721. }
  9722. }
  9723. }
  9724. prevDef = mPropDef;
  9725. prevTarget = mPropTarget;
  9726. }
  9727. }
  9728. if ((mPropDef == NULL) && (genericParamInst->IsEnum()))
  9729. {
  9730. if ((fieldName == "Underlying") || (fieldName == "UnderlyingRef"))
  9731. {
  9732. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  9733. return;
  9734. }
  9735. }
  9736. }
  9737. if (mPropDef != NULL)
  9738. {
  9739. mOrigPropTarget = origResult;
  9740. if ((CheckIsBase(nameLeft)) || (wasBaseLookup))
  9741. {
  9742. if (mPropDef->IsVirtual())
  9743. mPropDefBypassVirtual = true;
  9744. }
  9745. }
  9746. if ((mResult) || (mPropDef != NULL))
  9747. return;
  9748. if (hadError != NULL)
  9749. *hadError = true;
  9750. BfTypeInstance* typeInst = lookupType->ToTypeInstance();
  9751. auto compiler = mModule->mCompiler;
  9752. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  9753. {
  9754. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), false);
  9755. }
  9756. if (((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0) && (typeInst != NULL) && (CheckForMethodName(nameRight, typeInst, fieldName)))
  9757. return;
  9758. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(lookupType).c_str()), nameRight);
  9759. }
  9760. void BfExprEvaluator::LookupQualifiedStaticField(BfQualifiedNameNode* nameNode, bool ignoreIdentifierNotFoundError)
  9761. {
  9762. // Lookup left side as a type
  9763. {
  9764. BfType* type = NULL;
  9765. {
  9766. type = mModule->ResolveTypeRef(nameNode->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  9767. mModule->CheckTypeRefFixit(nameNode->mLeft);
  9768. }
  9769. if (type != NULL)
  9770. {
  9771. BfTypedValue lookupType;
  9772. if (type->IsWrappableType())
  9773. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  9774. else
  9775. lookupType = BfTypedValue(type);
  9776. auto findName = nameNode->mRight->ToString();
  9777. /*if (findName == "base")
  9778. {
  9779. mResult = BfTypedValue(lookupType);
  9780. return;
  9781. }*/
  9782. mResult = LookupField(nameNode->mRight, lookupType, findName);
  9783. if ((mResult) || (mPropDef != NULL))
  9784. return;
  9785. if (lookupType.mType != NULL)
  9786. {
  9787. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  9788. auto compiler = mModule->mCompiler;
  9789. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameNode->mRight)))
  9790. {
  9791. FixitAddMember(typeInst, mExpectingType, nameNode->mRight->ToString(), true);
  9792. }
  9793. }
  9794. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  9795. mModule->Fail("Field not found", nameNode->mRight);
  9796. return;
  9797. }
  9798. }
  9799. String fieldName = nameNode->mRight->ToString();
  9800. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameNode->mLeft))
  9801. LookupQualifiedStaticField(qualifiedLeftName, true);
  9802. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameNode->mLeft))
  9803. {
  9804. mResult = LookupIdentifier(leftName);
  9805. }
  9806. GetResult();
  9807. if (!mResult)
  9808. {
  9809. if (!ignoreIdentifierNotFoundError)
  9810. mModule->Fail("Identifier not found", nameNode->mLeft);
  9811. return;
  9812. }
  9813. if (mResult.mType->IsObject())
  9814. {
  9815. mResult = mModule->LoadValue(mResult);
  9816. }
  9817. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  9818. {
  9819. BfPointerType* structPtrType = (BfPointerType*) mResult.mType;
  9820. mResult = mModule->LoadValue(mResult);
  9821. mResult.mType = structPtrType->mElementType;
  9822. }
  9823. if (!mResult)
  9824. return;
  9825. if (!mResult.mType->IsTypeInstance())
  9826. {
  9827. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameNode->mLeft);
  9828. return;
  9829. }
  9830. auto leftResult = mResult;
  9831. mResult = LookupField(nameNode->mRight, leftResult, fieldName);
  9832. if ((mResult) || (mPropDef != NULL))
  9833. return;
  9834. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(leftResult.mType).c_str()), nameNode->mRight);
  9835. }
  9836. void BfExprEvaluator::LookupQualifiedStaticField(BfAstNode* nameNode, BfIdentifierNode* nameLeft, BfIdentifierNode* nameRight, bool ignoreIdentifierNotFoundError)
  9837. {
  9838. // Lookup left side as a type
  9839. {
  9840. BfType* type = mModule->ResolveTypeRef(nameLeft, NULL, BfPopulateType_Declaration, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_IgnoreLookupError | BfResolveTypeRefFlag_AllowGlobalContainer));
  9841. if ((type != NULL) && (type->IsVar()) && (nameLeft->Equals("var")))
  9842. type = NULL;
  9843. if (type != NULL)
  9844. {
  9845. BfTypedValue lookupType;
  9846. if (type->IsWrappableType())
  9847. lookupType = BfTypedValue(mModule->GetWrappedStructType(type));
  9848. else
  9849. lookupType = BfTypedValue(type);
  9850. auto findName = nameRight->ToString();
  9851. if ((lookupType.mType != NULL) && (lookupType.mType->IsGenericParam()))
  9852. {
  9853. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)lookupType.mType);
  9854. if (genericParamInstance->mTypeConstraint != NULL)
  9855. {
  9856. mResult = LookupField(nameRight, BfTypedValue(genericParamInstance->mTypeConstraint), findName);
  9857. if ((mResult) || (mPropDef != NULL))
  9858. {
  9859. mOrigPropTarget = lookupType;
  9860. return;
  9861. }
  9862. }
  9863. for (auto constraint : genericParamInstance->mInterfaceConstraints)
  9864. {
  9865. mResult = LookupField(nameRight, BfTypedValue(constraint), findName);
  9866. if ((mResult) || (mPropDef != NULL))
  9867. {
  9868. mOrigPropTarget = lookupType;
  9869. return;
  9870. }
  9871. }
  9872. }
  9873. /*if (findName == "base")
  9874. {
  9875. mResult = BfTypedValue(lookupType);
  9876. return;
  9877. }*/
  9878. mResult = LookupField(nameRight, lookupType, findName);
  9879. if ((mResult) || (mPropDef != NULL))
  9880. return;
  9881. if (lookupType.mType != NULL)
  9882. {
  9883. BfTypeInstance* typeInst = lookupType.mType->ToTypeInstance();
  9884. auto compiler = mModule->mCompiler;
  9885. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(nameRight)))
  9886. {
  9887. FixitAddMember(typeInst, mExpectingType, nameRight->ToString(), true);
  9888. }
  9889. }
  9890. if ((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0)
  9891. {
  9892. auto typeInst = lookupType.mType->ToTypeInstance();
  9893. if ((typeInst != NULL) && (CheckForMethodName(nameRight, typeInst, findName)))
  9894. return;
  9895. }
  9896. if ((mBfEvalExprFlags & BfEvalExprFlags_NoLookupError) == 0)
  9897. mModule->Fail("Field not found", nameRight);
  9898. return;
  9899. }
  9900. }
  9901. String fieldName = nameRight->ToString();
  9902. if (auto qualifiedLeftName = BfNodeDynCast<BfQualifiedNameNode>(nameLeft))
  9903. LookupQualifiedStaticField(qualifiedLeftName, qualifiedLeftName->mLeft, qualifiedLeftName->mRight, true);
  9904. else if (auto leftName = BfNodeDynCast<BfIdentifierNode>(nameLeft))
  9905. {
  9906. mResult = LookupIdentifier(leftName);
  9907. }
  9908. GetResult();
  9909. if (!mResult)
  9910. {
  9911. if (!ignoreIdentifierNotFoundError)
  9912. mModule->Fail("Identifier not found", nameLeft);
  9913. return;
  9914. }
  9915. if (mResult.mType->IsObject())
  9916. {
  9917. mResult = mModule->LoadValue(mResult);
  9918. }
  9919. else if ((mResult.mType->IsPointer()) && mResult.mType->IsStructOrStructPtr())
  9920. {
  9921. BfPointerType* structPtrType = (BfPointerType*)mResult.mType;
  9922. mResult = mModule->LoadValue(mResult);
  9923. mResult = BfTypedValue(mResult.mValue, structPtrType->mElementType, true);
  9924. }
  9925. if (!mResult)
  9926. return;
  9927. if (!mResult.mType->IsTypeInstance())
  9928. {
  9929. if (mResult.mType->IsSizedArray())
  9930. {
  9931. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  9932. mResult.mValue = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(mResult.mType->ToTypeInstance()));
  9933. }
  9934. else if (mResult.mType->IsWrappableType())
  9935. {
  9936. mResult.mType = mModule->GetWrappedStructType(mResult.mType);
  9937. }
  9938. else
  9939. {
  9940. mModule->Fail(StrFormat("Type '%s' has no fields", mModule->TypeToString(mResult.mType).c_str()), nameLeft);
  9941. return;
  9942. }
  9943. }
  9944. auto leftResult = mResult;
  9945. mResult = LookupField(nameRight, leftResult, fieldName);
  9946. if ((mResult) || (mPropDef != NULL))
  9947. return;
  9948. mModule->CheckTypeRefFixit(nameLeft);
  9949. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", fieldName.c_str(), mModule->TypeToString(leftResult.mType).c_str()), nameRight);
  9950. }
  9951. void BfExprEvaluator::Visit(BfQualifiedNameNode* nameNode)
  9952. {
  9953. auto autoComplete = GetAutoComplete();
  9954. if (autoComplete != NULL)
  9955. {
  9956. autoComplete->CheckMemberReference(nameNode->mLeft, nameNode->mDot, nameNode->mRight);
  9957. }
  9958. bool hadError = false;
  9959. LookupQualifiedName(nameNode, nameNode->mLeft, nameNode->mRight, true, &hadError);
  9960. if ((mResult) || (mPropDef != NULL))
  9961. return;
  9962. if (hadError)
  9963. return;
  9964. LookupQualifiedStaticField(nameNode, nameNode->mLeft, nameNode->mRight, false);
  9965. }
  9966. void BfExprEvaluator::Visit(BfThisExpression* thisExpr)
  9967. {
  9968. mResult = mModule->GetThis();
  9969. if (!mResult)
  9970. {
  9971. mModule->Fail("Static methods don't have 'this'", thisExpr);
  9972. return;
  9973. }
  9974. auto autoComplete = GetAutoComplete();
  9975. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(thisExpr)))
  9976. autoComplete->SetDefinitionLocation(mModule->mCurTypeInstance->mTypeDef->GetRefNode());
  9977. mResultLocalVar = mModule->GetThisVariable();
  9978. mResultFieldInstance = NULL;
  9979. }
  9980. void BfExprEvaluator::Visit(BfBaseExpression* baseExpr)
  9981. {
  9982. mResult = mModule->GetThis();
  9983. if (!mResult)
  9984. {
  9985. mModule->Fail("Static methods don't have 'base'", baseExpr);
  9986. return;
  9987. }
  9988. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowBase) == 0)
  9989. mModule->Fail("Use of keyword 'base' is not valid in this context", baseExpr);
  9990. auto baseType = mModule->mCurTypeInstance->mBaseType;
  9991. if (baseType == NULL)
  9992. baseType = mModule->mContext->mBfObjectType;
  9993. auto autoComplete = GetAutoComplete();
  9994. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(baseExpr)))
  9995. autoComplete->SetDefinitionLocation(baseType->mTypeDef->GetRefNode());
  9996. mModule->PopulateType(baseType, BfPopulateType_Data);
  9997. mResult = mModule->Cast(baseExpr, mResult, baseType, BfCastFlags_Explicit);
  9998. if (mResult.IsSplat())
  9999. mResult.mKind = BfTypedValueKind_BaseSplatHead;
  10000. else if (mResult.IsAddr())
  10001. mResult.mKind = BfTypedValueKind_BaseAddr;
  10002. else if (mResult)
  10003. mResult.mKind = BfTypedValueKind_BaseValue;
  10004. }
  10005. void BfExprEvaluator::Visit(BfMixinExpression* mixinExpr)
  10006. {
  10007. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin)
  10008. {
  10009. auto varType = mModule->GetPrimitiveType(BfTypeCode_Var);
  10010. auto newVar = mModule->AllocFromType(varType, mModule->mCurMethodState->mCurScope);
  10011. mResult = BfTypedValue(newVar, varType, true);
  10012. return;
  10013. }
  10014. auto curMethodState = mModule->mCurMethodState;
  10015. if (curMethodState->mMixinState == NULL)
  10016. {
  10017. mModule->Fail("Mixin references can only be used within mixins", mixinExpr);
  10018. return;
  10019. }
  10020. int localIdx = GetMixinVariable();
  10021. if (localIdx != -1)
  10022. {
  10023. auto varDecl = curMethodState->mLocals[localIdx];
  10024. if (varDecl != NULL)
  10025. {
  10026. BfTypedValue localResult = LoadLocal(varDecl);
  10027. mResult = localResult;
  10028. mResultLocalVar = varDecl;
  10029. mResultFieldInstance = NULL;
  10030. mResultLocalVarRefNode = mixinExpr;
  10031. return;
  10032. }
  10033. }
  10034. if (mModule->mCurMethodInstance->mIsUnspecialized)
  10035. {
  10036. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  10037. return;
  10038. }
  10039. mModule->Fail("Mixin value cannot be inferred", mixinExpr);
  10040. }
  10041. void BfExprEvaluator::Visit(BfSizedArrayCreateExpression* createExpr)
  10042. {
  10043. auto type = mModule->ResolveTypeRef(createExpr->mTypeRef);
  10044. if (type == NULL)
  10045. return;
  10046. if (type->IsArray())
  10047. {
  10048. // If we have a case like 'int[] (1, 2)' then we infer the sized array size from the initializer
  10049. auto arrayType = (BfArrayType*)type;
  10050. if (arrayType->mDimensions == 1)
  10051. {
  10052. int arraySize = 0;
  10053. if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(createExpr->mInitializer))
  10054. {
  10055. arraySize = (int)arrayInitExpr->mValues.size();
  10056. }
  10057. type = mModule->CreateSizedArrayType(arrayType->GetUnderlyingType(), arraySize);
  10058. }
  10059. }
  10060. if (!type->IsSizedArray())
  10061. {
  10062. mModule->Fail("Sized array expected", createExpr->mTypeRef);
  10063. return;
  10064. }
  10065. BfSizedArrayType* arrayType = (BfSizedArrayType*)type;
  10066. if (createExpr->mInitializer == NULL)
  10067. {
  10068. mModule->AssertErrorState();
  10069. mResult = mModule->GetDefaultTypedValue(arrayType);
  10070. return;
  10071. }
  10072. InitializedSizedArray(arrayType, createExpr->mInitializer->mOpenBrace, createExpr->mInitializer->mValues, createExpr->mInitializer->mCommas, createExpr->mInitializer->mCloseBrace);
  10073. }
  10074. void BfExprEvaluator::Visit(BfInitializerExpression* initExpr)
  10075. {
  10076. uint64 unassignedFieldFlags = 0;
  10077. if (auto typeRef = BfNodeDynCast<BfTypeReference>(initExpr->mTarget))
  10078. {
  10079. BfType* type = NULL;
  10080. if (auto typeRef = BfNodeDynCast<BfDotTypeReference>(initExpr->mTarget))
  10081. {
  10082. type = mExpectingType;
  10083. }
  10084. if (type == NULL)
  10085. type = mModule->ResolveTypeRef(typeRef);
  10086. if (type != NULL)
  10087. {
  10088. if (type->IsValueType())
  10089. {
  10090. if (mReceivingValue != NULL)
  10091. {
  10092. mResult = *mReceivingValue;
  10093. mReceivingValue = NULL;
  10094. }
  10095. else
  10096. {
  10097. mResult = BfTypedValue(mModule->CreateAlloca(type), type, true);
  10098. }
  10099. auto typeInstance = type->ToTypeInstance();
  10100. if (typeInstance != NULL)
  10101. unassignedFieldFlags = (1 << typeInstance->mMergedFieldDataCount) - 1;
  10102. }
  10103. else
  10104. {
  10105. mModule->Fail("Initializer expressions can only be used on value types or allocated values", initExpr->mTarget);
  10106. }
  10107. }
  10108. }
  10109. else
  10110. VisitChild(initExpr->mTarget);
  10111. if (!mResult)
  10112. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  10113. BfIRBlock initBlock = BfIRBlock();
  10114. if (unassignedFieldFlags != 0)
  10115. {
  10116. initBlock = mModule->mBfIRBuilder->CreateBlock("initStart", true);
  10117. mModule->mBfIRBuilder->CreateBr(initBlock);
  10118. mModule->mBfIRBuilder->SetInsertPoint(initBlock);
  10119. }
  10120. BfTypedValue initValue = GetResult(true);
  10121. bool isFirstAdd = true;
  10122. BfFunctionBindResult addFunctionBindResult;
  10123. addFunctionBindResult.mWantsArgs = true;
  10124. for (auto elementExpr : initExpr->mValues)
  10125. {
  10126. if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0)
  10127. {
  10128. mModule->Fail("Comptime cannot evaluate initializer expressions", elementExpr);
  10129. break;
  10130. }
  10131. bool wasValidInitKind = false;
  10132. if (auto assignExpr = BfNodeDynCast<BfAssignmentExpression>(elementExpr))
  10133. {
  10134. BfTypedValue fieldResult;
  10135. if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(assignExpr->mLeft))
  10136. {
  10137. StringT<128> findName;
  10138. identifierNode->ToString(findName);
  10139. mResultFieldInstance = NULL;
  10140. fieldResult = LookupField(identifierNode, initValue, findName, BfLookupFieldFlag_IsImplicitThis);
  10141. if ((fieldResult.mKind == BfTypedValueKind_TempAddr) || (fieldResult.mKind == BfTypedValueKind_RestrictedTempAddr))
  10142. fieldResult.mKind = BfTypedValueKind_Addr;
  10143. if ((mResultFieldInstance != NULL) && (mResultFieldInstance->mMergedDataIdx != -1))
  10144. {
  10145. int resultLocalVarField = 0;
  10146. int resultLocalVarFieldCount = 0;
  10147. mResultFieldInstance->GetDataRange(resultLocalVarField, resultLocalVarFieldCount);
  10148. for (int i = 0; i < resultLocalVarFieldCount; i++)
  10149. unassignedFieldFlags &= ~((int64)1 << (resultLocalVarField - 1 + i));
  10150. }
  10151. wasValidInitKind = true;
  10152. if ((fieldResult) || (mPropDef != NULL))
  10153. {
  10154. if (mResultFieldInstance != NULL)
  10155. {
  10156. auto autoComplete = GetAutoComplete();
  10157. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(identifierNode)))
  10158. {
  10159. auto fieldDef = mResultFieldInstance->GetFieldDef();
  10160. if (fieldDef != NULL)
  10161. autoComplete->SetDefinitionLocation(fieldDef->GetRefNode());
  10162. }
  10163. }
  10164. mResult = fieldResult;
  10165. PerformAssignment(assignExpr, true, BfTypedValue());
  10166. mResult = BfTypedValue();
  10167. }
  10168. else
  10169. {
  10170. mModule->Fail(StrFormat("'%s' does not contain a definition for '%s'", mModule->TypeToString(initValue.mType).c_str(),
  10171. findName.c_str()), identifierNode);
  10172. }
  10173. }
  10174. }
  10175. else
  10176. {
  10177. auto autoComplete = GetAutoComplete();
  10178. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(elementExpr)))
  10179. {
  10180. if (auto identiferNode = BfNodeDynCast<BfIdentifierNode>(elementExpr))
  10181. {
  10182. auto typeInstance = initValue.mType->ToTypeInstance();
  10183. if (typeInstance != NULL)
  10184. {
  10185. String filter;
  10186. identiferNode->ToString(filter);
  10187. autoComplete->AddTypeMembers(typeInstance, false, true, filter, typeInstance, false, true, false);
  10188. }
  10189. }
  10190. }
  10191. bool wasFirstAdd = isFirstAdd;
  10192. if (isFirstAdd)
  10193. {
  10194. BfExprEvaluator exprEvaluator(mModule);
  10195. exprEvaluator.mFunctionBindResult = &addFunctionBindResult;
  10196. SizedArray<BfExpression*, 2> argExprs;
  10197. argExprs.push_back(elementExpr);
  10198. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  10199. BfResolvedArgs argValues(&sizedArgExprs);
  10200. exprEvaluator.ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  10201. exprEvaluator.MatchMethod(elementExpr, NULL, initValue, false, false, "Add", argValues, BfMethodGenericArguments());
  10202. if (addFunctionBindResult.mMethodInstance != NULL)
  10203. CreateCall(initExpr, addFunctionBindResult.mMethodInstance, addFunctionBindResult.mFunc, true, addFunctionBindResult.mIRArgs);
  10204. isFirstAdd = false;
  10205. }
  10206. else if ((addFunctionBindResult.mMethodInstance == NULL) || (addFunctionBindResult.mMethodInstance->GetParamCount() == 0))
  10207. {
  10208. mModule->CreateValueFromExpression(elementExpr, NULL, (BfEvalExprFlags)(mBfEvalExprFlags& BfEvalExprFlags_InheritFlags));
  10209. }
  10210. else
  10211. {
  10212. auto argValue = mModule->CreateValueFromExpression(elementExpr, addFunctionBindResult.mMethodInstance->GetParamType(0), (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  10213. if ((argValue) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  10214. {
  10215. SizedArray<BfIRValue, 2> irArgs;
  10216. PushThis(elementExpr, initValue, addFunctionBindResult.mMethodInstance, irArgs);
  10217. PushArg(argValue, irArgs);
  10218. for (int argIdx = (int)irArgs.size(); argIdx < (int)addFunctionBindResult.mIRArgs.size(); argIdx++)
  10219. irArgs.Add(addFunctionBindResult.mIRArgs[argIdx]);
  10220. CreateCall(initExpr, addFunctionBindResult.mMethodInstance, addFunctionBindResult.mFunc, true, irArgs);
  10221. }
  10222. }
  10223. wasValidInitKind = true;
  10224. }
  10225. if (!wasValidInitKind)
  10226. {
  10227. mModule->Fail("Invalid initializer member declarator", initExpr);
  10228. }
  10229. }
  10230. if (unassignedFieldFlags != 0)
  10231. {
  10232. auto curBlock = mModule->mBfIRBuilder->GetInsertBlock();
  10233. mModule->mBfIRBuilder->SetInsertPointAtStart(initBlock);
  10234. mModule->mBfIRBuilder->CreateMemSet(initValue.mValue, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  10235. mModule->GetConstValue(initValue.mType->mSize), initValue.mType->mAlign);
  10236. mModule->mBfIRBuilder->SetInsertPoint(curBlock);
  10237. }
  10238. mResult = initValue;
  10239. }
  10240. void BfExprEvaluator::Visit(BfCollectionInitializerExpression* arrayInitExpr)
  10241. {
  10242. mModule->Fail("Collection initializer not usable here", arrayInitExpr);
  10243. }
  10244. void BfExprEvaluator::Visit(BfTypeOfExpression* typeOfExpr)
  10245. {
  10246. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  10247. auto autoComplete = GetAutoComplete();
  10248. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  10249. {
  10250. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  10251. }
  10252. BfType* type;
  10253. if ((typeOfExpr->mTypeRef != NULL) && (typeOfExpr->mTypeRef->IsA<BfVarTypeReference>()))
  10254. {
  10255. type = mModule->GetPrimitiveType(BfTypeCode_Var);
  10256. }
  10257. else
  10258. {
  10259. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_AllowGlobalsSelf | BfResolveTypeRefFlag_AllowUnboundGeneric));
  10260. }
  10261. if (type == NULL)
  10262. {
  10263. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  10264. return;
  10265. }
  10266. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10267. mResult = BfTypedValue(mModule->CreateTypeDataRef(type), typeType);
  10268. }
  10269. bool BfExprEvaluator::LookupTypeProp(BfTypeOfExpression* typeOfExpr, BfIdentifierNode* propName)
  10270. {
  10271. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  10272. BfType* type;
  10273. //
  10274. {
  10275. // We ignore errors because we go through the normal Visit(BfTypeOfExpression) if this fails, which will throw the error again
  10276. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  10277. if (auto genericTypeRef = BfNodeDynCast<BfGenericInstanceTypeRef>(typeOfExpr->mTypeRef))
  10278. {
  10279. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  10280. type = mModule->ResolveTypeRefAllowUnboundGenerics(typeOfExpr->mTypeRef, BfPopulateType_Identity);
  10281. }
  10282. else
  10283. {
  10284. type = ResolveTypeRef(typeOfExpr->mTypeRef, BfPopulateType_Identity, BfResolveTypeRefFlag_IgnoreLookupError);
  10285. }
  10286. }
  10287. if (type == NULL)
  10288. {
  10289. mResult = mModule->GetDefaultTypedValue(mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef));
  10290. return false;
  10291. }
  10292. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10293. mModule->PopulateType(type);
  10294. auto typeInstance = type->ToTypeInstance();
  10295. auto _BoolResult = [&](bool val)
  10296. {
  10297. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, val ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  10298. };
  10299. auto _Int32Result = [&](int32 val)
  10300. {
  10301. mResult = BfTypedValue(mModule->GetConstValue32(val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  10302. };
  10303. String memberName;
  10304. propName->ToString(memberName);
  10305. bool handled = true;
  10306. if (memberName == "IsTypedPrimitive")
  10307. _BoolResult(type->IsPrimitiveType());
  10308. else if (memberName == "IsObject")
  10309. _BoolResult(type->IsObject());
  10310. else if (memberName == "IsValueType")
  10311. _BoolResult(type->IsValueType());
  10312. else if (memberName == "IsPrimitive")
  10313. _BoolResult(type->IsPrimitiveType());
  10314. else if (memberName == "IsInteger")
  10315. _BoolResult(type->IsInteger());
  10316. else if (memberName == "IsIntegral")
  10317. _BoolResult(type->IsIntegral());
  10318. else if (memberName == "IsSigned")
  10319. _BoolResult(type->IsSigned());
  10320. else if (memberName == "IsFloatingPoint")
  10321. _BoolResult(type->IsFloat());
  10322. else if (memberName == "IsPointer")
  10323. _BoolResult(type->IsPointer());
  10324. else if (memberName == "IsStruct")
  10325. _BoolResult(type->IsStruct());
  10326. else if (memberName == "IsSplattable")
  10327. _BoolResult(type->IsSplattable());
  10328. else if (memberName == "IsUnion")
  10329. _BoolResult(type->IsUnion());
  10330. else if (memberName == "IsBoxed")
  10331. _BoolResult(type->IsBoxed());
  10332. else if (memberName == "IsEnum")
  10333. _BoolResult(type->IsEnum());
  10334. else if (memberName == "IsTuple")
  10335. _BoolResult(type->IsTuple());
  10336. else if (memberName == "IsNullable")
  10337. _BoolResult(type->IsNullable());
  10338. else if (memberName == "IsGenericType")
  10339. _BoolResult(type->IsGenericTypeInstance());
  10340. else if (memberName == "IsGenericParam")
  10341. _BoolResult(type->IsGenericParam());
  10342. else if (memberName == "IsArray")
  10343. _BoolResult(type->IsArray());
  10344. else if (memberName == "IsSizedArray")
  10345. _BoolResult(type->IsSizedArray());
  10346. else if (memberName == "TypeId")
  10347. {
  10348. _Int32Result(type->mTypeId);
  10349. mResult.mType = mModule->ResolveTypeDef(mModule->mCompiler->mReflectTypeIdTypeDef);
  10350. }
  10351. else if (memberName == "GenericParamCount")
  10352. {
  10353. auto genericTypeInst = type->ToGenericTypeInstance();
  10354. _Int32Result((genericTypeInst != NULL) ? (int)genericTypeInst->mGenericTypeInfo->mTypeGenericArguments.size() : 0);
  10355. }
  10356. else if (memberName == "Size")
  10357. _Int32Result(type->mSize);
  10358. else if (memberName == "Align")
  10359. _Int32Result(type->mAlign);
  10360. else if (memberName == "Stride")
  10361. _Int32Result(type->GetStride());
  10362. else if (memberName == "InstanceSize")
  10363. _Int32Result((typeInstance != NULL) ? typeInstance->mInstSize : type->mSize);
  10364. else if (memberName == "InstanceAlign")
  10365. _Int32Result((typeInstance != NULL) ? typeInstance->mInstAlign : type->mSize);
  10366. else if (memberName == "InstanceStride")
  10367. _Int32Result((typeInstance != NULL) ? typeInstance->GetInstStride() : type->GetStride());
  10368. else if (memberName == "UnderlyingType")
  10369. {
  10370. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef);
  10371. if (type->IsGenericParam())
  10372. {
  10373. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)type);
  10374. if (genericParamInstance->IsEnum())
  10375. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(typeType)), typeType);
  10376. }
  10377. else if (type->IsEnum())
  10378. {
  10379. auto underlyingType = type->GetUnderlyingType();
  10380. if (underlyingType != NULL)
  10381. {
  10382. mModule->AddDependency(underlyingType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10383. mResult = BfTypedValue(mModule->CreateTypeDataRef(underlyingType), typeType);
  10384. }
  10385. }
  10386. }
  10387. else if (memberName == "BitSize")
  10388. {
  10389. auto int32Type = mModule->GetPrimitiveType(BfTypeCode_Int32);
  10390. BfType* checkType = type;
  10391. if (checkType->IsTypedPrimitive())
  10392. checkType = checkType->GetUnderlyingType();
  10393. if (checkType->IsGenericParam())
  10394. {
  10395. mResult = mModule->GetDefaultTypedValue(int32Type, false, Beefy::BfDefaultValueKind_Undef);
  10396. return true;
  10397. }
  10398. if ((typeInstance != NULL) && (typeInstance->IsEnum()))
  10399. {
  10400. if (typeInstance->mTypeInfoEx != NULL)
  10401. {
  10402. int64 minValue = typeInstance->mTypeInfoEx->mMinValue;
  10403. if (minValue < 0)
  10404. minValue = ~minValue;
  10405. int64 maxValue = typeInstance->mTypeInfoEx->mMaxValue;
  10406. if (maxValue < 0)
  10407. maxValue = ~maxValue;
  10408. uint64 value = (uint64)minValue | (uint64)maxValue;
  10409. int bitCount = 1;
  10410. if (typeInstance->mTypeInfoEx->mMinValue < 0)
  10411. bitCount++;
  10412. while (value >>= 1)
  10413. bitCount++;
  10414. mModule->AddDependency(typeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  10415. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, bitCount), int32Type);
  10416. return true;
  10417. }
  10418. }
  10419. int bitSize = checkType->mSize * 8;
  10420. if (checkType->GetTypeCode() == BfTypeCode_Boolean)
  10421. bitSize = 1;
  10422. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, bitSize), int32Type);
  10423. return true;
  10424. }
  10425. else if ((memberName == "MinValue") || (memberName == "MaxValue"))
  10426. {
  10427. bool isMin = memberName == "MinValue";
  10428. bool isBitSize = memberName == "BitSize";
  10429. BfType* checkType = type;
  10430. if (checkType->IsTypedPrimitive())
  10431. checkType = checkType->GetUnderlyingType();
  10432. if (checkType->IsGenericParam())
  10433. {
  10434. bool foundMatch = false;
  10435. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)checkType);
  10436. if (((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Enum) != 0) ||
  10437. ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsInstanceOf(mModule->mCompiler->mEnumTypeDef))))
  10438. foundMatch = true;
  10439. else
  10440. {
  10441. for (auto constraint : genericParamInstance->mInterfaceConstraints)
  10442. {
  10443. if (constraint->IsInstanceOf(mModule->mCompiler->mIIntegerTypeDef))
  10444. foundMatch = true;
  10445. }
  10446. }
  10447. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  10448. {
  10449. for (int genericParamIdx = (int)mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments.size();
  10450. genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  10451. {
  10452. genericParamInstance = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  10453. if (genericParamInstance->mExternType == type)
  10454. {
  10455. if (((genericParamInstance->mGenericParamFlags & BfGenericParamFlag_Enum) != 0) ||
  10456. ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsInstanceOf(mModule->mCompiler->mEnumTypeDef))))
  10457. foundMatch = true;
  10458. }
  10459. }
  10460. }
  10461. if (foundMatch)
  10462. {
  10463. mResult = mModule->GetDefaultTypedValue(type, false, Beefy::BfDefaultValueKind_Undef);
  10464. return true;
  10465. }
  10466. }
  10467. if (checkType->IsPrimitiveType())
  10468. {
  10469. auto primType = (BfPrimitiveType*)checkType;
  10470. if ((typeInstance != NULL) && (typeInstance->IsEnum()))
  10471. {
  10472. if (typeInstance->mTypeInfoEx != NULL)
  10473. {
  10474. mModule->AddDependency(typeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ReadFields);
  10475. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)typeInstance->mTypeInfoEx->mMinValue : (uint64)typeInstance->mTypeInfoEx->mMaxValue), typeInstance);
  10476. return true;
  10477. }
  10478. }
  10479. else
  10480. {
  10481. switch (primType->mTypeDef->mTypeCode)
  10482. {
  10483. case BfTypeCode_Int8:
  10484. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x80 : 0x7F), primType);
  10485. return true;
  10486. case BfTypeCode_Int16:
  10487. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? -0x8000 : 0x7FFF), primType);
  10488. return true;
  10489. case BfTypeCode_Int32:
  10490. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x80000000LL : 0x7FFFFFFF), primType);
  10491. return true;
  10492. case BfTypeCode_Int64:
  10493. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x8000000000000000LL : (uint64)0x7FFFFFFFFFFFFFFFLL), primType);
  10494. return true;
  10495. case BfTypeCode_UInt8:
  10496. case BfTypeCode_Char8:
  10497. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFF), primType);
  10498. return true;
  10499. case BfTypeCode_UInt16:
  10500. case BfTypeCode_Char16:
  10501. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : 0xFFFF), primType);
  10502. return true;
  10503. case BfTypeCode_UInt32:
  10504. case BfTypeCode_Char32:
  10505. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFLL), primType);
  10506. return true;
  10507. case BfTypeCode_UInt64:
  10508. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFFFFFFFFFLL), primType);
  10509. return true;
  10510. case BfTypeCode_IntPtr:
  10511. if (mModule->mSystem->mPtrSize == 8)
  10512. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x8000000000000000LL : (uint64)0x7FFFFFFFFFFFFFFFLL), primType);
  10513. else
  10514. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? (uint64)-0x80000000LL : 0x7FFFFFFF), primType);
  10515. return true;
  10516. case BfTypeCode_UIntPtr:
  10517. if (mModule->mSystem->mPtrSize == 8)
  10518. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFFFFFFFFFLL), primType);
  10519. else
  10520. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, isMin ? 0 : (uint64)0xFFFFFFFFLL), primType);
  10521. return true;
  10522. default: break;
  10523. }
  10524. }
  10525. }
  10526. if (type->IsEnum())
  10527. {
  10528. mModule->Fail(StrFormat("'MinValue' cannot be used on enum with payload '%s'", mModule->TypeToString(type).c_str()), propName);
  10529. }
  10530. else
  10531. {
  10532. mModule->Fail(StrFormat("'%s' cannot be used on type '%s'", memberName.c_str(), mModule->TypeToString(type).c_str()), propName);
  10533. }
  10534. }
  10535. else
  10536. return false;
  10537. if ((type->IsGenericParam()) && (!mModule->mIsComptimeModule))
  10538. {
  10539. if (mResult.mType != NULL)
  10540. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, Beefy::BfDefaultValueKind_Undef);
  10541. }
  10542. auto autoComplete = GetAutoComplete();
  10543. if ((autoComplete != NULL) && (typeOfExpr->mTypeRef != NULL))
  10544. {
  10545. autoComplete->CheckTypeRef(typeOfExpr->mTypeRef, false, true);
  10546. }
  10547. return true;
  10548. }
  10549. void BfExprEvaluator::DoTypeIntAttr(BfTypeReference* typeRef, BfTokenNode* commaToken, BfIdentifierNode* memberName, BfToken token)
  10550. {
  10551. auto autoComplete = GetAutoComplete();
  10552. auto type = mModule->ResolveTypeRef(typeRef, BfPopulateType_Data, BfResolveTypeRefFlag_AutoComplete);
  10553. if (type == NULL)
  10554. return;
  10555. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage); // Local usage ensures it changes when the type data changes
  10556. auto typeInst = type->ToTypeInstance();
  10557. if ((typeInst != NULL) && (typeInst->mTypeDef->mIsOpaque))
  10558. {
  10559. mModule->Fail(StrFormat("Unable to determine attributes for opaque type '%s'", mModule->TypeToString(type).c_str()), typeRef);
  10560. }
  10561. BfType* sizeType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  10562. int attrVal = 0;
  10563. switch (token)
  10564. {
  10565. case BfToken_SizeOf: attrVal = type->mSize; break;
  10566. case BfToken_AlignOf: attrVal = type->mAlign; break;
  10567. case BfToken_StrideOf: attrVal = type->GetStride(); break;
  10568. default: break;
  10569. }
  10570. if (token == BfToken_OffsetOf)
  10571. {
  10572. bool found = false;
  10573. String findName;
  10574. if (memberName != NULL)
  10575. findName = memberName->ToString();
  10576. BfAstNode* refNode = typeRef;
  10577. if (memberName != NULL)
  10578. refNode = memberName;
  10579. auto checkTypeInst = typeInst;
  10580. while (checkTypeInst != NULL)
  10581. {
  10582. checkTypeInst->mTypeDef->PopulateMemberSets();
  10583. String filter;
  10584. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(commaToken, memberName, filter)))
  10585. {
  10586. auto activeTypeDef = mModule->GetActiveTypeDef();
  10587. mModule->PopulateType(checkTypeInst);
  10588. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  10589. for (auto fieldDef : checkTypeInst->mTypeDef->mFields)
  10590. {
  10591. if (fieldDef->mIsStatic)
  10592. continue;
  10593. if (!mModule->CheckProtection(protectionCheckFlags, typeInst, fieldDef->mDeclaringType->mProject, fieldDef->mProtection, typeInst))
  10594. continue;
  10595. if ((!typeInst->IsTypeMemberIncluded(fieldDef->mDeclaringType, activeTypeDef, mModule)) ||
  10596. (!typeInst->IsTypeMemberAccessible(fieldDef->mDeclaringType, activeTypeDef)))
  10597. continue;
  10598. auto& fieldInst = checkTypeInst->mFieldInstances[fieldDef->mIdx];
  10599. autoComplete->AddField(checkTypeInst, fieldDef, &fieldInst, filter);
  10600. }
  10601. }
  10602. BfMemberSetEntry* memberSetEntry = NULL;
  10603. if (checkTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  10604. {
  10605. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  10606. if (fieldDef != NULL)
  10607. {
  10608. if (fieldDef->mIsStatic)
  10609. mModule->Fail(StrFormat("Cannot generate an offset from static field '%s.%s'", mModule->TypeToString(type).c_str(), fieldDef->mName.c_str()), refNode);
  10610. mModule->PopulateType(checkTypeInst);
  10611. auto& fieldInst = checkTypeInst->mFieldInstances[fieldDef->mIdx];
  10612. attrVal = fieldInst.mDataOffset;
  10613. found = true;
  10614. break;
  10615. }
  10616. }
  10617. checkTypeInst = checkTypeInst->mBaseType;
  10618. }
  10619. if (!found)
  10620. {
  10621. mModule->Fail(StrFormat("Unable to locate field '%s.%s'", mModule->TypeToString(type).c_str(), findName.c_str()), refNode);
  10622. }
  10623. }
  10624. bool isUndefVal = false;
  10625. if (type->IsGenericParam())
  10626. isUndefVal = true;
  10627. if (type->IsSizedArray())
  10628. {
  10629. auto sizedArray = (BfSizedArrayType*)type;
  10630. if (sizedArray->mElementCount == -1)
  10631. isUndefVal = true;
  10632. }
  10633. if (isUndefVal)
  10634. {
  10635. // We do this so we know it's a constant but we can't assume anything about its value
  10636. // We make the value an Int32 which doesn't match the IntPtr type, but it allows us to
  10637. // assume it can be implicitly cased to int32
  10638. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->MapType(sizeType)), sizeType);
  10639. }
  10640. else
  10641. mResult = BfTypedValue(mModule->GetConstValue(attrVal, sizeType), sizeType);
  10642. }
  10643. void BfExprEvaluator::Visit(BfSizeOfExpression* sizeOfExpr)
  10644. {
  10645. DoTypeIntAttr(sizeOfExpr->mTypeRef, NULL, NULL, BfToken_SizeOf);
  10646. }
  10647. void BfExprEvaluator::Visit(BfAlignOfExpression* alignOfExpr)
  10648. {
  10649. DoTypeIntAttr(alignOfExpr->mTypeRef, NULL, NULL, BfToken_AlignOf);
  10650. }
  10651. void BfExprEvaluator::Visit(BfStrideOfExpression* strideOfExpr)
  10652. {
  10653. DoTypeIntAttr(strideOfExpr->mTypeRef, NULL, NULL, BfToken_StrideOf);
  10654. }
  10655. void BfExprEvaluator::Visit(BfOffsetOfExpression* offsetOfExpr)
  10656. {
  10657. DoTypeIntAttr(offsetOfExpr->mTypeRef, offsetOfExpr->mCommaToken, offsetOfExpr->mMemberName, BfToken_OffsetOf);
  10658. }
  10659. void BfExprEvaluator::Visit(BfNameOfExpression* nameOfExpr)
  10660. {
  10661. String name;
  10662. if (mModule->IsInSpecializedGeneric())
  10663. {
  10664. if (auto identifierNode = BfNodeDynCastExact<BfIdentifierNode>(nameOfExpr->mTarget))
  10665. {
  10666. // This is necessary so we don't resolve 'T' to the actual generic argument type
  10667. name = identifierNode->ToString();
  10668. }
  10669. }
  10670. if (name.IsEmpty())
  10671. {
  10672. auto type = mModule->ResolveTypeRef(nameOfExpr->mTarget, {}, BfPopulateType_IdentityNoRemapAlias,
  10673. (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_AllowUnboundGeneric | BfResolveTypeRefFlag_IgnoreLookupError | BfResolveTypeRefFlag_IgnoreProtection));
  10674. if (type != NULL)
  10675. {
  10676. auto typeInst = type->ToTypeInstance();
  10677. if (typeInst != NULL)
  10678. name = typeInst->mTypeDef->mName->ToString();
  10679. else
  10680. name = mModule->TypeToString(type);
  10681. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_NameReference);
  10682. // Just do this for autocomplete
  10683. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  10684. VisitChild(nameOfExpr->mTarget);
  10685. }
  10686. }
  10687. if (name.IsEmpty())
  10688. {
  10689. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(nameOfExpr->mTarget))
  10690. {
  10691. String targetStr = nameOfExpr->mTarget->ToString();
  10692. BfAtomComposite targetComposite;
  10693. bool isValid = mModule->mSystem->ParseAtomComposite(targetStr, targetComposite);
  10694. bool namespaceExists = false;
  10695. BfProject* bfProject = NULL;
  10696. auto activeTypeDef = mModule->GetActiveTypeDef();
  10697. if (activeTypeDef != NULL)
  10698. bfProject = activeTypeDef->mProject;
  10699. auto _CheckProject = [&](BfProject* project)
  10700. {
  10701. if ((isValid) && (project->mNamespaces.ContainsKey(targetComposite)))
  10702. namespaceExists = true;
  10703. };
  10704. if (bfProject != NULL)
  10705. {
  10706. for (int depIdx = -1; depIdx < (int)bfProject->mDependencies.size(); depIdx++)
  10707. {
  10708. BfProject* depProject = (depIdx == -1) ? bfProject : bfProject->mDependencies[depIdx];
  10709. _CheckProject(depProject);
  10710. }
  10711. }
  10712. else
  10713. {
  10714. for (auto project : mModule->mSystem->mProjects)
  10715. _CheckProject(project);
  10716. }
  10717. if (namespaceExists)
  10718. {
  10719. if (mModule->mCompiler->mResolvePassData != NULL)
  10720. {
  10721. if (auto sourceClassifier = mModule->mCompiler->mResolvePassData->GetSourceClassifier(nameOfExpr->mTarget))
  10722. {
  10723. BfAstNode* checkIdentifier = identifer;
  10724. while (true)
  10725. {
  10726. auto qualifiedIdentifier = BfNodeDynCast<BfQualifiedNameNode>(checkIdentifier);
  10727. if (qualifiedIdentifier == NULL)
  10728. break;
  10729. sourceClassifier->SetElementType(qualifiedIdentifier->mRight, BfSourceElementType_Namespace);
  10730. checkIdentifier = qualifiedIdentifier->mLeft;
  10731. }
  10732. sourceClassifier->SetElementType(checkIdentifier, BfSourceElementType_Namespace);
  10733. }
  10734. }
  10735. name = targetComposite.mParts[targetComposite.mSize - 1]->ToString();
  10736. }
  10737. }
  10738. }
  10739. if (name.IsEmpty())
  10740. {
  10741. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NameOf));
  10742. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mBfIRBuilder->mIgnoreWrites, true);
  10743. VisitChild(nameOfExpr->mTarget);
  10744. if ((mBfEvalExprFlags & BfEvalExprFlags_NameOfSuccess) != 0)
  10745. {
  10746. BfAstNode* nameNode = nameOfExpr->mTarget;
  10747. if (auto attributedIdentifierNode = BfNodeDynCast<BfAttributedIdentifierNode>(nameNode))
  10748. nameNode = attributedIdentifierNode->mIdentifier;
  10749. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(nameNode))
  10750. nameNode = memberReferenceExpr->mMemberName;
  10751. if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(nameNode))
  10752. nameNode = qualifiedNameNode->mRight;
  10753. name = nameNode->ToString();
  10754. }
  10755. else if (mResultFieldInstance != NULL)
  10756. {
  10757. auto fieldDef = mResultFieldInstance->GetFieldDef();
  10758. if (fieldDef != NULL)
  10759. name = fieldDef->mName;
  10760. }
  10761. else if (mResultLocalVar != NULL)
  10762. {
  10763. name = mResultLocalVar->mName;
  10764. }
  10765. else if (mPropDef != NULL)
  10766. {
  10767. name = mPropDef->mName;
  10768. }
  10769. }
  10770. if ((name.IsEmpty()) && (nameOfExpr->mTarget != NULL))
  10771. mModule->Fail("Expression does not have a name", nameOfExpr->mTarget);
  10772. mResult = BfTypedValue(mModule->GetStringObjectValue(name), mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  10773. }
  10774. void BfExprEvaluator::Visit(BfIsConstExpression* isConstExpr)
  10775. {
  10776. if (isConstExpr->mExpression == NULL)
  10777. {
  10778. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  10779. return;
  10780. }
  10781. BfMethodState methodState;
  10782. SetAndRestoreValue<BfMethodState*> prevMethodState(mModule->mCurMethodState, &methodState, false);
  10783. if (mModule->mCurMethodState == NULL)
  10784. prevMethodState.Set();
  10785. methodState.mTempKind = BfMethodState::TempKind_NonStatic;
  10786. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  10787. SetAndRestoreValue<bool> allowUninitReads(mModule->mCurMethodState->mAllowUinitReads, true);
  10788. BfEvalExprFlags exprFlags = BfEvalExprFlags_None;
  10789. auto result = mModule->CreateValueFromExpression(isConstExpr->mExpression, NULL, BfEvalExprFlags_DeclType);
  10790. bool isConst = mModule->mBfIRBuilder->IsConstValue(result.mValue);
  10791. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, isConst ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  10792. }
  10793. void BfExprEvaluator::Visit(BfDefaultExpression* defaultExpr)
  10794. {
  10795. auto autoComplete = GetAutoComplete();
  10796. if (autoComplete != NULL)
  10797. autoComplete->CheckTypeRef(defaultExpr->mTypeRef, false, true);
  10798. BfType* type = NULL;
  10799. if (defaultExpr->mOpenParen == NULL)
  10800. {
  10801. if (mExpectingType)
  10802. {
  10803. type = mExpectingType;
  10804. }
  10805. else
  10806. {
  10807. mModule->Fail("Type cannot be inferred, consider adding explicit type name", defaultExpr);
  10808. return;
  10809. }
  10810. }
  10811. else
  10812. type = mModule->ResolveTypeRef(defaultExpr->mTypeRef);
  10813. if (type == NULL)
  10814. return;
  10815. BfDefaultValueKind defaultKind = BfDefaultValueKind_Const;
  10816. if (type->IsRef())
  10817. {
  10818. mModule->Fail(StrFormat("There is no default value for type '%s'", mModule->TypeToString(type).c_str()), defaultExpr);
  10819. defaultKind = BfDefaultValueKind_Addr;
  10820. }
  10821. mModule->ValidateAllocation(type, defaultExpr->mTypeRef);
  10822. mModule->AddDependency(type, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10823. mResult = mModule->GetDefaultTypedValue(type, true, defaultKind);
  10824. }
  10825. void BfExprEvaluator::Visit(BfUninitializedExpression* uninitialziedExpr)
  10826. {
  10827. mModule->Fail("Invalid use of the '?' uninitialized specifier", uninitialziedExpr);
  10828. }
  10829. void BfExprEvaluator::Visit(BfCheckTypeExpression* checkTypeExpr)
  10830. {
  10831. auto targetValue = mModule->CreateValueFromExpression(checkTypeExpr->mTarget, NULL, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  10832. if (!targetValue)
  10833. return;
  10834. if (checkTypeExpr->mTypeRef == NULL)
  10835. {
  10836. mModule->AssertErrorState();
  10837. return;
  10838. }
  10839. auto autoComplete = GetAutoComplete();
  10840. if (autoComplete != NULL)
  10841. autoComplete->CheckTypeRef(checkTypeExpr->mTypeRef, false, true);
  10842. auto targetType = mModule->ResolveTypeRef(checkTypeExpr->mTypeRef, BfPopulateType_Declaration);
  10843. if (!targetType)
  10844. {
  10845. mModule->AssertErrorState();
  10846. return;
  10847. }
  10848. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10849. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  10850. if (targetValue.mType->IsVar())
  10851. {
  10852. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Undef);
  10853. return;
  10854. }
  10855. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  10856. {
  10857. auto typeInstance = targetValue.mType->ToTypeInstance();
  10858. if (targetValue.mType->IsWrappableType())
  10859. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  10860. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  10861. if (!matches)
  10862. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  10863. if (!typeInstance->IsGenericParam())
  10864. {
  10865. if (matches)
  10866. mModule->Warn(0, "The result of this operation is always 'true'", checkTypeExpr->mIsToken);
  10867. else
  10868. mModule->Warn(0, "The result of this operation is always 'false'", checkTypeExpr->mIsToken);
  10869. }
  10870. mResult = BfTypedValue(mModule->GetConstValue(matches ? 1 : 0, boolType), boolType);
  10871. return;
  10872. }
  10873. if (targetType->IsValueType())
  10874. {
  10875. if ((targetValue.mType != mModule->mContext->mBfObjectType) && (!targetValue.mType->IsInterface()))
  10876. {
  10877. mResult = BfTypedValue(mModule->GetConstValue(0, boolType), boolType);
  10878. return;
  10879. }
  10880. }
  10881. int wantTypeId = 0;
  10882. if (!targetType->IsGenericParam())
  10883. wantTypeId = targetType->mTypeId;
  10884. auto objectType = mModule->mContext->mBfObjectType;
  10885. mModule->PopulateType(objectType, BfPopulateType_Full);
  10886. targetValue = mModule->LoadValue(targetValue);
  10887. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  10888. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  10889. bool wasGenericParamType = false;
  10890. if ((srcTypeInstance != NULL) && (targetTypeInstance != NULL))
  10891. {
  10892. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  10893. {
  10894. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  10895. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  10896. // it may be a "necessary cast" indeed
  10897. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  10898. {
  10899. if (srcTypeInstance == targetType)
  10900. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary check, the value is already type '%s'",
  10901. mModule->TypeToString(srcTypeInstance).c_str()), checkTypeExpr->mIsToken);
  10902. else
  10903. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary check, '%s' is a subtype of '%s'",
  10904. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), checkTypeExpr->mIsToken);
  10905. }
  10906. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  10907. return;
  10908. }
  10909. else if ((!targetType->IsInterface()) && (srcTypeInstance != mModule->mContext->mBfObjectType) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  10910. {
  10911. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  10912. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), checkTypeExpr->mIsToken);
  10913. }
  10914. }
  10915. if (mModule->mCompiler->IsAutocomplete())
  10916. {
  10917. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Addr);
  10918. return;
  10919. }
  10920. auto irb = mModule->mBfIRBuilder;
  10921. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  10922. auto matchBB = mModule->mBfIRBuilder->CreateBlock("is.match");
  10923. auto endBB = mModule->mBfIRBuilder->CreateBlock("is.done");
  10924. BfIRValue boolResult = mModule->CreateAlloca(boolType);
  10925. irb->CreateAlignedStore(irb->CreateConst(BfTypeCode_Boolean, 0), boolResult, 1);
  10926. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBB, endBB);
  10927. mModule->AddBasicBlock(matchBB);
  10928. irb->CreateAlignedStore(irb->CreateConst(BfTypeCode_Boolean, 1), boolResult, 1);
  10929. irb->CreateBr(endBB);
  10930. mModule->AddBasicBlock(endBB);
  10931. mResult = BfTypedValue(irb->CreateAlignedLoad(boolResult, 1), boolType);
  10932. }
  10933. void BfExprEvaluator::Visit(BfDynamicCastExpression* dynCastExpr)
  10934. {
  10935. auto targetValue = mModule->CreateValueFromExpression(dynCastExpr->mTarget);
  10936. auto targetType = mModule->ResolveTypeRefAllowUnboundGenerics(dynCastExpr->mTypeRef, BfPopulateType_Data, false);
  10937. auto autoComplete = GetAutoComplete();
  10938. if (autoComplete != NULL)
  10939. {
  10940. autoComplete->CheckTypeRef(dynCastExpr->mTypeRef, false, true);
  10941. }
  10942. auto origTargetType = targetType;
  10943. if (!targetValue)
  10944. return;
  10945. if (!targetType)
  10946. {
  10947. mModule->AssertErrorState();
  10948. return;
  10949. }
  10950. bool wasGenericParamType = false;
  10951. if (targetType->IsGenericParam())
  10952. {
  10953. //targetType = mModule->ResolveGenericType(targetType);
  10954. //wasGenericParamType = true;
  10955. }
  10956. if ((targetValue.mType->IsMethodRef()) || (targetType->IsMethodRef()))
  10957. {
  10958. // We can never cast a MethodRef to any class type
  10959. mResult = mModule->GetDefaultTypedValue(targetType);
  10960. return;
  10961. }
  10962. if (mModule->mContext->mResolvingVarField)
  10963. {
  10964. mResult = mModule->GetDefaultTypedValue(targetType);
  10965. return;
  10966. }
  10967. mModule->AddDependency(targetType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_ExprTypeReference);
  10968. if (targetType->IsGenericParam())
  10969. {
  10970. wasGenericParamType = true;
  10971. BfGenericParamInstance* origGenericParam = NULL;
  10972. int pass = 0;
  10973. while ((targetType != NULL) && (targetType->IsGenericParam()))
  10974. {
  10975. auto genericParamType = (BfGenericParamType*)targetType;
  10976. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  10977. if (pass == 0)
  10978. origGenericParam = genericParam;
  10979. auto typeConstraint = genericParam->mTypeConstraint;
  10980. if ((typeConstraint == NULL) && (genericParam->mGenericParamFlags & (BfGenericParamFlag_Class | BfGenericParamFlag_Interface)))
  10981. typeConstraint = mModule->mContext->mBfObjectType;
  10982. targetType = typeConstraint;
  10983. if (++pass >= 100) // Sanity - but we should have caught circular error before
  10984. break;
  10985. }
  10986. if ((targetType == NULL) || (!targetType->IsObjectOrInterface()))
  10987. {
  10988. mModule->Fail(StrFormat("The type parameter '%s' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' or 'interface' constraint",
  10989. origGenericParam->GetGenericParamDef()->mName.c_str()), dynCastExpr->mTypeRef);
  10990. return;
  10991. }
  10992. }
  10993. if (targetType->IsVar())
  10994. {
  10995. mResult = mModule->GetDefaultTypedValue(targetType);
  10996. return;
  10997. }
  10998. if ((!targetType->IsObjectOrInterface()) && (!targetType->IsNullable()))
  10999. {
  11000. mModule->Fail(StrFormat("The as operator must be used with a reference type or nullable type ('%s' is a non-nullable value type)",
  11001. mModule->TypeToString(origTargetType).c_str()), dynCastExpr->mTypeRef);
  11002. return;
  11003. }
  11004. if (targetValue.mType->IsGenericParam())
  11005. {
  11006. auto genericParamType = (BfGenericParamType*)targetValue.mType;
  11007. auto genericParam = mModule->GetGenericParamInstance(genericParamType);
  11008. auto typeConstraint = genericParam->mTypeConstraint;
  11009. if (typeConstraint == NULL)
  11010. typeConstraint = mModule->mContext->mBfObjectType;
  11011. if ((typeConstraint->IsDelegate()) && (typeConstraint == targetType))
  11012. {
  11013. // Delegate constraints may be matched by valueless method references, so this won't always match (don't warn)
  11014. mResult = mModule->GetDefaultTypedValue(targetType);
  11015. return;
  11016. }
  11017. targetValue = mModule->GetDefaultTypedValue(typeConstraint);
  11018. }
  11019. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  11020. auto _CheckResult = [&]()
  11021. {
  11022. if ((mResult) && (origTargetType->IsGenericParam()))
  11023. mResult = mModule->GetDefaultTypedValue(origTargetType, false, BfDefaultValueKind_Undef);
  11024. };
  11025. if ((targetValue.mType->IsNullable()) && (targetType->IsInterface()))
  11026. {
  11027. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_SilentFail);
  11028. if (!mResult)
  11029. {
  11030. mModule->Warn(0, StrFormat("Conversion from '%s' to '%s' will always be null",
  11031. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(origTargetType).c_str()), dynCastExpr->mAsToken);
  11032. mResult = BfTypedValue(mModule->GetDefaultValue(origTargetType), origTargetType);
  11033. }
  11034. _CheckResult();
  11035. return;
  11036. }
  11037. if (targetValue.mType->IsVar())
  11038. {
  11039. mResult = mModule->GetDefaultTypedValue(targetType, false, BfDefaultValueKind_Undef);
  11040. return;
  11041. }
  11042. if (targetValue.mType->IsValueTypeOrValueTypePtr())
  11043. {
  11044. mModule->Warn(0, StrFormat("Type '%s' is not applicable for dynamic casting",
  11045. mModule->TypeToString(targetValue.mType).c_str()), dynCastExpr->mAsToken);
  11046. auto typeInstance = targetValue.mType->ToTypeInstance();
  11047. if (targetValue.mType->IsWrappableType())
  11048. typeInstance = mModule->GetWrappedStructType(targetValue.mType);
  11049. bool matches = (targetValue.mType == targetType) || (mModule->mContext->mBfObjectType == targetType);
  11050. if (targetType->IsNullable())
  11051. {
  11052. auto elementType = targetType->GetUnderlyingType();
  11053. if (elementType == targetValue.mType)
  11054. {
  11055. // We match nullable element
  11056. auto allocaInst = mModule->CreateAlloca(targetType);
  11057. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  11058. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  11059. hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 0); // value
  11060. mModule->mBfIRBuilder->CreateStore(targetValue.mValue, hasValueAddr);
  11061. mResult = BfTypedValue(allocaInst, targetType, true);
  11062. _CheckResult();
  11063. return;
  11064. }
  11065. }
  11066. if (!matches)
  11067. matches = mModule->TypeIsSubTypeOf(typeInstance, targetType->ToTypeInstance());
  11068. if (matches)
  11069. mResult = mModule->Cast(dynCastExpr, targetValue, targetType, BfCastFlags_Explicit);
  11070. else if (targetType->IsNullable())
  11071. {
  11072. auto allocaInst = mModule->CreateAlloca(targetType);
  11073. auto allocaBits = mModule->mBfIRBuilder->CreateBitCast(allocaInst, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  11074. mModule->mBfIRBuilder->CreateMemSet(allocaBits, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  11075. mModule->GetConstValue(targetType->mSize), targetType->mAlign);
  11076. mResult = BfTypedValue(allocaInst, targetType, true);
  11077. }
  11078. else
  11079. mResult = BfTypedValue(mModule->GetDefaultValue(targetType), targetType);
  11080. _CheckResult();
  11081. return;
  11082. }
  11083. if (targetType->IsNullable())
  11084. {
  11085. if (autoComplete != NULL)
  11086. {
  11087. mResult = mModule->GetDefaultTypedValue(targetType);
  11088. return;
  11089. }
  11090. auto elementType = targetType->GetUnderlyingType();
  11091. auto allocaInst = mModule->CreateAlloca(targetType);
  11092. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, elementType->IsValuelessType() ? 1 : 2); // has_value
  11093. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(0, boolType), hasValueAddr);
  11094. auto objectType = mModule->mContext->mBfObjectType;
  11095. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  11096. auto matchBB = mModule->mBfIRBuilder->CreateBlock("as.match");
  11097. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  11098. mModule->EmitDynamicCastCheck(targetValue, elementType, matchBB, endBB);
  11099. BfBoxedType* boxedType = mModule->CreateBoxedType(elementType);
  11100. mModule->AddBasicBlock(matchBB);
  11101. if (elementType->IsValuelessType())
  11102. {
  11103. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // has_value
  11104. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  11105. }
  11106. else
  11107. {
  11108. auto hasValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 2); // has_value
  11109. mModule->mBfIRBuilder->CreateStore(mModule->GetConstValue(1, boolType), hasValueAddr);
  11110. auto nullableValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(allocaInst, 0, 1); // value
  11111. auto srcBoxedType = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(boxedType, BfIRPopulateType_Full));
  11112. auto boxedValueAddr = mModule->mBfIRBuilder->CreateInBoundsGEP(srcBoxedType, 0, 1); // mValue
  11113. auto boxedValue = mModule->mBfIRBuilder->CreateLoad(boxedValueAddr);
  11114. mModule->mBfIRBuilder->CreateStore(boxedValue, nullableValueAddr);
  11115. }
  11116. mModule->mBfIRBuilder->CreateBr(endBB);
  11117. mModule->AddBasicBlock(endBB);
  11118. mResult = BfTypedValue(allocaInst, targetType, true);
  11119. _CheckResult();
  11120. return;
  11121. }
  11122. targetValue = mModule->LoadValue(targetValue);
  11123. if (targetType->IsValueType())
  11124. {
  11125. mModule->Fail("Invalid dynamic cast type", dynCastExpr->mTypeRef);
  11126. return;
  11127. }
  11128. BfTypeInstance* srcTypeInstance = targetValue.mType->ToTypeInstance();
  11129. BfTypeInstance* targetTypeInstance = targetType->ToTypeInstance();
  11130. if (mModule->TypeIsSubTypeOf(srcTypeInstance, targetTypeInstance))
  11131. {
  11132. // We don't give this warning when we have wasGenericParmType set because that indicates we had a generic type constraint,
  11133. // and a type constraint infers that the ACTUAL type used will be equal to or derived from that type and therefore
  11134. // it may be a "necessary cast" indeed
  11135. if ((!wasGenericParamType) && (mModule->mCurMethodState->mMixinState == NULL))
  11136. {
  11137. if (srcTypeInstance == targetType)
  11138. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, the value is already type '%s'",
  11139. mModule->TypeToString(srcTypeInstance).c_str()), dynCastExpr->mAsToken);
  11140. else
  11141. mModule->Warn(BfWarning_BF4203_UnnecessaryDynamicCast, StrFormat("Unnecessary cast, '%s' is a subtype of '%s'",
  11142. mModule->TypeToString(srcTypeInstance).c_str(), mModule->TypeToString(targetType).c_str()), dynCastExpr->mAsToken);
  11143. }
  11144. auto castedValue = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetTypeInstance));
  11145. mResult = BfTypedValue(castedValue, targetTypeInstance);
  11146. _CheckResult();
  11147. return;
  11148. }
  11149. else if ((!targetType->IsInterface()) && (!mModule->TypeIsSubTypeOf(targetTypeInstance, srcTypeInstance)))
  11150. {
  11151. if (!mModule->IsInSpecializedSection())
  11152. {
  11153. mModule->Fail(StrFormat("Cannot convert type '%s' to '%s' via any conversion",
  11154. mModule->TypeToString(targetValue.mType).c_str(), mModule->TypeToString(targetTypeInstance).c_str()), dynCastExpr->mAsToken);
  11155. }
  11156. mResult = mModule->GetDefaultTypedValue(targetType);
  11157. return;
  11158. }
  11159. if (autoComplete != NULL)
  11160. {
  11161. mResult = mModule->GetDefaultTypedValue(targetType, false, BfDefaultValueKind_Addr);
  11162. _CheckResult();
  11163. return;
  11164. }
  11165. auto irb = mModule->mBfIRBuilder;
  11166. auto objectType = mModule->mContext->mBfObjectType;
  11167. mModule->PopulateType(objectType, BfPopulateType_Full);
  11168. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  11169. auto endBB = mModule->mBfIRBuilder->CreateBlock("as.end");
  11170. auto matchBlock = irb->CreateBlock("as.match");
  11171. BfIRValue targetVal = mModule->CreateAlloca(targetType);
  11172. irb->CreateAlignedStore(irb->CreateConstNull(irb->MapType(targetType)), targetVal, targetType->mAlign);
  11173. mModule->EmitDynamicCastCheck(targetValue, targetType, matchBlock, endBB);
  11174. mModule->AddBasicBlock(matchBlock);
  11175. BfIRValue castedCallResult = mModule->mBfIRBuilder->CreateBitCast(targetValue.mValue, mModule->mBfIRBuilder->MapType(targetType));
  11176. irb->CreateAlignedStore(castedCallResult, targetVal, targetValue.mType->mAlign);
  11177. irb->CreateBr(endBB);
  11178. mModule->AddBasicBlock(endBB);
  11179. mResult = BfTypedValue(irb->CreateAlignedLoad(targetVal, targetType->mAlign), targetType);
  11180. _CheckResult();
  11181. }
  11182. void BfExprEvaluator::Visit(BfCastExpression* castExpr)
  11183. {
  11184. auto autoComplete = GetAutoComplete();
  11185. if ((autoComplete != NULL) && (castExpr->mTypeRef != NULL))
  11186. {
  11187. // 'mayBeIdentifier' because this may be a misidentified cast - it could be a parenthesized expression
  11188. autoComplete->CheckTypeRef(castExpr->mTypeRef, true, true);
  11189. }
  11190. BfType* resolvedType = NULL;
  11191. if ((BfNodeDynCastExact<BfDotTypeReference>(castExpr->mTypeRef) != NULL) && (mExpectingType != NULL))
  11192. {
  11193. //mModule->SetElementType(castExpr->mTypeRef, BfSourceElementType_TypeRef);
  11194. resolvedType = mExpectingType;
  11195. }
  11196. else
  11197. resolvedType = ResolveTypeRef(castExpr->mTypeRef);
  11198. if (resolvedType != NULL)
  11199. mModule->AddDependency(resolvedType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_LocalUsage);
  11200. // If resolvedType is NULL then that's okay- we just leave the following expression uncasted
  11201. if (castExpr->mExpression == NULL)
  11202. {
  11203. mModule->AssertErrorState();
  11204. return;
  11205. }
  11206. auto exprFlags = (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_NoAutoComplete) | BfEvalExprFlags_ExplicitCast);
  11207. mResult = mModule->CreateValueFromExpression(castExpr->mExpression, resolvedType, exprFlags);
  11208. }
  11209. bool BfExprEvaluator::IsExactMethodMatch(BfMethodInstance* methodA, BfMethodInstance* methodB, bool ignoreImplicitParams)
  11210. {
  11211. if (methodA->mReturnType != methodB->mReturnType)
  11212. return false;
  11213. int implicitParamCountA = methodA->GetImplicitParamCount();
  11214. if (methodA->HasExplicitThis())
  11215. implicitParamCountA++;
  11216. int implicitParamCountB = methodB->GetImplicitParamCount();
  11217. if (methodB->HasExplicitThis())
  11218. implicitParamCountB++;
  11219. if (methodA->GetParamCount() - implicitParamCountA != methodB->GetParamCount() - implicitParamCountB)
  11220. return false;
  11221. for (int i = 0; i < (int)methodA->GetParamCount() - implicitParamCountA; i++)
  11222. {
  11223. auto paramA = methodA->GetParamType(i + implicitParamCountA);
  11224. auto paramB = methodB->GetParamType(i + implicitParamCountB);
  11225. if (paramA != paramB)
  11226. return false;
  11227. }
  11228. return true;
  11229. }
  11230. void BfExprEvaluator::ConstResolve(BfExpression* expr)
  11231. {
  11232. BfConstResolver constResolver(mModule);
  11233. constResolver.Resolve(expr);
  11234. mResult = constResolver.mResult;
  11235. }
  11236. BfTypeInstance* BfExprEvaluator::VerifyBaseDelegateType(BfTypeInstance* baseDelegateType)
  11237. {
  11238. mModule->PopulateType(baseDelegateType, BfPopulateType_DataAndMethods);
  11239. if (baseDelegateType->mFieldInstances.size() != 2)
  11240. {
  11241. mModule->AssertErrorState();
  11242. return NULL;
  11243. }
  11244. return baseDelegateType;
  11245. }
  11246. bool BfExprEvaluator::CanBindDelegate(BfDelegateBindExpression* delegateBindExpr, BfMethodInstance** boundMethod, BfType* origMethodExpectingType, BfTypeVector* methodGenericArgumentsSubstitute)
  11247. {
  11248. if ((mExpectingType == NULL) && (origMethodExpectingType == NULL))
  11249. {
  11250. return false;
  11251. }
  11252. bool isGenericMatch = mExpectingType == NULL;
  11253. auto expectingType = mExpectingType;
  11254. if (expectingType == NULL)
  11255. expectingType = origMethodExpectingType;
  11256. auto typeInstance = expectingType->ToTypeInstance();
  11257. if ((typeInstance == NULL) ||
  11258. ((!typeInstance->mTypeDef->mIsDelegate) && (!typeInstance->mTypeDef->mIsFunction)))
  11259. return false;
  11260. mModule->PopulateType(typeInstance, BfPopulateType_DataAndMethods);
  11261. auto methodInstance = mModule->GetRawMethodInstanceAtIdx(typeInstance, 0, "Invoke");
  11262. if (methodInstance == NULL)
  11263. {
  11264. BF_DBG_FATAL("Invoke not found");
  11265. return false;
  11266. }
  11267. if (delegateBindExpr->mTarget == NULL)
  11268. return false;
  11269. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  11270. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  11271. typedValueExprs.resize(methodInstance->GetParamCount());
  11272. SizedArray<BfExpression*, 4> args;
  11273. args.resize(methodInstance->GetParamCount());
  11274. auto _FixType = [&](BfType* type)
  11275. {
  11276. if (!isGenericMatch)
  11277. return type;
  11278. auto fixedType = mModule->ResolveGenericType(type, NULL, methodGenericArgumentsSubstitute, mModule->mCurTypeInstance);
  11279. if (fixedType != NULL)
  11280. return fixedType;
  11281. return (BfType*)mModule->GetPrimitiveType(BfTypeCode_Var);
  11282. };
  11283. auto _TypeMatches = [&](BfType* lhs, BfType* rhs)
  11284. {
  11285. if (lhs == rhs)
  11286. return true;
  11287. return lhs->IsVar();
  11288. };
  11289. for (int i = 0; i < (int) methodInstance->GetParamCount(); i++)
  11290. {
  11291. auto typedValueExpr = &typedValueExprs[i];
  11292. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  11293. typedValueExpr->mTypedValue.mType = _FixType(methodInstance->GetParamType(i));
  11294. typedValueExpr->mRefNode = NULL;
  11295. args[i] = typedValueExpr;
  11296. }
  11297. BfMethodGenericArguments methodGenericArgs;
  11298. if (delegateBindExpr->mGenericArgs != NULL)
  11299. methodGenericArgs.mArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  11300. BfFunctionBindResult bindResult;
  11301. bindResult.mSkipMutCheck = true; // Allow operating on copies
  11302. bindResult.mBindType = expectingType;
  11303. mFunctionBindResult = &bindResult;
  11304. SetAndRestoreValue<bool> ignoreError(mModule->mIgnoreErrors, true);
  11305. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArgs);
  11306. mFunctionBindResult = NULL;
  11307. if (bindResult.mMethodInstance == NULL)
  11308. return false;
  11309. if (boundMethod != NULL)
  11310. *boundMethod = bindResult.mMethodInstance;
  11311. auto matchedMethod = bindResult.mMethodInstance;
  11312. if (!_TypeMatches(_FixType(methodInstance->mReturnType), matchedMethod->mReturnType))
  11313. return false;
  11314. int implicitParamCountA = methodInstance->GetImplicitParamCount();
  11315. int implicitParamCountB = matchedMethod->GetImplicitParamCount();
  11316. if (methodInstance->GetParamCount() - implicitParamCountA != matchedMethod->GetParamCount() - implicitParamCountB)
  11317. return false;
  11318. for (int i = 0; i < (int)methodInstance->GetParamCount() - implicitParamCountA; i++)
  11319. {
  11320. auto paramA = _FixType(methodInstance->GetParamType(i + implicitParamCountA));
  11321. auto paramB = _FixType(matchedMethod->GetParamType(i + implicitParamCountB));
  11322. if (!_TypeMatches(paramA, paramB))
  11323. return false;
  11324. }
  11325. return true;
  11326. }
  11327. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfIdentifierNode* identifierNode, int shadowIdx)
  11328. {
  11329. String findName = identifierNode->ToString();
  11330. if (mModule->mCurMethodState != NULL)
  11331. {
  11332. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  11333. auto checkMethodState = mModule->mCurMethodState;
  11334. bool isMixinOuterVariablePass = false;
  11335. int shadowSkip = shadowIdx;
  11336. while (checkMethodState != NULL)
  11337. {
  11338. BP_ZONE("LookupIdentifier:DoImplicitArgCapture");
  11339. BfTypeInstance* closureTypeInst = NULL;
  11340. BfClosureInstanceInfo* closureInstanceInfo = NULL;
  11341. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mClosureType != NULL) && (!checkMethodState->mClosureState->mCapturing))
  11342. {
  11343. closureTypeInst = mModule->mCurMethodState->mClosureState->mClosureType;
  11344. }
  11345. BfLocalVarEntry* entry;
  11346. if (checkMethodState->mLocalVarSet.TryGetWith<StringImpl&>(findName, &entry))
  11347. {
  11348. auto varDecl = entry->mLocalVar;
  11349. while (varDecl != NULL)
  11350. {
  11351. if (varDecl->mNameNode == identifierNode)
  11352. {
  11353. if (shadowSkip > 0)
  11354. {
  11355. shadowSkip--;
  11356. }
  11357. else
  11358. {
  11359. BfTypedValue localResult = LoadLocal(varDecl);
  11360. if (!isMixinOuterVariablePass)
  11361. {
  11362. mResultLocalVar = varDecl;
  11363. mResultFieldInstance = NULL;
  11364. mResultLocalVarRefNode = identifierNode;
  11365. }
  11366. return localResult;
  11367. }
  11368. }
  11369. varDecl = varDecl->mShadowedLocal;
  11370. }
  11371. }
  11372. // Check for the captured locals. It's important we do it here so we get local-first precedence still
  11373. if (closureTypeInst != NULL)
  11374. {
  11375. closureTypeInst->mTypeDef->PopulateMemberSets();
  11376. BfMemberSetEntry* memberSetEntry = NULL;
  11377. if (closureTypeInst->mTypeDef->mFieldSet.TryGetWith(findName, &memberSetEntry))
  11378. {
  11379. auto fieldDef = (BfFieldDef*)memberSetEntry->mMemberDef;
  11380. while (fieldDef != NULL)
  11381. {
  11382. BfIdentifierNode* fieldNameNode = NULL;
  11383. if (fieldDef->mIdx < (int)checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries.size())
  11384. fieldNameNode = checkMethodState->mClosureState->mClosureInstanceInfo->mCaptureEntries[fieldDef->mIdx].mNameNode;
  11385. if (fieldNameNode == identifierNode)
  11386. {
  11387. auto& field = closureTypeInst->mFieldInstances[fieldDef->mIdx];
  11388. if (!field.mResolvedType->IsValuelessType())
  11389. {
  11390. if (mModule->mCurMethodState->mClosureState->mCapturing)
  11391. {
  11392. mModule->mCurMethodState->mClosureState->mReferencedOuterClosureMembers.Add(&field);
  11393. return mModule->GetDefaultTypedValue(field.mResolvedType);
  11394. }
  11395. auto localVar = mModule->mCurMethodState->mLocals[0];
  11396. auto thisValue = localVar->mValue;
  11397. mModule->mBfIRBuilder->PopulateType(localVar->mResolvedType);
  11398. BfTypedValue result = BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue, 0, field.mDataIdx), field.mResolvedType, true);
  11399. if (field.mResolvedType->IsRef())
  11400. {
  11401. auto refType = (BfRefType*)field.mResolvedType;
  11402. auto underlyingType = refType->GetUnderlyingType();
  11403. result = BfTypedValue(mModule->mBfIRBuilder->CreateAlignedLoad(result.mValue, underlyingType->mAlign), underlyingType, true);
  11404. }
  11405. else if (fieldDef->mIsReadOnly)
  11406. result = mModule->LoadValue(result);
  11407. mResultLocalVar = localVar;
  11408. mResultFieldInstance = &field;
  11409. mResultLocalVarField = -(field.mMergedDataIdx + 1);
  11410. return result;
  11411. }
  11412. }
  11413. fieldDef = fieldDef->mNextWithSameName;
  11414. }
  11415. }
  11416. }
  11417. if ((checkMethodState->mClosureState != NULL) && (checkMethodState->mClosureState->mCapturing) /*&& (checkMethodState->mClosureState->mIsLocalMethod)*/)
  11418. {
  11419. checkMethodState = checkMethodState->mPrevMethodState;
  11420. continue;
  11421. }
  11422. // Allow local mixin to see outside variables during its processing -- since we don't actually "capture" those into params
  11423. bool isLocalMixinProcessing = false;
  11424. if ((checkMethodState->mClosureState != NULL) && (!checkMethodState->mClosureState->mCapturing) && (closureTypeInst == NULL) &&
  11425. (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Mixin))
  11426. isLocalMixinProcessing = true;
  11427. if (!isLocalMixinProcessing)
  11428. break;
  11429. isMixinOuterVariablePass = true;
  11430. checkMethodState = checkMethodState->mPrevMethodState;
  11431. }
  11432. }
  11433. return BfTypedValue();
  11434. }
  11435. BfTypedValue BfExprEvaluator::DoImplicitArgCapture(BfAstNode* refNode, BfMethodInstance* methodInstance, int paramIdx, bool& failed, BfImplicitParamKind paramKind, const BfTypedValue& methodRefTarget)
  11436. {
  11437. if ((methodRefTarget) && (methodRefTarget.mValue.mId != BfIRValue::ID_IMPLICIT))
  11438. {
  11439. if (methodRefTarget.mType->IsMethodRef())
  11440. {
  11441. BfMethodRefType* methodRefType = (BfMethodRefType*)methodRefTarget.mType;
  11442. BfMethodInstance* methodRefMethodInst = methodRefType->mMethodRef;
  11443. BF_ASSERT(methodRefMethodInst == methodInstance);
  11444. auto paramType = methodInstance->GetParamType(paramIdx);
  11445. int dataIdx = methodRefType->GetDataIdxFromParamIdx(paramIdx);
  11446. if (dataIdx == -1)
  11447. {
  11448. BF_ASSERT(paramType->IsValuelessType());
  11449. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), paramType);
  11450. }
  11451. if (methodRefTarget.IsSplat())
  11452. {
  11453. if (methodRefType->WantsDataPassedAsSplat(dataIdx))
  11454. {
  11455. BF_ASSERT(paramIdx == -1);
  11456. return BfTypedValue(methodRefTarget.mValue, paramType, BfTypedValueKind_SplatHead);
  11457. }
  11458. else
  11459. {
  11460. int splatIdx = dataIdx;
  11461. if (dataIdx > 0)
  11462. {
  11463. if (methodRefType->WantsDataPassedAsSplat(0))
  11464. splatIdx += methodRefType->GetCaptureType(0)->GetSplatCount() - 1;
  11465. }
  11466. bool isAddr = false;
  11467. BfIRValue value = mModule->ExtractSplatValue(methodRefTarget, splatIdx, paramType, &isAddr);
  11468. // We moved the composite load from ExtractSplatValue to here. Hopefully this is correct.
  11469. // 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)
  11470. // if ((paramType->IsComposite()) && (mModule->IsTargetingBeefBackend()))
  11471. // value = mModule->mBfIRBuilder->CreateLoad(value);
  11472. auto lookupVal = BfTypedValue(value, paramType, isAddr);
  11473. if ((isAddr) && (!lookupVal.mType->IsComposite()))
  11474. lookupVal = mModule->LoadValue(lookupVal);
  11475. return lookupVal;
  11476. }
  11477. }
  11478. if ((paramType->IsComposite()) && (methodRefTarget.IsAddr()))
  11479. return BfTypedValue(mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefTarget.mValue, 0, dataIdx), paramType, true);
  11480. return BfTypedValue(mModule->ExtractValue(methodRefTarget, dataIdx), paramType);
  11481. }
  11482. }
  11483. // 'Default' implicit arg lookup, by identifier. May match field (for lambda), or local variable
  11484. if (paramKind == BfImplicitParamKind_General)
  11485. {
  11486. if (paramIdx == -1)
  11487. {
  11488. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(refNode))
  11489. {
  11490. BfAstNode* thisNode = NULL;
  11491. BfTypedValue thisValue;
  11492. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(delegateBindExpr->mTarget))
  11493. thisNode = memberReferenceExpr->mTarget;
  11494. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(delegateBindExpr->mTarget))
  11495. thisNode = qualifiedNameNode->mLeft;
  11496. else if (auto identifierNode = BfNodeDynCast<BfIdentifierNode>(delegateBindExpr->mTarget))
  11497. {
  11498. // Implicit
  11499. thisValue = mModule->GetThis();
  11500. }
  11501. if (auto thisExpr = BfNodeDynCast<BfExpression>(thisNode))
  11502. {
  11503. thisValue = mModule->CreateValueFromExpression(thisExpr);
  11504. if (!thisValue)
  11505. return BfTypedValue();
  11506. }
  11507. if (thisValue)
  11508. {
  11509. //TODO: handle 'mut', throw error if trying to capture from a non-mut, etc...
  11510. return thisValue;
  11511. }
  11512. }
  11513. }
  11514. String captureName = methodInstance->GetParamName(paramIdx);
  11515. BfIdentifierNode* identifierNode = methodInstance->GetParamNameNode(paramIdx);
  11516. BfTypedValue lookupVal;
  11517. if (identifierNode != NULL)
  11518. {
  11519. lookupVal = DoImplicitArgCapture(refNode, identifierNode, 0);
  11520. }
  11521. else
  11522. {
  11523. lookupVal = LookupIdentifier(NULL, captureName);
  11524. }
  11525. if (lookupVal)
  11526. {
  11527. auto paramType = methodInstance->GetParamType(paramIdx);
  11528. if (paramType->IsRef())
  11529. {
  11530. auto refType = (BfRefType*)paramType;
  11531. if (mResultLocalVar != NULL)
  11532. {
  11533. // When we are capturing, we need to note that we require capturing by reference here
  11534. auto localVar = mResultLocalVar;
  11535. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  11536. }
  11537. bool isValid = false;
  11538. if ((refType->mRefKind == BfRefType::RefKind_Mut) && (lookupVal.mKind == BfTypedValueKind_MutableValue))
  11539. isValid = true;
  11540. if ((lookupVal.mType->IsRef()) || (lookupVal.IsAddr()))
  11541. isValid = true;
  11542. if (!isValid)
  11543. {
  11544. // Is there another way this can fail than to be in a lambda?
  11545. auto error = mModule->Fail(StrFormat("Method '%s' requires that '%s' be captured by reference. Consider adding by-reference capture specifier [&] to lambda.",
  11546. mModule->MethodToString(methodInstance).c_str(), captureName.c_str()), refNode, true);
  11547. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  11548. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  11549. failed = true;
  11550. }
  11551. }
  11552. else
  11553. {
  11554. if (lookupVal.mType->IsRef())
  11555. lookupVal = mModule->RemoveRef(lookupVal);
  11556. if (!lookupVal.mType->IsComposite())
  11557. lookupVal = mModule->LoadValue(lookupVal);
  11558. }
  11559. return lookupVal;
  11560. }
  11561. else
  11562. {
  11563. mModule->Fail(StrFormat("Failed to lookup implicit capture '%s'", captureName.c_str()), refNode, true);
  11564. failed = true;
  11565. return BfTypedValue();
  11566. }
  11567. }
  11568. return BfTypedValue();
  11569. }
  11570. void BfExprEvaluator::Visit(BfDelegateBindExpression* delegateBindExpr)
  11571. {
  11572. BfAutoParentNodeEntry autoParentNodeEntry(mModule, delegateBindExpr);
  11573. if (mExpectingType == NULL)
  11574. {
  11575. mModule->Fail("Cannot infer delegate type", delegateBindExpr);
  11576. return;
  11577. }
  11578. BfTokenNode* newToken = NULL;
  11579. BfAllocTarget allocTarget;
  11580. ResolveAllocTarget(allocTarget, delegateBindExpr->mNewToken, newToken);
  11581. SizedArray<BfTypedValueExpression, 4> typedValueExprs;
  11582. SizedArray<BfExpression*, 4> args;
  11583. BfTypeInstance* delegateTypeInstance = NULL;
  11584. BfMethodInstance* methodInstance = NULL;
  11585. const char* bindTypeName = NULL;
  11586. bool isMethodRefMatch = false;
  11587. if (mExpectingType->IsMethodRef())
  11588. {
  11589. auto methodRefType = (BfMethodRefType*)mExpectingType;
  11590. BF_ASSERT(delegateBindExpr->mNewToken == NULL);
  11591. methodInstance = methodRefType->mMethodRef;
  11592. isMethodRefMatch = true;
  11593. }
  11594. else
  11595. {
  11596. if (mExpectingType->IsGenericParam())
  11597. {
  11598. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  11599. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsDelegate()))
  11600. {
  11601. delegateTypeInstance = genericParamInstance->mTypeConstraint->ToTypeInstance();
  11602. }
  11603. }
  11604. else
  11605. delegateTypeInstance = mExpectingType->ToTypeInstance();
  11606. if ((delegateTypeInstance == NULL) ||
  11607. ((!delegateTypeInstance->IsDelegate()) && (!delegateTypeInstance->IsFunction())))
  11608. {
  11609. mModule->Fail(StrFormat("Type '%s' cannot be used for method binding. Only delegate or function types are allowed.", mModule->TypeToString(mExpectingType).c_str()), delegateBindExpr);
  11610. return;
  11611. }
  11612. bindTypeName = (delegateTypeInstance->IsDelegate()) ? "delegate" : "function";
  11613. mModule->PopulateType(delegateTypeInstance, BfPopulateType_DataAndMethods);
  11614. methodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  11615. if (methodInstance == NULL)
  11616. {
  11617. BF_DBG_FATAL("Invoke not found");
  11618. return;
  11619. }
  11620. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(delegateBindExpr->mNewToken))
  11621. {
  11622. if (delegateTypeInstance->IsFunction())
  11623. mModule->Fail("Function bindings are direct assignments, allocation specifier is not applicable", delegateBindExpr->mNewToken);
  11624. else if (tokenNode->GetToken() == BfToken_Append)
  11625. {
  11626. mModule->Fail("Append allocation on delegate bind not supported", delegateBindExpr->mNewToken);
  11627. }
  11628. }
  11629. }
  11630. int paramOffset = methodInstance->HasExplicitThis() ? 1 : 0;
  11631. typedValueExprs.resize(methodInstance->GetParamCount() - paramOffset);
  11632. args.resize(methodInstance->GetParamCount() - paramOffset);
  11633. for (int i = 0; i < (int)methodInstance->GetParamCount() - paramOffset; i++)
  11634. {
  11635. auto typedValueExpr = &typedValueExprs[i];
  11636. typedValueExpr->mTypedValue.mValue = BfIRValue(BfIRValueFlags_Value, -1);
  11637. typedValueExpr->mTypedValue.mType = methodInstance->GetParamType(i + paramOffset);
  11638. typedValueExpr->mRefNode = NULL;
  11639. args[i] = typedValueExpr;
  11640. }
  11641. BfMethodGenericArguments methodGenericArgs;
  11642. if (delegateBindExpr->mGenericArgs != NULL)
  11643. methodGenericArgs.mArguments = &delegateBindExpr->mGenericArgs->mGenericArgs;
  11644. if (delegateBindExpr->mTarget == NULL)
  11645. {
  11646. mModule->AssertErrorState();
  11647. return;
  11648. }
  11649. auto autoComplete = GetAutoComplete();
  11650. if (autoComplete != NULL)
  11651. {
  11652. SetAndRestoreValue<bool> prevForceAllowNonStatic(autoComplete->mForceAllowNonStatic, methodInstance->mMethodDef->mHasExplicitThis);
  11653. GetAutoComplete()->CheckNode(delegateBindExpr->mTarget, true);
  11654. }
  11655. if ((!delegateBindExpr->mTarget->IsA<BfIdentifierNode>()) &&
  11656. (!delegateBindExpr->mTarget->IsA<BfMemberReferenceExpression>()))
  11657. {
  11658. mModule->Fail(StrFormat("Invalid %s binding target, %s can only bind to method references. Consider wrapping expression in a lambda.", bindTypeName, bindTypeName), delegateBindExpr->mTarget);
  11659. mModule->CreateValueFromExpression(delegateBindExpr->mTarget);
  11660. return;
  11661. }
  11662. BfFunctionBindResult bindResult;
  11663. bindResult.mSkipMutCheck = true; // Allow operating on copies
  11664. bindResult.mBindType = delegateTypeInstance;
  11665. //
  11666. {
  11667. SetAndRestoreValue<BfType*> prevExpectingType(mExpectingType, methodInstance->mReturnType);
  11668. mFunctionBindResult = &bindResult;
  11669. DoInvocation(delegateBindExpr->mTarget, delegateBindExpr, args, methodGenericArgs);
  11670. mFunctionBindResult = NULL;
  11671. }
  11672. SetMethodElementType(delegateBindExpr->mTarget);
  11673. if (bindResult.mMethodInstance == NULL)
  11674. {
  11675. if ((mResult) && (IsVar(mResult.mType)))
  11676. return;
  11677. mResult = BfTypedValue();
  11678. return;
  11679. }
  11680. auto bindMethodInstance = bindResult.mMethodInstance;
  11681. if (isMethodRefMatch)
  11682. {
  11683. // WTF- this was always false, what was it supposed to catch?
  11684. // if (bindMethodInstance != bindResult.mMethodInstance)
  11685. // {
  11686. // mResult = BfTypedValue();
  11687. // return;
  11688. // }
  11689. }
  11690. else
  11691. {
  11692. bool isExactMethodMatch = IsExactMethodMatch(methodInstance, bindMethodInstance, true);
  11693. if ((mExpectingType != NULL) && (mExpectingType->IsFunction()) && (methodInstance->mMethodDef->mIsMutating != bindMethodInstance->mMethodDef->mIsMutating))
  11694. isExactMethodMatch = false;
  11695. if (!isExactMethodMatch)
  11696. {
  11697. if (bindResult.mCheckedMultipleMethods)
  11698. {
  11699. mModule->Fail(StrFormat("No overload for '%s' matches %s '%s'", bindMethodInstance->mMethodDef->mName.c_str(), bindTypeName,
  11700. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  11701. }
  11702. else
  11703. {
  11704. mModule->Fail(StrFormat("Method '%s' does not match %s '%s'", mModule->MethodToString(bindMethodInstance, (BfMethodNameFlags)(BfMethodNameFlag_ResolveGenericParamNames | BfMethodNameFlag_IncludeReturnType | BfMethodNameFlag_IncludeMut)).c_str(), bindTypeName,
  11705. mModule->TypeToString(delegateTypeInstance).c_str()), delegateBindExpr->mTarget);
  11706. }
  11707. mResult = BfTypedValue();
  11708. return;
  11709. }
  11710. }
  11711. bool isDirectFunction = false;
  11712. if ((bindResult.mMethodInstance->GetOwner()->IsFunction()) && (bindResult.mFunc))
  11713. isDirectFunction = true;
  11714. if (bindMethodInstance->mIsIntrinsic)
  11715. {
  11716. 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);
  11717. mResult = BfTypedValue();
  11718. return;
  11719. }
  11720. bool hasIncompatibleCallingConventions = !mModule->mSystem->IsCompatibleCallingConvention(methodInstance->mCallingConvention, bindMethodInstance->mCallingConvention);
  11721. auto _GetInvokeMethodName = [&]()
  11722. {
  11723. StringT<512> methodName = "Invoke$";
  11724. methodName += mModule->mCurMethodInstance->mMethodDef->mName;
  11725. int prevSepPos = (int)methodName.LastIndexOf('$');
  11726. if (prevSepPos > 6)
  11727. {
  11728. methodName.RemoveToEnd(prevSepPos);
  11729. }
  11730. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  11731. HashContext hashCtx;
  11732. if (mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mPartialIdx != -1)
  11733. hashCtx.Mixin(mModule->mCurMethodInstance->mMethodDef->mDeclaringType->mPartialIdx);
  11734. if (delegateBindExpr->mFatArrowToken != NULL)
  11735. {
  11736. hashCtx.Mixin(delegateBindExpr->mFatArrowToken->GetStartCharId());
  11737. }
  11738. if (rootMethodState->mMethodInstance->mMethodInfoEx != NULL)
  11739. {
  11740. for (auto methodGenericArg : rootMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  11741. {
  11742. StringT<128> genericTypeName;
  11743. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  11744. hashCtx.MixinStr(genericTypeName);
  11745. }
  11746. }
  11747. Val128 hashVal = hashCtx.Finish128();
  11748. methodName += '$';
  11749. methodName += BfTypeUtils::HashEncode64(hashVal.mLow);
  11750. StringT<512> mangledName;
  11751. BfMangler::MangleMethodName(mangledName, mModule->mCompiler->GetMangleKind(), mModule->mCurTypeInstance, methodName);
  11752. return mangledName;
  11753. };
  11754. if ((delegateBindExpr->mNewToken == NULL) || (delegateTypeInstance->IsFunction()))
  11755. {
  11756. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder != NULL))
  11757. {
  11758. BF_ASSERT(bindResult.mMethodInstance->mHotMethod != NULL);
  11759. mModule->mCurMethodState->mHotDataReferenceBuilder->mFunctionPtrs.Add(bindResult.mMethodInstance->mHotMethod);
  11760. }
  11761. if (isDirectFunction)
  11762. {
  11763. //if ((delegateTypeInstance != NULL) && (delegateTypeInstance->IsFunction()))
  11764. if (mExpectingType->IsFunction())
  11765. {
  11766. auto intPtrVal = mModule->mBfIRBuilder->CreatePtrToInt(bindResult.mFunc, BfTypeCode_IntPtr);
  11767. mResult = BfTypedValue(intPtrVal, mExpectingType);
  11768. return;
  11769. }
  11770. }
  11771. if (mExpectingType->IsFunction())
  11772. {
  11773. BfIRValue result;
  11774. if ((hasIncompatibleCallingConventions) && (mModule->HasExecutedOutput()))
  11775. {
  11776. //
  11777. {
  11778. SetAndRestoreValue<bool> prevIgnore(mModule->mBfIRBuilder->mIgnoreWrites, true);
  11779. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mOrigTarget, bindResult.mMethodInstance, mExpectingType);
  11780. }
  11781. if (result)
  11782. {
  11783. String methodName = _GetInvokeMethodName();
  11784. SizedArray<BfIRType, 8> irParamTypes;
  11785. BfIRType irReturnType;
  11786. methodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  11787. int thisFuncParamIdx = methodInstance->GetThisIdx();
  11788. int thisBindParamIdx = methodInstance->GetThisIdx();
  11789. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  11790. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  11791. mModule->mBfIRBuilder->SaveDebugLocation();
  11792. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  11793. auto funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  11794. auto srcCallingConv = mModule->GetIRCallingConvention(methodInstance);
  11795. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  11796. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  11797. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  11798. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  11799. SizedArray<BfIRValue, 8> irArgs;
  11800. for (int paramIdx = 0; paramIdx < irParamTypes.size(); paramIdx++)
  11801. {
  11802. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(paramIdx));
  11803. }
  11804. auto bindFuncVal = bindResult.mFunc;
  11805. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!mModule->mIsComptimeModule))
  11806. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  11807. auto callResult = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  11808. auto destCallingConv = mModule->GetIRCallingConvention(bindMethodInstance);
  11809. if (destCallingConv != BfIRCallingConv_CDecl)
  11810. mModule->mBfIRBuilder->SetCallCallingConv(callResult, destCallingConv);
  11811. if (methodInstance->mReturnType->IsValuelessType())
  11812. mModule->mBfIRBuilder->CreateRetVoid();
  11813. else
  11814. mModule->mBfIRBuilder->CreateRet(callResult);
  11815. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  11816. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  11817. mModule->mBfIRBuilder->RestoreDebugLocation();
  11818. result = mModule->mBfIRBuilder->CreatePtrToInt(funcValue, BfTypeCode_IntPtr);
  11819. }
  11820. }
  11821. else
  11822. {
  11823. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsGenericParam()) && (bindResult.mMethodInstance->GetOwner()->IsInterface()))
  11824. {
  11825. bool matching = true;
  11826. if (methodInstance->HasExplicitThis())
  11827. {
  11828. auto thisType = methodInstance->GetParamType(0);
  11829. if (thisType->IsPointer())
  11830. thisType = thisType->GetUnderlyingType();
  11831. if (thisType->IsRef())
  11832. thisType = thisType->GetUnderlyingType();
  11833. matching = thisType == bindResult.mOrigTarget.mType;
  11834. }
  11835. if (matching)
  11836. {
  11837. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), mExpectingType);
  11838. return;
  11839. }
  11840. }
  11841. result = mModule->CastToFunction(delegateBindExpr->mTarget, bindResult.mOrigTarget, bindResult.mMethodInstance, mExpectingType, BfCastFlags_None, bindResult.mFunc);
  11842. }
  11843. if (result)
  11844. mResult = BfTypedValue(result, mExpectingType);
  11845. return;
  11846. }
  11847. if (bindResult.mMethodInstance->mDisallowCalling)
  11848. {
  11849. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  11850. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  11851. return;
  11852. }
  11853. auto methodRefType = mModule->CreateMethodRefType(bindResult.mMethodInstance);
  11854. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  11855. mModule->AddCallDependency(bindResult.mMethodInstance);
  11856. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  11857. {
  11858. mResult = bindResult.mOrigTarget;
  11859. }
  11860. else
  11861. {
  11862. if ((bindResult.mMethodInstance->mMethodDef->mIsLocalMethod) || (!bindResult.mTarget))
  11863. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  11864. else
  11865. {
  11866. auto methodRefPtr = mModule->CreateAlloca(methodRefType, "bindResult");
  11867. auto elemPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(methodRefPtr, 0, 0);
  11868. BfTypedValue target;
  11869. if (bindResult.mTarget.IsSplat())
  11870. target = mModule->AggregateSplat(bindResult.mTarget, &bindResult.mIRArgs[0]);
  11871. else
  11872. target = bindResult.mTarget;
  11873. mModule->mBfIRBuilder->CreateStore(target.mValue, elemPtr);
  11874. mResult = BfTypedValue(methodRefPtr, methodRefType, true);
  11875. }
  11876. }
  11877. return;
  11878. }
  11879. int implicitParamCount = bindMethodInstance->GetImplicitParamCount();
  11880. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  11881. BfClosureType* closureTypeInst = NULL;
  11882. auto origTarget = bindResult.mOrigTarget;
  11883. auto target = bindResult.mTarget;
  11884. BfTypedValue methodRefTarget;
  11885. if ((bindResult.mOrigTarget) && (bindResult.mOrigTarget.mType->IsMethodRef()))
  11886. methodRefTarget = bindResult.mOrigTarget;
  11887. bool isStructTarget = (target) && (target.mType->IsStruct());
  11888. bool bindCapturesThis = bindMethodInstance->HasThis() && !isStructTarget;
  11889. bool needsSplat = (isStructTarget) && (!bindMethodInstance->mMethodDef->mIsMutating) && (bindMethodInstance->AllowsSplatting(-1));
  11890. bool captureThisByValue = isStructTarget;
  11891. if (bindMethodInstance->mMethodDef->mIsLocalMethod)
  11892. {
  11893. // Local method captures always capture 'this' by reference
  11894. captureThisByValue = false;
  11895. }
  11896. if ((origTarget.mType != NULL) &&
  11897. ((origTarget.mType->IsRef()) || (origTarget.mType->IsPointer())))
  11898. {
  11899. captureThisByValue = false;
  11900. }
  11901. if (methodRefTarget)
  11902. BF_ASSERT(methodRefTarget.mType->IsMethodRef());
  11903. if (target.IsSplat())
  11904. target = mModule->AggregateSplat(target, &bindResult.mIRArgs[0]);
  11905. bool hasCaptures = false;
  11906. // Do we need a special delegate type for this?
  11907. if (((captureThisByValue) || (needsSplat) || (implicitParamCount > 0) /*|| (hasIncompatibleCallingConventions)*/) &&
  11908. (mModule->HasExecutedOutput()))
  11909. {
  11910. hasCaptures = true;
  11911. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  11912. if (captureThisByValue)
  11913. target = mModule->LoadValue(target);
  11914. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  11915. HashContext hashCtx;
  11916. hashCtx.MixinStr(delegateTypeName);
  11917. // We mix in the project for reasons described in the lambda binding handler
  11918. hashCtx.MixinStr(curProject->mName);
  11919. String structTargetTypeName;
  11920. String structTargetName;
  11921. // Implicit param separator
  11922. for (int implicitParamIdx = bindMethodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  11923. {
  11924. auto paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  11925. if ((implicitParamIdx == -1) && (captureThisByValue))
  11926. {
  11927. if (paramType->IsPointer())
  11928. paramType = paramType->GetUnderlyingType();
  11929. }
  11930. structTargetTypeName = mModule->TypeToString(paramType);
  11931. structTargetName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  11932. hashCtx.MixinStr(structTargetTypeName);
  11933. hashCtx.MixinStr(structTargetName);
  11934. }
  11935. Val128 hash128 = hashCtx.Finish128();
  11936. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  11937. checkClosureType->mContext = mModule->mContext;
  11938. checkClosureType->mBaseType = delegateTypeInstance;
  11939. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_TypeDef);
  11940. closureTypeInst = (BfClosureType*)resolvedClosureType;
  11941. if (checkClosureType == resolvedClosureType)
  11942. {
  11943. // This is a new closure type
  11944. closureTypeInst->Init(curProject);
  11945. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  11946. {
  11947. String fieldName = bindResult.mMethodInstance->GetParamName(implicitParamIdx);
  11948. BfType* paramType = bindResult.mMethodInstance->GetParamType(implicitParamIdx);
  11949. if ((implicitParamIdx == -1) && (captureThisByValue))
  11950. {
  11951. if (paramType->IsPointer())
  11952. paramType = paramType->GetUnderlyingType();
  11953. }
  11954. if (fieldName == "this")
  11955. fieldName = "__this";
  11956. closureTypeInst->AddField(paramType, fieldName);
  11957. }
  11958. closureTypeInst->Finish();
  11959. mModule->PopulateType(resolvedClosureType, BfPopulateType_Declaration);
  11960. }
  11961. else
  11962. {
  11963. // Already had this entry
  11964. delete checkClosureType;
  11965. }
  11966. useTypeInstance = closureTypeInst;
  11967. }
  11968. mModule->PopulateType(useTypeInstance);
  11969. if (delegateBindExpr->mTarget == NULL)
  11970. {
  11971. mModule->AssertErrorState();
  11972. return;
  11973. }
  11974. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  11975. // Do we need specialized calling code for this?
  11976. BfIRValue funcValue;
  11977. if (((needsSplat) || (implicitParamCount > 0) || (hasIncompatibleCallingConventions)) &&
  11978. (mModule->HasExecutedOutput()))
  11979. {
  11980. int fieldIdx = 0;
  11981. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  11982. {
  11983. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  11984. int gepIdx = fieldInst->mDataIdx;
  11985. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, gepIdx);
  11986. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  11987. if ((implicitParamIdx == -1) && (captureThisByValue))
  11988. {
  11989. if (fieldType->IsPointer())
  11990. fieldType = fieldType->GetUnderlyingType();
  11991. }
  11992. bool failed = false;
  11993. BfTypedValue lookupVal;
  11994. if (implicitParamIdx == -1)
  11995. lookupVal = target;
  11996. else
  11997. lookupVal = DoImplicitArgCapture(delegateBindExpr->mTarget, bindResult.mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_General, methodRefTarget);
  11998. if (!lookupVal)
  11999. continue;
  12000. if ((fieldType->IsPointer()) && (lookupVal.mType != fieldType))
  12001. {
  12002. BF_ASSERT(fieldType->GetUnderlyingType() == lookupVal.mType);
  12003. BF_ASSERT(lookupVal.IsAddr());
  12004. }
  12005. else if (!fieldType->IsRef())
  12006. lookupVal = mModule->LoadOrAggregateValue(lookupVal);
  12007. if (lookupVal)
  12008. mModule->mBfIRBuilder->CreateStore(lookupVal.mValue, fieldPtr);
  12009. fieldIdx++;
  12010. }
  12011. String methodName = _GetInvokeMethodName();
  12012. SizedArray<BfIRType, 8> irParamTypes;
  12013. BfIRType irReturnType;
  12014. bool hasThis = false;
  12015. if (hasCaptures)
  12016. {
  12017. hasThis = true;
  12018. methodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  12019. int thisIdx = 0;
  12020. if (GetStructRetIdx(methodInstance) == 0)
  12021. thisIdx = 1;
  12022. irParamTypes[thisIdx] = mModule->mBfIRBuilder->MapType(useTypeInstance);
  12023. }
  12024. else
  12025. {
  12026. BF_ASSERT(hasIncompatibleCallingConventions);
  12027. bindMethodInstance->GetIRFunctionInfo(mModule, irReturnType, irParamTypes);
  12028. hasThis = bindMethodInstance->HasThis();
  12029. }
  12030. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  12031. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  12032. mModule->mBfIRBuilder->SaveDebugLocation();
  12033. auto funcType = mModule->mBfIRBuilder->CreateFunctionType(irReturnType, irParamTypes);
  12034. funcValue = mModule->mBfIRBuilder->CreateFunction(funcType, BfIRLinkageType_External, methodName);
  12035. if (GetStructRetIdx(methodInstance) != -1)
  12036. {
  12037. mModule->mBfIRBuilder->Func_AddAttribute(funcValue, GetStructRetIdx(methodInstance) + 1, BfIRAttribute_NoAlias);
  12038. mModule->mBfIRBuilder->Func_AddAttribute(funcValue, GetStructRetIdx(methodInstance) + 1, BfIRAttribute_StructRet);
  12039. }
  12040. auto srcCallingConv = mModule->GetIRCallingConvention(methodInstance);
  12041. if ((!hasThis) && (methodInstance->mCallingConvention == BfCallingConvention_Stdcall))
  12042. srcCallingConv = BfIRCallingConv_StdCall;
  12043. else if (methodInstance->mCallingConvention == BfCallingConvention_Fastcall)
  12044. srcCallingConv = BfIRCallingConv_FastCall;
  12045. mModule->mBfIRBuilder->SetFuncCallingConv(funcValue, srcCallingConv);
  12046. mModule->mBfIRBuilder->SetActiveFunction(funcValue);
  12047. auto entryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  12048. mModule->mBfIRBuilder->SetInsertPoint(entryBlock);
  12049. fieldIdx = 0;
  12050. SizedArray<BfIRValue, 8> irArgs;
  12051. int argIdx = 0;
  12052. if (GetStructRetIdx(bindMethodInstance) == 0)
  12053. {
  12054. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(GetStructRetIdx(methodInstance)));
  12055. argIdx++;
  12056. }
  12057. for (int implicitParamIdx = bindMethodInstance->HasThis() ? -1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  12058. {
  12059. auto fieldInst = &useTypeInstance->mFieldInstances[fieldIdx];
  12060. int gepIdx = fieldInst->mDataIdx;
  12061. auto fieldType = bindMethodInstance->GetParamType(implicitParamIdx);
  12062. bool disableSplat = false;
  12063. if ((implicitParamIdx == -1) && (captureThisByValue))
  12064. {
  12065. if (fieldType->IsPointer())
  12066. {
  12067. fieldType = fieldType->GetUnderlyingType();
  12068. disableSplat = true;
  12069. }
  12070. }
  12071. int thisIdx = 0;
  12072. if (GetStructRetIdx(methodInstance) == 0)
  12073. thisIdx = 1;
  12074. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->GetArgument(thisIdx), 0, gepIdx);
  12075. BfTypedValue typedVal(fieldPtr, fieldType, true);
  12076. PushArg(typedVal, irArgs, disableSplat);
  12077. fieldIdx++;
  12078. }
  12079. if (hasThis)
  12080. argIdx++;
  12081. if (GetStructRetIdx(bindMethodInstance) == 1)
  12082. {
  12083. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(GetStructRetIdx(methodInstance)));
  12084. argIdx++;
  12085. }
  12086. for (int paramIdx = 0; paramIdx < methodInstance->GetParamCount(); paramIdx++)
  12087. {
  12088. auto paramType = methodInstance->GetParamType(paramIdx);
  12089. if ((paramType->IsSplattable()) && (!IsComptime()))
  12090. {
  12091. BfTypeUtils::SplatIterate([&](BfType* checkType) { irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++)); }, paramType);
  12092. }
  12093. else if (!paramType->IsValuelessType())
  12094. {
  12095. irArgs.push_back(mModule->mBfIRBuilder->GetArgument(argIdx++));
  12096. }
  12097. }
  12098. auto bindFuncVal = bindResult.mFunc;
  12099. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!mModule->mIsComptimeModule))
  12100. bindFuncVal = mModule->mBfIRBuilder->RemapBindFunction(bindFuncVal);
  12101. auto callInst = mModule->mBfIRBuilder->CreateCall(bindFuncVal, irArgs);
  12102. if (GetStructRetIdx(bindMethodInstance) != -1)
  12103. mModule->mBfIRBuilder->Call_AddAttribute(callInst, GetStructRetIdx(bindMethodInstance) + 1, BfIRAttribute_StructRet);
  12104. auto destCallingConv = mModule->GetIRCallingConvention(bindMethodInstance);
  12105. if (destCallingConv != BfIRCallingConv_CDecl)
  12106. mModule->mBfIRBuilder->SetCallCallingConv(callInst, destCallingConv);
  12107. if ((methodInstance->mReturnType->IsValuelessType()) || (GetStructRetIdx(methodInstance) != -1))
  12108. {
  12109. mModule->mBfIRBuilder->CreateRetVoid();
  12110. }
  12111. else
  12112. {
  12113. mModule->mBfIRBuilder->CreateRet(callInst);
  12114. }
  12115. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  12116. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  12117. mModule->mBfIRBuilder->RestoreDebugLocation();
  12118. }
  12119. else if ((closureTypeInst != NULL) && (captureThisByValue))
  12120. {
  12121. // 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
  12122. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, 1);
  12123. target = mModule->LoadValue(target);
  12124. mModule->mBfIRBuilder->CreateStore(target.mValue, fieldPtr);
  12125. target = BfTypedValue(fieldPtr, target.mType, true);
  12126. }
  12127. BfResolvedArgs resolvedArgs;
  12128. MatchConstructor(delegateBindExpr, delegateBindExpr, mResult, useTypeInstance, resolvedArgs, false, false);
  12129. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  12130. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType, BfIRPopulateType_Full));
  12131. // >> delegate.mTarget = bindResult.mTarget
  12132. BfIRValue valPtr;
  12133. if (mModule->HasExecutedOutput())
  12134. {
  12135. if ((implicitParamCount > 0) || (needsSplat)) // Point back to self, it contains capture data
  12136. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12137. else if (bindResult.mTarget)
  12138. valPtr = mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_NullPtr));
  12139. else
  12140. valPtr = mModule->GetDefaultValue(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  12141. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 2);
  12142. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  12143. }
  12144. if (!funcValue)
  12145. {
  12146. funcValue = bindResult.mFunc;
  12147. if (!funcValue)
  12148. {
  12149. if ((mModule->HasExecutedOutput()) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  12150. mModule->AssertErrorState();
  12151. return;
  12152. }
  12153. if ((mModule->mCompiler->mOptions.mAllowHotSwapping) && (!bindResult.mMethodInstance->mMethodDef->mIsVirtual) && (!mModule->mIsComptimeModule))
  12154. {
  12155. funcValue = mModule->mBfIRBuilder->RemapBindFunction(funcValue);
  12156. }
  12157. }
  12158. // >> delegate.mFuncPtr = bindResult.mFunc
  12159. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  12160. valPtr = mModule->mBfIRBuilder->CreateBitCast(funcValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  12161. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, 1);
  12162. mModule->mBfIRBuilder->CreateStore(valPtr, fieldPtr);
  12163. }
  12164. void BfExprEvaluator::VisitLambdaBodies(BfAstNode* body, BfFieldDtorDeclaration* fieldDtor)
  12165. {
  12166. if (auto blockBody = BfNodeDynCast<BfBlock>(body))
  12167. mModule->VisitChild(blockBody);
  12168. else if (auto bodyExpr = BfNodeDynCast<BfExpression>(body))
  12169. {
  12170. auto result = mModule->CreateValueFromExpression(bodyExpr);
  12171. if ((result) && (mModule->mCurMethodState->mClosureState != NULL) &&
  12172. (mModule->mCurMethodState->mClosureState->mReturnTypeInferState == BfReturnTypeInferState_Inferring))
  12173. mModule->mCurMethodState->mClosureState->mReturnType = result.mType;
  12174. }
  12175. while (fieldDtor != NULL)
  12176. {
  12177. mModule->mCurMethodState->mLeftBlockUncond = false;
  12178. mModule->VisitChild(fieldDtor->mBody);
  12179. fieldDtor = fieldDtor->mNextFieldDtor;
  12180. }
  12181. }
  12182. BfLambdaInstance* BfExprEvaluator::GetLambdaInstance(BfLambdaBindExpression* lambdaBindExpr, BfAllocTarget& allocTarget)
  12183. {
  12184. if (mModule->mCurMethodState == NULL)
  12185. return NULL;
  12186. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  12187. BfAstNodeList cacheNodeList;
  12188. cacheNodeList.mList.Add(lambdaBindExpr);
  12189. ///
  12190. {
  12191. auto checkMethodState = mModule->mCurMethodState;
  12192. while (checkMethodState != NULL)
  12193. {
  12194. if (checkMethodState->mMixinState != NULL)
  12195. cacheNodeList.mList.Add(checkMethodState->mMixinState->mSource);
  12196. checkMethodState = checkMethodState->mPrevMethodState;
  12197. }
  12198. }
  12199. bool isInferReturnType = (mBfEvalExprFlags & BfEvalExprFlags_InferReturnType) != 0;
  12200. BfLambdaInstance* lambdaInstance = NULL;
  12201. if ((!isInferReturnType) && (rootMethodState->mLambdaCache.TryGetValue(cacheNodeList, &lambdaInstance)))
  12202. return lambdaInstance;
  12203. static int sBindCount = 0;
  12204. sBindCount++;
  12205. bool isFunctionBind = false;
  12206. BfTypeInstance* delegateTypeInstance = NULL;
  12207. BfMethodInstance* invokeMethodInstance = NULL;
  12208. if (mExpectingType == NULL)
  12209. {
  12210. mModule->Fail("Cannot infer delegate type", lambdaBindExpr);
  12211. delegateTypeInstance = mModule->ResolveTypeDef(mModule->mCompiler->mActionTypeDef)->ToTypeInstance();
  12212. }
  12213. else
  12214. {
  12215. delegateTypeInstance = mExpectingType->ToTypeInstance();
  12216. if ((delegateTypeInstance == NULL) ||
  12217. ((!delegateTypeInstance->mTypeDef->mIsDelegate) && (!delegateTypeInstance->mTypeDef->mIsFunction)))
  12218. {
  12219. if (lambdaBindExpr->mFatArrowToken != NULL)
  12220. mModule->Fail("Can only bind lambdas to delegate types", lambdaBindExpr->mFatArrowToken);
  12221. delegateTypeInstance = mModule->ResolveTypeDef(mModule->mCompiler->mActionTypeDef)->ToTypeInstance();
  12222. }
  12223. else
  12224. {
  12225. invokeMethodInstance = mModule->GetRawMethodInstanceAtIdx(delegateTypeInstance, 0, "Invoke");
  12226. }
  12227. isFunctionBind = delegateTypeInstance->mTypeDef->mIsFunction;
  12228. }
  12229. if (auto tokenNode = BfNodeDynCast<BfTokenNode>(lambdaBindExpr->mNewToken))
  12230. {
  12231. if (isFunctionBind)
  12232. {
  12233. mModule->Fail("Function lambda binding does not require allocation", lambdaBindExpr->mNewToken);
  12234. }
  12235. else if (tokenNode->GetToken() == BfToken_Append)
  12236. {
  12237. mModule->Fail("Append allocation on delegate bind not supported", lambdaBindExpr->mNewToken);
  12238. }
  12239. }
  12240. if (invokeMethodInstance != NULL)
  12241. {
  12242. if ((int)lambdaBindExpr->mParams.size() < invokeMethodInstance->GetParamCount())
  12243. {
  12244. BfAstNode* refNode = lambdaBindExpr->mCloseParen;
  12245. if (refNode == NULL)
  12246. refNode = lambdaBindExpr;
  12247. mModule->Fail(StrFormat("Not enough parameters for delegate type '%s'. Expected %d more.",
  12248. mModule->TypeToString(delegateTypeInstance).c_str(), invokeMethodInstance->GetParamCount() - lambdaBindExpr->mParams.size()), refNode);
  12249. }
  12250. else if ((int)lambdaBindExpr->mParams.size() > invokeMethodInstance->GetParamCount())
  12251. {
  12252. BfAstNode* refNode = lambdaBindExpr->mParams[invokeMethodInstance->GetParamCount()];
  12253. mModule->Fail(StrFormat("Too many parameters for delegate type '%s'. Expected %d fewer.",
  12254. mModule->TypeToString(delegateTypeInstance).c_str(), lambdaBindExpr->mParams.size() - invokeMethodInstance->GetParamCount()), refNode);
  12255. }
  12256. }
  12257. auto autoComplete = GetAutoComplete();
  12258. bool wasCapturingMethodInfo = false;
  12259. if ((autoComplete != NULL) && (invokeMethodInstance != NULL))
  12260. {
  12261. wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  12262. if (autoComplete->IsAutocompleteNode(lambdaBindExpr, lambdaBindExpr->mFatArrowToken))
  12263. autoComplete->CheckInvocation(lambdaBindExpr, lambdaBindExpr->mOpenParen, lambdaBindExpr->mCloseParen, lambdaBindExpr->mCommas);
  12264. if (autoComplete->mIsCapturingMethodMatchInfo)
  12265. {
  12266. autoComplete->mMethodMatchInfo->mInstanceList.Clear();
  12267. auto methodMatchInfo = autoComplete->mMethodMatchInfo;
  12268. BfAutoComplete::MethodMatchEntry methodMatchEntry;
  12269. methodMatchEntry.mTypeInstance = invokeMethodInstance->GetOwner();
  12270. methodMatchEntry.mCurMethodInstance = mModule->mCurMethodInstance;
  12271. methodMatchEntry.mMethodDef = invokeMethodInstance->mMethodDef;
  12272. autoComplete->mMethodMatchInfo->mInstanceList.push_back(methodMatchEntry);
  12273. methodMatchInfo->mBestIdx = 0;
  12274. methodMatchInfo->mMostParamsMatched = 0;
  12275. int cursorIdx = lambdaBindExpr->GetParser()->mCursorIdx;
  12276. if ((lambdaBindExpr->mCloseParen == NULL) || (cursorIdx <= lambdaBindExpr->mCloseParen->GetSrcStart()))
  12277. {
  12278. int paramIdx = 0;
  12279. for (int commaIdx = 0; commaIdx < (int)lambdaBindExpr->mCommas.size(); commaIdx++)
  12280. {
  12281. auto commaNode = lambdaBindExpr->mCommas[commaIdx];
  12282. if ((commaNode != NULL) && (cursorIdx >= commaNode->GetSrcStart()))
  12283. paramIdx = commaIdx + 1;
  12284. }
  12285. bool isEmpty = true;
  12286. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  12287. {
  12288. auto paramNode = lambdaBindExpr->mParams[paramIdx];
  12289. if (paramNode != NULL)
  12290. isEmpty = false;
  12291. }
  12292. if (isEmpty)
  12293. {
  12294. if (paramIdx < (int)invokeMethodInstance->GetParamCount())
  12295. {
  12296. String paramName = invokeMethodInstance->GetParamName(paramIdx);
  12297. autoComplete->mEntriesSet.Clear();
  12298. if (paramName.IsEmpty())
  12299. paramName += StrFormat("val%d", paramIdx + 1);
  12300. autoComplete->AddEntry(AutoCompleteEntry("paramName", paramName));
  12301. autoComplete->mInsertStartIdx = cursorIdx;
  12302. autoComplete->mInsertEndIdx = cursorIdx;
  12303. if ((paramIdx == 0) && (lambdaBindExpr->mParams.IsEmpty()))
  12304. {
  12305. String totalNames;
  12306. for (int checkIdx = 0; checkIdx < (int)invokeMethodInstance->GetParamCount(); checkIdx++)
  12307. {
  12308. if (!totalNames.IsEmpty())
  12309. totalNames += ", ";
  12310. String paramName = invokeMethodInstance->GetParamName(checkIdx);
  12311. if (paramName.IsEmpty())
  12312. paramName += StrFormat("val%d", checkIdx + 1);
  12313. totalNames += paramName;
  12314. }
  12315. autoComplete->AddEntry(AutoCompleteEntry("paramNames", totalNames));
  12316. }
  12317. }
  12318. }
  12319. }
  12320. }
  12321. }
  12322. defer
  12323. (
  12324. {
  12325. if (autoComplete != NULL)
  12326. autoComplete->mIsCapturingMethodMatchInfo = (wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo != NULL);
  12327. }
  12328. );
  12329. if (lambdaBindExpr->mBody == NULL)
  12330. {
  12331. mModule->AssertErrorState();
  12332. return NULL;
  12333. }
  12334. if ((lambdaBindExpr->mNewToken == NULL) && (isInferReturnType))
  12335. {
  12336. // Method ref, but let this follow infer route
  12337. }
  12338. else if ((lambdaBindExpr->mNewToken == NULL) || (isFunctionBind))
  12339. {
  12340. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  12341. {
  12342. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  12343. VisitLambdaBodies(lambdaBindExpr->mBody, lambdaBindExpr->mDtor);
  12344. }
  12345. if ((lambdaBindExpr->mNewToken != NULL) && (isFunctionBind))
  12346. mModule->Fail("Binds to functions should do not require allocations.", lambdaBindExpr->mNewToken);
  12347. if (lambdaBindExpr->mDtor != NULL)
  12348. {
  12349. mModule->Fail("Valueless method reference cannot contain destructor. Consider either removing destructor or using an allocated lambda.", lambdaBindExpr->mDtor->mTildeToken);
  12350. // Eat it
  12351. auto fieldDtor = lambdaBindExpr->mDtor;
  12352. while (fieldDtor != NULL)
  12353. {
  12354. mModule->VisitEmbeddedStatement(fieldDtor->mBody);
  12355. fieldDtor = fieldDtor->mNextFieldDtor;
  12356. }
  12357. }
  12358. if (invokeMethodInstance != NULL)
  12359. {
  12360. BfLocalMethod* localMethod = new BfLocalMethod();
  12361. localMethod->mMethodName = "anon";
  12362. localMethod->mSystem = mModule->mSystem;
  12363. localMethod->mModule = mModule;
  12364. localMethod->mExpectedFullName = mModule->GetLocalMethodName(localMethod->mMethodName, lambdaBindExpr->mFatArrowToken, mModule->mCurMethodState, mModule->mCurMethodState->mMixinState);
  12365. localMethod->mLambdaInvokeMethodInstance = invokeMethodInstance;
  12366. localMethod->mLambdaBindExpr = lambdaBindExpr;
  12367. localMethod->mDeclMethodState = mModule->mCurMethodState;
  12368. mModule->mContext->mLocalMethodGraveyard.push_back(localMethod);
  12369. auto moduleMethodInstance = mModule->GetLocalMethodInstance(localMethod, BfTypeVector());
  12370. if (moduleMethodInstance.mMethodInstance->mDisallowCalling)
  12371. {
  12372. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  12373. return NULL;
  12374. }
  12375. auto methodRefType = mModule->CreateMethodRefType(moduleMethodInstance.mMethodInstance);
  12376. mModule->AddDependency(methodRefType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  12377. mModule->AddCallDependency(moduleMethodInstance.mMethodInstance);
  12378. mResult = BfTypedValue(BfIRValue(BfIRValueFlags_Value, BfIRValue::ID_IMPLICIT), methodRefType);
  12379. return NULL;
  12380. }
  12381. }
  12382. //SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites);
  12383. SetAndRestoreValue<bool> prevIgnoreIRWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mWantsIRIgnoreWrites || mModule->mCurMethodInstance->mIsUnspecialized);
  12384. BfTypeInstance* outerClosure = NULL;
  12385. if ((mModule->mCurMethodState->mClosureState != NULL) && (!mModule->mCurMethodState->mClosureState->mCapturing))
  12386. outerClosure = mModule->mCurMethodState->mClosureState->mClosureType;
  12387. Val128 val128(delegateTypeInstance->mTypeId);
  12388. bool isConstEval = ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0);
  12389. BfMethodState methodState;
  12390. methodState.mPrevMethodState = mModule->mCurMethodState;
  12391. BfIRFunctionType funcType;
  12392. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  12393. SizedArray<BfIRType, 0> paramTypes;
  12394. funcType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), paramTypes, false);
  12395. auto prevInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  12396. BF_ASSERT(prevInsertBlock || isConstEval);
  12397. auto prevActiveFunction = mModule->mBfIRBuilder->GetActiveFunction();
  12398. mModule->mBfIRBuilder->SaveDebugLocation();
  12399. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  12400. BfDeferredLocalAssignData deferredLocalAssignData;
  12401. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  12402. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData);
  12403. SetAndRestoreValue<BfMethodState*> prevMethodState(mModule->mCurMethodState, &methodState);
  12404. methodState.mIRHeadBlock = mModule->mBfIRBuilder->CreateBlock("head", true);
  12405. methodState.mIRInitBlock = mModule->mBfIRBuilder->CreateBlock("init", true);
  12406. methodState.mIREntryBlock = mModule->mBfIRBuilder->CreateBlock("entry", true);
  12407. methodState.mCurScope->mDIScope = prevMethodState.mPrevVal->mCurScope->mDIScope;//invokeMethodInstance->mDIFunction;
  12408. methodState.mCurLocalVarId = -1;
  12409. methodState.mIRFunction = prevMethodState.mPrevVal->mIRFunction;
  12410. methodState.mDeferredLocalAssignData = &deferredLocalAssignData;
  12411. mModule->mBfIRBuilder->SetInsertPoint(methodState.mIREntryBlock);
  12412. BfClosureState closureState;
  12413. if (delegateTypeInstance->IsDelegate())
  12414. closureState.mReturnType = mModule->GetDelegateReturnType(delegateTypeInstance);
  12415. else
  12416. closureState.mReturnType = mModule->mContext->mBfObjectType;
  12417. closureState.mCapturing = true;
  12418. if (delegateTypeInstance->IsDelegate())
  12419. closureState.mDelegateType = delegateTypeInstance;
  12420. closureState.mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  12421. methodState.mClosureState = &closureState;
  12422. closureState.mClosureType = outerClosure;
  12423. BF_ASSERT(methodState.mCurLocalVarId == -1);
  12424. int outerLocalsCount = (int)methodState.mLocals.size();
  12425. // static int sItrCount = 0;
  12426. // ++sItrCount;
  12427. // int itrCount = sItrCount;
  12428. // if ((itrCount == 8) || (itrCount == 10))
  12429. // {
  12430. // NOP;
  12431. // }
  12432. String delegateTypeName = mModule->TypeToString(delegateTypeInstance);
  12433. HashContext hashCtx;
  12434. hashCtx.MixinStr(delegateTypeName);
  12435. BfSource* bfSource = delegateTypeInstance->mTypeDef->mSource;
  12436. BfMethodDef* methodDef = new BfMethodDef();
  12437. methodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  12438. Val128 closureMethodHash;
  12439. OwnedVector<BfParameterDeclaration> tempParamDecls;
  12440. if ((autoComplete != NULL) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->IsAutocompleteNode(lambdaBindExpr->mBody)))
  12441. {
  12442. // Don't show outer method match info when our cursor is inside a lambda expression (being passed as a parameter)
  12443. autoComplete->RemoveMethodMatchInfo();
  12444. }
  12445. if (invokeMethodInstance != NULL)
  12446. {
  12447. for (int paramIdx = 0; paramIdx < (int)invokeMethodInstance->mMethodDef->mParams.size(); paramIdx++)
  12448. {
  12449. auto invokeParamDef = invokeMethodInstance->mMethodDef->mParams[paramIdx];
  12450. BfParameterDef* paramDef = new BfParameterDef();
  12451. paramDef->mParamDeclaration = tempParamDecls.Alloc();
  12452. BfAstNode::Zero(paramDef->mParamDeclaration);
  12453. BfLocalVariable* localVar = new BfLocalVariable();
  12454. if (paramIdx < (int)lambdaBindExpr->mParams.size())
  12455. {
  12456. localVar->mName = lambdaBindExpr->mParams[paramIdx]->ToString();
  12457. localVar->mNameNode = lambdaBindExpr->mParams[paramIdx];
  12458. paramDef->mParamDeclaration->mNameNode = lambdaBindExpr->mParams[paramIdx];
  12459. }
  12460. else
  12461. {
  12462. mModule->AssertErrorState();
  12463. localVar->mName = invokeParamDef->mName;
  12464. paramDef->mParamDeclaration->mNameNode = NULL;
  12465. }
  12466. paramDef->mName = localVar->mName;
  12467. methodDef->mParams.push_back(paramDef);
  12468. localVar->mResolvedType = invokeMethodInstance->GetParamType(paramIdx);
  12469. mModule->PopulateType(localVar->mResolvedType);
  12470. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  12471. localVar->mReadFromId = 0;
  12472. auto rootMethodState = methodState.GetRootMethodState();
  12473. localVar->mLocalVarId = rootMethodState->mCurLocalVarId++;
  12474. mModule->DoAddLocalVariable(localVar);
  12475. if (autoComplete != NULL)
  12476. autoComplete->CheckLocalDef(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), methodState.mLocals.back());
  12477. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  12478. if (resolvePassData != NULL)
  12479. resolvePassData->HandleLocalReference(BfNodeDynCast<BfIdentifierNode>(paramDef->mParamDeclaration->mNameNode), mModule->mCurTypeInstance->mTypeDef,
  12480. mModule->mCurMethodInstance->mMethodDef, localVar->mLocalVarId);
  12481. }
  12482. }
  12483. bool isAutocomplete = mModule->mCompiler->IsAutocomplete();
  12484. methodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  12485. methodDef->mBody = lambdaBindExpr->mBody;
  12486. ///
  12487. auto varMethodState = methodState.mPrevMethodState;
  12488. bool hasExplicitCaptureNames = false;
  12489. for (auto& captureEntry : allocTarget.mCaptureInfo->mCaptures)
  12490. {
  12491. if (captureEntry.mNameNode == NULL)
  12492. {
  12493. hasExplicitCaptureNames = false;
  12494. break;
  12495. }
  12496. hasExplicitCaptureNames = true;
  12497. }
  12498. auto _SetNotCapturedFlag = [&](bool notCaptured)
  12499. {
  12500. auto varMethodState = methodState.mPrevMethodState;
  12501. while (varMethodState != NULL)
  12502. {
  12503. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  12504. {
  12505. auto localVar = varMethodState->mLocals[localIdx];
  12506. localVar->mNotCaptured = notCaptured;
  12507. }
  12508. varMethodState = varMethodState->mPrevMethodState;
  12509. if (varMethodState == NULL)
  12510. break;
  12511. if (varMethodState->mMixinState != NULL)
  12512. break;
  12513. if (varMethodState->mClosureState != NULL)
  12514. {
  12515. if (!varMethodState->mClosureState->mCapturing)
  12516. break;
  12517. }
  12518. }
  12519. };
  12520. if (hasExplicitCaptureNames)
  12521. {
  12522. _SetNotCapturedFlag(true);
  12523. auto varMethodState = methodState.mPrevMethodState;
  12524. while (varMethodState != NULL)
  12525. {
  12526. for (auto& captureEntry : allocTarget.mCaptureInfo->mCaptures)
  12527. {
  12528. if (captureEntry.mNameNode != NULL)
  12529. {
  12530. StringT<64> captureName;
  12531. captureEntry.mNameNode->ToString(captureName);
  12532. BfLocalVarEntry* entry;
  12533. if (varMethodState->mLocalVarSet.TryGetWith<StringImpl&>(captureName, &entry))
  12534. {
  12535. auto localVar = entry->mLocalVar;
  12536. while (localVar != NULL)
  12537. {
  12538. if (autoComplete != NULL)
  12539. autoComplete->CheckLocalRef(captureEntry.mNameNode, localVar);
  12540. if (((mModule->mCurMethodState->mClosureState == NULL) || (mModule->mCurMethodState->mClosureState->mCapturing)) &&
  12541. (mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCurMethodInstance != NULL))
  12542. mModule->mCompiler->mResolvePassData->HandleLocalReference(captureEntry.mNameNode, localVar->mNameNode, mModule->mCurTypeInstance->mTypeDef, rootMethodState->mMethodInstance->mMethodDef, localVar->mLocalVarId);
  12543. localVar->mNotCaptured = false;
  12544. localVar = localVar->mShadowedLocal;
  12545. }
  12546. }
  12547. }
  12548. }
  12549. varMethodState = varMethodState->mPrevMethodState;
  12550. if (varMethodState == NULL)
  12551. break;
  12552. if (varMethodState->mMixinState != NULL)
  12553. break;
  12554. if (varMethodState->mClosureState != NULL)
  12555. {
  12556. if (!varMethodState->mClosureState->mCapturing)
  12557. break;
  12558. }
  12559. }
  12560. }
  12561. BfClosureInstanceInfo* closureInstanceInfo = new BfClosureInstanceInfo();
  12562. auto checkInsertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  12563. closureState.mCaptureStartAccessId = methodState.mPrevMethodState->GetRootMethodState()->mCurAccessId;
  12564. closureState.mCaptureVisitingBody = true;
  12565. closureState.mClosureInstanceInfo = closureInstanceInfo;
  12566. if ((mBfEvalExprFlags & BfEvalExprFlags_InferReturnType) != 0)
  12567. {
  12568. closureState.mReturnType = NULL;
  12569. closureState.mReturnTypeInferState = BfReturnTypeInferState_Inferring;
  12570. }
  12571. VisitLambdaBodies(lambdaBindExpr->mBody, lambdaBindExpr->mDtor);
  12572. if (hasExplicitCaptureNames)
  12573. _SetNotCapturedFlag(false);
  12574. // If we ended up being called by a method with a lower captureStartAccessId, propagate that to whoever is calling us, too...
  12575. if ((methodState.mPrevMethodState->mClosureState != NULL) && (methodState.mPrevMethodState->mClosureState->mCapturing))
  12576. {
  12577. auto prevClosureState = methodState.mPrevMethodState->mClosureState;
  12578. if (closureState.mCaptureStartAccessId < prevClosureState->mCaptureStartAccessId)
  12579. prevClosureState->mCaptureStartAccessId = closureState.mCaptureStartAccessId;
  12580. }
  12581. bool earlyExit = false;
  12582. if (isInferReturnType)
  12583. {
  12584. if ((closureState.mReturnTypeInferState == BfReturnTypeInferState_Fail) ||
  12585. (closureState.mReturnType == NULL))
  12586. {
  12587. mResult = BfTypedValue();
  12588. }
  12589. else
  12590. {
  12591. mResult = BfTypedValue(closureState.mReturnType);
  12592. }
  12593. earlyExit = true;
  12594. }
  12595. else if (mModule->mCurMethodInstance->mIsUnspecialized)
  12596. {
  12597. earlyExit = true;
  12598. mResult = mModule->GetDefaultTypedValue(delegateTypeInstance);
  12599. }
  12600. if (earlyExit)
  12601. {
  12602. prevIgnoreWrites.Restore();
  12603. mModule->mBfIRBuilder->RestoreDebugLocation();
  12604. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  12605. if (!prevInsertBlock.IsFake())
  12606. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  12607. delete methodDef;
  12608. delete closureInstanceInfo;
  12609. return NULL;
  12610. }
  12611. closureState.mCaptureVisitingBody = false;
  12612. prevIgnoreWrites.Restore();
  12613. mModule->mBfIRBuilder->RestoreDebugLocation();
  12614. auto _GetCaptureType = [&](const StringImpl& str)
  12615. {
  12616. if (allocTarget.mCaptureInfo->mCaptures.IsEmpty())
  12617. return BfCaptureType_Copy;
  12618. for (auto& captureEntry : allocTarget.mCaptureInfo->mCaptures)
  12619. {
  12620. if ((captureEntry.mNameNode == NULL) || (captureEntry.mNameNode->Equals(str)))
  12621. {
  12622. captureEntry.mUsed = true;
  12623. return captureEntry.mCaptureType;
  12624. }
  12625. }
  12626. return BfCaptureType_None;
  12627. };
  12628. Array<BfClosureCapturedEntry> capturedEntries;
  12629. bool copyOuterCaptures = false;
  12630. //
  12631. {
  12632. auto varMethodState = methodState.mPrevMethodState;
  12633. while (varMethodState != NULL)
  12634. {
  12635. for (int localIdx = 0; localIdx < varMethodState->mLocals.size(); localIdx++)
  12636. {
  12637. auto localVar = varMethodState->mLocals[localIdx];
  12638. if ((localVar->mReadFromId >= closureState.mCaptureStartAccessId) || (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  12639. {
  12640. if ((localVar->mIsThis) && (outerClosure != NULL))
  12641. {
  12642. continue;
  12643. }
  12644. auto outerLocal = localVar;
  12645. if ((localVar->mConstValue) || (localVar->mResolvedType->IsValuelessType()))
  12646. {
  12647. closureState.mConstLocals.push_back(*outerLocal);
  12648. continue;
  12649. }
  12650. BfClosureCapturedEntry capturedEntry;
  12651. auto capturedType = outerLocal->mResolvedType;
  12652. bool captureByRef = false;
  12653. auto captureType = _GetCaptureType(localVar->mName);
  12654. if (captureType == BfCaptureType_None)
  12655. {
  12656. continue;
  12657. }
  12658. if (!capturedType->IsRef())
  12659. {
  12660. if (captureType == BfCaptureType_Reference)
  12661. {
  12662. if (outerLocal->mIsThis)
  12663. {
  12664. if ((outerLocal->mResolvedType->IsValueType()) && (mModule->mCurMethodInstance->mMethodDef->HasNoThisSplat()))
  12665. captureByRef = true;
  12666. }
  12667. else if ((!localVar->mIsReadOnly) && (localVar->mWrittenToId >= closureState.mCaptureStartAccessId))
  12668. captureByRef = true;
  12669. }
  12670. }
  12671. else
  12672. {
  12673. if ((captureType != BfCaptureType_Reference) || (localVar->mWrittenToId < closureState.mCaptureStartAccessId))
  12674. {
  12675. capturedType = ((BfRefType*)capturedType)->mElementType;
  12676. }
  12677. }
  12678. if (captureByRef)
  12679. {
  12680. capturedType = mModule->CreateRefType(capturedType);
  12681. }
  12682. if (captureType == BfCaptureType_Reference)
  12683. capturedEntry.mExplicitlyByReference = true;
  12684. capturedEntry.mType = capturedType;
  12685. capturedEntry.mNameNode = outerLocal->mNameNode;
  12686. if (outerLocal->mName == "this")
  12687. capturedEntry.mName = "__this";
  12688. else
  12689. {
  12690. capturedEntry.mName = outerLocal->mName;
  12691. BfLocalVarEntry* entry = NULL;
  12692. if (varMethodState->mLocalVarSet.TryGetWith<StringImpl&>(capturedEntry.mName, &entry))
  12693. {
  12694. auto startCheckVar = entry->mLocalVar;
  12695. int shadowIdx = 0;
  12696. auto checkVar = startCheckVar;
  12697. while (checkVar != NULL)
  12698. {
  12699. if (checkVar == outerLocal)
  12700. {
  12701. // We only use mShadowIdx when we have duplicate name nodes (ie: in the case of for looks with iterator vs value)
  12702. auto shadowCheckVar = startCheckVar;
  12703. while (shadowCheckVar != checkVar)
  12704. {
  12705. if (shadowCheckVar->mNameNode == checkVar->mNameNode)
  12706. capturedEntry.mShadowIdx++;
  12707. shadowCheckVar = shadowCheckVar->mShadowedLocal;
  12708. }
  12709. for (int i = 0; i < shadowIdx; i++)
  12710. capturedEntry.mName.Insert(0, '@');
  12711. break;
  12712. }
  12713. shadowIdx++;
  12714. checkVar = checkVar->mShadowedLocal;
  12715. }
  12716. }
  12717. }
  12718. capturedEntries.Add(capturedEntry);
  12719. }
  12720. }
  12721. varMethodState = varMethodState->mPrevMethodState;
  12722. if (varMethodState == NULL)
  12723. break;
  12724. if (varMethodState->mMixinState != NULL)
  12725. break;
  12726. if (varMethodState->mClosureState != NULL)
  12727. {
  12728. if (!varMethodState->mClosureState->mCapturing)
  12729. break;
  12730. }
  12731. }
  12732. }
  12733. for (auto& captureEntry : allocTarget.mCaptureInfo->mCaptures)
  12734. {
  12735. if ((!captureEntry.mUsed) && (captureEntry.mNameNode != NULL))
  12736. mModule->Warn(0, "Capture specifier not used", captureEntry.mNameNode);
  12737. }
  12738. for (auto copyField : closureState.mReferencedOuterClosureMembers)
  12739. {
  12740. auto fieldDef = copyField->GetFieldDef();
  12741. auto captureType = _GetCaptureType(fieldDef->mName);
  12742. BfClosureCapturedEntry capturedEntry;
  12743. capturedEntry.mName = fieldDef->mName;
  12744. capturedEntry.mType = copyField->mResolvedType;
  12745. if ((captureType == BfCaptureType_Reference) && (capturedEntry.mType->IsRef()))
  12746. {
  12747. capturedEntry.mExplicitlyByReference = true;
  12748. }
  12749. else if ((captureType != BfCaptureType_Reference) && (capturedEntry.mType->IsRef()))
  12750. {
  12751. auto refType = (BfRefType*)capturedEntry.mType;
  12752. capturedEntry.mType = refType->mElementType;
  12753. }
  12754. else if ((captureType == BfCaptureType_Reference) && (!capturedEntry.mType->IsRef()) && (!fieldDef->mIsReadOnly))
  12755. {
  12756. capturedEntry.mType = mModule->CreateRefType(capturedEntry.mType);
  12757. }
  12758. }
  12759. std::sort(capturedEntries.begin(), capturedEntries.end());
  12760. bool hasCapture = false;
  12761. BfMethodInstanceGroup methodInstanceGroup;
  12762. methodInstanceGroup.mOwner = mModule->mCurTypeInstance;
  12763. methodInstanceGroup.mOnDemandKind = BfMethodOnDemandKind_AlwaysInclude;
  12764. BfMethodInstance* methodInstance = new BfMethodInstance();
  12765. methodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  12766. methodInstance->GetMethodInfoEx()->mClosureInstanceInfo = closureInstanceInfo;
  12767. if (invokeMethodInstance != NULL)
  12768. methodInstance->mParams = invokeMethodInstance->mParams;
  12769. methodInstance->mIsClosure = true;
  12770. // We want the closure ID to match between hot reloads -- otherwise we wouldn't be able to modify them,
  12771. // so we use the charId from the 'fat arrow' token
  12772. int closureId = 0;
  12773. if (lambdaBindExpr->mFatArrowToken != NULL)
  12774. closureId = lambdaBindExpr->mFatArrowToken->GetStartCharId();
  12775. auto curProject = mModule->mCurTypeInstance->mTypeDef->mProject;
  12776. BF_ASSERT(curProject != NULL);
  12777. // We need to make these per-project even though you'd think we might not because we
  12778. // insert generic type specializations in the generic definition's project,
  12779. // BECAUSE: we would need to scan the captured fields the same way we scan the
  12780. // generic arguments to determine if each project can see it or not in the vdata
  12781. BfTypeInstance* useTypeInstance = delegateTypeInstance;
  12782. BfClosureType* closureTypeInst = NULL;
  12783. // If we are allowing hot swapping we may add a capture later. We also need an equal method that ignores 'target' even when we're capturing ourself
  12784. if ((capturedEntries.size() != 0) || (lambdaBindExpr->mDtor != NULL) || (copyOuterCaptures) || (mModule->mCompiler->mOptions.mAllowHotSwapping) || (closureState.mCapturedDelegateSelf))
  12785. {
  12786. hashCtx.MixinStr(curProject->mName);
  12787. if (copyOuterCaptures)
  12788. {
  12789. hashCtx.Mixin(outerClosure->mTypeId);
  12790. }
  12791. for (auto& capturedEntry : capturedEntries)
  12792. {
  12793. hashCtx.Mixin(capturedEntry.mType->mTypeId);
  12794. hashCtx.MixinStr(capturedEntry.mName);
  12795. hashCtx.Mixin(capturedEntry.mExplicitlyByReference);
  12796. }
  12797. if (lambdaBindExpr->mDtor != NULL)
  12798. {
  12799. // Has DTOR thunk
  12800. bool hasDtorThunk = true;
  12801. hashCtx.Mixin(hasDtorThunk);
  12802. }
  12803. Val128 hash128 = hashCtx.Finish128();
  12804. BfClosureType* checkClosureType = new BfClosureType(delegateTypeInstance, hash128);
  12805. checkClosureType->mContext = mModule->mContext;
  12806. checkClosureType->mBaseType = delegateTypeInstance;
  12807. BfType* resolvedClosureType = mModule->ResolveType(checkClosureType, BfPopulateType_TypeDef);
  12808. closureTypeInst = (BfClosureType*)resolvedClosureType;
  12809. if (checkClosureType == resolvedClosureType)
  12810. {
  12811. // This is a new closure type
  12812. closureTypeInst->Init(curProject);
  12813. closureTypeInst->mTypeDef->mProject = curProject;
  12814. auto delegateDirectTypeRef = BfAstNode::ZeroedAlloc<BfDirectTypeDefReference>();
  12815. delegateDirectTypeRef->Init(mModule->mCompiler->mDelegateTypeDef);
  12816. closureTypeInst->mDirectAllocNodes.push_back(delegateDirectTypeRef);
  12817. BfMethodDef* methodDef = BfDefBuilder::AddMethod(closureTypeInst->mTypeDef, BfMethodType_Normal, BfProtection_Public, false, "Equals");
  12818. methodDef->mReturnTypeRef = mModule->mSystem->mDirectBoolTypeRef;
  12819. BfDefBuilder::AddParam(methodDef, delegateDirectTypeRef, "val");
  12820. methodDef->mIsVirtual = true;
  12821. methodDef->mIsOverride = true;
  12822. if (copyOuterCaptures)
  12823. {
  12824. for (auto& fieldInstance : outerClosure->mFieldInstances)
  12825. {
  12826. BfFieldDef* origFieldDef = fieldInstance.GetFieldDef();
  12827. BfFieldDef* fieldDef = closureTypeInst->AddField(fieldInstance.mResolvedType, origFieldDef->mName);
  12828. fieldDef->mIsReadOnly = origFieldDef->mIsReadOnly;
  12829. }
  12830. }
  12831. for (auto& capturedEntry : capturedEntries)
  12832. {
  12833. BfFieldDef* fieldDef = closureTypeInst->AddField(capturedEntry.mType, capturedEntry.mName);
  12834. if (!capturedEntry.mExplicitlyByReference)
  12835. fieldDef->mIsReadOnly = true;
  12836. }
  12837. if (lambdaBindExpr->mDtor != NULL)
  12838. {
  12839. auto dtorDef = closureTypeInst->AddDtor();
  12840. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  12841. auto voidPtrType = mModule->CreatePointerType(voidType);
  12842. closureTypeInst->AddField(voidPtrType, "__dtorThunk");
  12843. }
  12844. closureTypeInst->Finish();
  12845. }
  12846. else
  12847. {
  12848. // Already had this entry
  12849. delete checkClosureType;
  12850. }
  12851. useTypeInstance = closureTypeInst;
  12852. }
  12853. mModule->mBfIRBuilder->PopulateType(useTypeInstance);
  12854. mModule->PopulateType(useTypeInstance);
  12855. methodDef->mIsStatic = closureTypeInst == NULL;
  12856. SizedArray<BfIRType, 8> origParamTypes;
  12857. BfIRType origReturnType;
  12858. bool forceStatic = false;
  12859. if (invokeMethodInstance != NULL)
  12860. {
  12861. forceStatic = methodDef->mIsStatic;
  12862. auto invokeFunctionType = mModule->mBfIRBuilder->MapMethod(invokeMethodInstance);
  12863. invokeMethodInstance->GetIRFunctionInfo(mModule, origReturnType, origParamTypes, forceStatic);
  12864. }
  12865. else
  12866. {
  12867. origReturnType = mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_None));
  12868. }
  12869. SizedArray<BfIRType, 3> newTypes;
  12870. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) == 0))
  12871. newTypes.push_back(origParamTypes[0]);
  12872. if (!methodDef->mIsStatic)
  12873. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  12874. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) == 1))
  12875. newTypes.push_back(origParamTypes[1]);
  12876. int paramStartIdx = 0;
  12877. if ((invokeMethodInstance != NULL) && (GetStructRetIdx(invokeMethodInstance, forceStatic) != -1))
  12878. paramStartIdx++;
  12879. if (!methodDef->mIsStatic)
  12880. paramStartIdx++;
  12881. for (int i = paramStartIdx; i < (int)origParamTypes.size(); i++)
  12882. newTypes.push_back(origParamTypes[i]);
  12883. auto closureFuncType = mModule->mBfIRBuilder->CreateFunctionType(origReturnType, newTypes, false);
  12884. prevMethodState.Restore();
  12885. mModule->mBfIRBuilder->SetActiveFunction(prevActiveFunction);
  12886. if ((prevInsertBlock) && (!prevInsertBlock.IsFake()))
  12887. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  12888. // Just a check
  12889. mModule->mBfIRBuilder->GetInsertBlock();
  12890. //auto rootMethodState = mModule->mCurMethodState;
  12891. HashContext closureHashCtx;
  12892. closureHashCtx.Mixin(closureId);
  12893. // When we're a nested lambda, strip off the outer hash and closureTypeInst markers
  12894. methodDef->mName = mModule->mCurMethodInstance->mMethodDef->mName;
  12895. int prevSepPos = (int)methodDef->mName.LastIndexOf('$');
  12896. if (prevSepPos != -1)
  12897. {
  12898. closureHashCtx.Mixin(methodDef->mName.c_str() + prevSepPos, (int)methodDef->mName.length() - prevSepPos);
  12899. methodDef->mName.RemoveToEnd(prevSepPos);
  12900. }
  12901. // Mix in this because this can be emitted multiple times when there's multiple ctors and field initializers with lambdas
  12902. if (mModule->mCurMethodInstance->mMethodDef->mMethodType == BfMethodType_Ctor)
  12903. {
  12904. if (auto ctorDecl = BfNodeDynCast<BfConstructorDeclaration>(mModule->mCurMethodInstance->mMethodDef->mMethodDeclaration))
  12905. {
  12906. if (ctorDecl->mThisToken != NULL)
  12907. closureHashCtx.Mixin(ctorDecl->mThisToken->GetStartCharId());
  12908. }
  12909. }
  12910. auto checkMethodState = mModule->mCurMethodState;
  12911. while (checkMethodState != NULL)
  12912. {
  12913. if (checkMethodState->mMethodInstance != NULL)
  12914. {
  12915. if (checkMethodState->mMethodInstance->mMethodInfoEx != NULL)
  12916. {
  12917. for (auto methodGenericArg : checkMethodState->mMethodInstance->mMethodInfoEx->mMethodGenericArguments)
  12918. {
  12919. StringT<128> genericTypeName;
  12920. BfMangler::Mangle(genericTypeName, mModule->mCompiler->GetMangleKind(), methodGenericArg);
  12921. closureHashCtx.MixinStr(genericTypeName);
  12922. }
  12923. }
  12924. }
  12925. checkMethodState = checkMethodState->mPrevMethodState;
  12926. }
  12927. uint64 closureHash = closureHashCtx.Finish64();
  12928. methodDef->mName += "$";
  12929. methodDef->mName += BfTypeUtils::HashEncode64(closureHash);
  12930. methodInstance->mMethodDef = methodDef;
  12931. if (invokeMethodInstance != NULL)
  12932. {
  12933. methodInstance->mParams = invokeMethodInstance->mParams;
  12934. methodInstance->mReturnType = invokeMethodInstance->mReturnType;
  12935. }
  12936. else
  12937. methodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  12938. StringT<128> closureFuncName;
  12939. BfMangler::Mangle(closureFuncName, mModule->mCompiler->GetMangleKind(), methodInstance);
  12940. auto closureFunc = mModule->mBfIRBuilder->CreateFunction(closureFuncType, BfIRLinkageType_External, closureFuncName);
  12941. methodInstance->mIRFunction = closureFunc;
  12942. if (methodInstance->mIsReified)
  12943. mModule->CheckHotMethod(methodInstance, closureFuncName);
  12944. if ((methodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  12945. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(methodInstance->mHotMethod);
  12946. methodState.Reset();
  12947. lambdaInstance = new BfLambdaInstance();
  12948. rootMethodState->mLambdaCache[cacheNodeList] = lambdaInstance;
  12949. lambdaInstance->mDelegateTypeInstance = delegateTypeInstance;
  12950. lambdaInstance->mUseTypeInstance = useTypeInstance;
  12951. lambdaInstance->mClosureTypeInstance = closureTypeInst;
  12952. lambdaInstance->mOuterClosure = outerClosure;
  12953. lambdaInstance->mCopyOuterCaptures = copyOuterCaptures;
  12954. lambdaInstance->mDeclaringMethodIsMutating = mModule->mCurMethodInstance->mMethodDef->mIsMutating;
  12955. lambdaInstance->mIsStatic = methodDef->mIsStatic;
  12956. lambdaInstance->mClosureFunc = closureFunc;
  12957. lambdaInstance->mMethodInstance = methodInstance;
  12958. lambdaInstance->mConstLocals = closureState.mConstLocals;
  12959. lambdaInstance->mParamDecls = tempParamDecls;
  12960. lambdaInstance->mDeclMixinState = mModule->mCurMethodState->mMixinState;
  12961. if (lambdaInstance->mDeclMixinState != NULL)
  12962. lambdaInstance->mDeclMixinState->mHasDeferredUsage = true;
  12963. tempParamDecls.ClearWithoutDeleting();
  12964. closureState.mCapturing = false;
  12965. closureState.mClosureType = useTypeInstance;
  12966. closureInstanceInfo->mThisOverride = useTypeInstance;
  12967. mModule->mIncompleteMethodCount++;
  12968. SetAndRestoreValue<BfClosureState*> prevClosureState(mModule->mCurMethodState->mClosureState, &closureState);
  12969. if (mModule->HasExecutedOutput())
  12970. mModule->SetupIRMethod(methodInstance, methodInstance->mIRFunction, methodInstance->mAlwaysInline);
  12971. // This keeps us from giving errors twice. ProcessMethod can give errors when we capture by value but needed to
  12972. // capture by reference, so we still need to do it for resolve-only
  12973. bool processMethods = (mModule->mCompiler->GetAutoComplete() == NULL) && !mModule->mHadBuildError;
  12974. mModule->mBfIRBuilder->SaveDebugLocation();
  12975. //
  12976. {
  12977. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  12978. if (mModule->mCompiler->mResolvePassData != NULL)
  12979. {
  12980. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  12981. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  12982. }
  12983. if (processMethods)
  12984. {
  12985. // If we are in an always-ignored block, we will have mIgnoreWrites set
  12986. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  12987. // mModule->ProcessMethod(methodInstance);
  12988. }
  12989. if (mModule->mCompiler->mResolvePassData != NULL)
  12990. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  12991. }
  12992. mModule->mBfIRBuilder->RestoreDebugLocation();
  12993. if (mModule->IsSkippingExtraResolveChecks())
  12994. closureFunc = BfIRFunction();
  12995. BfIRFunction dtorFunc;
  12996. if (lambdaBindExpr->mDtor != NULL)
  12997. {
  12998. SizedArray<BfIRType, 1> newTypes;
  12999. newTypes.push_back(mModule->mBfIRBuilder->MapType(useTypeInstance));
  13000. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  13001. auto dtorFuncType = mModule->mBfIRBuilder->CreateFunctionType(mModule->mBfIRBuilder->MapType(voidType), newTypes, false);
  13002. BfMethodDef* dtorMethodDef = new BfMethodDef();
  13003. dtorMethodDef->mDeclaringType = mModule->mCurMethodInstance->mMethodDef->mDeclaringType;
  13004. dtorMethodDef->mName = "~this$";
  13005. dtorMethodDef->mName += methodDef->mName;
  13006. dtorMethodDef->mMethodType = BfMethodType_Normal;
  13007. dtorMethodDef->mBody = lambdaBindExpr->mDtor;
  13008. dtorMethodDef->mIdx = mModule->mCurMethodInstance->mMethodDef->mIdx;
  13009. BfMethodInstance* dtorMethodInstance = new BfMethodInstance();
  13010. dtorMethodInstance->mMethodDef = dtorMethodDef;
  13011. dtorMethodInstance->mReturnType = mModule->GetPrimitiveType(BfTypeCode_None);
  13012. dtorMethodInstance->mMethodInstanceGroup = &methodInstanceGroup;
  13013. StringT<128> dtorMangledName;
  13014. BfMangler::Mangle(dtorMangledName, mModule->mCompiler->GetMangleKind(), dtorMethodInstance);
  13015. dtorFunc = mModule->mBfIRBuilder->CreateFunction(dtorFuncType, BfIRLinkageType_External, dtorMangledName);
  13016. mModule->SetupIRMethod(NULL, dtorFunc, false);
  13017. dtorMethodInstance->mIRFunction = dtorFunc;
  13018. mModule->mIncompleteMethodCount++;
  13019. mModule->mBfIRBuilder->SaveDebugLocation();
  13020. //
  13021. if (processMethods)
  13022. {
  13023. // If we are in an always-ignored block, we will have mIgnoreWrites set
  13024. // SetAndRestoreValue<bool> prevWantsIgnoreWrite(mModule->mWantsIRIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites);
  13025. // mModule->ProcessMethod(dtorMethodInstance);
  13026. }
  13027. mModule->mBfIRBuilder->RestoreDebugLocation();
  13028. if (mModule->IsSkippingExtraResolveChecks())
  13029. dtorFunc = BfIRFunction();
  13030. if (dtorMethodInstance->mIsReified)
  13031. mModule->CheckHotMethod(dtorMethodInstance, dtorMangledName);
  13032. if ((dtorMethodInstance->mHotMethod != NULL) && (mModule->mCurMethodState->mHotDataReferenceBuilder))
  13033. mModule->mCurMethodState->mHotDataReferenceBuilder->mInnerMethods.Add(dtorMethodInstance->mHotMethod);
  13034. lambdaInstance->mDtorMethodInstance = dtorMethodInstance;
  13035. lambdaInstance->mDtorFunc = dtorFunc;
  13036. dtorMethodInstance->mMethodInstanceGroup = NULL;
  13037. }
  13038. prevClosureState.Restore();
  13039. if ((prevInsertBlock) && (!prevInsertBlock.IsFake()))
  13040. mModule->mBfIRBuilder->SetInsertPoint(prevInsertBlock);
  13041. for (auto& capturedEntry : capturedEntries)
  13042. {
  13043. BfLambdaCaptureInfo lambdaCapture;
  13044. if (capturedEntry.mName == "__this")
  13045. lambdaCapture.mName = "this";
  13046. else
  13047. lambdaCapture.mName = capturedEntry.mName;
  13048. lambdaInstance->mCaptures.Add(lambdaCapture);
  13049. closureInstanceInfo->mCaptureEntries.Add(capturedEntry);
  13050. }
  13051. if (processMethods)
  13052. rootMethodState->mDeferredLambdaInstances.Add(lambdaInstance);
  13053. methodInstance->mMethodInstanceGroup = NULL;
  13054. return lambdaInstance;
  13055. }
  13056. void BfExprEvaluator::Visit(BfLambdaBindExpression* lambdaBindExpr)
  13057. {
  13058. BfTokenNode* newToken = NULL;
  13059. BfCaptureInfo captureInfo;
  13060. BfAllocTarget allocTarget;
  13061. allocTarget.mCaptureInfo = &captureInfo;
  13062. ResolveAllocTarget(allocTarget, lambdaBindExpr->mNewToken, newToken);
  13063. if (mModule->mCurMethodInstance == NULL)
  13064. mModule->Fail("Invalid use of lambda bind expression", lambdaBindExpr);
  13065. if (((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mBlindCapturing)) ||
  13066. (mModule->mCurMethodInstance == NULL))
  13067. {
  13068. // We're just capturing. We just need to visit the bodies here. This helps infinite recursion with local methods containing lambdas calling each other
  13069. if (lambdaBindExpr->mBody != NULL)
  13070. mModule->VisitChild(lambdaBindExpr->mBody);
  13071. if ((lambdaBindExpr->mDtor != NULL) && (lambdaBindExpr->mDtor->mBody != NULL))
  13072. mModule->VisitChild(lambdaBindExpr->mDtor->mBody);
  13073. return;
  13074. }
  13075. BfLambdaInstance* lambdaInstance = GetLambdaInstance(lambdaBindExpr, allocTarget);
  13076. if (lambdaInstance == NULL)
  13077. return;
  13078. BfTypeInstance* delegateTypeInstance = lambdaInstance->mDelegateTypeInstance;
  13079. BfTypeInstance* useTypeInstance = lambdaInstance->mUseTypeInstance;
  13080. BfTypeInstance* closureTypeInst = lambdaInstance->mClosureTypeInstance;
  13081. mResult = BfTypedValue(mModule->AllocFromType(useTypeInstance, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None), useTypeInstance);
  13082. if (!delegateTypeInstance->IsDelegate())
  13083. {
  13084. mModule->AssertErrorState();
  13085. return;
  13086. }
  13087. auto baseDelegateType = VerifyBaseDelegateType(delegateTypeInstance->mBaseType);
  13088. if (baseDelegateType == NULL)
  13089. {
  13090. mModule->Fail("Invalid delegate type", lambdaBindExpr);
  13091. return;
  13092. }
  13093. mModule->PopulateType(baseDelegateType);
  13094. auto& funcPtrField = baseDelegateType->mFieldInstances[0];
  13095. auto& targetField = baseDelegateType->mFieldInstances[1];
  13096. auto baseDelegate = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(baseDelegateType));
  13097. // >> delegate.mTarget = bindResult.mTarget
  13098. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  13099. BfIRValue valPtr;
  13100. if (!lambdaInstance->mIsStatic)
  13101. valPtr = mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(nullPtrType));
  13102. else
  13103. valPtr = mModule->GetDefaultValue(nullPtrType);
  13104. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, targetField.mDataIdx);
  13105. mModule->mBfIRBuilder->CreateAlignedStore(valPtr, fieldPtr, targetField.mResolvedType->mAlign);
  13106. // >> delegate.mFuncPtr = bindResult.mFunc
  13107. if (lambdaInstance->mClosureFunc)
  13108. {
  13109. auto nullPtrType = mModule->GetPrimitiveType(BfTypeCode_NullPtr);
  13110. auto valPtr = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mClosureFunc, mModule->mBfIRBuilder->MapType(nullPtrType));
  13111. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(baseDelegate, 0, funcPtrField.mDataIdx);
  13112. mModule->mBfIRBuilder->CreateAlignedStore(valPtr, fieldPtr, funcPtrField.mResolvedType->mAlign);
  13113. }
  13114. mModule->AddDependency(useTypeInstance, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  13115. // Copy captures into the delegate
  13116. if (lambdaInstance->mClosureTypeInstance != NULL)
  13117. {
  13118. int fieldIdx = 0;
  13119. if (lambdaInstance->mCopyOuterCaptures)
  13120. {
  13121. for (auto& fieldInstance : lambdaInstance->mOuterClosure->mFieldInstances)
  13122. {
  13123. if (!fieldInstance.mResolvedType->IsValuelessType())
  13124. {
  13125. BF_ASSERT(fieldInstance.mDataIdx == fieldIdx + 1);
  13126. auto localVar = mModule->mCurMethodState->mLocals[0];
  13127. auto capturedValue = mModule->mBfIRBuilder->CreateInBoundsGEP(localVar->mValue, 0, fieldInstance.mDataIdx);
  13128. capturedValue = mModule->mBfIRBuilder->CreateAlignedLoad(capturedValue, fieldInstance.mResolvedType->mAlign);
  13129. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance.mDataIdx);
  13130. mModule->mBfIRBuilder->CreateStore(capturedValue, fieldPtr);
  13131. fieldIdx++;
  13132. }
  13133. }
  13134. }
  13135. int captureIdx = 0;
  13136. for (int captureIdx = 0; captureIdx < (int)lambdaInstance->mCaptures.size(); captureIdx++)
  13137. {
  13138. auto& capturedEntry = lambdaInstance->mCaptures[captureIdx];
  13139. auto& closureCaptureEntry = lambdaInstance->mMethodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureEntries[captureIdx];
  13140. BfIdentifierNode* identifierNode = closureCaptureEntry.mNameNode;
  13141. BfIRValue capturedValue;
  13142. auto fieldInstance = &closureTypeInst->mFieldInstances[fieldIdx];
  13143. BfTypedValue capturedTypedVal;
  13144. if (identifierNode != NULL)
  13145. capturedTypedVal = DoImplicitArgCapture(NULL, identifierNode, closureCaptureEntry.mShadowIdx);
  13146. else
  13147. capturedTypedVal = LookupIdentifier(NULL, capturedEntry.mName);
  13148. if (!fieldInstance->mResolvedType->IsRef())
  13149. capturedTypedVal = mModule->LoadOrAggregateValue(capturedTypedVal);
  13150. else if (!capturedTypedVal.IsAddr())
  13151. {
  13152. mModule->Fail(StrFormat("Unable to capture '%s' by reference", capturedEntry.mName.c_str()), lambdaBindExpr);
  13153. break;
  13154. }
  13155. capturedValue = capturedTypedVal.mValue;
  13156. if (capturedValue)
  13157. {
  13158. if (!IsVar(capturedTypedVal.mType))
  13159. {
  13160. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, fieldInstance->mDataIdx);
  13161. mModule->mBfIRBuilder->CreateAlignedStore(capturedValue, fieldPtr, fieldInstance->mResolvedType->mAlign);
  13162. }
  13163. }
  13164. else
  13165. {
  13166. mModule->Fail(StrFormat("Unable to capture '%s'", capturedEntry.mName.c_str()), lambdaBindExpr);
  13167. mModule->AssertErrorState();
  13168. }
  13169. fieldIdx++;
  13170. }
  13171. if (lambdaInstance->mDtorFunc)
  13172. {
  13173. auto fieldPtr = mModule->mBfIRBuilder->CreateInBoundsGEP(mResult.mValue, 0, closureTypeInst->mFieldInstances[fieldIdx].mDataIdx);
  13174. auto voidType = mModule->GetPrimitiveType(BfTypeCode_None);
  13175. auto voidPtrType = mModule->CreatePointerType(voidType);
  13176. auto dtorThunk = mModule->mBfIRBuilder->CreateBitCast(lambdaInstance->mDtorFunc, mModule->mBfIRBuilder->MapType(voidPtrType));
  13177. mModule->mBfIRBuilder->CreateAlignedStore(dtorThunk, fieldPtr, mModule->mSystem->mPtrSize);
  13178. fieldIdx++;
  13179. }
  13180. }
  13181. }
  13182. void BfExprEvaluator::ProcessArrayInitializer(BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, int dimensions, SizedArrayImpl<int64>& dimLengths, int dim, bool& hasFailed)
  13183. {
  13184. bool setSize = false;
  13185. if (dim == dimLengths.size())
  13186. {
  13187. dimLengths.push_back((int)valueExprs.size());
  13188. setSize = true;
  13189. }
  13190. else if (dimLengths[dim] == -1)
  13191. {
  13192. dimLengths[dim] = (int)valueExprs.size();
  13193. setSize = true;
  13194. }
  13195. int64 initCountDiff = (int)valueExprs.size() - dimLengths[dim];
  13196. if ((dimLengths[dim] != -1) && (initCountDiff != 0) && (!hasFailed))
  13197. {
  13198. if (initCountDiff > 0)
  13199. {
  13200. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[(int)dimLengths[dim]]);
  13201. hasFailed = true;
  13202. }
  13203. else
  13204. {
  13205. // If it ends with ", ?) or ",)" then allow unsized
  13206. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  13207. (commas.size() < valueExprs.size()))
  13208. {
  13209. BfAstNode* refNode = closeToken;
  13210. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  13211. refNode = mModule->mParentNodeEntry->mNode;
  13212. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  13213. hasFailed = true;
  13214. }
  13215. }
  13216. }
  13217. for (int i = 0; i < (int)valueExprs.size(); i++)
  13218. {
  13219. BfExpression* expr = valueExprs[i];
  13220. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(expr))
  13221. {
  13222. continue;
  13223. }
  13224. auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr);
  13225. if (dim < dimensions - 1)
  13226. {
  13227. if (innerInitExpr == NULL)
  13228. {
  13229. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(expr))
  13230. {
  13231. ProcessArrayInitializer(innerTupleExpr->mOpenParen, innerTupleExpr->mValues, innerTupleExpr->mCommas, innerTupleExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  13232. }
  13233. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  13234. {
  13235. SizedArray<BfExpression*, 1> values;
  13236. values.Add(parenExpr->mExpression);
  13237. SizedArray<BfTokenNode*, 1> commas;
  13238. ProcessArrayInitializer(parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, dimensions, dimLengths, dim + 1, hasFailed);
  13239. }
  13240. else
  13241. {
  13242. hasFailed = true;
  13243. mModule->Fail("A nested array initializer is expected", expr);
  13244. continue;
  13245. }
  13246. }
  13247. else
  13248. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  13249. }
  13250. else if (innerInitExpr != NULL)
  13251. {
  13252. hasFailed = true;
  13253. mModule->Fail("Unexpected nested initializer", expr);
  13254. ProcessArrayInitializer(innerInitExpr->mOpenBrace, innerInitExpr->mValues, innerInitExpr->mCommas, innerInitExpr->mCloseBrace, dimensions, dimLengths, dim + 1, hasFailed);
  13255. }
  13256. else
  13257. {
  13258. //mModule->Fail("Expected initializer", )
  13259. }
  13260. }
  13261. }
  13262. void BfExprEvaluator::CheckObjectCreateTypeRef(BfType* expectingType, BfAstNode* afterNode)
  13263. {
  13264. auto autoComplete = GetAutoComplete();
  13265. if ((autoComplete != NULL) && (afterNode != NULL) && (autoComplete->mIsAutoComplete) &&
  13266. (afterNode->IsFromParser(mModule->mCompiler->mResolvePassData->mParsers[0])) &&
  13267. (afterNode->GetParser()->mCursorIdx == afterNode->GetSrcEnd() + 1))
  13268. {
  13269. BfType* expectingType = mExpectingType;
  13270. BfTypeInstance* expectingTypeInst = NULL;
  13271. if (mExpectingType != NULL)
  13272. {
  13273. expectingTypeInst = mExpectingType->ToTypeInstance();
  13274. }
  13275. if ((mExpectingType != NULL) && (((expectingTypeInst == NULL) || (!expectingTypeInst->mTypeDef->mIsDelegate))))
  13276. {
  13277. // Why were we doing this? It floods the autocomplete with every possible type
  13278. //autoComplete->AddTopLevelTypes(NULL);
  13279. autoComplete->mInsertStartIdx = afterNode->GetSourceData()->ToParser()->mCursorIdx;
  13280. BF_ASSERT(autoComplete->mInsertStartIdx != -1);
  13281. auto expectingType = mExpectingType;
  13282. while (expectingType->IsArray())
  13283. {
  13284. auto arrayType = (BfArrayType*)expectingType;
  13285. expectingType = arrayType->mGenericTypeInfo->mTypeGenericArguments[0];
  13286. }
  13287. auto expectingTypeInst = expectingType->ToTypeInstance();
  13288. if (expectingTypeInst != NULL)
  13289. {
  13290. autoComplete->AddTypeInstanceEntry(expectingTypeInst);
  13291. }
  13292. else
  13293. autoComplete->mDefaultSelection = mModule->TypeToString(expectingType);
  13294. }
  13295. }
  13296. }
  13297. void BfExprEvaluator::Visit(BfObjectCreateExpression* objCreateExpr)
  13298. {
  13299. CreateObject(objCreateExpr, objCreateExpr->mNewNode, NULL);
  13300. }
  13301. void BfExprEvaluator::CreateObject(BfObjectCreateExpression* objCreateExpr, BfAstNode* allocNode, BfType* wantAllocType)
  13302. {
  13303. auto autoComplete = GetAutoComplete();
  13304. if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mTypeRef != NULL))
  13305. {
  13306. autoComplete->CheckTypeRef(objCreateExpr->mTypeRef, false, true);
  13307. }
  13308. if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mOpenToken != NULL) && (objCreateExpr->mCloseToken != NULL) &&
  13309. (objCreateExpr->mOpenToken->mToken == BfToken_LBrace) && (autoComplete->CheckFixit(objCreateExpr->mOpenToken)))
  13310. {
  13311. auto refNode = objCreateExpr->mOpenToken;
  13312. BfParserData* parser = refNode->GetSourceData()->ToParserData();
  13313. if (parser != NULL)
  13314. {
  13315. autoComplete->AddEntry(AutoCompleteEntry("fixit", StrFormat("Change initializer braces to parentheses\treformat|%s|%d-1|(\x01|%s|%d-1|)",
  13316. parser->mFileName.c_str(), refNode->mSrcStart,
  13317. parser->mFileName.c_str(), objCreateExpr->mCloseToken->mSrcStart).c_str()));
  13318. }
  13319. }
  13320. CheckObjectCreateTypeRef(mExpectingType, allocNode);
  13321. BfAttributeState attributeState;
  13322. attributeState.mTarget = BfAttributeTargets_Alloc;
  13323. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  13324. BfTokenNode* newToken = NULL;
  13325. BfAllocTarget allocTarget;
  13326. ResolveAllocTarget(allocTarget, allocNode, newToken, &attributeState.mCustomAttributes);
  13327. bool isScopeAlloc = newToken->GetToken() == BfToken_Scope;
  13328. bool isAppendAlloc = newToken->GetToken() == BfToken_Append;
  13329. bool isStackAlloc = (newToken->GetToken() == BfToken_Stack) || (isScopeAlloc);
  13330. bool isArrayAlloc = false;// (objCreateExpr->mArraySizeSpecifier != NULL);
  13331. bool isRawArrayAlloc = (objCreateExpr != NULL) && (objCreateExpr->mStarToken != NULL);
  13332. if (isScopeAlloc)
  13333. {
  13334. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  13335. {
  13336. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", allocNode);
  13337. }
  13338. if (allocNode == newToken) // Scope, no target specified
  13339. {
  13340. if (mModule->mParentNodeEntry != NULL)
  13341. {
  13342. if (auto assignExpr = BfNodeDynCastExact<BfAssignmentExpression>(mModule->mParentNodeEntry->mNode))
  13343. {
  13344. if (mModule->mCurMethodState->mCurScope->mCloseNode == NULL)
  13345. {
  13346. // 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
  13347. if ((mBfEvalExprFlags & BfEvalExprFlags_PendingPropSet) == 0)
  13348. mModule->Warn(0, "This allocation will immediately go out of scope. Consider specifying a wider scope target such as 'scope::'", allocNode);
  13349. }
  13350. }
  13351. }
  13352. }
  13353. }
  13354. BfAutoParentNodeEntry autoParentNodeEntry(mModule, objCreateExpr);
  13355. SizedArray<BfAstNode*, 2> dimLengthRefs;
  13356. SizedArray<BfIRValue, 2> dimLengthVals;
  13357. BfArrayType* arrayType = NULL;
  13358. BfType* unresolvedTypeRef = NULL;
  13359. BfType* resolvedTypeRef = NULL;
  13360. if (wantAllocType != NULL)
  13361. {
  13362. unresolvedTypeRef = wantAllocType;
  13363. resolvedTypeRef = wantAllocType;
  13364. }
  13365. else if (objCreateExpr->mTypeRef == NULL)
  13366. {
  13367. if ((!mExpectingType) || (!mExpectingType->IsArray()))
  13368. {
  13369. mModule->Fail("Cannot imply array type. Explicitly state array type or use array in an assignment to an array type.", objCreateExpr);
  13370. resolvedTypeRef = mModule->mContext->mBfObjectType;
  13371. unresolvedTypeRef = resolvedTypeRef;
  13372. }
  13373. else
  13374. {
  13375. auto arrayType = (BfArrayType*)mExpectingType;
  13376. unresolvedTypeRef = arrayType->GetUnderlyingType();
  13377. resolvedTypeRef = unresolvedTypeRef;
  13378. }
  13379. }
  13380. else
  13381. {
  13382. if ((objCreateExpr->mTypeRef->IsExact<BfDotTypeReference>()) && (mExpectingType != NULL))
  13383. {
  13384. //mModule->SetElementType(objCreateExpr->mTypeRef, BfSourceElementType_TypeRef);
  13385. if ((mExpectingType->IsObject()) || (mExpectingType->IsGenericParam()))
  13386. {
  13387. unresolvedTypeRef = mExpectingType;
  13388. if (unresolvedTypeRef->IsArray())
  13389. {
  13390. arrayType = (BfArrayType*)unresolvedTypeRef;
  13391. unresolvedTypeRef = unresolvedTypeRef->GetUnderlyingType();
  13392. isArrayAlloc = true;
  13393. }
  13394. }
  13395. else if (mExpectingType->IsPointer())
  13396. {
  13397. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  13398. }
  13399. else if (mExpectingType->IsVar())
  13400. unresolvedTypeRef = mExpectingType;
  13401. }
  13402. if (unresolvedTypeRef == NULL)
  13403. {
  13404. if (auto arrayTypeRef = BfNodeDynCast<BfArrayTypeRef>(objCreateExpr->mTypeRef))
  13405. {
  13406. isArrayAlloc = true;
  13407. if (auto dotTypeRef = BfNodeDynCast<BfDotTypeReference>(arrayTypeRef->mElementType))
  13408. {
  13409. if ((mExpectingType != NULL) &&
  13410. ((mExpectingType->IsArray()) || (mExpectingType->IsPointer()) || (mExpectingType->IsSizedArray())))
  13411. unresolvedTypeRef = mExpectingType->GetUnderlyingType();
  13412. }
  13413. if (unresolvedTypeRef == NULL)
  13414. unresolvedTypeRef = mModule->ResolveTypeRef(arrayTypeRef->mElementType);
  13415. if (unresolvedTypeRef == NULL)
  13416. unresolvedTypeRef = mModule->mContext->mBfObjectType;
  13417. int dimensions = 1;
  13418. bool commaExpected = false;
  13419. if (arrayTypeRef->mParams.size() != 0)
  13420. {
  13421. auto intType = mModule->ResolveTypeDef(mModule->mSystem->mTypeIntPtr);
  13422. for (auto arg : arrayTypeRef->mParams)
  13423. {
  13424. if (auto tokenNode = BfNodeDynCastExact<BfTokenNode>(arg))
  13425. {
  13426. if (tokenNode->GetToken() == BfToken_Comma)
  13427. {
  13428. if (isRawArrayAlloc)
  13429. {
  13430. mModule->Fail("Sized arrays cannot be multidimensional.", tokenNode);
  13431. continue;
  13432. }
  13433. dimensions++;
  13434. if (dimensions == 5)
  13435. {
  13436. mModule->Fail("Too many array dimensions, consider using a jagged array.", tokenNode);
  13437. }
  13438. commaExpected = false;
  13439. continue;
  13440. }
  13441. }
  13442. auto expr = BfNodeDynCast<BfExpression>(arg);
  13443. if ((isRawArrayAlloc) && (!dimLengthVals.IsEmpty()))
  13444. {
  13445. mModule->CreateValueFromExpression(expr, intType);
  13446. continue;
  13447. }
  13448. dimLengthRefs.Add(expr);
  13449. BfTypedValue dimLength;
  13450. if (expr == NULL)
  13451. {
  13452. // Not specified
  13453. dimLengthVals.push_back(BfIRValue());
  13454. continue;
  13455. }
  13456. if (arg != NULL)
  13457. {
  13458. dimLength = mModule->CreateValueFromExpression(expr, intType, BfEvalExprFlags_NoCast);
  13459. BfCastFlags castFlags = BfCastFlags_None;
  13460. if ((dimLength) && (dimLength.mType->IsInteger()))
  13461. {
  13462. // Allow uint for size - just force to int
  13463. if (!((BfPrimitiveType*)dimLength.mType)->IsSigned())
  13464. castFlags = BfCastFlags_Explicit;
  13465. }
  13466. if (dimLength)
  13467. dimLength = mModule->Cast(expr, dimLength, intType, castFlags);
  13468. }
  13469. if (commaExpected)
  13470. {
  13471. mModule->AssertErrorState();
  13472. continue;
  13473. }
  13474. if (!dimLength)
  13475. {
  13476. dimLength = mModule->GetDefaultTypedValue(intType);
  13477. }
  13478. dimLengthVals.push_back(dimLength.mValue);
  13479. commaExpected = true;
  13480. }
  13481. }
  13482. if ((arrayTypeRef->mParams.size() == 0) && (objCreateExpr->mOpenToken == NULL))
  13483. mModule->Fail("Array size or array initializer expected", arrayTypeRef->mOpenBracket);
  13484. if (dimensions > 4)
  13485. dimensions = 4;
  13486. if (!isRawArrayAlloc)
  13487. arrayType = mModule->CreateArrayType(unresolvedTypeRef, dimensions);
  13488. }
  13489. if (unresolvedTypeRef == NULL)
  13490. {
  13491. unresolvedTypeRef = ResolveTypeRef(objCreateExpr->mTypeRef, BfPopulateType_Declaration, BfResolveTypeRefFlag_NoResolveGenericParam);
  13492. }
  13493. }
  13494. resolvedTypeRef = unresolvedTypeRef;
  13495. if ((resolvedTypeRef != NULL) && (IsVar(resolvedTypeRef)))
  13496. resolvedTypeRef = unresolvedTypeRef;
  13497. }
  13498. if (resolvedTypeRef == NULL)
  13499. {
  13500. unresolvedTypeRef = mModule->GetPrimitiveType(BfTypeCode_Var);
  13501. resolvedTypeRef = unresolvedTypeRef;
  13502. }
  13503. auto resultType = resolvedTypeRef;
  13504. if ((resolvedTypeRef->IsInterface()) && (!isArrayAlloc))
  13505. {
  13506. mModule->Fail("Cannot create an instance of an interface", objCreateExpr->mTypeRef);
  13507. resolvedTypeRef = mModule->mContext->mBfObjectType;
  13508. }
  13509. BfTypeInstance* typeInstance = resolvedTypeRef->ToTypeInstance();
  13510. int elementSize = resolvedTypeRef->mSize;
  13511. int elementAlign = resolvedTypeRef->mAlign;
  13512. BfIRType allocType = mModule->mBfIRBuilder->MapType(resolvedTypeRef);
  13513. if (typeInstance != NULL)
  13514. {
  13515. if (!mModule->mCurTypeInstance->mResolvingVarField)
  13516. mModule->PopulateType(typeInstance);
  13517. if ((typeInstance->mTypeDef->mIsDelegate) && (!isArrayAlloc))
  13518. mModule->Fail("Delegates must be constructed through delegate binding", objCreateExpr->mTypeRef);
  13519. elementSize = BF_MAX(0, typeInstance->mInstSize);
  13520. elementAlign = typeInstance->mInstAlign;
  13521. allocType = mModule->mBfIRBuilder->MapTypeInst(typeInstance);
  13522. }
  13523. if (isAppendAlloc)
  13524. {
  13525. if (!mModule->mCurTypeInstance->IsObject())
  13526. {
  13527. mModule->Fail("Append allocations are only allowed in classes", allocNode);
  13528. isAppendAlloc = false;
  13529. }
  13530. else if ((mBfEvalExprFlags & BfEvalExprFlags_VariableDeclaration) == 0)
  13531. {
  13532. mModule->Fail("Append allocations are only allowed as local variable initializers in constructor body", allocNode);
  13533. isAppendAlloc = false;
  13534. }
  13535. else
  13536. {
  13537. auto methodDef = mModule->mCurMethodInstance->mMethodDef;
  13538. if (methodDef->mMethodType == BfMethodType_CtorCalcAppend)
  13539. {
  13540. mModule->Fail("Append allocations are only allowed as local variable declarations in the main method body", allocNode);
  13541. isAppendAlloc = false;
  13542. }
  13543. else if (!methodDef->mHasAppend)
  13544. {
  13545. mModule->Fail("Append allocations can only be used on constructors with [AllowAppend] specified", allocNode);
  13546. isAppendAlloc = false;
  13547. }
  13548. else if (methodDef->mMethodType != BfMethodType_Ctor)
  13549. {
  13550. mModule->Fail("Append allocations are only allowed in constructors", allocNode);
  13551. isAppendAlloc = false;
  13552. }
  13553. else if (methodDef->mIsStatic)
  13554. {
  13555. mModule->Fail("Append allocations are only allowed in non-static constructors", allocNode);
  13556. isAppendAlloc = false;
  13557. }
  13558. }
  13559. }
  13560. if (isArrayAlloc)
  13561. {
  13562. const int MAX_DIMENSIONS = 2;
  13563. int dimensions = 1;
  13564. if (arrayType != NULL)
  13565. {
  13566. dimensions = arrayType->mDimensions;
  13567. mModule->AddDependency(arrayType, mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_Calls);
  13568. }
  13569. bool zeroMemory = true;
  13570. if (objCreateExpr->mOpenToken != NULL)
  13571. {
  13572. if ((objCreateExpr->mArguments.size() == 1) &&
  13573. (BfNodeDynCastExact<BfUninitializedExpression>(objCreateExpr->mArguments[0]) != NULL))
  13574. {
  13575. // Special case for a single "{ ? }"
  13576. zeroMemory = false;
  13577. }
  13578. else
  13579. {
  13580. SizedArray<int64, 2> dimLengths;
  13581. if (dimLengthVals.size() != 0)
  13582. {
  13583. for (int dim = 0; dim < dimensions; dim++)
  13584. {
  13585. BfIRValue dimLengthVal;
  13586. if (dim < (int)dimLengthVals.size())
  13587. dimLengthVal = dimLengthVals[dim];
  13588. if (!dimLengthVal)
  13589. {
  13590. dimLengths.push_back(-1);
  13591. continue;
  13592. }
  13593. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVal);
  13594. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  13595. {
  13596. int64 dimLength = constant->mInt64;
  13597. if (dimLength < 0)
  13598. {
  13599. mModule->Fail(StrFormat("Invalid array dimension '%lld'", dimLength), dimLengthRefs[dim]);
  13600. dimLength = -1;
  13601. }
  13602. dimLengths.push_back(dimLength);
  13603. }
  13604. else if ((constant != NULL) && (constant->mConstType == BfConstType_Undef))
  13605. {
  13606. dimLengths.push_back(-1);
  13607. }
  13608. else
  13609. {
  13610. mModule->Fail("A constant length is required when using an initializer", dimLengthRefs[dim]);
  13611. dimLengths.push_back(-1);
  13612. }
  13613. }
  13614. }
  13615. // Ending in an ", )" means we need to zero-fill ending
  13616. zeroMemory = objCreateExpr->mCommas.size() >= objCreateExpr->mArguments.size();
  13617. bool hasFailed = false;
  13618. ProcessArrayInitializer(objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, dimensions, dimLengths, 0, hasFailed);
  13619. dimLengthVals.resize(dimLengths.size());
  13620. for (int i = 0; i < (int)dimLengthVals.size(); i++)
  13621. {
  13622. if (!dimLengthVals[i])
  13623. {
  13624. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  13625. dimLengthVals[i] = mModule->GetConstValue(dimLengths[i], intType);
  13626. }
  13627. }
  13628. }
  13629. }
  13630. while ((int)dimLengthVals.size() < dimensions)
  13631. dimLengthVals.push_back(mModule->GetConstValue(0));
  13632. BfTypedValue arrayValue;
  13633. BfIRValue arraySize;
  13634. for (BfIRValue dimSize : dimLengthVals)
  13635. {
  13636. if (!arraySize)
  13637. arraySize = dimSize;
  13638. else
  13639. arraySize = mModule->mBfIRBuilder->CreateMul(arraySize, dimSize);
  13640. }
  13641. BfAllocFlags allocFlags = BfAllocFlags_None;
  13642. if (isRawArrayAlloc)
  13643. allocFlags = (BfAllocFlags)(allocFlags | BfAllocFlags_RawArray);
  13644. int writeIdx = 0;
  13645. struct BfInitContext
  13646. {
  13647. public:
  13648. BfModule* mModule;
  13649. BfType* resultType;
  13650. int dimensions;
  13651. SizedArray<BfIRValue, 2>& dimLengthVals;
  13652. BfIRValue arraySize;
  13653. int& writeIdx;
  13654. BfInitContext(BfModule* module, BfType* resultType, int dimensions, SizedArray<BfIRValue, 2>& dimLengthVals, BfIRValue arraySize, int& writeIdx) :
  13655. mModule(module), resultType(resultType), dimensions(dimensions), dimLengthVals(dimLengthVals), arraySize(arraySize), writeIdx(writeIdx)
  13656. {
  13657. }
  13658. void Handle(BfIRValue addr, int curDim, const BfSizedArray<BfExpression*>& valueExprs)
  13659. {
  13660. int exprIdx = 0;
  13661. int dimWriteIdx = 0;
  13662. bool isUninit = false;
  13663. int dimLength = -1;
  13664. if (dimLengthVals[curDim].IsConst())
  13665. {
  13666. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[curDim]);
  13667. dimLength = constant->mInt32;
  13668. }
  13669. while (exprIdx < (int)valueExprs.size())
  13670. {
  13671. auto initExpr = valueExprs[exprIdx];
  13672. exprIdx++;
  13673. if (!initExpr)
  13674. break;
  13675. if (auto unintExpr = BfNodeDynCastExact<BfUninitializedExpression>(initExpr))
  13676. {
  13677. isUninit = true;
  13678. break;
  13679. }
  13680. if (exprIdx > dimLength)
  13681. break;
  13682. if (curDim < dimensions - 1)
  13683. {
  13684. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(initExpr))
  13685. {
  13686. Handle(addr, curDim + 1, innerTupleExpr->mValues);
  13687. }
  13688. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(initExpr))
  13689. {
  13690. SizedArray<BfExpression*, 1> values;
  13691. values.Add(parenExpr->mExpression);
  13692. Handle(addr, curDim + 1, values);
  13693. }
  13694. else if (auto innerInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(initExpr))
  13695. {
  13696. Handle(addr, curDim + 1, innerInitExpr->mValues);
  13697. }
  13698. dimWriteIdx++;
  13699. continue;
  13700. }
  13701. BfIRValue elemAddr;
  13702. if (!resultType->IsValuelessType())
  13703. elemAddr = mModule->CreateIndexedValue(resultType, addr, writeIdx);
  13704. else
  13705. elemAddr = mModule->mBfIRBuilder->GetFakeVal();
  13706. writeIdx++;
  13707. dimWriteIdx++;
  13708. BfTypedValue elemPtrTypedVal = BfTypedValue(elemAddr, resultType, BfTypedValueKind_Addr);
  13709. BfExprEvaluator exprEvaluator(mModule);
  13710. exprEvaluator.mExpectingType = resultType;
  13711. exprEvaluator.mReceivingValue = &elemPtrTypedVal;
  13712. exprEvaluator.Evaluate(initExpr);
  13713. exprEvaluator.GetResult();
  13714. if (exprEvaluator.mReceivingValue == NULL)
  13715. {
  13716. // We wrote directly to the array in-place, we're done with this element
  13717. continue;
  13718. }
  13719. auto storeValue = exprEvaluator.mResult;
  13720. if (!storeValue)
  13721. continue;
  13722. storeValue = mModule->Cast(initExpr, storeValue, resultType);
  13723. if (!storeValue)
  13724. continue;
  13725. if (!resultType->IsValuelessType())
  13726. {
  13727. storeValue = mModule->LoadOrAggregateValue(storeValue);
  13728. mModule->mBfIRBuilder->CreateStore(storeValue.mValue, elemAddr);
  13729. }
  13730. }
  13731. int clearFromIdx = writeIdx;
  13732. int sectionElemCount = 1;
  13733. BfIRValue numElemsLeft = arraySize;
  13734. if (dimLength != -1)
  13735. {
  13736. int clearCount = dimLength - dimWriteIdx;
  13737. if (clearCount > 0)
  13738. {
  13739. for (int checkDim = curDim + 1; checkDim < (int)dimLengthVals.size(); checkDim++)
  13740. {
  13741. if (dimLengthVals[checkDim].IsConst())
  13742. {
  13743. auto constant = mModule->mBfIRBuilder->GetConstant(dimLengthVals[checkDim]);
  13744. clearCount *= constant->mInt32;
  13745. sectionElemCount *= constant->mInt32;
  13746. }
  13747. }
  13748. }
  13749. writeIdx += clearCount;
  13750. numElemsLeft = mModule->GetConstValue(clearCount);
  13751. }
  13752. // Actually leave it alone?
  13753. if ((isUninit) &&
  13754. ((mModule->IsOptimized()) || (mModule->mIsComptimeModule) || (mModule->mBfIRBuilder->mIgnoreWrites)))
  13755. return;
  13756. bool doClear = true;
  13757. if (numElemsLeft.IsConst())
  13758. {
  13759. auto constant = mModule->mBfIRBuilder->GetConstant(numElemsLeft);
  13760. doClear = constant->mInt64 > 0;
  13761. }
  13762. if (doClear)
  13763. {
  13764. // We multiply by GetStride. This relies on the fact that we over-allocate on the array allocation -- the last
  13765. // element doesn't need to be padded out to the element alignment, but we do anyway. Otherwise this would be
  13766. // a more complicated computation
  13767. auto clearBytes = mModule->mBfIRBuilder->CreateMul(numElemsLeft, mModule->GetConstValue(resultType->GetStride()));
  13768. if (isUninit)
  13769. {
  13770. // Limit to a reasonable number of bytes to stomp with 0xCC
  13771. int maxStompBytes = BF_MIN(128, resultType->GetStride() * sectionElemCount);
  13772. if (clearBytes.IsConst())
  13773. {
  13774. auto constant = mModule->mBfIRBuilder->GetConstant(clearBytes);
  13775. if (constant->mInt64 > maxStompBytes)
  13776. clearBytes = mModule->GetConstValue(maxStompBytes);
  13777. }
  13778. else
  13779. {
  13780. auto insertBlock = mModule->mBfIRBuilder->GetInsertBlock();
  13781. auto gtBlock = mModule->mBfIRBuilder->CreateBlock("unint.gt");
  13782. auto contBlock = mModule->mBfIRBuilder->CreateBlock("unint.cont");
  13783. auto cmp = mModule->mBfIRBuilder->CreateCmpLTE(clearBytes, mModule->GetConstValue(maxStompBytes), true);
  13784. mModule->mBfIRBuilder->CreateCondBr(cmp, contBlock, gtBlock);
  13785. mModule->mBfIRBuilder->AddBlock(gtBlock);
  13786. mModule->mBfIRBuilder->SetInsertPoint(gtBlock);
  13787. mModule->mBfIRBuilder->CreateBr(contBlock);
  13788. mModule->mBfIRBuilder->AddBlock(contBlock);
  13789. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  13790. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_IntPtr)), 2);
  13791. mModule->mBfIRBuilder->AddPhiIncoming(phi, clearBytes, insertBlock);
  13792. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(maxStompBytes), gtBlock);
  13793. clearBytes = phi;
  13794. }
  13795. }
  13796. mModule->mBfIRBuilder->PopulateType(resultType);
  13797. if (!resultType->IsValuelessType())
  13798. {
  13799. mModule->mBfIRBuilder->CreateMemSet(mModule->CreateIndexedValue(resultType, addr, clearFromIdx),
  13800. mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, isUninit ? 0xCC : 0), clearBytes, resultType->mAlign);
  13801. }
  13802. }
  13803. }
  13804. };
  13805. BfInitContext initContext(mModule, resultType, dimensions, dimLengthVals, arraySize, writeIdx);
  13806. if (IsVar(resultType))
  13807. {
  13808. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  13809. mResult = BfTypedValue(BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), mModule->GetPrimitiveType(BfTypeCode_Var)));
  13810. initContext.Handle(mResult.mValue, 0, objCreateExpr->mArguments);
  13811. return;
  13812. }
  13813. if (isRawArrayAlloc)
  13814. {
  13815. // 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
  13816. BfType* ptrType = mModule->CreatePointerType(resultType);
  13817. if (isAppendAlloc)
  13818. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, false), ptrType);
  13819. else
  13820. {
  13821. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), ptrType);
  13822. }
  13823. initContext.Handle(arrayValue.mValue, 0, objCreateExpr->mArguments);
  13824. mResult = arrayValue;
  13825. return;
  13826. }
  13827. if (dimLengthVals.size() > 4)
  13828. {
  13829. dimLengthVals.RemoveRange(4, dimLengthVals.size() - 4);
  13830. mModule->Fail("Too many array dimensions, consider using a jagged array.", objCreateExpr);
  13831. }
  13832. if (arrayType == NULL)
  13833. return;
  13834. if (isAppendAlloc)
  13835. arrayValue = BfTypedValue(mModule->AppendAllocFromType(resultType, BfIRValue(), 0, arraySize, (int)dimLengthVals.size(), isRawArrayAlloc, zeroMemory), arrayType);
  13836. else
  13837. {
  13838. arrayValue = BfTypedValue(mModule->AllocFromType(resultType, allocTarget, BfIRValue(), arraySize, (int)dimLengthVals.size(), allocFlags, allocTarget.mAlignOverride), arrayType);
  13839. if (isScopeAlloc)
  13840. {
  13841. // See notes below on "general" SkipObjectAccessCheck usage on why we can do this
  13842. mModule->SkipObjectAccessCheck(arrayValue);
  13843. }
  13844. }
  13845. //mModule->InitTypeInst(arrayValue, scopeData);
  13846. BfAstNode* refNode = objCreateExpr->mTypeRef;
  13847. while (true)
  13848. {
  13849. if (auto arrayRef = BfNodeDynCast<BfElementedTypeRef>(refNode))
  13850. {
  13851. refNode = arrayRef->mElementType;
  13852. continue;
  13853. }
  13854. break;
  13855. }
  13856. BfResolvedArgs resolvedArgs;
  13857. auto rawAutoComplete = mModule->mCompiler->GetAutoComplete();
  13858. if (rawAutoComplete != NULL)
  13859. {
  13860. SetAndRestoreValue<bool> prevCapturing(rawAutoComplete->mIsCapturingMethodMatchInfo, false);
  13861. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, false);
  13862. }
  13863. else
  13864. {
  13865. MatchConstructor(refNode, objCreateExpr, arrayValue, arrayType, resolvedArgs, false, false);
  13866. }
  13867. //TODO: Assert 'length' var is at slot 1
  13868. mModule->PopulateType(arrayType->mBaseType, BfPopulateType_DataAndMethods);
  13869. mModule->mBfIRBuilder->PopulateType(arrayType);
  13870. auto arrayBits = mModule->mBfIRBuilder->CreateBitCast(arrayValue.mValue, mModule->mBfIRBuilder->MapTypeInstPtr(arrayType->mBaseType));
  13871. int arrayLengthBitCount = arrayType->GetLengthBitCount();
  13872. if (arrayLengthBitCount == 0)
  13873. {
  13874. mModule->Fail("INTERNAL ERROR: Unable to find array 'length' field", objCreateExpr);
  13875. return;
  13876. }
  13877. mResult = arrayValue;
  13878. auto lengthFieldInstance = mModule->GetFieldByName(arrayType->mBaseType->ToTypeInstance(), "mLength");
  13879. if (lengthFieldInstance == NULL)
  13880. return;
  13881. auto firstElementFieldInstance = mModule->GetFieldByName(arrayType->ToTypeInstance(), "mFirstElement");
  13882. if (firstElementFieldInstance == NULL)
  13883. return;
  13884. auto addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayBits, 0, lengthFieldInstance->mDataIdx);
  13885. if (arrayLengthBitCount == 64)
  13886. mModule->mBfIRBuilder->CreateAlignedStore(arraySize, addr, 8);
  13887. else
  13888. {
  13889. auto arraySize32 = mModule->mBfIRBuilder->CreateNumericCast(arraySize, true, BfTypeCode_Int32);
  13890. mModule->mBfIRBuilder->CreateAlignedStore(arraySize32, addr, 4);
  13891. }
  13892. for (int lowerDim = 1; lowerDim < (int)dimLengthVals.size(); lowerDim++)
  13893. {
  13894. auto length1FieldInstance = mModule->GetFieldByName(arrayType->ToTypeInstance(), "mLength1");
  13895. if (length1FieldInstance == NULL)
  13896. return;
  13897. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, length1FieldInstance->mDataIdx + lowerDim - 1);
  13898. auto lowerDimVal = mModule->mBfIRBuilder->CreateNumericCast(dimLengthVals[lowerDim], true, (arrayLengthBitCount == 64) ? BfTypeCode_Int64 : BfTypeCode_Int32);
  13899. mModule->mBfIRBuilder->CreateStore(lowerDimVal, addr);
  13900. }
  13901. if (resultType->IsValuelessType())
  13902. addr = mModule->mBfIRBuilder->GetFakeVal();
  13903. else
  13904. addr = mModule->mBfIRBuilder->CreateInBoundsGEP(arrayValue.mValue, 0, firstElementFieldInstance->mDataIdx);
  13905. initContext.Handle(addr, 0, objCreateExpr->mArguments);
  13906. return;
  13907. }
  13908. else
  13909. {
  13910. if (resolvedTypeRef->IsVar())
  13911. {
  13912. // Leave as a var
  13913. }
  13914. else if ((!resolvedTypeRef->IsObjectOrInterface()) && (!resolvedTypeRef->IsGenericParam()))
  13915. {
  13916. resultType = mModule->CreatePointerType(resolvedTypeRef);
  13917. }
  13918. }
  13919. if ((isStackAlloc) && (mModule->mCurMethodState == NULL))
  13920. {
  13921. mModule->Fail("Cannot use 'stack' here", allocNode);
  13922. isStackAlloc = false;
  13923. isScopeAlloc = false;
  13924. }
  13925. bool isGenericParam = unresolvedTypeRef->IsGenericParam();
  13926. if (resolvedTypeRef->IsGenericParam())
  13927. {
  13928. BfGenericParamFlags genericParamFlags = BfGenericParamFlag_None;
  13929. BfType* typeConstraint = NULL;
  13930. auto genericParam = mModule->GetMergedGenericParamData((BfGenericParamType*)resolvedTypeRef, genericParamFlags, typeConstraint);
  13931. if (typeConstraint == NULL)
  13932. {
  13933. if ((genericParamFlags & BfGenericParamFlag_Var) != 0)
  13934. {
  13935. // Allow it
  13936. }
  13937. else
  13938. {
  13939. if ((genericParamFlags & BfGenericParamFlag_New) == 0)
  13940. {
  13941. mModule->Fail(StrFormat("Must add 'where %s : new' constraint to generic parameter to instantiate type", genericParam->GetName().c_str()), objCreateExpr->mTypeRef);
  13942. }
  13943. if (objCreateExpr->mArguments.size() != 0)
  13944. {
  13945. mModule->Fail(StrFormat("Only default parameterless constructors can be called on generic argument '%s'", genericParam->GetName().c_str()), objCreateExpr->mTypeRef);
  13946. }
  13947. }
  13948. }
  13949. if (((typeConstraint != NULL) && (typeConstraint->IsValueType())) ||
  13950. ((genericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr)) != 0))
  13951. {
  13952. resultType = mModule->CreatePointerType(resolvedTypeRef);
  13953. }
  13954. else if (((typeConstraint != NULL) && (!typeConstraint->IsValueType())) ||
  13955. ((genericParamFlags & (BfGenericParamFlag_Class)) != 0))
  13956. {
  13957. // Leave as 'T'
  13958. resultType = resolvedTypeRef;
  13959. }
  13960. else
  13961. resultType = mModule->CreateModifiedTypeType(resolvedTypeRef, BfToken_AllocType);
  13962. mResult.mType = resultType;
  13963. if (typeInstance == NULL)
  13964. {
  13965. mResult = mModule->GetDefaultTypedValue(resultType);
  13966. return;
  13967. }
  13968. }
  13969. else if (resolvedTypeRef->IsSizedArray())
  13970. {
  13971. // Handle the case of "int[3]* val = new .(1, 2, 3)"
  13972. if (auto dotTypeRef = BfNodeDynCastExact<BfDotTypeReference>(objCreateExpr->mTypeRef))
  13973. {
  13974. BfIRValue allocValue;
  13975. if (isAppendAlloc)
  13976. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, BfIRValue(), 0, BfIRValue(), 0, false, false);
  13977. else
  13978. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, BfIRValue(), BfIRValue(), 0, BfAllocFlags_None);
  13979. auto result = BfTypedValue(allocValue, resolvedTypeRef, BfTypedValueKind_Addr);
  13980. InitializedSizedArray((BfSizedArrayType*)resolvedTypeRef, objCreateExpr->mOpenToken, objCreateExpr->mArguments, objCreateExpr->mCommas, objCreateExpr->mCloseToken, &result);
  13981. // Turn from an addr of a sized array to pointer of sized array
  13982. mResult = BfTypedValue(mResult.mValue, resultType);
  13983. return;
  13984. }
  13985. }
  13986. SetAndRestoreValue<bool> prevNoBind(mNoBind, mNoBind || isGenericParam);
  13987. if ((typeInstance != NULL) && (typeInstance->mTypeDef->mIsAbstract))
  13988. {
  13989. mModule->Fail("Cannot create an instance of an abstract class", objCreateExpr->mTypeRef);
  13990. return;
  13991. }
  13992. BfFunctionBindResult bindResult;
  13993. bindResult.mSkipThis = true;
  13994. bindResult.mWantsArgs = true;
  13995. SetAndRestoreValue<BfFunctionBindResult*> prevBindResult(mFunctionBindResult, &bindResult);
  13996. BfIRValue appendSizeValue;
  13997. BfTypedValue emtpyThis(mModule->mBfIRBuilder->GetFakeVal(), resolvedTypeRef, resolvedTypeRef->IsStruct());
  13998. BfResolvedArgs argValues;
  13999. if (objCreateExpr != NULL)
  14000. {
  14001. argValues.Init(objCreateExpr->mOpenToken, &objCreateExpr->mArguments, &objCreateExpr->mCommas, objCreateExpr->mCloseToken);
  14002. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval); ////
  14003. }
  14004. if (typeInstance == NULL)
  14005. {
  14006. // No CTOR needed
  14007. if (objCreateExpr->mArguments.size() != 0)
  14008. {
  14009. mModule->Fail(StrFormat("Only default parameterless constructors can be called on primitive type '%s'", mModule->TypeToString(resolvedTypeRef).c_str()), objCreateExpr->mTypeRef);
  14010. }
  14011. }
  14012. else if ((autoComplete != NULL) && (objCreateExpr != NULL) && (objCreateExpr->mOpenToken != NULL))
  14013. {
  14014. auto wasCapturingMethodInfo = autoComplete->mIsCapturingMethodMatchInfo;
  14015. autoComplete->CheckInvocation(objCreateExpr, objCreateExpr->mOpenToken, objCreateExpr->mCloseToken, objCreateExpr->mCommas);
  14016. MatchConstructor(objCreateExpr->mTypeRef, objCreateExpr, emtpyThis, typeInstance, argValues, false, true);
  14017. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  14018. {
  14019. if (autoComplete->mMethodMatchInfo != NULL)
  14020. autoComplete->mIsCapturingMethodMatchInfo = true;
  14021. }
  14022. else
  14023. autoComplete->mIsCapturingMethodMatchInfo = false;
  14024. }
  14025. else if (!resolvedTypeRef->IsFunction())
  14026. {
  14027. auto refNode = allocNode;
  14028. if (objCreateExpr != NULL)
  14029. refNode = objCreateExpr->mTypeRef;
  14030. MatchConstructor(refNode, objCreateExpr, emtpyThis, typeInstance, argValues, false, true);
  14031. }
  14032. if (objCreateExpr != NULL)
  14033. mModule->ValidateAllocation(typeInstance, objCreateExpr->mTypeRef);
  14034. prevBindResult.Restore();
  14035. int allocAlign = resolvedTypeRef->mAlign;
  14036. if (typeInstance != NULL)
  14037. allocAlign = typeInstance->mInstAlign;
  14038. int appendAllocAlign = 0;
  14039. if ((bindResult.mMethodInstance != NULL) && (bindResult.mMethodInstance->mMethodDef->mHasAppend))
  14040. {
  14041. if (!bindResult.mFunc)
  14042. {
  14043. BF_ASSERT((!mModule->HasExecutedOutput()) || (mModule->mBfIRBuilder->mIgnoreWrites));
  14044. appendSizeValue = mModule->GetConstValue(0);
  14045. }
  14046. else
  14047. {
  14048. auto calcAppendMethodModule = mModule->GetMethodInstanceAtIdx(bindResult.mMethodInstance->GetOwner(), bindResult.mMethodInstance->mMethodDef->mIdx + 1, BF_METHODNAME_CALCAPPEND);
  14049. SizedArray<BfIRValue, 2> irArgs;
  14050. if (bindResult.mIRArgs.size() > 1)
  14051. irArgs.Insert(0, &bindResult.mIRArgs[1], bindResult.mIRArgs.size() - 1);
  14052. BfTypedValue appendSizeTypedValue = mModule->TryConstCalcAppend(calcAppendMethodModule.mMethodInstance, irArgs);
  14053. if (!appendSizeTypedValue)
  14054. {
  14055. BF_ASSERT(calcAppendMethodModule.mFunc);
  14056. appendSizeTypedValue = CreateCall(objCreateExpr, calcAppendMethodModule.mMethodInstance, calcAppendMethodModule.mFunc, false, irArgs);
  14057. BF_ASSERT(appendSizeTypedValue.mType == mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  14058. }
  14059. appendSizeValue = appendSizeTypedValue.mValue;
  14060. allocAlign = BF_MAX(allocAlign, calcAppendMethodModule.mMethodInstance->mAppendAllocAlign);
  14061. appendAllocAlign = calcAppendMethodModule.mMethodInstance->mAppendAllocAlign;
  14062. }
  14063. if (appendAllocAlign != 0)
  14064. {
  14065. int endingAlign = typeInstance->GetEndingInstanceAlignment();
  14066. if (endingAlign % appendAllocAlign != 0)
  14067. {
  14068. int extraSize = appendAllocAlign - (endingAlign % appendAllocAlign);
  14069. appendSizeValue = mModule->mBfIRBuilder->CreateAdd(appendSizeValue, mModule->GetConstValue(extraSize));
  14070. }
  14071. }
  14072. }
  14073. // WTF? I'm not even sure this is correct - add more tests
  14074. appendAllocAlign = BF_MAX(appendAllocAlign, allocAlign);
  14075. BfIRValue allocValue;
  14076. if (IsVar(resolvedTypeRef))
  14077. {
  14078. mResult = mModule->GetDefaultTypedValue(resultType);
  14079. return;
  14080. }
  14081. else
  14082. {
  14083. if (isAppendAlloc)
  14084. {
  14085. allocValue = mModule->AppendAllocFromType(resolvedTypeRef, appendSizeValue, appendAllocAlign);
  14086. }
  14087. else
  14088. {
  14089. allocValue = mModule->AllocFromType(resolvedTypeRef, allocTarget, appendSizeValue, BfIRValue(), 0, BfAllocFlags_None, allocAlign);
  14090. }
  14091. if (((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) && (mModule->mCompiler->mCeMachine != NULL))
  14092. {
  14093. mModule->mCompiler->mCeMachine->SetAppendAllocInfo(mModule, allocValue, appendSizeValue);
  14094. }
  14095. mResult = BfTypedValue(allocValue, resultType);
  14096. }
  14097. if (isScopeAlloc)
  14098. {
  14099. // This allows readonly (ie: 'let') local usage to not require an access check. No matter what scope the alloc is tied to, the
  14100. // lifetime of the local variable will be no longer than that of the allocated value
  14101. mModule->SkipObjectAccessCheck(mResult);
  14102. }
  14103. /*if (typeInstance != NULL)
  14104. {
  14105. mModule->InitTypeInst(mResult, scopeData, true);
  14106. }
  14107. if (isStackAlloc)
  14108. {
  14109. mModule->AddStackAlloc(mResult, objCreateExpr, scopeData);
  14110. }*/
  14111. if (mResult)
  14112. {
  14113. if (bindResult.mMethodInstance == NULL)
  14114. {
  14115. // Why did we have this? It was already zeroed right?
  14116. // Zero
  14117. //mModule->mBfIRBuilder->CreateMemSet(mResult.mValue, mModule->GetConstValue8(0), mModule->GetConstValue(resolvedTypeRef->mSize), resolvedTypeRef->mAlign);
  14118. }
  14119. else if (bindResult.mFunc)
  14120. {
  14121. if (typeInstance->IsObject())
  14122. {
  14123. bool hasRealtimeLeakCheck = (mModule->mCompiler->mOptions.mEnableRealtimeLeakCheck) && (!IsComptime());
  14124. bool wantsCtorClear = true;
  14125. if (hasRealtimeLeakCheck)
  14126. {
  14127. // Dbg_ObjectAlloc clears internally so we don't need to call CtorClear for those
  14128. if ((!isStackAlloc) && (!isAppendAlloc) && (!allocTarget.mCustomAllocator) && (allocTarget.mScopedInvocationTarget == NULL))
  14129. wantsCtorClear = false;
  14130. }
  14131. if (wantsCtorClear)
  14132. {
  14133. auto ctorClear = mModule->GetMethodByName(typeInstance, "__BfCtorClear");
  14134. if (!ctorClear)
  14135. {
  14136. mModule->AssertErrorState();
  14137. }
  14138. else if ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) == 0)
  14139. {
  14140. SizedArray<BfIRValue, 1> irArgs;
  14141. irArgs.push_back(mResult.mValue);
  14142. CreateCall(objCreateExpr, ctorClear.mMethodInstance, ctorClear.mFunc, false, irArgs);
  14143. }
  14144. }
  14145. if ((!mModule->mIsComptimeModule) && (isStackAlloc) && (hasRealtimeLeakCheck))
  14146. {
  14147. BfMethodInstance* markMethod = mModule->GetRawMethodByName(mModule->mContext->mBfObjectType, "GCMarkMembers");
  14148. BF_ASSERT(markMethod != NULL);
  14149. if (markMethod != NULL)
  14150. {
  14151. auto& vtableEntry = typeInstance->mVirtualMethodTable[markMethod->mVirtualTableIdx];
  14152. if (vtableEntry.mImplementingMethod.mTypeInstance != mModule->mContext->mBfObjectType)
  14153. {
  14154. auto impMethodInstance = (BfMethodInstance*)vtableEntry.mImplementingMethod;
  14155. bool needsCall = false;
  14156. if (impMethodInstance != NULL)
  14157. {
  14158. needsCall = impMethodInstance->mMethodDef->mBody != NULL;
  14159. }
  14160. else
  14161. {
  14162. needsCall = true;
  14163. BF_ASSERT(vtableEntry.mImplementingMethod.mKind == BfMethodRefKind_AmbiguousRef);
  14164. }
  14165. if (!needsCall)
  14166. {
  14167. for (auto& fieldInst : typeInstance->mFieldInstances)
  14168. {
  14169. if (fieldInst.IsAppendedObject())
  14170. {
  14171. needsCall = true;
  14172. break;
  14173. }
  14174. }
  14175. }
  14176. if (needsCall)
  14177. {
  14178. SizedArray<BfIRValue, 1> irArgs;
  14179. irArgs.push_back(mModule->mBfIRBuilder->CreateBitCast(mResult.mValue, mModule->mBfIRBuilder->MapType(mModule->mContext->mBfObjectType)));
  14180. auto gcType = mModule->ResolveTypeDef(mModule->mCompiler->mGCTypeDef);
  14181. BF_ASSERT(gcType != NULL);
  14182. if (gcType != NULL)
  14183. {
  14184. auto addStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "AddStackMarkableObject", 1);
  14185. BF_ASSERT(addStackObjMethod);
  14186. if (addStackObjMethod)
  14187. {
  14188. mModule->mBfIRBuilder->CreateCall(addStackObjMethod.mFunc, irArgs);
  14189. }
  14190. auto removeStackObjMethod = mModule->GetMethodByName(gcType->ToTypeInstance(), "RemoveStackMarkableObject", 1);
  14191. BF_ASSERT(removeStackObjMethod);
  14192. if (removeStackObjMethod)
  14193. {
  14194. mModule->AddDeferredCall(removeStackObjMethod, irArgs, allocTarget.mScopeData, allocNode);
  14195. }
  14196. }
  14197. }
  14198. }
  14199. }
  14200. }
  14201. }
  14202. if ((bindResult.mMethodInstance->mMethodDef->mHasAppend) && (mResult.mType->IsObject()))
  14203. {
  14204. BF_ASSERT(bindResult.mIRArgs[0].IsFake());
  14205. auto typeInst = mResult.mType->ToTypeInstance();
  14206. auto intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  14207. auto thisVal = mResult;
  14208. BfIRValue intPtrVal = mModule->CreateAlloca(intPtrType);
  14209. auto intPtrThisVal = mModule->mBfIRBuilder->CreatePtrToInt(thisVal.mValue, (intPtrType->mSize == 4) ? BfTypeCode_Int32 : BfTypeCode_Int64);
  14210. auto curValPtr = mModule->mBfIRBuilder->CreateAdd(intPtrThisVal, mModule->GetConstValue(typeInst->mInstSize, intPtrType));
  14211. mModule->mBfIRBuilder->CreateStore(curValPtr, intPtrVal);
  14212. bindResult.mIRArgs[0] = intPtrVal;
  14213. }
  14214. if (!typeInstance->IsValuelessType())
  14215. bindResult.mIRArgs.Insert(0, mResult.mValue);
  14216. auto result = CreateCall(objCreateExpr, bindResult.mMethodInstance, bindResult.mFunc, false, bindResult.mIRArgs);
  14217. if ((result) && (!result.mType->IsVoid()))
  14218. mResult = result;
  14219. }
  14220. }
  14221. if (((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0) && (mModule->mCompiler->mCeMachine != NULL))
  14222. {
  14223. mModule->mCompiler->mCeMachine->ClearAppendAllocInfo();
  14224. }
  14225. }
  14226. void BfExprEvaluator::Visit(BfBoxExpression* boxExpr)
  14227. {
  14228. /*if ((boxExpr->mAllocNode == NULL) || (boxExpr->mExpression == NULL))
  14229. {
  14230. mModule->AssertErrorState();
  14231. return;
  14232. }*/
  14233. BfTokenNode* newToken = NULL;
  14234. BfAllocTarget allocTarget;
  14235. ResolveAllocTarget(allocTarget, boxExpr->mAllocNode, newToken);
  14236. if ((boxExpr->mAllocNode != NULL) && (boxExpr->mAllocNode->mToken == BfToken_Scope))
  14237. {
  14238. if ((mBfEvalExprFlags & BfEvalExprFlags_FieldInitializer) != 0)
  14239. {
  14240. mModule->Warn(0, "This allocation will only be in scope during the constructor. Consider using a longer-term allocation such as 'new'", boxExpr->mAllocNode);
  14241. }
  14242. }
  14243. if (boxExpr->mExpression == NULL)
  14244. {
  14245. mModule->AssertErrorState();
  14246. return;
  14247. }
  14248. auto exprValue = mModule->CreateValueFromExpression(boxExpr->mExpression);
  14249. if (exprValue)
  14250. {
  14251. bool doFail = false;
  14252. bool doWarn = false;
  14253. BfType* boxedType = NULL;
  14254. if (exprValue.mType->IsGenericParam())
  14255. {
  14256. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  14257. auto genericParamTarget = (BfGenericParamType*)exprValue.mType;
  14258. auto genericParamInstance = mModule->GetGenericParamInstance(genericParamTarget);
  14259. if ((genericParamInstance->mGenericParamFlags & (BfGenericParamFlag_Struct | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class)) == BfGenericParamFlag_Class)
  14260. doWarn = true;
  14261. if ((genericParamInstance->mTypeConstraint != NULL) && (genericParamInstance->mTypeConstraint->IsObjectOrInterface()))
  14262. doWarn = true;
  14263. boxedType = mModule->mContext->mBfObjectType;
  14264. }
  14265. else
  14266. {
  14267. doFail = !exprValue.mType->IsValueTypeOrValueTypePtr();
  14268. doWarn = exprValue.mType->IsObjectOrInterface();
  14269. }
  14270. if (doWarn)
  14271. {
  14272. mModule->Warn(0, StrFormat("Boxing is unnecessary since type '%s' is already a reference type.", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  14273. mResult = exprValue;
  14274. return;
  14275. }
  14276. if (doFail)
  14277. {
  14278. 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);
  14279. return;
  14280. }
  14281. if (boxedType == NULL)
  14282. boxedType = mModule->CreateBoxedType(exprValue.mType);
  14283. if (boxedType == NULL)
  14284. boxedType = mModule->mContext->mBfObjectType;
  14285. mResult = mModule->BoxValue(boxExpr->mExpression, exprValue, boxedType, allocTarget);
  14286. if (!mResult)
  14287. {
  14288. mModule->Fail(StrFormat("Type '%s' is not boxable", mModule->TypeToString(exprValue.mType).c_str()), boxExpr->mExpression);
  14289. return;
  14290. }
  14291. }
  14292. }
  14293. void BfExprEvaluator::ResolveAllocTarget(BfAllocTarget& allocTarget, BfAstNode* allocNode, BfTokenNode*& newToken, BfCustomAttributes** outCustomAttributes)
  14294. {
  14295. auto autoComplete = GetAutoComplete();
  14296. BfAttributeDirective* attributeDirective = NULL;
  14297. allocTarget.mRefNode = allocNode;
  14298. newToken = BfNodeDynCast<BfTokenNode>(allocNode);
  14299. if (newToken == NULL)
  14300. {
  14301. if (auto scopeNode = BfNodeDynCast<BfScopeNode>(allocNode))
  14302. {
  14303. newToken = scopeNode->mScopeToken;
  14304. allocTarget.mScopeData = mModule->FindScope(scopeNode->mTargetNode, true);
  14305. if (autoComplete != NULL)
  14306. {
  14307. auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(scopeNode->mTargetNode);
  14308. if ((scopeNode->mTargetNode == NULL) || (targetIdentifier != NULL))
  14309. autoComplete->CheckLabel(targetIdentifier, scopeNode->mColonToken, allocTarget.mScopeData);
  14310. }
  14311. attributeDirective = scopeNode->mAttributes;
  14312. }
  14313. if (auto newNode = BfNodeDynCast<BfNewNode>(allocNode))
  14314. {
  14315. newToken = newNode->mNewToken;
  14316. if (auto allocExpr = BfNodeDynCast<BfExpression>(newNode->mAllocNode))
  14317. {
  14318. allocTarget.mCustomAllocator = mModule->CreateValueFromExpression(allocExpr);
  14319. allocTarget.mRefNode = allocExpr;
  14320. }
  14321. else if (auto scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(newNode->mAllocNode))
  14322. {
  14323. allocTarget.mScopedInvocationTarget = scopedInvocationTarget;
  14324. }
  14325. attributeDirective = newNode->mAttributes;
  14326. }
  14327. }
  14328. else if (newToken->GetToken() == BfToken_Scope)
  14329. {
  14330. if (mModule->mCurMethodState != NULL)
  14331. allocTarget.mScopeData = mModule->mCurMethodState->mCurScope->GetTargetable();
  14332. }
  14333. else if (newToken->GetToken() == BfToken_Stack)
  14334. {
  14335. if (mModule->mCurMethodState != NULL)
  14336. allocTarget.mScopeData = &mModule->mCurMethodState->mHeadScope;
  14337. }
  14338. if (attributeDirective != NULL)
  14339. {
  14340. auto customAttrs = mModule->GetCustomAttributes(attributeDirective, BfAttributeTargets_Alloc, BfGetCustomAttributesFlags_AllowNonConstArgs, allocTarget.mCaptureInfo);
  14341. if (customAttrs != NULL)
  14342. {
  14343. for (auto& attrib : customAttrs->mAttributes)
  14344. {
  14345. if (attrib.mType->IsInstanceOf(mModule->mCompiler->mAlignAttributeTypeDef))
  14346. {
  14347. allocTarget.mAlignOverride = 16; // System conservative default
  14348. if (!attrib.mCtorArgs.IsEmpty())
  14349. {
  14350. BfIRConstHolder* constHolder = mModule->mCurTypeInstance->mConstHolder;
  14351. auto constant = constHolder->GetConstant(attrib.mCtorArgs[0]);
  14352. if (constant != NULL)
  14353. {
  14354. int alignOverride = (int)BF_MAX(1, constant->mInt64);
  14355. if ((alignOverride & (alignOverride - 1)) == 0)
  14356. allocTarget.mAlignOverride = alignOverride;
  14357. else
  14358. mModule->Fail("Alignment must be a power of 2", attrib.GetRefNode());
  14359. }
  14360. }
  14361. }
  14362. else if (attrib.mType->IsInstanceOf(mModule->mCompiler->mFriendAttributeTypeDef))
  14363. allocTarget.mIsFriend = true;
  14364. }
  14365. if (outCustomAttributes != NULL)
  14366. *outCustomAttributes = customAttrs;
  14367. else
  14368. delete customAttrs;
  14369. }
  14370. }
  14371. }
  14372. BfTypedValue BfExprEvaluator::MakeCallableTarget(BfAstNode* targetSrc, BfTypedValue target)
  14373. {
  14374. if ((target.mType->IsRef()) || (target.mType->IsPointer()))
  14375. {
  14376. auto underlying = target.mType->GetUnderlyingType();
  14377. bool underlyingIsStruct = underlying->IsStruct();
  14378. if (underlyingIsStruct)
  14379. {
  14380. target = mModule->LoadValue(target);
  14381. target.mType = underlying;
  14382. target.mKind = BfTypedValueKind_Addr;
  14383. }
  14384. }
  14385. if ((target.mType->IsStruct()) && (!target.IsAddr()))
  14386. {
  14387. if (IsConstEval())
  14388. return target;
  14389. target = mModule->MakeAddressable(target);
  14390. }
  14391. if (IsVar(target.mType))
  14392. {
  14393. target.mType = mModule->mContext->mBfObjectType;
  14394. return target;
  14395. }
  14396. if (target.mType->IsWrappableType())
  14397. {
  14398. auto primStructType = mModule->GetWrappedStructType(target.mType);
  14399. if (primStructType != NULL)
  14400. {
  14401. mModule->PopulateType(primStructType);
  14402. if (primStructType->IsTypedPrimitive())
  14403. {
  14404. // Type is already the same
  14405. target.mType = primStructType;
  14406. }
  14407. else if (target.IsAddr())
  14408. {
  14409. auto ptrType = mModule->CreatePointerType(primStructType);
  14410. target = BfTypedValue(mModule->mBfIRBuilder->CreateBitCast(target.mValue, mModule->mBfIRBuilder->MapType(ptrType)), primStructType, true);
  14411. }
  14412. else if ((primStructType->IsSplattable()) && (target.IsSplat()) && (!IsComptime()))
  14413. {
  14414. target.mType = primStructType;
  14415. target.mKind = BfTypedValueKind_SplatHead;
  14416. }
  14417. else
  14418. {
  14419. auto allocPtr = mModule->CreateAlloca(primStructType);
  14420. auto srcPtrType = mModule->mBfIRBuilder->CreateBitCast(allocPtr, mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->MapType(target.mType)));
  14421. mModule->mBfIRBuilder->CreateStore(target.mValue, srcPtrType);
  14422. target = BfTypedValue(allocPtr, primStructType, true);
  14423. }
  14424. }
  14425. return target;
  14426. }
  14427. if (target.mType->IsGenericParam())
  14428. {
  14429. target.mType = mModule->mContext->mBfObjectType;
  14430. return target;
  14431. }
  14432. if ((!target.mType->IsTypeInstance()) && (!target.mType->IsConcreteInterfaceType()))
  14433. {
  14434. mModule->Fail(StrFormat("Methods cannot be called on type '%s'", mModule->TypeToString(target.mType).c_str()), targetSrc);
  14435. return BfTypedValue();
  14436. }
  14437. return target;
  14438. }
  14439. int BfExprEvaluator::GetMixinVariable()
  14440. {
  14441. auto curMethodState = mModule->mCurMethodState;
  14442. for (int localIdx = (int)curMethodState->mLocals.size() - 1; localIdx >= 0; localIdx--)
  14443. {
  14444. auto varDecl = curMethodState->mLocals[localIdx];
  14445. if (varDecl->mName == "mixin")
  14446. return localIdx;
  14447. }
  14448. return -1;
  14449. }
  14450. BfModuleMethodInstance BfExprEvaluator::GetSelectedMethod(BfAstNode* targetSrc, BfTypeInstance* curTypeInst, BfMethodDef* methodDef, BfMethodMatcher& methodMatcher, BfType** overrideReturnType)
  14451. {
  14452. bool failed = false;
  14453. BfTypeVector resolvedGenericArguments;
  14454. BfMethodState* rootMethodState = NULL;
  14455. if (mModule->mCurMethodState != NULL)
  14456. rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  14457. int localInferrableGenericArgCount = -1;
  14458. if ((methodMatcher.mBestMethodGenericArguments.size() == 0) && (!methodMatcher.mExplicitMethodGenericArguments.IsEmpty()))
  14459. {
  14460. int uniqueGenericStartIdx = mModule->GetLocalInferrableGenericArgCount(methodDef);
  14461. int64 genericArgCountDiff = (int)methodMatcher.mExplicitMethodGenericArguments.size() + uniqueGenericStartIdx - (int)methodDef->mGenericParams.size();
  14462. BfInvocationExpression* invocationExpr = NULL;
  14463. if (mModule->mParentNodeEntry != NULL)
  14464. {
  14465. invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode);
  14466. }
  14467. if (genericArgCountDiff > 0)
  14468. {
  14469. BfAstNode* errorNode = targetSrc;
  14470. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL))
  14471. {
  14472. errorNode = invocationExpr->mGenericArgs->mGenericArgs[(int)methodDef->mGenericParams.size()];
  14473. if (errorNode == NULL)
  14474. invocationExpr->mGenericArgs->mCommas.GetSafe((int)methodDef->mGenericParams.size() - 1, errorNode);
  14475. if (errorNode == NULL)
  14476. errorNode = targetSrc;
  14477. }
  14478. mModule->Fail(StrFormat("Too many generic arguments, expected %d fewer", genericArgCountDiff), errorNode);
  14479. }
  14480. else if ((genericArgCountDiff < 0) && (!methodMatcher.mHadOpenGenericArguments))
  14481. {
  14482. BfAstNode* errorNode = targetSrc;
  14483. if ((invocationExpr != NULL) && (invocationExpr->mGenericArgs != NULL) && (invocationExpr->mGenericArgs->mCloseChevron != NULL))
  14484. errorNode = invocationExpr->mGenericArgs->mCloseChevron;
  14485. mModule->Fail(StrFormat("Too few generic arguments, expected %d more", -genericArgCountDiff), errorNode);
  14486. }
  14487. methodMatcher.mBestMethodGenericArguments.resize(methodDef->mGenericParams.size());
  14488. for (int i = 0; i < std::min(methodDef->mGenericParams.size() - uniqueGenericStartIdx, methodMatcher.mExplicitMethodGenericArguments.size()); i++)
  14489. {
  14490. methodMatcher.mBestMethodGenericArguments[i + uniqueGenericStartIdx] = methodMatcher.mExplicitMethodGenericArguments[i];
  14491. }
  14492. }
  14493. BfMethodInstance* unspecializedMethod = NULL;
  14494. bool hasVarGenerics = false;
  14495. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  14496. {
  14497. BfMethodInstance* outerMethodInstance = NULL;
  14498. auto& genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  14499. if (genericArg == NULL)
  14500. {
  14501. if ((methodDef->mIsLocalMethod) && (checkGenericIdx < mModule->mCurMethodInstance->GetNumGenericArguments()))
  14502. {
  14503. // If the root method is generic and we need that param then use that...
  14504. auto rootMethodInstance = rootMethodState->mMethodInstance;
  14505. if ((rootMethodInstance->mMethodInfoEx != NULL) && (checkGenericIdx < rootMethodInstance->mMethodInfoEx->mMethodGenericArguments.size()))
  14506. {
  14507. genericArg = rootMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  14508. }
  14509. else
  14510. {
  14511. if (localInferrableGenericArgCount == -1)
  14512. localInferrableGenericArgCount = mModule->GetLocalInferrableGenericArgCount(methodDef);
  14513. // Otherwise we can only infer generics at the level that the called method was contained
  14514. if (checkGenericIdx < localInferrableGenericArgCount)
  14515. genericArg = mModule->mCurMethodInstance->mMethodInfoEx->mMethodGenericArguments[checkGenericIdx];
  14516. }
  14517. }
  14518. }
  14519. if (genericArg == NULL)
  14520. {
  14521. if (unspecializedMethod == NULL)
  14522. unspecializedMethod = mModule->GetRawMethodInstance(curTypeInst, methodDef);
  14523. auto genericParam = unspecializedMethod->mMethodInfoEx->mGenericParams[checkGenericIdx];
  14524. if ((genericParam->mTypeConstraint != NULL) && (genericParam->mTypeConstraint->IsDelegate()))
  14525. {
  14526. // The only other option was to bind to a MethodRef
  14527. genericArg = mModule->ResolveGenericType(genericParam->mTypeConstraint, NULL, &methodMatcher.mBestMethodGenericArguments, mModule->mCurTypeInstance);
  14528. }
  14529. else
  14530. {
  14531. if (((genericParam->mGenericParamFlags & BfGenericParamFlag_Const) != 0) && (genericParam->mTypeConstraint != NULL))
  14532. {
  14533. for (int paramIdx = 0; paramIdx < (int)unspecializedMethod->mDefaultValues.size(); paramIdx++)
  14534. {
  14535. auto defaultVal = unspecializedMethod->mDefaultValues[paramIdx];
  14536. if (!defaultVal)
  14537. continue;
  14538. auto& param = unspecializedMethod->mParams[paramIdx];
  14539. if (param.mResolvedType->IsGenericParam())
  14540. {
  14541. auto genericParamType = (BfGenericParamType*)param.mResolvedType;
  14542. if ((genericParamType->mGenericParamKind == BfGenericParamKind_Method) && (genericParamType->mGenericParamIdx == checkGenericIdx))
  14543. {
  14544. BfTypedValue constExprVal;
  14545. constExprVal.mType = genericParam->mTypeConstraint;
  14546. auto constant = curTypeInst->mConstHolder->GetConstant(defaultVal.mValue);
  14547. constExprVal.mValue = mModule->ConstantToCurrent(constant, curTypeInst->mConstHolder, genericParam->mTypeConstraint);
  14548. genericArg = mModule->CreateConstExprValueType(constExprVal);
  14549. }
  14550. }
  14551. }
  14552. }
  14553. }
  14554. if (genericArg == NULL)
  14555. {
  14556. BfGenericInferContext genericInferContext;
  14557. genericInferContext.mModule = mModule;
  14558. genericInferContext.mCheckMethodGenericArguments = &methodMatcher.mBestMethodGenericArguments;
  14559. genericInferContext.InferGenericArguments(unspecializedMethod);
  14560. }
  14561. if (genericArg == NULL)
  14562. {
  14563. failed = true;
  14564. BfError* error = mModule->Fail(StrFormat("Unable to determine generic argument '%s'", methodDef->mGenericParams[checkGenericIdx]->mName.c_str()).c_str(), targetSrc);
  14565. if ((genericParam->mTypeConstraint != NULL) && (!genericParam->mTypeConstraint->IsUnspecializedType()))
  14566. genericArg = genericParam->mTypeConstraint;
  14567. else
  14568. genericArg = mModule->mContext->mBfObjectType;
  14569. if (error != NULL)
  14570. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), unspecializedMethod->mMethodDef->GetRefNode());
  14571. }
  14572. }
  14573. if (genericArg->IsVar())
  14574. {
  14575. //BF_ASSERT(methodMatcher.mHasVarArguments);
  14576. hasVarGenerics = true;
  14577. }
  14578. if (genericArg->IsIntUnknown())
  14579. genericArg = mModule->FixIntUnknown(genericArg);
  14580. auto resolvedGenericArg = genericArg;
  14581. resolvedGenericArguments.push_back(genericArg);
  14582. }
  14583. BfTypeInstance* foreignType = NULL;
  14584. BfGetMethodInstanceFlags flags = BfGetMethodInstanceFlag_None;
  14585. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef)))
  14586. {
  14587. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForceInline);
  14588. mModule->mAttributeState->mUsed = true;
  14589. }
  14590. if ((!mModule->mCurTypeInstance->IsInterface()) && (methodDef->mBody != NULL))
  14591. {
  14592. if ((methodMatcher.mBypassVirtual) && (methodMatcher.mBestMethodTypeInstance->IsInterface()))
  14593. {
  14594. // This is an explicit 'base' call to a default interface method. We pull the methodDef into our own concrete type.
  14595. foreignType = curTypeInst;
  14596. curTypeInst = mModule->mCurTypeInstance;
  14597. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  14598. }
  14599. else if ((methodDef->mIsStatic) && (curTypeInst->IsInterface()))
  14600. {
  14601. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  14602. {
  14603. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  14604. foreignType = curTypeInst;
  14605. curTypeInst = mModule->mCurTypeInstance;
  14606. flags = (BfGetMethodInstanceFlags)(flags | BfGetMethodInstanceFlag_ForeignMethodDef);
  14607. }
  14608. }
  14609. }
  14610. if (hasVarGenerics)
  14611. return BfModuleMethodInstance();
  14612. BfModuleMethodInstance moduleMethodInstance;
  14613. if (methodMatcher.mBestMethodInstance)
  14614. {
  14615. moduleMethodInstance = methodMatcher.mBestMethodInstance;
  14616. }
  14617. else
  14618. {
  14619. moduleMethodInstance = mModule->GetMethodInstance(curTypeInst, methodDef, resolvedGenericArguments, flags, foreignType);
  14620. }
  14621. if (mModule->IsSkippingExtraResolveChecks())
  14622. {
  14623. //BF_ASSERT(methodInstance.mFunc == NULL);
  14624. }
  14625. if (moduleMethodInstance.mMethodInstance == NULL)
  14626. return NULL;
  14627. if (methodDef->IsEmptyPartial())
  14628. return moduleMethodInstance;
  14629. if (moduleMethodInstance.mMethodInstance->mMethodInfoEx != NULL)
  14630. {
  14631. for (int checkGenericIdx = 0; checkGenericIdx < (int)moduleMethodInstance.mMethodInstance->mMethodInfoEx->mGenericParams.size(); checkGenericIdx++)
  14632. {
  14633. auto genericParams = moduleMethodInstance.mMethodInstance->mMethodInfoEx->mGenericParams[checkGenericIdx];
  14634. BfTypeVector* checkMethodGenericArgs = NULL;
  14635. BfType* genericArg = NULL;
  14636. if (checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size())
  14637. {
  14638. genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  14639. }
  14640. else
  14641. {
  14642. checkMethodGenericArgs = &methodMatcher.mBestMethodGenericArguments;
  14643. genericArg = genericParams->mExternType;
  14644. auto owner = moduleMethodInstance.mMethodInstance->GetOwner();
  14645. BfTypeVector* typeGenericArguments = NULL;
  14646. if (owner->mGenericTypeInfo != NULL)
  14647. typeGenericArguments = &owner->mGenericTypeInfo->mTypeGenericArguments;
  14648. //genericArg = mModule->ResolveGenericType(genericArg, typeGenericArguments, checkMethodGenericArgs);
  14649. }
  14650. if (genericArg->IsVar())
  14651. continue;
  14652. BfAstNode* paramSrc;
  14653. if (checkGenericIdx >= methodMatcher.mBestMethodGenericArgumentSrcs.size())
  14654. {
  14655. paramSrc = targetSrc;
  14656. }
  14657. else
  14658. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  14659. // Note: don't pass methodMatcher.mBestMethodGenericArguments into here, this method is already specialized
  14660. BfError* error = NULL;
  14661. if (!mModule->CheckGenericConstraints(BfGenericParamSource(moduleMethodInstance.mMethodInstance), genericArg, paramSrc, genericParams, NULL,
  14662. failed ? NULL : &error))
  14663. {
  14664. if (moduleMethodInstance.mMethodInstance->IsSpecializedGenericMethod())
  14665. {
  14666. // We mark this as failed to make sure we don't try to process a method that doesn't even follow the constraints
  14667. moduleMethodInstance.mMethodInstance->mFailedConstraints = true;
  14668. }
  14669. if (moduleMethodInstance.mMethodInstance->mMethodDef->mMethodDeclaration != NULL)
  14670. {
  14671. if (error != NULL)
  14672. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), moduleMethodInstance.mMethodInstance->mMethodDef->GetRefNode());
  14673. }
  14674. }
  14675. }
  14676. }
  14677. else
  14678. BF_ASSERT(methodMatcher.mBestMethodGenericArguments.IsEmpty());
  14679. if ((overrideReturnType != NULL) && (moduleMethodInstance.mMethodInstance->mIsUnspecializedVariation) &&
  14680. ((moduleMethodInstance.mMethodInstance->mReturnType->IsUnspecializedTypeVariation()) || (moduleMethodInstance.mMethodInstance->mReturnType->IsVar())))
  14681. {
  14682. if (unspecializedMethod == NULL)
  14683. unspecializedMethod = mModule->GetRawMethodInstance(curTypeInst, methodDef);
  14684. BfTypeVector* typeGenericArgs = NULL;
  14685. auto typeUnspecMethodInstance = unspecializedMethod;
  14686. if (curTypeInst->IsUnspecializedTypeVariation())
  14687. {
  14688. typeUnspecMethodInstance = mModule->GetUnspecializedMethodInstance(typeUnspecMethodInstance, true);
  14689. typeGenericArgs = &curTypeInst->mGenericTypeInfo->mTypeGenericArguments;
  14690. }
  14691. BfType* specializedReturnType = mModule->ResolveGenericType(typeUnspecMethodInstance->mReturnType, typeGenericArgs, &methodMatcher.mBestMethodGenericArguments,
  14692. mModule->mCurTypeInstance);
  14693. if (specializedReturnType != NULL)
  14694. *overrideReturnType = specializedReturnType;
  14695. }
  14696. return moduleMethodInstance;
  14697. }
  14698. BfModuleMethodInstance BfExprEvaluator::GetSelectedMethod(BfMethodMatcher& methodMatcher)
  14699. {
  14700. if (!methodMatcher.mBestMethodInstance)
  14701. methodMatcher.mBestMethodInstance = GetSelectedMethod(methodMatcher.mTargetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  14702. return methodMatcher.mBestMethodInstance;
  14703. }
  14704. void BfExprEvaluator::CheckLocalMethods(BfAstNode* targetSrc, BfTypeInstance* typeInstance, const StringImpl& methodName, BfMethodMatcher& methodMatcher, BfMethodType methodType)
  14705. {
  14706. auto _GetNodeId = [&]()
  14707. {
  14708. auto parser = targetSrc->GetSourceData()->ToParserData();
  14709. return ((int64)parser->mDataId << 32) + targetSrc->GetSrcStart();
  14710. };
  14711. BfMethodState* ctxMethodState = NULL;
  14712. BfClosureInstanceInfo* ctxClosureInstanceInfo = NULL;
  14713. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL))
  14714. {
  14715. ctxClosureInstanceInfo = mModule->mCurMethodState->mClosureState->mClosureInstanceInfo;
  14716. ctxMethodState = mModule->mCurMethodState;
  14717. }
  14718. bool atCtxMethodState = false;
  14719. auto checkMethodState = mModule->mCurMethodState;
  14720. auto rootMethodState = checkMethodState;
  14721. while (checkMethodState != NULL)
  14722. {
  14723. rootMethodState = checkMethodState;
  14724. if (checkMethodState == ctxMethodState)
  14725. atCtxMethodState = true;
  14726. if ((ctxClosureInstanceInfo != NULL) && (!ctxMethodState->mClosureState->mCapturing))
  14727. {
  14728. BfMethodDef* localMethodDef = NULL;
  14729. if (ctxClosureInstanceInfo->mLocalMethodBindings.TryGetValue(_GetNodeId(), &localMethodDef))
  14730. {
  14731. methodMatcher.CheckMethod(mModule->mCurTypeInstance, mModule->mCurTypeInstance, localMethodDef, true);
  14732. BF_ASSERT(methodMatcher.mBestMethodDef != NULL);
  14733. return;
  14734. }
  14735. }
  14736. else
  14737. {
  14738. BfLocalMethod* matchedLocalMethod = NULL;
  14739. BfLocalMethod* localMethod = NULL;
  14740. if (checkMethodState->mLocalMethodMap.TryGetValue(methodName, &localMethod))
  14741. {
  14742. auto typeInst = mModule->mCurTypeInstance;
  14743. if (checkMethodState->mMixinState != NULL)
  14744. typeInst = checkMethodState->mMixinState->mMixinMethodInstance->GetOwner();
  14745. while (localMethod != NULL)
  14746. {
  14747. auto methodDef = mModule->GetLocalMethodDef(localMethod);
  14748. if (methodDef->mMethodType == methodType)
  14749. {
  14750. methodMatcher.CheckMethod(mModule->mCurTypeInstance, typeInst, methodDef, true);
  14751. if (methodMatcher.mBestMethodDef == methodDef)
  14752. matchedLocalMethod = localMethod;
  14753. }
  14754. localMethod = localMethod->mNextWithSameName;
  14755. }
  14756. }
  14757. if (matchedLocalMethod != NULL)
  14758. {
  14759. if ((mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  14760. {
  14761. BfModuleMethodInstance moduleMethodInstance = GetSelectedMethod(targetSrc, typeInstance, matchedLocalMethod->mMethodDef, methodMatcher);
  14762. if (moduleMethodInstance)
  14763. {
  14764. auto methodInstance = moduleMethodInstance.mMethodInstance;
  14765. if ((methodInstance->mMethodInfoEx != NULL) && (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState != NULL))
  14766. {
  14767. // The called method is calling us from its mLocalMethodRefs set. Stretch our mCaptureStartAccessId back to incorporate its
  14768. // captures as well
  14769. if (methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId < mModule->mCurMethodState->mClosureState->mCaptureStartAccessId)
  14770. mModule->mCurMethodState->mClosureState->mCaptureStartAccessId = methodInstance->mMethodInfoEx->mClosureInstanceInfo->mCaptureClosureState->mCaptureStartAccessId;
  14771. }
  14772. else
  14773. {
  14774. if (methodInstance->mDisallowCalling) // We need to process the captures from this guy
  14775. {
  14776. if (mModule->mCurMethodState->mClosureState->mLocalMethodRefSet.Add(methodInstance))
  14777. mModule->mCurMethodState->mClosureState->mLocalMethodRefs.Add(methodInstance);
  14778. }
  14779. }
  14780. }
  14781. }
  14782. if (ctxClosureInstanceInfo != NULL)
  14783. {
  14784. BF_ASSERT(mModule->mCurMethodState->mClosureState->mCapturing);
  14785. ctxClosureInstanceInfo->mLocalMethodBindings[_GetNodeId()] = methodMatcher.mBestMethodDef;
  14786. }
  14787. break;
  14788. }
  14789. }
  14790. checkMethodState = checkMethodState->mPrevMethodState;
  14791. }
  14792. }
  14793. void BfExprEvaluator::InjectMixin(BfAstNode* targetSrc, BfTypedValue target, bool allowImplicitThis, const StringImpl& name, const BfSizedArray<BfExpression*>& arguments, const BfMethodGenericArguments& methodGenericArgs)
  14794. {
  14795. if (mModule->mCurMethodState == NULL)
  14796. return;
  14797. if (mDeferCallRef != NULL)
  14798. {
  14799. mModule->Fail("Mixins cannot be directly deferred. Consider wrapping in a block.", targetSrc);
  14800. }
  14801. BfAstNode* origTargetSrc = targetSrc;
  14802. BfScopedInvocationTarget* scopedInvocationTarget = NULL;
  14803. if (mModule->mParentNodeEntry != NULL)
  14804. {
  14805. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  14806. {
  14807. scopedInvocationTarget = BfNodeDynCast<BfScopedInvocationTarget>(invocationExpr->mTarget);
  14808. }
  14809. }
  14810. auto targetNameNode = targetSrc;
  14811. if (scopedInvocationTarget != NULL)
  14812. targetNameNode = scopedInvocationTarget->mTarget;
  14813. while (true)
  14814. {
  14815. if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(targetNameNode))
  14816. {
  14817. targetNameNode = qualifiedNameNode->mRight;
  14818. continue;
  14819. }
  14820. if (auto memberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(targetNameNode))
  14821. {
  14822. targetNameNode = memberRefExpr->mMemberName;
  14823. continue;
  14824. }
  14825. break;
  14826. }
  14827. BfTypeInstance* mixinClass = NULL;
  14828. if (target.mType != NULL)
  14829. mixinClass = target.mType->ToTypeInstance();
  14830. int inLine = mModule->mCurFilePosition.mCurLine;
  14831. SizedArray<BfResolvedArg, 4> args;
  14832. SizedArray<BfExprEvaluator*, 8> argExprEvaluators;
  14833. defer
  14834. (
  14835. {
  14836. for (auto exprEvaluator : argExprEvaluators)
  14837. delete exprEvaluator;
  14838. }
  14839. );
  14840. auto _AddArg = [&](BfExpression* argExpr)
  14841. {
  14842. BfResolvedArg resolvedArg;
  14843. argExprEvaluators.push_back(new BfExprEvaluator(mModule));
  14844. BfExprEvaluator* exprEvaluator = argExprEvaluators.back();
  14845. exprEvaluator->mResolveGenericParam = false;
  14846. exprEvaluator->mBfEvalExprFlags = (BfEvalExprFlags)(exprEvaluator->mBfEvalExprFlags | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowRefExpr | BfEvalExprFlags_AllowOutExpr);
  14847. bool deferExpr = false;
  14848. if (auto variableDecl = BfNodeDynCast<BfVariableDeclaration>(argExpr))
  14849. {
  14850. deferExpr = true;
  14851. resolvedArg.mArgFlags = (BfArgFlags)(resolvedArg.mArgFlags | BfArgFlag_VariableDeclaration);
  14852. }
  14853. if (deferExpr)
  14854. {
  14855. //
  14856. }
  14857. else if (argExpr != NULL)
  14858. exprEvaluator->Evaluate(argExpr, false, false, true);
  14859. else
  14860. mModule->Fail("Missing argument", targetSrc);
  14861. auto argValue = exprEvaluator->mResult;
  14862. mModule->FixIntUnknown(argValue);
  14863. if (argValue)
  14864. {
  14865. if (argValue.mType->IsRef())
  14866. {
  14867. exprEvaluator->FinishExpressionResult();
  14868. }
  14869. }
  14870. resolvedArg.mTypedValue = argValue;
  14871. resolvedArg.mExpression = argExpr;
  14872. args.push_back(resolvedArg);
  14873. };
  14874. for (BfExpression* argExpr : arguments)
  14875. {
  14876. _AddArg(argExpr);
  14877. }
  14878. auto autoComplete = GetAutoComplete();
  14879. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo) && (autoComplete->mMethodMatchInfo != NULL) && (autoComplete->mMethodMatchInfo->mInstanceList.size() != 0))
  14880. autoComplete->mIsCapturingMethodMatchInfo = false;
  14881. BfMethodMatcher methodMatcher(targetSrc, mModule, name, args, methodGenericArgs);
  14882. methodMatcher.mMethodType = BfMethodType_Mixin;
  14883. methodMatcher.mSkipImplicitParams = true;
  14884. auto curTypeInst = mModule->mCurTypeInstance;
  14885. if (mixinClass != NULL)
  14886. curTypeInst = mixinClass;
  14887. if (target.mType == NULL)
  14888. {
  14889. CheckLocalMethods(targetSrc, curTypeInst, name, methodMatcher, BfMethodType_Mixin);
  14890. }
  14891. if (methodMatcher.mBestMethodDef == NULL)
  14892. methodMatcher.mBestMethodDef = methodMatcher.mBackupMethodDef;
  14893. if (methodMatcher.mBestMethodDef == NULL)
  14894. {
  14895. if (mixinClass != NULL)
  14896. methodMatcher.CheckType(mixinClass, BfTypedValue(), false);
  14897. else
  14898. methodMatcher.CheckType(mModule->mCurTypeInstance, BfTypedValue(), false);
  14899. }
  14900. if ((methodMatcher.mBestMethodDef == NULL) && (target.mType == NULL) && (mModule->mContext->mCurTypeState != NULL))
  14901. {
  14902. BF_ASSERT(mModule->mCurTypeInstance == mModule->mContext->mCurTypeState->mType);
  14903. BfGlobalLookup globalLookup;
  14904. globalLookup.mKind = BfGlobalLookup::Kind_Method;
  14905. globalLookup.mName = name;
  14906. mModule->PopulateGlobalContainersList(globalLookup);
  14907. for (auto& globalContainer : mModule->mContext->mCurTypeState->mGlobalContainers)
  14908. {
  14909. if (globalContainer.mTypeInst == NULL)
  14910. continue;
  14911. methodMatcher.CheckType(globalContainer.mTypeInst, BfTypedValue(), false);
  14912. if (methodMatcher.mBestMethodDef != NULL)
  14913. break;
  14914. }
  14915. }
  14916. if (methodMatcher.mBestMethodDef == NULL)
  14917. {
  14918. BfStaticSearch* staticSearch = mModule->GetStaticSearch();
  14919. if (staticSearch != NULL)
  14920. {
  14921. for (auto typeInst : staticSearch->mStaticTypes)
  14922. {
  14923. if (methodMatcher.CheckType(typeInst, BfTypedValue(), false))
  14924. {
  14925. if (methodMatcher.mBestMethodDef != NULL)
  14926. break;
  14927. }
  14928. }
  14929. }
  14930. }
  14931. if (methodMatcher.mBestMethodDef == NULL)
  14932. {
  14933. mModule->Fail("Cannot find mixin", targetSrc);
  14934. return;
  14935. }
  14936. auto resolvePassData = mModule->mCompiler->mResolvePassData;
  14937. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(targetNameNode)) && (autoComplete->mDefType == NULL))
  14938. {
  14939. autoComplete->mInsertStartIdx = targetNameNode->GetSrcStart();
  14940. autoComplete->mInsertEndIdx = targetNameNode->GetSrcEnd();
  14941. autoComplete->mDefType = methodMatcher.mBestMethodTypeInstance->mTypeDef;
  14942. autoComplete->mDefMethod = methodMatcher.mBestMethodDef;
  14943. autoComplete->SetDefinitionLocation(methodMatcher.mBestMethodDef->GetMethodDeclaration()->mNameNode);
  14944. }
  14945. if ((mModule->mCompiler->mResolvePassData != NULL) && (mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind == BfGetSymbolReferenceKind_Method))
  14946. {
  14947. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() - 1);
  14948. mModule->mCompiler->mResolvePassData->HandleMethodReference(targetNameNode, methodMatcher.mBestMethodTypeInstance->mTypeDef, methodMatcher.mBestMethodDef);
  14949. targetNameNode->SetSrcEnd(targetNameNode->GetSrcEnd() + 1);
  14950. }
  14951. auto curMethodState = mModule->mCurMethodState;
  14952. auto moduleMethodInstance = GetSelectedMethod(targetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  14953. if (!moduleMethodInstance)
  14954. {
  14955. if (methodMatcher.mHasVarArguments)
  14956. {
  14957. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  14958. return;
  14959. }
  14960. mModule->Fail("Failed to get selected mixin", targetSrc);
  14961. return;
  14962. }
  14963. if (!mModule->CheckUseMethodInstance(moduleMethodInstance.mMethodInstance, targetSrc))
  14964. return;
  14965. auto methodInstance = moduleMethodInstance.mMethodInstance;
  14966. PerformCallChecks(methodInstance, targetSrc);
  14967. for (int checkGenericIdx = 0; checkGenericIdx < (int)methodMatcher.mBestMethodGenericArguments.size(); checkGenericIdx++)
  14968. {
  14969. auto& genericParams = methodInstance->mMethodInfoEx->mGenericParams;
  14970. auto genericArg = methodMatcher.mBestMethodGenericArguments[checkGenericIdx];
  14971. if (genericArg->IsVar())
  14972. continue;
  14973. BfAstNode* paramSrc;
  14974. if (methodMatcher.mBestMethodGenericArgumentSrcs.size() == 0)
  14975. paramSrc = targetSrc;
  14976. else
  14977. paramSrc = methodMatcher.mArguments[methodMatcher.mBestMethodGenericArgumentSrcs[checkGenericIdx]].mExpression;
  14978. // Note: don't pass methodMatcher.mBestMethodGenericArguments into here, this method is already specialized
  14979. BfError* error = NULL;
  14980. if (!mModule->CheckGenericConstraints(BfGenericParamSource(methodInstance), genericArg, paramSrc, genericParams[checkGenericIdx], NULL, &error))
  14981. {
  14982. if (methodInstance->mMethodDef->mMethodDeclaration != NULL)
  14983. {
  14984. if (error != NULL)
  14985. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  14986. }
  14987. }
  14988. }
  14989. if (curMethodState->mCurScope->mMixinDepth >= 128)
  14990. {
  14991. mModule->Fail("Maximum nested mixin depth exceeded", targetSrc);
  14992. return;
  14993. }
  14994. // Check circular ref based on methodInstance. We must check the arg types since we could be making progress in mixin evaluation
  14995. // based on method selection within the mixin dependent on args
  14996. {
  14997. bool hasCircularRef = false;
  14998. BfMixinState* checkMixinState = NULL;
  14999. auto checkMethodState = curMethodState;
  15000. while (checkMethodState != NULL)
  15001. {
  15002. auto curMixinState = checkMethodState->mMixinState;
  15003. while (curMixinState != NULL)
  15004. {
  15005. if ((curMixinState->mDoCircularVarResult) && (curMixinState->mMixinMethodInstance == methodInstance))
  15006. {
  15007. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  15008. return;
  15009. }
  15010. if ((!curMixinState->mCheckedCircularRef) && (curMixinState->mMixinMethodInstance == methodInstance))
  15011. {
  15012. checkMixinState = curMixinState;
  15013. checkMixinState->mCheckedCircularRef = true;
  15014. }
  15015. else if (checkMixinState != NULL)
  15016. {
  15017. if ((curMixinState->mMixinMethodInstance == checkMixinState->mMixinMethodInstance) &&
  15018. (curMixinState->mArgTypes == checkMixinState->mArgTypes) &&
  15019. (curMixinState->mArgConsts.mSize == checkMixinState->mArgConsts.mSize))
  15020. {
  15021. bool constsMatch = true;
  15022. for (int i = 0; i < curMixinState->mArgConsts.mSize; i++)
  15023. {
  15024. if (!mModule->mBfIRBuilder->CheckConstEquality(curMixinState->mArgConsts[i], checkMixinState->mArgConsts[i]))
  15025. {
  15026. constsMatch = false;
  15027. break;
  15028. }
  15029. }
  15030. if (constsMatch)
  15031. hasCircularRef = true;
  15032. }
  15033. }
  15034. curMixinState = curMixinState->mPrevMixinState;
  15035. }
  15036. checkMethodState = checkMethodState->mPrevMethodState;
  15037. }
  15038. if (hasCircularRef)
  15039. {
  15040. for (auto argType : checkMixinState->mArgTypes)
  15041. {
  15042. if (argType->IsVar())
  15043. checkMixinState->mDoCircularVarResult = true;
  15044. }
  15045. if (checkMixinState->mDoCircularVarResult)
  15046. {
  15047. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  15048. return;
  15049. }
  15050. mModule->Fail("Circular reference detected between mixins", targetSrc);
  15051. return;
  15052. }
  15053. }
  15054. AddCallDependencies(methodInstance);
  15055. if (!methodMatcher.mBestMethodDef->mIsStatic)
  15056. {
  15057. if ((!target) && (allowImplicitThis))
  15058. target = mModule->GetThis();
  15059. if (!target)
  15060. {
  15061. BfError* error = mModule->Fail(StrFormat("An instance reference is required to invoke the non-static mixin '%s'",
  15062. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  15063. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  15064. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15065. }
  15066. }
  15067. else
  15068. {
  15069. if (target)
  15070. {
  15071. BfError* error = mModule->Fail(StrFormat("Mixin '%s' cannot be accessed with an instance reference; qualify it with a type name instead",
  15072. mModule->MethodToString(methodInstance).c_str()), targetSrc);
  15073. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  15074. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15075. }
  15076. }
  15077. int methodParamCount = (int)methodInstance->GetParamCount();
  15078. // Implicit params are ignored for calling- they should be resolved at the injection site
  15079. int implicitParamCount = methodInstance->GetImplicitParamCount();
  15080. int explicitParamCount = methodParamCount - implicitParamCount;
  15081. while ((int)args.size() < explicitParamCount)
  15082. {
  15083. int argIdx = (int)args.size();
  15084. BfExpression* expr = methodInstance->GetParamInitializer(argIdx);
  15085. if (expr == NULL)
  15086. break;
  15087. _AddArg(expr);
  15088. }
  15089. if ((int)args.size() < explicitParamCount)
  15090. {
  15091. BfError* error = mModule->Fail(StrFormat("Not enough arguments specified, expected %d more.", explicitParamCount - (int)arguments.size()), targetSrc);
  15092. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  15093. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15094. return;
  15095. }
  15096. else if ((int)args.size() > explicitParamCount)
  15097. {
  15098. BfError* error = mModule->Fail(StrFormat("Too many arguments specified, expected %d fewer.", (int)arguments.size() - explicitParamCount), targetSrc);
  15099. if ((error != NULL) && (methodInstance->mMethodDef->GetRefNode() != NULL))
  15100. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  15101. return;
  15102. }
  15103. int paramIdx = implicitParamCount;
  15104. auto argExprEvaluatorItr = argExprEvaluators.begin();
  15105. for (int argIdx = 0; argIdx < (int)args.size(); argIdx++)
  15106. {
  15107. auto exprEvaluator = *argExprEvaluatorItr;
  15108. //auto paramType = methodInstance->GetParamKind(paramIdx);
  15109. BfType* wantType = methodInstance->mParams[paramIdx].mResolvedType;
  15110. auto& arg = args[argIdx];
  15111. if ((arg.mArgFlags & BfArgFlag_VariableDeclaration) != 0)
  15112. {
  15113. arg.mTypedValue = ResolveArgValue(arg, wantType);
  15114. }
  15115. if (wantType->IsGenericParam())
  15116. {
  15117. //
  15118. }
  15119. else if (!wantType->IsVar())
  15120. {
  15121. if (arg.mTypedValue.mType == NULL)
  15122. {
  15123. mModule->AssertErrorState();
  15124. return;
  15125. }
  15126. if (arg.mTypedValue.mType != wantType)
  15127. {
  15128. exprEvaluator->FinishExpressionResult();
  15129. arg.mTypedValue = mModule->LoadValue(arg.mTypedValue);
  15130. arg.mTypedValue = mModule->Cast(arg.mExpression, arg.mTypedValue, wantType);
  15131. /*// Do this to generate default implicit cast error
  15132. mModule->Fail(StrFormat("Mixin argument type '%s' must match parameter type '%s'.",
  15133. mModule->TypeToString(arg.mTypedValue.mType).c_str(),
  15134. mModule->TypeToString(wantType).c_str()), arg.mExpression);
  15135. return;*/
  15136. }
  15137. }
  15138. paramIdx++;
  15139. argExprEvaluatorItr++;
  15140. }
  15141. mModule->AddDependency(methodInstance->GetOwner(), mModule->mCurTypeInstance, BfDependencyMap::DependencyFlag_InlinedCall);
  15142. auto startBlock = mModule->mBfIRBuilder->CreateBlock("mixinStart");
  15143. mModule->mBfIRBuilder->CreateBr(startBlock);
  15144. mModule->mBfIRBuilder->AddBlock(startBlock);
  15145. mModule->mBfIRBuilder->SetInsertPoint(startBlock);
  15146. //auto prevDebugLoc = mModule->mBfIRBuilder->getCurrentDebugLocation();
  15147. // This is so when we debug we can hit a steppoint on the inlined "call line"
  15148. mModule->EmitEnsureInstructionAt();
  15149. auto rootMethodState = mModule->mCurMethodState->GetRootMethodState();
  15150. BfMixinState* mixinState = rootMethodState->mMixinStates.Alloc();
  15151. mixinState->mInjectFilePosition = mModule->mCurFilePosition;
  15152. mixinState->mPrevMixinState = curMethodState->mMixinState;
  15153. mixinState->mLocalsStartIdx = (int)mModule->mCurMethodState->mLocals.size();
  15154. mixinState->mMixinMethodInstance = methodInstance;
  15155. mixinState->mSource = origTargetSrc;
  15156. mixinState->mCallerScope = mModule->mCurMethodState->mCurScope;
  15157. mixinState->mTargetScope = mixinState->mCallerScope;
  15158. mixinState->mResultExpr = NULL;
  15159. mixinState->mHasDeferredUsage = false;
  15160. mixinState->mUsedInvocationScope = false;
  15161. mixinState->mTarget = target;
  15162. auto checkNode = origTargetSrc;
  15163. if (scopedInvocationTarget != NULL)
  15164. {
  15165. auto targetScope = mModule->FindScope(scopedInvocationTarget->mScopeName, curMethodState->mMixinState);
  15166. if (targetScope != NULL)
  15167. {
  15168. mixinState->mTargetScope = targetScope;
  15169. if (autoComplete != NULL)
  15170. {
  15171. if (auto identifer = BfNodeDynCast<BfIdentifierNode>(scopedInvocationTarget->mScopeName))
  15172. autoComplete->CheckLabel(identifer, NULL, targetScope);
  15173. }
  15174. }
  15175. }
  15176. mModule->mBfIRBuilder->SaveDebugLocation();
  15177. SetAndRestoreValue<BfMixinState*> prevMixinState(curMethodState->mMixinState, mixinState);
  15178. BfGetSymbolReferenceKind prevSymbolRefKind = BfGetSymbolReferenceKind_None;
  15179. if (mModule->mCompiler->mResolvePassData != NULL)
  15180. {
  15181. prevSymbolRefKind = mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind;
  15182. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = BfGetSymbolReferenceKind_None;
  15183. }
  15184. defer
  15185. (
  15186. {
  15187. if (mModule->mCompiler->mResolvePassData != NULL)
  15188. mModule->mCompiler->mResolvePassData->mGetSymbolReferenceKind = prevSymbolRefKind;
  15189. }
  15190. );
  15191. auto methodDef = methodInstance->mMethodDef;
  15192. auto methodDeclaration = methodDef->GetMethodDeclaration();
  15193. BfScopeData scopeData;
  15194. scopeData.mCloseNode = methodDeclaration->mBody;
  15195. if (auto block = BfNodeDynCast<BfBlock>(methodDeclaration->mBody))
  15196. {
  15197. if (block->mCloseBrace != NULL)
  15198. scopeData.mCloseNode = block->mCloseBrace;
  15199. }
  15200. curMethodState->AddScope(&scopeData);
  15201. curMethodState->mCurScope->mMixinDepth++;
  15202. // We can't flush scope state because we extend params in as arbitrary values
  15203. mModule->NewScopeState(true, false);
  15204. bool wantsDIData = (mModule->mBfIRBuilder->DbgHasInfo()) && (mModule->mHasFullDebugInfo);
  15205. DISubprogram* diFunction = NULL;
  15206. int startLocalIdx = (int)mModule->mCurMethodState->mLocals.size();
  15207. int endLocalIdx = startLocalIdx;
  15208. if ((wantsDIData) || (mModule->mIsComptimeModule))
  15209. {
  15210. BfIRMDNode diFuncType = mModule->mBfIRBuilder->DbgCreateSubroutineType(methodInstance);
  15211. //int defLine = mModule->mCurFilePosition.mCurLine;
  15212. int flags = 0;
  15213. curMethodState->mCurScope->mDIInlinedAt = mModule->mBfIRBuilder->DbgGetCurrentLocation();
  15214. // 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
  15215. // definitions, so we need to be consistent and use the actual line
  15216. mModule->UpdateSrcPos(methodDeclaration->mNameNode, BfSrcPosFlag_NoSetDebugLoc);
  15217. int defLine = mModule->mCurFilePosition.mCurLine;
  15218. auto diParentType = mModule->mBfIRBuilder->DbgGetTypeInst(methodInstance->GetOwner());
  15219. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  15220. {
  15221. String methodName = methodDef->mName;
  15222. methodName += "!";
  15223. BfMangler::Mangle(methodName, mModule->mCompiler->GetMangleKind(), methodInstance);
  15224. String linkageName;
  15225. if ((mModule->mIsComptimeModule) && (mModule->mCompiler->mCeMachine->mCurBuilder != NULL))
  15226. linkageName = StrFormat("%d", mModule->mCompiler->mCeMachine->mCurBuilder->DbgCreateMethodRef(methodInstance, ""));
  15227. curMethodState->mCurScope->mDIScope = mModule->mBfIRBuilder->DbgCreateFunction(diParentType, methodName, linkageName, mModule->mCurFilePosition.mFileInstance->mDIFile,
  15228. defLine + 1, diFuncType, false, true, mModule->mCurFilePosition.mCurLine + 1, flags, false, BfIRValue());
  15229. scopeData.mAltDIFile = mModule->mCurFilePosition.mFileInstance->mDIFile;
  15230. }
  15231. }
  15232. if (methodDef->mBody != NULL)
  15233. mModule->UpdateSrcPos(methodDef->mBody);
  15234. mModule->SetIllegalSrcPos();
  15235. auto _AddLocalVariable = [&](BfLocalVariable* newLocalVar, BfExprEvaluator* exprEvaluator)
  15236. {
  15237. mModule->SetIllegalSrcPos();
  15238. bool hasConstValue = newLocalVar->mConstValue;
  15239. if (hasConstValue)
  15240. {
  15241. auto constant = mModule->mBfIRBuilder->GetConstant(newLocalVar->mConstValue);
  15242. hasConstValue = constant->mConstType < BfConstType_GlobalVar;
  15243. }
  15244. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL) && (exprEvaluator->mResultLocalVarField == 0))
  15245. {
  15246. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  15247. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  15248. auto inLocalVar = exprEvaluator->mResultLocalVar;
  15249. newLocalVar->mAssignedKind = inLocalVar->mAssignedKind;
  15250. newLocalVar->mUnassignedFieldFlags = inLocalVar->mUnassignedFieldFlags;
  15251. newLocalVar->mReadFromId = inLocalVar->mReadFromId;
  15252. newLocalVar->mIsReadOnly = inLocalVar->mIsReadOnly;
  15253. if ((newLocalVar->mAssignedKind == BfLocalVarAssignKind_None) && (mModule->mCurMethodState->mDeferredLocalAssignData != NULL))
  15254. {
  15255. for (auto deferredAssign : mModule->mCurMethodState->mDeferredLocalAssignData->mAssignedLocals)
  15256. {
  15257. if (deferredAssign.mLocalVar == inLocalVar)
  15258. newLocalVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15259. }
  15260. }
  15261. }
  15262. else
  15263. {
  15264. mModule->AddLocalVariableDef(newLocalVar, hasConstValue);
  15265. }
  15266. if ((wantsDIData) && (!mModule->mBfIRBuilder->mIgnoreWrites))
  15267. {
  15268. bool handled = false;
  15269. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  15270. if (hasConstValue)
  15271. {
  15272. // Already handled
  15273. handled = true;
  15274. }
  15275. else if (newLocalVar->mIsSplat)
  15276. {
  15277. bool found = false;
  15278. auto checkMethodState = mModule->mCurMethodState;
  15279. while ((checkMethodState != NULL) && (!found))
  15280. {
  15281. for (auto localVar : checkMethodState->mLocals)
  15282. {
  15283. if (localVar == newLocalVar)
  15284. continue;
  15285. if (!localVar->mIsSplat)
  15286. continue;
  15287. if (newLocalVar->mValue != localVar->mAddr)
  15288. continue;
  15289. bool isDupName = false;
  15290. for (auto param : methodDef->mParams)
  15291. {
  15292. if (param->mName == localVar->mName)
  15293. {
  15294. isDupName = true;
  15295. break;
  15296. }
  15297. }
  15298. if (isDupName)
  15299. {
  15300. auto splatAgg = mModule->AggregateSplat(BfTypedValue(newLocalVar->mValue, newLocalVar->mResolvedType, BfTypedValueKind_SplatHead));
  15301. // Don't allow alias if one of our args has the same name
  15302. newLocalVar->mIsSplat = false;
  15303. newLocalVar->mValue = BfIRValue();
  15304. if (splatAgg.IsAddr())
  15305. newLocalVar->mAddr = splatAgg.mValue;
  15306. else
  15307. newLocalVar->mValue = splatAgg.mValue;
  15308. found = true;
  15309. break;
  15310. }
  15311. String name = "$";
  15312. name += newLocalVar->mName;
  15313. name += "$alias$";
  15314. name += localVar->mName;
  15315. // auto fakeValue = mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int32, 0);
  15316. // auto diType = mModule->mBfIRBuilder->DbgGetType(mModule->GetPrimitiveType(BfTypeCode_Int32));
  15317. // auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  15318. // name, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  15319. // mModule->mBfIRBuilder->DbgInsertValueIntrinsic(fakeValue, diVariable);
  15320. auto diType = mModule->mBfIRBuilder->DbgGetType(mModule->GetPrimitiveType(BfTypeCode_NullPtr));
  15321. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  15322. name, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  15323. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(mModule->mBfIRBuilder->CreateConstNull(), diVariable);
  15324. handled = true;
  15325. found = true;
  15326. break;
  15327. }
  15328. checkMethodState = checkMethodState->mPrevMethodState;
  15329. }
  15330. }
  15331. if (handled)
  15332. {
  15333. //
  15334. }
  15335. else if ((mModule->IsTargetingBeefBackend()) && (!mModule->mIsComptimeModule))
  15336. {
  15337. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  15338. mModule->SetIllegalSrcPos();
  15339. // With the Beef backend we can assign two variables to the same value, but LLVM does not allow this
  15340. // so we have to create a ref to that variable
  15341. auto diType = mModule->mBfIRBuilder->DbgGetType(newLocalVar->mResolvedType);
  15342. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  15343. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  15344. if (newLocalVar->mIsSplat)
  15345. {
  15346. //TODO: Implement
  15347. }
  15348. else if (newLocalVar->mResolvedType->IsValuelessType())
  15349. {
  15350. // Do nothing
  15351. }
  15352. else
  15353. {
  15354. BfIRValue value = newLocalVar->mValue;
  15355. if (newLocalVar->mAddr)
  15356. value = newLocalVar->mAddr;
  15357. else if (newLocalVar->mConstValue)
  15358. value = newLocalVar->mConstValue;
  15359. auto aliasValue = mModule->mBfIRBuilder->CreateAliasValue(value);
  15360. if (mModule->WantsLifetimes())
  15361. scopeData.mDeferredLifetimeEnds.Add(aliasValue);
  15362. if (newLocalVar->mAddr)
  15363. mModule->mBfIRBuilder->DbgInsertDeclare(aliasValue, diVariable);
  15364. else
  15365. {
  15366. if (newLocalVar->mResolvedType->IsBoolean())
  15367. {
  15368. // Fix case of remote condbr referencing
  15369. newLocalVar->mAddr = mModule->CreateAlloca(newLocalVar->mResolvedType);
  15370. mModule->mBfIRBuilder->CreateStore(newLocalVar->mValue, newLocalVar->mAddr);
  15371. }
  15372. mModule->mBfIRBuilder->DbgInsertValueIntrinsic(aliasValue, diVariable);
  15373. }
  15374. }
  15375. }
  15376. else if (newLocalVar->mAddr)
  15377. {
  15378. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  15379. mModule->SetIllegalSrcPos();
  15380. auto refType = mModule->CreateRefType(newLocalVar->mResolvedType);
  15381. auto allocaVal = mModule->CreateAlloca(refType);
  15382. mModule->mBfIRBuilder->CreateStore(newLocalVar->mAddr, allocaVal);
  15383. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  15384. {
  15385. auto diType = mModule->mBfIRBuilder->DbgGetType(refType);
  15386. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  15387. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  15388. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  15389. }
  15390. }
  15391. else if (newLocalVar->mValue)
  15392. {
  15393. mModule->UpdateSrcPos(methodDeclaration->mNameNode);
  15394. mModule->SetIllegalSrcPos();
  15395. auto localVal = LoadLocal(newLocalVar);
  15396. localVal = mModule->LoadValue(localVal);
  15397. localVal = mModule->AggregateSplat(localVal);
  15398. BfType* allocType = localVal.mType;
  15399. auto allocaVal = mModule->CreateAlloca(allocType);
  15400. mModule->mBfIRBuilder->CreateStore(localVal.mValue, allocaVal);
  15401. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  15402. {
  15403. if (newLocalVar->mIsSplat)
  15404. {
  15405. //TODO: Implement
  15406. }
  15407. else
  15408. {
  15409. auto diType = mModule->mBfIRBuilder->DbgGetType(allocType);
  15410. auto diVariable = mModule->mBfIRBuilder->DbgCreateAutoVariable(mModule->mCurMethodState->mCurScope->mDIScope,
  15411. newLocalVar->mName, mModule->mCurFilePosition.mFileInstance->mDIFile, mModule->mCurFilePosition.mCurLine, diType);
  15412. mModule->mBfIRBuilder->DbgInsertDeclare(allocaVal, diVariable);
  15413. }
  15414. }
  15415. }
  15416. }
  15417. newLocalVar->mParamIdx = -3;
  15418. mixinState->mArgTypes.Add(newLocalVar->mResolvedType);
  15419. if (mModule->mBfIRBuilder->IsConstValue(newLocalVar->mConstValue))
  15420. mixinState->mArgConsts.Add(newLocalVar->mConstValue);
  15421. };
  15422. argExprEvaluatorItr = argExprEvaluators.begin();
  15423. for (int argIdx = methodDef->mIsStatic ? 0 : -1; argIdx < (int)explicitParamCount; argIdx++)
  15424. {
  15425. int paramIdx = argIdx;
  15426. auto exprEvaluator = *argExprEvaluatorItr;
  15427. BfTypedValue argValue;
  15428. BfLocalVariable* localVar = new BfLocalVariable();
  15429. if (argIdx == -1)
  15430. {
  15431. argValue = target;
  15432. localVar->mName = "this";
  15433. localVar->mIsThis = true;
  15434. localVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15435. }
  15436. else
  15437. {
  15438. auto arg = &args[argIdx];
  15439. auto paramDef = methodDef->mParams[paramIdx];
  15440. localVar->mName = paramDef->mName;
  15441. if (!arg->mTypedValue)
  15442. {
  15443. auto wantType = methodInstance->GetParamType(paramIdx);
  15444. if (wantType->IsVar())
  15445. wantType = mModule->mContext->mBfObjectType;
  15446. arg->mTypedValue = mModule->GetDefaultTypedValue(wantType);
  15447. }
  15448. argValue = arg->mTypedValue;
  15449. }
  15450. if (!argValue)
  15451. continue;
  15452. localVar->mResolvedType = argValue.mType;
  15453. if (argValue.mType->IsRef())
  15454. {
  15455. auto refType = (BfRefType*)localVar->mResolvedType;
  15456. localVar->mAddr = mModule->LoadValue(argValue).mValue;
  15457. localVar->mResolvedType = argValue.mType->GetUnderlyingType();
  15458. localVar->mAssignedKind = (refType->mRefKind != BfRefType::RefKind_Out) ? BfLocalVarAssignKind_Unconditional : BfLocalVarAssignKind_None;
  15459. }
  15460. else if (argValue.IsAddr())
  15461. localVar->mAddr = argValue.mValue;
  15462. else
  15463. {
  15464. if (!argValue.mValue)
  15465. {
  15466. // Untyped value
  15467. }
  15468. else if (argValue.mValue.IsConst())
  15469. {
  15470. localVar->mConstValue = argValue.mValue;
  15471. }
  15472. else if (argValue.IsSplat())
  15473. {
  15474. localVar->mValue = argValue.mValue;
  15475. localVar->mIsSplat = true;
  15476. }
  15477. else
  15478. {
  15479. if (argValue.IsAddr())
  15480. localVar->mAddr = argValue.mValue;
  15481. else
  15482. localVar->mValue = argValue.mValue;
  15483. }
  15484. localVar->mIsReadOnly = argValue.IsReadOnly();
  15485. }
  15486. if (argValue.IsReadOnly())
  15487. localVar->mIsReadOnly = true;
  15488. if (argIdx == -1)
  15489. {
  15490. _AddLocalVariable(localVar, NULL);
  15491. }
  15492. else
  15493. {
  15494. _AddLocalVariable(localVar, exprEvaluator);
  15495. endLocalIdx++;
  15496. ++argExprEvaluatorItr;
  15497. }
  15498. }
  15499. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15500. {
  15501. mModule->VisitCodeBlock(blockBody);
  15502. if (mixinState->mResultExpr != NULL)
  15503. {
  15504. if (auto exprNode = BfNodeDynCast<BfExpression>(mixinState->mResultExpr))
  15505. {
  15506. if (!exprNode->IsA<BfBlock>())
  15507. {
  15508. // Mixin expression result
  15509. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_AllowRefExpr));
  15510. mModule->UpdateSrcPos(exprNode);
  15511. VisitChild(exprNode);
  15512. FinishExpressionResult();
  15513. ResolveGenericType();
  15514. }
  15515. }
  15516. }
  15517. GetResult();
  15518. }
  15519. else if (auto expr = BfNodeDynCast<BfExpression>(methodDef->mBody))
  15520. {
  15521. mModule->UpdateSrcPos(expr);
  15522. mResult = mModule->CreateValueFromExpression(expr);
  15523. }
  15524. if (!mResult)
  15525. {
  15526. // If we didn't have an expression body then just make the result "void"
  15527. mResult = BfTypedValue(BfIRValue(), mModule->GetPrimitiveType(BfTypeCode_None));
  15528. }
  15529. mResult = mModule->RemoveRef(mResult);
  15530. if (mResult.IsAddr())
  15531. {
  15532. if (mModule->mCurMethodState->mCurScope->ExtendLifetime(mResult.mValue))
  15533. mModule->mBfIRBuilder->CreateLifetimeSoftEnd(mResult.mValue);
  15534. }
  15535. int localIdx = startLocalIdx;
  15536. argExprEvaluatorItr = argExprEvaluators.begin();
  15537. for (; localIdx < endLocalIdx; localIdx++)
  15538. {
  15539. auto exprEvaluator = *argExprEvaluatorItr;
  15540. BfLocalVariable* localVar = curMethodState->mLocals[localIdx];
  15541. //TODO: Merge unassigned flags together
  15542. if ((exprEvaluator != NULL) && (exprEvaluator->mResultLocalVar != NULL))
  15543. {
  15544. auto inLocalVar = exprEvaluator->mResultLocalVar;
  15545. if (localVar->mAssignedKind != BfLocalVarAssignKind_None)
  15546. inLocalVar->mAssignedKind = BfLocalVarAssignKind_Unconditional;
  15547. if (localVar->mReadFromId != -1)
  15548. inLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  15549. }
  15550. ++argExprEvaluatorItr;
  15551. }
  15552. if (auto blockBody = BfNodeDynCast<BfBlock>(methodDef->mBody))
  15553. {
  15554. if (blockBody->mCloseBrace != NULL)
  15555. mModule->UpdateSrcPos(blockBody->mCloseBrace);
  15556. }
  15557. else if (auto methodDeclaration = BfNodeDynCast<BfMethodDeclaration>(methodDef->mMethodDeclaration))
  15558. {
  15559. if (methodDeclaration->mFatArrowToken != NULL)
  15560. mModule->UpdateSrcPos(methodDeclaration->mFatArrowToken);
  15561. }
  15562. mModule->RestoreScopeState();
  15563. prevMixinState.Restore();
  15564. if ((scopedInvocationTarget != NULL) && (scopedInvocationTarget->mScopeName != NULL) && (!mixinState->mUsedInvocationScope))
  15565. {
  15566. mModule->Warn(0, "Scope specifier was not referenced in mixin", scopedInvocationTarget->mScopeName);
  15567. }
  15568. if (mixinState->mHasDeferredUsage)
  15569. {
  15570. mixinState->mTarget = BfTypedValue();
  15571. // Put deferred mixin states at the front
  15572. BF_ASSERT(rootMethodState->mMixinStates.back() == mixinState);
  15573. rootMethodState->mMixinStates.pop_back();
  15574. rootMethodState->mMixinStates.Insert(0, mixinState);
  15575. }
  15576. else
  15577. {
  15578. BF_ASSERT(rootMethodState->mMixinStates.back() == mixinState);
  15579. rootMethodState->mMixinStates.pop_back();
  15580. delete mixinState;
  15581. }
  15582. mModule->mBfIRBuilder->RestoreDebugLocation();
  15583. mModule->mBfIRBuilder->DupDebugLocation();
  15584. }
  15585. void BfExprEvaluator::SetMethodElementType(BfAstNode* target)
  15586. {
  15587. if (auto delegateBindExpr = BfNodeDynCast<BfDelegateBindExpression>(target))
  15588. {
  15589. SetMethodElementType(delegateBindExpr->mTarget);
  15590. return;
  15591. }
  15592. if (auto lambdaBindExpr = BfNodeDynCast<BfLambdaBindExpression>(target))
  15593. {
  15594. return;
  15595. }
  15596. if (auto attributedIdentifierNode = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  15597. {
  15598. if (attributedIdentifierNode->mIdentifier != NULL)
  15599. mModule->SetElementType(attributedIdentifierNode->mIdentifier, BfSourceElementType_Method);
  15600. }
  15601. else if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(target))
  15602. {
  15603. if (memberReferenceExpr->mMemberName != NULL)
  15604. SetMethodElementType(memberReferenceExpr->mMemberName);
  15605. }
  15606. else if (auto qualifiedNameNode = BfNodeDynCast<BfQualifiedNameNode>(target))
  15607. SetMethodElementType(qualifiedNameNode->mRight);
  15608. else
  15609. mModule->SetElementType(target, BfSourceElementType_Method);
  15610. }
  15611. void BfExprEvaluator::DoInvocation(BfAstNode* target, BfMethodBoundExpression* methodBoundExpr, const BfSizedArray<BfExpression*>& args, const BfMethodGenericArguments& methodGenericArgs, BfTypedValue* outCascadeValue)
  15612. {
  15613. auto methodGenericArguments = methodGenericArgs.mArguments;
  15614. // Just a check
  15615. mModule->mBfIRBuilder->GetInsertBlock();
  15616. bool wasCapturingMethodInfo = false;
  15617. auto autoComplete = GetAutoComplete();
  15618. if ((autoComplete != NULL) && (methodGenericArguments != NULL))
  15619. {
  15620. for (BfAstNode* methodGenericArg : *methodGenericArguments)
  15621. {
  15622. autoComplete->CheckNode(methodGenericArg, false, true);
  15623. }
  15624. }
  15625. if ((autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo))
  15626. {
  15627. // We don't want to capture a call within the target node
  15628. wasCapturingMethodInfo = true;
  15629. autoComplete->mIsCapturingMethodMatchInfo = false;
  15630. }
  15631. bool allowImplicitThis = false;
  15632. BfAstNode* methodNodeSrc = target;
  15633. BfAttributeState attributeState;
  15634. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_Invocation | BfAttributeTargets_MemberAccess);
  15635. if (auto scopedTarget = BfNodeDynCast<BfScopedInvocationTarget>(target))
  15636. {
  15637. target = scopedTarget->mTarget;
  15638. if (autoComplete != NULL)
  15639. {
  15640. if (auto identifier = BfNodeDynCast<BfIdentifierNode>(scopedTarget->mScopeName))
  15641. autoComplete->CheckLabel(identifier, scopedTarget->mColonToken, NULL);
  15642. }
  15643. //mModule->FindScope(scopedTarget->mScopeName);
  15644. }
  15645. bool isCascade = false;
  15646. BfAstNode* cascadeOperatorToken = NULL;
  15647. bool bypassVirtual = false;
  15648. bool gaveUnqualifiedDotError = false;
  15649. String targetFunctionName;
  15650. BfTypedValue thisValue;
  15651. //TODO: This may just be a fully qualified static method name, so let's check that also
  15652. if (auto memberRefExpression = BfNodeDynCast<BfMemberReferenceExpression>(target))
  15653. {
  15654. if (autoComplete != NULL)
  15655. {
  15656. if (memberRefExpression->mTarget != NULL)
  15657. autoComplete->CheckMemberReference(memberRefExpression->mTarget, memberRefExpression->mDotToken, memberRefExpression->mMemberName, false, mExpectingType);
  15658. else if (mExpectingType != NULL)
  15659. {
  15660. String filter;
  15661. if ((autoComplete != NULL) && (autoComplete->InitAutocomplete(memberRefExpression->mDotToken, memberRefExpression->mMemberName, filter)))
  15662. {
  15663. auto typeInst = mExpectingType->ToTypeInstance();
  15664. if (typeInst != NULL)
  15665. {
  15666. String filter;
  15667. if ((memberRefExpression->mMemberName != NULL) && (autoComplete->IsAutocompleteNode(memberRefExpression->mMemberName)))
  15668. filter = autoComplete->GetFilter(memberRefExpression->mMemberName);
  15669. bool allowPrivate = typeInst == mModule->mCurTypeInstance;
  15670. autoComplete->AddEnumTypeMembers(typeInst, filter, false, allowPrivate);
  15671. autoComplete->AddSelfResultTypeMembers(typeInst, typeInst, filter, allowPrivate);
  15672. }
  15673. }
  15674. }
  15675. }
  15676. if ((memberRefExpression->mTarget == NULL) && (memberRefExpression->mMemberName == NULL))
  15677. {
  15678. auto expectingType = mExpectingType;
  15679. if ((expectingType != NULL) && (expectingType->IsNullable()))
  15680. {
  15681. auto underlyingType = expectingType->GetUnderlyingType();
  15682. expectingType = underlyingType;
  15683. }
  15684. if (expectingType != NULL)
  15685. {
  15686. if (expectingType->IsSizedArray())
  15687. {
  15688. if (mModule->mParentNodeEntry != NULL)
  15689. {
  15690. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  15691. {
  15692. InitializedSizedArray((BfSizedArrayType*)expectingType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen);
  15693. return;
  15694. }
  15695. }
  15696. }
  15697. else if ((expectingType->IsStruct()) || (expectingType->IsTypedPrimitive()))
  15698. {
  15699. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  15700. {
  15701. autoComplete->mIsCapturingMethodMatchInfo = true;
  15702. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  15703. }
  15704. if (mModule->mParentNodeEntry != NULL)
  15705. {
  15706. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  15707. {
  15708. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  15709. BfResolveArgsFlags resolveArgsFlags = BfResolveArgsFlag_DeferParamEval;
  15710. ResolveArgValues(argValues, resolveArgsFlags);
  15711. if ((mReceivingValue != NULL) && (mReceivingValue->mType == expectingType) && (mReceivingValue->IsAddr()))
  15712. {
  15713. mResult = *mReceivingValue;
  15714. mReceivingValue = NULL;
  15715. }
  15716. else
  15717. mResult = BfTypedValue(mModule->CreateAlloca(expectingType), expectingType, BfTypedValueKind_TempAddr);
  15718. auto ctorResult = MatchConstructor(target, methodBoundExpr, mResult, expectingType->ToTypeInstance(), argValues, false, false);
  15719. if ((ctorResult) && (!ctorResult.mType->IsVoid()))
  15720. mResult = ctorResult;
  15721. mModule->ValidateAllocation(expectingType, invocationExpr->mTarget);
  15722. return;
  15723. }
  15724. }
  15725. }
  15726. else if (expectingType->IsGenericParam())
  15727. {
  15728. if (mModule->mParentNodeEntry != NULL)
  15729. {
  15730. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  15731. {
  15732. BfResolvedArgs argValues(invocationExpr->mOpenParen, &invocationExpr->mArguments, &invocationExpr->mCommas, invocationExpr->mCloseParen);
  15733. BfResolveArgsFlags resolveArgsFlags = BfResolveArgsFlag_None;
  15734. ResolveArgValues(argValues, resolveArgsFlags);
  15735. CheckGenericCtor((BfGenericParamType*)expectingType, argValues, invocationExpr->mTarget);
  15736. mResult = mModule->GetDefaultTypedValue(expectingType);
  15737. return;
  15738. }
  15739. }
  15740. }
  15741. else if (expectingType->IsVar())
  15742. {
  15743. // Silently allow
  15744. gaveUnqualifiedDotError = true;
  15745. }
  15746. else if (expectingType->IsPrimitiveType())
  15747. {
  15748. // Allow
  15749. }
  15750. else if ((mBfEvalExprFlags & BfEvalExprFlags_AppendFieldInitializer) == 0)
  15751. {
  15752. gaveUnqualifiedDotError = true;
  15753. if (mModule->PreFail())
  15754. mModule->Fail(StrFormat("Cannot use inferred constructor on type '%s'", mModule->TypeToString(expectingType).c_str()), memberRefExpression->mDotToken);
  15755. }
  15756. }
  15757. }
  15758. if (memberRefExpression->IsA<BfBaseExpression>())
  15759. bypassVirtual = true;
  15760. if (memberRefExpression->mMemberName != NULL)
  15761. methodNodeSrc = memberRefExpression->mMemberName;
  15762. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpression->mMemberName))
  15763. {
  15764. if (attrIdentifier->mIdentifier != NULL)
  15765. methodNodeSrc = attrIdentifier->mIdentifier;
  15766. attributeState.mSrc = attrIdentifier->mAttributes;
  15767. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  15768. if (attrIdentifier->mIdentifier != NULL)
  15769. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  15770. }
  15771. else if (memberRefExpression->mMemberName != NULL)
  15772. targetFunctionName = memberRefExpression->mMemberName->ToString();
  15773. if (memberRefExpression->mTarget == NULL)
  15774. {
  15775. if (mExpectingType)
  15776. {
  15777. if (mExpectingType->IsVar())
  15778. {
  15779. }
  15780. mResult = BfTypedValue(mExpectingType);
  15781. }
  15782. else if (!gaveUnqualifiedDotError)
  15783. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", memberRefExpression->mDotToken);
  15784. }
  15785. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpression->mTarget))
  15786. {
  15787. // Static method
  15788. mResult = BfTypedValue(ResolveTypeRef(typeRef));
  15789. }
  15790. if (auto leftIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpression->mTarget))
  15791. {
  15792. bool hadError = false;
  15793. thisValue = LookupIdentifier(leftIdentifier, true, &hadError);
  15794. CheckResultForReading(thisValue);
  15795. if (mPropDef != NULL)
  15796. thisValue = GetResult(true);
  15797. if (hadError)
  15798. {
  15799. mModule->AssertErrorState();
  15800. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  15801. }
  15802. if ((!thisValue) && (mPropDef == NULL))
  15803. {
  15804. // Identifier not found. Static method? Just check speculatively don't throw error
  15805. BfType* type;
  15806. {
  15807. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  15808. type = mModule->ResolveTypeRef(leftIdentifier, NULL, BfPopulateType_DataAndMethods, BfResolveTypeRefFlag_NoResolveGenericParam);
  15809. }
  15810. if (type != NULL)
  15811. thisValue = BfTypedValue(type);
  15812. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(leftIdentifier))
  15813. {
  15814. LookupQualifiedStaticField(qualifiedLeft, true);
  15815. thisValue = mResult;
  15816. mResult = BfTypedValue();
  15817. }
  15818. }
  15819. if (mPropDef != NULL)
  15820. thisValue = GetResult(true);
  15821. if (!thisValue.mType)
  15822. {
  15823. mModule->Fail("Identifier not found", leftIdentifier);
  15824. mModule->CheckTypeRefFixit(leftIdentifier);
  15825. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  15826. }
  15827. if (mResult)
  15828. CheckResultForReading(mResult);
  15829. mResult = thisValue;
  15830. }
  15831. else if (auto expr = BfNodeDynCast<BfExpression>(memberRefExpression->mTarget))
  15832. {
  15833. BfType* expectingTargetType = NULL;
  15834. if (memberRefExpression->mDotToken->mToken == BfToken_DotDot)
  15835. expectingTargetType = mExpectingType;
  15836. bool handled = false;
  15837. if (auto subMemberRefExpr = BfNodeDynCast<BfMemberReferenceExpression>(expr))
  15838. {
  15839. String findName;
  15840. if (subMemberRefExpr->mMemberName != NULL)
  15841. findName = subMemberRefExpr->mMemberName->ToString();
  15842. if (findName == "base") // Generic IFace<T>.base
  15843. {
  15844. thisValue = mModule->GetThis();
  15845. if (thisValue)
  15846. {
  15847. VisitChild(subMemberRefExpr->mTarget);
  15848. if (mResult.HasType())
  15849. {
  15850. if (mResult.mValue)
  15851. {
  15852. mModule->Fail("Type name expected", subMemberRefExpr->mTarget);
  15853. }
  15854. else
  15855. {
  15856. auto type = mResult.mType;
  15857. if (type != NULL)
  15858. {
  15859. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  15860. {
  15861. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  15862. mModule->TypeToString(type).c_str(),
  15863. mModule->TypeToString(thisValue.mType).c_str()), subMemberRefExpr->mTarget);
  15864. }
  15865. else
  15866. {
  15867. if (type->IsInterface())
  15868. {
  15869. thisValue.mType = type;
  15870. }
  15871. else
  15872. {
  15873. auto castedThis = mModule->Cast(subMemberRefExpr->mMemberName, thisValue, type, BfCastFlags_Explicit);
  15874. if (castedThis)
  15875. thisValue = castedThis;
  15876. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  15877. }
  15878. }
  15879. handled = true;
  15880. }
  15881. bypassVirtual = true;
  15882. }
  15883. }
  15884. }
  15885. }
  15886. }
  15887. if (!handled)
  15888. {
  15889. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  15890. auto flags = (BfEvalExprFlags)(BfEvalExprFlags_PropogateNullConditional | BfEvalExprFlags_NoCast);
  15891. if (mFunctionBindResult != NULL)
  15892. {
  15893. if (auto paranExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  15894. {
  15895. // Allow 'ref' on binding, to indicate we want to capture 'this' by reference
  15896. flags = (BfEvalExprFlags)(flags | BfEvalExprFlags_AllowRefExpr);
  15897. expr = paranExpr->mExpression;
  15898. }
  15899. }
  15900. if (expr != NULL)
  15901. mResult = mModule->CreateValueFromExpression(expr, expectingTargetType, flags);
  15902. }
  15903. }
  15904. isCascade = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_DotDot);
  15905. if (isCascade)
  15906. cascadeOperatorToken = memberRefExpression->mDotToken;
  15907. bool isNullCondLookup = (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->GetToken() == BfToken_QuestionDot);
  15908. if (isNullCondLookup)
  15909. mResult = SetupNullConditional(mResult, memberRefExpression->mDotToken);
  15910. if ((mResult.mType == NULL) && (memberRefExpression->mTarget != NULL))
  15911. {
  15912. mModule->AssertErrorState();
  15913. mResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  15914. }
  15915. thisValue = mResult;
  15916. mResult = BfTypedValue();
  15917. if ((thisValue) && (memberRefExpression->mDotToken != NULL) && (memberRefExpression->mDotToken->mToken == BfToken_Arrow))
  15918. thisValue = TryArrowLookup(thisValue, memberRefExpression->mDotToken);
  15919. }
  15920. else if (auto qualifiedName = BfNodeDynCast<BfQualifiedNameNode>(target))
  15921. {
  15922. if (GetAutoComplete() != NULL)
  15923. GetAutoComplete()->CheckMemberReference(qualifiedName->mLeft, qualifiedName->mDot, qualifiedName->mRight);
  15924. if (qualifiedName->mLeft->GetSrcLength() == 4)
  15925. {
  15926. if (CheckIsBase(qualifiedName->mLeft))
  15927. bypassVirtual = true;
  15928. }
  15929. if (qualifiedName->mRight != NULL)
  15930. methodNodeSrc = qualifiedName->mRight;
  15931. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(qualifiedName->mRight))
  15932. {
  15933. if (attrIdentifier->mIdentifier != NULL)
  15934. methodNodeSrc = attrIdentifier->mIdentifier;
  15935. attributeState.mSrc = attrIdentifier->mAttributes;
  15936. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  15937. targetFunctionName = attrIdentifier->mIdentifier->ToString();
  15938. }
  15939. else
  15940. targetFunctionName = qualifiedName->mRight->ToString();
  15941. bool hadError = false;
  15942. thisValue = LookupIdentifier(qualifiedName->mLeft, true, &hadError);
  15943. CheckResultForReading(thisValue);
  15944. if (mPropDef != NULL)
  15945. thisValue = GetResult(true);
  15946. if (hadError)
  15947. {
  15948. mModule->AssertErrorState();
  15949. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  15950. }
  15951. if ((!thisValue) && (mPropDef == NULL))
  15952. {
  15953. // Identifier not found. Static method? Just check speculatively don't throw error
  15954. BfType* type;
  15955. {
  15956. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  15957. type = mModule->ResolveTypeRef(qualifiedName->mLeft, NULL, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowGlobalContainer | BfResolveTypeRefFlag_IgnoreLookupError));
  15958. }
  15959. if (type == NULL)
  15960. {
  15961. //SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, true);
  15962. type = mModule->ResolveTypeRef(qualifiedName, methodGenericArguments, BfPopulateType_DataAndMethods, (BfResolveTypeRefFlags)(BfResolveTypeRefFlag_NoResolveGenericParam | BfResolveTypeRefFlag_AllowGlobalContainer | BfResolveTypeRefFlag_IgnoreLookupError));
  15963. if (type != NULL)
  15964. {
  15965. // This is a CTOR call, treat it as such
  15966. targetFunctionName.clear();
  15967. }
  15968. }
  15969. if (type != NULL)
  15970. thisValue = BfTypedValue(type);
  15971. else if (auto qualifiedLeft = BfNodeDynCast<BfQualifiedNameNode>(qualifiedName->mLeft))
  15972. {
  15973. String findName = qualifiedLeft->mRight->ToString();
  15974. bool handled = false;
  15975. if (findName == "base")
  15976. {
  15977. auto type = mModule->ResolveTypeRef(qualifiedLeft->mLeft, NULL, BfPopulateType_Data, BfResolveTypeRefFlag_AllowRef);
  15978. mModule->CheckTypeRefFixit(qualifiedLeft->mLeft);
  15979. thisValue = mModule->GetThis();
  15980. if (type != NULL)
  15981. {
  15982. if ((thisValue.mType == type) || (!mModule->TypeIsSubTypeOf(thisValue.mType->ToTypeInstance(), type->ToTypeInstance())))
  15983. {
  15984. mModule->Fail(StrFormat("Type '%s' is not a base type of '%s'",
  15985. mModule->TypeToString(type).c_str(),
  15986. mModule->TypeToString(thisValue.mType).c_str()), qualifiedLeft->mLeft);
  15987. }
  15988. else
  15989. {
  15990. if (type->IsInterface())
  15991. {
  15992. thisValue.mType = type;
  15993. }
  15994. else
  15995. {
  15996. auto castedThis = mModule->Cast(qualifiedLeft->mRight, thisValue, type, BfCastFlags_Explicit);
  15997. if (castedThis)
  15998. thisValue = castedThis;
  15999. //mModule->Fail("Explicit base types can only be used for specifying default interface members", qualifiedLeft->mLeft);
  16000. }
  16001. }
  16002. handled = true;
  16003. }
  16004. bypassVirtual = true;
  16005. }
  16006. if (!handled)
  16007. {
  16008. LookupQualifiedStaticField(qualifiedLeft, true);
  16009. thisValue = mResult;
  16010. mResult = BfTypedValue();
  16011. }
  16012. }
  16013. }
  16014. if (mPropDef != NULL)
  16015. thisValue = GetResult(true);
  16016. if (!thisValue.mType)
  16017. {
  16018. mModule->Fail("Identifier not found", qualifiedName->mLeft);
  16019. mModule->CheckTypeRefFixit(qualifiedName->mLeft);
  16020. mModule->CheckIdentifierFixit(qualifiedName->mLeft);
  16021. thisValue = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  16022. }
  16023. if (mResult)
  16024. CheckResultForReading(mResult);
  16025. mResult = BfTypedValue();
  16026. }
  16027. else if (auto identiferExpr = BfNodeDynCast<BfIdentifierNode>(target))
  16028. {
  16029. if (auto attrIdentifier = BfNodeDynCast<BfAttributedIdentifierNode>(target))
  16030. {
  16031. if (attrIdentifier->mIdentifier != NULL)
  16032. methodNodeSrc = attrIdentifier->mIdentifier;
  16033. attributeState.mSrc = attrIdentifier->mAttributes;
  16034. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifier->mAttributes, attributeState.mTarget);
  16035. }
  16036. allowImplicitThis = true;
  16037. if (autoComplete != NULL)
  16038. autoComplete->CheckIdentifier(identiferExpr);
  16039. targetFunctionName = target->ToString();
  16040. if (targetFunctionName == "PrintF") // Just directly call that one
  16041. {
  16042. BfType* charType = mModule->GetPrimitiveType(BfTypeCode_Char8);
  16043. BfType* charPtrType = mModule->CreatePointerType(charType);
  16044. auto func = mModule->GetBuiltInFunc(BfBuiltInFuncType_PrintF);
  16045. SizedArray<BfIRValue, 4> irArgs;
  16046. for (BfExpression* arg : args)
  16047. {
  16048. BfTypedValue value;
  16049. if (arg != NULL)
  16050. value = mModule->CreateValueFromExpression(arg);
  16051. if (!value)
  16052. return;
  16053. auto typeInst = value.mType->ToTypeInstance();
  16054. if ((typeInst != NULL) && (typeInst->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  16055. value = mModule->Cast(arg, value, charPtrType);
  16056. if ((value.mType->IsFloat()) && (value.mType->mSize != 8)) // Always cast float to double
  16057. value = mModule->Cast(arg, value, mModule->GetPrimitiveType(BfTypeCode_Double));
  16058. irArgs.push_back(value.mValue);
  16059. }
  16060. if ((targetFunctionName != "PrintF") || (irArgs.size() > 0))
  16061. {
  16062. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCall(func, irArgs/*, targetFunctionName*/),
  16063. mModule->ResolveTypeDef(mModule->mSystem->mTypeInt32));
  16064. }
  16065. return;
  16066. }
  16067. if (auto ceDbgState = mModule->GetCeDbgState())
  16068. {
  16069. if (targetFunctionName.StartsWith("__"))
  16070. {
  16071. auto ceDebugger = mModule->mCompiler->mCeMachine->mDebugger;
  16072. auto _ResolveArg = [&](int argIdx, BfType* type = NULL)
  16073. {
  16074. if ((argIdx < 0) || (argIdx >= args.mSize))
  16075. return BfTypedValue();
  16076. return mModule->CreateValueFromExpression(args[argIdx], type);
  16077. };
  16078. if (targetFunctionName == "__getHighBits")
  16079. {
  16080. auto typedVal = _ResolveArg(0);
  16081. if ((typedVal) && (typedVal.mType->IsPrimitiveType()))
  16082. {
  16083. auto primType = (BfPrimitiveType*)typedVal.mType;
  16084. int64 val = ceDebugger->ValueToInt(typedVal);
  16085. int64 bitCount = ceDebugger->ValueToInt(_ResolveArg(1));
  16086. int64 resultVal = val >> (typedVal.mType->mSize * 8 - bitCount);
  16087. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)resultVal), typedVal.mType);
  16088. return;
  16089. }
  16090. }
  16091. else if (targetFunctionName == "__clearHighBits")
  16092. {
  16093. auto typedVal = _ResolveArg(0);
  16094. if ((typedVal) && (typedVal.mType->IsPrimitiveType()))
  16095. {
  16096. auto primType = (BfPrimitiveType*)typedVal.mType;
  16097. int64 val = ceDebugger->ValueToInt(typedVal);
  16098. int64 bitCount = ceDebugger->ValueToInt(_ResolveArg(1));
  16099. int64 andBits = (0x8000000000000000LL) >> ((typedVal.mType->mSize - 8) * 8 + bitCount - 1);
  16100. int64 resultVal = val & ~andBits;
  16101. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(primType->mTypeDef->mTypeCode, (uint64)resultVal), typedVal.mType);
  16102. return;
  16103. }
  16104. }
  16105. else if ((targetFunctionName == "__cast") || (targetFunctionName == "__bitcast"))
  16106. {
  16107. BfType* type = NULL;
  16108. String typeName;
  16109. for (int argIdx = 0; argIdx < args.mSize - 1; argIdx++)
  16110. {
  16111. auto arg = _ResolveArg(argIdx);
  16112. if (!arg)
  16113. continue;
  16114. if (arg.mType->IsInstanceOf(mModule->mCompiler->mStringTypeDef))
  16115. {
  16116. auto strPtr = mModule->GetStringPoolString(arg.mValue, mModule->mBfIRBuilder);
  16117. if (strPtr != NULL)
  16118. {
  16119. if ((type != NULL) && (*strPtr == "*"))
  16120. {
  16121. type = mModule->CreatePointerType(type);
  16122. }
  16123. else
  16124. typeName += *strPtr;
  16125. }
  16126. }
  16127. if (arg.mType->IsInteger())
  16128. {
  16129. int64 intVal = ceDebugger->ValueToInt(arg);
  16130. if (typeName.IsEmpty())
  16131. {
  16132. auto typeType = mModule->ResolveTypeDef(mModule->mCompiler->mTypeTypeDef)->ToTypeInstance();
  16133. auto fieldDef = typeType->mTypeDef->GetFieldByName("mTypeId");
  16134. if (fieldDef != NULL)
  16135. {
  16136. int typeId = ceDebugger->ReadMemory<int>((intptr)intVal + typeType->mFieldInstances[fieldDef->mIdx].mDataOffset);
  16137. type = mModule->mContext->FindTypeById(typeId);
  16138. }
  16139. }
  16140. else
  16141. typeName += StrFormat("%lld", intVal);
  16142. }
  16143. }
  16144. auto fromTypedVal = _ResolveArg(args.mSize - 1);
  16145. if (!typeName.IsEmpty())
  16146. type = ceDebugger->FindType(typeName);
  16147. if (type != NULL)
  16148. {
  16149. if (targetFunctionName == "__bitcast")
  16150. {
  16151. if ((type->IsObjectOrInterface()) || (type->IsPointer()))
  16152. {
  16153. auto ceAddrVal = ceDebugger->GetAddr(fromTypedVal);
  16154. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIntToPtr(ceAddrVal.mAddr, mModule->mBfIRBuilder->MapType(type)), type);
  16155. }
  16156. else
  16157. {
  16158. Array<uint8> memArr;
  16159. memArr.Resize(BF_MAX(type->mSize, fromTypedVal.mType->mSize));
  16160. mModule->mBfIRBuilder->WriteConstant(fromTypedVal.mValue, memArr.mVals, fromTypedVal.mType);
  16161. auto newVal = mModule->mBfIRBuilder->ReadConstant(memArr.mVals, type);
  16162. mResult = BfTypedValue(newVal, type);
  16163. }
  16164. }
  16165. else
  16166. mResult = mModule->Cast(target, fromTypedVal, type, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_SilentFail));
  16167. }
  16168. return;
  16169. }
  16170. else if (targetFunctionName == "__stringView")
  16171. {
  16172. auto ptrVal = _ResolveArg(0);
  16173. auto sizeVal = _ResolveArg(1);
  16174. if (ceDbgState->mFormatInfo != NULL)
  16175. ceDbgState->mFormatInfo->mOverrideCount = (int)ceDebugger->ValueToInt(sizeVal);
  16176. mResult = ptrVal;
  16177. return;
  16178. }
  16179. else if ((targetFunctionName == "__funcName") || (targetFunctionName == "__funcTarget"))
  16180. {
  16181. auto addrVal = _ResolveArg(0);
  16182. auto ceAddrVal = ceDebugger->GetAddr(addrVal);
  16183. CeFunction* ceFunction = NULL;
  16184. int functionId = 0;
  16185. if (mModule->mSystem->mPtrSize == 4)
  16186. {
  16187. functionId = (int)addrVal;
  16188. }
  16189. else
  16190. {
  16191. CeFunction* checkCeFunction = (CeFunction*)ceAddrVal.mAddr;
  16192. functionId = checkCeFunction->SafeGetId();
  16193. }
  16194. if (mModule->mCompiler->mCeMachine->mFunctionIdMap.TryGetValue(functionId, &ceFunction))
  16195. {
  16196. BfMethodInstance* methodInstance = ceFunction->mMethodInstance;
  16197. if (methodInstance != NULL)
  16198. {
  16199. if (targetFunctionName == "__funcTarget")
  16200. {
  16201. BfType* targetType = methodInstance->GetOwner();
  16202. if (targetType->IsValueType())
  16203. targetType = mModule->CreatePointerType(targetType);
  16204. auto targetVal = _ResolveArg(1);
  16205. auto ceTargetVal = ceDebugger->GetAddr(targetVal);
  16206. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIntToPtr(ceTargetVal.mAddr, mModule->mBfIRBuilder->MapType(targetType)), targetType);
  16207. return;
  16208. }
  16209. else
  16210. {
  16211. mResult = BfTypedValue(mModule->GetStringObjectValue(mModule->MethodToString(methodInstance)),
  16212. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  16213. return;
  16214. }
  16215. }
  16216. else if ((ceFunction->mCeInnerFunctionInfo != NULL) && (targetFunctionName == "__funcName"))
  16217. {
  16218. mResult = BfTypedValue(mModule->GetStringObjectValue(BfDemangler::Demangle(ceFunction->mCeInnerFunctionInfo->mName, DbgLanguage_Beef)),
  16219. mModule->ResolveTypeDef(mModule->mCompiler->mStringTypeDef));
  16220. return;
  16221. }
  16222. }
  16223. if (targetFunctionName == "__funcTarget")
  16224. mResult = _ResolveArg(1);
  16225. else
  16226. mResult = addrVal;
  16227. return;
  16228. }
  16229. }
  16230. }
  16231. }
  16232. else if (auto expr = BfNodeDynCast<BfExpression>(target))
  16233. {
  16234. auto innerInvocationResult = mModule->CreateValueFromExpression(expr);
  16235. if (!innerInvocationResult)
  16236. {
  16237. mModule->AssertErrorState();
  16238. innerInvocationResult = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16239. }
  16240. if (innerInvocationResult.mType->IsVar())
  16241. {
  16242. mResult = innerInvocationResult;
  16243. return;
  16244. }
  16245. targetFunctionName = "Invoke";
  16246. if (innerInvocationResult.mType->IsTypeInstance())
  16247. {
  16248. auto invocationTypeInst = innerInvocationResult.mType->ToTypeInstance();
  16249. if ((invocationTypeInst->mTypeDef->mIsDelegate) || (invocationTypeInst->mTypeDef->mIsFunction))
  16250. {
  16251. thisValue = innerInvocationResult;
  16252. }
  16253. }
  16254. if (!thisValue)
  16255. {
  16256. mModule->Fail(StrFormat("Cannot perform invocation on type '%s'", mModule->TypeToString(innerInvocationResult.mType).c_str()), expr);
  16257. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16258. }
  16259. }
  16260. else
  16261. {
  16262. mModule->Fail("Invalid invocation target", target);
  16263. thisValue = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  16264. }
  16265. if ((wasCapturingMethodInfo) && (autoComplete->mMethodMatchInfo != NULL))
  16266. {
  16267. autoComplete->mIsCapturingMethodMatchInfo = true;
  16268. BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  16269. }
  16270. SetAndRestoreValue<BfAttributeState*> prevAttributeState;
  16271. if (attributeState.mCustomAttributes != NULL)
  16272. prevAttributeState.Init(mModule->mAttributeState, &attributeState);
  16273. if ((targetFunctionName != "") && (targetFunctionName[targetFunctionName.length() - 1] == '!'))
  16274. {
  16275. targetFunctionName = targetFunctionName.Substring(0, targetFunctionName.length() - 1);
  16276. InjectMixin(methodNodeSrc, thisValue, allowImplicitThis, targetFunctionName, args, methodGenericArgs);
  16277. return;
  16278. }
  16279. //TODO: We removed this... Messed up with PrimStruct 'this' non-mut errors
  16280. // 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
  16281. /*if (thisValue)
  16282. {
  16283. if ((!thisValue.mType->IsGenericParam()) && (!thisValue.IsSplat()) && (!thisValue.mType->IsVar()))
  16284. thisValue = MakeCallableTarget(target, thisValue);
  16285. }*/
  16286. int methodCount = 0;
  16287. bool mayBeSkipCall = false;
  16288. bool mayBeComptimeCall = false;
  16289. if (thisValue.mType != NULL)
  16290. {
  16291. if (thisValue.mType->IsAllocType())
  16292. thisValue.mType = thisValue.mType->GetUnderlyingType();
  16293. auto checkTypeInst = thisValue.mType->ToTypeInstance();
  16294. while (checkTypeInst != NULL)
  16295. {
  16296. checkTypeInst->mTypeDef->PopulateMemberSets();
  16297. BfMemberSetEntry* memberSetEntry;
  16298. if (checkTypeInst->mTypeDef->mMethodSet.TryGetWith(targetFunctionName, &memberSetEntry))
  16299. {
  16300. BfMethodDef* methodDef = (BfMethodDef*)memberSetEntry->mMemberDef;
  16301. while (methodDef != NULL)
  16302. {
  16303. if (methodDef->mIsSkipCall)
  16304. mayBeSkipCall = true;
  16305. if (methodDef->mHasComptime)
  16306. mayBeComptimeCall = true;
  16307. methodDef = methodDef->mNextWithSameName;
  16308. }
  16309. }
  16310. checkTypeInst = checkTypeInst->mBaseType;
  16311. }
  16312. }
  16313. SizedArray<BfExpression*, 8> copiedArgs;
  16314. for (BfExpression* arg : args)
  16315. copiedArgs.push_back(arg);
  16316. BfSizedArray<BfExpression*> sizedCopiedArgs(copiedArgs);
  16317. BfResolvedArgs argValues(&sizedCopiedArgs);
  16318. if (mModule->mParentNodeEntry != NULL)
  16319. {
  16320. if (auto invocationExpr = BfNodeDynCast<BfInvocationExpression>(mModule->mParentNodeEntry->mNode))
  16321. {
  16322. argValues.mOpenToken = invocationExpr->mOpenParen;
  16323. argValues.mCommas = &invocationExpr->mCommas;
  16324. argValues.mCloseToken = invocationExpr->mCloseParen;
  16325. }
  16326. }
  16327. BfResolveArgsFlags resolveArgsFlags = (BfResolveArgsFlags)(BfResolveArgsFlag_DeferFixits | BfResolveArgsFlag_AllowUnresolvedTypes);
  16328. resolveArgsFlags = (BfResolveArgsFlags)(resolveArgsFlags | BfResolveArgsFlag_DeferParamEval);
  16329. if ((mayBeSkipCall) || (mayBeComptimeCall))
  16330. resolveArgsFlags = (BfResolveArgsFlags)(resolveArgsFlags | BfResolveArgsFlag_DeferParamValues);
  16331. static int sCallIdx = 0;
  16332. sCallIdx++;
  16333. int callIdx = sCallIdx;
  16334. if (callIdx == 1557)
  16335. {
  16336. NOP;
  16337. }
  16338. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  16339. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  16340. {
  16341. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  16342. {
  16343. checkedKind = BfCheckedKind_Checked;
  16344. mModule->mAttributeState->mUsed = true;
  16345. }
  16346. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  16347. {
  16348. checkedKind = BfCheckedKind_Unchecked;
  16349. mModule->mAttributeState->mUsed = true;
  16350. }
  16351. }
  16352. if ((isCascade) && (cascadeOperatorToken != NULL) && ((mBfEvalExprFlags & BfEvalExprFlags_Comptime) != 0))
  16353. mModule->Fail("Cascade operator cannot be used in const evaluation", cascadeOperatorToken);
  16354. SetAndRestoreValue<bool> prevUsedAsStatement(mUsedAsStatement, mUsedAsStatement || isCascade);
  16355. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlags(mBfEvalExprFlags);
  16356. if (isCascade)
  16357. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_InCascade);
  16358. ResolveArgValues(argValues, resolveArgsFlags);
  16359. //
  16360. {
  16361. // We also apply this right before the actual call, but we need to set the comptime flag earlier
  16362. SetAndRestoreValue<BfEvalExprFlags> prevEvalExprFlag(mBfEvalExprFlags);
  16363. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL) && (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mConstEvalAttributeTypeDef)))
  16364. {
  16365. mModule->mAttributeState->mUsed = true;
  16366. mBfEvalExprFlags = (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_Comptime);
  16367. }
  16368. mResult = MatchMethod(methodNodeSrc, methodBoundExpr, thisValue, allowImplicitThis, bypassVirtual, targetFunctionName, argValues, methodGenericArgs, checkedKind);
  16369. }
  16370. argValues.HandleFixits(mModule);
  16371. if (mModule->mAttributeState == &attributeState)
  16372. mModule->FinishAttributeState(&attributeState);
  16373. if (isCascade)
  16374. {
  16375. if ((outCascadeValue != NULL) && (thisValue.mValue))
  16376. {
  16377. *outCascadeValue = thisValue;
  16378. }
  16379. else
  16380. {
  16381. mModule->Fail("Invalid use of cascade operator", cascadeOperatorToken);
  16382. }
  16383. }
  16384. }
  16385. void BfExprEvaluator::Visit(BfInvocationExpression* invocationExpr)
  16386. {
  16387. BfAutoParentNodeEntry autoParentNodeEntry(mModule, invocationExpr);
  16388. // We need to check for sized array constructor like "uint8[2](1, 2)"
  16389. if (BfNodeDynCastExact<BfIndexerExpression>(invocationExpr->mTarget) != NULL)
  16390. {
  16391. auto checkTarget = invocationExpr->mTarget;
  16392. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  16393. {
  16394. checkTarget = indexerExpr->mTarget;
  16395. }
  16396. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  16397. auto resolvedType = mModule->ResolveTypeRef(checkTarget, NULL, BfPopulateType_Identity);
  16398. prevIgnoreError.Restore();
  16399. if (resolvedType != NULL)
  16400. {
  16401. BfType* curType = resolvedType;
  16402. auto checkTarget = invocationExpr->mTarget;
  16403. while (auto indexerExpr = BfNodeDynCastExact<BfIndexerExpression>(checkTarget))
  16404. {
  16405. checkTarget = indexerExpr->mTarget;
  16406. if (indexerExpr->mCommas.size() != 0)
  16407. 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]);
  16408. int arrSize = 0;
  16409. BfTypeState typeState;
  16410. typeState.mArrayInitializerSize = (int)invocationExpr->mArguments.size();
  16411. SetAndRestoreValue<BfTypeState*> prevTypeState(mModule->mContext->mCurTypeState, &typeState);
  16412. if (indexerExpr->mArguments.size() != 0)
  16413. {
  16414. BfConstResolver constResolver(mModule);
  16415. auto arg = indexerExpr->mArguments[0];
  16416. constResolver.mExpectingType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  16417. if (arg != NULL)
  16418. constResolver.Resolve(arg, NULL, BfConstResolveFlag_ArrayInitSize);
  16419. if (constResolver.mResult.mValue.IsConst())
  16420. {
  16421. auto constant = mModule->mBfIRBuilder->GetConstant(constResolver.mResult.mValue);
  16422. if ((mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 >= 0))
  16423. {
  16424. arrSize = constant->mInt32;
  16425. }
  16426. else
  16427. mModule->Fail("Non-negative integer expected", indexerExpr->mArguments[0]);
  16428. }
  16429. }
  16430. else
  16431. arrSize = invocationExpr->mArguments.size();
  16432. curType = mModule->CreateSizedArrayType(curType, arrSize);
  16433. }
  16434. InitializedSizedArray((BfSizedArrayType*)curType, invocationExpr->mOpenParen, invocationExpr->mArguments, invocationExpr->mCommas, invocationExpr->mCloseParen, NULL);
  16435. return;
  16436. }
  16437. }
  16438. auto autoComplete = GetAutoComplete();
  16439. auto wasCapturingMethodInfo = (autoComplete != NULL) && (autoComplete->mIsCapturingMethodMatchInfo);
  16440. if (autoComplete != NULL)
  16441. autoComplete->CheckInvocation(invocationExpr, invocationExpr->mOpenParen, invocationExpr->mCloseParen, invocationExpr->mCommas);
  16442. mModule->UpdateExprSrcPos(invocationExpr);
  16443. BfMethodGenericArguments methodGenericArgs;
  16444. if (invocationExpr->mGenericArgs != NULL)
  16445. {
  16446. methodGenericArgs.mArguments = &invocationExpr->mGenericArgs->mGenericArgs;
  16447. if ((!invocationExpr->mGenericArgs->mCommas.IsEmpty()) && (invocationExpr->mGenericArgs->mCommas.back()->mToken == BfToken_DotDotDot))
  16448. {
  16449. methodGenericArgs.mIsOpen = true;
  16450. methodGenericArgs.mIsPartial = true;
  16451. }
  16452. for (int i = 0; i < (int)methodGenericArgs.mArguments->mSize; i++)
  16453. if (BfNodeIsA<BfUninitializedExpression>((*methodGenericArgs.mArguments)[i]))
  16454. methodGenericArgs.mIsPartial = true;
  16455. }
  16456. SizedArray<BfExpression*, 8> copiedArgs;
  16457. for (BfExpression* arg : invocationExpr->mArguments)
  16458. copiedArgs.push_back(arg);
  16459. BfTypedValue cascadeValue;
  16460. DoInvocation(invocationExpr->mTarget, invocationExpr, copiedArgs, methodGenericArgs, &cascadeValue);
  16461. if (autoComplete != NULL)
  16462. {
  16463. if ((wasCapturingMethodInfo) && (!autoComplete->mIsCapturingMethodMatchInfo))
  16464. {
  16465. if (autoComplete->mMethodMatchInfo != NULL)
  16466. autoComplete->mIsCapturingMethodMatchInfo = true;
  16467. else
  16468. autoComplete->mIsCapturingMethodMatchInfo = false;
  16469. //BF_ASSERT(autoComplete->mMethodMatchInfo != NULL);
  16470. }
  16471. else
  16472. autoComplete->mIsCapturingMethodMatchInfo = false;
  16473. }
  16474. /// Previous check for discard
  16475. if (cascadeValue)
  16476. mResult = cascadeValue;
  16477. }
  16478. BfMethodDef* BfExprEvaluator::GetPropertyMethodDef(BfPropertyDef* propDef, BfMethodType methodType, BfCheckedKind checkedKind, BfTypedValue propTarget)
  16479. {
  16480. bool allowMut = true;
  16481. if ((propTarget) && (propTarget.mType->IsValueType()))
  16482. {
  16483. if (propTarget.IsReadOnly())
  16484. {
  16485. allowMut = false;
  16486. }
  16487. else if (!propTarget.IsAddr())
  16488. {
  16489. mModule->PopulateType(propTarget.mType);
  16490. if (!propTarget.IsValuelessType())
  16491. allowMut = false;
  16492. }
  16493. }
  16494. int bestPri = -1000;
  16495. BfMethodDef* matchedMethod = NULL;
  16496. for (auto methodDef : propDef->mMethods)
  16497. {
  16498. if (methodDef->mMethodType != methodType)
  16499. continue;
  16500. int curPri = 0;
  16501. if (methodDef->mCheckedKind == checkedKind)
  16502. {
  16503. curPri = 5;
  16504. }
  16505. else if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  16506. curPri = 3;
  16507. else
  16508. curPri = 1;
  16509. if (methodDef->mIsMutating)
  16510. {
  16511. if (allowMut)
  16512. curPri++;
  16513. else
  16514. curPri -= 10;
  16515. }
  16516. if (curPri > bestPri)
  16517. {
  16518. bestPri = curPri;
  16519. matchedMethod = methodDef;
  16520. }
  16521. }
  16522. return matchedMethod;
  16523. /*BfMethodDef* matchedMethod = NULL;
  16524. BfMethodDef* backupMethod = NULL;
  16525. for (auto methodDef : propDef->mMethods)
  16526. {
  16527. if (methodDef->mMethodType != methodType)
  16528. continue;
  16529. if (methodDef->mCheckedKind == checkedKind)
  16530. {
  16531. matchedMethod = methodDef;
  16532. break;
  16533. }
  16534. if ((checkedKind == BfCheckedKind_NotSet) && (methodDef->mCheckedKind == mModule->GetDefaultCheckedKind()))
  16535. matchedMethod = methodDef;
  16536. else
  16537. backupMethod = methodDef;
  16538. }
  16539. if (matchedMethod == NULL)
  16540. matchedMethod = backupMethod;
  16541. return matchedMethod;*/
  16542. }
  16543. BfModuleMethodInstance BfExprEvaluator::GetPropertyMethodInstance(BfMethodDef* methodDef)
  16544. {
  16545. if (mPropDefBypassVirtual)
  16546. {
  16547. if (mPropTarget.mType->IsInterface())
  16548. {
  16549. auto curTypeInst = mPropTarget.mType->ToTypeInstance();
  16550. if (mModule->TypeIsSubTypeOf(mModule->mCurTypeInstance, curTypeInst))
  16551. {
  16552. if (methodDef->mBody != NULL)
  16553. {
  16554. // This is an explicit call to a default static interface method. We pull the methodDef into our own concrete type.
  16555. mPropTarget = mModule->GetThis();
  16556. return mModule->GetMethodInstance(mModule->mCurTypeInstance, methodDef, BfTypeVector(), BfGetMethodInstanceFlag_ForeignMethodDef, curTypeInst);
  16557. }
  16558. }
  16559. else
  16560. {
  16561. mModule->Fail("Property is not implemented by this type", mPropSrc);
  16562. return BfModuleMethodInstance();
  16563. }
  16564. }
  16565. else
  16566. {
  16567. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  16568. mModule->PopulateType(propTypeInst, BfPopulateType_DataAndMethods);
  16569. auto rawMethodInstance = mModule->GetRawMethodInstance(propTypeInst, methodDef);
  16570. if (rawMethodInstance->mVirtualTableIdx == -1)
  16571. {
  16572. if (!mModule->mCompiler->mIsResolveOnly)
  16573. {
  16574. // ResolveOnly does not force methods to slot
  16575. BF_ASSERT(rawMethodInstance->mVirtualTableIdx != -1);
  16576. mModule->Fail(StrFormat("Failed to devirtualize %s", mModule->MethodToString(rawMethodInstance).c_str()));
  16577. }
  16578. }
  16579. else
  16580. {
  16581. auto useTypeInst = mOrigPropTarget.mType->ToTypeInstance();
  16582. auto virtualMethod = (BfMethodInstance*)useTypeInst->mVirtualMethodTable[rawMethodInstance->mVirtualTableIdx].mImplementingMethod;
  16583. return mModule->ReferenceExternalMethodInstance(virtualMethod);
  16584. }
  16585. }
  16586. }
  16587. if ((mOrigPropTarget) && (mOrigPropTarget.mType != mPropTarget.mType) &&
  16588. ((!mOrigPropTarget.mType->IsGenericParam()) && (mPropTarget.mType->IsInterface())))
  16589. {
  16590. auto checkType = mOrigPropTarget.mType;
  16591. if ((checkType->IsNullable()) && (!mPropTarget.mType->IsNullable()))
  16592. checkType = checkType->GetUnderlyingType();
  16593. if (checkType->IsPointer())
  16594. checkType = ((BfPointerType*)checkType)->mElementType;
  16595. if (checkType->IsWrappableType())
  16596. checkType = mModule->GetWrappedStructType(checkType);
  16597. if ((checkType != NULL) && (checkType->IsTypeInstance()))
  16598. {
  16599. auto activeTypeDef = mModule->GetActiveTypeDef();
  16600. BfTypeInterfaceEntry* bestIFaceEntry = NULL;
  16601. bool checkedUnderlying = false;
  16602. auto checkTypeInst = checkType->ToTypeInstance();
  16603. while (checkTypeInst != NULL)
  16604. {
  16605. mModule->PopulateType(checkTypeInst, BfPopulateType_DataAndMethods);
  16606. BF_ASSERT((checkTypeInst->mDefineState >= BfTypeDefineState_DefinedAndMethodsSlotted) || (mModule->mCompiler->IsAutocomplete()));
  16607. if (checkTypeInst->mDefineState != BfTypeDefineState_DefinedAndMethodsSlotted)
  16608. break;
  16609. for (auto& iface : checkTypeInst->mInterfaces)
  16610. {
  16611. if (!mModule->IsInSpecializedSection())
  16612. {
  16613. if (!checkTypeInst->IsTypeMemberAccessible(iface.mDeclaringType, activeTypeDef))
  16614. continue;
  16615. }
  16616. if (iface.mInterfaceType == mPropTarget.mType)
  16617. {
  16618. if (bestIFaceEntry == NULL)
  16619. {
  16620. bestIFaceEntry = &iface;
  16621. continue;
  16622. }
  16623. bool isBetter;
  16624. bool isWorse;
  16625. mModule->CompareDeclTypes(NULL, iface.mDeclaringType, bestIFaceEntry->mDeclaringType, isBetter, isWorse);
  16626. if (isBetter == isWorse)
  16627. {
  16628. // Failed
  16629. }
  16630. else
  16631. {
  16632. if (isBetter)
  16633. bestIFaceEntry = &iface;
  16634. }
  16635. }
  16636. }
  16637. if (bestIFaceEntry != NULL)
  16638. break;
  16639. checkTypeInst = checkTypeInst->mBaseType;
  16640. if (checkTypeInst == NULL)
  16641. {
  16642. if (!checkedUnderlying)
  16643. {
  16644. checkedUnderlying = true;
  16645. if (checkType->HasWrappedRepresentation())
  16646. {
  16647. auto underlyingType = checkType->GetUnderlyingType();
  16648. if (underlyingType != NULL)
  16649. checkTypeInst = mModule->GetWrappedStructType(underlyingType);
  16650. }
  16651. }
  16652. }
  16653. }
  16654. if (bestIFaceEntry != NULL)
  16655. {
  16656. auto ifaceMethodEntry = checkTypeInst->mInterfaceMethodTable[bestIFaceEntry->mStartInterfaceTableIdx + methodDef->mIdx];
  16657. BfMethodInstance* bestMethodInstance = ifaceMethodEntry.mMethodRef;
  16658. if (bestMethodInstance != NULL)
  16659. {
  16660. mPropTarget = mOrigPropTarget;
  16661. //mPropTarget.mType = checkTypeInst;
  16662. //mPropTarget = mModule->Cast( mOrigPropTarget, checkTypeInst);
  16663. return mModule->GetMethodInstanceAtIdx(ifaceMethodEntry.mMethodRef.mTypeInstance, ifaceMethodEntry.mMethodRef.mMethodNum);
  16664. }
  16665. }
  16666. }
  16667. mModule->AssertErrorState();
  16668. return BfModuleMethodInstance();
  16669. }
  16670. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  16671. if (propTypeInst == NULL)
  16672. {
  16673. propTypeInst = mModule->GetWrappedStructType(mPropTarget.mType);
  16674. }
  16675. if (propTypeInst == NULL)
  16676. {
  16677. mModule->Fail("INTERNAL ERROR: Invalid property target", mPropSrc);
  16678. return BfModuleMethodInstance();
  16679. }
  16680. return mModule->GetMethodInstance(propTypeInst, methodDef, BfTypeVector(), mPropGetMethodFlags);
  16681. }
  16682. void BfExprEvaluator::CheckPropFail(BfMethodDef* propMethodDef, BfMethodInstance* methodInstance, bool checkProt)
  16683. {
  16684. auto propTypeInst = mPropTarget.mType->ToTypeInstance();
  16685. // If mExplicitInterface is null then we are implicitly calling through an interface
  16686. if ((checkProt) && (propTypeInst != NULL) && (methodInstance->GetExplicitInterface() == NULL) &&
  16687. (!mModule->CheckAccessMemberProtection(propMethodDef->mProtection, propTypeInst)))
  16688. mModule->Fail(StrFormat("'%s' is inaccessible due to its protection level", mModule->MethodToString(methodInstance).c_str()), mPropSrc);
  16689. else if (mPropCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  16690. {
  16691. bool passes = true;
  16692. if (mPropCheckedKind != BfCheckedKind_NotSet)
  16693. {
  16694. passes = false;
  16695. }
  16696. else
  16697. {
  16698. auto defaultCheckedKind = mModule->GetDefaultCheckedKind();
  16699. if (defaultCheckedKind != methodInstance->mMethodDef->mCheckedKind)
  16700. passes = false;
  16701. }
  16702. if (!passes)
  16703. {
  16704. 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);
  16705. if (error != NULL)
  16706. {
  16707. if ((error != NULL) && (methodInstance->mMethodDef->mMethodDeclaration != NULL))
  16708. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See method declaration"), methodInstance->mMethodDef->GetRefNode());
  16709. }
  16710. }
  16711. }
  16712. }
  16713. bool BfExprEvaluator::HasResult()
  16714. {
  16715. return (mResult) || (mPropDef != NULL);
  16716. }
  16717. BfTypedValue BfExprEvaluator::GetResult(bool clearResult, bool resolveGenericType)
  16718. {
  16719. if ((!mResult) && (mPropDef != NULL))
  16720. {
  16721. bool handled = false;
  16722. if (mPropTarget.mType->IsGenericTypeInstance())
  16723. {
  16724. auto genericTypeInst = (BfTypeInstance*)mPropTarget.mType;
  16725. if (genericTypeInst->IsInstanceOf(mModule->mCompiler->mSizedArrayTypeDef))
  16726. {
  16727. if (mPropDef->mName == "Count")
  16728. {
  16729. auto sizedType = genericTypeInst->mGenericTypeInfo->mTypeGenericArguments[1];
  16730. if (sizedType->IsConstExprValue())
  16731. {
  16732. auto constExprType = (BfConstExprValueType*)sizedType;
  16733. mResult = BfTypedValue(mModule->GetConstValue(constExprType->mValue.mInt64), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  16734. handled = true;
  16735. }
  16736. else
  16737. {
  16738. BF_ASSERT(mModule->mCurMethodInstance->mIsUnspecialized);
  16739. mResult = BfTypedValue(mModule->mBfIRBuilder->GetUndefConstValue(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_IntPtr)), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  16740. handled = true;
  16741. }
  16742. }
  16743. }
  16744. }
  16745. if (!handled)
  16746. {
  16747. SetAndRestoreValue<BfFunctionBindResult*> prevFunctionBindResult(mFunctionBindResult, NULL);
  16748. SetAndRestoreValue<BfAstNode*> prevDeferCallRef(mDeferCallRef, NULL);
  16749. BfMethodDef* matchedMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  16750. if (matchedMethod == NULL)
  16751. {
  16752. mModule->Fail("Property has no getter", mPropSrc);
  16753. return mResult;
  16754. }
  16755. auto methodInstance = GetPropertyMethodInstance(matchedMethod);
  16756. if (methodInstance.mMethodInstance == NULL)
  16757. return mResult;
  16758. BF_ASSERT(methodInstance.mMethodInstance->mMethodDef->mName == matchedMethod->mName);
  16759. if (!mModule->mBfIRBuilder->mIgnoreWrites)
  16760. {
  16761. BF_ASSERT(!methodInstance.mFunc.IsFake());
  16762. }
  16763. if (mPropSrc != NULL)
  16764. mModule->UpdateExprSrcPos(mPropSrc);
  16765. auto autoComplete = GetAutoComplete();
  16766. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(mPropSrc)) && (autoComplete->mResolveType == BfResolveType_GetResultString))
  16767. {
  16768. autoComplete->mResultString = ":";
  16769. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->mReturnType);
  16770. autoComplete->mResultString += " ";
  16771. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetOwner());
  16772. autoComplete->mResultString += ".";
  16773. autoComplete->mResultString += mPropDef->mName;
  16774. }
  16775. CheckPropFail(matchedMethod, methodInstance.mMethodInstance, (mPropGetMethodFlags & BfGetMethodInstanceFlag_Friend) == 0);
  16776. PerformCallChecks(methodInstance.mMethodInstance, mPropSrc);
  16777. if (methodInstance.mMethodInstance->IsSkipCall())
  16778. {
  16779. mResult = mModule->GetDefaultTypedValue(methodInstance.mMethodInstance->mReturnType);
  16780. }
  16781. else
  16782. {
  16783. SizedArray<BfIRValue, 4> args;
  16784. if (!matchedMethod->mIsStatic)
  16785. {
  16786. auto owner = methodInstance.mMethodInstance->GetOwner();
  16787. bool isTypeMatch = mPropTarget.mType == owner;
  16788. if (owner->IsTypedPrimitive())
  16789. isTypeMatch |= mPropTarget.mType == owner->GetUnderlyingType();
  16790. if ((!isTypeMatch) ||
  16791. ((mPropTarget.mValue.IsFake()) && (!mOrigPropTarget.mValue.IsFake())))
  16792. {
  16793. auto prevPropTarget = mPropTarget;
  16794. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, owner);
  16795. if (!mPropTarget)
  16796. {
  16797. mModule->Fail("Internal property error", mPropSrc);
  16798. return BfTypedValue();
  16799. }
  16800. }
  16801. if ((mPropGetMethodFlags & BfGetMethodInstanceFlag_DisableObjectAccessChecks) == 0)
  16802. mModule->EmitObjectAccessCheck(mPropTarget);
  16803. }
  16804. auto callFlags = mPropDefBypassVirtual ? BfCreateCallFlags_BypassVirtual : BfCreateCallFlags_None;
  16805. mResult = CreateCall(mPropSrc, mPropTarget, mOrigPropTarget, matchedMethod, methodInstance, callFlags, mIndexerValues, NULL);
  16806. }
  16807. }
  16808. mPropDef = NULL;
  16809. mPropDefBypassVirtual = false;
  16810. mIndexerValues.clear();
  16811. mResultLocalVar = NULL;
  16812. mResultFieldInstance = NULL;
  16813. }
  16814. if (resolveGenericType)
  16815. ResolveGenericType();
  16816. BfTypedValue result = mResult;
  16817. if (clearResult)
  16818. mResult = BfTypedValue();
  16819. return result;
  16820. }
  16821. void BfExprEvaluator::CheckResultForReading(BfTypedValue& typedValue)
  16822. {
  16823. if (mModule->mCurMethodState == NULL)
  16824. return;
  16825. if ((mModule->mCurMethodState->mTempKind != BfMethodState::TempKind_None) || (mModule->mCurMethodState->mAllowUinitReads))
  16826. return;
  16827. if ((mModule->mCurTypeInstance->mResolvingVarField) || (mModule->mCurTypeInstance->mResolvingConstField))
  16828. return;
  16829. if ((typedValue) && (typedValue.IsAddr()))
  16830. {
  16831. if ((mResultLocalVar != NULL) && (mResultLocalVarRefNode != NULL))
  16832. {
  16833. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors);
  16834. if ((mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mCapturing))
  16835. {
  16836. // These errors can only be detected during capture time, so we don't ignore them on this pass
  16837. mModule->mIgnoreErrors = false;
  16838. }
  16839. int fieldIdx = mResultLocalVarField - 1;
  16840. auto localVar = mResultLocalVar;
  16841. if (localVar->mCompositeCount > 0)
  16842. {
  16843. mModule->Fail(StrFormat("Cannot read from composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  16844. typedValue = BfTypedValue();
  16845. return;
  16846. }
  16847. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  16848. {
  16849. mModule->TryLocalVariableInit(localVar);
  16850. }
  16851. if (localVar->mAssignedKind == BfLocalVarAssignKind_None)
  16852. {
  16853. auto methodStateForLocal = mModule->mCurMethodState->GetMethodStateForLocal(localVar);
  16854. bool isAssigned = false;
  16855. int64 undefinedFieldFlags = localVar->mUnassignedFieldFlags;
  16856. auto deferredLocalAssignData = methodStateForLocal->mDeferredLocalAssignData;
  16857. while ((deferredLocalAssignData != NULL) && (deferredLocalAssignData->mIsChained))
  16858. deferredLocalAssignData = deferredLocalAssignData->mChainedAssignData;
  16859. if (deferredLocalAssignData != NULL)
  16860. {
  16861. for (auto& assignedVar : deferredLocalAssignData->mAssignedLocals)
  16862. {
  16863. auto assignedLocal = assignedVar.mLocalVar;
  16864. if (assignedLocal == localVar)
  16865. {
  16866. int assignedFieldIdx = assignedVar.mLocalVarField;
  16867. if (assignedFieldIdx >= 0)
  16868. undefinedFieldFlags &= ~((int64)1 << assignedFieldIdx);
  16869. else
  16870. undefinedFieldFlags = 0;
  16871. }
  16872. }
  16873. if (deferredLocalAssignData->mLeftBlockUncond)
  16874. isAssigned = true;
  16875. }
  16876. if (fieldIdx == -1)
  16877. {
  16878. if (undefinedFieldFlags == 0)
  16879. isAssigned = true;
  16880. }
  16881. else
  16882. {
  16883. isAssigned = true;
  16884. for (int i = 0; i < mResultLocalVarFieldCount; i++)
  16885. if ((undefinedFieldFlags & (1LL << (fieldIdx + i))) != 0)
  16886. isAssigned = false;
  16887. }
  16888. if (!isAssigned)
  16889. {
  16890. if ((localVar->mIsThis) && (fieldIdx != -1))
  16891. {
  16892. // When we have initializers for fields, they won't all be processed in the autocomplte case
  16893. if (!mModule->mCompiler->IsAutocomplete())
  16894. {
  16895. auto bfError = mModule->Fail(StrFormat("Use of possibly unassigned field '%s'", mResultLocalVarRefNode->ToString().c_str()), mResultLocalVarRefNode, true);
  16896. }
  16897. }
  16898. else
  16899. {
  16900. mModule->Fail(StrFormat("Use of unassigned local variable '%s'", localVar->mName.c_str()), mResultLocalVarRefNode);
  16901. }
  16902. }
  16903. }
  16904. localVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  16905. }
  16906. }
  16907. }
  16908. void BfExprEvaluator::FinishExpressionResult()
  16909. {
  16910. CheckResultForReading(mResult);
  16911. mResultLocalVar = NULL;
  16912. mResultFieldInstance = NULL;
  16913. }
  16914. bool BfExprEvaluator::CheckAllowValue(const BfTypedValue& typedValue, BfAstNode* refNode)
  16915. {
  16916. return true;
  16917. }
  16918. void BfExprEvaluator::MarkResultUsed()
  16919. {
  16920. if (mResultLocalVar != NULL)
  16921. {
  16922. mResultLocalVar->mReadFromId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  16923. }
  16924. }
  16925. void BfExprEvaluator::MarkResultAssigned()
  16926. {
  16927. if (mResultLocalVar != NULL)
  16928. {
  16929. //int localIdx = mResultLocalVarIdx;
  16930. //if (localIdx == 0x7FFF)
  16931. //return;
  16932. auto localVar = mResultLocalVar;
  16933. int fieldIdx = mResultLocalVarField - 1;
  16934. int count = mResultLocalVarFieldCount;
  16935. if (fieldIdx == -1)
  16936. count = 1;
  16937. for (int i = 0; i < count; i++)
  16938. mModule->mCurMethodState->GetMethodStateForLocal(localVar)->LocalDefined(localVar, fieldIdx + i);
  16939. //if (localIdx != 0x7FFF)
  16940. {
  16941. if (localVar->mCompositeCount > 0)
  16942. {
  16943. mModule->Fail(StrFormat("Cannot write to composite '%s', it can only be used in an argument list", localVar->mName.c_str()), mResultLocalVarRefNode);
  16944. }
  16945. }
  16946. }
  16947. }
  16948. void BfExprEvaluator::MakeResultAsValue()
  16949. {
  16950. // Expressions like parens will turn a variable reference into a simple value
  16951. mResultLocalVar = NULL;
  16952. mResultFieldInstance = NULL;
  16953. }
  16954. bool BfExprEvaluator::CheckIsBase(BfAstNode* checkNode)
  16955. {
  16956. if (checkNode == NULL)
  16957. return false;
  16958. if (!checkNode->Equals("base"))
  16959. return false;
  16960. auto autoComplete = GetAutoComplete();
  16961. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(checkNode)))
  16962. {
  16963. if ((mModule->mCurTypeInstance != NULL) && (mModule->mCurTypeInstance->mBaseType != NULL))
  16964. autoComplete->SetDefinitionLocation(mModule->mCurTypeInstance->mBaseType->mTypeDef->GetRefNode());
  16965. }
  16966. return true;
  16967. }
  16968. bool BfExprEvaluator::CheckModifyResult(BfTypedValue& typedVal, BfAstNode* refNode, const char* modifyType, bool onlyNeedsMut, bool emitWarning, bool skipCopyOnMutate)
  16969. {
  16970. BfLocalVariable* localVar = NULL;
  16971. bool isCapturedLocal = false;
  16972. if (mResultLocalVar != NULL)
  16973. {
  16974. localVar = mResultLocalVar;
  16975. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  16976. }
  16977. else if (typedVal.IsThis())
  16978. {
  16979. localVar = mModule->GetThisVariable();
  16980. }
  16981. else if (typedVal.IsSplat())
  16982. {
  16983. for (auto checkLocal : mModule->mCurMethodState->mLocals)
  16984. {
  16985. if (checkLocal->mAddr == typedVal.mValue)
  16986. {
  16987. localVar = checkLocal;
  16988. break;
  16989. }
  16990. }
  16991. }
  16992. else if (typedVal.mValue.IsArg())
  16993. {
  16994. auto methodState = mModule->mCurMethodState->GetNonCaptureState();
  16995. localVar = methodState->mLocals[typedVal.mValue.mId];
  16996. }
  16997. if ((typedVal.mKind == BfTypedValueKind_MutableValue) && (onlyNeedsMut))
  16998. {
  16999. return true;
  17000. }
  17001. bool canModify = typedVal.CanModify();
  17002. if (((typedVal.mKind == BfTypedValueKind_TempAddr) || (typedVal.mKind == BfTypedValueKind_CopyOnMutateAddr_Derived)) &&
  17003. (strcmp(modifyType, "assign to") == 0))
  17004. mModule->Warn(0, "Assigning to temporary copy of a value. Consider using 'ref' in value source declaration.", refNode);
  17005. auto _Fail = [&](const StringImpl& error, BfAstNode* refNode)
  17006. {
  17007. if (emitWarning)
  17008. return mModule->Warn(BfWarning_BF4204_AddressOfReadOnly, error, refNode);
  17009. else
  17010. return mModule->Fail(error, refNode);
  17011. };
  17012. if (localVar != NULL)
  17013. {
  17014. if (!canModify)
  17015. {
  17016. BfError* error = NULL;
  17017. if (localVar->mIsThis)
  17018. {
  17019. bool isClosure = false;
  17020. BfTypeInstance* checkTypeInst = localVar->mResolvedType->ToTypeInstance();
  17021. int fieldIdx = mResultLocalVarField - 1;
  17022. if ((!isCapturedLocal) && (mModule->mCurMethodState != NULL) && (mModule->mCurMethodState->mClosureState != NULL) && (mModule->mCurMethodState->mClosureState->mClosureType != NULL))
  17023. {
  17024. isClosure = true;
  17025. auto closureThis = mModule->mCurMethodState->mClosureState->mClosureType;
  17026. closureThis = checkTypeInst->mFieldInstances[0].mResolvedType->ToTypeInstance();
  17027. if (fieldIdx >= -1)
  17028. {
  17029. checkTypeInst = closureThis;
  17030. }
  17031. else
  17032. {
  17033. fieldIdx = -fieldIdx - 2;
  17034. isCapturedLocal = true;
  17035. }
  17036. }
  17037. if (fieldIdx < 0)
  17038. {
  17039. if (isClosure)
  17040. {
  17041. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  17042. error = _Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType), refNode);
  17043. else
  17044. error = _Fail(StrFormat("Cannot %s 'this' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType), refNode);
  17045. }
  17046. else if (localVar->mResolvedType->IsValueType())
  17047. {
  17048. error = _Fail(StrFormat("Cannot %s 'this' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  17049. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17050. }
  17051. else
  17052. {
  17053. error = _Fail(StrFormat("Cannot %s 'this' because '%s' is a reference type.", modifyType,
  17054. mModule->TypeToString(localVar->mResolvedType).c_str()), refNode);
  17055. }
  17056. return false;
  17057. }
  17058. else if (mResultFieldInstance != NULL)
  17059. {
  17060. if (isCapturedLocal)
  17061. {
  17062. error = _Fail(StrFormat("Cannot %s read-only captured local variable '%s'. Consider adding by-reference capture specifier [&] to lambda and ensuring that captured value is not read-only.", modifyType,
  17063. mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  17064. }
  17065. else if (isClosure)
  17066. {
  17067. if (!mModule->mCurMethodState->mClosureState->mDeclaringMethodIsMutating)
  17068. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding 'mut' specifier to this method.", modifyType,
  17069. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  17070. else
  17071. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct lambda. Consider adding by-reference capture specifier [&] to lambda.", modifyType,
  17072. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str()), refNode);
  17073. }
  17074. else if (mResultFieldInstance->GetFieldDef()->mIsReadOnly)
  17075. {
  17076. error = _Fail(StrFormat("Cannot %s readonly field '%s.%s' within method '%s'", modifyType,
  17077. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  17078. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17079. }
  17080. else if (auto propertyDeclaration = BfNodeDynCast<BfPropertyDeclaration>(mResultFieldInstance->GetFieldDef()->mFieldDeclaration))
  17081. {
  17082. String propNam;
  17083. if (propertyDeclaration->mNameNode != NULL)
  17084. propertyDeclaration->mNameNode->ToString(propNam);
  17085. error = _Fail(StrFormat("Cannot %s auto-implemented property '%s.%s' without set accessor", modifyType,
  17086. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), propNam.c_str()), refNode);
  17087. }
  17088. else
  17089. {
  17090. error = _Fail(StrFormat("Cannot %s field '%s.%s' within struct method '%s'. Consider adding 'mut' specifier to this method.", modifyType,
  17091. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  17092. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17093. }
  17094. return false;
  17095. }
  17096. }
  17097. else if (localVar->IsParam())
  17098. {
  17099. if (!mModule->mCurMethodInstance->IsMixin())
  17100. {
  17101. if (mModule->mCurMethodState->mMixinState != NULL)
  17102. {
  17103. error = _Fail(StrFormat("Cannot %s mixin parameter '%s'", modifyType,
  17104. localVar->mName.c_str()), refNode);
  17105. }
  17106. else if ((onlyNeedsMut) && (localVar->mResolvedType != NULL) && (localVar->mResolvedType->IsGenericParam()))
  17107. {
  17108. if (emitWarning)
  17109. error = _Fail(StrFormat("The address of '%s' may be temporary or immutable. Consider adding 'mut' or 'ref' specifier to parameter or declaring 'var %s;' to create a mutable copy.",
  17110. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  17111. else
  17112. error = _Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'mut' or 'ref' specifier to parameter or declaring 'var %s;' to create a mutable copy.", modifyType,
  17113. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  17114. }
  17115. else
  17116. {
  17117. if (emitWarning)
  17118. error = _Fail(StrFormat("The address of '%s' may be temporary or immutable. Consider adding 'ref' specifier to parameter or declaring 'var %s;' to create a mutable copy.",
  17119. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  17120. else
  17121. error = _Fail(StrFormat("Cannot %s parameter '%s'. Consider adding 'ref' specifier to parameter or declaring 'var %s;' to create a mutable copy.", modifyType,
  17122. localVar->mName.c_str(), localVar->mName.c_str()), refNode);
  17123. }
  17124. return false;
  17125. }
  17126. }
  17127. else
  17128. {
  17129. if ((mResultLocalVarField != 0) && (!localVar->mIsReadOnly))
  17130. {
  17131. auto typeInst = localVar->mResolvedType->ToTypeInstance();
  17132. int dataIdx = mResultLocalVarField - 1;
  17133. if (typeInst != NULL)
  17134. {
  17135. for (auto& field : typeInst->mFieldInstances)
  17136. {
  17137. if (field.mDataIdx == dataIdx)
  17138. {
  17139. error = _Fail(StrFormat("Cannot %s readonly field '%s.%s'.", modifyType,
  17140. mModule->TypeToString(typeInst).c_str(),
  17141. field.GetFieldDef()->mName.c_str()), refNode);
  17142. break;
  17143. }
  17144. }
  17145. }
  17146. }
  17147. if (error == NULL)
  17148. {
  17149. error = _Fail(StrFormat("Cannot %s read-only local variable '%s'.", modifyType,
  17150. localVar->mName.c_str()), refNode);
  17151. }
  17152. return false;
  17153. }
  17154. }
  17155. else
  17156. {
  17157. // When we are capturing, we need to note that we require capturing by reference here
  17158. localVar->mWrittenToId = mModule->mCurMethodState->GetRootMethodState()->mCurAccessId++;
  17159. }
  17160. }
  17161. if ((mResultFieldInstance != NULL) && (mResultFieldInstance->GetFieldDef()->mIsReadOnly) && (!canModify))
  17162. {
  17163. auto error = _Fail(StrFormat("Cannot %s static readonly field '%s.%s' within method '%s'", modifyType,
  17164. mModule->TypeToString(mResultFieldInstance->mOwner).c_str(), mResultFieldInstance->GetFieldDef()->mName.c_str(),
  17165. mModule->MethodToString(mModule->mCurMethodInstance).c_str()), refNode);
  17166. return false;
  17167. }
  17168. if ((!skipCopyOnMutate) && (typedVal.IsCopyOnMutate()))
  17169. typedVal = mModule->CopyValue(typedVal);
  17170. return mModule->CheckModifyValue(typedVal, refNode, modifyType);
  17171. }
  17172. void BfExprEvaluator::Visit(BfConditionalExpression* condExpr)
  17173. {
  17174. static int sCallCount = 0;
  17175. sCallCount++;
  17176. auto condResult = mModule->CreateValueFromExpression(condExpr->mConditionExpression, mModule->GetPrimitiveType(BfTypeCode_Boolean), (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  17177. if (!condResult)
  17178. return;
  17179. if (condExpr->mTrueExpression == NULL)
  17180. {
  17181. mModule->AssertErrorState();
  17182. return;
  17183. }
  17184. if (condExpr->mFalseExpression == NULL)
  17185. {
  17186. mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, BfEvalExprFlags_NoCast);
  17187. mModule->AssertErrorState();
  17188. return;
  17189. }
  17190. bool isConstBranch = false;
  17191. bool constResult = false;
  17192. bool constResultUndef = false;
  17193. if (condResult.mValue.IsConst())
  17194. {
  17195. auto constValue = mModule->mBfIRBuilder->GetConstant(condResult.mValue);
  17196. if (constValue->mTypeCode == BfTypeCode_Boolean)
  17197. {
  17198. isConstBranch = true;
  17199. constResult = constValue->mBool;
  17200. }
  17201. else if (constValue->mConstType == BfConstType_Undef)
  17202. {
  17203. isConstBranch = true;
  17204. constResultUndef = true;
  17205. }
  17206. }
  17207. if (isConstBranch)
  17208. {
  17209. BfExpression* actualExpr = (constResult) ? condExpr->mTrueExpression : condExpr->mFalseExpression;
  17210. BfExpression* ignoredExpr = (constResult) ? condExpr->mFalseExpression : condExpr->mTrueExpression;
  17211. BfTypedValue actualValue = mModule->CreateValueFromExpression(actualExpr, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  17212. BfTypedValue ignoredValue;
  17213. //
  17214. {
  17215. auto curBlock = mModule->mBfIRBuilder->GetInsertBlock();
  17216. SetAndRestoreValue<bool> ignoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  17217. SetAndRestoreValue<bool> prevInConstIgnore(mModule->mCurMethodState->mCurScope->mInConstIgnore, true);
  17218. ignoredValue = mModule->CreateValueFromExpression(ignoredExpr, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast));
  17219. mModule->mBfIRBuilder->SetInsertPoint(curBlock);
  17220. }
  17221. if (!actualValue)
  17222. return;
  17223. if ((ignoredValue) && (ignoredValue.mType != actualValue.mType) && (!ignoredValue.mType->IsVar()))
  17224. {
  17225. // Cast to more specific 'ignored' type if applicable
  17226. if (mModule->CanCast(actualValue, ignoredValue.mType))
  17227. {
  17228. actualValue = mModule->Cast(actualExpr, actualValue, ignoredValue.mType);
  17229. }
  17230. else if (!mModule->CanCast(ignoredValue, actualValue.mType))
  17231. {
  17232. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  17233. mModule->TypeToString(actualValue.mType).c_str(), mModule->TypeToString(ignoredValue.mType).c_str()), condExpr);
  17234. }
  17235. }
  17236. mResult = actualValue;
  17237. if (constResultUndef)
  17238. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Undef);
  17239. return;
  17240. }
  17241. auto trueBB = mModule->mBfIRBuilder->CreateBlock("cond.then");
  17242. auto falseBB = mModule->mBfIRBuilder->CreateBlock("cond.else");
  17243. auto endBB = mModule->mBfIRBuilder->CreateBlock("cond.end");
  17244. auto contBB = mModule->mBfIRBuilder->CreateBlock("cond.cont");
  17245. mModule->mBfIRBuilder->CreateCondBr(condResult.mValue, trueBB, falseBB);
  17246. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mCurScope->mInnerIsConditional, true);
  17247. bool wantExpectingCast = (mExpectingType != NULL) && ((mBfEvalExprFlags & BfEvalExprFlags_NoCast) == 0);
  17248. mModule->AddBasicBlock(trueBB);
  17249. auto trueValue = mModule->CreateValueFromExpression(condExpr->mTrueExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  17250. if ((wantExpectingCast) && (trueValue) && (trueValue.mType != mExpectingType))
  17251. {
  17252. // In some cases like typed primitives - we CAN individually cast each value which it's a constant still, but not after the merging
  17253. // IE: Color c = isOver ? 0xFF000000 : 0xFFFFFFFF;
  17254. // Otherwise the resulting value would just be 'int' which cannot implicitly convert to Color, but each of those ints can be
  17255. // a uint32 if converted separately
  17256. auto checkTrueValue = mModule->Cast(condExpr->mTrueExpression, trueValue, mExpectingType, BfCastFlags_SilentFail);
  17257. if (checkTrueValue)
  17258. trueValue = checkTrueValue;
  17259. mModule->FixIntUnknown(trueValue);
  17260. }
  17261. auto trueBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  17262. mModule->AddBasicBlock(falseBB);
  17263. auto falseValue = mModule->CreateValueFromExpression(condExpr->mFalseExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  17264. auto falseBlockPos = mModule->mBfIRBuilder->GetInsertBlock();
  17265. if ((wantExpectingCast) && (falseValue) && (falseValue.mType != mExpectingType))
  17266. {
  17267. auto checkFalseValue = mModule->Cast(condExpr->mFalseExpression, falseValue, mExpectingType, BfCastFlags_SilentFail);
  17268. if (checkFalseValue)
  17269. falseValue = checkFalseValue;
  17270. mModule->FixIntUnknown(falseValue);
  17271. }
  17272. prevInCondBlock.Restore();
  17273. bool isValid = trueValue && falseValue;
  17274. if (isValid)
  17275. {
  17276. BfTypedValue falseToTrue;
  17277. {
  17278. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  17279. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  17280. falseToTrue = mModule->Cast(condExpr->mFalseExpression, falseValue, trueValue.mType);
  17281. }
  17282. if (falseToTrue)
  17283. {
  17284. falseValue = falseToTrue;
  17285. }
  17286. else
  17287. {
  17288. BfTypedValue trueToFalse;
  17289. {
  17290. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  17291. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  17292. trueToFalse = mModule->Cast(condExpr->mTrueExpression, trueValue, falseValue.mType);
  17293. }
  17294. if (!trueToFalse)
  17295. {
  17296. mModule->Fail(StrFormat("Type of conditional expression cannot be determined because there is no implicit conversion between '%s' and '%s'",
  17297. mModule->TypeToString(trueValue.mType).c_str(), mModule->TypeToString(falseValue.mType).c_str()), condExpr);
  17298. //return;
  17299. isValid = false;
  17300. }
  17301. else
  17302. trueValue = trueToFalse;
  17303. }
  17304. }
  17305. mModule->mBfIRBuilder->SetInsertPoint(trueBlockPos);
  17306. if (isValid)
  17307. trueValue = mModule->LoadValue(trueValue);
  17308. mModule->mBfIRBuilder->CreateBr(endBB);
  17309. mModule->mBfIRBuilder->SetInsertPoint(falseBlockPos);
  17310. if (isValid)
  17311. falseValue = mModule->LoadValue(falseValue);
  17312. mModule->mBfIRBuilder->CreateBr(endBB);
  17313. mModule->AddBasicBlock(endBB, false);
  17314. if (!isValid)
  17315. return;
  17316. mModule->mBfIRBuilder->SetInsertPoint(endBB);
  17317. BfIRValue phi;
  17318. if (!trueValue.mType->IsValuelessType())
  17319. {
  17320. if (trueValue.mType->IsVar())
  17321. {
  17322. phi = mModule->mBfIRBuilder->GetFakeVal();
  17323. }
  17324. else
  17325. {
  17326. mModule->mBfIRBuilder->PopulateType(trueValue.mType);
  17327. phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(trueValue.mType), 2);
  17328. mModule->mBfIRBuilder->AddPhiIncoming(phi, trueValue.mValue, trueBlockPos);
  17329. mModule->mBfIRBuilder->AddPhiIncoming(phi, falseValue.mValue, falseBlockPos);
  17330. }
  17331. }
  17332. mModule->mBfIRBuilder->CreateBr(contBB);
  17333. mModule->AddBasicBlock(contBB);
  17334. mResult = BfTypedValue(phi, trueValue.mType);
  17335. }
  17336. void BfExprEvaluator::PopulateDeferrredTupleAssignData(BfTupleExpression* tupleExpr, DeferredTupleAssignData& deferredTupleAssignData)
  17337. {
  17338. BfTypeVector fieldTypes;
  17339. Array<String> fieldNames;
  17340. // We need to evaluate each LHS tuple component in a separate BfExprEvaluator because each one
  17341. // could be a property and the 'mPropDef' target info is tied to a single evaluator
  17342. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  17343. {
  17344. DeferredTupleAssignData::Entry entry;
  17345. entry.mExprEvaluator = NULL;
  17346. entry.mInnerTuple = NULL;
  17347. entry.mVarType = NULL;
  17348. entry.mVarNameNode = NULL;
  17349. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  17350. entry.mExpr = valueExpr;
  17351. BfType* fieldType = NULL;
  17352. BfType* resultType = NULL;
  17353. if (auto innerTupleExpr = BfNodeDynCast<BfTupleExpression>(valueExpr))
  17354. {
  17355. entry.mInnerTuple = new DeferredTupleAssignData();
  17356. PopulateDeferrredTupleAssignData(innerTupleExpr, *entry.mInnerTuple);
  17357. resultType = entry.mInnerTuple->mTupleType;
  17358. }
  17359. else
  17360. {
  17361. BfExprEvaluator* exprEvaluator = new BfExprEvaluator(mModule);
  17362. entry.mExprEvaluator = exprEvaluator;
  17363. if (valueExpr->IsA<BfUninitializedExpression>())
  17364. {
  17365. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  17366. }
  17367. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(valueExpr))
  17368. {
  17369. if ((varDecl->mTypeRef->IsA<BfLetTypeReference>()) || (varDecl->mTypeRef->IsA<BfVarTypeReference>()))
  17370. {
  17371. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  17372. }
  17373. else
  17374. {
  17375. resultType = ResolveTypeRef(varDecl->mTypeRef);
  17376. if (resultType == NULL)
  17377. resultType = mModule->GetPrimitiveType(BfTypeCode_Var);
  17378. }
  17379. entry.mVarType = resultType;
  17380. }
  17381. if (auto binOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>(valueExpr))
  17382. {
  17383. if (binOpExpr->mOp == BfBinaryOp_Multiply)
  17384. {
  17385. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  17386. auto resolvedType = mModule->ResolveTypeRef(binOpExpr->mLeft, NULL);
  17387. prevIgnoreError.Restore();
  17388. if (resolvedType != NULL)
  17389. {
  17390. resultType = mModule->CreatePointerType(resolvedType);
  17391. entry.mVarType = resultType;
  17392. entry.mVarNameNode = binOpExpr->mRight;
  17393. }
  17394. }
  17395. }
  17396. if (resultType == NULL)
  17397. {
  17398. exprEvaluator->VisitChild(valueExpr);
  17399. if ((!exprEvaluator->mResult) && (exprEvaluator->mPropDef == NULL))
  17400. exprEvaluator->mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  17401. resultType = exprEvaluator->mResult.mType;
  17402. }
  17403. if ((resultType == NULL) && (exprEvaluator->mPropDef != NULL) && (exprEvaluator->mPropTarget.mType != NULL))
  17404. {
  17405. auto propTypeInst = exprEvaluator->mPropTarget.mType->ToTypeInstance();
  17406. if ((propTypeInst == NULL) && (exprEvaluator->mPropTarget.mType->IsPointer()))
  17407. {
  17408. BfPointerType* pointerType = (BfPointerType*)exprEvaluator->mPropTarget.mType;
  17409. propTypeInst = pointerType->mElementType->ToTypeInstance();
  17410. }
  17411. auto setMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  17412. if (setMethod != NULL)
  17413. {
  17414. auto methodInstance = mModule->GetMethodInstance(propTypeInst, setMethod, BfTypeVector());
  17415. resultType = methodInstance.mMethodInstance->GetParamType(0);
  17416. }
  17417. else
  17418. {
  17419. auto getMethod = GetPropertyMethodDef(exprEvaluator->mPropDef, BfMethodType_PropertyGetter, mPropCheckedKind, mPropTarget);
  17420. if (getMethod != NULL)
  17421. {
  17422. auto methodInstance = mModule->GetMethodInstance(propTypeInst, getMethod, BfTypeVector());
  17423. auto retType = methodInstance.mMethodInstance->mReturnType;
  17424. if (retType->IsRef())
  17425. resultType = retType->GetUnderlyingType();
  17426. }
  17427. }
  17428. }
  17429. }
  17430. if (resultType == NULL)
  17431. resultType = mModule->GetPrimitiveType(BfTypeCode_None);
  17432. deferredTupleAssignData.mChildren.push_back(entry);
  17433. fieldTypes.push_back(resultType);
  17434. }
  17435. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  17436. {
  17437. if (requestedName == NULL)
  17438. fieldNames.push_back("");
  17439. else
  17440. fieldNames.push_back(requestedName->mNameNode->ToString());
  17441. }
  17442. BfTypeInstance* tupleType = mModule->CreateTupleType(fieldTypes, fieldNames, true);
  17443. deferredTupleAssignData.mTupleType = tupleType;
  17444. }
  17445. void BfExprEvaluator::AssignDeferrredTupleAssignData(BfAssignmentExpression* assignExpr, DeferredTupleAssignData& deferredTupleAssignData, BfTypedValue rightValue)
  17446. {
  17447. BF_ASSERT(rightValue.mType->IsTuple());
  17448. auto tupleType = (BfTypeInstance*)rightValue.mType;
  17449. for (int valueIdx = 0; valueIdx < (int)deferredTupleAssignData.mChildren.size(); valueIdx++)
  17450. {
  17451. auto& child = deferredTupleAssignData.mChildren[valueIdx];
  17452. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[valueIdx];
  17453. BfTypedValue elementValue;
  17454. if (fieldInstance->mDataIdx >= 0)
  17455. {
  17456. rightValue = mModule->LoadOrAggregateValue(rightValue);
  17457. mModule->mBfIRBuilder->PopulateType(rightValue.mType);
  17458. auto extractedValue = mModule->mBfIRBuilder->CreateExtractValue(rightValue.mValue, fieldInstance->mDataIdx);
  17459. elementValue = BfTypedValue(extractedValue, fieldInstance->GetResolvedType());
  17460. if (child.mInnerTuple != NULL)
  17461. {
  17462. AssignDeferrredTupleAssignData(assignExpr, *child.mInnerTuple, elementValue);
  17463. delete child.mInnerTuple;
  17464. child.mInnerTuple = NULL;
  17465. }
  17466. else
  17467. {
  17468. if (child.mExprEvaluator->HasResult())
  17469. {
  17470. child.mExprEvaluator->mBfEvalExprFlags = (BfEvalExprFlags)(child.mExprEvaluator->mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete);
  17471. child.mExprEvaluator->PerformAssignment(assignExpr, true, elementValue);
  17472. }
  17473. }
  17474. }
  17475. if (child.mVarType != NULL)
  17476. {
  17477. if (auto varDecl = BfNodeDynCast<BfVariableDeclaration>(child.mExpr))
  17478. {
  17479. if (!elementValue)
  17480. elementValue = mModule->GetDefaultTypedValue(fieldInstance->GetResolvedType());
  17481. mModule->HandleVariableDeclaration(varDecl, elementValue);
  17482. }
  17483. else
  17484. {
  17485. // This handles the 'a*b' disambiguated variable decl case
  17486. mModule->HandleVariableDeclaration(child.mVarType, child.mVarNameNode, elementValue);
  17487. }
  17488. }
  17489. }
  17490. }
  17491. void BfExprEvaluator::DoTupleAssignment(BfAssignmentExpression* assignExpr)
  17492. {
  17493. auto tupleExpr = BfNodeDynCast<BfTupleExpression>(assignExpr->mLeft);
  17494. DeferredTupleAssignData deferredTupleAssignData;
  17495. PopulateDeferrredTupleAssignData(tupleExpr, deferredTupleAssignData);
  17496. BfTypeInstance* tupleType = deferredTupleAssignData.mTupleType;
  17497. BfTypedValue rightValue;
  17498. if (assignExpr->mRight != NULL)
  17499. {
  17500. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, tupleType);
  17501. }
  17502. if (!rightValue)
  17503. {
  17504. tupleType = mModule->SantizeTupleType(tupleType);
  17505. rightValue = mModule->GetDefaultTypedValue(tupleType);
  17506. }
  17507. rightValue = mModule->LoadValue(rightValue);
  17508. AssignDeferrredTupleAssignData(assignExpr, deferredTupleAssignData, rightValue);
  17509. mResult = rightValue;
  17510. }
  17511. BfTypedValue BfExprEvaluator::PerformAssignment_CheckOp(BfAssignmentExpression* assignExpr, bool deferBinop, BfTypedValue& leftValue, BfTypedValue& rightValue, bool& evaluatedRight)
  17512. {
  17513. BfResolvedArgs argValues;
  17514. auto checkTypeInst = leftValue.mType->ToTypeInstance();
  17515. while (checkTypeInst != NULL)
  17516. {
  17517. for (auto operatorDef : checkTypeInst->mTypeDef->mOperators)
  17518. {
  17519. if (operatorDef->mOperatorDeclaration->mAssignOp != assignExpr->mOp)
  17520. continue;
  17521. auto methodInst = mModule->GetRawMethodInstanceAtIdx(checkTypeInst, operatorDef->mIdx);
  17522. if (methodInst->GetParamCount() != 1)
  17523. continue;
  17524. auto paramType = methodInst->GetParamType(0);
  17525. if (deferBinop)
  17526. {
  17527. if (argValues.mArguments == NULL)
  17528. {
  17529. SizedArray<BfExpression*, 2> argExprs;
  17530. argExprs.push_back(assignExpr->mRight);
  17531. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  17532. argValues.Init(&sizedArgExprs);
  17533. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  17534. }
  17535. evaluatedRight = true;
  17536. rightValue = ResolveArgValue(argValues.mResolvedArgs[0], paramType);
  17537. if (!rightValue)
  17538. continue;
  17539. }
  17540. else
  17541. {
  17542. if (!mModule->CanCast(rightValue, paramType))
  17543. continue;
  17544. }
  17545. mModule->SetElementType(assignExpr->mOpToken, BfSourceElementType_Method);
  17546. auto autoComplete = GetAutoComplete();
  17547. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(assignExpr->mOpToken)))
  17548. {
  17549. if (operatorDef->mOperatorDeclaration != NULL)
  17550. autoComplete->SetDefinitionLocation(operatorDef->mOperatorDeclaration->mOpTypeToken);
  17551. }
  17552. auto moduleMethodInstance = mModule->GetMethodInstance(checkTypeInst, operatorDef, BfTypeVector());
  17553. BfExprEvaluator exprEvaluator(mModule);
  17554. SizedArray<BfIRValue, 1> args;
  17555. exprEvaluator.PushThis(assignExpr->mLeft, leftValue, moduleMethodInstance.mMethodInstance, args);
  17556. exprEvaluator.PushArg(rightValue, args);
  17557. exprEvaluator.CreateCall(assignExpr, moduleMethodInstance.mMethodInstance, moduleMethodInstance.mFunc, false, args);
  17558. return leftValue;
  17559. }
  17560. checkTypeInst = mModule->GetBaseType(checkTypeInst);
  17561. }
  17562. return BfTypedValue();
  17563. }
  17564. void BfExprEvaluator::PerformAssignment(BfAssignmentExpression* assignExpr, bool evaluatedLeft, BfTypedValue rightValue, BfTypedValue* outCascadeValue)
  17565. {
  17566. auto binaryOp = BfAssignOpToBinaryOp(assignExpr->mOp);
  17567. BfExpression* targetNode = assignExpr->mLeft;
  17568. if ((BfNodeIsA<BfMixinExpression>(targetNode)) && (!mModule->mCurMethodInstance->mIsUnspecialized))
  17569. {
  17570. // If we have a "mixin = <X>" but there's no mixin target then ignore the assignment
  17571. int mixinVar = GetMixinVariable();
  17572. if (mixinVar == -1)
  17573. {
  17574. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_None));
  17575. return;
  17576. }
  17577. }
  17578. BfAutoComplete* autoComplete = GetAutoComplete();
  17579. bool deferredFixits = false;
  17580. //TODO: Why was this needed? This breaks fixits on target nodes (ie: 'using' field fixit for 'fully quality')
  17581. /*if ((autoComplete != NULL) && (autoComplete->mResolveType == BfResolveType_GetFixits))
  17582. {
  17583. SetAndRestoreValue<bool> ignoreFixits(autoComplete->mIgnoreFixits, true);
  17584. VisitChild(targetNode);
  17585. deferredFixits = true;
  17586. }
  17587. else*/
  17588. if (!evaluatedLeft)
  17589. {
  17590. if (auto memberReferenceExpr = BfNodeDynCast<BfMemberReferenceExpression>(targetNode))
  17591. {
  17592. DoMemberReference(memberReferenceExpr, outCascadeValue);
  17593. }
  17594. else
  17595. VisitChild(targetNode);
  17596. }
  17597. if ((!mResult) && (mPropDef == NULL))
  17598. {
  17599. if (assignExpr->mRight != NULL)
  17600. {
  17601. auto result = mModule->CreateValueFromExpression(assignExpr->mRight);
  17602. if (deferredFixits)
  17603. {
  17604. SetAndRestoreValue<bool> ignoreErrors(mModule->mIgnoreErrors, true);
  17605. mExpectingType = result.mType;
  17606. VisitChild(targetNode);
  17607. mResult = BfTypedValue();
  17608. }
  17609. }
  17610. return;
  17611. }
  17612. ResolveGenericType();
  17613. auto ptr = mModule->RemoveRef(mResult);
  17614. mResult = BfTypedValue();
  17615. if (mPropDef != NULL)
  17616. {
  17617. bool hasLeftVal = false;
  17618. auto propDef = mPropDef;
  17619. auto propTarget = mPropTarget;
  17620. auto setMethod = GetPropertyMethodDef(mPropDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  17621. if (setMethod == NULL)
  17622. {
  17623. // Allow for a ref return on the getter to be used if a setter is not available
  17624. GetResult();
  17625. if ((mResult) && (mResult.mKind == BfTypedValueKind_Addr))
  17626. {
  17627. ptr = mResult;
  17628. mResult = BfTypedValue();
  17629. hasLeftVal = true;
  17630. }
  17631. else
  17632. {
  17633. mModule->Fail("Property has no setter", mPropSrc);
  17634. if (assignExpr->mRight != NULL)
  17635. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, BfEvalExprFlags_NoCast);
  17636. return;
  17637. }
  17638. }
  17639. if (!hasLeftVal)
  17640. {
  17641. auto methodInstance = GetPropertyMethodInstance(setMethod);
  17642. if (methodInstance.mMethodInstance == NULL)
  17643. return;
  17644. //BF_ASSERT(methodInstance.mMethodInstance->mMethodDef == setMethod);
  17645. CheckPropFail(setMethod, methodInstance.mMethodInstance, (mPropGetMethodFlags & BfGetMethodInstanceFlag_Friend) == 0);
  17646. auto autoComplete = GetAutoComplete();
  17647. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(mPropSrc)) && (autoComplete->mResolveType == BfResolveType_GetResultString))
  17648. {
  17649. autoComplete->mResultString = ":";
  17650. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetParamType(0));
  17651. autoComplete->mResultString += " ";
  17652. autoComplete->mResultString += mModule->TypeToString(methodInstance.mMethodInstance->GetOwner());
  17653. autoComplete->mResultString += ".";
  17654. autoComplete->mResultString += mPropDef->mName;
  17655. }
  17656. bool handled = false;
  17657. BfTypedValue convVal;
  17658. if (binaryOp != BfBinaryOp_None)
  17659. {
  17660. BfTypedValue leftValue = mModule->CreateValueFromExpression(assignExpr->mLeft, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  17661. if (!leftValue)
  17662. return;
  17663. bool evaluatedRight = false;
  17664. auto opResult = PerformAssignment_CheckOp(assignExpr, true, leftValue, rightValue, evaluatedRight);
  17665. if (opResult)
  17666. {
  17667. mResult = opResult;
  17668. return;
  17669. }
  17670. else
  17671. {
  17672. if (evaluatedRight)
  17673. {
  17674. if (!rightValue)
  17675. return;
  17676. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType, leftValue, rightValue);
  17677. }
  17678. else
  17679. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, BfBinOpFlag_ForceLeftType, leftValue);
  17680. if (!mResult)
  17681. return;
  17682. convVal = mResult;
  17683. mResult = BfTypedValue();
  17684. if (!convVal)
  17685. return;
  17686. }
  17687. }
  17688. else
  17689. {
  17690. auto wantType = methodInstance.mMethodInstance->GetParamType(0);
  17691. if (rightValue)
  17692. {
  17693. convVal = mModule->Cast(assignExpr->mRight, rightValue, wantType);
  17694. }
  17695. else
  17696. {
  17697. if (assignExpr->mRight == NULL)
  17698. {
  17699. mModule->AssertErrorState();
  17700. return;
  17701. }
  17702. BfEvalExprFlags exprFlags = (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_PendingPropSet);
  17703. if (wantType->IsRef())
  17704. exprFlags = (BfEvalExprFlags)(exprFlags | BfEvalExprFlags_AllowRefExpr);
  17705. convVal = mModule->CreateValueFromExpression(assignExpr->mRight, wantType, exprFlags);
  17706. }
  17707. if (!convVal)
  17708. {
  17709. mPropDef = NULL;
  17710. return;
  17711. }
  17712. }
  17713. if (!handled)
  17714. {
  17715. if (mPropSrc != NULL)
  17716. mModule->UpdateExprSrcPos(mPropSrc);
  17717. BfResolvedArg valueArg;
  17718. valueArg.mTypedValue = convVal;
  17719. mIndexerValues.Insert(0, valueArg);
  17720. if (!setMethod->mIsStatic)
  17721. {
  17722. auto owner = methodInstance.mMethodInstance->GetOwner();
  17723. if ((mPropTarget.mType != owner) ||
  17724. ((mPropTarget.mValue.IsFake()) && (!mOrigPropTarget.mValue.IsFake())))
  17725. {
  17726. if ((mPropDefBypassVirtual) || (!mPropTarget.mType->IsInterface()))
  17727. {
  17728. mPropTarget = mModule->Cast(mPropSrc, mOrigPropTarget, owner);
  17729. if (!mPropTarget)
  17730. {
  17731. mModule->Fail("Internal property error", mPropSrc);
  17732. return;
  17733. }
  17734. }
  17735. }
  17736. }
  17737. auto callFlags = mPropDefBypassVirtual ? BfCreateCallFlags_BypassVirtual : BfCreateCallFlags_None;
  17738. mResult = CreateCall(mPropSrc, mPropTarget, mOrigPropTarget, setMethod, methodInstance, callFlags, mIndexerValues, NULL);
  17739. mPropDef = NULL;
  17740. mResult = convVal;
  17741. mIndexerValues.Clear();
  17742. return;
  17743. }
  17744. }
  17745. }
  17746. auto toType = ptr.mType;
  17747. if (toType->IsRef())
  17748. {
  17749. auto refType = (BfRefType*)toType;
  17750. toType = refType->mElementType;
  17751. }
  17752. if (toType->IsIntUnknown())
  17753. toType = mModule->FixIntUnknown(toType);
  17754. if ((autoComplete != NULL) && (assignExpr->mOpToken != NULL) && (toType != NULL))
  17755. autoComplete->CheckEmptyStart(assignExpr->mOpToken, toType);
  17756. BfExpression* rightExpr = assignExpr->mRight;
  17757. if (rightExpr == NULL)
  17758. {
  17759. mModule->AssertErrorState();
  17760. return;
  17761. }
  17762. bool alreadyWritten = false;
  17763. BfTypedValue convVal;
  17764. if (binaryOp != BfBinaryOp_None)
  17765. {
  17766. CheckResultForReading(ptr);
  17767. BfTypedValue leftValue = ptr;
  17768. bool deferBinop = false;
  17769. BfDeferEvalChecker deferEvalChecker;
  17770. deferEvalChecker.mDeferLiterals = false;
  17771. assignExpr->mRight->Accept(&deferEvalChecker);
  17772. if (deferEvalChecker.mNeedsDeferEval)
  17773. deferBinop = true;
  17774. if (binaryOp == BfBinaryOp_NullCoalesce)
  17775. {
  17776. deferBinop = true;
  17777. }
  17778. if (!deferBinop)
  17779. {
  17780. auto expectedType = ptr.mType;
  17781. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  17782. expectedType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  17783. if ((!rightValue) && (assignExpr->mRight != NULL))
  17784. {
  17785. rightValue = mModule->CreateValueFromExpression(assignExpr->mRight, expectedType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  17786. }
  17787. }
  17788. BfResolvedArgs argValues;
  17789. if ((rightValue) || (deferBinop))
  17790. {
  17791. bool evaluatedRight = false;
  17792. auto opResult = PerformAssignment_CheckOp(assignExpr, deferBinop, leftValue, rightValue, evaluatedRight);
  17793. if (opResult)
  17794. {
  17795. mResult = opResult;
  17796. return;
  17797. }
  17798. else
  17799. {
  17800. auto flags = BfBinOpFlag_ForceLeftType;
  17801. if (deferBinop)
  17802. flags = (BfBinOpFlags)(flags | BfBinOpFlag_DeferRight);
  17803. leftValue = mModule->LoadValue(leftValue);
  17804. if (binaryOp == BfBinaryOp_NullCoalesce)
  17805. {
  17806. if (!CheckModifyResult(ptr, assignExpr->mOpToken, "assign to", false, false, true))
  17807. {
  17808. mModule->CreateValueFromExpression(assignExpr->mRight, ptr.mType, (BfEvalExprFlags)(BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  17809. mResult = leftValue;
  17810. return;
  17811. }
  17812. if (PerformBinaryOperation_NullCoalesce(assignExpr->mOpToken, assignExpr->mLeft, assignExpr->mRight, leftValue, leftValue.mType, &ptr))
  17813. return;
  17814. }
  17815. PerformBinaryOperation(assignExpr->mLeft, assignExpr->mRight, binaryOp, assignExpr->mOpToken, flags, leftValue, rightValue);
  17816. }
  17817. }
  17818. convVal = mResult;
  17819. mResult = BfTypedValue();
  17820. if (!convVal)
  17821. return;
  17822. }
  17823. else
  17824. {
  17825. convVal = rightValue;
  17826. if (!convVal)
  17827. {
  17828. if (auto uninitExpr = BfNodeDynCast<BfUninitializedExpression>(rightExpr))
  17829. {
  17830. if (mResultLocalVar != NULL)
  17831. {
  17832. MarkResultAssigned();
  17833. return;
  17834. }
  17835. }
  17836. // In the cases like "structVal = GetVal()", the allowDirectStructRetWrite optimization allows us to pass the
  17837. // address of structVal into the sret. We only allow that if structVal is a local, because if it's globally
  17838. // visible then we could see the results of a partially-modified structVal
  17839. //bool allowDirectStructRetWrite = mResultLocalVarIdx != -1;
  17840. // ALTHOUGH- we can only allow this optimization if we can be sure the local value is not aliased- we could
  17841. // have the backend ensure that this local value never gets its address taken.
  17842. bool allowDirectStructWrite = false;
  17843. BfExprEvaluator exprEvaluator(mModule);
  17844. exprEvaluator.mExpectingType = toType;
  17845. if (allowDirectStructWrite)
  17846. exprEvaluator.mReceivingValue = &ptr;
  17847. exprEvaluator.Evaluate(rightExpr, false, false, true);
  17848. exprEvaluator.CheckResultForReading(exprEvaluator.mResult);
  17849. convVal = exprEvaluator.GetResult();
  17850. mModule->FixIntUnknown(convVal);
  17851. alreadyWritten = (allowDirectStructWrite) && (exprEvaluator.mReceivingValue == NULL);
  17852. if (!convVal)
  17853. convVal = mModule->GetDefaultTypedValue(toType);
  17854. // Did we use mReceivingValue as a mixin result?
  17855. if ((convVal.mValue) && (convVal.mValue == ptr.mValue))
  17856. {
  17857. mResult = convVal;
  17858. return;
  17859. }
  17860. }
  17861. }
  17862. if (!CheckModifyResult(ptr, assignExpr->mOpToken, "assign to", false, false, true))
  17863. {
  17864. mResult = convVal;
  17865. return;
  17866. }
  17867. if (ptr.mKind == BfTypedValueKind_CopyOnMutateAddr)
  17868. ptr.mKind = BfTypedValueKind_Addr;
  17869. else if (ptr.IsCopyOnMutate())
  17870. ptr = mModule->CopyValue(ptr);
  17871. BF_ASSERT(convVal);
  17872. if ((convVal) && (convVal.mType->IsNull()) && (ptr.mType->IsNullable()))
  17873. {
  17874. // Allow this to pass through so we can catch it in the memset later in this function
  17875. }
  17876. else
  17877. {
  17878. if (!convVal.mType->IsComposite())
  17879. convVal = mModule->LoadValue(convVal);
  17880. convVal = mModule->Cast(rightExpr, convVal, toType);
  17881. if (!convVal)
  17882. return;
  17883. convVal = mModule->LoadValue(convVal);
  17884. }
  17885. if (ptr.mType->IsVar())
  17886. {
  17887. mResult = ptr;
  17888. MarkResultAssigned();
  17889. return;
  17890. }
  17891. if (convVal.mValue)
  17892. {
  17893. if ((ptr.mType->IsStruct()) && (!ptr.mType->IsValuelessType()) && (convVal.mValue.IsConst()))
  17894. {
  17895. auto constant = mModule->mBfIRBuilder->GetConstant(convVal.mValue);
  17896. if ((constant->mTypeCode == BfTypeCode_NullPtr) || (constant->mConstType == BfConstType_AggZero))
  17897. {
  17898. auto type = ptr.mType;
  17899. mModule->mBfIRBuilder->CreateMemSet(ptr.mValue, mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_Int8)),
  17900. mModule->GetConstValue(type->mSize), type->mAlign);
  17901. mResult = ptr;
  17902. MarkResultAssigned();
  17903. return;
  17904. }
  17905. }
  17906. // if (ptr.mType->IsMethodRef())
  17907. // {
  17908. // auto methodRefType = (BfMethodRefType*)ptr.mType;
  17909. // auto methodInstance = methodRefType->mMethodInstance;
  17910. // int implicitParamCount = methodInstance->GetImplicitParamCount();
  17911. // for (int implicitParamIdx = methodInstance->HasThis() ? - 1 : 0; implicitParamIdx < implicitParamCount; implicitParamIdx++)
  17912. // {
  17913. // bool failed = false;
  17914. // auto destPtr = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericTypeMember_Addr);
  17915. // auto srcVal = DoImplicitArgCapture(assignExpr, methodRefType->mMethodInstance, implicitParamIdx, failed, BfImplicitParamKind_GenericMethodMember);
  17916. // if ((destPtr) && (srcVal))
  17917. // {
  17918. // srcVal = mModule->AggregateSplat(srcVal);
  17919. // mModule->mBfIRBuilder->CreateStore(srcVal.mValue, destPtr.mValue);
  17920. // }
  17921. // }
  17922. // }
  17923. // else
  17924. {
  17925. mModule->mBfIRBuilder->PopulateType(ptr.mType);
  17926. if (convVal.IsSplat())
  17927. {
  17928. //convVal = mModule->AggregateSplat(convVal);
  17929. mModule->AggregateSplatIntoAddr(convVal, ptr.mValue);
  17930. }
  17931. else
  17932. {
  17933. if (ptr.mType->IsValuelessType())
  17934. {
  17935. mModule->EmitEnsureInstructionAt();
  17936. }
  17937. else if (!alreadyWritten)
  17938. {
  17939. if ((mModule->mIsComptimeModule) && (mModule->mCompiler->mCeMachine->mDebugger != NULL) && (mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState != NULL))
  17940. {
  17941. auto ceDbgState = mModule->mCompiler->mCeMachine->mDebugger->mCurDbgState;
  17942. bool success = false;
  17943. if ((convVal.mValue.IsConst()) && (ptr.mValue.IsConst()))
  17944. {
  17945. auto constant = mModule->mBfIRBuilder->GetConstant(ptr.mValue);
  17946. auto valConstant = mModule->mBfIRBuilder->GetConstant(convVal.mValue);
  17947. auto ceTypedVal = mModule->mCompiler->mCeMachine->mDebugger->GetAddr(constant);
  17948. if (!ceTypedVal)
  17949. {
  17950. mModule->Fail("Invalid assignment address", assignExpr);
  17951. return;
  17952. }
  17953. auto ceContext = mModule->mCompiler->mCeMachine->mCurContext;
  17954. if (ceContext->CheckMemory((addr_ce)ceTypedVal.mAddr, convVal.mType->mSize))
  17955. {
  17956. if ((ceDbgState->mDbgExpressionFlags & DwEvalExpressionFlag_AllowSideEffects) != 0)
  17957. {
  17958. ceDbgState->mHadSideEffects = true;
  17959. if (ceContext->WriteConstant(mModule, (addr_ce)ceTypedVal.mAddr, valConstant, convVal.mType))
  17960. success = true;
  17961. }
  17962. else
  17963. {
  17964. ceDbgState->mBlockedSideEffects = true;
  17965. success = true;
  17966. }
  17967. }
  17968. }
  17969. if (!success)
  17970. {
  17971. mModule->Fail("Assignment failed", assignExpr);
  17972. return;
  17973. }
  17974. }
  17975. if (!alreadyWritten)
  17976. {
  17977. //ptr = mModule->LoadValue(ptr);
  17978. BF_ASSERT(ptr.IsAddr());
  17979. convVal = mModule->LoadValue(convVal);
  17980. auto storeInst = mModule->mBfIRBuilder->CreateAlignedStore(convVal.mValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  17981. }
  17982. }
  17983. }
  17984. }
  17985. }
  17986. else
  17987. {
  17988. BF_ASSERT(convVal.mType->IsValuelessType());
  17989. }
  17990. mResult = convVal;
  17991. MarkResultAssigned();
  17992. }
  17993. void BfExprEvaluator::Visit(BfAssignmentExpression* assignExpr)
  17994. {
  17995. if (assignExpr->mLeft->IsA<BfTupleExpression>())
  17996. {
  17997. DoTupleAssignment(assignExpr);
  17998. return;
  17999. }
  18000. BfAutoParentNodeEntry autoParentNodeEntry(mModule, assignExpr);
  18001. BfTypedValue cascadeValue;
  18002. PerformAssignment(assignExpr, false, BfTypedValue(), &cascadeValue);
  18003. if (cascadeValue)
  18004. mResult = cascadeValue;
  18005. }
  18006. void BfExprEvaluator::Visit(BfParenthesizedExpression* parenExpr)
  18007. {
  18008. VisitChild(parenExpr->mExpression);
  18009. MakeResultAsValue();
  18010. }
  18011. void BfExprEvaluator::InitializedSizedArray(BfSizedArrayType* arrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, BfTypedValue* receivingValue)
  18012. {
  18013. struct InitValue
  18014. {
  18015. BfTypedValue mValue;
  18016. bool mIsUninitialized;
  18017. bool mIsDefaultInitializer;
  18018. bool mIsDeferred;
  18019. InitValue()
  18020. {
  18021. mIsUninitialized = false;
  18022. mIsDefaultInitializer = false;
  18023. mIsDeferred = false;
  18024. }
  18025. };
  18026. SizedArray<InitValue, 8> values;
  18027. {
  18028. //bool hasFailed = false;
  18029. HashSet<int> failedAt;
  18030. bool isAllConst = true;
  18031. //bool endUninitialzied = false;
  18032. int depth = 0;
  18033. std::function<void(BfSizedArrayType*, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*, bool)>
  18034. _GetValues = [&](BfSizedArrayType* checkArrayType, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken, bool ignore)
  18035. {
  18036. int64 initCountDiff = (int)valueExprs.size() - checkArrayType->mElementCount;
  18037. if ((initCountDiff != 0) && (!valueExprs.IsEmpty()) && (!failedAt.Contains(depth)))
  18038. {
  18039. if (checkArrayType->mElementCount == -1)
  18040. {
  18041. // mModule->Fail("Initializers not supported for unknown-sized arrays", valueExprs[0]);
  18042. // failedAt.Add(depth);
  18043. }
  18044. else if (initCountDiff > 0)
  18045. {
  18046. mModule->Fail(StrFormat("Too many initializers, expected %d fewer", initCountDiff), valueExprs[BF_MAX((int)checkArrayType->mElementCount, 0)]);
  18047. failedAt.Add(depth);
  18048. }
  18049. else
  18050. {
  18051. // If it ends with ", ?) or ",)" then allow unsized
  18052. if (((valueExprs.size() == 0) || (BfNodeDynCast<BfUninitializedExpression>(valueExprs.back()) == NULL)) &&
  18053. ((commas.size() < valueExprs.size()) || (valueExprs.size() == 0)))
  18054. {
  18055. BfAstNode* refNode = closeToken;
  18056. if ((refNode == NULL) && (mModule->mParentNodeEntry != NULL))
  18057. refNode = mModule->mParentNodeEntry->mNode;
  18058. BF_ASSERT(refNode != NULL);
  18059. mModule->Fail(StrFormat("Too few initializer, expected %d more", -initCountDiff), refNode);
  18060. failedAt.Add(depth);
  18061. }
  18062. }
  18063. }
  18064. for (int idx = 0; idx < BF_MAX(checkArrayType->mElementCount, valueExprs.size()); idx++)
  18065. {
  18066. BfTypedValue elementValue;
  18067. bool deferredValue = false;
  18068. BfExpression* expr = NULL;
  18069. if (idx < (int)valueExprs.size())
  18070. {
  18071. expr = valueExprs[idx];
  18072. if (expr == NULL)
  18073. {
  18074. if (idx == 0)
  18075. mModule->FailAfter("Expression expected", openToken);
  18076. else
  18077. mModule->FailAfter("Expression expected", commas[idx - 1]);
  18078. }
  18079. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  18080. {
  18081. isAllConst = false;
  18082. break;
  18083. }
  18084. if (checkArrayType->mElementType->IsSizedArray())
  18085. {
  18086. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  18087. {
  18088. depth++;
  18089. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen, ignore);
  18090. depth--;
  18091. continue;
  18092. }
  18093. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  18094. {
  18095. depth++;
  18096. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace, ignore);
  18097. depth--;
  18098. continue;
  18099. }
  18100. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  18101. {
  18102. depth++;
  18103. SizedArray<BfExpression*, 1> values;
  18104. values.Add(parenExpr->mExpression);
  18105. SizedArray<BfTokenNode*, 1> commas;
  18106. _GetValues((BfSizedArrayType*)checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen, ignore);
  18107. depth--;
  18108. continue;
  18109. }
  18110. }
  18111. if (expr != NULL)
  18112. {
  18113. auto evalFlags = (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags);
  18114. bool tryDefer = false;
  18115. if ((checkArrayType->IsComposite()) &&
  18116. ((expr->IsA<BfInvocationExpression>()) || (expr->IsExact<BfTupleExpression>())))
  18117. {
  18118. // We evaluate with a new scope because this expression may create variables that we don't want to be visible to other
  18119. // non-deferred evaluations (since the value may actually be a FakeVal)
  18120. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  18121. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType, (BfEvalExprFlags)(evalFlags | BfEvalExprFlags_CreateConditionalScope));
  18122. deferredValue = !prevIgnoreWrites.mPrevVal && elementValue.mValue.IsFake();
  18123. }
  18124. else
  18125. {
  18126. elementValue = mModule->CreateValueFromExpression(expr, checkArrayType->mElementType, evalFlags);
  18127. }
  18128. if (!elementValue)
  18129. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  18130. if ((!elementValue) || (!CheckAllowValue(elementValue, expr)))
  18131. elementValue = mModule->GetDefaultTypedValue(checkArrayType->mElementType);
  18132. // For now, we can't properly create const-valued non-size-aligned composites
  18133. if (!elementValue.mValue.IsConst())
  18134. isAllConst = false;
  18135. if (elementValue.IsAddr())
  18136. isAllConst = false;
  18137. InitValue initValue;
  18138. initValue.mValue = elementValue;
  18139. initValue.mIsDeferred = deferredValue;
  18140. values.push_back(initValue);
  18141. }
  18142. }
  18143. }
  18144. };
  18145. int valueIdx = 0;
  18146. std::function<void(BfTypedValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  18147. _CreateMemArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  18148. {
  18149. BF_ASSERT(arrayValue.mType->IsSizedArray());
  18150. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  18151. int valIdx = 0;
  18152. bool hasUninit = false;
  18153. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  18154. {
  18155. BfExpression* expr = NULL;
  18156. BfTypedValue elementValue;
  18157. if (idx >= (int)valueExprs.size())
  18158. break;
  18159. expr = valueExprs[idx];
  18160. if ((BfNodeDynCastExact<BfUninitializedExpression>(expr) != NULL) && (idx == (int)commas.size()))
  18161. {
  18162. hasUninit = true;
  18163. break;
  18164. }
  18165. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  18166. valIdx++;
  18167. if (checkArrayType->mElementType->IsSizedArray())
  18168. {
  18169. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  18170. {
  18171. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen);
  18172. continue;
  18173. }
  18174. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  18175. {
  18176. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace);
  18177. continue;
  18178. }
  18179. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  18180. {
  18181. depth++;
  18182. SizedArray<BfExpression*, 1> values;
  18183. values.Add(parenExpr->mExpression);
  18184. SizedArray<BfTokenNode*, 1> commas;
  18185. _CreateMemArray(BfTypedValue(elemPtrValue, checkArrayType->mElementType, true), parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen);
  18186. depth--;
  18187. continue;
  18188. }
  18189. }
  18190. if (expr != NULL)
  18191. {
  18192. InitValue initValue = values[valueIdx++];
  18193. elementValue = initValue.mValue;
  18194. if (initValue.mIsDeferred)
  18195. {
  18196. BfTypedValue elemePtrTypedVal = BfTypedValue(elemPtrValue, checkArrayType->mElementType, BfTypedValueKind_Addr);
  18197. BfExprEvaluator exprEvaluator(mModule);
  18198. exprEvaluator.mExpectingType = checkArrayType->mElementType;
  18199. exprEvaluator.mReceivingValue = &elemePtrTypedVal;
  18200. exprEvaluator.Evaluate(expr);
  18201. exprEvaluator.GetResult();
  18202. if (exprEvaluator.mReceivingValue == NULL)
  18203. {
  18204. // We wrote directly to the array in-place, we're done with this element
  18205. continue;
  18206. }
  18207. elementValue = exprEvaluator.mResult;
  18208. elementValue = mModule->Cast(expr, elementValue, checkArrayType->mElementType);
  18209. if (!elementValue)
  18210. {
  18211. mModule->AssertErrorState();
  18212. continue;
  18213. }
  18214. }
  18215. elementValue = mModule->LoadValue(elementValue);
  18216. mModule->mBfIRBuilder->CreateAlignedStore(elementValue.mValue, elemPtrValue, checkArrayType->mElementType->mAlign);
  18217. }
  18218. }
  18219. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  18220. if (fillCount > 0)
  18221. {
  18222. BfIRValue elemPtrValue = mModule->CreateIndexedValue(checkArrayType->mElementType, arrayValue.mValue, valIdx, true);
  18223. if (hasUninit)
  18224. {
  18225. if (!mModule->IsOptimized())
  18226. {
  18227. int setSize = std::min(checkArrayType->mElementType->mSize, 128); // Keep it to a reasonable number of bytes to trash
  18228. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0xCC),
  18229. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  18230. }
  18231. }
  18232. else
  18233. {
  18234. int setSize = (int)((checkArrayType->mElementType->GetStride() * (fillCount - 1)) + checkArrayType->mElementType->mSize);
  18235. if (setSize >= 0)
  18236. {
  18237. mModule->mBfIRBuilder->CreateMemSet(elemPtrValue, mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 0),
  18238. mModule->GetConstValue(setSize), checkArrayType->mElementType->mAlign);
  18239. }
  18240. }
  18241. }
  18242. };
  18243. std::function<BfIRValue(BfTypedValue, BfTokenNode*, const BfSizedArray<BfExpression*>&, const BfSizedArray<BfTokenNode*>&, BfTokenNode*)>
  18244. _CreateConstArray = [&](BfTypedValue arrayValue, BfTokenNode* openToken, const BfSizedArray<BfExpression*>& valueExprs, const BfSizedArray<BfTokenNode*>& commas, BfTokenNode* closeToken)
  18245. {
  18246. SizedArray<BfIRValue, 8> members;
  18247. BF_ASSERT(arrayValue.mType->IsSizedArray());
  18248. auto checkArrayType = (BfSizedArrayType*)arrayValue.mType;
  18249. int valIdx = 0;
  18250. for (int idx = 0; idx < checkArrayType->mElementCount; idx++)
  18251. {
  18252. BfTypedValue elementValue;
  18253. if (idx >= (int)valueExprs.size())
  18254. break;
  18255. auto expr = valueExprs[idx];
  18256. if (expr == NULL)
  18257. continue;
  18258. valIdx++;
  18259. if (checkArrayType->mElementType->IsSizedArray())
  18260. {
  18261. if (auto arrayInitExpr = BfNodeDynCast<BfTupleExpression>(expr))
  18262. {
  18263. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenParen, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseParen));
  18264. continue;
  18265. }
  18266. else if (auto arrayInitExpr = BfNodeDynCast<BfCollectionInitializerExpression>(expr))
  18267. {
  18268. members.push_back(_CreateConstArray(checkArrayType->mElementType, arrayInitExpr->mOpenBrace, arrayInitExpr->mValues, arrayInitExpr->mCommas, arrayInitExpr->mCloseBrace));
  18269. continue;
  18270. }
  18271. else if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(expr))
  18272. {
  18273. depth++;
  18274. SizedArray<BfExpression*, 1> values;
  18275. values.Add(parenExpr->mExpression);
  18276. SizedArray<BfTokenNode*, 1> commas;
  18277. members.push_back(_CreateConstArray(checkArrayType->mElementType, parenExpr->mOpenParen, values, commas, parenExpr->mCloseParen));
  18278. depth--;
  18279. continue;
  18280. }
  18281. }
  18282. InitValue initValue = values[valueIdx++];
  18283. BF_ASSERT(!initValue.mIsUninitialized);
  18284. elementValue = initValue.mValue;
  18285. members.push_back(elementValue.mValue);
  18286. }
  18287. int fillCount = (int)(checkArrayType->mElementCount - valIdx);
  18288. if (fillCount > 0)
  18289. {
  18290. // We just need to insert one default value, it will be duplicated as needed into the backend
  18291. auto defaultVal = mModule->GetDefaultTypedValue(checkArrayType->GetUnderlyingType());
  18292. BF_ASSERT(defaultVal.mValue.IsConst());
  18293. members.push_back(defaultVal.mValue);
  18294. }
  18295. auto allocArrayType = checkArrayType;
  18296. if (checkArrayType->IsUndefSizedArray())
  18297. allocArrayType = mModule->CreateSizedArrayType(checkArrayType->GetUnderlyingType(), (int)members.size());
  18298. return mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(checkArrayType), members);
  18299. };
  18300. _GetValues(arrayType, openToken, valueExprs, commas, closeToken, false);
  18301. if (!failedAt.IsEmpty())
  18302. {
  18303. mResult = mModule->GetDefaultTypedValue(arrayType, false, BfDefaultValueKind_Addr);
  18304. return;
  18305. }
  18306. if (receivingValue != NULL)
  18307. {
  18308. BF_ASSERT(receivingValue->mType == arrayType);
  18309. BF_ASSERT(receivingValue->IsAddr());
  18310. mResult = *receivingValue;
  18311. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  18312. }
  18313. else if (isAllConst)
  18314. {
  18315. mResult = BfTypedValue(_CreateConstArray(arrayType, openToken, valueExprs, commas, closeToken), arrayType, BfTypedValueKind_Value);
  18316. }
  18317. else
  18318. {
  18319. if ((mReceivingValue != NULL) && (mReceivingValue->mType == arrayType) && (mReceivingValue->IsAddr()))
  18320. {
  18321. mResult = *mReceivingValue;
  18322. mReceivingValue = NULL;
  18323. }
  18324. else
  18325. {
  18326. auto arrayValue = mModule->CreateAlloca(arrayType);
  18327. mResult = BfTypedValue(arrayValue, arrayType, BfTypedValueKind_TempAddr);
  18328. }
  18329. if (!arrayType->IsValuelessType())
  18330. _CreateMemArray(mResult, openToken, valueExprs, commas, closeToken);
  18331. }
  18332. }
  18333. }
  18334. void BfExprEvaluator::Visit(BfTupleExpression* tupleExpr)
  18335. {
  18336. BfTypeInstance* tupleType = NULL;
  18337. bool hadFullMatch = false;
  18338. if ((mExpectingType != NULL) && (mExpectingType->IsTuple()))
  18339. {
  18340. tupleType = (BfTypeInstance*)mExpectingType;
  18341. hadFullMatch = tupleType->mFieldInstances.size() == tupleExpr->mValues.size();
  18342. }
  18343. struct InitValue
  18344. {
  18345. BfTypedValue mValue;
  18346. bool mIsUninitialized;
  18347. bool mIsDefaultInitializer;
  18348. bool mIsDeferred;
  18349. InitValue()
  18350. {
  18351. mIsUninitialized = false;
  18352. mIsDefaultInitializer = false;
  18353. mIsDeferred = false;
  18354. }
  18355. };
  18356. SizedArray<BfTypedValue, 2> typedValues;
  18357. if ((tupleExpr->mCommas.size() != 0) && (tupleExpr->mCommas.size() >= tupleExpr->mValues.size()))
  18358. {
  18359. // We would normally give this error during syntax parsing, but a TupleExpression can be an array initializer
  18360. mModule->FailAfter("Expression expected", tupleExpr->mCommas.back());
  18361. }
  18362. for (int valueIdx = 0; valueIdx < (int)tupleExpr->mValues.size(); valueIdx++)
  18363. {
  18364. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  18365. BfType* fieldType = NULL;
  18366. BfFieldInstance* fieldInstance = NULL;
  18367. if (tupleType != NULL)
  18368. {
  18369. if (valueIdx < (int)tupleType->mFieldInstances.size())
  18370. {
  18371. fieldInstance = (BfFieldInstance*)&tupleType->mFieldInstances[valueIdx];
  18372. fieldType = fieldInstance->GetResolvedType();
  18373. if (fieldType->IsVoid())
  18374. {
  18375. typedValues.push_back(BfTypedValue());
  18376. continue;
  18377. }
  18378. if (fieldType->IsVar())
  18379. {
  18380. hadFullMatch = false;
  18381. fieldType = NULL;
  18382. }
  18383. }
  18384. }
  18385. bool tryDefer = false;
  18386. if (((fieldType == NULL) || (fieldType->IsComposite())) &&
  18387. ((valueExpr->IsA<BfInvocationExpression>()) || (valueExpr->IsExact<BfTupleExpression>())))
  18388. {
  18389. tryDefer = true;
  18390. }
  18391. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, mModule->mBfIRBuilder->mIgnoreWrites || tryDefer);
  18392. BfTypedValue value = mModule->CreateValueFromExpression(valueExpr, fieldType);
  18393. if (!value)
  18394. {
  18395. if (fieldType != NULL)
  18396. value = mModule->GetDefaultTypedValue(fieldType);
  18397. else
  18398. value = mModule->GetDefaultTypedValue(mModule->mContext->mBfObjectType);
  18399. }
  18400. if ((fieldInstance != NULL) && (!fieldInstance->GetFieldDef()->IsUnnamedTupleField()) && (valueIdx < (int)tupleExpr->mNames.size()))
  18401. {
  18402. auto checkName = tupleExpr->mNames[valueIdx];
  18403. if (checkName != NULL)
  18404. {
  18405. if (checkName->ToString() != fieldInstance->GetFieldDef()->mName)
  18406. hadFullMatch = false;
  18407. }
  18408. }
  18409. value = mModule->LoadValue(value);
  18410. typedValues.push_back(value);
  18411. }
  18412. if (!hadFullMatch)
  18413. {
  18414. BfTypeVector fieldTypes;
  18415. Array<String> fieldNames;
  18416. HashSet<String> fieldNameSet;
  18417. for (auto typedVal : typedValues)
  18418. {
  18419. auto type = typedVal.mType;
  18420. if (type != NULL)
  18421. fieldTypes.push_back(type);
  18422. else
  18423. fieldTypes.push_back(mModule->mContext->mBfObjectType);
  18424. }
  18425. for (BfTupleNameNode* requestedName : tupleExpr->mNames)
  18426. {
  18427. if (requestedName == NULL)
  18428. fieldNames.push_back("");
  18429. else
  18430. {
  18431. auto fieldName = requestedName->mNameNode->ToString();
  18432. if (!fieldNameSet.TryAdd(fieldName, NULL))
  18433. {
  18434. mModule->Fail(StrFormat("A field named '%s' has already been declared", fieldName.c_str()), requestedName->mNameNode);
  18435. }
  18436. fieldNames.push_back(fieldName);
  18437. }
  18438. }
  18439. tupleType = mModule->CreateTupleType(fieldTypes, fieldNames);
  18440. }
  18441. mModule->mBfIRBuilder->PopulateType(tupleType);
  18442. BfIRValue curTupleValue;
  18443. if ((mReceivingValue != NULL) && (mReceivingValue->mType == tupleType) && (mReceivingValue->IsAddr()))
  18444. {
  18445. mResult = *mReceivingValue;
  18446. mReceivingValue = NULL;
  18447. curTupleValue = mResult.mValue;
  18448. }
  18449. else
  18450. {
  18451. int valueIdx = -1;
  18452. bool isExactConst = true;
  18453. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  18454. {
  18455. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  18456. if (fieldInstance->mDataIdx < 0)
  18457. continue;
  18458. ++valueIdx;
  18459. auto typedValue = typedValues[valueIdx];
  18460. if (typedValue.mType != fieldInstance->mResolvedType)
  18461. {
  18462. isExactConst = false;
  18463. break;
  18464. }
  18465. if (!typedValue.mValue.IsConst())
  18466. {
  18467. isExactConst = false;
  18468. break;
  18469. }
  18470. }
  18471. if (isExactConst)
  18472. {
  18473. mModule->PopulateType(tupleType);
  18474. Array<BfIRValue> irValues;
  18475. irValues.Resize(typedValues.mSize + 1);
  18476. irValues[0] = mModule->mBfIRBuilder->CreateConstAggZero(mModule->mBfIRBuilder->MapType(tupleType->mBaseType));
  18477. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  18478. {
  18479. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  18480. if (fieldInstance->mDataIdx < 0)
  18481. continue;
  18482. irValues[fieldInstance->mDataIdx] = typedValues[fieldIdx].mValue;
  18483. }
  18484. for (auto& val : irValues)
  18485. {
  18486. if (!val)
  18487. val = mModule->mBfIRBuilder->CreateConstArrayZero(0);
  18488. }
  18489. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(tupleType), irValues), tupleType);
  18490. return;
  18491. }
  18492. curTupleValue = mModule->CreateAlloca(tupleType);
  18493. mResultIsTempComposite = true;
  18494. mResult = BfTypedValue(curTupleValue, tupleType, BfTypedValueKind_TempAddr);
  18495. }
  18496. int valueIdx = -1;
  18497. for (int fieldIdx = 0; fieldIdx < (int)tupleType->mFieldInstances.size(); fieldIdx++)
  18498. {
  18499. BfFieldInstance* fieldInstance = &tupleType->mFieldInstances[fieldIdx];
  18500. ++valueIdx;
  18501. if (fieldInstance->mResolvedType->IsValuelessType())
  18502. continue;
  18503. auto typedVal = typedValues[valueIdx];
  18504. if (!typedVal)
  18505. {
  18506. mModule->AssertErrorState();
  18507. continue;
  18508. }
  18509. if (fieldInstance->mDataIdx >= 0)
  18510. {
  18511. auto memberVal = mModule->mBfIRBuilder->CreateInBoundsGEP(curTupleValue, 0, fieldInstance->mDataIdx);
  18512. if ((!mModule->mBfIRBuilder->mIgnoreWrites) && (typedVal.mValue.IsFake()))
  18513. {
  18514. // Value was deferred. Allow us to try to init in place
  18515. BfExpression* valueExpr = tupleExpr->mValues[valueIdx];
  18516. BfTypedValue memberPtrTypedVal = BfTypedValue(memberVal, fieldInstance->mResolvedType, BfTypedValueKind_Addr);
  18517. BfExprEvaluator exprEvaluator(mModule);
  18518. exprEvaluator.mExpectingType = fieldInstance->mResolvedType;
  18519. exprEvaluator.mReceivingValue = &memberPtrTypedVal;
  18520. exprEvaluator.Evaluate(valueExpr);
  18521. exprEvaluator.GetResult();
  18522. if (exprEvaluator.mReceivingValue == NULL)
  18523. {
  18524. // We wrote directly to the array in-place, we're done with this element
  18525. continue;
  18526. }
  18527. typedVal = exprEvaluator.mResult;
  18528. typedVal = mModule->Cast(valueExpr, typedVal, fieldInstance->mResolvedType);
  18529. if (!typedVal)
  18530. {
  18531. mModule->AssertErrorState();
  18532. continue;
  18533. }
  18534. typedVal = mModule->LoadValue(typedVal);
  18535. }
  18536. if (typedVal.mType->IsVar())
  18537. {
  18538. // Do nothing
  18539. }
  18540. else if (typedVal.IsSplat())
  18541. mModule->AggregateSplatIntoAddr(typedVal, memberVal);
  18542. else
  18543. mModule->mBfIRBuilder->CreateAlignedStore(typedVal.mValue, memberVal, typedVal.mType->mAlign);
  18544. }
  18545. }
  18546. }
  18547. BfTypedValue BfExprEvaluator::SetupNullConditional(BfTypedValue thisValue, BfTokenNode* dotToken)
  18548. {
  18549. bool isStaticLookup = (!thisValue) ||
  18550. ((!thisValue.mType->IsValuelessType()) && (!thisValue.mValue));
  18551. if (isStaticLookup)
  18552. {
  18553. mModule->Fail("Null conditional reference not valid for static field references", dotToken);
  18554. return thisValue;
  18555. }
  18556. auto opResult = PerformUnaryOperation_TryOperator(thisValue, NULL, BfUnaryOp_NullConditional, dotToken, BfUnaryOpFlag_None);
  18557. if (opResult)
  18558. thisValue = opResult;
  18559. if (thisValue.mType->IsGenericParam())
  18560. {
  18561. bool isValid = false;
  18562. auto genericParams = mModule->GetGenericParamInstance((BfGenericParamType*)thisValue.mType);
  18563. if (genericParams->mTypeConstraint != NULL)
  18564. {
  18565. if ((genericParams->mTypeConstraint->IsNullable()) ||
  18566. (genericParams->mTypeConstraint->IsPointer()) ||
  18567. (genericParams->mTypeConstraint->IsObjectOrInterface()))
  18568. isValid = true;
  18569. }
  18570. if ((genericParams->mGenericParamFlags & (BfGenericParamFlag_Var | BfGenericParamFlag_StructPtr | BfGenericParamFlag_Class)) != 0)
  18571. isValid = true;
  18572. if (isValid)
  18573. return thisValue;
  18574. }
  18575. if ((thisValue.mType->IsNullable()) || (thisValue.mType->IsVar()))
  18576. {
  18577. // Success
  18578. }
  18579. else if ((thisValue.mType->IsPointer()) || (thisValue.mType->IsObjectOrInterface()))
  18580. {
  18581. // Also good
  18582. }
  18583. else
  18584. {
  18585. bool canBeNull = false;
  18586. if (thisValue.mType->IsGenericParam())
  18587. canBeNull = true;
  18588. if (!canBeNull)
  18589. mModule->Warn(0, StrFormat("Null conditional reference is unnecessary since value type '%s' can never be null", mModule->TypeToString(thisValue.mType).c_str()), dotToken);
  18590. return thisValue;
  18591. }
  18592. thisValue = mModule->LoadValue(thisValue);
  18593. if (thisValue.mType->IsVar())
  18594. return thisValue;
  18595. BfPendingNullConditional* pendingNullCond = mModule->mCurMethodState->mPendingNullConditional;
  18596. if (pendingNullCond == NULL)
  18597. {
  18598. pendingNullCond = new BfPendingNullConditional();
  18599. mModule->mCurMethodState->mPendingNullConditional = pendingNullCond;
  18600. }
  18601. if (!pendingNullCond->mPrevBB)
  18602. pendingNullCond->mPrevBB = mModule->mBfIRBuilder->GetInsertBlock();
  18603. if (!pendingNullCond->mDoneBB)
  18604. pendingNullCond->mDoneBB = mModule->mBfIRBuilder->CreateBlock("nullCond.done");
  18605. // We will in the br to checkBB later
  18606. if (!pendingNullCond->mCheckBB)
  18607. {
  18608. pendingNullCond->mCheckBB = mModule->mBfIRBuilder->CreateBlock("nullCond.check");
  18609. mModule->AddBasicBlock(pendingNullCond->mCheckBB);
  18610. }
  18611. BfIRValue isNotNull;
  18612. if (thisValue.mType->IsNullable())
  18613. {
  18614. BfTypeInstance* nullableType = (BfTypeInstance*)thisValue.mType->ToTypeInstance();
  18615. auto elementType = nullableType->GetUnderlyingType();
  18616. if (elementType->IsValuelessType())
  18617. {
  18618. thisValue = mModule->MakeAddressable(thisValue);
  18619. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mHasValue
  18620. isNotNull = mModule->mBfIRBuilder->CreateAlignedLoad(hasValuePtr, 1);
  18621. thisValue = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), elementType, true);
  18622. }
  18623. else
  18624. {
  18625. thisValue = mModule->MakeAddressable(thisValue);
  18626. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 2); // mHasValue
  18627. isNotNull = mModule->mBfIRBuilder->CreateAlignedLoad(hasValuePtr, 1);
  18628. BfIRValue valuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(thisValue.mValue, 0, 1); // mValue
  18629. thisValue = BfTypedValue(valuePtr, elementType, true);
  18630. }
  18631. }
  18632. else
  18633. isNotNull = mModule->mBfIRBuilder->CreateIsNotNull(thisValue.mValue);
  18634. BfIRBlock notNullBB = mModule->mBfIRBuilder->CreateBlock("nullCond.notNull");
  18635. pendingNullCond->mNotNullBBs.Add(notNullBB);
  18636. mModule->mBfIRBuilder->CreateCondBr(isNotNull, notNullBB, pendingNullCond->mDoneBB);
  18637. mModule->AddBasicBlock(notNullBB);
  18638. return thisValue;
  18639. }
  18640. void BfExprEvaluator::CheckDotToken(BfTokenNode* tokenNode)
  18641. {
  18642. if ((tokenNode != NULL) && (tokenNode->mToken == BfToken_DotDot))
  18643. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", tokenNode);
  18644. }
  18645. void BfExprEvaluator::DoMemberReference(BfMemberReferenceExpression* memberRefExpr, BfTypedValue* outCascadeValue)
  18646. {
  18647. CheckDotToken(memberRefExpr->mDotToken);
  18648. BfAttributeState attributeState;
  18649. attributeState.mTarget = (BfAttributeTargets)(BfAttributeTargets_MemberAccess);
  18650. String findName;
  18651. BfAstNode* nameRefNode = memberRefExpr->mMemberName;
  18652. if (auto attrIdentifierExpr = BfNodeDynCast<BfAttributedIdentifierNode>(memberRefExpr->mMemberName))
  18653. {
  18654. nameRefNode = attrIdentifierExpr->mIdentifier;
  18655. // Don't validate
  18656. attributeState.mCustomAttributes = mModule->GetCustomAttributes(attrIdentifierExpr->mAttributes, BfAttributeTargets_SkipValidate);
  18657. if (nameRefNode != NULL)
  18658. findName = attrIdentifierExpr->mIdentifier->ToString();
  18659. }
  18660. else if (memberRefExpr->mMemberName != NULL)
  18661. findName = memberRefExpr->mMemberName->ToString();
  18662. else if (memberRefExpr->mDotToken != NULL)
  18663. mModule->FailAfter("Member name expected", memberRefExpr->mDotToken);
  18664. defer
  18665. (
  18666. if (attributeState.mCustomAttributes != NULL)
  18667. {
  18668. if (mPropDef != NULL)
  18669. attributeState.mTarget = (BfAttributeTargets)(attributeState.mTarget | BfAttributeTargets_Invocation);
  18670. mModule->ValidateCustomAttributes(attributeState.mCustomAttributes, attributeState.mTarget);
  18671. }
  18672. );
  18673. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, &attributeState);
  18674. BfTypeInstance* expectingTypeInst = NULL;
  18675. if (mExpectingType != NULL)
  18676. {
  18677. expectingTypeInst = mExpectingType->ToTypeInstance();
  18678. if (mExpectingType->IsPointer())
  18679. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  18680. else if (mExpectingType->IsNullable())
  18681. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  18682. else if (mExpectingType->IsConstExprValue())
  18683. expectingTypeInst = mExpectingType->GetUnderlyingType()->ToTypeInstance();
  18684. else if (mExpectingType->IsGenericParam())
  18685. {
  18686. auto genericParam = mModule->GetGenericParamInstance((BfGenericParamType*)mExpectingType);
  18687. if (genericParam->mTypeConstraint != NULL)
  18688. expectingTypeInst = genericParam->mTypeConstraint->ToTypeInstance();
  18689. }
  18690. }
  18691. BfAutoComplete* autoComplete = GetAutoComplete();
  18692. if (autoComplete != NULL)
  18693. {
  18694. SetAndRestoreValue<bool> prevFriendSet(autoComplete->mHasFriendSet, (attributeState.mCustomAttributes != NULL) && (attributeState.mCustomAttributes->Contains(mModule->mCompiler->mFriendAttributeTypeDef)));
  18695. if (memberRefExpr->mTarget == NULL)
  18696. {
  18697. String filter;
  18698. if ((mExpectingType != NULL) &&
  18699. (autoComplete->InitAutocomplete(memberRefExpr->mDotToken, memberRefExpr->mMemberName, filter)))
  18700. {
  18701. if (expectingTypeInst != NULL)
  18702. {
  18703. bool allowPrivate = expectingTypeInst == mModule->mCurTypeInstance;
  18704. if (expectingTypeInst->IsEnum())
  18705. autoComplete->AddEnumTypeMembers(expectingTypeInst, filter, false, allowPrivate);
  18706. autoComplete->AddSelfResultTypeMembers(expectingTypeInst, expectingTypeInst, filter, allowPrivate);
  18707. }
  18708. }
  18709. }
  18710. else
  18711. {
  18712. autoComplete->CheckMemberReference(memberRefExpr->mTarget, memberRefExpr->mDotToken, memberRefExpr->mMemberName, false, mExpectingType);
  18713. if (auto objCreateExpr = BfNodeDynCast<BfObjectCreateExpression>(memberRefExpr->mTarget))
  18714. {
  18715. // This handles a weird case where we have "obj a = new\nWhatever().Thing = 123;".
  18716. // That gets parsed as "Whatever()" being the type we want to create, and then referencing
  18717. // the "Thing" member of that new object.
  18718. //if (objCreateExpr->mArraySizeSpecifier == NULL)
  18719. CheckObjectCreateTypeRef(mExpectingType, objCreateExpr->mNewNode);
  18720. }
  18721. }
  18722. }
  18723. if (memberRefExpr->mTarget == NULL)
  18724. {
  18725. if (mExpectingType == NULL)
  18726. {
  18727. if (mModule->PreFail())
  18728. mModule->Fail("Unqualified dot syntax can only be used when the result type can be inferred", nameRefNode);
  18729. return;
  18730. }
  18731. if (mExpectingType->IsVar())
  18732. {
  18733. mResult = mModule->GetDefaultTypedValue(mExpectingType);
  18734. return;
  18735. }
  18736. if (expectingTypeInst == NULL)
  18737. {
  18738. if (mModule->PreFail())
  18739. mModule->Fail(StrFormat("Unqualified dot syntax cannot be used with type '%s'", mModule->TypeToString(mExpectingType).c_str()), nameRefNode);
  18740. return;
  18741. }
  18742. BfTypedValue expectingVal(expectingTypeInst);
  18743. mResult = LookupField(memberRefExpr->mMemberName, expectingVal, findName);
  18744. if ((mResult) || (mPropDef != NULL))
  18745. return;
  18746. }
  18747. bool isNullCondLookup = (memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_QuestionDot);
  18748. bool isCascade = ((memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_DotDot));
  18749. bool isArrowLookup = ((memberRefExpr->mDotToken != NULL) && (memberRefExpr->mDotToken->GetToken() == BfToken_Arrow));
  18750. BfIdentifierNode* nameLeft = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mTarget);
  18751. BfIdentifierNode* nameRight = BfIdentifierCast(memberRefExpr->mMemberName);
  18752. if ((nameLeft != NULL) && (nameRight != NULL) && (!isNullCondLookup) && (!isCascade) && (!isArrowLookup))
  18753. {
  18754. bool hadError = false;
  18755. LookupQualifiedName(memberRefExpr, nameLeft, nameRight, true, &hadError);
  18756. if ((mResult) || (mPropDef != NULL))
  18757. return;
  18758. if (hadError)
  18759. return;
  18760. LookupQualifiedStaticField(memberRefExpr, nameLeft, nameRight, false);
  18761. return;
  18762. }
  18763. BfTypedValue thisValue;
  18764. if (auto exprTarget = BfNodeDynCast<BfExpression>(memberRefExpr->mTarget))
  18765. {
  18766. if (auto typeOfExpr = BfNodeDynCast<BfTypeOfExpression>(memberRefExpr->mTarget))
  18767. {
  18768. if (auto nameIdentifer = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  18769. {
  18770. if (LookupTypeProp(typeOfExpr, nameIdentifer))
  18771. return;
  18772. }
  18773. }
  18774. //Hm, not using VisitChild broke our ability to write to a field for a not-initialized local struct
  18775. VisitChild(memberRefExpr->mTarget);
  18776. GetResult();
  18777. thisValue = mResult;
  18778. if (!thisValue)
  18779. {
  18780. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(exprTarget))
  18781. {
  18782. thisValue = BfTypedValue(mModule->ResolveTypeRef(targetIdentifier, NULL, BfPopulateType_Declaration));
  18783. }
  18784. }
  18785. if (!thisValue.HasType())
  18786. return;
  18787. //thisValue = mResult;
  18788. }
  18789. else if (auto typeRef = BfNodeDynCast<BfTypeReference>(memberRefExpr->mTarget))
  18790. {
  18791. // Look up static field
  18792. thisValue = BfTypedValue(ResolveTypeRef(typeRef));
  18793. }
  18794. if (nameRefNode == NULL)
  18795. {
  18796. mModule->AssertErrorState();
  18797. return;
  18798. }
  18799. if (isNullCondLookup)
  18800. thisValue = SetupNullConditional(thisValue, memberRefExpr->mDotToken);
  18801. if ((isArrowLookup) && (thisValue))
  18802. thisValue = TryArrowLookup(thisValue, memberRefExpr->mDotToken);
  18803. mResult = LookupField(nameRefNode, thisValue, findName);
  18804. if ((!mResult) && (mPropDef == NULL))
  18805. {
  18806. if (thisValue.mType != NULL)
  18807. {
  18808. BfTypeInstance* typeInst = thisValue.mType->ToTypeInstance();
  18809. auto compiler = mModule->mCompiler;
  18810. if ((typeInst != NULL) && (compiler->IsAutocomplete()) && (compiler->mResolvePassData->mAutoComplete->CheckFixit(memberRefExpr->mMemberName)))
  18811. {
  18812. FixitAddMember(typeInst, mExpectingType, findName, !thisValue.mValue);
  18813. }
  18814. }
  18815. if ((!thisValue.mValue) && (thisValue.mType != NULL))
  18816. {
  18817. if (auto targetIdentifier = BfNodeDynCast<BfIdentifierNode>(memberRefExpr->mMemberName))
  18818. {
  18819. if ((mBfEvalExprFlags & BfEvalExprFlags_NameOf) != 0)
  18820. {
  18821. auto typeInst = thisValue.mType->ToTypeInstance();
  18822. if ((typeInst != NULL) && (CheckForMethodName(nameRight, typeInst, findName)))
  18823. return;
  18824. }
  18825. mResult.mType = mModule->ResolveInnerType(thisValue.mType, targetIdentifier, BfPopulateType_Declaration);
  18826. }
  18827. }
  18828. if ((memberRefExpr->mTarget == NULL) && (expectingTypeInst != NULL) && (autoComplete != NULL))
  18829. {
  18830. if (autoComplete->CheckFixit(memberRefExpr->mMemberName))
  18831. {
  18832. autoComplete->FixitAddCase(expectingTypeInst, memberRefExpr->mMemberName->ToString(), BfTypeVector());
  18833. }
  18834. }
  18835. if (mResult.mType == NULL)
  18836. {
  18837. if (mModule->PreFail())
  18838. {
  18839. if ((thisValue) && (thisValue.mType->IsPointer()) && (thisValue.mType->GetUnderlyingType()->IsObjectOrInterface()))
  18840. mModule->Fail(StrFormat("Members cannot be referenced on type '%s' because the type is a pointer to a reference type (ie: a double-reference).",
  18841. mModule->TypeToString(thisValue.mType).c_str()), nameRefNode);
  18842. else if (thisValue)
  18843. mModule->Fail(StrFormat("Unable to find member '%s' in '%s'", findName.c_str(), mModule->TypeToString(thisValue.mType).c_str()), nameRefNode);
  18844. else
  18845. mModule->Fail("Unable to find member", nameRefNode);
  18846. }
  18847. }
  18848. }
  18849. if ((isNullCondLookup) && (mPropDef == NULL))
  18850. mResult = GetResult();
  18851. if (isCascade)
  18852. {
  18853. if (outCascadeValue != NULL)
  18854. *outCascadeValue = thisValue;
  18855. else if (mModule->PreFail())
  18856. mModule->Fail("Unexpected cascade operation. Chaining can only be used for method invocations", memberRefExpr->mDotToken);
  18857. }
  18858. }
  18859. void BfExprEvaluator::Visit(BfMemberReferenceExpression* memberRefExpr)
  18860. {
  18861. DoMemberReference(memberRefExpr, NULL);
  18862. }
  18863. void BfExprEvaluator::Visit(BfIndexerExpression* indexerExpr)
  18864. {
  18865. BfTypedValue target;
  18866. bool wantStatic = false;
  18867. // Try first as a non-static indexer, then as a static indexer
  18868. for (int pass = 0; pass < 2; pass++)
  18869. {
  18870. ///
  18871. {
  18872. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoLookupError | BfEvalExprFlags_AllowBase), pass == 0);
  18873. VisitChild(indexerExpr->mTarget);
  18874. }
  18875. ResolveGenericType();
  18876. target = GetResult(true);
  18877. if (target)
  18878. break;
  18879. if (pass == 0)
  18880. {
  18881. SetAndRestoreValue<bool> prevIgnoreErrors(mModule->mIgnoreErrors, (mModule->mIgnoreErrors) || (pass == 0));
  18882. auto staticType = mModule->ResolveTypeRef(indexerExpr->mTarget, {});
  18883. if (staticType != NULL)
  18884. {
  18885. wantStatic = true;
  18886. target.mType = staticType;
  18887. break;
  18888. }
  18889. }
  18890. }
  18891. if (!target.HasType())
  18892. return;
  18893. if (target.mType->IsGenericParam())
  18894. {
  18895. auto genericParamInstance = mModule->GetGenericParamInstance((BfGenericParamType*)target.mType);
  18896. if (genericParamInstance->mTypeConstraint != NULL)
  18897. target.mType = genericParamInstance->mTypeConstraint;
  18898. }
  18899. BfCheckedKind checkedKind = BfCheckedKind_NotSet;
  18900. bool isInlined = false;
  18901. if ((mModule->mAttributeState != NULL) && (mModule->mAttributeState->mCustomAttributes != NULL))
  18902. {
  18903. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mInlineAttributeTypeDef))
  18904. {
  18905. isInlined = true;
  18906. mModule->mAttributeState->mUsed = true;
  18907. }
  18908. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mCheckedAttributeTypeDef))
  18909. {
  18910. checkedKind = BfCheckedKind_Checked;
  18911. mModule->mAttributeState->mUsed = true;
  18912. }
  18913. if (mModule->mAttributeState->mCustomAttributes->Contains(mModule->mCompiler->mUncheckedAttributeTypeDef))
  18914. {
  18915. checkedKind = BfCheckedKind_Unchecked;
  18916. mModule->mAttributeState->mUsed = true;
  18917. }
  18918. }
  18919. // Avoid attempting to apply the current attributes to the indexer arguments
  18920. SetAndRestoreValue<BfAttributeState*> prevAttributeState(mModule->mAttributeState, NULL);
  18921. bool isNullCondLookup = (indexerExpr->mOpenBracket != NULL) && (indexerExpr->mOpenBracket->GetToken() == BfToken_QuestionLBracket);
  18922. if (isNullCondLookup)
  18923. target = SetupNullConditional(target, indexerExpr->mOpenBracket);
  18924. if (target.mType->IsVar())
  18925. {
  18926. mResult = BfTypedValue(mModule->GetDefaultValue(target.mType), target.mType, true);
  18927. return;
  18928. }
  18929. if (target.mType->IsTypeInstance())
  18930. {
  18931. mIndexerValues.clear();
  18932. SizedArray<BfExpression*, 2> argExprs;
  18933. BfSizedArray<BfExpression*> sizedArgExprs(indexerExpr->mArguments);
  18934. BfResolvedArgs argValues(&sizedArgExprs);
  18935. ResolveArgValues(argValues, (BfResolveArgsFlags)(BfResolveArgsFlag_DeferParamEval | BfResolveArgsFlag_FromIndexer));
  18936. mIndexerValues = argValues.mResolvedArgs;
  18937. BfMethodMatcher methodMatcher(indexerExpr->mTarget, mModule, "[]", mIndexerValues, BfMethodGenericArguments());
  18938. methodMatcher.mCheckedKind = checkedKind;
  18939. BfMethodDef* methodDef = NULL;
  18940. auto startCheckTypeInst = target.mType->ToTypeInstance();
  18941. for (int pass = 0; pass < 2; pass++)
  18942. {
  18943. bool isFailurePass = pass == 1;
  18944. BfPropertyDef* foundProp = NULL;
  18945. BfTypeInstance* foundPropTypeInst = NULL;
  18946. auto curCheckType = startCheckTypeInst;
  18947. while (curCheckType != NULL)
  18948. {
  18949. BfProtectionCheckFlags protectionCheckFlags = BfProtectionCheckFlag_None;
  18950. curCheckType->mTypeDef->PopulateMemberSets();
  18951. BfMemberSetEntry* entry;
  18952. BfPropertyDef* matchedProp = NULL;
  18953. BfPropertyDef* nextProp = NULL;
  18954. if (curCheckType->mTypeDef->mPropertySet.TryGetWith(String("[]"), &entry))
  18955. nextProp = (BfPropertyDef*)entry->mMemberDef;
  18956. while (nextProp != NULL)
  18957. {
  18958. auto prop = nextProp;
  18959. nextProp = nextProp->mNextWithSameName;
  18960. //TODO: Match against setMethod (minus last param) if we have no 'get' method
  18961. for (auto checkMethod : prop->mMethods)
  18962. {
  18963. if (checkMethod->mMethodType != BfMethodType_PropertyGetter)
  18964. continue;
  18965. // For generic params - check interface constraints for an indexer, call that method
  18966. BF_ASSERT(!target.mType->IsGenericParam());
  18967. if (checkMethod->mIsStatic != wantStatic)
  18968. continue;
  18969. if (checkMethod->mExplicitInterface != NULL)
  18970. continue;
  18971. auto autoComplete = GetAutoComplete();
  18972. bool wasCapturingMethodMatchInfo = false;
  18973. if (autoComplete != NULL)
  18974. {
  18975. // Set to false to make sure we don't capture method match info from 'params' array creation
  18976. wasCapturingMethodMatchInfo = autoComplete->mIsCapturingMethodMatchInfo;
  18977. autoComplete->mIsCapturingMethodMatchInfo = false;
  18978. }
  18979. defer
  18980. (
  18981. if (autoComplete != NULL)
  18982. autoComplete->mIsCapturingMethodMatchInfo = wasCapturingMethodMatchInfo;
  18983. );
  18984. if ((!isFailurePass) && (!methodMatcher.WantsCheckMethod(protectionCheckFlags, startCheckTypeInst, curCheckType, checkMethod)))
  18985. continue;
  18986. if (!methodMatcher.IsMemberAccessible(curCheckType, checkMethod->mDeclaringType))
  18987. continue;
  18988. methodMatcher.mCheckedKind = checkedKind;
  18989. methodMatcher.mTarget = target;
  18990. bool hadMatch = methodMatcher.CheckMethod(startCheckTypeInst, curCheckType, checkMethod, false);
  18991. if ((hadMatch) || (methodMatcher.mBackupMethodDef == checkMethod))
  18992. {
  18993. foundPropTypeInst = curCheckType;
  18994. foundProp = prop;
  18995. }
  18996. }
  18997. }
  18998. curCheckType = curCheckType->mBaseType;
  18999. }
  19000. if (foundProp != NULL)
  19001. {
  19002. mPropSrc = indexerExpr->mOpenBracket;
  19003. mPropDef = foundProp;
  19004. if (foundProp->mIsStatic)
  19005. {
  19006. mPropTarget = BfTypedValue(foundPropTypeInst);
  19007. }
  19008. else
  19009. {
  19010. if (target.mType != foundPropTypeInst)
  19011. mPropTarget = mModule->Cast(indexerExpr->mTarget, target, foundPropTypeInst);
  19012. else
  19013. mPropTarget = target;
  19014. }
  19015. mOrigPropTarget = mPropTarget;
  19016. if (isInlined)
  19017. mPropGetMethodFlags = (BfGetMethodInstanceFlags)(mPropGetMethodFlags | BfGetMethodInstanceFlag_ForceInline);
  19018. mPropCheckedKind = checkedKind;
  19019. if ((target.IsBase()) && (mPropDef->IsVirtual()))
  19020. mPropDefBypassVirtual = true;
  19021. return;
  19022. }
  19023. }
  19024. mModule->Fail("Unable to find indexer property", indexerExpr->mTarget);
  19025. return;
  19026. }
  19027. bool wantsChecks = checkedKind == BfCheckedKind_Checked;
  19028. if (checkedKind == BfCheckedKind_NotSet)
  19029. wantsChecks = mModule->GetDefaultCheckedKind() == BfCheckedKind_Checked;
  19030. //target.mType = mModule->ResolveGenericType(target.mType);
  19031. if (target.mType->IsVar())
  19032. {
  19033. mResult = target;
  19034. return;
  19035. }
  19036. if ((!target.mType->IsPointer()) && (!target.mType->IsSizedArray()))
  19037. {
  19038. mModule->Fail("Expected pointer or array type", indexerExpr->mTarget);
  19039. return;
  19040. }
  19041. auto _GetDefaultResult = [&]()
  19042. {
  19043. return mModule->GetDefaultTypedValue(target.mType->GetUnderlyingType(), false, BfDefaultValueKind_Addr);
  19044. };
  19045. if (indexerExpr->mArguments.size() != 1)
  19046. {
  19047. mModule->Fail("Expected single index", indexerExpr->mOpenBracket);
  19048. mResult = _GetDefaultResult();
  19049. return;
  19050. }
  19051. if (indexerExpr->mArguments[0] == NULL)
  19052. {
  19053. mModule->AssertErrorState();
  19054. mResult = _GetDefaultResult();
  19055. return;
  19056. }
  19057. bool isUndefIndex = false;
  19058. auto indexArgument = mModule->CreateValueFromExpression(indexerExpr->mArguments[0], mModule->GetPrimitiveType(BfTypeCode_IntPtr), BfEvalExprFlags_NoCast);
  19059. if (!indexArgument)
  19060. return;
  19061. if (!indexArgument.mType->IsIntegral())
  19062. {
  19063. if (indexArgument.mType->IsVar())
  19064. {
  19065. isUndefIndex = true;
  19066. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr), false, BfDefaultValueKind_Undef);
  19067. }
  19068. else
  19069. {
  19070. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  19071. if (!indexArgument)
  19072. indexArgument = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  19073. }
  19074. }
  19075. if (indexArgument.mType->IsPrimitiveType())
  19076. {
  19077. auto primType = (BfPrimitiveType*)indexArgument.mType;
  19078. if ((!primType->IsSigned()) && (primType->mSize < 8))
  19079. {
  19080. // GEP will always do a signed upcast so we need to cast manually if we are unsigned
  19081. indexArgument = BfTypedValue(mModule->mBfIRBuilder->CreateNumericCast(indexArgument.mValue, false, BfTypeCode_IntPtr), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  19082. }
  19083. }
  19084. mModule->PopulateType(target.mType);
  19085. if (target.mType->IsSizedArray())
  19086. {
  19087. BfSizedArrayType* sizedArrayType = (BfSizedArrayType*)target.mType;
  19088. auto underlyingType = sizedArrayType->mElementType;
  19089. if (indexArgument.mValue.IsConst())
  19090. {
  19091. auto indexConst = mModule->mBfIRBuilder->GetConstant(indexArgument.mValue);
  19092. if (indexConst->mUInt64 >= (uint64)sizedArrayType->mElementCount)
  19093. {
  19094. if ((!mModule->IsInSpecializedSection()) && (checkedKind != BfCheckedKind_Unchecked))
  19095. {
  19096. mModule->Fail(StrFormat("Index '%d' is out of bounds for type '%s'", indexConst->mInt32, mModule->TypeToString(target.mType).c_str()), indexerExpr->mArguments[0]);
  19097. mResult = _GetDefaultResult();
  19098. return;
  19099. }
  19100. else
  19101. {
  19102. // Is this any good?
  19103. mModule->mBfIRBuilder->CreateUnreachable();
  19104. }
  19105. }
  19106. }
  19107. else if (((mModule->HasExecutedOutput()) || (mModule->mIsComptimeModule)) &&
  19108. (wantsChecks))
  19109. {
  19110. if (checkedKind == BfCheckedKind_NotSet)
  19111. checkedKind = mModule->GetDefaultCheckedKind();
  19112. if (checkedKind == BfCheckedKind_Checked)
  19113. {
  19114. auto oobBlock = mModule->mBfIRBuilder->CreateBlock("oob", true);
  19115. auto contBlock = mModule->mBfIRBuilder->CreateBlock("cont", true);
  19116. auto indexType = (BfPrimitiveType*)indexArgument.mType;
  19117. if (!mModule->mSystem->DoesLiteralFit(indexType->mTypeDef->mTypeCode, (int64)sizedArrayType->mElementCount))
  19118. {
  19119. // We need to upsize the index so we can compare it against the larger elementCount
  19120. indexType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  19121. indexArgument = mModule->Cast(indexerExpr->mArguments[0], indexArgument, indexType);
  19122. }
  19123. auto cmpRes = mModule->mBfIRBuilder->CreateCmpGTE(indexArgument.mValue, mModule->mBfIRBuilder->CreateConst(indexType->mTypeDef->mTypeCode, (uint64)sizedArrayType->mElementCount), false);
  19124. mModule->mBfIRBuilder->CreateCondBr(cmpRes, oobBlock, contBlock);
  19125. mModule->mBfIRBuilder->SetInsertPoint(oobBlock);
  19126. auto internalType = mModule->ResolveTypeDef(mModule->mCompiler->mInternalTypeDef);
  19127. auto oobFunc = mModule->GetMethodByName(internalType->ToTypeInstance(), "ThrowIndexOutOfRange");
  19128. if (oobFunc.mFunc)
  19129. {
  19130. if (mModule->mIsComptimeModule)
  19131. mModule->mCompiler->mCeMachine->QueueMethod(oobFunc.mMethodInstance, oobFunc.mFunc);
  19132. SizedArray<BfIRValue, 1> args;
  19133. args.push_back(mModule->GetConstValue(0));
  19134. mModule->mBfIRBuilder->CreateCall(oobFunc.mFunc, args);
  19135. mModule->mBfIRBuilder->CreateUnreachable();
  19136. }
  19137. else
  19138. {
  19139. mModule->Fail("System.Internal class must contain method 'ThrowIndexOutOfRange'");
  19140. }
  19141. mModule->mBfIRBuilder->SetInsertPoint(contBlock);
  19142. }
  19143. }
  19144. // If this is a 'bag of bytes', we should try hard not to have to make this addressable
  19145. if ((!target.IsAddr()) && (!target.mType->IsSizeAligned()))
  19146. mModule->MakeAddressable(target);
  19147. mModule->PopulateType(underlyingType);
  19148. if ((sizedArrayType->IsUndefSizedArray()) || (isUndefIndex))
  19149. {
  19150. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  19151. }
  19152. else if (sizedArrayType->IsValuelessType())
  19153. {
  19154. if (underlyingType->IsValuelessType())
  19155. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), underlyingType, true);
  19156. else
  19157. {
  19158. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  19159. }
  19160. }
  19161. else if (target.IsAddr())
  19162. {
  19163. if (target.mType->IsSizeAligned())
  19164. {
  19165. auto gepResult = mModule->mBfIRBuilder->CreateInBoundsGEP(target.mValue, mModule->GetConstValue(0), indexArgument.mValue);
  19166. mResult = BfTypedValue(gepResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  19167. }
  19168. else
  19169. {
  19170. auto indexResult = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  19171. mResult = BfTypedValue(indexResult, underlyingType, target.IsReadOnly() ? BfTypedValueKind_ReadOnlyAddr : BfTypedValueKind_Addr);
  19172. }
  19173. }
  19174. else
  19175. {
  19176. if ((!target.mValue.IsConst()) && (!indexArgument.mValue.IsConst()))
  19177. {
  19178. mModule->Fail("Unable to index value", indexerExpr->mTarget);
  19179. return;
  19180. }
  19181. mModule->mBfIRBuilder->PopulateType(target.mType);
  19182. auto gepResult = mModule->mBfIRBuilder->CreateExtractValue(target.mValue, indexArgument.mValue);
  19183. if ((underlyingType->IsString()) || (underlyingType->IsPointer()))
  19184. {
  19185. auto resultConst = mModule->mBfIRBuilder->GetConstant(gepResult);
  19186. if ((resultConst != NULL) && (resultConst->mTypeCode == BfTypeCode_Int32))
  19187. {
  19188. int strId = resultConst->mInt32;
  19189. const StringImpl& str = mModule->mContext->mStringObjectIdMap[strId].mString;
  19190. if (underlyingType->IsString())
  19191. gepResult = mModule->GetStringObjectValue(str, false);
  19192. else
  19193. gepResult = mModule->GetStringCharPtr(strId);
  19194. }
  19195. }
  19196. mResult = BfTypedValue(gepResult, underlyingType, BfTypedValueKind_Value);
  19197. }
  19198. }
  19199. else
  19200. {
  19201. target = mModule->LoadValue(target);
  19202. BfPointerType* pointerType = (BfPointerType*)target.mType;
  19203. auto underlyingType = pointerType->mElementType;
  19204. mModule->mBfIRBuilder->PopulateType(underlyingType);
  19205. if (isUndefIndex)
  19206. {
  19207. mResult = mModule->GetDefaultTypedValue(underlyingType, false, BfDefaultValueKind_Addr);
  19208. }
  19209. else
  19210. {
  19211. BfIRValue result = mModule->CreateIndexedValue(underlyingType, target.mValue, indexArgument.mValue);
  19212. mResult = BfTypedValue(result, underlyingType, true);
  19213. }
  19214. }
  19215. }
  19216. void BfExprEvaluator::Visit(BfUnaryOperatorExpression* unaryOpExpr)
  19217. {
  19218. BfAutoParentNodeEntry autoParentNodeEntry(mModule, unaryOpExpr);
  19219. PerformUnaryOperation(unaryOpExpr->mExpression, unaryOpExpr->mOp, unaryOpExpr->mOpToken, BfUnaryOpFlag_None);
  19220. }
  19221. void BfExprEvaluator::PerformUnaryOperation(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  19222. {
  19223. if ((unaryOpExpr == NULL) && (unaryOp == BfUnaryOp_PartialRangeThrough))
  19224. {
  19225. PerformBinaryOperation(NULL, NULL, BfBinaryOp_ClosedRange, opToken, BfBinOpFlag_None);
  19226. return;
  19227. }
  19228. ///
  19229. {
  19230. // If this is a cast, we don't want the value to be coerced before the unary operator is applied.
  19231. // WAIT: Why not?
  19232. //SetAndRestoreValue<BfType*> prevExpectingType(mExpectingType, NULL);
  19233. BfType* prevExpedcting = mExpectingType;
  19234. switch (unaryOp)
  19235. {
  19236. case BfUnaryOp_Negate:
  19237. case BfUnaryOp_Positive:
  19238. case BfUnaryOp_InvertBits:
  19239. // If we're expecting an int64 or uint64 then just leave the type as unknown
  19240. if ((mExpectingType != NULL) && (mExpectingType->IsInteger()) && (mExpectingType->mSize == 8))
  19241. mExpectingType = NULL;
  19242. // Otherwise keep expecting type
  19243. break;
  19244. default:
  19245. mExpectingType = NULL;
  19246. }
  19247. VisitChild(unaryOpExpr);
  19248. mExpectingType = prevExpedcting;
  19249. }
  19250. BfExprEvaluator::PerformUnaryOperation_OnResult(unaryOpExpr, unaryOp, opToken, opFlags);
  19251. }
  19252. BfTypedValue BfExprEvaluator::PerformUnaryOperation_TryOperator(const BfTypedValue& inValue, BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  19253. {
  19254. if ((!inValue.mType->IsTypeInstance()) && (!inValue.mType->IsGenericParam()))
  19255. return BfTypedValue();
  19256. SizedArray<BfResolvedArg, 1> args;
  19257. BfResolvedArg resolvedArg;
  19258. resolvedArg.mTypedValue = inValue;
  19259. args.push_back(resolvedArg);
  19260. BfMethodMatcher methodMatcher(opToken, mModule, "", args, BfMethodGenericArguments());
  19261. methodMatcher.mBfEvalExprFlags = BfEvalExprFlags_NoAutoComplete;
  19262. methodMatcher.mAllowImplicitRef = true;
  19263. BfBaseClassWalker baseClassWalker(inValue.mType, NULL, mModule);
  19264. BfUnaryOp findOp = unaryOp;
  19265. bool isPostOp = false;
  19266. if (findOp == BfUnaryOp_PostIncrement)
  19267. {
  19268. findOp = BfUnaryOp_Increment;
  19269. isPostOp = true;
  19270. }
  19271. if (findOp == BfUnaryOp_PostDecrement)
  19272. {
  19273. findOp = BfUnaryOp_Decrement;
  19274. isPostOp = true;
  19275. }
  19276. bool isConstraintCheck = ((opFlags & BfUnaryOpFlag_IsConstraintCheck) != 0);
  19277. BfType* operatorConstraintReturnType = NULL;
  19278. BfType* bestSelfType = NULL;
  19279. while (true)
  19280. {
  19281. auto entry = baseClassWalker.Next();
  19282. auto checkType = entry.mTypeInstance;
  19283. if (checkType == NULL)
  19284. break;
  19285. for (auto operatorDef : checkType->mTypeDef->mOperators)
  19286. {
  19287. if (operatorDef->mOperatorDeclaration->mUnaryOp == findOp)
  19288. {
  19289. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  19290. continue;
  19291. int prevArgSize = (int)args.mSize;
  19292. if (!operatorDef->mIsStatic)
  19293. {
  19294. // Try without arg
  19295. args.mSize = 0;
  19296. }
  19297. if (isConstraintCheck)
  19298. {
  19299. auto returnType = mModule->CheckOperator(checkType, operatorDef, inValue, BfTypedValue());
  19300. if (returnType != NULL)
  19301. {
  19302. operatorConstraintReturnType = returnType;
  19303. methodMatcher.mBestMethodDef = operatorDef;
  19304. }
  19305. }
  19306. else
  19307. {
  19308. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  19309. methodMatcher.mSelfType = entry.mSrcType;
  19310. }
  19311. args.mSize = prevArgSize;
  19312. }
  19313. }
  19314. }
  19315. methodMatcher.FlushAmbiguityError();
  19316. if (methodMatcher.mBestMethodDef == NULL)
  19317. {
  19318. // Check method generic constraints
  19319. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  19320. {
  19321. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  19322. {
  19323. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  19324. for (auto& opConstraint : genericParam->mOperatorConstraints)
  19325. {
  19326. if (opConstraint.mUnaryOp == findOp)
  19327. {
  19328. if (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType, isConstraintCheck ? BfCastFlags_IsConstraintCheck : BfCastFlags_None))
  19329. {
  19330. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  19331. }
  19332. }
  19333. }
  19334. }
  19335. }
  19336. // Check type generic constraints
  19337. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  19338. {
  19339. auto genericTypeInst = (BfTypeInstance*)mModule->mCurTypeInstance;
  19340. for (int genericParamIdx = 0; genericParamIdx < genericTypeInst->mGenericTypeInfo->mGenericParams.size(); genericParamIdx++)
  19341. {
  19342. auto genericParam = mModule->GetGenericTypeParamInstance(genericParamIdx);
  19343. for (auto& opConstraint : genericParam->mOperatorConstraints)
  19344. {
  19345. if (opConstraint.mUnaryOp == findOp)
  19346. {
  19347. if (mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType, isConstraintCheck ? BfCastFlags_IsConstraintCheck : BfCastFlags_None))
  19348. {
  19349. return BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), genericParam->mExternType);
  19350. }
  19351. }
  19352. }
  19353. }
  19354. }
  19355. return BfTypedValue();
  19356. }
  19357. if ((!baseClassWalker.mMayBeFromInterface) && (opToken != NULL))
  19358. mModule->SetElementType(opToken, BfSourceElementType_Method);
  19359. auto methodDef = methodMatcher.mBestMethodDef;
  19360. auto autoComplete = GetAutoComplete();
  19361. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  19362. {
  19363. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  19364. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  19365. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  19366. }
  19367. SizedArray<BfExpression*, 2> argSrcs;
  19368. argSrcs.push_back(unaryOpExpr);
  19369. BfTypedValue targetVal = args[0].mTypedValue;
  19370. BfTypedValue postOpVal;
  19371. if (isPostOp)
  19372. postOpVal = mModule->LoadValue(targetVal);
  19373. BfTypedValue callTarget;
  19374. if (!methodMatcher.mBestMethodDef->mIsStatic)
  19375. {
  19376. callTarget = targetVal;
  19377. args.Clear();
  19378. }
  19379. BfTypedValue result;
  19380. if (isConstraintCheck)
  19381. {
  19382. result = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), operatorConstraintReturnType);
  19383. }
  19384. else
  19385. {
  19386. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  19387. result = CreateCall(&methodMatcher, callTarget);
  19388. }
  19389. if (!methodMatcher.mBestMethodDef->mIsStatic)
  19390. {
  19391. if (!isPostOp)
  19392. result = mModule->LoadValue(targetVal);
  19393. }
  19394. else if ((result.mType != NULL) && (methodMatcher.mSelfType != NULL) && (result.mType->IsSelf()))
  19395. {
  19396. BF_ASSERT(mModule->IsInGeneric());
  19397. result = mModule->GetDefaultTypedValue(methodMatcher.mSelfType);
  19398. }
  19399. if ((methodMatcher.mBestMethodInstance) &&
  19400. ((findOp == BfUnaryOp_Increment) || (findOp == BfUnaryOp_Decrement)))
  19401. {
  19402. if (methodMatcher.mBestMethodInstance.mMethodInstance->mIsIntrinsic)
  19403. {
  19404. if (args[0].mTypedValue.IsAddr())
  19405. mModule->mBfIRBuilder->CreateStore(result.mValue, args[0].mTypedValue.mValue);
  19406. else
  19407. {
  19408. mModule->AssertErrorState();
  19409. }
  19410. }
  19411. else
  19412. {
  19413. if (!result.mType->IsValuelessType())
  19414. {
  19415. if (targetVal.IsAddr())
  19416. {
  19417. result = mModule->LoadValue(result);
  19418. mModule->mBfIRBuilder->CreateStore(result.mValue, targetVal.mValue);
  19419. }
  19420. }
  19421. }
  19422. }
  19423. if (postOpVal)
  19424. result = postOpVal;
  19425. return result;
  19426. }
  19427. void BfExprEvaluator::PerformUnaryOperation_OnResult(BfExpression* unaryOpExpr, BfUnaryOp unaryOp, BfTokenNode* opToken, BfUnaryOpFlags opFlags)
  19428. {
  19429. BfAstNode* propSrc = mPropSrc;
  19430. BfTypedValue origPropTarget = mOrigPropTarget;
  19431. BfTypedValue propTarget = mPropTarget;
  19432. BfPropertyDef* propDef = mPropDef;
  19433. SizedArray<BfResolvedArg, 2> indexerVals = mIndexerValues;
  19434. BfTypedValue writeToProp;
  19435. GetResult();
  19436. if (!mResult)
  19437. return;
  19438. mResult = mModule->RemoveRef(mResult);
  19439. if (mResult.mType->IsVar())
  19440. {
  19441. mResult = BfTypedValue(mModule->GetDefaultValue(mResult.mType), mResult.mType);
  19442. return;
  19443. }
  19444. if (BfCanOverloadOperator(unaryOp))
  19445. {
  19446. auto opResult = PerformUnaryOperation_TryOperator(mResult, unaryOpExpr, unaryOp, opToken, opFlags);
  19447. if (opResult)
  19448. {
  19449. mResult = opResult;
  19450. return;
  19451. }
  19452. }
  19453. switch (unaryOp)
  19454. {
  19455. case BfUnaryOp_PostIncrement:
  19456. case BfUnaryOp_Increment:
  19457. case BfUnaryOp_PostDecrement:
  19458. case BfUnaryOp_Decrement:
  19459. {
  19460. if (mResult.mKind == BfTypedValueKind_CopyOnMutateAddr)
  19461. {
  19462. // Support this ops on direct auto-property access without a copy
  19463. mResult.mKind = BfTypedValueKind_Addr;
  19464. }
  19465. }
  19466. break;
  19467. }
  19468. bool numericFail = false;
  19469. switch (unaryOp)
  19470. {
  19471. case BfUnaryOp_Not:
  19472. {
  19473. CheckResultForReading(mResult);
  19474. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  19475. auto value = mModule->LoadValue(mResult);
  19476. value = mModule->Cast(unaryOpExpr, value, boolType);
  19477. if (!value)
  19478. {
  19479. mResult = BfTypedValue();
  19480. return;
  19481. }
  19482. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), boolType);
  19483. }
  19484. break;
  19485. case BfUnaryOp_Positive:
  19486. return;
  19487. case BfUnaryOp_Negate:
  19488. {
  19489. CheckResultForReading(mResult);
  19490. auto value = mModule->LoadValue(mResult);
  19491. if (!value)
  19492. {
  19493. mResult = BfTypedValue();
  19494. return;
  19495. }
  19496. BfType* origType = value.mType;
  19497. if (value.mType->IsTypedPrimitive())
  19498. value.mType = value.mType->GetUnderlyingType();
  19499. if (value.mType->IsIntegral())
  19500. {
  19501. auto primType = (BfPrimitiveType*)value.mType;
  19502. auto wantType = primType;
  19503. auto constant = mModule->mBfIRBuilder->GetConstant(value.mValue);
  19504. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)))
  19505. {
  19506. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (constant->mInt64 == 0x80000000LL))
  19507. {
  19508. mResult = BfTypedValue(mModule->GetConstValue32(-0x80000000LL), mModule->GetPrimitiveType(BfTypeCode_Int32));
  19509. return;
  19510. }
  19511. else if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt64) && (constant->mInt64 == 0x8000000000000000LL))
  19512. {
  19513. mResult = BfTypedValue(mModule->GetConstValue64(-0x8000000000000000LL), mModule->GetPrimitiveType(BfTypeCode_Int64));
  19514. return;
  19515. }
  19516. }
  19517. /*if (auto constantInt = dyn_cast<ConstantInt>((Value*)value.mValue))
  19518. {
  19519. int64 i64Val = constantInt->getSExtValue();
  19520. // This is a special case where the user entered -0x80000000 (maxint) but we thought "0x80000000" was a uint in the parser
  19521. // which would get upcasted to an int64 for this negate. Properly bring back down to an int32
  19522. if ((primType->mTypeDef->mTypeCode == BfTypeCode_UInt32) && (i64Val == -0x80000000LL))
  19523. {
  19524. mResult = BfTypedValue(mModule->GetConstValue((int)i64Val), mModule->GetPrimitiveType(BfTypeCode_Int32));
  19525. return;
  19526. }
  19527. }*/
  19528. if (!primType->IsSigned())
  19529. {
  19530. if (primType->mSize == 1)
  19531. wantType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  19532. else if (primType->mSize == 2)
  19533. wantType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  19534. else if (primType->mSize == 4)
  19535. wantType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  19536. else
  19537. mModule->Fail("Operator '-' cannot be applied to uint64", opToken);
  19538. }
  19539. if (primType != wantType)
  19540. {
  19541. value = mModule->Cast(unaryOpExpr, value, wantType, BfCastFlags_Explicit);
  19542. if (!value)
  19543. {
  19544. mResult = BfTypedValue();
  19545. return;
  19546. }
  19547. }
  19548. if (origType->mSize == wantType->mSize) // Allow negative of primitive typed but not if we had to upsize
  19549. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  19550. else
  19551. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), wantType);
  19552. }
  19553. else if (value.mType->IsFloat())
  19554. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNeg(value.mValue), origType);
  19555. else
  19556. numericFail = true;
  19557. }
  19558. break;
  19559. case BfUnaryOp_InvertBits:
  19560. {
  19561. CheckResultForReading(mResult);
  19562. auto value = mModule->LoadValue(mResult);
  19563. if (!value)
  19564. return;
  19565. bool isInteger = value.mType->IsIntegral();
  19566. if (value.mType->IsTypedPrimitive())
  19567. isInteger = value.mType->GetUnderlyingType()->IsIntegral();
  19568. if (!isInteger)
  19569. {
  19570. mResult = BfTypedValue();
  19571. mModule->Fail("Operator can only be used on integer types", opToken);
  19572. return;
  19573. }
  19574. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateNot(value.mValue), value.mType);
  19575. }
  19576. break;
  19577. case BfUnaryOp_AddressOf:
  19578. {
  19579. MarkResultUsed();
  19580. mModule->FixIntUnknown(mResult);
  19581. mModule->PopulateType(mResult.mType);
  19582. auto ptrType = mModule->CreatePointerType(mResult.mType);
  19583. if (mResult.mType->IsValuelessType())
  19584. {
  19585. // Sentinel value
  19586. auto val = mModule->mBfIRBuilder->CreateIntToPtr(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), mModule->mBfIRBuilder->MapType(ptrType));
  19587. mResult = BfTypedValue(val, ptrType);
  19588. }
  19589. else if (!CheckModifyResult(mResult, unaryOpExpr, "take address of", false, true))
  19590. {
  19591. if (!mResult.IsAddr())
  19592. mResult = mModule->MakeAddressable(mResult, false, true);
  19593. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  19594. }
  19595. else
  19596. mResult = BfTypedValue(mResult.mValue, ptrType, false);
  19597. }
  19598. break;
  19599. case BfUnaryOp_Dereference:
  19600. {
  19601. CheckResultForReading(mResult);
  19602. if (!mResult.mType->IsPointer())
  19603. {
  19604. mResult = BfTypedValue();
  19605. mModule->Fail("Cannot dereference non-pointer type", unaryOpExpr);
  19606. return;
  19607. }
  19608. if (mResult.mValue.IsConst())
  19609. {
  19610. auto constant = mModule->mBfIRBuilder->GetConstant(mResult.mValue);
  19611. bool isNull = constant->mTypeCode == BfTypeCode_NullPtr;
  19612. if (constant->mConstType == BfConstType_ExtractValue)
  19613. {
  19614. auto constExtract = (BfConstantExtractValue*)constant;
  19615. auto targetConst = mModule->mBfIRBuilder->GetConstantById(constExtract->mTarget);
  19616. if (targetConst->mConstType == BfConstType_AggZero)
  19617. isNull = true;
  19618. }
  19619. if (isNull)
  19620. {
  19621. mModule->Warn(0, "Cannot dereference a null pointer", unaryOpExpr);
  19622. mResult = mModule->GetDefaultTypedValue(mResult.mType, false, BfDefaultValueKind_Addr);
  19623. mResult = mModule->LoadValue(mResult);
  19624. }
  19625. }
  19626. auto derefTarget = mModule->LoadValue(mResult);
  19627. BfPointerType* pointerType = (BfPointerType*)derefTarget.mType;
  19628. auto resolvedType = pointerType->mElementType;
  19629. mModule->PopulateType(resolvedType);
  19630. if (resolvedType->IsValuelessType())
  19631. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), resolvedType, true);
  19632. else
  19633. mResult = BfTypedValue(derefTarget.mValue, resolvedType, true);
  19634. }
  19635. break;
  19636. case BfUnaryOp_PostIncrement:
  19637. case BfUnaryOp_Increment:
  19638. {
  19639. CheckResultForReading(mResult);
  19640. auto ptr = mResult;
  19641. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  19642. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "increment")))
  19643. return;
  19644. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  19645. BfIRValue origVal = origTypedVal.mValue;
  19646. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  19647. BfIRValue resultValue;
  19648. if (ptr.mType->IsPointer())
  19649. {
  19650. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  19651. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  19652. constValue = mModule->GetConstValue(ptrType->mElementType->GetStride(), intPtrType);
  19653. auto i8PtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  19654. BfIRValue origPtrValue = mModule->mBfIRBuilder->CreateBitCast(origVal, i8PtrType);
  19655. BfIRValue newPtrValue = mModule->mBfIRBuilder->CreateInBoundsGEP(origPtrValue, constValue);
  19656. resultValue = mModule->mBfIRBuilder->CreateBitCast(newPtrValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  19657. }
  19658. else
  19659. {
  19660. constValue = mModule->GetConstValue(1, ptr.mType);
  19661. if (!constValue)
  19662. {
  19663. numericFail = true;
  19664. break;
  19665. }
  19666. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()) || (ptr.mType->IsFloat()))
  19667. {
  19668. resultValue = mModule->mBfIRBuilder->CreateAdd(origVal, constValue/*, "inc"*/);
  19669. }
  19670. else
  19671. {
  19672. numericFail = true;
  19673. break;
  19674. }
  19675. }
  19676. if ((propDef != NULL) && (!ptr.IsAddr()))
  19677. writeToProp = BfTypedValue(resultValue, ptr.mType);
  19678. else
  19679. mModule->mBfIRBuilder->CreateAlignedStore(resultValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  19680. if (unaryOp == BfUnaryOp_PostIncrement)
  19681. mResult = BfTypedValue(origVal, ptr.mType, false);
  19682. else
  19683. mResult = BfTypedValue(resultValue, ptr.mType, false);
  19684. }
  19685. break;
  19686. case BfUnaryOp_PostDecrement:
  19687. case BfUnaryOp_Decrement:
  19688. {
  19689. CheckResultForReading(mResult);
  19690. auto ptr = mResult;
  19691. //if ((propDef == NULL) && (!mModule->CheckModifyValue(ptr, opToken)))
  19692. //return;
  19693. if ((propDef == NULL) && (!CheckModifyResult(ptr, opToken, "decrement")))
  19694. return;
  19695. BfTypedValue origTypedVal = mModule->LoadValue(ptr, NULL, mIsVolatileReference);
  19696. BfIRValue origVal = origTypedVal.mValue;
  19697. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  19698. BfIRValue resultValue;
  19699. if (ptr.mType->IsPointer())
  19700. {
  19701. BfPointerType* ptrType = (BfPointerType*)ptr.mType;
  19702. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  19703. constValue = mModule->GetConstValue(-ptrType->mElementType->GetStride(), intPtrType);
  19704. auto i8PtrType = mModule->mBfIRBuilder->GetPointerTo(mModule->mBfIRBuilder->GetPrimitiveType(BfTypeCode_Int8));
  19705. BfIRValue origPtrValue = mModule->mBfIRBuilder->CreateBitCast(origVal, i8PtrType);
  19706. BfIRValue newPtrValue = mModule->mBfIRBuilder->CreateInBoundsGEP(origPtrValue, constValue);
  19707. resultValue = mModule->mBfIRBuilder->CreateBitCast(newPtrValue, mModule->mBfIRBuilder->MapType(ptr.mType));
  19708. }
  19709. else
  19710. {
  19711. BfIRValue constValue = mModule->GetConstValue(1, ptr.mType);
  19712. if (!constValue)
  19713. {
  19714. numericFail = true;
  19715. break;
  19716. }
  19717. if ((ptr.mType->IsIntegral()) || (ptr.mType->IsEnum()))
  19718. {
  19719. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  19720. }
  19721. else if (ptr.mType->IsFloat())
  19722. {
  19723. resultValue = mModule->mBfIRBuilder->CreateSub(origVal, constValue);
  19724. }
  19725. else
  19726. {
  19727. numericFail = true;
  19728. break;
  19729. }
  19730. }
  19731. if ((propDef != NULL) && (!ptr.IsAddr()))
  19732. writeToProp = BfTypedValue(resultValue, ptr.mType);
  19733. else
  19734. mModule->mBfIRBuilder->CreateAlignedStore(resultValue, ptr.mValue, ptr.mType->mAlign, mIsVolatileReference);
  19735. if (unaryOp == BfUnaryOp_PostDecrement)
  19736. mResult = BfTypedValue(origVal, ptr.mType, false);
  19737. else
  19738. mResult = BfTypedValue(resultValue, ptr.mType, false);
  19739. }
  19740. break;
  19741. case BfUnaryOp_Ref:
  19742. case BfUnaryOp_Mut:
  19743. {
  19744. if (mAllowReadOnlyReference)
  19745. {
  19746. if (mResult.mKind == BfTypedValueKind_ReadOnlyAddr)
  19747. mResult.mKind = BfTypedValueKind_Addr;
  19748. }
  19749. CheckResultForReading(mResult);
  19750. if ((unaryOp == BfUnaryOp_Mut) && (!mResult.mType->IsValueType()) && (!mResult.mType->IsGenericParam()))
  19751. {
  19752. // Non-valuetypes types are already mutable, leave them alone...
  19753. break;
  19754. }
  19755. if ((unaryOp != BfUnaryOp_Mut) || (mResult.mKind != BfTypedValueKind_MutableValue))
  19756. {
  19757. if (!CheckModifyResult(mResult, unaryOpExpr, StrFormat("use '%s' on", BfGetOpName(unaryOp)).c_str()))
  19758. {
  19759. // Just leave the non-ref version in mResult
  19760. return;
  19761. }
  19762. }
  19763. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowRefExpr) == 0)
  19764. {
  19765. mResult = BfTypedValue();
  19766. mModule->Fail(StrFormat("Invalid usage of '%s' expression", BfGetOpName(unaryOp)), opToken);
  19767. return;
  19768. }
  19769. ResolveGenericType();
  19770. if (mResult.mType->IsVar())
  19771. break;
  19772. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, (unaryOp == BfUnaryOp_Ref) ? BfRefType::RefKind_Ref : BfRefType::RefKind_Mut));
  19773. }
  19774. break;
  19775. case BfUnaryOp_Out:
  19776. {
  19777. if (!CheckModifyResult(mResult, unaryOpExpr, "use 'out' on"))
  19778. {
  19779. // Just leave the non-ref version in mResult
  19780. return;
  19781. }
  19782. if ((mBfEvalExprFlags & BfEvalExprFlags_AllowOutExpr) == 0)
  19783. {
  19784. mModule->Fail("Invalid usage of 'out' expression", opToken);
  19785. return;
  19786. }
  19787. if (mInsidePendingNullable)
  19788. {
  19789. // 'out' inside null conditionals never actually causes a definite assignment...
  19790. }
  19791. else
  19792. MarkResultAssigned();
  19793. MarkResultUsed();
  19794. ResolveGenericType();
  19795. if (mResult.mType->IsVar())
  19796. break;
  19797. mResult = BfTypedValue(mResult.mValue, mModule->CreateRefType(mResult.mType, BfRefType::RefKind_Out));
  19798. }
  19799. break;
  19800. case BfUnaryOp_Params:
  19801. {
  19802. bool allowParams = (mBfEvalExprFlags & BfEvalExprFlags_AllowParamsExpr) != 0;
  19803. if (allowParams)
  19804. {
  19805. if ((mResultLocalVar != NULL) && (mResultLocalVar->mCompositeCount >= 0)) // Delegate params
  19806. {
  19807. allowParams = true;
  19808. }
  19809. else
  19810. {
  19811. auto isValid = false;
  19812. auto genericTypeInst = mResult.mType->ToGenericTypeInstance();
  19813. if ((genericTypeInst != NULL) && (genericTypeInst->IsInstanceOf(mModule->mCompiler->mSpanTypeDef)))
  19814. isValid = true;
  19815. else if ((mResult.mType->IsArray()) || (mResult.mType->IsSizedArray()))
  19816. isValid = true;
  19817. if (!isValid)
  19818. {
  19819. mModule->Fail(StrFormat("A 'params' expression cannot be used on type '%s'", mModule->TypeToString(mResult.mType).c_str()), opToken);
  19820. }
  19821. }
  19822. }
  19823. if (allowParams)
  19824. {
  19825. mResult = mModule->LoadValue(mResult);
  19826. if (mResult.IsSplat())
  19827. mResult.mKind = BfTypedValueKind_ParamsSplat;
  19828. else
  19829. mResult.mKind = BfTypedValueKind_Params;
  19830. }
  19831. else
  19832. {
  19833. mModule->Fail("Illegal use of 'params' expression", opToken);
  19834. }
  19835. }
  19836. break;
  19837. case BfUnaryOp_Cascade:
  19838. {
  19839. mModule->Fail("Illegal use of argument cascade expression", opToken);
  19840. }
  19841. break;
  19842. case BfUnaryOp_FromEnd:
  19843. {
  19844. CheckResultForReading(mResult);
  19845. auto value = mModule->Cast(unaryOpExpr, mResult, mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  19846. value = mModule->LoadValue(value);
  19847. if (value)
  19848. {
  19849. auto indexType = mModule->ResolveTypeDef(mModule->mCompiler->mIndexTypeDef);
  19850. auto alloca = mModule->CreateAlloca(indexType);
  19851. mModule->mBfIRBuilder->CreateStore(value.mValue, mModule->mBfIRBuilder->CreateInBoundsGEP(mModule->mBfIRBuilder->CreateInBoundsGEP(alloca, 0, 1), 0, 1));
  19852. mModule->mBfIRBuilder->CreateStore(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 1), mModule->mBfIRBuilder->CreateInBoundsGEP(alloca, 0, 2));
  19853. mResult = BfTypedValue(alloca, indexType, BfTypedValueKind_Addr);
  19854. }
  19855. }
  19856. break;
  19857. case BfUnaryOp_PartialRangeUpTo:
  19858. PerformBinaryOperation(NULL, unaryOpExpr, BfBinaryOp_Range, opToken, BfBinOpFlag_None);
  19859. break;
  19860. case BfUnaryOp_PartialRangeThrough:
  19861. PerformBinaryOperation(NULL, unaryOpExpr, BfBinaryOp_ClosedRange, opToken, BfBinOpFlag_None);
  19862. break;
  19863. case BfUnaryOp_PartialRangeFrom:
  19864. PerformBinaryOperation(unaryOpExpr, NULL, BfBinaryOp_ClosedRange, opToken, BfBinOpFlag_None);
  19865. break;
  19866. default:
  19867. mModule->Fail(StrFormat("Illegal use of '%s' unary operator", BfGetOpName(unaryOp)), unaryOpExpr);
  19868. break;
  19869. }
  19870. if (numericFail)
  19871. {
  19872. if (opToken == NULL)
  19873. {
  19874. BF_ASSERT(mModule->mBfIRBuilder->mIgnoreWrites);
  19875. }
  19876. else if ((mResult.mType != NULL) && (mResult.mType->IsInterface()))
  19877. {
  19878. mModule->Fail(
  19879. StrFormat("Operator '%s' cannot be used on interface '%s'. Consider rewriting using generics and use this interface as a generic constraint.",
  19880. BfTokenToString(opToken->mToken), mModule->TypeToString(mResult.mType).c_str()), opToken);
  19881. }
  19882. else
  19883. {
  19884. mModule->Fail(
  19885. StrFormat("Operator '%s' cannot be used because type '%s' is neither a numeric type nor does it define an applicable operator overload",
  19886. BfTokenToString(opToken->mToken), mModule->TypeToString(mResult.mType).c_str()), opToken);
  19887. }
  19888. mResult = BfTypedValue();
  19889. }
  19890. if (writeToProp)
  19891. {
  19892. auto setMethod = GetPropertyMethodDef(propDef, BfMethodType_PropertySetter, mPropCheckedKind, mPropTarget);
  19893. if (setMethod == NULL)
  19894. {
  19895. mModule->Fail("Property has no setter", propSrc);
  19896. return;
  19897. }
  19898. auto methodInstance = GetPropertyMethodInstance(setMethod);
  19899. if (!methodInstance.mFunc)
  19900. return;
  19901. if (propSrc != NULL)
  19902. mModule->UpdateExprSrcPos(propSrc);
  19903. SizedArray<BfIRValue, 4> args;
  19904. if (!setMethod->mIsStatic)
  19905. {
  19906. auto usePropTarget = propTarget;
  19907. if (origPropTarget.mType == methodInstance.mMethodInstance->GetOwner())
  19908. usePropTarget = origPropTarget;
  19909. else
  19910. BF_ASSERT(propTarget.mType == methodInstance.mMethodInstance->GetOwner());
  19911. PushThis(propSrc, usePropTarget, methodInstance.mMethodInstance, args);
  19912. }
  19913. for (int paramIdx = 0; paramIdx < (int)indexerVals.size(); paramIdx++)
  19914. {
  19915. auto val = mModule->Cast(propSrc, indexerVals[paramIdx].mTypedValue, methodInstance.mMethodInstance->GetParamType(paramIdx));
  19916. if (!val)
  19917. return;
  19918. PushArg(val, args);
  19919. }
  19920. PushArg(writeToProp, args);
  19921. CreateCall(opToken, methodInstance.mMethodInstance, methodInstance.mFunc, false, args);
  19922. }
  19923. }
  19924. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue)
  19925. {
  19926. BfTypedValue rightValue;
  19927. if (rightExpression == NULL)
  19928. {
  19929. mModule->AssertErrorState();
  19930. return;
  19931. }
  19932. if (!leftValue)
  19933. {
  19934. if (!rightValue)
  19935. mModule->CreateValueFromExpression(rightExpression, mExpectingType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  19936. return;
  19937. }
  19938. if (leftValue.mType->IsRef())
  19939. leftValue.mType = leftValue.mType->GetUnderlyingType();
  19940. if ((binaryOp == BfBinaryOp_ConditionalAnd) || (binaryOp == BfBinaryOp_ConditionalOr))
  19941. {
  19942. if (mModule->mCurMethodState->mDeferredLocalAssignData != NULL)
  19943. mModule->mCurMethodState->mDeferredLocalAssignData->BreakExtendChain();
  19944. if (mModule->mCurMethodState->mCurScope->mScopeKind == BfScopeKind_StatementTarget)
  19945. mModule->mCurMethodState->mCurScope->mScopeKind = BfScopeKind_StatementTarget_Conditional;
  19946. bool isAnd = binaryOp == BfBinaryOp_ConditionalAnd;
  19947. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  19948. leftValue = mModule->Cast(leftExpression, leftValue, boolType);
  19949. if (!leftValue)
  19950. {
  19951. mModule->CreateValueFromExpression(rightExpression);
  19952. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Undef);
  19953. return;
  19954. }
  19955. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  19956. SetAndRestoreValue<bool> prevInCondBlock(mModule->mCurMethodState->mInConditionalBlock, true);
  19957. // The RHS is not guaranteed to be executed
  19958. if ((mModule->mCurMethodState->mDeferredLocalAssignData != NULL) &&
  19959. (mModule->mCurMethodState->mDeferredLocalAssignData->mIsIfCondition))
  19960. mModule->mCurMethodState->mDeferredLocalAssignData->mIfMayBeSkipped = true;
  19961. if (isAnd)
  19962. {
  19963. bool isConstBranch = false;
  19964. bool constResult = false;
  19965. if (leftValue.mValue.IsConst())
  19966. {
  19967. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  19968. if (constValue->mTypeCode == BfTypeCode_Boolean)
  19969. {
  19970. isConstBranch = true;
  19971. constResult = constValue->mBool;
  19972. }
  19973. }
  19974. if (isConstBranch)
  19975. {
  19976. if ((constResult) || (HasVariableDeclaration(rightExpression)))
  19977. {
  19978. // Only right side
  19979. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  19980. mResult = rightValue;
  19981. }
  19982. else
  19983. {
  19984. // Always false
  19985. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  19986. SetAndRestoreValue<bool> prevInConstIgnore(mModule->mCurMethodState->mCurScope->mInConstIgnore, true);
  19987. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  19988. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), boolType);
  19989. }
  19990. }
  19991. else
  19992. {
  19993. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("land.rhs");
  19994. auto endBB = mModule->mBfIRBuilder->CreateBlock("land.end");
  19995. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, rhsBB, endBB);
  19996. mModule->AddBasicBlock(rhsBB);
  19997. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_CreateConditionalScope));
  19998. mModule->mBfIRBuilder->CreateBr(endBB);
  19999. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  20000. mModule->AddBasicBlock(endBB);
  20001. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  20002. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(0, boolType), prevBB);
  20003. if (rightValue)
  20004. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  20005. mResult = BfTypedValue(phi, boolType);
  20006. }
  20007. }
  20008. else
  20009. {
  20010. // Put variables in here into a 'possibly assigned' but never commit it.
  20011. // Because if we had "if ((Get(out a)) || (GetOther(out a))" then the LHS would already set it as defined, so
  20012. // the RHS is inconsequential
  20013. BfDeferredLocalAssignData deferredLocalAssignData;
  20014. deferredLocalAssignData.ExtendFrom(mModule->mCurMethodState->mDeferredLocalAssignData, false);
  20015. deferredLocalAssignData.mVarIdBarrier = mModule->mCurMethodState->GetRootMethodState()->mCurLocalVarId;
  20016. SetAndRestoreValue<BfDeferredLocalAssignData*> prevDLA(mModule->mCurMethodState->mDeferredLocalAssignData, &deferredLocalAssignData);
  20017. bool isConstBranch = false;
  20018. bool constResult = false;
  20019. if (leftValue.mValue.IsConst())
  20020. {
  20021. auto constValue = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  20022. if (constValue->mTypeCode == BfTypeCode_Boolean)
  20023. {
  20024. isConstBranch = true;
  20025. constResult = constValue->mBool;
  20026. }
  20027. }
  20028. if (isConstBranch)
  20029. {
  20030. if ((constResult) && (!HasVariableDeclaration(rightExpression)))
  20031. {
  20032. // Always true
  20033. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  20034. SetAndRestoreValue<bool> prevInConstIgnore(mModule->mCurMethodState->mCurScope->mInConstIgnore, true);
  20035. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  20036. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), boolType);
  20037. }
  20038. else
  20039. {
  20040. // Only right side
  20041. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  20042. mResult = rightValue;
  20043. }
  20044. }
  20045. else
  20046. {
  20047. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("lor.rhs");
  20048. auto endBB = mModule->mBfIRBuilder->CreateBlock("lor.end");
  20049. // This makes any 'scope' allocs be dyn since we aren't sure if this will be short-circuited
  20050. SetAndRestoreValue<bool> prevIsConditional(mModule->mCurMethodState->mCurScope->mIsConditional, true);
  20051. mModule->mBfIRBuilder->CreateCondBr(leftValue.mValue, endBB, rhsBB);
  20052. mModule->AddBasicBlock(rhsBB);
  20053. rightValue = mModule->CreateValueFromExpression(rightExpression, boolType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  20054. mModule->mBfIRBuilder->CreateBr(endBB);
  20055. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  20056. mModule->AddBasicBlock(endBB);
  20057. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(boolType), 2);
  20058. mModule->mBfIRBuilder->AddPhiIncoming(phi, mModule->GetConstValue(1, boolType), prevBB);
  20059. if (rightValue)
  20060. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  20061. mResult = BfTypedValue(phi, boolType);
  20062. }
  20063. }
  20064. return;
  20065. }
  20066. BfType* wantType = leftValue.mType;
  20067. BfType* origWantType = wantType;
  20068. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  20069. wantType = NULL; // Don't presume
  20070. wantType = mModule->FixIntUnknown(wantType);
  20071. if ((binaryOp == BfBinaryOp_NullCoalesce) && (PerformBinaryOperation_NullCoalesce(opToken, leftExpression, rightExpression, leftValue, wantType, NULL)))
  20072. return;
  20073. BfType* rightWantType = wantType;
  20074. if (origWantType->IsIntUnknown())
  20075. rightWantType = NULL;
  20076. else if ((mExpectingType != NULL) && (wantType != NULL) && (mExpectingType->IsIntegral()) && (wantType->IsIntegral()) && (mExpectingType->mSize > wantType->mSize) &&
  20077. ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_Multiply)))
  20078. rightWantType = mExpectingType;
  20079. rightValue = mModule->CreateValueFromExpression(rightExpression, rightWantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  20080. if ((rightWantType != wantType) && (rightValue.mType == rightWantType))
  20081. wantType = rightWantType;
  20082. if ((!leftValue) || (!rightValue))
  20083. return;
  20084. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue);
  20085. }
  20086. bool BfExprEvaluator::PerformBinaryOperation_NullCoalesce(BfTokenNode* opToken, BfExpression* leftExpression, BfExpression* rightExpression, BfTypedValue leftValue, BfType* wantType, BfTypedValue* assignTo)
  20087. {
  20088. if ((leftValue) && ((leftValue.mType->IsPointer()) || (leftValue.mType->IsFunction()) || (leftValue.mType->IsObject())))
  20089. {
  20090. leftValue = mModule->LoadValue(leftValue);
  20091. if (leftValue.mValue.IsConst())
  20092. {
  20093. auto constant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  20094. if (constant->IsNull())
  20095. {
  20096. mResult = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)(mBfEvalExprFlags & BfEvalExprFlags_InheritFlags));
  20097. return true;
  20098. }
  20099. // Already have a value, we don't need the right side
  20100. SetAndRestoreValue<bool> prevIgnoreWrites(mModule->mBfIRBuilder->mIgnoreWrites, true);
  20101. SetAndRestoreValue<bool> prevInConstIgnore(mModule->mCurMethodState->mCurScope->mInConstIgnore, true);
  20102. mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_CreateConditionalScope));
  20103. mResult = leftValue;
  20104. return true;
  20105. }
  20106. auto prevBB = mModule->mBfIRBuilder->GetInsertBlock();
  20107. auto rhsBB = mModule->mBfIRBuilder->CreateBlock("nullc.rhs");
  20108. auto endBB = mModule->mBfIRBuilder->CreateBlock("nullc.end");
  20109. auto lhsBB = endBB;
  20110. auto endLhsBB = prevBB;
  20111. BfIRValue isNull;
  20112. if (leftValue.mType->IsFunction())
  20113. isNull = mModule->mBfIRBuilder->CreateIsNull(
  20114. mModule->mBfIRBuilder->CreateIntToPtr(leftValue.mValue, mModule->mBfIRBuilder->MapType(mModule->GetPrimitiveType(BfTypeCode_NullPtr))));
  20115. else
  20116. isNull = mModule->mBfIRBuilder->CreateIsNull(leftValue.mValue);
  20117. mModule->AddBasicBlock(rhsBB);
  20118. BfTypedValue rightValue;
  20119. if (assignTo != NULL)
  20120. rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_CreateConditionalScope));
  20121. else
  20122. rightValue = mModule->CreateValueFromExpression(rightExpression, wantType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_CreateConditionalScope));
  20123. if (!rightValue)
  20124. {
  20125. mModule->AssertErrorState();
  20126. return true;
  20127. }
  20128. rightValue = mModule->LoadValue(rightValue);
  20129. if (assignTo == NULL)
  20130. {
  20131. auto rightToLeftValue = mModule->CastToValue(rightExpression, rightValue, leftValue.mType, BfCastFlags_SilentFail);
  20132. if (rightToLeftValue)
  20133. {
  20134. rightValue = BfTypedValue(rightToLeftValue, leftValue.mType);
  20135. }
  20136. else
  20137. {
  20138. lhsBB = mModule->mBfIRBuilder->CreateBlock("nullc.lhs", true);
  20139. mModule->mBfIRBuilder->SetInsertPoint(lhsBB);
  20140. auto leftToRightValue = mModule->CastToValue(leftExpression, leftValue, rightValue.mType, BfCastFlags_SilentFail);
  20141. if (leftToRightValue)
  20142. {
  20143. leftValue = BfTypedValue(leftToRightValue, rightValue.mType);
  20144. }
  20145. else
  20146. {
  20147. // Note: Annoying trigraph split for '??'
  20148. mModule->Fail(StrFormat("Operator '?" "?' cannot be applied to operands of type '%s' and '%s'",
  20149. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  20150. leftValue = mModule->GetDefaultTypedValue(rightValue.mType);
  20151. }
  20152. mModule->mBfIRBuilder->CreateBr(endBB);
  20153. endLhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  20154. mModule->mBfIRBuilder->SetInsertPoint(rhsBB);
  20155. }
  20156. }
  20157. if (assignTo != NULL)
  20158. mModule->mBfIRBuilder->CreateStore(rightValue.mValue, assignTo->mValue);
  20159. mModule->mBfIRBuilder->CreateBr(endBB);
  20160. auto endRhsBB = mModule->mBfIRBuilder->GetInsertBlock();
  20161. // Actually add CondBr at start
  20162. mModule->mBfIRBuilder->SetInsertPoint(prevBB);
  20163. mModule->mBfIRBuilder->CreateCondBr(isNull, rhsBB, lhsBB);
  20164. mModule->AddBasicBlock(endBB);
  20165. if (assignTo != NULL)
  20166. {
  20167. mResult = *assignTo;
  20168. }
  20169. else
  20170. {
  20171. auto phi = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(leftValue.mType), 2);
  20172. mModule->mBfIRBuilder->AddPhiIncoming(phi, leftValue.mValue, endLhsBB);
  20173. mModule->mBfIRBuilder->AddPhiIncoming(phi, rightValue.mValue, endRhsBB);
  20174. mResult = BfTypedValue(phi, leftValue.mType);
  20175. }
  20176. return true;
  20177. }
  20178. return false;
  20179. }
  20180. bool BfExprEvaluator::PerformBinaryOperation_Numeric(BfAstNode* leftExpression, BfAstNode* rightExpression, BfBinaryOp binaryOp, BfAstNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue, BfTypedValue rightValue)
  20181. {
  20182. switch (binaryOp)
  20183. {
  20184. case BfBinaryOp_Add:
  20185. case BfBinaryOp_Subtract:
  20186. case BfBinaryOp_Multiply:
  20187. case BfBinaryOp_Divide:
  20188. case BfBinaryOp_Modulus:
  20189. break;
  20190. default:
  20191. return false;
  20192. }
  20193. auto wantType = mExpectingType;
  20194. if ((wantType == NULL) ||
  20195. ((!wantType->IsFloat()) && (!wantType->IsIntegral())))
  20196. wantType = NULL;
  20197. auto leftType = mModule->GetClosestNumericCastType(leftValue, mExpectingType);
  20198. auto rightType = mModule->GetClosestNumericCastType(rightValue, mExpectingType);
  20199. if (leftType != NULL)
  20200. {
  20201. if ((rightType == NULL) || (mModule->CanCast(mModule->GetFakeTypedValue(rightType), leftType)))
  20202. wantType = leftType;
  20203. else if ((rightType != NULL) && (mModule->CanCast(mModule->GetFakeTypedValue(leftType), rightType)))
  20204. wantType = rightType;
  20205. }
  20206. else if (rightType != NULL)
  20207. wantType = rightType;
  20208. if (wantType == NULL)
  20209. wantType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  20210. auto convLeftValue = mModule->Cast(opToken, leftValue, wantType, BfCastFlags_SilentFail);
  20211. if (!convLeftValue)
  20212. return false;
  20213. auto convRightValue = mModule->Cast(opToken, rightValue, wantType, BfCastFlags_SilentFail);
  20214. if (!convRightValue)
  20215. return false;
  20216. mResult = BfTypedValue();
  20217. // Let the error come from here, if any - so we always return 'true' to avoid a second error
  20218. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, convLeftValue, convRightValue);
  20219. return true;
  20220. }
  20221. void BfExprEvaluator::PerformBinaryOperation(BfExpression* leftExpression, BfExpression* rightExpression, BfBinaryOp binaryOp, BfTokenNode* opToken, BfBinOpFlags flags)
  20222. {
  20223. if ((binaryOp == BfBinaryOp_Range) || (binaryOp == BfBinaryOp_ClosedRange))
  20224. {
  20225. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  20226. bool isIndexExpr = false;
  20227. BfTypeDef* typeDef = NULL;
  20228. if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(leftExpression))
  20229. if (unaryOpExpr->mOp == BfUnaryOp_FromEnd)
  20230. isIndexExpr = true;
  20231. if (rightExpression == NULL)
  20232. isIndexExpr = true;
  20233. if (auto unaryOpExpr = BfNodeDynCast<BfUnaryOperatorExpression>(rightExpression))
  20234. if (unaryOpExpr->mOp == BfUnaryOp_FromEnd)
  20235. isIndexExpr = true;
  20236. if (isIndexExpr)
  20237. typeDef = mModule->mCompiler->mIndexRangeTypeDef;
  20238. else
  20239. typeDef = (binaryOp == BfBinaryOp_Range) ? mModule->mCompiler->mRangeTypeDef : mModule->mCompiler->mClosedRangeTypeDef;
  20240. auto allocType = mModule->ResolveTypeDef(typeDef)->ToTypeInstance();
  20241. auto alloca = mModule->CreateAlloca(allocType);
  20242. BfTypedValueExpression leftTypedValueExpr;
  20243. BfTypedValueExpression rightTypedValueExpr;
  20244. BfTypedValueExpression isClosedTypedValueExpr;
  20245. SizedArray<BfExpression*, 2> argExprs;
  20246. if (leftExpression != NULL)
  20247. {
  20248. argExprs.Add(leftExpression);
  20249. }
  20250. else
  20251. {
  20252. leftTypedValueExpr.mRefNode = opToken;
  20253. leftTypedValueExpr.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), mModule->GetPrimitiveType(BfTypeCode_IntPtr));
  20254. argExprs.Add(&leftTypedValueExpr);
  20255. }
  20256. if (rightExpression != NULL)
  20257. {
  20258. argExprs.Add(rightExpression);
  20259. }
  20260. else
  20261. {
  20262. // Add as a `^1`
  20263. auto indexType = mModule->ResolveTypeDef(mModule->mCompiler->mIndexTypeDef)->ToTypeInstance();
  20264. rightTypedValueExpr.mRefNode = opToken;
  20265. auto valueTypeEmpty = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType->mBaseType->mBaseType), {});
  20266. SizedArray<BfIRValue, 8> enumMembers;
  20267. enumMembers.Add(valueTypeEmpty);
  20268. auto enumValue = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType->mBaseType), enumMembers);
  20269. SizedArray<BfIRValue, 8> tupleMembers;
  20270. tupleMembers.Add(valueTypeEmpty);
  20271. tupleMembers.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1));
  20272. auto tupleValue = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType->mFieldInstances[0].mResolvedType), tupleMembers);
  20273. SizedArray<BfIRValue, 8> indexMembers;
  20274. indexMembers.Add(enumValue);
  20275. indexMembers.Add(tupleValue);
  20276. indexMembers.Add(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Int8, 1));
  20277. auto indexValue = mModule->mBfIRBuilder->CreateConstAgg(mModule->mBfIRBuilder->MapType(indexType), indexMembers);
  20278. rightTypedValueExpr.mTypedValue = BfTypedValue(indexValue, indexType);
  20279. argExprs.Add(&rightTypedValueExpr);
  20280. }
  20281. if (isIndexExpr)
  20282. {
  20283. isClosedTypedValueExpr.mRefNode = opToken;
  20284. isClosedTypedValueExpr.mTypedValue = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, (binaryOp == BfBinaryOp_ClosedRange) ? 1 : 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  20285. argExprs.Add(&isClosedTypedValueExpr);
  20286. }
  20287. BfSizedArray<BfExpression*> args = argExprs;
  20288. BfResolvedArgs argValues;
  20289. argValues.Init(&args);
  20290. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  20291. mResult = BfTypedValue(alloca, allocType, true);
  20292. auto result = MatchConstructor(opToken, NULL, mResult, allocType, argValues, true, false);
  20293. if ((result) && (!result.mType->IsVoid()))
  20294. mResult = result;
  20295. return;
  20296. }
  20297. BfTypedValue leftValue;
  20298. if (leftExpression != NULL)
  20299. {
  20300. leftValue = mModule->CreateValueFromExpression(leftExpression, mExpectingType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_NoCast | BfEvalExprFlags_AllowIntUnknown));
  20301. }
  20302. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue);
  20303. }
  20304. bool BfExprEvaluator::CheckConstCompare(BfBinaryOp binaryOp, BfAstNode* opToken, const BfTypedValue& leftValue, const BfTypedValue& rightValue)
  20305. {
  20306. if ((binaryOp < BfBinaryOp_Equality) || (binaryOp > BfBinaryOp_LessThanOrEqual))
  20307. return false;
  20308. // LHS is expected to be a value and RHS is expected to be a const
  20309. if (!leftValue.mType->IsIntegral())
  20310. return false;
  20311. BF_ASSERT(rightValue.mValue.IsConst());
  20312. auto rightConst = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  20313. if (!mModule->mBfIRBuilder->IsInt(rightConst->mTypeCode))
  20314. return false;
  20315. BfType* checkType = leftValue.mType;
  20316. if (checkType->IsTypedPrimitive())
  20317. checkType = checkType->GetUnderlyingType();
  20318. if (!checkType->IsPrimitiveType())
  20319. return false;
  20320. BfTypeCode typeCode = ((BfPrimitiveType*)checkType)->mTypeDef->mTypeCode;
  20321. int64 minValue = 0;
  20322. int64 maxValue = 0;
  20323. switch (typeCode)
  20324. {
  20325. case BfTypeCode_Int8:
  20326. minValue = -0x80;
  20327. maxValue = 0x7F;
  20328. break;
  20329. case BfTypeCode_Int16:
  20330. minValue = -0x8000;
  20331. maxValue = 0x7FFF;
  20332. break;
  20333. case BfTypeCode_Int32:
  20334. minValue = -0x80000000LL;
  20335. maxValue = 0x7FFFFFFF;
  20336. break;
  20337. case BfTypeCode_Int64:
  20338. minValue = -0x8000000000000000LL;
  20339. maxValue = 0x7FFFFFFFFFFFFFFFLL;
  20340. break;
  20341. case BfTypeCode_UInt8:
  20342. maxValue = 0xFF;
  20343. break;
  20344. case BfTypeCode_UInt16:
  20345. maxValue = 0xFFFF;
  20346. break;
  20347. case BfTypeCode_UInt32:
  20348. maxValue = 0xFFFFFFFF;
  20349. break;
  20350. default:
  20351. return false;
  20352. }
  20353. int constResult = -1;
  20354. if (typeCode == BfTypeCode_UInt64)
  20355. {
  20356. switch (binaryOp)
  20357. {
  20358. case BfBinaryOp_Equality:
  20359. case BfBinaryOp_StrictEquality:
  20360. if (rightConst->mInt64 < minValue)
  20361. constResult = 0;
  20362. break;
  20363. case BfBinaryOp_InEquality:
  20364. case BfBinaryOp_StrictInEquality:
  20365. if (rightConst->mInt64 < minValue)
  20366. constResult = 1;
  20367. break;
  20368. case BfBinaryOp_LessThan:
  20369. if (rightConst->mInt64 <= minValue)
  20370. constResult = 0;
  20371. break;
  20372. case BfBinaryOp_LessThanOrEqual:
  20373. if (rightConst->mInt64 < minValue)
  20374. constResult = 0;
  20375. break;
  20376. default: break;
  20377. }
  20378. return false;
  20379. }
  20380. else
  20381. {
  20382. switch (binaryOp)
  20383. {
  20384. case BfBinaryOp_Equality:
  20385. case BfBinaryOp_StrictEquality:
  20386. if (rightConst->mInt64 < minValue)
  20387. constResult = 0;
  20388. else if (rightConst->mInt64 > maxValue)
  20389. constResult = 0;
  20390. break;
  20391. case BfBinaryOp_InEquality:
  20392. case BfBinaryOp_StrictInEquality:
  20393. if (rightConst->mInt64 < minValue)
  20394. constResult = 1;
  20395. else if (rightConst->mInt64 > maxValue)
  20396. constResult = 1;
  20397. break;
  20398. case BfBinaryOp_LessThan:
  20399. if (rightConst->mInt64 <= minValue)
  20400. constResult = 0;
  20401. else if (rightConst->mInt64 > maxValue)
  20402. constResult = 1;
  20403. break;
  20404. case BfBinaryOp_LessThanOrEqual:
  20405. if (rightConst->mInt64 < minValue)
  20406. constResult = 0;
  20407. else if (rightConst->mInt64 >= maxValue)
  20408. constResult = 1;
  20409. break;
  20410. case BfBinaryOp_GreaterThan:
  20411. if (rightConst->mInt64 >= maxValue)
  20412. constResult = 0;
  20413. else if (rightConst->mInt64 < minValue)
  20414. constResult = 1;
  20415. break;
  20416. case BfBinaryOp_GreaterThanOrEqual:
  20417. if (rightConst->mInt64 > maxValue)
  20418. constResult = 0;
  20419. else if (rightConst->mInt64 <= minValue)
  20420. constResult = 1;
  20421. break;
  20422. default: break;
  20423. }
  20424. }
  20425. if (constResult == 0)
  20426. {
  20427. mModule->Warn(0, "The result of this operation is always 'false'", opToken);
  20428. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  20429. return true;
  20430. }
  20431. else if (constResult == 1)
  20432. {
  20433. mModule->Warn(0, "The result of this operation is always 'true'", opToken);
  20434. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  20435. return true;
  20436. }
  20437. return false;
  20438. }
  20439. void BfExprEvaluator::AddStrings(const BfTypedValue& leftValue, const BfTypedValue& rightValue, BfAstNode* refNode)
  20440. {
  20441. if ((leftValue.mValue.IsConst()) && (rightValue.mValue.IsConst()))
  20442. {
  20443. String* lhsStr = mModule->GetStringPoolString(leftValue.mValue, mModule->mBfIRBuilder);
  20444. String* rhsStr = mModule->GetStringPoolString(rightValue.mValue, mModule->mBfIRBuilder);
  20445. if ((lhsStr != NULL) && (rhsStr != NULL))
  20446. {
  20447. String resultStr = *lhsStr + *rhsStr;
  20448. BfVariant variant;
  20449. variant.mTypeCode = BfTypeCode_CharPtr;
  20450. variant.mString = &resultStr;
  20451. GetLiteral(refNode, variant);
  20452. return;
  20453. }
  20454. }
  20455. mModule->Fail("Strings can only be added when they are constants. Consider allocating a string and using Concat.", refNode);
  20456. return;
  20457. }
  20458. void BfExprEvaluator::PerformBinaryOperation(BfAstNode* leftExpression, BfAstNode* rightExpression, BfBinaryOp binaryOp, BfAstNode* opToken, BfBinOpFlags flags, BfTypedValue leftValue, BfTypedValue rightValue)
  20459. {
  20460. bool noClassify = (flags & BfBinOpFlag_NoClassify) != 0;
  20461. bool forceLeftType = (flags & BfBinOpFlag_ForceLeftType) != 0;
  20462. bool deferRight = (flags & BfBinOpFlag_DeferRight) != 0;
  20463. if (deferRight)
  20464. {
  20465. rightValue = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  20466. }
  20467. if ((rightValue.mValue.IsConst()) && (!leftValue.mValue.IsConst()))
  20468. {
  20469. if (CheckConstCompare(binaryOp, opToken, leftValue, rightValue))
  20470. return;
  20471. }
  20472. else if ((leftValue.mValue.IsConst()) && (!rightValue.mValue.IsConst()))
  20473. {
  20474. if (CheckConstCompare(BfGetOppositeBinaryOp(binaryOp), opToken, rightValue, leftValue))
  20475. return;
  20476. }
  20477. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  20478. {
  20479. forceLeftType = true;
  20480. }
  20481. if (rightValue.mType->IsRef())
  20482. rightValue.mType = rightValue.mType->GetUnderlyingType();
  20483. BfType* origLeftType = leftValue.mType;
  20484. BfType* origRightType = rightValue.mType;
  20485. mModule->FixIntUnknown(leftValue, rightValue);
  20486. // Prefer floats, prefer chars
  20487. int leftCompareSize = leftValue.mType->mSize;
  20488. if (leftValue.mType->IsFloat())
  20489. leftCompareSize += 0x10;
  20490. if (leftValue.mType->IsChar())
  20491. leftCompareSize += 0x100;
  20492. if (!leftValue.mType->IsPrimitiveType())
  20493. leftCompareSize += 0x1000;
  20494. int rightCompareSize = rightValue.mType->mSize;
  20495. if (rightValue.mType->IsFloat())
  20496. rightCompareSize += 0x10;
  20497. if (rightValue.mType->IsChar())
  20498. rightCompareSize += 0x100;
  20499. if (!rightValue.mType->IsPrimitiveType())
  20500. rightCompareSize += 0x1000;
  20501. if ((leftValue.mType->IsTypeInstance()) && (rightValue.mType->IsTypeInstance()))
  20502. {
  20503. int leftInheritDepth = leftValue.mType->ToTypeInstance()->mInheritDepth;
  20504. int rightInheritDepth = rightValue.mType->ToTypeInstance()->mInheritDepth;
  20505. if (leftInheritDepth < rightInheritDepth)
  20506. {
  20507. // If both are type instances then choose the type with the lowest inherit depth
  20508. // so we will choose the base type when applicable
  20509. forceLeftType = true;
  20510. }
  20511. }
  20512. auto resultType = leftValue.mType;
  20513. if (!forceLeftType)
  20514. {
  20515. bool handled = false;
  20516. BfType* expectingType = mExpectingType;
  20517. if (leftValue.mType == rightValue.mType)
  20518. {
  20519. // All good
  20520. handled = true;
  20521. }
  20522. else if ((expectingType != NULL) &&
  20523. (mModule->CanCast(leftValue, expectingType, BfCastFlags_NoBox)) &&
  20524. (mModule->CanCast(rightValue, expectingType, BfCastFlags_NoBox)) &&
  20525. (!leftValue.mType->IsVar()) && (!rightValue.mType->IsVar()))
  20526. {
  20527. resultType = expectingType;
  20528. handled = true;
  20529. }
  20530. else
  20531. {
  20532. // If one of these is a constant that can be converted into a smaller type, then do that
  20533. if (rightValue.mValue.IsConst())
  20534. {
  20535. if (mModule->CanCast(rightValue, leftValue.mType, BfCastFlags_NoBox))
  20536. {
  20537. resultType = leftValue.mType;
  20538. handled = true;
  20539. }
  20540. }
  20541. // If left is an IntUnknown, allow the right to inform the type
  20542. if (leftValue.mType->IsIntUnknown())
  20543. {
  20544. if (leftValue.mValue.IsConst())
  20545. {
  20546. if (mModule->CanCast(leftValue, rightValue.mType))
  20547. {
  20548. resultType = rightValue.mType;
  20549. handled = true;
  20550. }
  20551. }
  20552. }
  20553. if ((leftValue.mType->IsPointer()) &&
  20554. (rightValue.mType->IsPointer()))
  20555. {
  20556. BfPointerType* leftPointerType = (BfPointerType*)leftValue.mType;
  20557. BfPointerType* rightPointerType = (BfPointerType*)rightValue.mType;
  20558. // If one is a pointer to a sized array then use the other type
  20559. if (leftPointerType->mElementType->IsSizedArray())
  20560. {
  20561. resultType = rightPointerType;
  20562. handled = true;
  20563. }
  20564. else if (rightPointerType->mElementType->IsSizedArray())
  20565. {
  20566. resultType = leftPointerType;
  20567. handled = true;
  20568. }
  20569. }
  20570. }
  20571. if (!handled)
  20572. {
  20573. if ((resultType->IsNull()) ||
  20574. (rightCompareSize > leftCompareSize) ||
  20575. (((rightCompareSize == leftCompareSize) && (!rightValue.mType->IsSigned()))) ||
  20576. (rightValue.mType->IsTypedPrimitive()))
  20577. {
  20578. // Select the type with the "most information"
  20579. if (!rightValue.mType->IsNull())
  20580. resultType = rightValue.mType;
  20581. }
  20582. if ((!resultType->IsPointer()) && (rightValue.mType->IsPointer()))
  20583. resultType = rightValue.mType;
  20584. }
  20585. }
  20586. bool explicitCast = false;
  20587. BfTypedValue* resultTypedValue;
  20588. BfTypedValue* otherTypedValue;
  20589. BfType* otherType;
  20590. BfAstNode* resultTypeSrc;
  20591. BfAstNode* otherTypeSrc;
  20592. if (resultType == leftValue.mType)
  20593. {
  20594. resultTypedValue = &leftValue;
  20595. resultTypeSrc = leftExpression;
  20596. otherTypedValue = &rightValue;
  20597. otherTypeSrc = rightExpression;
  20598. otherType = otherTypedValue->mType;
  20599. }
  20600. else
  20601. {
  20602. resultTypedValue = &rightValue;
  20603. resultTypeSrc = rightExpression;
  20604. otherTypedValue = &leftValue;
  20605. otherTypeSrc = leftExpression;
  20606. otherType = otherTypedValue->mType;
  20607. }
  20608. auto _OpFail = [&]()
  20609. {
  20610. if ((rightValue.mType != NULL) && (leftValue.mType != NULL))
  20611. {
  20612. if (rightValue.mType != leftValue.mType)
  20613. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between types '%s' and '%s'",
  20614. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()), opToken);
  20615. else
  20616. {
  20617. if (leftValue.mType->IsInterface())
  20618. {
  20619. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between two instances of interface '%s'. Consider rewriting using generics and use this interface as a generic constraint.",
  20620. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  20621. }
  20622. else
  20623. {
  20624. mModule->Fail(StrFormat("Cannot perform binary operation '%s' between two instances of type '%s'",
  20625. BfGetOpName(binaryOp), mModule->TypeToString(leftValue.mType).c_str()), opToken);
  20626. }
  20627. }
  20628. }
  20629. else
  20630. mModule->Fail(StrFormat("Cannot perform binary operation '%s'", BfGetOpName(binaryOp)), opToken);
  20631. };
  20632. // This case fixes cases like "c == 0" where "0" is technically an int but can be reduced
  20633. if (BfBinOpEqualityCheck(binaryOp))
  20634. {
  20635. if ((resultType != otherType) && (resultTypedValue->mValue.IsConst()) && (mModule->CanCast(*resultTypedValue, otherType)))
  20636. {
  20637. std::swap(resultTypedValue, otherTypedValue);
  20638. std::swap(resultTypeSrc, otherTypeSrc);
  20639. std::swap(resultType, otherType);
  20640. }
  20641. }
  20642. BfIRValue convLeftValue;
  20643. BfIRValue convRightValue;
  20644. if (((resultType->IsVar()) || (otherType->IsVar())) && (!deferRight))
  20645. {
  20646. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  20647. if (isComparison)
  20648. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Boolean), false, BfDefaultValueKind_Addr);
  20649. else if (mExpectingType != NULL)
  20650. mResult = mModule->GetDefaultTypedValue(mExpectingType, false, BfDefaultValueKind_Addr);
  20651. else
  20652. mResult = mModule->GetDefaultTypedValue(resultType, false, BfDefaultValueKind_Addr);
  20653. return;
  20654. }
  20655. if ((otherType->IsNull()) && (BfBinOpEqualityCheck(binaryOp)))
  20656. {
  20657. bool isEquality = (binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality);
  20658. if ((resultType->IsValueType()) && (!resultType->IsFunction()))
  20659. {
  20660. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  20661. if (resultType->IsNullable())
  20662. {
  20663. auto elementType = resultType->GetUnderlyingType();
  20664. mModule->PopulateType(elementType);
  20665. if (elementType->IsValuelessType())
  20666. {
  20667. mModule->mBfIRBuilder->PopulateType(resultType);
  20668. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  20669. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 1);
  20670. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateAlignedLoad(hasValuePtr, 1);
  20671. if (isEquality)
  20672. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  20673. mResult = BfTypedValue(hasValueValue, boolType);
  20674. }
  20675. else
  20676. {
  20677. mModule->mBfIRBuilder->PopulateType(resultType);
  20678. BfTypedValue nullableTypedVale = mModule->MakeAddressable(*resultTypedValue);
  20679. BfIRValue hasValuePtr = mModule->mBfIRBuilder->CreateInBoundsGEP(nullableTypedVale.mValue, 0, 2);
  20680. BfIRValue hasValueValue = mModule->mBfIRBuilder->CreateAlignedLoad(hasValuePtr, 1);
  20681. if (isEquality)
  20682. hasValueValue = mModule->mBfIRBuilder->CreateNot(hasValueValue);
  20683. mResult = BfTypedValue(hasValueValue, boolType);
  20684. }
  20685. return;
  20686. }
  20687. if (resultType->IsNull())
  20688. {
  20689. // Null always equals null
  20690. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 1 : 0, boolType), boolType);
  20691. return;
  20692. }
  20693. if (!mModule->IsInSpecializedSection())
  20694. {
  20695. //CS0472: The result of the expression is always 'true' since a value of type 'int' is never equal to 'null' of type '<null>'
  20696. mModule->Warn(BfWarning_CS0472_ValueTypeNullCompare,
  20697. StrFormat("The result of the expression is always '%s' since a value of type '%s' can never be null",
  20698. isEquality ? "false" : "true", mModule->TypeToString(resultType).c_str()), otherTypeSrc);
  20699. }
  20700. // Valuetypes never equal null
  20701. mResult = BfTypedValue(mModule->GetConstValue(isEquality ? 0 : 1, boolType), boolType);
  20702. return;
  20703. }
  20704. }
  20705. // Check for constant equality checks (mostly for strings)
  20706. if (BfBinOpEqualityCheck(binaryOp))
  20707. {
  20708. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  20709. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  20710. if ((leftConstant != NULL) && (rightConstant != NULL))
  20711. {
  20712. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  20713. int leftStringPoolIdx = mModule->GetStringPoolIdx(leftValue.mValue, mModule->mBfIRBuilder);
  20714. if (leftStringPoolIdx != -1)
  20715. {
  20716. int rightStringPoolIdx = mModule->GetStringPoolIdx(rightValue.mValue, mModule->mBfIRBuilder);
  20717. if (rightStringPoolIdx != -1)
  20718. {
  20719. bool isEqual = leftStringPoolIdx == rightStringPoolIdx;
  20720. if ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  20721. isEqual = !isEqual;
  20722. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  20723. return;
  20724. }
  20725. }
  20726. int eqResult = mModule->mBfIRBuilder->CheckConstEquality(leftValue.mValue, rightValue.mValue);
  20727. if (eqResult != -1)
  20728. {
  20729. bool isEqual = eqResult == 1;
  20730. if ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  20731. isEqual = !isEqual;
  20732. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  20733. return;
  20734. }
  20735. }
  20736. }
  20737. if ((leftValue.mType->IsTypeInstance()) || (leftValue.mType->IsGenericParam()) ||
  20738. (rightValue.mType->IsTypeInstance()) || (rightValue.mType->IsGenericParam()))
  20739. {
  20740. // As an optimization, we don't call user operator overloads for null checks
  20741. bool skipOpOverload = false;
  20742. if ((binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  20743. skipOpOverload = true;
  20744. else if (BfBinOpEqualityCheck(binaryOp))
  20745. {
  20746. if (!leftValue.IsAddr())
  20747. {
  20748. auto leftConstant = mModule->mBfIRBuilder->GetConstant(leftValue.mValue);
  20749. if ((leftConstant != NULL) && (leftConstant->IsNull()))
  20750. skipOpOverload = true;
  20751. }
  20752. if (!rightValue.IsAddr())
  20753. {
  20754. auto rightConstant = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  20755. if ((rightConstant != NULL) && (rightConstant->IsNull()))
  20756. skipOpOverload = true;
  20757. }
  20758. }
  20759. if ((binaryOp == BfBinaryOp_Add) && (resultType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  20760. {
  20761. // Allow failover to constant string addition
  20762. if ((leftValue.mValue.IsConst()) && (rightValue.mValue.IsConst()))
  20763. skipOpOverload = true;
  20764. }
  20765. if (!skipOpOverload)
  20766. {
  20767. BfBinaryOp findBinaryOp = binaryOp;
  20768. bool isComparison = (binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_LessThanOrEqual);
  20769. for (int pass = 0; pass < 2; pass++)
  20770. {
  20771. BfBinaryOp oppositeBinaryOp = BfGetOppositeBinaryOp(findBinaryOp);
  20772. BfBinaryOp overflowBinaryOp = BfBinaryOp_None;
  20773. if (findBinaryOp == BfBinaryOp_OverflowAdd)
  20774. overflowBinaryOp = BfBinaryOp_Add;
  20775. else if (findBinaryOp == BfBinaryOp_OverflowSubtract)
  20776. overflowBinaryOp = BfBinaryOp_Subtract;
  20777. else if (findBinaryOp == BfBinaryOp_OverflowMultiply)
  20778. overflowBinaryOp = BfBinaryOp_Multiply;
  20779. bool foundOp = false;
  20780. BfResolvedArg leftArg;
  20781. leftArg.mExpression = leftExpression;
  20782. leftArg.mTypedValue = leftValue;
  20783. BfResolvedArg rightArg;
  20784. rightArg.mExpression = rightExpression;
  20785. rightArg.mTypedValue = rightValue;
  20786. if (deferRight)
  20787. {
  20788. BfResolvedArgs argValues;
  20789. SizedArray<BfExpression*, 2> argExprs;
  20790. argExprs.push_back(BfNodeDynCast<BfExpression>(rightExpression));
  20791. BfSizedArray<BfExpression*> sizedArgExprs(argExprs);
  20792. argValues.Init(&sizedArgExprs);
  20793. ResolveArgValues(argValues, BfResolveArgsFlag_DeferParamEval);
  20794. rightArg = argValues.mResolvedArgs[0];
  20795. }
  20796. SizedArray<BfResolvedArg, 2> args;
  20797. if (pass == 0)
  20798. {
  20799. args.push_back(leftArg);
  20800. args.push_back(rightArg);
  20801. }
  20802. else
  20803. {
  20804. args.push_back(rightArg);
  20805. args.push_back(leftArg);
  20806. }
  20807. auto checkLeftType = leftValue.mType;
  20808. auto checkRightType = rightValue.mType;
  20809. BfMethodMatcher methodMatcher(opToken, mModule, "", args, BfMethodGenericArguments());
  20810. methodMatcher.mAllowImplicitRef = true;
  20811. methodMatcher.mBfEvalExprFlags = BfEvalExprFlags_NoAutoComplete;
  20812. BfBaseClassWalker baseClassWalker(checkLeftType, checkRightType, mModule);
  20813. bool invertResult = false;
  20814. BfType* operatorConstraintReturnType = NULL;
  20815. bool wasTransformedUsage = (pass == 1);
  20816. while (true)
  20817. {
  20818. auto entry = baseClassWalker.Next();
  20819. auto checkType = entry.mTypeInstance;
  20820. if (checkType == NULL)
  20821. break;
  20822. bool foundExactMatch = false;
  20823. SizedArray<BfOperatorDef*, 8> oppositeOperatorDefs;
  20824. for (auto operatorDef : checkType->mTypeDef->mOperators)
  20825. {
  20826. bool allowOp = operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp;
  20827. if ((isComparison) && (operatorDef->mOperatorDeclaration->mBinOp == BfBinaryOp_Compare))
  20828. allowOp = true;
  20829. if (allowOp)
  20830. {
  20831. foundOp = true;
  20832. if (!methodMatcher.IsMemberAccessible(checkType, operatorDef->mDeclaringType))
  20833. continue;
  20834. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  20835. {
  20836. if (operatorDef->mGenericParams.IsEmpty())
  20837. {
  20838. // Fast check
  20839. auto returnType = mModule->CheckOperator(checkType, operatorDef, args[0].mTypedValue, args[1].mTypedValue);
  20840. if (returnType != NULL)
  20841. {
  20842. operatorConstraintReturnType = returnType;
  20843. methodMatcher.mBestMethodDef = operatorDef;
  20844. methodMatcher.mBestMethodTypeInstance = checkType;
  20845. foundExactMatch = true;
  20846. }
  20847. }
  20848. else
  20849. {
  20850. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  20851. {
  20852. auto rawMethodInstance = mModule->GetRawMethodInstance(checkType, operatorDef);
  20853. auto returnType = mModule->ResolveGenericType(rawMethodInstance->mReturnType, NULL, &methodMatcher.mBestMethodGenericArguments,
  20854. mModule->mCurTypeInstance);
  20855. if (returnType != NULL)
  20856. {
  20857. operatorConstraintReturnType = returnType;
  20858. foundExactMatch = true;
  20859. }
  20860. }
  20861. }
  20862. }
  20863. else
  20864. {
  20865. if (methodMatcher.CheckMethod(NULL, checkType, operatorDef, false))
  20866. {
  20867. methodMatcher.mSelfType = entry.mSrcType;
  20868. if (operatorDef->mOperatorDeclaration->mBinOp == findBinaryOp)
  20869. foundExactMatch = true;
  20870. }
  20871. }
  20872. }
  20873. else if ((operatorDef->mOperatorDeclaration->mBinOp == oppositeBinaryOp) || (operatorDef->mOperatorDeclaration->mBinOp == overflowBinaryOp))
  20874. oppositeOperatorDefs.Add(operatorDef);
  20875. }
  20876. if ((((methodMatcher.mBestMethodDef == NULL) && (operatorConstraintReturnType == NULL)) || (!foundExactMatch)) && (!oppositeOperatorDefs.IsEmpty()))
  20877. {
  20878. foundOp = true;
  20879. for (auto oppositeOperatorDef : oppositeOperatorDefs)
  20880. {
  20881. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  20882. {
  20883. if (oppositeOperatorDef->mGenericParams.IsEmpty())
  20884. {
  20885. // Fast check
  20886. auto returnType = mModule->CheckOperator(checkType, oppositeOperatorDef, args[0].mTypedValue, args[1].mTypedValue);
  20887. if (returnType != NULL)
  20888. {
  20889. operatorConstraintReturnType = returnType;
  20890. methodMatcher.mBestMethodDef = oppositeOperatorDef;
  20891. methodMatcher.mBestMethodTypeInstance = checkType;
  20892. methodMatcher.mSelfType = entry.mSrcType;
  20893. if (oppositeBinaryOp != BfBinaryOp_None)
  20894. wasTransformedUsage = true;
  20895. }
  20896. }
  20897. else
  20898. {
  20899. if (methodMatcher.CheckMethod(NULL, checkType, oppositeOperatorDef, false))
  20900. {
  20901. auto rawMethodInstance = mModule->GetRawMethodInstance(checkType, oppositeOperatorDef);
  20902. auto returnType = mModule->ResolveGenericType(rawMethodInstance->mReturnType, NULL, &methodMatcher.mBestMethodGenericArguments,
  20903. mModule->mCurTypeInstance);
  20904. if (returnType != NULL)
  20905. {
  20906. operatorConstraintReturnType = returnType;
  20907. methodMatcher.mSelfType = entry.mSrcType;
  20908. if (oppositeBinaryOp != BfBinaryOp_None)
  20909. wasTransformedUsage = true;
  20910. }
  20911. }
  20912. }
  20913. }
  20914. else
  20915. {
  20916. if (methodMatcher.CheckMethod(NULL, checkType, oppositeOperatorDef, false))
  20917. {
  20918. methodMatcher.mSelfType = entry.mSrcType;
  20919. if (oppositeBinaryOp != BfBinaryOp_None)
  20920. wasTransformedUsage = true;
  20921. }
  20922. }
  20923. }
  20924. }
  20925. }
  20926. bool hadMatch = (methodMatcher.mBestMethodDef != NULL);
  20927. if ((methodMatcher.mBestMethodDef != NULL) && ((flags & BfBinOpFlag_IgnoreOperatorWithWrongResult) != 0))
  20928. {
  20929. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  20930. methodMatcher.mBestMethodInstance = GetSelectedMethod(methodMatcher.mTargetSrc, methodMatcher.mBestMethodTypeInstance, methodMatcher.mBestMethodDef, methodMatcher);
  20931. if ((methodMatcher.mBestMethodInstance.mMethodInstance->mReturnType != mExpectingType) &&
  20932. ((matchedOp == binaryOp) || (matchedOp == oppositeBinaryOp)))
  20933. {
  20934. if (binaryOp == BfBinaryOp_Equality)
  20935. binaryOp = BfBinaryOp_StrictEquality;
  20936. if (binaryOp == BfBinaryOp_InEquality)
  20937. binaryOp = BfBinaryOp_StrictEquality;
  20938. hadMatch = false;
  20939. break;
  20940. }
  20941. }
  20942. if (hadMatch)
  20943. {
  20944. methodMatcher.FlushAmbiguityError();
  20945. auto matchedOp = ((BfOperatorDeclaration*)methodMatcher.mBestMethodDef->mMethodDeclaration)->mBinOp;
  20946. bool invertResult = matchedOp == oppositeBinaryOp;
  20947. auto methodDef = methodMatcher.mBestMethodDef;
  20948. auto autoComplete = GetAutoComplete();
  20949. bool wasCapturingMethodInfo = false;
  20950. if ((autoComplete != NULL) && (autoComplete->IsAutocompleteNode(opToken)))
  20951. {
  20952. auto operatorDecl = BfNodeDynCast<BfOperatorDeclaration>(methodDef->mMethodDeclaration);
  20953. if ((operatorDecl != NULL) && (operatorDecl->mOpTypeToken != NULL))
  20954. autoComplete->SetDefinitionLocation(operatorDecl->mOpTypeToken);
  20955. }
  20956. if ((wasTransformedUsage) && (methodDef->mCommutableKind != BfCommutableKind_Operator))
  20957. {
  20958. auto error = mModule->Warn(BfWarning_BF4206_OperatorCommutableUsage, "Transformed operator usage requires 'Commutable' attribute to be added to the operator declaration", opToken);
  20959. if ((error != NULL) && (methodDef->GetRefNode() != NULL))
  20960. mModule->mCompiler->mPassInstance->MoreInfo(StrFormat("See operator declaration"), methodDef->GetRefNode());
  20961. }
  20962. if (opToken != NULL)
  20963. {
  20964. if ((opToken->IsA<BfTokenNode>()) && (!noClassify) && (!baseClassWalker.mMayBeFromInterface))
  20965. mModule->SetElementType(opToken, BfSourceElementType_Method);
  20966. }
  20967. if ((flags & BfBinOpFlag_IsConstraintCheck) != 0)
  20968. {
  20969. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), operatorConstraintReturnType);
  20970. }
  20971. else
  20972. {
  20973. SetAndRestoreValue<BfEvalExprFlags> prevFlags(mBfEvalExprFlags, (BfEvalExprFlags)(mBfEvalExprFlags | BfEvalExprFlags_NoAutoComplete));
  20974. mResult = CreateCall(&methodMatcher, BfTypedValue());
  20975. }
  20976. if ((mResult.mType != NULL) && (methodMatcher.mSelfType != NULL) && (mResult.mType->IsSelf()))
  20977. {
  20978. BF_ASSERT(mModule->IsInGeneric());
  20979. mResult = mModule->GetDefaultTypedValue(methodMatcher.mSelfType, false, BfDefaultValueKind_Value);
  20980. }
  20981. if ((invertResult) && (mResult.mType == mModule->GetPrimitiveType(BfTypeCode_Boolean)))
  20982. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  20983. if (pass == 1)
  20984. {
  20985. if (findBinaryOp == BfBinaryOp_Compare)
  20986. {
  20987. mResult = mModule->LoadValue(mResult);
  20988. if (mResult.mType->IsIntegral())
  20989. mResult.mValue = mModule->mBfIRBuilder->CreateNeg(mResult.mValue);
  20990. }
  20991. }
  20992. if ((isComparison) && (matchedOp == BfBinaryOp_Compare))
  20993. {
  20994. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  20995. mResult = mModule->LoadValue(mResult);
  20996. if (mResult.mType != intType)
  20997. mResult = mModule->GetDefaultTypedValue(intType);
  20998. auto zeroVal = mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0);
  20999. auto useBinaryOp = binaryOp;
  21000. if (pass == 1)
  21001. useBinaryOp = BfGetFlippedBinaryOp(useBinaryOp);
  21002. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  21003. switch (useBinaryOp)
  21004. {
  21005. case BfBinaryOp_Equality:
  21006. case BfBinaryOp_StrictEquality:
  21007. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mResult.mValue, zeroVal), boolType);
  21008. break;
  21009. case BfBinaryOp_InEquality:
  21010. case BfBinaryOp_StrictInEquality:
  21011. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mResult.mValue, zeroVal), boolType);
  21012. break;
  21013. case BfBinaryOp_GreaterThan:
  21014. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(mResult.mValue, zeroVal, true), boolType);
  21015. break;
  21016. case BfBinaryOp_LessThan:
  21017. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(mResult.mValue, zeroVal, true), boolType);
  21018. break;
  21019. case BfBinaryOp_GreaterThanOrEqual:
  21020. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(mResult.mValue, zeroVal, true), boolType);
  21021. break;
  21022. case BfBinaryOp_LessThanOrEqual:
  21023. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(mResult.mValue, zeroVal, true), boolType);
  21024. break;
  21025. default: break;
  21026. }
  21027. }
  21028. return;
  21029. }
  21030. auto _CheckBinaryOp = [&](BfGenericParamInstance* genericParam)
  21031. {
  21032. for (auto& opConstraint : genericParam->mOperatorConstraints)
  21033. {
  21034. BfType* returnType = genericParam->mExternType;
  21035. bool works = false;
  21036. if (opConstraint.mBinaryOp == findBinaryOp)
  21037. {
  21038. if ((mModule->CanCast(args[0].mTypedValue, opConstraint.mLeftType)) &&
  21039. (mModule->CanCast(args[1].mTypedValue, opConstraint.mRightType)))
  21040. {
  21041. works = true;
  21042. }
  21043. }
  21044. if ((isComparison) && (opConstraint.mBinaryOp == BfBinaryOp_Compare))
  21045. {
  21046. if ((mModule->CanCast(args[0].mTypedValue, opConstraint.mLeftType)) &&
  21047. (mModule->CanCast(args[1].mTypedValue, opConstraint.mRightType)))
  21048. {
  21049. works = true;
  21050. }
  21051. else if ((mModule->CanCast(args[0].mTypedValue, opConstraint.mRightType)) &&
  21052. (mModule->CanCast(args[1].mTypedValue, opConstraint.mLeftType)))
  21053. {
  21054. works = true;
  21055. }
  21056. if (works)
  21057. {
  21058. returnType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  21059. }
  21060. }
  21061. if (works)
  21062. {
  21063. BF_ASSERT(genericParam->mExternType != NULL);
  21064. mResult = BfTypedValue(mModule->mBfIRBuilder->GetFakeVal(), returnType);
  21065. return true;
  21066. }
  21067. }
  21068. return false;
  21069. };
  21070. // Check method generic constraints
  21071. if ((mModule->mCurMethodInstance != NULL) && (mModule->mCurMethodInstance->mIsUnspecialized) && (mModule->mCurMethodInstance->mMethodInfoEx != NULL))
  21072. {
  21073. for (int genericParamIdx = 0; genericParamIdx < mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams.size(); genericParamIdx++)
  21074. {
  21075. auto genericParam = mModule->mCurMethodInstance->mMethodInfoEx->mGenericParams[genericParamIdx];
  21076. if (_CheckBinaryOp(genericParam))
  21077. return;
  21078. }
  21079. }
  21080. // Check type generic constraints
  21081. if ((mModule->mCurTypeInstance->IsGenericTypeInstance()) && (mModule->mCurTypeInstance->IsUnspecializedType()))
  21082. {
  21083. SizedArray<BfGenericParamInstance*, 4> genericParams;
  21084. mModule->GetActiveTypeGenericParamInstances(genericParams);
  21085. for (auto genericParam : genericParams)
  21086. {
  21087. if (_CheckBinaryOp(genericParam))
  21088. return;
  21089. }
  21090. }
  21091. if (pass == 1)
  21092. break;
  21093. auto flippedBinaryOp = BfGetFlippedBinaryOp(findBinaryOp);
  21094. if (flippedBinaryOp != BfBinaryOp_None)
  21095. findBinaryOp = flippedBinaryOp;
  21096. }
  21097. bool resultHandled = false;
  21098. if (((origLeftType != NULL) && (origLeftType->IsIntUnknown())) ||
  21099. ((origRightType != NULL) && (origRightType->IsIntUnknown())))
  21100. {
  21101. if (!resultType->IsPrimitiveType())
  21102. {
  21103. BfType* numericCastType = mModule->GetClosestNumericCastType(*resultTypedValue, mExpectingType);
  21104. if (numericCastType != NULL)
  21105. {
  21106. resultHandled = true;
  21107. resultType = numericCastType;
  21108. }
  21109. }
  21110. }
  21111. if (!resultHandled)
  21112. {
  21113. auto prevResultType = resultType;
  21114. if ((leftValue.mType->IsPrimitiveType()) && (!origLeftType->IsIntUnknown()) && (!rightValue.mType->IsTypedPrimitive()))
  21115. resultType = leftValue.mType;
  21116. if ((rightValue.mType->IsPrimitiveType()) && (!origRightType->IsIntUnknown()) && (!leftValue.mType->IsTypedPrimitive()))
  21117. resultType = rightValue.mType;
  21118. }
  21119. }
  21120. }
  21121. if (deferRight)
  21122. {
  21123. auto expectedType = resultType;
  21124. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  21125. expectedType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  21126. rightValue = mModule->CreateValueFromExpression(BfNodeDynCast<BfExpression>(rightExpression), expectedType, (BfEvalExprFlags)((mBfEvalExprFlags & BfEvalExprFlags_InheritFlags) | BfEvalExprFlags_AllowSplat | BfEvalExprFlags_NoCast));
  21127. if (rightValue)
  21128. PerformBinaryOperation(leftExpression, rightExpression, binaryOp, opToken, (BfBinOpFlags)(flags & ~BfBinOpFlag_DeferRight), leftValue, rightValue);
  21129. return;
  21130. }
  21131. if (mModule->IsUnboundGeneric(resultType))
  21132. {
  21133. mResult = mModule->GetDefaultTypedValue(mModule->GetPrimitiveType(BfTypeCode_Var));
  21134. return;
  21135. }
  21136. if (resultType->IsPointer() && otherType->IsPointer())
  21137. {
  21138. if ((binaryOp == BfBinaryOp_Add) && (resultType == otherType) &&
  21139. (resultType->GetUnderlyingType() == mModule->GetPrimitiveType(BfTypeCode_Char8)))
  21140. {
  21141. AddStrings(leftValue, rightValue, opToken);
  21142. return;
  21143. }
  21144. //TODO: Allow all pointer comparisons, but only allow SUBTRACTION between equal pointer types
  21145. if ((binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowSubtract))
  21146. {
  21147. if (!mModule->CanCast(*otherTypedValue, resultType))
  21148. {
  21149. mModule->Fail(StrFormat("Operands '%s' and '%s' are not comparable types.",
  21150. mModule->TypeToString(leftValue.mType).c_str(), mModule->TypeToString(rightValue.mType).c_str()),
  21151. opToken);
  21152. return;
  21153. }
  21154. BfPointerType* resultPointerType = (BfPointerType*)resultType;
  21155. BfType* intPtrType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  21156. if (resultPointerType->mElementType->mSize == 0)
  21157. {
  21158. if (!mModule->IsInSpecializedSection())
  21159. mModule->Warn(0, "Subtracting pointers to zero-sized elements will always result in zero", opToken);
  21160. mResult = mModule->GetDefaultTypedValue(intPtrType);
  21161. }
  21162. else
  21163. {
  21164. convLeftValue = mModule->CastToValue(leftExpression, leftValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  21165. convRightValue = mModule->CastToValue(rightExpression, rightValue, intPtrType, (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler));
  21166. BfIRValue diffValue = mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue);
  21167. diffValue = mModule->mBfIRBuilder->CreateDiv(diffValue, mModule->GetConstValue(resultPointerType->mElementType->mSize, intPtrType), true);
  21168. mResult = BfTypedValue(diffValue, intPtrType);
  21169. }
  21170. return;
  21171. }
  21172. else if ((binaryOp != BfBinaryOp_Equality) && (binaryOp != BfBinaryOp_StrictEquality) &&
  21173. (binaryOp != BfBinaryOp_InEquality) && (binaryOp != BfBinaryOp_StrictInEquality) &&
  21174. (binaryOp != BfBinaryOp_LessThan) && (binaryOp != BfBinaryOp_LessThanOrEqual) &&
  21175. (binaryOp != BfBinaryOp_GreaterThan) && (binaryOp != BfBinaryOp_GreaterThanOrEqual))
  21176. {
  21177. if (mModule->PreFail())
  21178. mModule->Fail("Invalid operation on pointers", opToken);
  21179. return;
  21180. }
  21181. if ((!BfBinOpEqualityCheck(binaryOp)) || (resultType != otherType))
  21182. {
  21183. resultType = mModule->GetPrimitiveType(BfTypeCode_UIntPtr);
  21184. explicitCast = true;
  21185. }
  21186. }
  21187. else if (resultType->IsPointer())
  21188. {
  21189. if (otherType->IsNull())
  21190. {
  21191. if (!BfBinOpEqualityCheck(binaryOp))
  21192. {
  21193. if (mModule->PreFail())
  21194. mModule->Fail(StrFormat("Invalid operation between '%s' and null", mModule->TypeToString(resultType).c_str()), opToken);
  21195. return;
  21196. }
  21197. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  21198. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21199. else
  21200. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21201. return;
  21202. }
  21203. // One pointer
  21204. if ((!otherType->IsIntegral()) ||
  21205. ((binaryOp != BfBinaryOp_Add) && (binaryOp != BfBinaryOp_Subtract) && (binaryOp != BfBinaryOp_OverflowAdd) && (binaryOp != BfBinaryOp_OverflowSubtract)))
  21206. {
  21207. _OpFail();
  21208. return;
  21209. }
  21210. auto underlyingType = resultType->GetUnderlyingType();
  21211. if ((underlyingType->IsSizedArray()) && (!mModule->IsInSpecializedSection()))
  21212. mModule->Warn(0, "Performing arithmetic on a pointer to a sized array. Consider performing arithmetic on an element pointer if this is not intended.", resultTypeSrc);
  21213. BfIRValue addValue = otherTypedValue->mValue;
  21214. if ((!otherTypedValue->mType->IsSigned()) && (otherTypedValue->mType->mSize < mModule->mSystem->mPtrSize))
  21215. addValue = mModule->mBfIRBuilder->CreateNumericCast(addValue, false, BfTypeCode_UIntPtr);
  21216. if ((binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowSubtract))
  21217. {
  21218. if (resultTypeSrc == rightExpression)
  21219. mModule->Fail("Cannot subtract a pointer from an integer", resultTypeSrc);
  21220. addValue = mModule->mBfIRBuilder->CreateNeg(addValue);
  21221. }
  21222. mModule->PopulateType(underlyingType);
  21223. if (underlyingType->IsValuelessType())
  21224. {
  21225. if (!mModule->IsInSpecializedSection())
  21226. mModule->Warn(0, "Adding to a pointer to a zero-sized element has no effect", opToken);
  21227. mResult = *resultTypedValue;
  21228. return;
  21229. }
  21230. mModule->mBfIRBuilder->PopulateType(underlyingType);
  21231. mResult = BfTypedValue(mModule->CreateIndexedValue(underlyingType, resultTypedValue->mValue, addValue), resultType);
  21232. return;
  21233. }
  21234. if ((resultType->IsFunction()) || (resultType->IsPointer()) || (resultType->IsObject()) || (resultType->IsInterface()) || (resultType->IsGenericParam()))
  21235. {
  21236. if ((binaryOp == BfBinaryOp_Add) &&
  21237. (resultType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)) &&
  21238. (otherType->IsInstanceOf(mModule->mCompiler->mStringTypeDef)))
  21239. {
  21240. AddStrings(leftValue, rightValue, opToken);
  21241. return;
  21242. }
  21243. if (!BfGetBinaryOpPrecendence(binaryOp))
  21244. {
  21245. //mModule->Fail("Invalid operation for objects", opToken);
  21246. _OpFail();
  21247. return;
  21248. }
  21249. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  21250. {
  21251. if (resultType->IsInterface())
  21252. {
  21253. // Compare as objects instead
  21254. resultType = mModule->mContext->mBfObjectType;
  21255. *resultTypedValue = mModule->Cast(resultTypeSrc, *resultTypedValue, resultType);
  21256. }
  21257. if (otherType->IsNull())
  21258. {
  21259. if (resultType->IsFunction())
  21260. {
  21261. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  21262. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21263. else
  21264. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21265. }
  21266. else
  21267. {
  21268. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  21269. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21270. else
  21271. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateIsNotNull(resultTypedValue->mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21272. }
  21273. }
  21274. else
  21275. {
  21276. auto convertedValue = mModule->Cast(otherTypeSrc, *otherTypedValue, resultType, BfCastFlags_NoBox);
  21277. if (!convertedValue)
  21278. return;
  21279. convertedValue = mModule->LoadValue(convertedValue);
  21280. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  21281. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(resultTypedValue->mValue, convertedValue.mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21282. else
  21283. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(resultTypedValue->mValue, convertedValue.mValue), mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21284. }
  21285. return;
  21286. }
  21287. }
  21288. if (resultType->IsTypedPrimitive())
  21289. {
  21290. bool needsOtherCast = true;
  21291. if (otherType != resultType)
  21292. {
  21293. if ((otherType->IsPrimitiveType()) && (!otherType->IsValuelessType()))
  21294. {
  21295. // Allow zero comparisons to match all typed primitives
  21296. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_InEquality))
  21297. {
  21298. auto constant = mModule->mBfIRBuilder->GetConstant(otherTypedValue->mValue);
  21299. if ((constant != NULL) && (mModule->mBfIRBuilder->IsInt(constant->mTypeCode)) && (constant->mInt64 == 0))
  21300. needsOtherCast = false;
  21301. }
  21302. // Allow integer offsetting
  21303. if ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowAdd) || (binaryOp == BfBinaryOp_OverflowSubtract))
  21304. {
  21305. if (otherType->IsIntegral())
  21306. needsOtherCast = false;
  21307. }
  21308. }
  21309. if (needsOtherCast)
  21310. {
  21311. // The only purpose of this cast is to potentially throw a casting error
  21312. BfIRValue otherCastResult = mModule->CastToValue(otherTypeSrc, *otherTypedValue, resultType, explicitCast ? BfCastFlags_Explicit : BfCastFlags_None);
  21313. if (!otherCastResult)
  21314. return;
  21315. }
  21316. }
  21317. auto underlyingType = resultType->GetUnderlyingType();
  21318. if ((binaryOp == BfBinaryOp_Subtract) && (otherTypedValue->mType == resultType))
  21319. {
  21320. intptr maxDist = 0;
  21321. auto resultTypeInstance = resultType->ToTypeInstance();
  21322. if ((resultTypeInstance != NULL) && (resultTypeInstance->mTypeInfoEx != NULL))
  21323. maxDist = resultTypeInstance->mTypeInfoEx->mMaxValue - resultTypeInstance->mTypeInfoEx->mMinValue;
  21324. if (maxDist >= 0x80000000UL)
  21325. resultType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  21326. else if (maxDist >= 0x8000)
  21327. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  21328. else if (maxDist >= 0x80)
  21329. resultType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  21330. else
  21331. resultType = mModule->GetPrimitiveType(BfTypeCode_Int8);
  21332. underlyingType = resultType;
  21333. }
  21334. BfIRValue convResultValue;
  21335. if (resultTypedValue->mType == resultType)
  21336. convResultValue = mModule->LoadValue(*resultTypedValue).mValue;
  21337. else
  21338. convResultValue = mModule->CastToValue(resultTypeSrc, *resultTypedValue, underlyingType, BfCastFlags_Explicit);
  21339. BfIRValue convOtherValue;
  21340. if (otherTypedValue->mType == resultType)
  21341. convOtherValue = mModule->LoadValue(*otherTypedValue).mValue;
  21342. else
  21343. convOtherValue = mModule->CastToValue(otherTypeSrc, *otherTypedValue, underlyingType, BfCastFlags_Explicit);
  21344. if ((!underlyingType->IsValuelessType()) && ((!convResultValue) || (!convOtherValue)))
  21345. return;
  21346. if (resultTypedValue == &leftValue)
  21347. PerformBinaryOperation(underlyingType, convResultValue, convOtherValue, binaryOp, opToken);
  21348. else
  21349. PerformBinaryOperation(underlyingType, convOtherValue, convResultValue, binaryOp, opToken);
  21350. if (mResult.mType == underlyingType)
  21351. mResult.mType = resultType;
  21352. return;
  21353. }
  21354. auto _CallValueTypeEquals = [&]()
  21355. {
  21356. BfModuleMethodInstance moduleMethodInstance;
  21357. auto typeInst = leftValue.mType->ToTypeInstance();
  21358. if (typeInst != NULL)
  21359. {
  21360. if ((binaryOp == BfBinaryOp_StrictEquality) || (binaryOp == BfBinaryOp_StrictInEquality))
  21361. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_STRICT_EQUALS);
  21362. else
  21363. moduleMethodInstance = mModule->GetMethodByName(typeInst, BF_METHODNAME_DEFAULT_EQUALS);
  21364. }
  21365. else
  21366. {
  21367. BF_ASSERT(leftValue.mType->IsSizedArray() || leftValue.mType->IsMethodRef());
  21368. auto valueTypeInst = mModule->ResolveTypeDef(mModule->mCompiler->mValueTypeTypeDef)->ToTypeInstance();
  21369. BfMethodDef* equalsMethodDef = mModule->mCompiler->mValueTypeTypeDef->GetMethodByName("Equals");
  21370. BfTypeVector typeVec;
  21371. typeVec.push_back(leftValue.mType);
  21372. moduleMethodInstance = mModule->GetMethodInstance(valueTypeInst, equalsMethodDef, typeVec);
  21373. }
  21374. if (moduleMethodInstance)
  21375. {
  21376. if ((opToken != NULL) && (!noClassify))
  21377. mModule->SetElementType(opToken, BfSourceElementType_Method);
  21378. SizedArray<BfResolvedArg, 4> argValues;
  21379. BfResolvedArg resolvedArg;
  21380. resolvedArg.mTypedValue = leftValue;
  21381. argValues.push_back(resolvedArg);
  21382. resolvedArg.mTypedValue = rightValue;
  21383. argValues.push_back(resolvedArg);
  21384. mResult = CreateCall(opToken, BfTypedValue(), BfTypedValue(), moduleMethodInstance.mMethodInstance->mMethodDef, moduleMethodInstance, BfCreateCallFlags_None, argValues);
  21385. if ((mResult) &&
  21386. ((binaryOp == BfBinaryOp_InEquality) || (binaryOp == BfBinaryOp_StrictInEquality)))
  21387. mResult.mValue = mModule->mBfIRBuilder->CreateNot(mResult.mValue);
  21388. return true;
  21389. }
  21390. return false;
  21391. };
  21392. //if (((leftValue.mType->IsComposite()) || (leftValue.mType->IsObject())))
  21393. if (((resultType->IsComposite()) || (resultType->IsObject())))
  21394. {
  21395. bool areEquivalentTuples = false;
  21396. if ((leftValue.mType->IsTuple()) && (rightValue.mType->IsTuple()))
  21397. {
  21398. auto leftTupleType = (BfTypeInstance*)leftValue.mType;
  21399. auto rightTupleType = (BfTypeInstance*)rightValue.mType;
  21400. // We only do this for tuples, because we would allow an implicit struct
  21401. // truncation if we allow it for all structs, which would result in only
  21402. // the base class's fields being compared
  21403. if (mModule->CanCast(rightValue, leftValue.mType))
  21404. rightValue = mModule->Cast(opToken, rightValue, leftValue.mType, BfCastFlags_Explicit);
  21405. else if (mModule->CanCast(leftValue, rightValue.mType))
  21406. leftValue = mModule->Cast(opToken, leftValue, rightValue.mType, BfCastFlags_Explicit);
  21407. }
  21408. if (leftValue.mType == rightValue.mType)
  21409. {
  21410. if (BfBinOpEqualityCheck(binaryOp))
  21411. {
  21412. auto intCoercibleType = mModule->GetIntCoercibleType(leftValue.mType);
  21413. if (intCoercibleType != NULL)
  21414. {
  21415. auto intLHS = mModule->GetIntCoercible(leftValue);
  21416. auto intRHS = mModule->GetIntCoercible(rightValue);
  21417. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  21418. if ((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality))
  21419. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(intLHS.mValue, intRHS.mValue), boolType);
  21420. else
  21421. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(intLHS.mValue, intRHS.mValue), boolType);
  21422. return;
  21423. }
  21424. // Valueless types always compare as 'equal' if we can ensure no members could have an equality operator overload
  21425. if (leftValue.mType->IsComposite())
  21426. {
  21427. mModule->PopulateType(leftValue.mType);
  21428. if (leftValue.mType->IsValuelessType())
  21429. {
  21430. bool mayHaveEqualOverload = false;
  21431. auto leftTypeInst = leftValue.mType->ToTypeInstance();
  21432. if (leftTypeInst != NULL)
  21433. {
  21434. std::function<bool(BfType*)> _HasTypeInstance = [&](BfType* type)
  21435. {
  21436. if (type == NULL)
  21437. return false;
  21438. if (type->IsTypeInstance())
  21439. return true;
  21440. if (type->IsSizedArray())
  21441. return _HasTypeInstance(((BfSizedArrayType*)type)->mElementType);
  21442. return false;
  21443. };
  21444. for (auto& fieldInstance : leftTypeInst->mFieldInstances)
  21445. {
  21446. if (_HasTypeInstance(fieldInstance.mResolvedType))
  21447. mayHaveEqualOverload = true;
  21448. }
  21449. }
  21450. if (!mayHaveEqualOverload)
  21451. {
  21452. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  21453. bool isEqual = (binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality);
  21454. mResult = BfTypedValue(mModule->GetConstValue(isEqual ? 1 : 0, boolType), boolType);
  21455. return;
  21456. }
  21457. }
  21458. }
  21459. if (_CallValueTypeEquals())
  21460. return;
  21461. }
  21462. if (PerformBinaryOperation_Numeric(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue))
  21463. return;
  21464. if (mModule->PreFail())
  21465. {
  21466. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s'",
  21467. BfGetOpName(binaryOp),
  21468. mModule->TypeToString(leftValue.mType).c_str()), opToken);
  21469. }
  21470. return;
  21471. }
  21472. else
  21473. {
  21474. bool handled = false;
  21475. for (int pass = 0; pass < 2; pass++)
  21476. {
  21477. BfTypedValue& fromValue = (pass == 0) ? leftValue : rightValue;
  21478. BfType* toType = (pass == 0) ? rightValue.mType : leftValue.mType;
  21479. if (mModule->CanCast(fromValue, toType))
  21480. {
  21481. auto result = mModule->Cast(opToken, fromValue, toType);
  21482. if (result)
  21483. {
  21484. resultType = toType;
  21485. fromValue = result;
  21486. handled = true;
  21487. break;
  21488. }
  21489. }
  21490. }
  21491. if (!handled)
  21492. {
  21493. if ((leftValue.mType->IsUndefSizedArray()) || (rightValue.mType->IsUndefSizedArray()))
  21494. {
  21495. if ((leftValue.mType->IsSizedArray()) && (rightValue.mType->IsSizedArray() &&
  21496. (leftValue.mType->GetUnderlyingType() == rightValue.mType->GetUnderlyingType())))
  21497. {
  21498. if (BfBinOpEqualityCheck(binaryOp))
  21499. {
  21500. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  21501. mResult = mModule->GetDefaultTypedValue(boolType, false, BfDefaultValueKind_Undef);
  21502. return;
  21503. }
  21504. }
  21505. }
  21506. if (PerformBinaryOperation_Numeric(leftExpression, rightExpression, binaryOp, opToken, flags, leftValue, rightValue))
  21507. return;
  21508. mModule->Fail(StrFormat("Operator '%s' cannot be applied to operands of type '%s' and '%s'",
  21509. BfGetOpName(binaryOp),
  21510. mModule->TypeToString(leftValue.mType).c_str(),
  21511. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  21512. return;
  21513. }
  21514. }
  21515. }
  21516. if (resultType->IsMethodRef() && otherType->IsMethodRef())
  21517. {
  21518. if (BfBinOpEqualityCheck(binaryOp))
  21519. {
  21520. auto boolType = mModule->GetPrimitiveType(BfTypeCode_Boolean);
  21521. BfMethodRefType* lhsMethodRefType = (BfMethodRefType*)leftValue.mType;
  21522. BfMethodRefType* rhsMethodRefType = (BfMethodRefType*)rightValue.mType;
  21523. if (lhsMethodRefType->mMethodRef != rhsMethodRefType->mMethodRef)
  21524. {
  21525. mResult = BfTypedValue(mModule->GetConstValue(((binaryOp == BfBinaryOp_Equality) || (binaryOp == BfBinaryOp_StrictEquality)) ? 0 : 1, boolType), boolType);
  21526. return;
  21527. }
  21528. if (_CallValueTypeEquals())
  21529. return;
  21530. }
  21531. }
  21532. if (resultType->IsIntegral())
  21533. {
  21534. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  21535. {
  21536. if (rightValue.mValue.IsConst())
  21537. {
  21538. auto constVal = mModule->mBfIRBuilder->GetConstant(rightValue.mValue);
  21539. if ((constVal->mInt64 < 0) || (constVal->mInt64 >= 8 * resultType->mSize))
  21540. {
  21541. mModule->Fail(StrFormat("Shift value '%lld' is out of range for type '%s'", constVal->mInt64, mModule->TypeToString(resultType).c_str()), opToken);
  21542. }
  21543. }
  21544. }
  21545. // We're trying a simplified scheme that doesn't always try to up-convert into an 'int'
  21546. if (leftValue.mType != rightValue.mType)
  21547. {
  21548. bool isBitwiseExpr =
  21549. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  21550. (binaryOp == BfBinaryOp_BitwiseOr) ||
  21551. (binaryOp == BfBinaryOp_ExclusiveOr) ||
  21552. (binaryOp == BfBinaryOp_LeftShift) ||
  21553. (binaryOp == BfBinaryOp_RightShift) ||
  21554. (binaryOp == BfBinaryOp_Equality) ||
  21555. (binaryOp == BfBinaryOp_InEquality) ||
  21556. (binaryOp == BfBinaryOp_StrictEquality) ||
  21557. (binaryOp == BfBinaryOp_StrictInEquality);
  21558. if ((binaryOp == BfBinaryOp_LeftShift) || (binaryOp == BfBinaryOp_RightShift))
  21559. {
  21560. // For shifts we have more lenient rules - shifts are naturally limited so any int type is equally valid
  21561. if (rightValue.mType->IsIntegral())
  21562. explicitCast = true;
  21563. }
  21564. else if (((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowAdd) || (binaryOp == BfBinaryOp_OverflowSubtract)) && (resultType->IsChar()) && (otherType->IsInteger()))
  21565. {
  21566. // charVal += intVal;
  21567. explicitCast = true;
  21568. }
  21569. else if ((!resultType->IsSigned()) && (otherType->IsSigned()))
  21570. {
  21571. if (mModule->CanCast(*otherTypedValue, resultType))
  21572. {
  21573. // If we can convert the 'other' value implicitly then it's a convertible literal, leave as uint
  21574. }
  21575. else
  21576. {
  21577. mModule->Fail(StrFormat("Operator cannot be applied to operands of type '%s' and '%s'",
  21578. mModule->TypeToString(leftValue.mType).c_str(),
  21579. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  21580. return;
  21581. }
  21582. }
  21583. else if ((isBitwiseExpr) && (otherType->IsIntegral()) && (resultType->mSize == otherType->mSize))
  21584. {
  21585. // Forget about signed/unsigned mismatches for bitwise operations
  21586. explicitCast = true;
  21587. }
  21588. else
  21589. {
  21590. if (((binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowSubtract)) &&
  21591. (resultType->IsChar()) && (otherType->IsChar()))
  21592. {
  21593. // "wchar - char" subtraction will always fit into int32, because of unicode range
  21594. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  21595. explicitCast = true;
  21596. }
  21597. else if ((otherType->IsChar()) &&
  21598. ((binaryOp == BfBinaryOp_Add) || (binaryOp == BfBinaryOp_Subtract) || (binaryOp == BfBinaryOp_OverflowAdd) || (binaryOp == BfBinaryOp_OverflowSubtract)))
  21599. {
  21600. mModule->Fail(StrFormat("Cannot perform operation between types '%s' and '%s'",
  21601. mModule->TypeToString(leftValue.mType).c_str(),
  21602. mModule->TypeToString(rightValue.mType).c_str()), opToken);
  21603. }
  21604. }
  21605. }
  21606. else if ((!resultType->IsSigned()) && (binaryOp == BfBinaryOp_Subtract) && (!forceLeftType))
  21607. {
  21608. if ((mExpectingType == NULL) || (mExpectingType->IsSigned()) || (resultType->IsChar()))
  21609. {
  21610. if ((resultType->IsChar()) && (resultType->mSize == 4))
  21611. {
  21612. // "wchar - wchar" subtraction will always fit into int32, because of unicode range
  21613. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  21614. }
  21615. else
  21616. {
  21617. // The result of uint8 - uint8 is int16 (for example)
  21618. switch (resultType->mSize)
  21619. {
  21620. case 1:
  21621. resultType = mModule->GetPrimitiveType(BfTypeCode_Int16);
  21622. break;
  21623. case 2:
  21624. resultType = mModule->GetPrimitiveType(BfTypeCode_Int32);
  21625. break;
  21626. case 4:
  21627. resultType = mModule->GetPrimitiveType(BfTypeCode_Int64);
  21628. break;
  21629. }
  21630. }
  21631. explicitCast = true;
  21632. }
  21633. }
  21634. else if (resultType->IsChar())
  21635. {
  21636. bool canDoOp =
  21637. (binaryOp == BfBinaryOp_BitwiseAnd) ||
  21638. (binaryOp == BfBinaryOp_BitwiseOr) ||
  21639. ((binaryOp >= BfBinaryOp_Equality) && (binaryOp <= BfBinaryOp_Compare));
  21640. if (!canDoOp)
  21641. {
  21642. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  21643. return;
  21644. }
  21645. }
  21646. }
  21647. if (!convLeftValue)
  21648. convLeftValue = mModule->CastToValue(leftExpression, leftValue, resultType,
  21649. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  21650. if (!convRightValue)
  21651. convRightValue = mModule->CastToValue(rightExpression, rightValue, resultType,
  21652. explicitCast ? (BfCastFlags)(BfCastFlags_Explicit | BfCastFlags_FromCompiler) : BfCastFlags_None);
  21653. PerformBinaryOperation(resultType, convLeftValue, convRightValue, binaryOp, opToken);
  21654. }
  21655. void BfExprEvaluator::PerformBinaryOperation(BfType* resultType, BfIRValue convLeftValue, BfIRValue convRightValue, BfBinaryOp binaryOp, BfAstNode* opToken)
  21656. {
  21657. if (resultType->IsValuelessType())
  21658. {
  21659. switch (binaryOp)
  21660. {
  21661. case BfBinaryOp_Equality:
  21662. case BfBinaryOp_StrictEquality:
  21663. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 1),
  21664. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21665. return;
  21666. case BfBinaryOp_InEquality:
  21667. case BfBinaryOp_StrictInEquality:
  21668. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateConst(BfTypeCode_Boolean, 0),
  21669. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21670. return;
  21671. default:
  21672. break;
  21673. }
  21674. }
  21675. if ((!convLeftValue) || (!convRightValue))
  21676. return;
  21677. if (resultType->IsPrimitiveType())
  21678. {
  21679. auto primType = (BfPrimitiveType*)resultType;
  21680. if (primType->mTypeDef->mTypeCode == BfTypeCode_Boolean)
  21681. {
  21682. bool passThrough = false;
  21683. switch (binaryOp)
  21684. {
  21685. case BfBinaryOp_Equality:
  21686. case BfBinaryOp_StrictEquality:
  21687. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  21688. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21689. break;
  21690. case BfBinaryOp_InEquality:
  21691. case BfBinaryOp_StrictInEquality:
  21692. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  21693. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21694. break;
  21695. case BfBinaryOp_BitwiseAnd:
  21696. case BfBinaryOp_ConditionalAnd:
  21697. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue),
  21698. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21699. break;
  21700. case BfBinaryOp_BitwiseOr:
  21701. case BfBinaryOp_ConditionalOr:
  21702. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue),
  21703. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21704. break;
  21705. case BfBinaryOp_ExclusiveOr:
  21706. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue),
  21707. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21708. break;
  21709. case BfBinaryOp_Compare:
  21710. passThrough = true;
  21711. break;
  21712. default:
  21713. if (mModule->PreFail())
  21714. mModule->Fail("Invalid operation for booleans", opToken);
  21715. break;
  21716. }
  21717. if (!passThrough)
  21718. return;
  21719. }
  21720. }
  21721. if ((!resultType->IsIntegralOrBool()) && (!resultType->IsFloat()))
  21722. {
  21723. if (mModule->PreFail())
  21724. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  21725. return;
  21726. }
  21727. if (resultType->IsIntegral())
  21728. {
  21729. switch (binaryOp)
  21730. {
  21731. case BfBinaryOp_BitwiseAnd:
  21732. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAnd(convLeftValue, convRightValue), resultType);
  21733. return;
  21734. case BfBinaryOp_BitwiseOr:
  21735. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateOr(convLeftValue, convRightValue), resultType);
  21736. return;
  21737. case BfBinaryOp_ExclusiveOr:
  21738. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateXor(convLeftValue, convRightValue), resultType);
  21739. return;
  21740. case BfBinaryOp_LeftShift:
  21741. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShl(convLeftValue, convRightValue), resultType);
  21742. mModule->CheckRangeError(resultType, opToken);
  21743. return;
  21744. case BfBinaryOp_RightShift:
  21745. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateShr(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  21746. return;
  21747. default: break;
  21748. }
  21749. }
  21750. if ((resultType->IsChar()) &&
  21751. ((binaryOp == BfBinaryOp_Multiply) ||
  21752. (binaryOp == BfBinaryOp_OverflowMultiply) ||
  21753. (binaryOp == BfBinaryOp_Divide) ||
  21754. (binaryOp == BfBinaryOp_Modulus)))
  21755. {
  21756. mModule->Fail(StrFormat("Cannot perform operation on type '%s'", mModule->TypeToString(resultType).c_str()), opToken);
  21757. return;
  21758. }
  21759. auto _GetOverflowKind = [&](bool wantOverflow)
  21760. {
  21761. if (resultType->IsFloat())
  21762. return BfOverflowCheckKind_None;
  21763. if (!wantOverflow)
  21764. return BfOverflowCheckKind_None;
  21765. if (mModule->GetDefaultCheckedKind() != BfCheckedKind_Checked)
  21766. return BfOverflowCheckKind_None;
  21767. bool arithmeticChecks = mModule->mCompiler->mOptions.mArithmeticChecks;
  21768. auto typeOptions = mModule->GetTypeOptions();
  21769. if (typeOptions != NULL)
  21770. arithmeticChecks = typeOptions->Apply(arithmeticChecks, BfOptionFlags_ArithmeticCheck);
  21771. if (!arithmeticChecks)
  21772. return BfOverflowCheckKind_None;
  21773. BfOverflowCheckKind overflowCheckKind = (resultType->IsSigned()) ? BfOverflowCheckKind_Signed : BfOverflowCheckKind_Unsigned;
  21774. if (!mModule->IsOptimized())
  21775. overflowCheckKind = (BfOverflowCheckKind)(overflowCheckKind | BfOverflowCheckKind_Flag_UseAsm);
  21776. return overflowCheckKind;
  21777. };
  21778. switch (binaryOp)
  21779. {
  21780. case BfBinaryOp_Add:
  21781. case BfBinaryOp_OverflowAdd:
  21782. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateAdd(convLeftValue, convRightValue, _GetOverflowKind(binaryOp == BfBinaryOp_Add)), resultType);
  21783. if (binaryOp != BfBinaryOp_OverflowAdd)
  21784. mModule->CheckRangeError(resultType, opToken);
  21785. break;
  21786. case BfBinaryOp_Subtract:
  21787. case BfBinaryOp_OverflowSubtract:
  21788. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(convLeftValue, convRightValue, _GetOverflowKind(binaryOp == BfBinaryOp_Subtract)), resultType);
  21789. if (binaryOp != BfBinaryOp_OverflowSubtract)
  21790. mModule->CheckRangeError(resultType, opToken);
  21791. break;
  21792. case BfBinaryOp_Multiply:
  21793. case BfBinaryOp_OverflowMultiply:
  21794. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateMul(convLeftValue, convRightValue, _GetOverflowKind(binaryOp == BfBinaryOp_Multiply)), resultType);
  21795. if (binaryOp != BfBinaryOp_OverflowMultiply)
  21796. mModule->CheckRangeError(resultType, opToken);
  21797. break;
  21798. case BfBinaryOp_Divide:
  21799. {
  21800. bool isZero = false;
  21801. if (convRightValue.IsConst())
  21802. {
  21803. auto constVal = mModule->mBfIRBuilder->GetConstant(convRightValue);
  21804. if (BfIRBuilder::IsInt(constVal->mTypeCode))
  21805. isZero = constVal->mInt64 == 0;
  21806. }
  21807. if (isZero)
  21808. {
  21809. mModule->Fail("Divide by zero", opToken);
  21810. mResult = mModule->GetDefaultTypedValue(resultType);
  21811. }
  21812. else
  21813. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateDiv(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  21814. }
  21815. break;
  21816. case BfBinaryOp_Modulus:
  21817. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateRem(convLeftValue, convRightValue, resultType->IsSigned()), resultType);
  21818. break;
  21819. case BfBinaryOp_Equality:
  21820. case BfBinaryOp_StrictEquality:
  21821. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpEQ(convLeftValue, convRightValue),
  21822. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21823. break;
  21824. case BfBinaryOp_InEquality:
  21825. case BfBinaryOp_StrictInEquality:
  21826. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpNE(convLeftValue, convRightValue),
  21827. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21828. break;
  21829. case BfBinaryOp_LessThan:
  21830. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned()),
  21831. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21832. break;
  21833. case BfBinaryOp_LessThanOrEqual:
  21834. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpLTE(convLeftValue, convRightValue, resultType->IsSigned()),
  21835. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21836. break;
  21837. case BfBinaryOp_GreaterThan:
  21838. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned()),
  21839. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21840. break;
  21841. case BfBinaryOp_GreaterThanOrEqual:
  21842. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateCmpGTE(convLeftValue, convRightValue, resultType->IsSigned()),
  21843. mModule->GetPrimitiveType(BfTypeCode_Boolean));
  21844. break;
  21845. case BfBinaryOp_Compare:
  21846. {
  21847. auto intType = mModule->GetPrimitiveType(BfTypeCode_IntPtr);
  21848. if ((convLeftValue.IsConst()) && (convRightValue.IsConst()))
  21849. {
  21850. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned());
  21851. auto ltConstant = mModule->mBfIRBuilder->GetConstant(cmpLtVal);
  21852. if (ltConstant->mBool)
  21853. {
  21854. mResult = BfTypedValue(mModule->GetConstValue(-1, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  21855. }
  21856. else
  21857. {
  21858. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned());
  21859. auto rtConstant = mModule->mBfIRBuilder->GetConstant(cmpGtVal);
  21860. if (rtConstant->mBool)
  21861. mResult = BfTypedValue(mModule->GetConstValue(1, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  21862. else
  21863. mResult = BfTypedValue(mModule->GetConstValue(0, mModule->GetPrimitiveType(BfTypeCode_IntPtr)), intType);
  21864. }
  21865. }
  21866. else if ((resultType->IsIntegralOrBool()) && (resultType->mSize < intType->mSize))
  21867. {
  21868. auto leftIntValue = mModule->mBfIRBuilder->CreateNumericCast(convLeftValue, resultType->IsSigned(), BfTypeCode_IntPtr);
  21869. auto rightIntValue = mModule->mBfIRBuilder->CreateNumericCast(convRightValue, resultType->IsSigned(), BfTypeCode_IntPtr);
  21870. mResult = BfTypedValue(mModule->mBfIRBuilder->CreateSub(leftIntValue, rightIntValue), intType);
  21871. }
  21872. else
  21873. {
  21874. BfIRBlock checkGtBlock = mModule->mBfIRBuilder->CreateBlock("cmpCheckGt");
  21875. BfIRBlock eqBlock = mModule->mBfIRBuilder->CreateBlock("cmpEq");
  21876. BfIRBlock endBlock = mModule->mBfIRBuilder->CreateBlock("cmpEnd");
  21877. auto startBlock = mModule->mBfIRBuilder->GetInsertBlock();
  21878. auto cmpLtVal = mModule->mBfIRBuilder->CreateCmpLT(convLeftValue, convRightValue, resultType->IsSigned());
  21879. mModule->mBfIRBuilder->CreateCondBr(cmpLtVal, endBlock, checkGtBlock);
  21880. mModule->mBfIRBuilder->AddBlock(checkGtBlock);
  21881. mModule->mBfIRBuilder->SetInsertPoint(checkGtBlock);
  21882. auto cmpGtVal = mModule->mBfIRBuilder->CreateCmpGT(convLeftValue, convRightValue, resultType->IsSigned());
  21883. mModule->mBfIRBuilder->CreateCondBr(cmpGtVal, endBlock, eqBlock);
  21884. mModule->mBfIRBuilder->AddBlock(eqBlock);
  21885. mModule->mBfIRBuilder->SetInsertPoint(eqBlock);
  21886. mModule->mBfIRBuilder->CreateBr(endBlock);
  21887. mModule->mBfIRBuilder->AddBlock(endBlock);
  21888. mModule->mBfIRBuilder->SetInsertPoint(endBlock);
  21889. auto phiVal = mModule->mBfIRBuilder->CreatePhi(mModule->mBfIRBuilder->MapType(intType), 3);
  21890. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, -1), startBlock);
  21891. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 1), checkGtBlock);
  21892. mModule->mBfIRBuilder->AddPhiIncoming(phiVal, mModule->mBfIRBuilder->CreateConst(BfTypeCode_IntPtr, 0), eqBlock);
  21893. mResult = BfTypedValue(phiVal, intType);
  21894. }
  21895. }
  21896. break;
  21897. default:
  21898. if (mModule->PreFail())
  21899. mModule->Fail("Invalid operation", opToken);
  21900. break;
  21901. }
  21902. }
  21903. void BfExprEvaluator::Visit(BfBinaryOperatorExpression* binOpExpr)
  21904. {
  21905. BfAutoParentNodeEntry autoParentNodeEntry(mModule, binOpExpr);
  21906. // There are a few binary operations that could actually be casts followed by an unary operation
  21907. // We can't determine that until we know whether the identifier in the parens is a typename or not
  21908. // (double)-1.0 (intptr)&val (BaseStruct)*val
  21909. BfUnaryOp unaryOp = BfUnaryOp_None;
  21910. switch (binOpExpr->mOp)
  21911. {
  21912. case BfBinaryOp_Add: unaryOp = BfUnaryOp_Positive; break;
  21913. case BfBinaryOp_Subtract: unaryOp = BfUnaryOp_Negate; break;
  21914. case BfBinaryOp_Multiply: unaryOp = BfUnaryOp_Dereference; break;
  21915. case BfBinaryOp_BitwiseAnd: unaryOp = BfUnaryOp_AddressOf; break;
  21916. default: break;
  21917. }
  21918. if (unaryOp != BfUnaryOp_None)
  21919. {
  21920. if (auto parenExpr = BfNodeDynCast<BfParenthesizedExpression>(binOpExpr->mLeft))
  21921. {
  21922. if (auto castTypeExpr = BfNodeDynCast<BfIdentifierNode>(parenExpr->mExpression))
  21923. {
  21924. SetAndRestoreValue<bool> prevIgnoreError(mModule->mIgnoreErrors, true);
  21925. auto resolvedType = mModule->ResolveTypeRef(castTypeExpr, NULL);
  21926. prevIgnoreError.Restore();
  21927. if (resolvedType != NULL)
  21928. {
  21929. if (auto rightBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>(binOpExpr->mRight))
  21930. {
  21931. int leftPrecedence = BfGetBinaryOpPrecendence(binOpExpr->mOp);
  21932. int rightPrecedence = BfGetBinaryOpPrecendence(rightBinOpExpr->mOp);
  21933. // Do we have a precedence order issue due to mis-parsing this?
  21934. // An example is: "(int)-5.5 * 10"
  21935. if (rightPrecedence > leftPrecedence)
  21936. {
  21937. mModule->FailAfter("Cast target must be wrapped in parentheses", binOpExpr->mLeft);
  21938. }
  21939. }
  21940. PerformUnaryOperation(binOpExpr->mRight, unaryOp, binOpExpr->mOpToken, BfUnaryOpFlag_None);
  21941. if (mResult)
  21942. {
  21943. mResult = mModule->LoadValue(mResult);
  21944. mResult = mModule->Cast(binOpExpr, mResult, resolvedType, BfCastFlags_Explicit);
  21945. }
  21946. return;
  21947. }
  21948. }
  21949. }
  21950. }
  21951. if ((binOpExpr->mOp == BfBinaryOp_LeftShift) || (binOpExpr->mOp == BfBinaryOp_RightShift) ||
  21952. (binOpExpr->mOp == BfBinaryOp_BitwiseAnd) || (binOpExpr->mOp == BfBinaryOp_BitwiseOr) ||
  21953. (binOpExpr->mOp == BfBinaryOp_ExclusiveOr))
  21954. {
  21955. for (int side = 0; side < 2; side++)
  21956. {
  21957. if (auto innerBinOpExpr = BfNodeDynCast<BfBinaryOperatorExpression>((side == 0) ? binOpExpr->mLeft : binOpExpr->mRight))
  21958. {
  21959. if ((innerBinOpExpr->mOp == BfBinaryOp_Add) || (innerBinOpExpr->mOp == BfBinaryOp_Subtract))
  21960. {
  21961. mModule->Warn(BfWarning_C4554_PossiblePrecedenceError, "Check operator precedence for possible error. Consider using parentheses to clarify precedence", innerBinOpExpr);
  21962. }
  21963. }
  21964. }
  21965. }
  21966. if (binOpExpr->mRight == NULL)
  21967. {
  21968. // We visit the children for autocompletion only
  21969. if (binOpExpr->mLeft != NULL)
  21970. VisitChild(binOpExpr->mLeft);
  21971. if (mResult)
  21972. {
  21973. auto autoComplete = GetAutoComplete();
  21974. if (autoComplete != NULL)
  21975. autoComplete->CheckEmptyStart(binOpExpr->mOpToken, mResult.mType);
  21976. }
  21977. if (binOpExpr->mRight != NULL)
  21978. VisitChild(binOpExpr->mRight);
  21979. return;
  21980. }
  21981. PerformBinaryOperation(binOpExpr->mLeft, binOpExpr->mRight, binOpExpr->mOp, binOpExpr->mOpToken, BfBinOpFlag_None);
  21982. }